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

81 lines
1.5 KiB
Go

package model
import (
"crypto/md5"
"encoding/hex"
"errors"
"strings"
"gitnet.fr/deblan/budget/database/manager"
)
func ImportBanquePopulaireTransactions(content string, bankAccountID int) ([]Transaction, error) {
lines := strings.Split(content, "\n")
db := manager.Get().Db
datas := []Transaction{}
for key, line := range lines {
if key == 0 {
continue
}
line = strings.TrimSpace(line)
if line == "" {
continue
}
fields := strings.Split(line, ";")
if len(fields) != 8 {
return datas, errors.New("Invalid format")
}
hash := md5.New()
hash.Write([]byte(line))
hashInBytes := hash.Sum(nil)
ref := hex.EncodeToString(hashInBytes)
var count int64
db.Model(Transaction{}).Where(Transaction{
Reference: ref,
BankAccountID: bankAccountID,
}).Count(&count)
if count > 0 {
continue
}
amount := ToFloat(fields[6])
debit := 0.0
credit := 0.0
if amount > 0 {
credit = amount
} else {
debit = -amount
}
transaction := Transaction{
ShortLabel: "",
Label: ToUTF8(fields[3]),
Reference: ref,
Information: "",
OperationType: "",
AccountedAt: ToDate(fields[1], "02/01/2006"),
BankCategory: "",
BankSubCategory: "",
Debit: debit,
Credit: credit,
BankAccountID: bankAccountID,
Date: ToDate(fields[2], "02/01/2006"),
}
db.Model(Transaction{}).Save(&transaction)
datas = append(datas, transaction)
}
return datas, nil
}