Files
sxchnge/backend/pkg/model/payment_ledger.go
T

78 lines
2.8 KiB
Go

package model
import (
"encoding/json"
"strings"
"git.sendico.io/tech/sxchnge/bff/pkg/merrors"
"go.mongodb.org/mongo-driver/v2/bson"
)
type LedgerPaymentData struct {
AccountRef string `bson:"accountRef,omitempty" json:"account_ref,omitempty"`
AccountCode string `bson:"accountCode,omitempty" json:"account_code,omitempty"`
ContraAccountRef string `bson:"contraAccountRef,omitempty" json:"contra_account_ref,omitempty"`
ContraAccountCode string `bson:"contraAccountCode,omitempty" json:"contra_account_code,omitempty"`
}
func (d *LedgerPaymentData) UnmarshalJSON(data []byte) error {
var raw struct {
AccountRef string `json:"account_ref"`
LedgerAccountRef string `json:"ledger_account_ref"`
AccountCode string `json:"account_code"`
ContraAccountRef string `json:"contra_account_ref"`
ContraLedgerAccountRef string `json:"contra_ledger_account_ref"`
ContraAccountCode string `json:"contra_account_code"`
}
if err := json.Unmarshal(data, &raw); err != nil {
return err
}
accountRef := strings.TrimSpace(raw.AccountRef)
ledgerAccountRef := strings.TrimSpace(raw.LedgerAccountRef)
if ledgerAccountRef != "" {
if accountRef != "" && accountRef != ledgerAccountRef {
return merrors.InvalidArgument("account_ref and ledger_account_ref must match")
}
accountRef = ledgerAccountRef
}
contraAccountRef := strings.TrimSpace(raw.ContraAccountRef)
contraLedgerAccountRef := strings.TrimSpace(raw.ContraLedgerAccountRef)
if contraLedgerAccountRef != "" {
if contraAccountRef != "" && contraAccountRef != contraLedgerAccountRef {
return merrors.InvalidArgument("contra_account_ref and contra_ledger_account_ref must match")
}
contraAccountRef = contraLedgerAccountRef
}
d.AccountRef = accountRef
d.AccountCode = strings.TrimSpace(raw.AccountCode)
d.ContraAccountRef = contraAccountRef
d.ContraAccountCode = strings.TrimSpace(raw.ContraAccountCode)
return nil
}
func (d *LedgerPaymentData) UnmarshalBSON(data []byte) error {
var raw map[string]any
if err := bson.Unmarshal(data, &raw); err != nil {
return err
}
d.AccountRef = firstPaymentDataString(raw, "accountRef", "account_ref", "ledgerAccountRef", "ledger_account_ref")
d.AccountCode = firstPaymentDataString(raw, "accountCode", "account_code")
d.ContraAccountRef = firstPaymentDataString(raw, "contraAccountRef", "contra_account_ref", "contraLedgerAccountRef", "contra_ledger_account_ref")
d.ContraAccountCode = firstPaymentDataString(raw, "contraAccountCode", "contra_account_code")
return nil
}
func (m *PaymentMethod) AsLedger() (*LedgerPaymentData, error) {
if m.Type != PaymentTypeLedger {
return nil, merrors.InvalidArgument("payment method type is "+m.Type.String()+", not ledger", "type")
}
var d LedgerPaymentData
if err := bson.Unmarshal(m.Data, &d); err != nil {
return nil, err
}
return &d, nil
}