File size: 3,076 Bytes
5bd4e3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1444c0a
 
 
 
 
 
 
 
 
 
 
5bd4e3a
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import { randomUUID } from "node:crypto";
import type { AccountKind, LedgerStore, Posting, Transaction } from "./types.js";

export class LedgerError extends Error {}

/**
 * Double-entry ledger. Sign convention: wallet balance = -(sum of postings) on the
 * user_wallet account (liability, credit-normal). Every transaction sums to zero.
 */
export class Ledger {
  constructor(private store: LedgerStore) {}

  static validate(postings: Posting[]): void {
    if (postings.length < 2) throw new LedgerError("transaction needs >= 2 postings");
    for (const p of postings) {
      if (!Number.isSafeInteger(p.amount) || p.amount === 0) throw new LedgerError("amounts must be non-zero integers (minor units)");
    }
    const sum = postings.reduce((s, p) => s + p.amount, 0);
    if (sum !== 0) throw new LedgerError(`unbalanced transaction (sum=${sum})`);
  }

  account(userId: string, kind: AccountKind, currency = "usd") {
    return this.store.getOrCreateAccount(userId, kind, currency.toLowerCase());
  }

  async walletBalance(userId: string, currency = "usd"): Promise<number> {
    const acct = await this.account(userId, "user_wallet", currency);
    return -(await this.store.balance(acct.id));
  }

  async post(input: Omit<Transaction, "id" | "created_at">): Promise<Transaction> {
    Ledger.validate(input.postings);
    const existing = await this.store.findTransactionByKey(input.user_id, input.idempotency_key);
    if (existing) return existing;
    const tx: Transaction = { ...input, id: randomUUID(), created_at: new Date().toISOString() };
    await this.store.insertTransaction(tx);
    return tx;
  }

  /** Credit wallet from a confirmed Stripe TEST payment. */
  async recordFunding(userId: string, amount: number, currency: string, stripeRef: string) {
    if (amount <= 0) throw new LedgerError("funding amount must be positive");
    const clearing = await this.account(userId, "stripe_clearing", currency);
    const wallet = await this.account(userId, "user_wallet", currency);
    return this.post({
      user_id: userId, kind: "funding", idempotency_key: `stripe:${stripeRef}`, memo: "Stripe test funding",
      postings: [{ account_id: clearing.id, amount }, { account_id: wallet.id, amount: -amount }],
    });
  }

  /** TEST-mode only: simulated deposit so the wallet is usable before Stripe keys exist. */
  async recordTestCredit(userId: string, amount: number, currency = "usd") {
    if (!Number.isSafeInteger(amount) || amount < 1 || amount > 100_000) throw new LedgerError("test credit must be 1..100000 minor units");
    const clearing = await this.account(userId, "stripe_clearing", currency);
    const wallet = await this.account(userId, "user_wallet", currency);
    return this.post({
      user_id: userId, kind: "funding", idempotency_key: `test-credit:${randomUUID()}`, memo: "Test credit (simulated, no Stripe)",
      postings: [{ account_id: clearing.id, amount }, { account_id: wallet.id, amount: -amount }],
    });
  }

  list(userId: string, limit = 50) { return this.store.listTransactions(userId, limit); }
}