You've already forked monobank-firefly3-bot
Make dynamic json config
This commit is contained in:
177
main.go
177
main.go
@ -4,12 +4,11 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/antihax/optional"
|
||||
"github.com/joho/godotenv"
|
||||
"io"
|
||||
"log"
|
||||
"main/firefly3"
|
||||
"main/monobank/api/webhook/models"
|
||||
firefly3 "main/firefly3"
|
||||
monobank "main/monobank/api/webhook/models"
|
||||
"math"
|
||||
"net/http"
|
||||
"os"
|
||||
@ -25,19 +24,11 @@ import (
|
||||
|
||||
// curl -X POST https://monobank-firefly3.stuzer.link/webhook -H 'Content-TransactionType: application/json' -d '{"test":123}'
|
||||
|
||||
// Configs
|
||||
var ShopConfig []ShopConfigItem
|
||||
var Firefy3AccountsConfig map[string]string
|
||||
|
||||
func handleWebhook(w http.ResponseWriter, r *http.Request) {
|
||||
LogString("-----------------\nwebhook received!")
|
||||
|
||||
func readResponseBody(r *http.Request) (monobank.Transaction, error) {
|
||||
// read body bytes
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
LogString(err.Error())
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return
|
||||
return monobank.Transaction{}, err
|
||||
}
|
||||
|
||||
//fmt.Println(string(body))
|
||||
@ -49,109 +40,112 @@ func handleWebhook(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// check empty body
|
||||
if len(string(body)) == 0 {
|
||||
LogString("empty body")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return
|
||||
return monobank.Transaction{}, err
|
||||
}
|
||||
|
||||
// parse body
|
||||
var transaction models.Transaction
|
||||
var transaction monobank.Transaction
|
||||
err = json.Unmarshal(body, &transaction)
|
||||
if err != nil {
|
||||
return monobank.Transaction{}, err
|
||||
}
|
||||
|
||||
return transaction, nil
|
||||
}
|
||||
|
||||
func handleWebhook(w http.ResponseWriter, r *http.Request) {
|
||||
var err error
|
||||
|
||||
firefly3TransactionTypeWithdrawal := firefly3.WITHDRAWAL_TransactionTypeProperty
|
||||
firefly3TransactionTypeTransfer := firefly3.TRANSFER_TransactionTypeProperty
|
||||
|
||||
// read request
|
||||
var monobankTransaction monobank.Transaction
|
||||
monobankTransaction, err = readResponseBody(r)
|
||||
if err != nil {
|
||||
LogString(err.Error())
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return
|
||||
}
|
||||
|
||||
//statement, err := requests.Statement(models2.StatementRequest{
|
||||
// Account: transaction.Data.Account,
|
||||
// From: transaction.Data.StatementItem.Time,
|
||||
// To: transaction.Data.StatementItem.Time,
|
||||
//})
|
||||
//if err != nil {
|
||||
// fmt.Printf("%+v", err.Error())
|
||||
// w.WriteHeader(http.StatusOK)
|
||||
// return
|
||||
//}
|
||||
//fmt.Printf("%+v", statement)
|
||||
// get body json string (for logging)
|
||||
monobankTransactionJson, err := json.Marshal(monobankTransaction)
|
||||
if err != nil {
|
||||
LogString(err.Error())
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return
|
||||
}
|
||||
|
||||
// read config
|
||||
var config Config
|
||||
config, err = ReadConfig(os.Getenv("CONFIG_PATH"))
|
||||
if err != nil {
|
||||
LogString(err.Error())
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return
|
||||
}
|
||||
|
||||
// find accounts
|
||||
account := ConfigGetAccountByMonobankId(config, monobankTransaction.Data.Account)
|
||||
|
||||
// cancel if one of account ids is empty
|
||||
if len(account.Firefly3Id) == 0 || len(account.MonobankId) == 0 {
|
||||
LogString("cannot find firefly3 or monobank ids (" + monobankTransaction.Data.Account + ")")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return
|
||||
}
|
||||
|
||||
// init firefly3 client
|
||||
clientConf := firefly3.NewConfiguration()
|
||||
clientConf.BasePath = os.Getenv("FIREFLY3_API_URL")
|
||||
clientConf.AddDefaultHeader("Authorization", "Bearer "+os.Getenv("FIREFLY3_TOKEN"))
|
||||
client := firefly3.NewAPIClient(clientConf)
|
||||
firefly3Client := firefly3.NewAPIClient(clientConf)
|
||||
|
||||
// get firefly3 account
|
||||
listOpts := firefly3.AccountsApiListAccountOpts{
|
||||
Type_: optional.NewInterface("asset"),
|
||||
}
|
||||
accounts, _, err := client.AccountsApi.ListAccount(context.Background(), &listOpts)
|
||||
if err != nil {
|
||||
LogString(err.Error())
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return
|
||||
}
|
||||
|
||||
var account firefly3.AccountRead
|
||||
for _, row := range accounts.Data {
|
||||
if row.Attributes.Notes == transaction.Data.Account {
|
||||
account = row
|
||||
}
|
||||
}
|
||||
|
||||
if len(account.Id) == 0 {
|
||||
LogString("unable to find account " + transaction.Data.Account + " in firefly3")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return
|
||||
}
|
||||
|
||||
// create transaction
|
||||
// create firefly3 transaction
|
||||
var firefly3Transactions []firefly3.TransactionSplitStore
|
||||
|
||||
transactionTypeWithdrawal := firefly3.WITHDRAWAL_TransactionTypeProperty
|
||||
transactionTypeTransfer := firefly3.TRANSFER_TransactionTypeProperty
|
||||
|
||||
firefly3Transaction := firefly3.TransactionSplitStore{
|
||||
Type_: &transactionTypeWithdrawal,
|
||||
Date: time.Unix(int64(transaction.Data.StatementItem.Time), 0).Add(time.Hour * 2),
|
||||
Notes: string(body),
|
||||
Amount: strconv.Itoa(int(math.Abs(math.Round(float64(transaction.Data.StatementItem.Amount/100)))) - int(math.Abs(math.Round(float64(transaction.Data.StatementItem.CommissionRate/100))))),
|
||||
SourceId: account.Id,
|
||||
Type_: &firefly3TransactionTypeWithdrawal,
|
||||
Date: time.Unix(int64(monobankTransaction.Data.StatementItem.Time), 0).Add(time.Hour * 2),
|
||||
Notes: string(monobankTransactionJson),
|
||||
Amount: strconv.Itoa(int(math.Abs(math.Round(float64(monobankTransaction.Data.StatementItem.Amount/100)))) - int(math.Abs(math.Round(float64(monobankTransaction.Data.StatementItem.CommissionRate/100))))),
|
||||
SourceId: account.Firefly3Id,
|
||||
}
|
||||
|
||||
if slices.Contains([]string{"З чорної картки"}, transaction.Data.StatementItem.Description) {
|
||||
firefly3Transaction.Type_ = &transactionTypeTransfer
|
||||
// Special transaction cases
|
||||
if slices.Contains([]string{"З чорної картки"}, monobankTransaction.Data.StatementItem.Description) {
|
||||
firefly3Transaction.Type_ = &firefly3TransactionTypeTransfer
|
||||
firefly3Transaction.Description = "Transfer between accounts"
|
||||
firefly3Transaction.DestinationId = Firefy3AccountsConfig["Mono White"]
|
||||
firefly3Transaction.DestinationId = ConfigGetAccountByName(config, "Mono White").Firefly3Id
|
||||
firefly3Transactions = append(firefly3Transactions, firefly3Transaction)
|
||||
} else if slices.Contains([]string{"З білої картки"}, transaction.Data.StatementItem.Description) {
|
||||
firefly3Transaction.Type_ = &transactionTypeTransfer
|
||||
} else if slices.Contains([]string{"З білої картки"}, monobankTransaction.Data.StatementItem.Description) {
|
||||
firefly3Transaction.Type_ = &firefly3TransactionTypeTransfer
|
||||
firefly3Transaction.Description = "Transfer between accounts"
|
||||
firefly3Transaction.DestinationId = Firefy3AccountsConfig["Mono Black"]
|
||||
firefly3Transaction.DestinationId = ConfigGetAccountByName(config, "Mono Black").Firefly3Id
|
||||
firefly3Transactions = append(firefly3Transactions, firefly3Transaction)
|
||||
} else if slices.Contains([]string{"Термінал City24"}, transaction.Data.StatementItem.Description) {
|
||||
firefly3Transaction.Type_ = &transactionTypeTransfer
|
||||
} else if slices.Contains([]string{"Термінал City24"}, monobankTransaction.Data.StatementItem.Description) {
|
||||
firefly3Transaction.Type_ = &firefly3TransactionTypeTransfer
|
||||
firefly3Transaction.Description = "Transfer between accounts"
|
||||
firefly3Transaction.SourceId = Firefy3AccountsConfig["Wallet cash (UAH)"]
|
||||
firefly3Transaction.SourceId = ConfigGetAccountByName(config, "Wallet cash (UAH)").Firefly3Id
|
||||
firefly3Transaction.DestinationId = firefly3Transaction.SourceId
|
||||
firefly3Transactions = append(firefly3Transactions, firefly3Transaction)
|
||||
} else if slices.Contains([]string{"Термінал EasyPay", "City24", "Термінал City24"}, transaction.Data.StatementItem.Description) {
|
||||
firefly3Transaction.Type_ = &transactionTypeTransfer
|
||||
} else if slices.Contains([]string{"Термінал EasyPay", "City24", "Термінал City24"}, monobankTransaction.Data.StatementItem.Description) {
|
||||
firefly3Transaction.Type_ = &firefly3TransactionTypeTransfer
|
||||
firefly3Transaction.Description = "Transfer between accounts"
|
||||
firefly3Transaction.SourceId = Firefy3AccountsConfig["Wallet cash (UAH)"] // test
|
||||
firefly3Transaction.DestinationId = account.Id // test
|
||||
firefly3Transaction.SourceId = ConfigGetAccountByName(config, "Wallet cash (UAH)").Firefly3Id // test
|
||||
firefly3Transaction.DestinationId = account.Firefly3Id // test
|
||||
firefly3Transactions = append(firefly3Transactions, firefly3Transaction)
|
||||
} else if slices.Contains([]string{"Банкомат DN00"}, transaction.Data.StatementItem.Description) {
|
||||
firefly3Transaction.Type_ = &transactionTypeTransfer
|
||||
} else if slices.Contains([]string{"Банкомат DN00"}, monobankTransaction.Data.StatementItem.Description) {
|
||||
firefly3Transaction.Type_ = &firefly3TransactionTypeTransfer
|
||||
firefly3Transaction.Description = "Transfer between accounts"
|
||||
firefly3Transaction.DestinationId = Firefy3AccountsConfig["Wallet cash (UAH)"] // test
|
||||
firefly3Transaction.DestinationId = ConfigGetAccountByName(config, "Wallet cash (UAH)").Firefly3Id // test
|
||||
firefly3Transactions = append(firefly3Transactions, firefly3Transaction)
|
||||
} else {
|
||||
for _, row := range ShopConfig {
|
||||
if slices.Contains(row.Names, transaction.Data.StatementItem.Description) || slices.Contains(row.MCCCodes, transaction.Data.StatementItem.Mcc) {
|
||||
firefly3Transaction.Description = row.TransactionDescription
|
||||
firefly3Transaction.DestinationName = row.TransactionDestination
|
||||
firefly3Transaction.CategoryName = row.TransactionCategory
|
||||
for _, row := range config.TransactionTypes {
|
||||
if slices.Contains(row.Names, monobankTransaction.Data.StatementItem.Description) || slices.Contains(row.MccCodes, monobankTransaction.Data.StatementItem.Mcc) {
|
||||
firefly3Transaction.Description = row.Firefly3.Description
|
||||
firefly3Transaction.DestinationName = row.Firefly3.Destination
|
||||
firefly3Transaction.CategoryName = row.Firefly3.Category
|
||||
firefly3Transactions = append(firefly3Transactions, firefly3Transaction)
|
||||
break
|
||||
}
|
||||
@ -159,14 +153,14 @@ func handleWebhook(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
// record transfer fee
|
||||
if transaction.Data.StatementItem.CommissionRate > 0 {
|
||||
if monobankTransaction.Data.StatementItem.CommissionRate > 0 {
|
||||
firefly3Transactions = append(firefly3Transactions, firefly3.TransactionSplitStore{
|
||||
Type_: &transactionTypeWithdrawal,
|
||||
Date: time.Unix(int64(transaction.Data.StatementItem.Time), 0).Add(time.Hour * 2),
|
||||
Notes: string(body),
|
||||
Type_: &firefly3TransactionTypeWithdrawal,
|
||||
Date: time.Unix(int64(monobankTransaction.Data.StatementItem.Time), 0).Add(time.Hour * 2),
|
||||
Notes: string(monobankTransactionJson),
|
||||
Description: "Transfer fee",
|
||||
Amount: strconv.Itoa(int(math.Abs(math.Round(float64(transaction.Data.StatementItem.CommissionRate / 100))))),
|
||||
SourceId: account.Id,
|
||||
Amount: strconv.Itoa(int(math.Abs(math.Round(float64(monobankTransaction.Data.StatementItem.CommissionRate / 100))))),
|
||||
SourceId: account.Firefly3Id,
|
||||
})
|
||||
}
|
||||
|
||||
@ -175,7 +169,7 @@ func handleWebhook(w http.ResponseWriter, r *http.Request) {
|
||||
transactionOpts := firefly3.TransactionsApiStoreTransactionOpts{}
|
||||
|
||||
for _, transaction := range firefly3Transactions {
|
||||
_, _, err = client.TransactionsApi.StoreTransaction(context.Background(), firefly3.TransactionStore{
|
||||
_, _, err = firefly3Client.TransactionsApi.StoreTransaction(context.Background(), firefly3.TransactionStore{
|
||||
ApplyRules: true,
|
||||
Transactions: []firefly3.TransactionSplitStore{transaction},
|
||||
}, &transactionOpts)
|
||||
@ -197,9 +191,6 @@ func main() {
|
||||
log.Fatalf("Error loading .env file")
|
||||
}
|
||||
|
||||
// Configure
|
||||
ShopConfig, Firefy3AccountsConfig = Configure()
|
||||
|
||||
// set webhook
|
||||
http.HandleFunc("/webhook", handleWebhook)
|
||||
|
||||
|
Reference in New Issue
Block a user