budget-go/database/model/transaction_revolut.go
2025-04-25 14:45:54 +02:00

88 lines
1.6 KiB
Go

package model
import (
"crypto/md5"
"encoding/csv"
"encoding/hex"
"errors"
"strings"
"gitnet.fr/deblan/budget/database/manager"
)
func ImportRevolutTransactions(content string, bankAccountID int) ([]Transaction, error) {
db := manager.Get().Db
datas := []Transaction{}
r := csv.NewReader(strings.NewReader(content))
records, err := r.ReadAll()
if err != nil {
return nil, err
}
for key, fields := range records {
if key == 0 {
continue
}
if len(fields) != 10 {
return datas, errors.New("Invalid format")
}
hash := md5.New()
hash.Write([]byte(strings.Join(fields, ",")))
hashInBytes := hash.Sum(nil)
ref := hex.EncodeToString(hashInBytes)
if fields[8] != "COMPLETED" {
continue
}
var count int64
db.Model(Transaction{}).Where(Transaction{
Reference: ref,
BankAccountID: bankAccountID,
}).Count(&count)
if count > 0 {
continue
}
amount := ToFloat(fields[5])
var debit float64
var credit float64
if amount < 0 {
debit = -amount
credit = 0
} else {
debit = 0
credit = amount
}
date := ToDate(fields[2], "2006-01-02 15:04:05")
transaction := Transaction{
ShortLabel: fields[4],
Label: fields[4],
Reference: ref,
Information: "",
OperationType: fields[0],
AccountedAt: date,
BankCategory: "",
BankSubCategory: "",
Debit: debit,
Credit: credit,
BankAccountID: bankAccountID,
Date: date,
}
db.Model(Transaction{}).Save(&transaction)
datas = append(datas, transaction)
}
return datas, nil
}