File size: 2,739 Bytes
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
import { z } from "zod";
import { Ledger, LedgerError } from "./ledger.js";

/** Invoice payload as decoded from a scanned QR code (JSON or projectos-invoice: URI). */
export const InvoiceSchema = z.object({
  v: z.literal(1),
  invoice_id: z.string().min(1).max(128),
  merchant_id: z.string().min(1).max(128),
  merchant_name: z.string().max(200).optional(),
  amount: z.number().int().positive(), // minor units
  currency: z.string().length(3).transform((c) => c.toLowerCase()),
  due_at: z.string().datetime().optional(),
});
export type Invoice = z.infer<typeof InvoiceSchema>;

export function parseInvoiceQr(raw: string): Invoice {
  let obj: unknown;
  const s = raw.trim();
  if (s.startsWith("projectos-invoice:")) {
    const params = new URLSearchParams(s.slice("projectos-invoice:".length).replace(/^\?/, ""));
    obj = Object.fromEntries(params);
    const o = obj as Record<string, unknown>;
    o.v = Number(o.v); o.amount = Number(o.amount);
  } else {
    try { obj = JSON.parse(s); } catch { throw new LedgerError("invalid invoice QR payload"); }
  }
  const r = InvoiceSchema.safeParse(obj);
  if (!r.success) throw new LedgerError(`invalid invoice: ${r.error.issues.map((i) => i.path.join(".") + " " + i.message).join("; ")}`);
  return r.data;
}

/**
 * Pay an invoice from wallet balance. INTERNAL LEDGER ONLY: moves value to a
 * merchant_payable account. No external payout/real-money path exists; settling to
 * unrelated merchants requires a licensed issuer integration (not implemented).
 */
export async function payInvoice(ledger: Ledger, userId: string, invoice: Invoice, now = new Date()) {
  if (invoice.due_at && new Date(invoice.due_at) < now) { /* overdue is allowed, informational */ }
  const balance = await ledger.walletBalance(userId, invoice.currency);
  const key = `invoice:${invoice.merchant_id}:${invoice.invoice_id}`;
  const prior = (await ledger.list(userId, 1000)).find((t) => t.idempotency_key === key);
  if (prior) return { status: "already_paid" as const, transaction: prior, balance };
  if (balance < invoice.amount) throw new LedgerError(`insufficient funds: balance ${balance} < ${invoice.amount}`);
  const wallet = await ledger.account(userId, "user_wallet", invoice.currency);
  const payable = await ledger.account(userId, "merchant_payable", invoice.currency);
  const tx = await ledger.post({
    user_id: userId, kind: "invoice_payment", idempotency_key: key,
    memo: `Invoice ${invoice.invoice_id} to ${invoice.merchant_name ?? invoice.merchant_id}`,
    postings: [{ account_id: wallet.id, amount: invoice.amount }, { account_id: payable.id, amount: -invoice.amount }],
  });
  return { status: "paid" as const, transaction: tx, balance: balance - invoice.amount };
}