package postgres import ( "context" "encoding/json" "errors" "fmt" "time" "gl/domain/ledger" "github.com/jackc/pgx/v5" ) var ErrNotFound = ledger.ErrNotFound type JournalFilter = ledger.JournalFilter func (r *JournalRepository) GetByID(ctx context.Context, journalID string) (ledger.Journal, error) { return r.get(ctx, getJournalByIDSQL, journalID) } func (r *JournalRepository) GetByIdempotencyKey(ctx context.Context, idempotencyKey string) (ledger.Journal, error) { return r.get(ctx, getJournalByIdempotencySQL, idempotencyKey) } func (r *JournalRepository) get(ctx context.Context, query string, value string) (ledger.Journal, error) { journal, err := scanJournal(r.database.QueryRow(ctx, query, value)) if errors.Is(err, pgx.ErrNoRows) { return ledger.Journal{}, ErrNotFound } if err != nil { return ledger.Journal{}, fmt.Errorf("read journal: %w", err) } journal.Entries, err = r.loadEntries(ctx, journal.ID) if err != nil { return ledger.Journal{}, err } return journal, nil } func (r *JournalRepository) List(ctx context.Context, filter JournalFilter) ([]ledger.Journal, error) { limit := filter.Limit if limit <= 0 || limit > 201 { limit = 50 } if filter.Offset < 0 { filter.Offset = 0 } var accountClass, ownerType, ownerID any if filter.Account != nil { accountClass = filter.Account.Class ownerType = filter.Account.OwnerType ownerID = filter.Account.OwnerID } rows, err := r.database.Query(ctx, listJournalsSQL, filter.AssetID, accountClass, ownerType, ownerID, filter.RecordedFrom, filter.RecordedTo, limit, filter.Offset, ) if err != nil { return nil, fmt.Errorf("list journals: %w", err) } defer rows.Close() journals := make([]ledger.Journal, 0, limit) for rows.Next() { journal, scanErr := scanJournal(rows) if scanErr != nil { return nil, fmt.Errorf("scan journal: %w", scanErr) } journals = append(journals, journal) } if err := rows.Err(); err != nil { return nil, fmt.Errorf("iterate journals: %w", err) } rows.Close() for index := range journals { journals[index].Entries, err = r.loadEntries(ctx, journals[index].ID) if err != nil { return nil, err } } return journals, nil } func (r *JournalRepository) Balance(ctx context.Context, account ledger.AccountReference, asOf time.Time) (ledger.Amount, error) { if err := account.Validate(); err != nil { return ledger.Amount{}, err } var asOfValue any if !asOf.IsZero() { asOfValue = asOf } var value string if err := r.database.QueryRow(ctx, getBalanceSQL, account.Class, account.OwnerType, account.OwnerID, account.AssetID, asOfValue, ).Scan(&value); err != nil { return ledger.Amount{}, fmt.Errorf("read balance: %w", err) } amount, err := ledger.ParseAmount(value) if err != nil { return ledger.Amount{}, fmt.Errorf("decode balance: %w", err) } return amount, nil } type scanner interface { Scan(...any) error } func scanJournal(row scanner) (ledger.Journal, error) { var ( journal ledger.Journal reversal *string metadata []byte ) err := row.Scan( &journal.ID, &journal.SourceService, &journal.IdempotencyKey, &journal.SourceTransactionID, &journal.TrackingCode, &journal.EffectKind, &journal.EventVersion, &reversal, &journal.OccurredAt, &journal.RecordedAt, &journal.CorrelationID, &journal.ActorID, &journal.Blockchain.Network, &journal.Blockchain.TransactionHash, &journal.Blockchain.LedgerSequence, &metadata, &journal.PayloadHash, ) if err != nil { return ledger.Journal{}, err } if reversal != nil { journal.ReversalOfJournalID = *reversal } if err := json.Unmarshal(metadata, &journal.Metadata); err != nil { return ledger.Journal{}, fmt.Errorf("decode metadata: %w", err) } return journal, nil } func (r *JournalRepository) loadEntries(ctx context.Context, journalID string) ([]ledger.Entry, error) { rows, err := r.database.Query(ctx, getEntriesSQL, journalID) if err != nil { return nil, fmt.Errorf("read journal entries: %w", err) } defer rows.Close() entries := make([]ledger.Entry, 0) for rows.Next() { var ( entry ledger.Entry amountValue string ) if err := rows.Scan( &entry.LineNumber, &entry.Account.Class, &entry.Account.OwnerType, &entry.Account.OwnerID, &entry.Account.AssetID, &amountValue, &entry.Description, ); err != nil { return nil, fmt.Errorf("scan journal entry: %w", err) } entry.Amount, err = ledger.ParseAmount(amountValue) if err != nil { return nil, fmt.Errorf("decode journal entry amount: %w", err) } entries = append(entries, entry) } if err := rows.Err(); err != nil { return nil, fmt.Errorf("iterate journal entries: %w", err) } return entries, nil } const journalColumns = ` j.id, j.source_service, j.idempotency_key, j.source_transaction_id, j.tracking_code, j.effect_kind, j.event_version, j.reversal_of_journal_id, j.occurred_at, j.recorded_at, j.correlation_id, j.actor_id, j.blockchain_network, j.blockchain_transaction_hash, j.blockchain_ledger_sequence, j.metadata, j.payload_hash` const getJournalByIDSQL = `SELECT ` + journalColumns + ` FROM journals j WHERE j.id = $1 AND j.sealed_at IS NOT NULL` const getJournalByIdempotencySQL = `SELECT ` + journalColumns + ` FROM journals j WHERE j.idempotency_key = $1 AND j.sealed_at IS NOT NULL` const listJournalsSQL = `SELECT DISTINCT ` + journalColumns + ` FROM journals j JOIN journal_entries e ON e.journal_id = j.id JOIN ledger_accounts a ON a.id = e.account_id WHERE j.sealed_at IS NOT NULL AND ($1::bigint IS NULL OR e.asset_id = $1) AND ($2::text IS NULL OR ( a.class = $2 AND a.owner_type = $3 AND a.owner_id = $4 )) AND ($5::timestamptz IS NULL OR j.recorded_at >= $5) AND ($6::timestamptz IS NULL OR j.recorded_at <= $6) ORDER BY j.recorded_at DESC, j.id DESC LIMIT $7 OFFSET $8` const getEntriesSQL = ` SELECT e.line_number, a.class, a.owner_type, a.owner_id, e.asset_id, e.amount::text, e.description FROM journal_entries e JOIN ledger_accounts a ON a.id = e.account_id WHERE e.journal_id = $1 ORDER BY e.line_number` const getBalanceSQL = ` SELECT COALESCE(sum(e.amount), 0)::text FROM journal_entries e JOIN ledger_accounts a ON a.id = e.account_id JOIN journals j ON j.id = e.journal_id WHERE j.sealed_at IS NOT NULL AND a.class = $1 AND a.owner_type = $2 AND a.owner_id = $3 AND a.asset_id = $4 AND ($5::timestamptz IS NULL OR j.recorded_at <= $5)`