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; 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; 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 }; }