package db import ( "context" "database/sql" "errors" "strings" "github.com/noderunners/dlbot/internal/ids" ) // Money errors. var ( ErrInsufficient = errors.New("db: insufficient balance") ErrDuplicate = errors.New("db: duplicate entry") ) // isUniqueViolation recognizes a unique constraint error on both engines. func isUniqueViolation(err error) bool { if err == nil { return false } msg := err.Error() return strings.Contains(msg, "UNIQUE constraint failed") || // sqlite strings.Contains(msg, "duplicate key value") || strings.Contains(msg, "23505") // postgres } // --- wallets --------------------------------------------------------------- const walletCols = `id, owner_type, owner_id, balance, created_at` func scanWallet(sc interface{ Scan(...any) error }) (*Wallet, error) { var w Wallet if err := sc.Scan(&w.ID, &w.OwnerType, &w.OwnerID, &w.Balance, &w.CreatedAt); err != nil { return nil, notFound(err) } return &w, nil } // GetWallet loads a wallet by ID. func (s *Store) GetWallet(ctx context.Context, id string) (*Wallet, error) { return scanWallet(s.row(ctx, `SELECT `+walletCols+` FROM wallets WHERE id = ?`, id)) } // FindWallet loads the wallet of an owner, or ErrNotFound. func (s *Store) FindWallet(ctx context.Context, ownerType string, ownerID int64) (*Wallet, error) { return scanWallet(s.row(ctx, `SELECT `+walletCols+` FROM wallets WHERE owner_type = ? AND owner_id = ?`, ownerType, ownerID)) } // EnsureWallet returns the wallet of an owner, creating it when needed. func (s *Store) EnsureWallet(ctx context.Context, ownerType string, ownerID int64) (*Wallet, error) { w, err := s.FindWallet(ctx, ownerType, ownerID) if err == nil || !errors.Is(err, ErrNotFound) { return w, err } _, err = s.exec(ctx, `INSERT INTO wallets (id, owner_type, owner_id, balance, created_at) VALUES (?, ?, ?, 0, ?) ON CONFLICT (owner_type, owner_id) DO NOTHING`, ids.New(), ownerType, ownerID, NowMilli()) if err != nil { return nil, err } return s.FindWallet(ctx, ownerType, ownerID) } // --- ledger ---------------------------------------------------------------- // AddLedger appends an entry and moves the wallet balance in the same // transaction. It must be called inside InTx. // // The entry is idempotent on DedupeKey: when an entry with that key exists // nothing changes and applied is false. A debit that the balance cannot // cover fails with ErrInsufficient and changes nothing. func (s *Store) AddLedger(ctx context.Context, e *LedgerEntry) (applied bool, err error) { if !s.inTx { return false, errors.New("db: AddLedger needs a transaction") } if e.Amount <= 0 { return false, errors.New("db: ledger amount must be positive") } if e.DedupeKey == "" { return false, errors.New("db: ledger entry needs a dedupe key") } var exists int err = s.row(ctx, `SELECT COUNT(*) FROM ledger WHERE dedupe_key = ?`, e.DedupeKey).Scan(&exists) if err != nil { return false, err } if exists > 0 { return false, nil } var n int64 switch e.Kind { case LedgerCredit, LedgerRefund: n, err = s.exec(ctx, `UPDATE wallets SET balance = balance + ? WHERE id = ?`, e.Amount, e.WalletID) case LedgerDebit: n, err = s.exec(ctx, `UPDATE wallets SET balance = balance - ? WHERE id = ? AND balance >= ?`, e.Amount, e.WalletID, e.Amount) if err == nil && n == 0 { return false, ErrInsufficient } default: return false, errors.New("db: unknown ledger kind " + e.Kind) } if err != nil { return false, err } if n == 0 { return false, ErrNotFound } if err := s.row(ctx, `SELECT balance FROM wallets WHERE id = ?`, e.WalletID).Scan(&e.BalanceAfter); err != nil { return false, err } if e.ID == "" { e.ID = ids.New() } if e.CreatedAt == 0 { e.CreatedAt = NowMilli() } if e.PaymentMethod == "" { e.PaymentMethod = PayLightning } _, err = s.exec(ctx, `INSERT INTO ledger (id, wallet_id, kind, amount, balance_after, reason, ref, dedupe_key, actor_id, created_at, payment_method) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, e.ID, e.WalletID, e.Kind, e.Amount, e.BalanceAfter, e.Reason, e.Ref, e.DedupeKey, e.ActorID, e.CreatedAt, e.PaymentMethod) if isUniqueViolation(err) { // Lost a race against the same key on another connection. The // surrounding transaction must roll back, which undoes the balance. return false, ErrDuplicate } return err == nil, err } // LedgerBalance recomputes a wallet balance from the ledger alone. func (s *Store) LedgerBalance(ctx context.Context, walletID string) (int64, error) { var sum sql.NullInt64 err := s.row(ctx, `SELECT SUM(CASE WHEN kind = 'debit' THEN -amount ELSE amount END) FROM ledger WHERE wallet_id = ?`, walletID).Scan(&sum) return sum.Int64, err } // WalletMismatch describes a wallet whose cached balance disagrees with // its ledger. type WalletMismatch struct { WalletID string Balance int64 Ledger int64 } // VerifyWallets compares every cached balance with its ledger and returns // the wallets that disagree. An empty result means the books are sound. func (s *Store) VerifyWallets(ctx context.Context) ([]WalletMismatch, error) { rows, err := s.rows(ctx, `SELECT w.id, w.balance, COALESCE((SELECT SUM(CASE WHEN l.kind = 'debit' THEN -l.amount ELSE l.amount END) FROM ledger l WHERE l.wallet_id = w.id), 0) AS ledger_sum FROM wallets w`) if err != nil { return nil, err } defer rows.Close() var out []WalletMismatch for rows.Next() { var m WalletMismatch if err := rows.Scan(&m.WalletID, &m.Balance, &m.Ledger); err != nil { return nil, err } if m.Balance != m.Ledger { out = append(out, m) } } return out, rows.Err() } // ListLedger returns the newest entries of a wallet. func (s *Store) ListLedger(ctx context.Context, walletID string, limit int) ([]*LedgerEntry, error) { rows, err := s.rows(ctx, `SELECT id, wallet_id, kind, amount, balance_after, reason, ref, dedupe_key, actor_id, created_at, payment_method FROM ledger WHERE wallet_id = ? ORDER BY created_at DESC, id DESC LIMIT ?`, walletID, limit) if err != nil { return nil, err } defer rows.Close() var out []*LedgerEntry for rows.Next() { var e LedgerEntry if err := rows.Scan(&e.ID, &e.WalletID, &e.Kind, &e.Amount, &e.BalanceAfter, &e.Reason, &e.Ref, &e.DedupeKey, &e.ActorID, &e.CreatedAt, &e.PaymentMethod); err != nil { return nil, err } out = append(out, &e) } return out, rows.Err() } // --- passes ---------------------------------------------------------------- // PassUntil returns when the wallet's pass coverage ends, or 0 when no // pass is active at now. Passes bought while one is active are stacked // end to end, so the latest expiry is the end of coverage. func (s *Store) PassUntil(ctx context.Context, walletID string, now int64) (int64, error) { var until sql.NullInt64 err := s.row(ctx, `SELECT MAX(expires_at) FROM passes WHERE wallet_id = ? AND expires_at > ?`, walletID, now).Scan(&until) return until.Int64, err } // AddPass grants a pass of the given length in milliseconds. When a pass // is still active the new one starts where it ends. func (s *Store) AddPass(ctx context.Context, walletID, kind string, lengthMS int64, source string, now int64) (*Pass, error) { start := now until, err := s.PassUntil(ctx, walletID, now) if err != nil { return nil, err } if until > start { start = until } p := &Pass{ ID: ids.New(), WalletID: walletID, Kind: kind, StartsAt: start, ExpiresAt: start + lengthMS, Source: source, CreatedAt: now, } _, err = s.exec(ctx, `INSERT INTO passes (id, wallet_id, kind, starts_at, expires_at, source, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)`, p.ID, p.WalletID, p.Kind, p.StartsAt, p.ExpiresAt, p.Source, p.CreatedAt) return p, err } // ExtendPass pushes the end of the current pass coverage out by lengthMS. // It reports false when the wallet has no active pass. func (s *Store) ExtendPass(ctx context.Context, walletID string, lengthMS, now int64) (bool, error) { until, err := s.PassUntil(ctx, walletID, now) if err != nil || until == 0 { return false, err } n, err := s.exec(ctx, `UPDATE passes SET expires_at = expires_at + ? WHERE wallet_id = ? AND expires_at = ?`, lengthMS, walletID, until) return n > 0, err } // --- purchases ------------------------------------------------------------- const purchaseCols = `id, user_id, wallet_id, product, amount_sats, status, payment_hash, bolt11, chat_id, message_id, message_is_photo, lang, request_id, profile, delivery_id, fulfilled, created_at, expires_at, paid_at, payment_method, stars_amount, tg_charge_id, refunded_at` func scanPurchase(sc interface{ Scan(...any) error }) (*Purchase, error) { var p Purchase err := sc.Scan(&p.ID, &p.UserID, &p.WalletID, &p.Product, &p.AmountSats, &p.Status, &p.PaymentHash, &p.Bolt11, &p.ChatID, &p.MessageID, &p.MessageIsPhoto, &p.Lang, &p.RequestID, &p.Profile, &p.DeliveryID, &p.Fulfilled, &p.CreatedAt, &p.ExpiresAt, &p.PaidAt, &p.PaymentMethod, &p.StarsAmount, &p.ChargeID, &p.RefundedAt) if err != nil { return nil, notFound(err) } return &p, nil } func scanPurchases(rows *sql.Rows, err error) ([]*Purchase, error) { if err != nil { return nil, err } defer rows.Close() var out []*Purchase for rows.Next() { p, err := scanPurchase(rows) if err != nil { return nil, err } out = append(out, p) } return out, rows.Err() } // InsertPurchase stores a new purchase. func (s *Store) InsertPurchase(ctx context.Context, p *Purchase) error { if p.PaymentMethod == "" { p.PaymentMethod = PayLightning } _, err := s.exec(ctx, `INSERT INTO purchases (`+purchaseCols+`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, p.ID, p.UserID, p.WalletID, p.Product, p.AmountSats, p.Status, p.PaymentHash, p.Bolt11, p.ChatID, p.MessageID, p.MessageIsPhoto, p.Lang, p.RequestID, p.Profile, p.DeliveryID, p.Fulfilled, p.CreatedAt, p.ExpiresAt, p.PaidAt, p.PaymentMethod, p.StarsAmount, p.ChargeID, p.RefundedAt) return err } // GetPurchase loads a purchase by ID. func (s *Store) GetPurchase(ctx context.Context, id string) (*Purchase, error) { return scanPurchase(s.row(ctx, `SELECT `+purchaseCols+` FROM purchases WHERE id = ?`, id)) } // GetPurchaseByHash loads a purchase by its Lightning payment hash. func (s *Store) GetPurchaseByHash(ctx context.Context, hash string) (*Purchase, error) { return scanPurchase(s.row(ctx, `SELECT `+purchaseCols+` FROM purchases WHERE payment_hash = ?`, hash)) } // MarkPurchasePaid moves a purchase to paid from any unpaid status and // reports whether this call did it. This single conditional update is what // makes settlement idempotent: however many webhooks and polls race, one // of them wins and the rest see false. func (s *Store) MarkPurchasePaid(ctx context.Context, id string, now int64) (bool, error) { n, err := s.exec(ctx, `UPDATE purchases SET status = 'paid', paid_at = ? WHERE id = ? AND status IN ('pending', 'expired', 'cancelled')`, now, id) return n == 1, err } // ClosePurchase moves a pending purchase to expired or cancelled. func (s *Store) ClosePurchase(ctx context.Context, id, status string) (bool, error) { n, err := s.exec(ctx, `UPDATE purchases SET status = ? WHERE id = ? AND status = 'pending'`, status, id) return n == 1, err } // MarkPurchaseFulfilled records that the follow-up of a paid purchase (the // download it was for) has been handled, and reports whether this call // was the first to do so. func (s *Store) MarkPurchaseFulfilled(ctx context.Context, id string) (bool, error) { n, err := s.exec(ctx, `UPDATE purchases SET fulfilled = ? WHERE id = ? AND fulfilled = ?`, true, id, false) return n == 1, err } // SetPurchaseMessage records the message that shows the invoice. func (s *Store) SetPurchaseMessage(ctx context.Context, id string, chatID, messageID int64, isPhoto bool) error { _, err := s.exec(ctx, `UPDATE purchases SET chat_id = ?, message_id = ?, message_is_photo = ? WHERE id = ?`, chatID, messageID, isPhoto, id) return err } // UnsettledPurchases lists purchases that may still turn out to be paid: // every pending one, plus those closed after the given time. A payment can // arrive in the moment an invoice expires or is cancelled. func (s *Store) UnsettledPurchases(ctx context.Context, closedAfter int64, limit int) ([]*Purchase, error) { return scanPurchases(s.rows(ctx, `SELECT `+purchaseCols+` FROM purchases WHERE payment_method = 'lightning' AND (status = 'pending' OR (status IN ('expired', 'cancelled') AND expires_at > ?)) ORDER BY created_at LIMIT ?`, closedAfter, limit)) } // UnfulfilledPaidPurchases lists paid purchases whose follow-up has not // run yet, for example because the core stopped right after settlement. func (s *Store) UnfulfilledPaidPurchases(ctx context.Context, limit int) ([]*Purchase, error) { return scanPurchases(s.rows(ctx, `SELECT `+purchaseCols+` FROM purchases WHERE status = 'paid' AND fulfilled = ? ORDER BY paid_at LIMIT ?`, false, limit)) } // CountReferralPurchases counts the settled purchases of a user that our // referral program looks at: everything but donations, paid over // Lightning. func (s *Store) CountReferralPurchases(ctx context.Context, userID int64) (int, error) { var n int err := s.row(ctx, `SELECT COUNT(*) FROM purchases WHERE user_id = ? AND status IN ('paid', 'refunded') AND product <> 'donation' AND payment_method = 'lightning'`, userID).Scan(&n) return n, err } // CountPaidPurchases counts the paid purchases of a user, donations aside. func (s *Store) CountPaidPurchases(ctx context.Context, userID int64) (int, error) { var n int err := s.row(ctx, `SELECT COUNT(*) FROM purchases WHERE user_id = ? AND status = 'paid' AND product <> 'donation'`, userID).Scan(&n) return n, err } // CountPurchases counts purchases by status, for metrics. func (s *Store) CountPurchases(ctx context.Context, status string) (int, error) { var n int err := s.row(ctx, `SELECT COUNT(*) FROM purchases WHERE status = ?`, status).Scan(&n) return n, err } // --- usage ----------------------------------------------------------------- // GetUsage returns what a user consumed on a day (YYYYMMDD). func (s *Store) GetUsage(ctx context.Context, userID int64, day int) (Usage, error) { var u Usage err := s.row(ctx, `SELECT downloads, bytes FROM usage_daily WHERE user_id = ? AND day = ?`, userID, day).Scan(&u.Downloads, &u.Bytes) if errors.Is(err, sql.ErrNoRows) { return Usage{}, nil } return u, err } // AddUsage adds to a user's counters for a day. Negative values give back. func (s *Store) AddUsage(ctx context.Context, userID int64, day, downloads int, bytes int64) error { _, err := s.exec(ctx, `INSERT INTO usage_daily (user_id, day, downloads, bytes) VALUES (?, ?, ?, ?) ON CONFLICT (user_id, day) DO UPDATE SET downloads = usage_daily.downloads + excluded.downloads, bytes = usage_daily.bytes + excluded.bytes`, userID, day, downloads, bytes) return err } // --- gift codes ------------------------------------------------------------ // InsertGiftCode stores a new code. func (s *Store) InsertGiftCode(ctx context.Context, g *GiftCode) error { if g.CreatedAt == 0 { g.CreatedAt = NowMilli() } _, err := s.exec(ctx, `INSERT INTO gift_codes (code, kind, amount, max_uses, uses, expires_at, created_by, created_at) VALUES (?, ?, ?, ?, 0, ?, ?, ?)`, g.Code, g.Kind, g.Amount, g.MaxUses, g.ExpiresAt, g.CreatedBy, g.CreatedAt) if isUniqueViolation(err) { return ErrDuplicate } return err } // GetGiftCode loads a code. func (s *Store) GetGiftCode(ctx context.Context, code string) (*GiftCode, error) { var g GiftCode err := s.row(ctx, `SELECT code, kind, amount, max_uses, uses, expires_at, created_by, created_at FROM gift_codes WHERE code = ?`, code).Scan(&g.Code, &g.Kind, &g.Amount, &g.MaxUses, &g.Uses, &g.ExpiresAt, &g.CreatedBy, &g.CreatedAt) if err != nil { return nil, notFound(err) } return &g, nil } // UseGiftCode takes one use of a code for a user. It must run in a // transaction. used is false when the code is spent, expired or was // already redeemed by this user. func (s *Store) UseGiftCode(ctx context.Context, code string, userID, now int64) (used bool, err error) { if !s.inTx { return false, errors.New("db: UseGiftCode needs a transaction") } var seen int if err := s.row(ctx, `SELECT COUNT(*) FROM gift_redemptions WHERE code = ? AND user_id = ?`, code, userID).Scan(&seen); err != nil { return false, err } if seen > 0 { return false, nil } n, err := s.exec(ctx, `UPDATE gift_codes SET uses = uses + 1 WHERE code = ? AND uses < max_uses AND (expires_at = 0 OR expires_at > ?)`, code, now) if err != nil || n == 0 { return false, err } _, err = s.exec(ctx, `INSERT INTO gift_redemptions (code, user_id, created_at) VALUES (?, ?, ?)`, code, userID, now) if isUniqueViolation(err) { return false, ErrDuplicate } return err == nil, err } // SetPurchaseCharge records Telegram's charge ID of a Stars payment. The // unique index makes a second purchase with the same charge fail with // ErrDuplicate. func (s *Store) SetPurchaseCharge(ctx context.Context, id, chargeID string) error { _, err := s.exec(ctx, `UPDATE purchases SET tg_charge_id = ? WHERE id = ? AND tg_charge_id = ''`, chargeID, id) if isUniqueViolation(err) { return ErrDuplicate } return err } // GetPurchaseByCharge finds a Stars purchase by Telegram's charge ID. func (s *Store) GetPurchaseByCharge(ctx context.Context, chargeID string) (*Purchase, error) { if chargeID == "" { return nil, ErrNotFound } return scanPurchase(s.row(ctx, `SELECT `+purchaseCols+` FROM purchases WHERE tg_charge_id = ?`, chargeID)) } // MarkPurchaseRefunded moves a paid Stars purchase to refunded. It // reports false when it was not paid, so a refund is undone once. func (s *Store) MarkPurchaseRefunded(ctx context.Context, id string, now int64) (bool, error) { n, err := s.exec(ctx, `UPDATE purchases SET status = 'refunded', refunded_at = ? WHERE id = ? AND status = 'paid' AND payment_method = 'stars'`, now, id) return n == 1, err } // RemovePassesFrom deletes the passes a purchase granted, for a refund, // and moves later passes of the wallet back by the time they lose. func (s *Store) RemovePassesFrom(ctx context.Context, walletID, source string) (int64, error) { var start, end sql.NullInt64 if err := s.row(ctx, `SELECT MIN(starts_at), MAX(expires_at) FROM passes WHERE wallet_id = ? AND source = ?`, walletID, source).Scan(&start, &end); err != nil || !start.Valid { return 0, err } n, err := s.exec(ctx, `DELETE FROM passes WHERE wallet_id = ? AND source = ?`, walletID, source) if err != nil || n == 0 { return n, err } // Passes that were stacked after the refunded one start earlier now. length := end.Int64 - start.Int64 _, err = s.exec(ctx, `UPDATE passes SET starts_at = starts_at - ?, expires_at = expires_at - ? WHERE wallet_id = ? AND starts_at >= ?`, length, length, walletID, end.Int64) return n, err } // Revenue is what one payment method brought in. type Revenue struct { Method string Purchases int Sats int64 // Lightning: sats received Stars int64 // Stars: Stars received, refunds excluded Refunded int } // RevenueByMethod sums settled purchases per payment method since a // moment (0 for all time). Refunded Stars purchases are counted apart. func (s *Store) RevenueByMethod(ctx context.Context, since int64) ([]Revenue, error) { rows, err := s.rows(ctx, `SELECT payment_method, COALESCE(SUM(CASE WHEN status = 'paid' THEN 1 ELSE 0 END), 0), COALESCE(SUM(CASE WHEN status = 'paid' AND payment_method = 'lightning' THEN amount_sats ELSE 0 END), 0), COALESCE(SUM(CASE WHEN status = 'paid' AND payment_method = 'stars' THEN stars_amount ELSE 0 END), 0), COALESCE(SUM(CASE WHEN status = 'refunded' THEN 1 ELSE 0 END), 0) FROM purchases WHERE status IN ('paid', 'refunded') AND paid_at >= ? GROUP BY payment_method ORDER BY payment_method`, since) if err != nil { return nil, err } defer rows.Close() var out []Revenue for rows.Next() { var r Revenue if err := rows.Scan(&r.Method, &r.Purchases, &r.Sats, &r.Stars, &r.Refunded); err != nil { return nil, err } out = append(out, r) } return out, rows.Err() }