CI (SIAX Cloud) / integration (push) Skipped
CI (SIAX Cloud) / sonar (push) Skipped
masterplan-lock / check (push) Successful in 10s
CI (SIAX Cloud) / sonar (pull_request) Skipped
Security Scan (SIAX Cloud) / security (push) Successful in 13s
masterplan-lock / check (pull_request) Successful in 7s
CI (SIAX Cloud) / security (push) Successful in 26s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 17s
CI (SIAX Cloud) / security (pull_request) Successful in 19s
CI (SIAX Cloud) / quality (push) Successful in 1m9s
CI (SIAX Cloud) / quality (pull_request) Successful in 2m26s
CI (SIAX Cloud) / integration (pull_request) Successful in 2m33s
- POST /api/0pt/documents/upload: real multipart bytes into DOC0 through the durable attempt journal and the existing coordinator; verified tenant/actor only, project authorization fail-closed. - POST /api/0pt/documents/structure: DOC0 segments -> INF0 -> evidence-bound validation -> optional JSON/CSV export, with credit reserve/settle. - Credits: balance, server-owned price book, Stripe Checkout and idempotent webhook reconciliation via a Stripe re-read of session + payment intent. - /portal/dokument and /portal/krediter: SIAX-styled workspace. - @siax/access: universal, framework-neutral OpenFGA project relationship primitive reusable by DOC0/N0D/other products. - Readiness: real Redis PING probe instead of presence-only; queue is now a live dependency when configured. - Dockerfile: copy every workspace manifest so --frozen-lockfile works. - Format/build hygiene: .prettierignore, .worktrees ignored, valid manifest YAML.
113 lines
5.1 KiB
TypeScript
113 lines
5.1 KiB
TypeScript
import type { RepositorySql } from '../repositories/db';
|
|
import { withCreditTenant } from './credit-tenant-scope';
|
|
|
|
export type CreditOperation = 'verified_payment' | 'reserve' | 'settle' | 'release';
|
|
export interface CreditCommand {
|
|
tenantId: string;
|
|
idempotencyKey: string;
|
|
kind: CreditOperation;
|
|
/** Verified globally unique provider payment reference, or reservation ID. */
|
|
reference: string;
|
|
amount: number;
|
|
}
|
|
export interface CreditBalance {
|
|
available: number;
|
|
reserved: number;
|
|
}
|
|
|
|
/**
|
|
* Internal transaction primitive. verified_payment must only be invoked after
|
|
* an independently verified and matched payment; this class does not verify
|
|
* a payment, authorize a caller, price a job, or implement refunds/chargebacks.
|
|
* No routes expose it. Account row locks serialize all changes per tenant.
|
|
*/
|
|
export class PostgresCreditLedger {
|
|
constructor(private readonly sql: RepositorySql) {}
|
|
|
|
/** Read-only balance for the authenticated tenant. Never creates a row. */
|
|
async balance(tenantId: string): Promise<CreditBalance> {
|
|
if (typeof tenantId !== "string" || !tenantId.trim() || tenantId.length > 256) {
|
|
throw new Error("Invalid credit tenant");
|
|
}
|
|
return withCreditTenant(this.sql, tenantId, async (tx) => {
|
|
const rows = await tx<{ available: string; reserved: string }[]>`
|
|
SELECT available, reserved FROM opt_credit_accounts WHERE tenant_id = ${tenantId}`;
|
|
const row = rows[0];
|
|
return row
|
|
? { available: Number(row.available), reserved: Number(row.reserved) }
|
|
: { available: 0, reserved: 0 };
|
|
});
|
|
}
|
|
|
|
async apply(command: CreditCommand): Promise<{ replay: boolean; balance: CreditBalance }> {
|
|
const { tenantId, idempotencyKey, kind, reference, amount } = command;
|
|
if (
|
|
![tenantId, idempotencyKey, reference].every(
|
|
(value) => typeof value === 'string' && value.trim().length > 0,
|
|
) ||
|
|
!['verified_payment', 'reserve', 'settle', 'release'].includes(kind) ||
|
|
!Number.isSafeInteger(amount) ||
|
|
amount < 0 ||
|
|
((kind === 'verified_payment' || kind === 'reserve') && amount === 0) ||
|
|
(kind === 'release' && amount !== 0)
|
|
)
|
|
throw new Error('Invalid credit command');
|
|
|
|
return withCreditTenant(this.sql, tenantId, async (tx) => {
|
|
await tx`INSERT INTO opt_credit_accounts (tenant_id) VALUES (${tenantId}) ON CONFLICT DO NOTHING`;
|
|
const accounts = await tx<{ available: string; reserved: string }[]>`
|
|
SELECT available, reserved FROM opt_credit_accounts WHERE tenant_id = ${tenantId} FOR UPDATE`;
|
|
const account = accounts[0]!;
|
|
let available = Number(account.available);
|
|
let reserved = Number(account.reserved);
|
|
const previous = await tx<{ kind: string; reference: string; amount: string }[]>`
|
|
SELECT kind, reference, amount FROM opt_credit_events WHERE tenant_id = ${tenantId} AND idempotency_key = ${idempotencyKey}`;
|
|
if (previous[0]) {
|
|
if (
|
|
previous[0].kind !== kind ||
|
|
previous[0].reference !== reference ||
|
|
Number(previous[0].amount) !== amount
|
|
) {
|
|
throw new Error('Idempotency key reused for a different credit command');
|
|
}
|
|
return { replay: true, balance: { available, reserved } };
|
|
}
|
|
|
|
if (kind === 'verified_payment') {
|
|
available += amount;
|
|
} else if (kind === 'reserve') {
|
|
if (available < amount) throw new Error('Insufficient available credits');
|
|
await tx`INSERT INTO opt_credit_reservations (tenant_id, reservation_id, amount, status)
|
|
VALUES (${tenantId}, ${reference}, ${amount}, 'reserved')`;
|
|
available -= amount;
|
|
reserved += amount;
|
|
} else {
|
|
const reservations = await tx<{ amount: string; status: string }[]>`
|
|
SELECT amount, status FROM opt_credit_reservations WHERE tenant_id = ${tenantId} AND reservation_id = ${reference} FOR UPDATE`;
|
|
const reservation = reservations[0];
|
|
if (!reservation || reservation.status !== 'reserved')
|
|
throw new Error('Active credit reservation not found');
|
|
const held = Number(reservation.amount);
|
|
if (kind === 'settle' && amount > held) throw new Error('Settlement exceeds reserved credits');
|
|
const spent = kind === 'settle' ? amount : 0;
|
|
reserved -= held;
|
|
available += held - spent;
|
|
await tx`UPDATE opt_credit_reservations SET status = ${kind === 'settle' ? 'settled' : 'released'},
|
|
settled_amount = ${spent} WHERE tenant_id = ${tenantId} AND reservation_id = ${reference}`;
|
|
}
|
|
if (
|
|
!Number.isSafeInteger(available) ||
|
|
!Number.isSafeInteger(reserved) ||
|
|
available < 0 ||
|
|
reserved < 0
|
|
) {
|
|
throw new Error('Credit balance outside supported range');
|
|
}
|
|
await tx`UPDATE opt_credit_accounts SET available = ${available}, reserved = ${reserved} WHERE tenant_id = ${tenantId}`;
|
|
await tx`INSERT INTO opt_credit_events (tenant_id, idempotency_key, kind, amount, reference)
|
|
VALUES (${tenantId}, ${idempotencyKey}, ${kind}, ${amount}, ${reference})`;
|
|
return { replay: false, balance: { available, reserved } };
|
|
});
|
|
}
|
|
}
|