@happyvertical/smrt-commerce 0.64.0 → 0.66.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +1 -0
- package/agents/settlement-accounts.md +48 -0
- package/dist/chunks/{InvoiceCollection-xooQnUwq.js → InvoiceCollection-CDmFvWvK.js} +9 -9
- package/dist/chunks/{InvoiceCollection-xooQnUwq.js.map → InvoiceCollection-CDmFvWvK.js.map} +1 -1
- package/dist/chunks/{allocation-integrity-C4SZJcao.js → allocation-integrity-CiTZdz1b.js} +6 -6
- package/dist/chunks/{allocation-integrity-C4SZJcao.js.map → allocation-integrity-CiTZdz1b.js.map} +1 -1
- package/dist/chunks/{contract-money-ATacxU6t.js → contract-money-Dgx-9LTN.js} +3 -3
- package/dist/chunks/{contract-money-ATacxU6t.js.map → contract-money-Dgx-9LTN.js.map} +1 -1
- package/dist/chunks/{invoice-posting-CDfxug3Q.js → invoice-posting-CahciFEt.js} +15 -8
- package/dist/chunks/invoice-posting-CahciFEt.js.map +1 -0
- package/dist/chunks/{retention-accounting-BA4wXUQc.js → retention-accounting-B2ZvtbXz.js} +19 -13
- package/dist/chunks/retention-accounting-B2ZvtbXz.js.map +1 -0
- package/dist/chunks/{tenant-money-barrier-BdyXIVT5.js → tenant-money-barrier-eaRtn-vq.js} +10 -12
- package/dist/chunks/tenant-money-barrier-eaRtn-vq.js.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +98 -11
- package/dist/index.js.map +1 -1
- package/dist/invoice-posting.d.ts.map +1 -1
- package/dist/invoices.js +1 -1
- package/dist/manifest.json +1 -1
- package/dist/models/Payment.d.ts.map +1 -1
- package/dist/settlement-accounts.d.ts +57 -0
- package/dist/settlement-accounts.d.ts.map +1 -0
- package/dist/smrt-knowledge.json +11 -5
- package/dist/smrt-knowledge.okf.md +6 -2
- package/dist/tax/identity.d.ts +6 -0
- package/dist/tax/identity.d.ts.map +1 -1
- package/package.json +17 -17
- package/dist/chunks/invoice-posting-CDfxug3Q.js.map +0 -1
- package/dist/chunks/retention-accounting-BA4wXUQc.js.map +0 -1
- package/dist/chunks/tenant-money-barrier-BdyXIVT5.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"invoice-posting.d.ts","sourceRoot":"","sources":["../src/invoice-posting.ts"],"names":[],"mappings":"AAAA,wDAAwD;AAExD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,qCAAqC,CAAC;AAC7E,OAAO,KAAK,EAAE,OAAO,EAAoB,MAAM,6BAA6B,CAAC;AAW7E,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AAInD,OAAO,EACL,KAAK,oBAAoB,EAEzB,KAAK,uBAAuB,EAC7B,MAAM,kBAAkB,CAAC;
|
|
1
|
+
{"version":3,"file":"invoice-posting.d.ts","sourceRoot":"","sources":["../src/invoice-posting.ts"],"names":[],"mappings":"AAAA,wDAAwD;AAExD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,qCAAqC,CAAC;AAC7E,OAAO,KAAK,EAAE,OAAO,EAAoB,MAAM,6BAA6B,CAAC;AAW7E,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AAInD,OAAO,EACL,KAAK,oBAAoB,EAEzB,KAAK,uBAAuB,EAC7B,MAAM,kBAAkB,CAAC;AAiL1B;;;GAGG;AACH,wBAAsB,aAAa,CACjC,EAAE,EAAE,iBAAiB,EACrB,OAAO,EAAE,OAAO,GACf,OAAO,CAAC,OAAO,CAAC,CAQlB;AAED,4EAA4E;AAC5E,wBAAsB,uBAAuB,CAC3C,KAAK,EAAE,OAAO,EACd,OAAO,EAAE,uBAAuB,GAC/B,OAAO,CAAC,OAAO,CAAC,CA6GlB;AA6BD,oEAAoE;AACpE,wBAAsB,gCAAgC,CACpD,KAAK,EAAE,OAAO,EACd,OAAO,EAAE,oBAAoB,GAC5B,OAAO,CAAC,OAAO,CAAC,CA+GlB"}
|
package/dist/invoices.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { S as calculateInvoiceMinorLine, _ as reconcileOrdinaryCreditAccounting, a as reconcileRetainedBaseInvoice, b as syncOrdinaryRefundToAccounting, c as syncRetainedCreditToAccounting, d as toRetainedCreditAccountingInput, f as toRetainedInvoiceAccountingInput, g as reconcileOrdinaryBaseInvoice, h as reconcileOrdinaryAccountingStep, i as reconcileRetainedAccountingStep, l as syncRetainedInvoiceToAccounting, m as readOrdinaryInvoiceAccountingState, n as loadRetainedInvoiceAccountingSnapshot, o as reconcileRetainedCreditAccounting, p as loadOrdinaryCreditAccountingSnapshot, r as readRetainedInvoiceAccountingState, s as releaseRetainedInvoiceToAccounting, t as loadRetainedCreditAccountingSnapshot, u as syncRetainedRefundToAccounting, v as syncOrdinaryCreditToAccounting, x as toOrdinaryCreditAccountingInput, y as syncOrdinaryInvoiceToAccounting } from "./chunks/retention-accounting-
|
|
1
|
+
import { S as calculateInvoiceMinorLine, _ as reconcileOrdinaryCreditAccounting, a as reconcileRetainedBaseInvoice, b as syncOrdinaryRefundToAccounting, c as syncRetainedCreditToAccounting, d as toRetainedCreditAccountingInput, f as toRetainedInvoiceAccountingInput, g as reconcileOrdinaryBaseInvoice, h as reconcileOrdinaryAccountingStep, i as reconcileRetainedAccountingStep, l as syncRetainedInvoiceToAccounting, m as readOrdinaryInvoiceAccountingState, n as loadRetainedInvoiceAccountingSnapshot, o as reconcileRetainedCreditAccounting, p as loadOrdinaryCreditAccountingSnapshot, r as readRetainedInvoiceAccountingState, s as releaseRetainedInvoiceToAccounting, t as loadRetainedCreditAccountingSnapshot, u as syncRetainedRefundToAccounting, v as syncOrdinaryCreditToAccounting, x as toOrdinaryCreditAccountingInput, y as syncOrdinaryInvoiceToAccounting } from "./chunks/retention-accounting-B2ZvtbXz.js";
|
|
2
2
|
import { MoneyValidationError } from "./money.js";
|
|
3
3
|
export { MoneyValidationError, calculateInvoiceMinorLine, loadOrdinaryCreditAccountingSnapshot, loadRetainedCreditAccountingSnapshot, loadRetainedInvoiceAccountingSnapshot, readOrdinaryInvoiceAccountingState, readRetainedInvoiceAccountingState, reconcileOrdinaryAccountingStep, reconcileOrdinaryBaseInvoice, reconcileOrdinaryCreditAccounting, reconcileRetainedAccountingStep, reconcileRetainedBaseInvoice, reconcileRetainedCreditAccounting, releaseRetainedInvoiceToAccounting, syncOrdinaryCreditToAccounting, syncOrdinaryInvoiceToAccounting, syncOrdinaryRefundToAccounting, syncRetainedCreditToAccounting, syncRetainedInvoiceToAccounting, syncRetainedRefundToAccounting, toOrdinaryCreditAccountingInput, toRetainedCreditAccountingInput, toRetainedInvoiceAccountingInput };
|
package/dist/manifest.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Payment.d.ts","sourceRoot":"","sources":["../../src/models/Payment.ts"],"names":[],"mappings":"AAGA;;;GAGG;AAEH,OAAO,EAIL,KAAK,iBAAiB,EACtB,UAAU,EACV,KAAK,eAAe,EAErB,MAAM,0BAA0B,CAAC;AAClC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,6BAA6B,CAAC;AAW3D,OAAO,EACL,KAAK,WAAW,EAChB,aAAa,EACb,KAAK,cAAc,EACnB,aAAa,EACb,KAAK,oBAAoB,EAC1B,MAAM,mBAAmB,CAAC;AAgD3B;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,qBAmDa,OAAQ,SAAQ,UAAU;IACrC,8EAA8E;IAC9E,IAAI,EAAE,WAAW,CAAa;IAE9B,kGAAkG;IAElG,iBAAiB,SAAM;IAEvB,4EAA4E;IAE5E,8BAA8B,SAAM;IAEpC,qEAAqE;IAErE,6BAA6B,SAAM;IAEnC;;;OAGG;IAEH,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAQ;IAE/B;;OAEG;IAGH,UAAU,EAAE,MAAM,GAAG,IAAI,CAAQ;IAEjC;;OAEG;IAGH,UAAU,EA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;IA2ItC;;OAEG;IACG,UAAU,IAAI,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC;IAa3C;;OAEG;IACH,UAAU,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI;IAOjC;;OAEG;IACH,MAAM,IAAI,IAAI;CAMf;AAED,eAAe,OAAO,CAAC"}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type { DatabaseInterface } from '@happyvertical/smrt-core/migrations';
|
|
2
|
+
/** The accounts every settlement chart carries, by stable number. */
|
|
3
|
+
export declare const SETTLEMENT_ACCOUNTS: readonly [{
|
|
4
|
+
readonly key: "cash";
|
|
5
|
+
readonly number: "1000";
|
|
6
|
+
readonly name: "Cash / Undeposited Funds";
|
|
7
|
+
readonly type: "asset";
|
|
8
|
+
readonly description: "Payments received and not yet deposited (clearing).";
|
|
9
|
+
}, {
|
|
10
|
+
readonly key: "receivables";
|
|
11
|
+
readonly number: "1200";
|
|
12
|
+
readonly name: "Accounts Receivable";
|
|
13
|
+
readonly type: "asset";
|
|
14
|
+
readonly description: "Amounts customers owe on issued invoices.";
|
|
15
|
+
}, {
|
|
16
|
+
readonly key: "salesTaxPayable";
|
|
17
|
+
readonly number: "2200";
|
|
18
|
+
readonly name: "Sales Tax Payable";
|
|
19
|
+
readonly type: "liability";
|
|
20
|
+
readonly description: "Sales tax collected and owed to the tax authority.";
|
|
21
|
+
}, {
|
|
22
|
+
readonly key: "revenue";
|
|
23
|
+
readonly number: "4000";
|
|
24
|
+
readonly name: "Sales Revenue";
|
|
25
|
+
readonly type: "revenue";
|
|
26
|
+
readonly description: "Revenue recognised on issued invoices.";
|
|
27
|
+
}];
|
|
28
|
+
export interface EnsureTenantSettlementAccountsOptions {
|
|
29
|
+
/** ISO 4217 currency of the ledger (three letters, any case). */
|
|
30
|
+
readonly currency: string;
|
|
31
|
+
}
|
|
32
|
+
/** Ids of a tenant's settlement ledger and accounts for one currency. */
|
|
33
|
+
export interface TenantSettlementAccounts {
|
|
34
|
+
readonly tenantId: string;
|
|
35
|
+
readonly currency: string;
|
|
36
|
+
readonly ledgerId: string;
|
|
37
|
+
readonly cashAccountId: string;
|
|
38
|
+
readonly receivablesAccountId: string;
|
|
39
|
+
readonly salesTaxPayableAccountId: string;
|
|
40
|
+
readonly revenueAccountId: string;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Seed (or load) the tenant's settlement ledger and chart for one currency.
|
|
44
|
+
*
|
|
45
|
+
* Idempotent and race safe: identities are deterministic, creation serializes
|
|
46
|
+
* on a tenant advisory lock (PostgreSQL) or the embedded write queue, and an
|
|
47
|
+
* existing row is never changed. A row found under a seed identity whose
|
|
48
|
+
* tenant, currency, ledger, number or type differs is refused, never adopted.
|
|
49
|
+
* The returned ids feed `Payment.recordPayment` directly
|
|
50
|
+
* (`ledgerId`, `receivablesAccountId`, `cashAccountId`).
|
|
51
|
+
*
|
|
52
|
+
* Call it outside a model transaction, as `ensureCommerceTenant`: it opens its
|
|
53
|
+
* own. Requires smrt-ledgers and a database with transactions. The caller owns
|
|
54
|
+
* authority for `tenantId`; this function never derives it.
|
|
55
|
+
*/
|
|
56
|
+
export declare function ensureTenantSettlementAccounts(db: DatabaseInterface, tenantId: string, options: EnsureTenantSettlementAccountsOptions): Promise<TenantSettlementAccounts>;
|
|
57
|
+
//# sourceMappingURL=settlement-accounts.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"settlement-accounts.d.ts","sourceRoot":"","sources":["../src/settlement-accounts.ts"],"names":[],"mappings":"AAgBA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,qCAAqC,CAAC;AAI7E,qEAAqE;AACrE,eAAO,MAAM,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;;EA6BtB,CAAC;AAIX,MAAM,WAAW,qCAAqC;IACpD,iEAAiE;IACjE,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;CAC3B;AAED,yEAAyE;AACzE,MAAM,WAAW,wBAAwB;IACvC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,oBAAoB,EAAE,MAAM,CAAC;IACtC,QAAQ,CAAC,wBAAwB,EAAE,MAAM,CAAC;IAC1C,QAAQ,CAAC,gBAAgB,EAAE,MAAM,CAAC;CACnC;AAcD;;;;;;;;;;;;;GAaG;AACH,wBAAsB,8BAA8B,CAClD,EAAE,EAAE,iBAAiB,EACrB,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,qCAAqC,GAC7C,OAAO,CAAC,wBAAwB,CAAC,CAqGnC"}
|
package/dist/smrt-knowledge.json
CHANGED
|
@@ -3,13 +3,13 @@
|
|
|
3
3
|
"sensitiveFieldsExcluded": true,
|
|
4
4
|
"generatedAt": "1970-01-01T00:00:00.000Z",
|
|
5
5
|
"packageName": "@happyvertical/smrt-commerce",
|
|
6
|
-
"packageVersion": "0.
|
|
6
|
+
"packageVersion": "0.66.0",
|
|
7
7
|
"sourceManifestPath": "dist/manifest.json",
|
|
8
8
|
"agentDocPath": "AGENTS.md",
|
|
9
9
|
"sourceHashes": {
|
|
10
|
-
"manifest": "
|
|
11
|
-
"packageJson": "
|
|
12
|
-
"agents": "
|
|
10
|
+
"manifest": "0880d63c907e367e6e33743b4d49988ae60e43f2635ac235301052347d29d1c3",
|
|
11
|
+
"packageJson": "605ac4a5a84172c21c638dcab7133e5f536891a2b275aa6138d77aaf1e3a52b5",
|
|
12
|
+
"agents": "4891a1eb6aa2be45b8374d9bacdcda357bab45e184d9d756596985381f6de442",
|
|
13
13
|
"moduleDoc:agents/customer-vendor-ui.md": "ee8cbe9b6c4334cb9d53c87258d20a6ec8abd042011135be75cb03d2198796cc",
|
|
14
14
|
"moduleDoc:README.md": "06668f73dad1198089b4eef19a9a6ab8421825615c581cf66c593da32754f359",
|
|
15
15
|
"moduleDoc:agents/invoice-quantity.md": "3a5fbb464c8fe63acc021b2259ba36f052bb22c49b29e503639c5316814e2028",
|
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
"moduleDoc:agents/accounting-payment-sync.md": "ed7e1671be6da8ecf3972a52ab8d9bff778f828c5a996514d098833d5015a413",
|
|
21
21
|
"moduleDoc:agents/historical-sales.md": "d7e68bb3a93495c91449b7406a5eefdcddb54fafea83d14d5ba8e2c8d6168de4",
|
|
22
22
|
"moduleDoc:agents/payment-allocations.md": "679894f603f62522515bce338741bafda3f10d16ef0b817b105dc2e732471fdb",
|
|
23
|
+
"moduleDoc:agents/settlement-accounts.md": "a3ecc28f41d019f842d80ea752c503ebbe12418b809f2f85f9ff7f76ac48d976",
|
|
23
24
|
"moduleDoc:agents/tax-codes.md": "6b07282f0ac93db4fd42ddb4a9551d880e24ec2bd2fae9d06c06561313b3cb9f",
|
|
24
25
|
"moduleDoc:agents/document-money.md": "7f198737c66d190dbdc9cc9a3dbef460fb7c9fb8ee47dd0eaaadde2f2ba91d47",
|
|
25
26
|
"moduleDoc:agents/money-upgrade.md": "8e9664e5c0c572654ac0cb4b6d7516415936bbba63d050fa11010b11c2d7e63a",
|
|
@@ -23629,7 +23630,7 @@
|
|
|
23629
23630
|
"polymorphicAssociations": 0,
|
|
23630
23631
|
"uuidColumns": 292
|
|
23631
23632
|
},
|
|
23632
|
-
"agentDoc": "# @happyvertical/smrt-commerce\n\nE-commerce with Contract STI hierarchy, invoice lifecycle, payment tracking, payout remittance, and optional ledger integration.\n\n## Models\n\n- **Customer** / **Vendor**: linked to Profile via string ID (not FK). `contacts` (JSON) is written via [`savePartyContacts()`](agents/customer-vendor-ui.md#contact-rows-3501). Customer has creditLimit, paymentTerms, customerType (DTC / WHOLESALE / RETAIL). Vendor has leadTimeDays, minimumOrder, and `payoutAddresses: Record<string, string>` — a flat map from payout-rail-qualified currency code (`USDC-base`, `BTC`, `USD-stripe`, ...) to destination string (EVM address, BTC address, Stripe Connect account id, IBAN). Use `getPayoutAddress(currency)` for a `Map.get`-style lookup; missing entries return `undefined` (caller decides skip-vs-error).\n- **Contract**: concrete STI base. Abstract **SalesContract** owns `customerId`; **PurchaseContract** owns `vendorId`. `channelId` is open-ended. Before upgrade, run `preflightCommercePartyLinks(db)` and repair linked base rows, stray parties, and wrong-branch links. See [README](README.md).\n- **WholesaleOrder**: B2B order. Conventional pairing — customer has `customerType: 'wholesale'`, NET-30/60 terms, delivered via wholesale-portal channel.\n- **ProductionOrder**: manufacturing equivalent of a PurchaseOrder — commission your factory to make finished goods. Consumes raw materials per BOM (`@happyvertical/smrt-manufacturing`) and produces SKU stock (`@happyvertical/smrt-inventory`).\n- **Cart**: transient order-in-progress. Same shape as Order; the application promotes the row from `_meta_type: Cart` to `_meta_type: Order` at checkout instead of copying data between tables.\n- **LicenseSale**: industry-neutral licensing primitive. Carries an *immutable* rights snapshot (`rightsMedium`, `rightsDistributionScope`, `rightsExclusivity`, `rightsDuration`, `rightsTerritory`, `rightsSublicensing`, `rightsDerivatives` — typed `Meta<T>` fields), licensee identity (`licenseeEmail`, optional `licenseeLegalEntity` / `licenseeJurisdiction`), and a signed-PDF reference (`pdfUrl`, `pdfHash`, optional `onChainHashRegistryRef`). Once saved at `ContractStatus.ACCEPTED`, the rights snapshot is frozen — mutating any of the seven rights fields and re-saving throws. The only legal transition out of ACCEPTED is `revoke()` (moves to CANCELLED without touching rights). Useful for stock media, music licensing, code-asset marketplaces, license keys, anywhere rights are sold for a fee.\n- **ContractLineItem**: items on contracts.\n- **Invoice**: status machine `DRAFT → SENT → VIEWED → PARTIAL → PAID` (also OVERDUE, CANCELLED, WRITTEN_OFF). `recognizeRevenue()` creates balanced AR journal entry (DR: Accounts Receivable, CR: Revenue, CR: Tax Payable).\n- **InvoiceLineItem**: fractional-quantity line items with safe minor-unit validation/recalculation on save; the existing-column migration is documented in [invoice quantity persistence](agents/invoice-quantity.md).\n- **Payment** / **PaymentAllocation**: tracks payments against invoices (status: see Gotchas). Carries optional backend-adapter fields for PaymentBackend-routed flows: `backendId` (rail adapter id — `base-usdc`, `btc`, `stripe`, distinct from `externalProvider` which names an accounting sync destination), `backendTxRef` (chain tx hash or gateway settlement id), `nativeAmount` / `nativeCurrency` (what actually arrived), `usdAtQuote` / `usdAtConfirmation` (drift accounting for volatile-currency rails). `Payment.usdDrift()` returns the confirmation - quote delta, or `0` when either side is unset.\n- **PaymentInstrument**: reusable saved payment method (\"card on file\"). Stores only provider references and non-sensitive display metadata (`providerCustomerId`, `providerPaymentMethodId`, brand / last4 / expiry), never raw card data. `isDefault` is domain-managed, not API-writable: `PaymentInstrumentCollection.setDefaultForCustomer(customerId, instrumentId)` validates the target and clears the customer's other defaults (one per customer).\n- **PaymentIntent**: short-lived pre-payment commitment with multi-option semantics. Locks a USD price for a fixed window (default 15 minutes) and lists one or more `PaymentOption`s describing different rails (`backendId`, `currency`, `payTo`, `nativeAmount`, optional `chain` / `memo` / `x402Capable` / `expiresAt`). First option to receive payment wins; the others are implicitly retired. State machine `awaiting_payment → paid → (issued | retired)` plus `expired` and `cancelled`. Mutate via dedicated `markPaid` / `markIssued` / `expire` / `cancel` / `retire` helpers — direct status assignment bypasses the invariant checks. Idempotency: see the natural-key Gotcha.\n- **TenantPaymentAccount**: tenant-owned Stripe Connect account; direct charges with an application fee, account→tenant webhook routing, refunds, no platform fallback. Write only through `connected-payments.ts`; see [connected payments](agents/connected-payments.md).\n- **Payout**: operator-to-supplier remittance. Distinct from Payment because direction, status machine, and chain semantics differ. Status machine `pending → sent → confirmed → failed` (failed is terminal but resettable via `resetFromFailed()` after fixing the underlying problem). References source `paymentId` (plain string) and destination `vendorId` (foreign key). Amount invariant `supplierNet === grossAmount - operatorFee` enforced exactly on save (integer minor units, no tolerance — #2401). `PayoutCollection.createFromPayment()` is the typical entry point; it pulls native amount / currency from the source Payment.\n- **Fulfillment** / **FulfillmentLineItem**: shipment/delivery tracking.\n\n## Recipes (#3590)\n\n`src/recipes.ts` declares four minimal `SmrtRecipe`s, emitted into the built\n`manifest.json` and `smrt-knowledge.json` `recipes`: `commerce.customers`\n(Customer), `commerce.vendors` (Vendor), `commerce.sales` (Order, requires\ncustomers), `commerce.purchases` (PurchaseOrder, requires vendors). Headers\nonly; line items, fulfilment, invoices, and payments are later recipes. Each\nhas user-facing help in `src/<name>.recipe.md` (#3591), and the fields those\nrecipes show carry `@field({ description })` text; keep both in plain\nlanguage for end users and update them when a recipe's fields change. See\n[core recipes](../core/agents/recipes.md).\n\nQuickBooks for tenants (#5136-#5139): [connection](agents/accounting-connection.md), [mappings](agents/accounting-mapping.md), [live gate](agents/accounting-live-gate.md), [payment sync](agents/accounting-payment-sync.md).\nSee [historical issued sales](agents/historical-sales.md) for exact original source\nmoney, immutable source children and combined historical/live customer funds.\nSee [payment allocation integrity](agents/payment-allocations.md) for atomic splits,\nretry identity, parent corrections and supported dialects.\nSee [tax codes](agents/tax-codes.md) for tenant-owned rate components, default codes,\nand the standard codes every tenant gets.\nSee [document money persistence](agents/document-money.md) for the one money\nmodel: tax-code resolution, atomic aggregate writes, issued snapshots, and\nfrozen fields. Every Invoice and Contract money write needs a tenant. Host\nbootstrap is `ensureCommerceTenant(db, tenantId, { cookbook })`, which returns\n`{ tenantId }`. Money data written by an earlier version is refused with\n`COMMERCE_DATA_NEEDS_UPGRADE` until `smrt db:upgrade-commerce-money` converts\nit; see [money data upgrade](agents/money-upgrade.md).\nSee [Contract money persistence](agents/contract-money.md) for the Contract\naggregate and purchase recoverability.\n\n## Ledger Integration\n\n`@happyvertical/smrt-ledgers` is a regular dependency, loaded lazily via dynamic `import()` (never a static import) so the package graph stays a DAG (#1582). Invoice stores `arJournalId` and `revenueJournalId` as string references. `recognizeRevenue()` creates a balanced AR journal entry; `getArJournal()` returns null when no journal has been recognized yet.\n\n## Billing-period close (#3060)\n\n`src/billing/` closes periods from smrt-subscriptions charges; see the README\nfor usage.\n\n- **Port, not provider.** Period close, events, and credit checkout call only\n the `BillingProvider` port (integer minor units). `stripe.ts` adapts\n `@happyvertical/accounting`, which takes currency *major* units; convert with\n `units.ts` and never hand-roll a Stripe call here. `units.ts` exponents are\n an explicit ISO 4217 table matching the SDK's, never `Intl` display digits\n (CLDR differs for IQD, MGA, … and drifts by ICU release). The SDK's\n `*Minor` fields are already ISO minor units. Capabilities a rail may lack\n (`chargeSavedPaymentMethod`, `createSetupCheckout`, `getCheckout`,\n `setDefaultPaymentMethod`, `markInvoiceUncollectible`) are optional port\n methods: detect them by presence, and keep additions optional (#3139).\n `sendAndReconcile` refuses a provider invoice whose subtotal or total\n disagrees with the local invoice.\n- **Replay safety is identity.** Close, invoice, line, payment, allocation,\n and claim ids are `deterministicId()`s; `BillingLineSource` (conflict key\n `source_type, source_id`) is the only double-billing guard, so never bill a\n source without claiming it, and never widen that key. Each close step is\n persisted before the next; `acquireCloseLease()` serializes workers. A\n close that nets to a credit keeps its claims and ends `carried_forward`;\n its subtotal is a `credit_carry_forward` source for the payer's next billed\n close, which marks the carried close `completed`.\n- **Cycles and flat-plan coverage (#3116).** `cycles.ts` is the schedule\n (pure; `BillingAccount.billingAnchorAt`, null = calendar months). A close\n with no period closes each payer's `lastEndedBillingPeriod()`. Flat-plan\n claims are the exception to \"id from the source\": their `sourceId` is\n `<subscriptionId>:seq:<chainSequence>` and their `periodStart/End` is the\n exact time they bill. `claimFlatWindow()` reads the last number, then the\n coverage (claims ending after the window start), claims one gap as number\n n + 1, and retries on conflict; reading in that order is what makes it\n safe. That numbering, not the period, stops overlaps when schedules or\n payers change — never claim a flat plan outside it, and keep both reads\n bounded (no whole-history scans). Each numbered claim is its own invoice\n line keyed `lineKey|periodStart` (a function of the claim alone, so a\n resumed close rebuilds the same line ids). Proration is\n `prorateMinorUnits()` (half up, BigInt) against the period's full cycle.\n- **System tables.** `BillingAccount`, `BillingPeriodClose`, and\n `BillingLineSource` are not tenant-scoped and have no generated surface.\n Collections stay unexported; models are root exports (#3082). Invoices,\n payments, and journals are written in the seller's tenant; payer-owned\n subscriptions and credit grants in a system context, only after\n verification.\n- **Events** use smrt-jobs' delivery inbox under provider\n `<name>-billing:<sellerTenantId>` and a provider-filtered\n `ForgeProjectionRuntime`, so a runtime never claims another seller's\n events; any other runtime sharing the inbox must pass `providers` too. Only\n events this package acts on are stored: foreign checkouts are `ignored`,\n and only `smrt_*` checkout metadata is kept; it is\n HMAC-signed with the webhook secret at creation (empty values are omitted:\n Stripe drops them), so another integration on the same account cannot forge\n a credit purchase or a card setup; credit is granted only when the\n collected total equals it plus provider tax. Checkout amounts come from the\n re-read session (`getCheckout()`), never the Stripe event, whose amounts are\n in Stripe's unit. Rotating the webhook secret strands in-flight checkouts\n (up to 24 h). `observe()` re-reads provider state, so ordering never depends\n on delivery order; the only provider writes in `observe()` are idempotent\n (making a saved card the default). The standing hook runs inside the event\n transaction and must be idempotent.\n- **Card on file and top-ups (#3139).** A saved card is the payer customer's\n default `PaymentInstrument` (seller tenant, id from the provider method).\n `autoChargeInvoices` bills such payers `charge_automatically`, decided once\n and saved as `Invoice.collectionMethod` before the first push, which every\n retry reuses (never recompute it: a lost push response would record a\n method the provider was not asked for, #3190); activation follows `paid`, never send. An auto top-up attempt\n is a `PENDING` `Payment` (`reference` `auto-top-up:<policyId>`, id from the\n policy and `count()` of its attempts) inserted before the charge, so racing\n evaluations derive one id and one charge; the charge key is derived from\n that id. `applyAutoTopUpOutcome()` must run in a transaction and starts with\n a conditional `UPDATE … WHERE status = 'pending'` row lock, so the hook and\n the `payment` webhook settle once; the grant is keyed by the charge key.\n Never settle an attempt outside that function. Taxed accounts are charged\n with provider tax by default (#3194): the attempt row holds the credit\n (the charge subtotal), the tax is journaled to tax payable at settlement,\n and the attempt's tax decision is recorded in its `notes` so a re-drive\n repeats the same charge request (the provider refuses a key reused with\n different tax). `claimAttempt()` is the only place that decides a\n skip and reports it (`onAutoTopUpSkipped`); `cardOnFile()` and period close\n use `defaultCardInstrument()` — never copy that predicate. A provider write-off moves the local invoice to\n `WRITTEN_OFF` (a later payment, by card or on a rail (#3188), is recorded\n and reinstates the payer; the status stays, so \"paid in full\" for a\n written-off invoice is read from its allocations).\n- **Billing invoices are money-model invoices.** The provider taxes them\n (`providerTaxAmount`, server-managed, not API-writable, added to line tax),\n so every billing line is an explicit `taxMode: 'override'` to the seller's\n `out-of-scope` code. Charges are written before credits so the running\n subtotal never goes negative, and provider tax is written in the save that\n issues the invoice. Revenue posting is idempotent. `ledger.bookCurrency` is\n required (ISO 4217, validated by `BillingRuntime`) and must equal the\n billing currency. `toAccountingInput({ mapping })` emits major units.\n- **Payment rails (#3138).** A runtime has one issuing `provider` and any\n number of `paymentProviders` (unique names, one inbox namespace each; a\n provider with `capabilities.issuesInvoices === false` can never issue).\n `observe()` resolves the provider from the delivery namespace, never the\n payload. Crypto rails implement the port over `@happyvertical/payments`'\n `CryptoCheckoutGateway`; never call BTCPay (or any gateway) from here.\n Settlement is decided by the pure `decideAttempt()` from gateway state and\n `paymentPolicy` — the gateway's `settled` is authoritative and nothing here\n counts confirmations. A `BillingPaymentAttempt` (`(provider, checkout_id)`\n deterministic id) records every state and settles once; grants and payments\n are keyed by checkout id. Invoice payments close the issuer's invoice out of\n band in `observe()` (idempotent) before `project()` records the payment, and\n `settlePaidInvoice` skips (records nothing for) a `paidOutOfBand` invoice\n the rail latched with `outOfBandRequestedAt`; other out-of-band closes are\n recorded as `OTHER` payments. Rails never save cards or charge tax: a taxed\n credit purchase on a rail needs an explicit `automaticTax: false`. Exceptions are flags for operators;\n nothing reverses or refunds automatically.\n- **Known limits**: write-offs post no bad-debt journal (AR stays until paid\n or journaled by an operator); discounts still reach Stripe as negative lines (the SDK's\n line `discount` would change the lines a replayed push reconciles, so it\n needs its own migration); `RetailCharge` has no adjustment ledger. Flat\n plans are monthly, in arrears; plan changes are not prorated (#3119).\n\n## Cross-Package References\n\n- `customerId` → `@foreignKey('Customer')` (hard reference within package)\n- `vendorId` → `@foreignKey('Vendor')` on PurchaseContract only\n- `profileId` → plain string to smrt-profiles\n- `arJournalId`, `revenueJournalId` → plain string to smrt-ledgers\n- `skuId` (on `PaymentIntent`, `LicenseSale`) → plain string to smrt-products\n- `paymentId` (on `PaymentIntent`, `Payout`, `LicenseSale`) → plain string to `Payment` (same package, but kept as plain string for cross-model consistency)\n- `vendorId` on `Payout` → `@foreignKey(Vendor)` (hard reference within package)\n- Billing records reference tenants with `@crossPackageRef('@happyvertical/smrt-users:Tenant')` and charges, plan periods, and adjustments by plain `sourceId`\n\n## Gotchas\n\n- **Optional tenancy**: all models `@TenantScoped({ mode: 'optional' })` + nullable tenantId\n- **Money units and arithmetic**: money fields use signed integer minor units; rates and quantities remain decimal where their contracts require them. Exact rounding, tax-code resolution, safe-integer validation, and journal units are defined in the [commercial money model](agents/money-model.md) and [money calculator](agents/money-calculator.md). Do not reintroduce floating-point tolerances on money paths.\n- **Money documents need a tenant**: models are optionally tenant-scoped, but every Invoice and Contract money write requires one (`MoneyValidationError` `INVALID_MONEY_INPUT`, `Commerce money documents require a tenant`).\n- **Earlier-version money data is refused**: never add a read or conversion path for it. Detection and the one-shot upgrade are in [money data upgrade](agents/money-upgrade.md).\n- **Book currency is required**: `recognizeRevenue()` and `cancelWithRevenueReversal()` take a required `bookCurrency`, which must equal the invoice currency.\n- **Asset-native amounts stay outside line rescales**: `Payment.nativeAmount` and `PaymentIntent.paymentOptions[].nativeAmount` are per-asset values identified by `nativeCurrency`; normalize each asset to its own minor unit before any type conversion, and never apply the commerce ×100 line-money rescale to them.\n- **Invoice controls payment status**: not the Payment model — use `Invoice.updatePaymentStatus()`\n- **Tax comes from tax codes**: the server resolves each line's code and computes line tax and header totals; client totals and a line's stored `taxRate` are never inputs\n- **Profile linking**: separate `ProfileCollection.create()` needed to fetch actual Profile object\n- **PaymentIntent natural key**: `conflictColumns: ['tenant_id', 'offering_ref', 'licensee_email', 'idempotency_key']` — a retried `create` with the same tuple upserts the existing row. Use `PaymentIntentCollection.getOrCreateByIdempotencyKey()` to branch on `{ intent, created }`. Empty natural-key inputs (e.g. blank `idempotencyKey`) disable dedup by design.\n- **Payout state-machine guards**: `markSent` requires a non-empty `backendTxRef`; `markConfirmed` only valid from `SENT`; `markFailed` only valid from `PENDING` / `SENT` (a confirmed payout can't fail — that path is a refund). `resetFromFailed()` is the dedicated escape hatch from `FAILED` back to `PENDING` after an operator fixes the underlying problem; it clears `backendTxRef` so the next attempt picks up a fresh one.\n- **LicenseSale immutability**: rights snapshot freezes on save-with-status-ACCEPTED. The captured snapshot lives in a module-scoped `WeakMap<LicenseSale, string>` so it doesn't interact with the schema or round-trip through `_meta_data`. Drafts (status != ACCEPTED) remain mutable. To \"change\" an issued license: `revoke()` it, then issue a new `LicenseSale` row.\n- **Vendor.payoutAddresses normalization**: the constructor accepts either a `Record<string, string>` or a pre-serialized JSON string. `initialize()` re-normalizes after the framework's option-override pass; `save()` re-normalizes defensively against direct field assignment. Non-string values inside the input map are silently dropped to preserve the typed invariant downstream.\n\n## Commercial UI\n\n`CustomerSelect`/`VendorSelect` are the registered selectors for Customer and\nVendor (`selects` in `src/ui.ts`); models carry `ui.widget` / `ui.format` hints. See\n[customer/vendor UI](agents/customer-vendor-ui.md#selectors-3602).\n\nSee [commercial UI composition](agents/commercial-ui.md) for native form recovery, amount compatibility and backend ownership. Package-owned guides under `agents/` ship with the package.\n\n## Quote and estimate UI\n\n`src/svelte/quote-types.ts` separates unparsed draft strings from explicit\nminor-unit revision DTOs. Native row submitters, caller-owned retry identity and\nextension conventions are documented in [agents/quote-ui.md](agents/quote-ui.md).\n\n## Purchasing UI\n\n`PurchaseOrderEditor` preserves allocation IDs and explicit zeroes, including\nretained reduction rows; the server validates review fingerprints before recording.\nSee [agents/purchasing-ui.md](agents/purchasing-ui.md) for caller responsibilities.\n\n## Exact cost billing\n\nPure signed cost billing and explicit tax rounding are available through the\nindependent `cost-billing` subpath; see [contract](agents/cost-billing.md).\n\nSee [contract billing schedules](agents/contract-billing-schedules.md) for exact\napproved milestone capacity, immutable amendments and atomic canonical invoice issue.\n\nSee [estimate conversion](agents/estimate-conversion.md) for turning an accepted\nEstimate into an idempotent Order with copied lines and lineage.\n\n## Customer funds (#4079)\n\nSee [customer advances](agents/customer-funds.md) for explicitly configured\nunapplied-AR/deposit-liability receipts, conserved application/refund capacity,\nreal liability reclassification, final-invoice attestation and mutation guards.\nUse the public commands; `Payment.customerFundsJson` is command-owned.\n\nSee [observed purchase prices](agents/observed-purchase-prices.md) for incomplete\noriginal supplier prices, explicit unknown totals and reviewed completion.\nSee [received sales agreement money](agents/received-sales-contract-money.md) for\nexact complete source Order/Agreement evidence without synthetic lines or tax recognition.\n\nSee [ordinary invoice accounting adjustments](agents/ordinary-accounting.md) for\nnon-retained provider credit applications, recorded refunds and durable recovery.\n\n## Protected billable sources (#4746)\n\n`invoice-source-binding.ts` is the generic pointer/guard contract for an owning\npackage's existing capacity reservation. It creates no capacity ledger. Trusted\npackages register qualified `billable:` source handlers; missing handlers and\nunbound protected lines fail closed at issue. `InvoiceLineItem.sourceReservationId`\nis command-owned; line save/delete, collection deletion, invoice cascade deletion\nand issue validate persisted identities. Release/unbind must share the owning\nreservation transaction. See [source binding](agents/invoice-source-binding.md).\n",
|
|
23633
|
+
"agentDoc": "# @happyvertical/smrt-commerce\n\nE-commerce with Contract STI hierarchy, invoice lifecycle, payment tracking, payout remittance, and optional ledger integration.\n\n## Models\n\n- **Customer** / **Vendor**: linked to Profile via string ID (not FK). `contacts` (JSON) is written via [`savePartyContacts()`](agents/customer-vendor-ui.md#contact-rows-3501). Customer has creditLimit, paymentTerms, customerType (DTC / WHOLESALE / RETAIL). Vendor has leadTimeDays, minimumOrder, and `payoutAddresses: Record<string, string>` — a flat map from payout-rail-qualified currency code (`USDC-base`, `BTC`, `USD-stripe`, ...) to destination string (EVM address, BTC address, Stripe Connect account id, IBAN). Use `getPayoutAddress(currency)` for a `Map.get`-style lookup; missing entries return `undefined` (caller decides skip-vs-error).\n- **Contract**: concrete STI base. Abstract **SalesContract** owns `customerId`; **PurchaseContract** owns `vendorId`. `channelId` is open-ended. Before upgrade, run `preflightCommercePartyLinks(db)` and repair linked base rows, stray parties, and wrong-branch links. See [README](README.md).\n- **WholesaleOrder**: B2B order. Conventional pairing — customer has `customerType: 'wholesale'`, NET-30/60 terms, delivered via wholesale-portal channel.\n- **ProductionOrder**: manufacturing equivalent of a PurchaseOrder — commission your factory to make finished goods. Consumes raw materials per BOM (`@happyvertical/smrt-manufacturing`) and produces SKU stock (`@happyvertical/smrt-inventory`).\n- **Cart**: transient order-in-progress. Same shape as Order; the application promotes the row from `_meta_type: Cart` to `_meta_type: Order` at checkout instead of copying data between tables.\n- **LicenseSale**: industry-neutral licensing primitive. Carries an *immutable* rights snapshot (`rightsMedium`, `rightsDistributionScope`, `rightsExclusivity`, `rightsDuration`, `rightsTerritory`, `rightsSublicensing`, `rightsDerivatives` — typed `Meta<T>` fields), licensee identity (`licenseeEmail`, optional `licenseeLegalEntity` / `licenseeJurisdiction`), and a signed-PDF reference (`pdfUrl`, `pdfHash`, optional `onChainHashRegistryRef`). Once saved at `ContractStatus.ACCEPTED`, the rights snapshot is frozen — mutating any of the seven rights fields and re-saving throws. The only legal transition out of ACCEPTED is `revoke()` (moves to CANCELLED without touching rights). Useful for stock media, music licensing, code-asset marketplaces, license keys, anywhere rights are sold for a fee.\n- **ContractLineItem**: items on contracts.\n- **Invoice**: status machine `DRAFT → SENT → VIEWED → PARTIAL → PAID` (also OVERDUE, CANCELLED, WRITTEN_OFF). `recognizeRevenue()` creates balanced AR journal entry (DR: Accounts Receivable, CR: Revenue, CR: Tax Payable).\n- **InvoiceLineItem**: fractional-quantity line items with safe minor-unit validation/recalculation on save; the existing-column migration is documented in [invoice quantity persistence](agents/invoice-quantity.md).\n- **Payment** / **PaymentAllocation**: tracks payments against invoices (status: see Gotchas). Carries optional backend-adapter fields for PaymentBackend-routed flows: `backendId` (rail adapter id — `base-usdc`, `btc`, `stripe`, distinct from `externalProvider` which names an accounting sync destination), `backendTxRef` (chain tx hash or gateway settlement id), `nativeAmount` / `nativeCurrency` (what actually arrived), `usdAtQuote` / `usdAtConfirmation` (drift accounting for volatile-currency rails). `Payment.usdDrift()` returns the confirmation - quote delta, or `0` when either side is unset.\n- **PaymentInstrument**: reusable saved payment method (\"card on file\"). Stores only provider references and non-sensitive display metadata (`providerCustomerId`, `providerPaymentMethodId`, brand / last4 / expiry), never raw card data. `isDefault` is domain-managed, not API-writable: `PaymentInstrumentCollection.setDefaultForCustomer(customerId, instrumentId)` validates the target and clears the customer's other defaults (one per customer).\n- **PaymentIntent**: short-lived pre-payment commitment with multi-option semantics. Locks a USD price for a fixed window (default 15 minutes) and lists one or more `PaymentOption`s describing different rails (`backendId`, `currency`, `payTo`, `nativeAmount`, optional `chain` / `memo` / `x402Capable` / `expiresAt`). First option to receive payment wins; the others are implicitly retired. State machine `awaiting_payment → paid → (issued | retired)` plus `expired` and `cancelled`. Mutate via dedicated `markPaid` / `markIssued` / `expire` / `cancel` / `retire` helpers — direct status assignment bypasses the invariant checks. Idempotency: see the natural-key Gotcha.\n- **TenantPaymentAccount**: tenant-owned Stripe Connect account; direct charges with an application fee, account→tenant webhook routing, refunds, no platform fallback. Write only through `connected-payments.ts`; see [connected payments](agents/connected-payments.md).\n- **Payout**: operator-to-supplier remittance. Distinct from Payment because direction, status machine, and chain semantics differ. Status machine `pending → sent → confirmed → failed` (failed is terminal but resettable via `resetFromFailed()` after fixing the underlying problem). References source `paymentId` (plain string) and destination `vendorId` (foreign key). Amount invariant `supplierNet === grossAmount - operatorFee` enforced exactly on save (integer minor units, no tolerance — #2401). `PayoutCollection.createFromPayment()` is the typical entry point; it pulls native amount / currency from the source Payment.\n- **Fulfillment** / **FulfillmentLineItem**: shipment/delivery tracking.\n\n## Recipes (#3590)\n\n`src/recipes.ts` declares four minimal `SmrtRecipe`s, emitted into the built\n`manifest.json` and `smrt-knowledge.json` `recipes`: `commerce.customers`\n(Customer), `commerce.vendors` (Vendor), `commerce.sales` (Order, requires\ncustomers), `commerce.purchases` (PurchaseOrder, requires vendors). Headers\nonly; line items, fulfilment, invoices, and payments are later recipes. Each\nhas user-facing help in `src/<name>.recipe.md` (#3591), and the fields those\nrecipes show carry `@field({ description })` text; keep both in plain\nlanguage for end users and update them when a recipe's fields change. See\n[core recipes](../core/agents/recipes.md).\n\nQuickBooks for tenants (#5136-#5139): [connection](agents/accounting-connection.md), [mappings](agents/accounting-mapping.md), [live gate](agents/accounting-live-gate.md), [payment sync](agents/accounting-payment-sync.md).\nSee [historical issued sales](agents/historical-sales.md) for exact original source\nmoney, immutable source children and combined historical/live customer funds.\nSee [payment allocation integrity](agents/payment-allocations.md) for atomic splits,\nretry identity, parent corrections and supported dialects.\nSee [settlement accounts](agents/settlement-accounts.md) for the default per-tenant ledger and chart that lets `recordPayment` settle payments.\nSee [tax codes](agents/tax-codes.md) for tenant-owned rate components, default codes,\nand the standard codes every tenant gets.\nSee [document money persistence](agents/document-money.md) for the one money\nmodel: tax-code resolution, atomic aggregate writes, issued snapshots, and\nfrozen fields. Every Invoice and Contract money write needs a tenant. Host\nbootstrap is `ensureCommerceTenant(db, tenantId, { cookbook })`, which returns\n`{ tenantId }`. Money data written by an earlier version is refused with\n`COMMERCE_DATA_NEEDS_UPGRADE` until `smrt db:upgrade-commerce-money` converts\nit; see [money data upgrade](agents/money-upgrade.md).\nSee [Contract money persistence](agents/contract-money.md) for the Contract\naggregate and purchase recoverability.\n\n## Ledger Integration\n\n`@happyvertical/smrt-ledgers` is a regular dependency, loaded lazily via dynamic `import()` (never a static import) so the package graph stays a DAG (#1582). Invoice stores `arJournalId` and `revenueJournalId` as string references. `recognizeRevenue()` creates a balanced AR journal entry; `getArJournal()` returns null when no journal has been recognized yet.\n\n## Billing-period close (#3060)\n\n`src/billing/` closes periods from smrt-subscriptions charges; see the README\nfor usage.\n\n- **Port, not provider.** Period close, events, and credit checkout call only\n the `BillingProvider` port (integer minor units). `stripe.ts` adapts\n `@happyvertical/accounting`, which takes currency *major* units; convert with\n `units.ts` and never hand-roll a Stripe call here. `units.ts` exponents are\n an explicit ISO 4217 table matching the SDK's, never `Intl` display digits\n (CLDR differs for IQD, MGA, … and drifts by ICU release). The SDK's\n `*Minor` fields are already ISO minor units. Capabilities a rail may lack\n (`chargeSavedPaymentMethod`, `createSetupCheckout`, `getCheckout`,\n `setDefaultPaymentMethod`, `markInvoiceUncollectible`) are optional port\n methods: detect them by presence, and keep additions optional (#3139).\n `sendAndReconcile` refuses a provider invoice whose subtotal or total\n disagrees with the local invoice.\n- **Replay safety is identity.** Close, invoice, line, payment, allocation,\n and claim ids are `deterministicId()`s; `BillingLineSource` (conflict key\n `source_type, source_id`) is the only double-billing guard, so never bill a\n source without claiming it, and never widen that key. Each close step is\n persisted before the next; `acquireCloseLease()` serializes workers. A\n close that nets to a credit keeps its claims and ends `carried_forward`;\n its subtotal is a `credit_carry_forward` source for the payer's next billed\n close, which marks the carried close `completed`.\n- **Cycles and flat-plan coverage (#3116).** `cycles.ts` is the schedule\n (pure; `BillingAccount.billingAnchorAt`, null = calendar months). A close\n with no period closes each payer's `lastEndedBillingPeriod()`. Flat-plan\n claims are the exception to \"id from the source\": their `sourceId` is\n `<subscriptionId>:seq:<chainSequence>` and their `periodStart/End` is the\n exact time they bill. `claimFlatWindow()` reads the last number, then the\n coverage (claims ending after the window start), claims one gap as number\n n + 1, and retries on conflict; reading in that order is what makes it\n safe. That numbering, not the period, stops overlaps when schedules or\n payers change — never claim a flat plan outside it, and keep both reads\n bounded (no whole-history scans). Each numbered claim is its own invoice\n line keyed `lineKey|periodStart` (a function of the claim alone, so a\n resumed close rebuilds the same line ids). Proration is\n `prorateMinorUnits()` (half up, BigInt) against the period's full cycle.\n- **System tables.** `BillingAccount`, `BillingPeriodClose`, and\n `BillingLineSource` are not tenant-scoped and have no generated surface.\n Collections stay unexported; models are root exports (#3082). Invoices,\n payments, and journals are written in the seller's tenant; payer-owned\n subscriptions and credit grants in a system context, only after\n verification.\n- **Events** use smrt-jobs' delivery inbox under provider\n `<name>-billing:<sellerTenantId>` and a provider-filtered\n `ForgeProjectionRuntime`, so a runtime never claims another seller's\n events; any other runtime sharing the inbox must pass `providers` too. Only\n events this package acts on are stored: foreign checkouts are `ignored`,\n and only `smrt_*` checkout metadata is kept; it is\n HMAC-signed with the webhook secret at creation (empty values are omitted:\n Stripe drops them), so another integration on the same account cannot forge\n a credit purchase or a card setup; credit is granted only when the\n collected total equals it plus provider tax. Checkout amounts come from the\n re-read session (`getCheckout()`), never the Stripe event, whose amounts are\n in Stripe's unit. Rotating the webhook secret strands in-flight checkouts\n (up to 24 h). `observe()` re-reads provider state, so ordering never depends\n on delivery order; the only provider writes in `observe()` are idempotent\n (making a saved card the default). The standing hook runs inside the event\n transaction and must be idempotent.\n- **Card on file and top-ups (#3139).** A saved card is the payer customer's\n default `PaymentInstrument` (seller tenant, id from the provider method).\n `autoChargeInvoices` bills such payers `charge_automatically`, decided once\n and saved as `Invoice.collectionMethod` before the first push, which every\n retry reuses (never recompute it: a lost push response would record a\n method the provider was not asked for, #3190); activation follows `paid`, never send. An auto top-up attempt\n is a `PENDING` `Payment` (`reference` `auto-top-up:<policyId>`, id from the\n policy and `count()` of its attempts) inserted before the charge, so racing\n evaluations derive one id and one charge; the charge key is derived from\n that id. `applyAutoTopUpOutcome()` must run in a transaction and starts with\n a conditional `UPDATE … WHERE status = 'pending'` row lock, so the hook and\n the `payment` webhook settle once; the grant is keyed by the charge key.\n Never settle an attempt outside that function. Taxed accounts are charged\n with provider tax by default (#3194): the attempt row holds the credit\n (the charge subtotal), the tax is journaled to tax payable at settlement,\n and the attempt's tax decision is recorded in its `notes` so a re-drive\n repeats the same charge request (the provider refuses a key reused with\n different tax). `claimAttempt()` is the only place that decides a\n skip and reports it (`onAutoTopUpSkipped`); `cardOnFile()` and period close\n use `defaultCardInstrument()` — never copy that predicate. A provider write-off moves the local invoice to\n `WRITTEN_OFF` (a later payment, by card or on a rail (#3188), is recorded\n and reinstates the payer; the status stays, so \"paid in full\" for a\n written-off invoice is read from its allocations).\n- **Billing invoices are money-model invoices.** The provider taxes them\n (`providerTaxAmount`, server-managed, not API-writable, added to line tax),\n so every billing line is an explicit `taxMode: 'override'` to the seller's\n `out-of-scope` code. Charges are written before credits so the running\n subtotal never goes negative, and provider tax is written in the save that\n issues the invoice. Revenue posting is idempotent. `ledger.bookCurrency` is\n required (ISO 4217, validated by `BillingRuntime`) and must equal the\n billing currency. `toAccountingInput({ mapping })` emits major units.\n- **Payment rails (#3138).** A runtime has one issuing `provider` and any\n number of `paymentProviders` (unique names, one inbox namespace each; a\n provider with `capabilities.issuesInvoices === false` can never issue).\n `observe()` resolves the provider from the delivery namespace, never the\n payload. Crypto rails implement the port over `@happyvertical/payments`'\n `CryptoCheckoutGateway`; never call BTCPay (or any gateway) from here.\n Settlement is decided by the pure `decideAttempt()` from gateway state and\n `paymentPolicy` — the gateway's `settled` is authoritative and nothing here\n counts confirmations. A `BillingPaymentAttempt` (`(provider, checkout_id)`\n deterministic id) records every state and settles once; grants and payments\n are keyed by checkout id. Invoice payments close the issuer's invoice out of\n band in `observe()` (idempotent) before `project()` records the payment, and\n `settlePaidInvoice` skips (records nothing for) a `paidOutOfBand` invoice\n the rail latched with `outOfBandRequestedAt`; other out-of-band closes are\n recorded as `OTHER` payments. Rails never save cards or charge tax: a taxed\n credit purchase on a rail needs an explicit `automaticTax: false`. Exceptions are flags for operators;\n nothing reverses or refunds automatically.\n- **Known limits**: write-offs post no bad-debt journal (AR stays until paid\n or journaled by an operator); discounts still reach Stripe as negative lines (the SDK's\n line `discount` would change the lines a replayed push reconciles, so it\n needs its own migration); `RetailCharge` has no adjustment ledger. Flat\n plans are monthly, in arrears; plan changes are not prorated (#3119).\n\n## Cross-Package References\n\n- `customerId` → `@foreignKey('Customer')` (hard reference within package)\n- `vendorId` → `@foreignKey('Vendor')` on PurchaseContract only\n- `profileId` → plain string to smrt-profiles\n- `arJournalId`, `revenueJournalId` → plain string to smrt-ledgers\n- `skuId` (on `PaymentIntent`, `LicenseSale`) → plain string to smrt-products\n- `paymentId` (on `PaymentIntent`, `Payout`, `LicenseSale`) → plain string to `Payment` (same package, but kept as plain string for cross-model consistency)\n- `vendorId` on `Payout` → `@foreignKey(Vendor)` (hard reference within package)\n- Billing records reference tenants with `@crossPackageRef('@happyvertical/smrt-users:Tenant')` and charges, plan periods, and adjustments by plain `sourceId`\n\n## Gotchas\n\n- **Optional tenancy**: all models `@TenantScoped({ mode: 'optional' })` + nullable tenantId\n- **Money units and arithmetic**: money fields use signed integer minor units; rates and quantities remain decimal where their contracts require them. Exact rounding, tax-code resolution, safe-integer validation, and journal units are defined in the [commercial money model](agents/money-model.md) and [money calculator](agents/money-calculator.md). Do not reintroduce floating-point tolerances on money paths.\n- **Money documents need a tenant**: models are optionally tenant-scoped, but every Invoice and Contract money write requires one (`MoneyValidationError` `INVALID_MONEY_INPUT`, `Commerce money documents require a tenant`).\n- **Earlier-version money data is refused**: never add a read or conversion path for it. Detection and the one-shot upgrade are in [money data upgrade](agents/money-upgrade.md).\n- **Book currency is required**: `recognizeRevenue()` and `cancelWithRevenueReversal()` take a required `bookCurrency`, which must equal the invoice currency.\n- **Asset-native amounts stay outside line rescales**: `Payment.nativeAmount` and `PaymentIntent.paymentOptions[].nativeAmount` are per-asset values identified by `nativeCurrency`; normalize each asset to its own minor unit before any type conversion, and never apply the commerce ×100 line-money rescale to them.\n- **Invoice controls payment status**: not the Payment model — use `Invoice.updatePaymentStatus()`\n- **Tax comes from tax codes**: the server resolves each line's code and computes line tax and header totals; client totals and a line's stored `taxRate` are never inputs\n- **Profile linking**: separate `ProfileCollection.create()` needed to fetch actual Profile object\n- **PaymentIntent natural key**: `conflictColumns: ['tenant_id', 'offering_ref', 'licensee_email', 'idempotency_key']` — a retried `create` with the same tuple upserts the existing row. Use `PaymentIntentCollection.getOrCreateByIdempotencyKey()` to branch on `{ intent, created }`. Empty natural-key inputs (e.g. blank `idempotencyKey`) disable dedup by design.\n- **Payout state-machine guards**: `markSent` requires a non-empty `backendTxRef`; `markConfirmed` only valid from `SENT`; `markFailed` only valid from `PENDING` / `SENT` (a confirmed payout can't fail — that path is a refund). `resetFromFailed()` is the dedicated escape hatch from `FAILED` back to `PENDING` after an operator fixes the underlying problem; it clears `backendTxRef` so the next attempt picks up a fresh one.\n- **LicenseSale immutability**: rights snapshot freezes on save-with-status-ACCEPTED. The captured snapshot lives in a module-scoped `WeakMap<LicenseSale, string>` so it doesn't interact with the schema or round-trip through `_meta_data`. Drafts (status != ACCEPTED) remain mutable. To \"change\" an issued license: `revoke()` it, then issue a new `LicenseSale` row.\n- **Vendor.payoutAddresses normalization**: the constructor accepts either a `Record<string, string>` or a pre-serialized JSON string. `initialize()` re-normalizes after the framework's option-override pass; `save()` re-normalizes defensively against direct field assignment. Non-string values inside the input map are silently dropped to preserve the typed invariant downstream.\n\n## Commercial UI\n\n`CustomerSelect`/`VendorSelect` are the registered selectors for Customer and\nVendor (`selects` in `src/ui.ts`); models carry `ui.widget` / `ui.format` hints. See\n[customer/vendor UI](agents/customer-vendor-ui.md#selectors-3602).\n\nSee [commercial UI composition](agents/commercial-ui.md) for native form recovery, amount compatibility and backend ownership. Package-owned guides under `agents/` ship with the package.\n\n## Quote and estimate UI\n\n`src/svelte/quote-types.ts` separates unparsed draft strings from explicit\nminor-unit revision DTOs. Native row submitters, caller-owned retry identity and\nextension conventions are documented in [agents/quote-ui.md](agents/quote-ui.md).\n\n## Purchasing UI\n\n`PurchaseOrderEditor` preserves allocation IDs and explicit zeroes, including\nretained reduction rows; the server validates review fingerprints before recording.\nSee [agents/purchasing-ui.md](agents/purchasing-ui.md) for caller responsibilities.\n\n## Exact cost billing\n\nPure signed cost billing and explicit tax rounding are available through the\nindependent `cost-billing` subpath; see [contract](agents/cost-billing.md).\n\nSee [contract billing schedules](agents/contract-billing-schedules.md) for exact\napproved milestone capacity, immutable amendments and atomic canonical invoice issue.\n\nSee [estimate conversion](agents/estimate-conversion.md) for turning an accepted\nEstimate into an idempotent Order with copied lines and lineage.\n\n## Customer funds (#4079)\n\nSee [customer advances](agents/customer-funds.md) for explicitly configured\nunapplied-AR/deposit-liability receipts, conserved application/refund capacity,\nreal liability reclassification, final-invoice attestation and mutation guards.\nUse the public commands; `Payment.customerFundsJson` is command-owned.\n\nSee [observed purchase prices](agents/observed-purchase-prices.md) for incomplete\noriginal supplier prices, explicit unknown totals and reviewed completion.\nSee [received sales agreement money](agents/received-sales-contract-money.md) for\nexact complete source Order/Agreement evidence without synthetic lines or tax recognition.\n\nSee [ordinary invoice accounting adjustments](agents/ordinary-accounting.md) for\nnon-retained provider credit applications, recorded refunds and durable recovery.\n\n## Protected billable sources (#4746)\n\n`invoice-source-binding.ts` is the generic pointer/guard contract for an owning\npackage's existing capacity reservation. It creates no capacity ledger. Trusted\npackages register qualified `billable:` source handlers; missing handlers and\nunbound protected lines fail closed at issue. `InvoiceLineItem.sourceReservationId`\nis command-owned; line save/delete, collection deletion, invoice cascade deletion\nand issue validate persisted identities. Release/unbind must share the owning\nreservation transaction. See [source binding](agents/invoice-source-binding.md).\n",
|
|
23633
23634
|
"moduleDocs": [
|
|
23634
23635
|
{
|
|
23635
23636
|
"path": "agents/customer-vendor-ui.md",
|
|
@@ -23681,6 +23682,11 @@
|
|
|
23681
23682
|
"module": "payment-allocations",
|
|
23682
23683
|
"content": "# Payment allocation integrity\n\n`PaymentAllocation.save()` owns the financial boundary for every direct or\ncollection write. Both payment and invoice must exist, belong to the same\nexact tenant (global is distinct), have the same customer and currency, and\nhave room for the positive safe-integer minor-unit amount. Zero-total invoices\nhave no room. Missing or zero-total invoice fixtures no longer bypass the cap.\nPending payments remain allocatable; this command does not establish settlement\nproof. Generated REST/MCP/CLI allocation writes remain closed. Applications\nmust authorize the actor before invoking these backend commands.\n\nUse `PaymentAllocationCollection.allocatePayment({ paymentId, allocations,\nallocatedBy })` for a split. Each allocation is `{ id, invoiceId, amount }`, with\na caller-generated stable UUID retained across retries. Exact replay\nreuses the existing rows without applying money again; an existing id with\ndifferent parents or amount fails. Replay preserves an already-paid invoice's\nrecorded payment date. Reversing\npayment clears that date; reaching full payment again records the new date.\nThe complete batch and invoice payment-status refresh share one transaction. Invoices must\nalready be in a status that permits payment (normally SENT); WRITTEN_OFF retains\nits terminal status. A failed leg rolls back every leg and parent revision.\nDirect allocation saves continue to leave status refresh to the caller. Allocation\nwrites advance both parent revisions: reload a previously held parent with\n`await parent.loadFromId()` before applying later edits or status refresh.\nStale parent saves continue to fail the core revision guard; no implicit\nrevision refresh bypasses another editor. In-package billing follows this rule.\n\nOnce inserted, allocation tenant/payment/invoice identity is immutable. Amount\ncorrections are capped against the other allocations. Parent saves reject\nchanges to tenant, customer, currency or amount that would invalidate committed\nallocations. A payment may be increased or reduced to its allocated total;\ninvoice totals continue to derive from persisted invoice lines where present.\nStandalone payments remain saveable when allocation storage has not been\nprovisioned. An existing allocation table always participates in validation;\nstorage probes and permission errors propagate instead of disabling the guard.\n\nAll participating writes bind collections to the owning transaction executor.\nThey claim parent revisions before reading balances. Concurrent writers can\nreceive a revision conflict or database serialization failure; reload and retry\nthe complete transaction with the same allocation ids. Never retry only the\nlast leg inside an already failed transaction. PostgreSQL Repeatable Read\nsnapshots fail closed through the same revision writes. SQLite serializes the\nowning write transaction. DuckDB is not a supported commerce allocation store:\nthe existing declared foreign keys require ON UPDATE CASCADE, which its DDL\nboundary explicitly refuses; no weaker schema is substituted.\n\n### Undelivered invoice payment progress\n\nAllocation may move an undelivered DRAFT invoice to PARTIAL or PAID without a\ncustomer delivery event. Neither operation invents `sentAt` or `viewedAt`.\nAfter allocations are removed, reload the parent and call\n`updatePaymentStatus(remainingTotal)` and `save()` within the caller transaction.\nZero remaining allocations restore DRAFT only for an undelivered invoice;\na delivered invoice returns to SENT/VIEWED according to its delivery history.\nDRAFT cannot conceal positive allocations. A DRAFT save checks both its supplied\ndelivery timestamps and the currently persisted timestamps, so clearing them\nlocally during reversal cannot bypass the undelivered requirement. This guard\ndoes not introduce an immutable lifetime delivery-history record.\n\nIf a prepaid invoice is actually delivered later, call `markSent()` and save.\nFor PARTIAL/PAID invoices it records the first `sentAt` while preserving payment\nstatus, paid amount, paid date and any existing view timestamp. Repeating this\ncall preserves the first send timestamp. It records the caller's delivery\nevent; it does not send a customer message or manufacture earlier delivery.\n\n\n## Original settlement dates (#4099)\n\n`Payment.recordPayment` and `recordRefund` accept optional `effectiveOn`, a strict\nreal `YYYY-MM-DD` calendar date. Explicit dates set the posted journal and `paidAt`\nto noon UTC on that date; omission preserves current-clock ordinary posting.\nCustomer-funds commands retain their reviewed date and reject a conflicting\nexplicit override. Recording cash evidence does not initiate a provider transfer.\nCompleted or refunded payment settlement dates and journal identities are immutable,\nincluding direct save; correcting evidence requires an explicit reversal workflow.\nPosting retains the caller transaction and rejects duplicate completion.\n\nValidation: shared payment-posting contracts and customer-funds proofs pass on\nSQLite and PostgreSQL (55 passed, one PostgreSQL-only case skipped in the SQLite\nlane). They cover leap-day settlement, malformed/impossible dates, immutable\nreloads, duplicate posting, rollback, concurrency and conflicting managed dates.\nPackage typecheck/Svelte check (zero errors/warnings) and build pass. Initial\nfailures retained in the MVP evidence identified the missing direct-save date\nfreeze and an order-dependent journal assertion; both were corrected.\n\n## Allocation deletion versus retained-refund reservation (#4063 / PR #4101)\n\nDeletion claims the persisted Payment revision in its owning transaction before\nchecking provider or customer-funds authority. It holds that revision through the\nallocation DELETE. A retained-refund reservation uses the same Payment revision\nclaim when saving its binding, so a stale unbound parent read cannot authorize\nremoval after the provider reservation commits. If deletion commits first, the\nprovider reservation must fail its stale Payment claim before provider I/O.\nOrdinary deletion advances the Payment revision; reload held Payment instances\nbefore subsequent edits. Invoice status refresh remains caller-owned.\n\nThe accepted review fix is high risk because concurrent deletion could remove\nsettlement evidence already reserved by an external accounting operation. No API,\nschema, accounting mapping or bank execution contract changes.\n\n| Behavior / reachable trigger | Positive / negative case | Actor / executor / runtime | External edge / focused evidence |\n| --- | --- | --- | --- |\n| Direct allocation deletion | Ordinary unbound row deletes; failed outer transaction preserves row and parent revision | Active owning tenant; one caller transaction; SQLite and PostgreSQL | No bank I/O; dedicated allocation-delete suite |\n| Existing provider binding | Protected row remains and rejected delete rolls back parent revision; foreign tenant cannot delete | Owning versus foreign active tenant; transaction-bound parent claim; both dialects | Public retained-refund sync plus immutable binding readback |\n| Claimed deletion commits first | Provider reservation reaches its Payment revision claim, then fails without binding, refund reservation or provider I/O | Separate native PostgreSQL transactions; deterministic claim barriers | Public refund operation fails closed after its stale settlement evidence is removed |\n| Stale unbound parent read | Provider reservation commits while delete is paused, then stale delete fails and exact allocation remains | Separate native PostgreSQL transactions; deterministic read barrier | Real public provider saga with fake provider port; exact retry creates no extra provider operation |\n\nThe PostgreSQL concurrency interleaving is intentionally not run on SQLite:\nSQLite serializes the owning write transaction instead of allowing PostgreSQL's\nstale-read interleaving. Shared mutation/rollback/tenant/binding cases run on both.\nThe dedicated native test must fail against the pre-fix implementation before\nclaiming regression coverage. External outcome recovery and malformed provider\ninputs are unchanged and covered by the retained-accounting suite; no new provider\nrequest shape is introduced here.\n\nFocused validation: the dedicated SQLite/PostgreSQL test file passes all four\ncases; both PostgreSQL races use real independent transactions and explicit\nmethod barriers, without sleeps or mocked database results. The stale deletion\ncase fails against the unchanged base because deletion succeeds after provider\nreservation. Existing SQLite allocation-integrity and customer-funds suites also\npass (19 cases), including the managed reversal caller. Scoped model/test\nTypeScript passes. Run the dedicated PostgreSQL proof with the standard managed\n`run-with-ci-postgres.mjs` wrapper; it creates and cleans its own database.\n"
|
|
23683
23684
|
},
|
|
23685
|
+
{
|
|
23686
|
+
"path": "agents/settlement-accounts.md",
|
|
23687
|
+
"module": "settlement-accounts",
|
|
23688
|
+
"content": "# Tenant settlement accounts (#5412)\n\nSource: `src/settlement-accounts.ts`.\n\n`ensureTenantSettlementAccounts(db, tenantId, { currency })` is the settlement\ncounterpart of `ensureCommerceTenant`. A payment only reaches `COMPLETED`\nthrough `Payment.recordPayment`, and only completed payments are pushed to the\naccounting provider ([payment sync](accounting-payment-sync.md)), so a host\nneeds a ledger and accounts before any payment can settle.\n\nIt seeds one **exact-integer** ledger per tenant and currency\n(`Settlement <CUR>`) and these accounts, under stable numbers hosts, provider\nmappings and reports can key off (`SETTLEMENT_ACCOUNTS`):\n\n| number | name | type |\n|---|---|---|\n| 1000 | Cash / Undeposited Funds | asset |\n| 1200 | Accounts Receivable | asset |\n| 2200 | Sales Tax Payable | liability |\n| 4000 | Sales Revenue | revenue |\n\nIt returns `{ ledgerId, cashAccountId, receivablesAccountId,\nsalesTaxPayableAccountId, revenueAccountId }`; the first three are exactly the\n`RecordPaymentOptions` of `recordPayment`, and the receivables and revenue\naccounts are the `arAccountId` / `revenueAccountId` of `recognizeRevenue`.\n\n- Idempotent and race safe: deterministic ids, a tenant advisory lock on\n PostgreSQL (the embedded write queue otherwise), and a reload when a racing\n insert wins. Existing rows are never changed.\n- A row found under a seed identity whose tenant, currency, ledger, number or\n type differs is refused, never adopted.\n- Call it outside a model transaction (it opens its own), like\n `ensureCommerceTenant`. Requires smrt-ledgers.\n- `recordPayment` posts into the ledger of the cash account. A ledger-scoped\n account used to be rejected (\"Journal entry account must belong to its journal\n ledger\") because the journal was always ledger-less; it now takes the cash\n account's ledger and refuses a `ledgerId` that does not own it. Ledger-less\n accounts (`ledgerId: ''`) keep posting to a ledger-less journal.\n- `recognizeRevenue` (and the cancellation reversal) post into the same ledger:\n the journal takes the ledger shared by its posting accounts, and a mix of\n ledgers (or of ledger-scoped and ledger-less accounts) is refused with a clear\n error. Point tax components' `liabilityAccountId` at Sales Tax Payable (2200)\n so the per-line tax accounts come from the same chart.\n- Scope: this chart settles incoming payments (cash and receivables) and gives\n `recognizeRevenue` its receivables, revenue and sales-tax accounts. It does not\n yet back `BillingRuntime.ledger`: the billing tax journal and `postOnce`\n journals stay ledger-less, and the chart has no fee or deposit-liability\n account for connected payments or customer funds.\n"
|
|
23689
|
+
},
|
|
23684
23690
|
{
|
|
23685
23691
|
"path": "agents/tax-codes.md",
|
|
23686
23692
|
"module": "tax-codes",
|
|
@@ -5,10 +5,10 @@ description: "Commerce models for the SMRT framework - contracts, fulfillments,
|
|
|
5
5
|
status: "stable"
|
|
6
6
|
generated:
|
|
7
7
|
by: "smrt/scripts/generate-knowledge-okf.ts"
|
|
8
|
-
at: "2026-11-
|
|
8
|
+
at: "2026-11-21T00:43:48Z"
|
|
9
9
|
audience: "internal"
|
|
10
10
|
evidence_level: "source-inspected"
|
|
11
|
-
source_revision: "sha256:
|
|
11
|
+
source_revision: "sha256:0c9262d63468ada343193a6e373998110623b9d92009cda17296c9b1cc814f27"
|
|
12
12
|
sources:
|
|
13
13
|
- id: "manifest"
|
|
14
14
|
resource: "https://github.com/happyvertical/smrt/blob/main/packages/commerce/package.json"
|
|
@@ -95,6 +95,9 @@ sources:
|
|
|
95
95
|
resource: "https://github.com/happyvertical/smrt/blob/main/packages/commerce/agents/received-sales-contract-money.md"
|
|
96
96
|
title: "@happyvertical/smrt-commerce packages/commerce/agents/received-sales-contract-money.md"
|
|
97
97
|
- id: "agents-28"
|
|
98
|
+
resource: "https://github.com/happyvertical/smrt/blob/main/packages/commerce/agents/settlement-accounts.md"
|
|
99
|
+
title: "@happyvertical/smrt-commerce packages/commerce/agents/settlement-accounts.md"
|
|
100
|
+
- id: "agents-29"
|
|
98
101
|
resource: "https://github.com/happyvertical/smrt/blob/main/packages/commerce/agents/tax-codes.md"
|
|
99
102
|
title: "@happyvertical/smrt-commerce packages/commerce/agents/tax-codes.md"
|
|
100
103
|
---
|
|
@@ -137,6 +140,7 @@ sources:
|
|
|
137
140
|
- `packages/commerce/agents/purchasing-ui.md`
|
|
138
141
|
- `packages/commerce/agents/quote-ui.md`
|
|
139
142
|
- `packages/commerce/agents/received-sales-contract-money.md`
|
|
143
|
+
- `packages/commerce/agents/settlement-accounts.md`
|
|
140
144
|
- `packages/commerce/agents/tax-codes.md`
|
|
141
145
|
|
|
142
146
|
## Framework dependencies
|
package/dist/tax/identity.d.ts
CHANGED
|
@@ -1,3 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Stable UUIDv5-shaped identity from a list of parts (SHA-256 of their JSON).
|
|
3
|
+
* Shared by the tenant tax and settlement-account seeds so retries and races
|
|
4
|
+
* converge on one row.
|
|
5
|
+
*/
|
|
6
|
+
export declare function deterministicSeedId(...parts: readonly string[]): Promise<string>;
|
|
1
7
|
/** Stable UUID identities make tenant tax bootstrap retry and race safe. */
|
|
2
8
|
export declare function deterministicTaxId(tenantId: string, kind: 'code' | 'component' | 'settings' | 'report', key: string): Promise<string>;
|
|
3
9
|
/** A racing deterministic insert loses safely and reloads the committed row. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"identity.d.ts","sourceRoot":"","sources":["../../src/tax/identity.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,wBAAsB,kBAAkB,CACtC,QAAQ,EAAE,MAAM,EAChB,IAAI,EAAE,MAAM,GAAG,WAAW,GAAG,UAAU,GAAG,QAAQ,EAClD,GAAG,EAAE,MAAM,GACV,OAAO,CAAC,MAAM,CAAC,
|
|
1
|
+
{"version":3,"file":"identity.d.ts","sourceRoot":"","sources":["../../src/tax/identity.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,wBAAsB,mBAAmB,CACvC,GAAG,KAAK,EAAE,SAAS,MAAM,EAAE,GAC1B,OAAO,CAAC,MAAM,CAAC,CASjB;AAED,4EAA4E;AAC5E,wBAAsB,kBAAkB,CACtC,QAAQ,EAAE,MAAM,EAChB,IAAI,EAAE,MAAM,GAAG,WAAW,GAAG,UAAU,GAAG,QAAQ,EAClD,GAAG,EAAE,MAAM,GACV,OAAO,CAAC,MAAM,CAAC,CAIjB;AAED,gFAAgF;AAChF,wBAAsB,mBAAmB,CAAC,CAAC,EACzC,MAAM,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,EACxB,IAAI,EAAE,MAAM,OAAO,CAAC,CAAC,GAAG,IAAI,GAAG,SAAS,CAAC,GACxC,OAAO,CAAC,CAAC,CAAC,CAeZ"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@happyvertical/smrt-commerce",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.66.0",
|
|
4
4
|
"smrtJsdoc": "strict",
|
|
5
5
|
"description": "Commerce models for the SMRT framework - contracts, fulfillments, payments",
|
|
6
6
|
"type": "module",
|
|
@@ -63,21 +63,21 @@
|
|
|
63
63
|
"access": "public"
|
|
64
64
|
},
|
|
65
65
|
"dependencies": {
|
|
66
|
-
"@happyvertical/accounting": "^0.
|
|
67
|
-
"@happyvertical/payments": "^0.
|
|
68
|
-
"@happyvertical/smrt-agents": "0.
|
|
69
|
-
"@happyvertical/smrt-core": "0.
|
|
70
|
-
"@happyvertical/smrt-jobs": "0.
|
|
71
|
-
"@happyvertical/smrt-ledgers": "0.
|
|
72
|
-
"@happyvertical/smrt-products": "0.
|
|
73
|
-
"@happyvertical/smrt-profiles": "0.
|
|
74
|
-
"@happyvertical/smrt-reports": "0.
|
|
75
|
-
"@happyvertical/smrt-subscriptions": "0.
|
|
76
|
-
"@happyvertical/smrt-svelte": "0.
|
|
77
|
-
"@happyvertical/smrt-tenancy": "0.
|
|
78
|
-
"@happyvertical/smrt-types": "0.
|
|
79
|
-
"@happyvertical/smrt-ui": "0.
|
|
80
|
-
"@happyvertical/sql": "^0.
|
|
66
|
+
"@happyvertical/accounting": "^0.116.6",
|
|
67
|
+
"@happyvertical/payments": "^0.116.6",
|
|
68
|
+
"@happyvertical/smrt-agents": "0.66.0",
|
|
69
|
+
"@happyvertical/smrt-core": "0.66.0",
|
|
70
|
+
"@happyvertical/smrt-jobs": "0.66.0",
|
|
71
|
+
"@happyvertical/smrt-ledgers": "0.66.0",
|
|
72
|
+
"@happyvertical/smrt-products": "0.66.0",
|
|
73
|
+
"@happyvertical/smrt-profiles": "0.66.0",
|
|
74
|
+
"@happyvertical/smrt-reports": "0.66.0",
|
|
75
|
+
"@happyvertical/smrt-subscriptions": "0.66.0",
|
|
76
|
+
"@happyvertical/smrt-svelte": "0.66.0",
|
|
77
|
+
"@happyvertical/smrt-tenancy": "0.66.0",
|
|
78
|
+
"@happyvertical/smrt-types": "0.66.0",
|
|
79
|
+
"@happyvertical/smrt-ui": "0.66.0",
|
|
80
|
+
"@happyvertical/sql": "^0.116.6"
|
|
81
81
|
},
|
|
82
82
|
"peerDependencies": {
|
|
83
83
|
"svelte": "^5.57.0"
|
|
@@ -88,7 +88,7 @@
|
|
|
88
88
|
}
|
|
89
89
|
},
|
|
90
90
|
"devDependencies": {
|
|
91
|
-
"@happyvertical/smrt-vitest": "0.
|
|
91
|
+
"@happyvertical/smrt-vitest": "0.66.0",
|
|
92
92
|
"@sveltejs/package": "^2.5.8",
|
|
93
93
|
"@sveltejs/vite-plugin-svelte": "^7.3.0",
|
|
94
94
|
"@testing-library/jest-dom": "^7.0.1",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"invoice-posting-CDfxug3Q.js","names":[],"sources":["../../src/invoice-posting.ts"],"sourcesContent":["/** Atomic revenue posting and cancellation reversal. */\n\nimport type { DatabaseInterface } from '@happyvertical/smrt-core/migrations';\nimport type { Journal, JournalEntryData } from '@happyvertical/smrt-ledgers';\nimport { getTenantId } from '@happyvertical/smrt-tenancy';\nimport { ISO_4217_MINOR_UNITS } from '@happyvertical/smrt-ui/currency';\nimport { deterministicId } from './billing/units.js';\nimport { DocumentTaxCollection } from './collections/DocumentTaxCollection.js';\nimport { InvoiceLineItemCollection } from './collections/InvoiceLineItemCollection.js';\nimport { lockAndReloadInvoice } from './document-money.js';\nimport {\n DOCUMENT_MONEY_WRITE,\n withDocumentMoneyTransaction,\n} from './document-money-internal.js';\nimport type { Invoice } from './models/Invoice.js';\nimport { MoneyValidationError } from './money.js';\nimport { buildRevenueJournalEntries } from './revenue-journal.js';\nimport { lockTenantMoneyRuntime } from './tenant-money-barrier.js';\nimport {\n type CancelRevenueOptions,\n InvoiceStatus,\n type RecognizeRevenueOptions,\n} from './types/index.js';\n\ntype PostingMetadata = {\n kind:\n | 'invoice-revenue'\n | 'credit-note-revenue'\n | 'invoice-cancellation-reversal'\n | 'credit-note-cancellation-reversal';\n invoiceId: string;\n moneySnapshotId: string;\n originalJournalId?: string;\n};\n\nfunction required(value: string | null | undefined, label: string): string {\n if (!value || value.trim() !== value)\n throw new MoneyValidationError(\n 'INVALID_MONEY_INPUT',\n `${label} must be a nonempty value`,\n );\n return value;\n}\n\nfunction bookCurrency(value: string | undefined): string {\n if (\n !value ||\n value !== value.toUpperCase() ||\n !ISO_4217_MINOR_UNITS.has(value) ||\n ISO_4217_MINOR_UNITS.get(value) === null\n )\n throw new MoneyValidationError(\n 'INVALID_MONEY_INPUT',\n 'Revenue posting requires a supported ISO 4217 bookCurrency',\n );\n return value;\n}\n\nfunction assertTenantAuthority(tenantId: string): void {\n if (getTenantId() !== tenantId)\n throw new MoneyValidationError(\n 'INVALID_MONEY_INPUT',\n 'Invoice posting requires its active tenant context',\n );\n}\n\nfunction canonicalEntries(entries: readonly JournalEntryData[]): string {\n return JSON.stringify(\n entries\n .map((entry) => ({\n accountId: entry.accountId,\n debit: entry.debit ?? 0,\n credit: entry.credit ?? 0,\n currency: entry.currency ?? '',\n memo: entry.memo ?? '',\n }))\n .sort((left, right) => {\n const leftKey = JSON.stringify(left);\n const rightKey = JSON.stringify(right);\n return leftKey < rightKey ? -1 : leftKey > rightKey ? 1 : 0;\n }),\n );\n}\n\nasync function validateAccounts(\n db: DatabaseInterface,\n tenantId: string,\n accountIds: readonly string[],\n): Promise<void> {\n const { AccountCollection } = await import('@happyvertical/smrt-ledgers');\n const accounts = await AccountCollection.create({ db });\n for (const accountId of [...new Set(accountIds)]) {\n const account = await accounts.get({ id: accountId }, { cache: false });\n if (!account || account.tenantId !== tenantId || !account.active)\n throw new MoneyValidationError(\n 'INVALID_MONEY_INPUT',\n `Posting account ${accountId} must be active and owned by the invoice tenant`,\n );\n }\n}\n\nasync function entriesForJournal(\n db: DatabaseInterface,\n journalId: string,\n): Promise<JournalEntryData[]> {\n const { JournalEntryCollection } = await import(\n '@happyvertical/smrt-ledgers'\n );\n const entries = await (\n await JournalEntryCollection.create({ db })\n ).findByJournal(journalId);\n return entries.map((entry) => ({\n accountId: entry.accountId,\n debit: entry.debit,\n credit: entry.credit,\n currency: entry.currency,\n memo: entry.memo,\n }));\n}\n\nfunction metadataMatches(journal: Journal, expected: PostingMetadata): boolean {\n const actual = journal.metadata as Partial<PostingMetadata>;\n return (\n actual.kind === expected.kind &&\n actual.invoiceId === expected.invoiceId &&\n actual.moneySnapshotId === expected.moneySnapshotId &&\n actual.originalJournalId === expected.originalJournalId\n );\n}\n\nasync function createOrReadPostedJournal(\n db: DatabaseInterface,\n input: {\n id: string;\n tenantId: string;\n sourceRef: string;\n description: string;\n date: Date;\n metadata: PostingMetadata;\n entries: readonly JournalEntryData[];\n },\n): Promise<Journal> {\n const { JournalCollection } = await import('@happyvertical/smrt-ledgers');\n const journals = await JournalCollection.create({ db });\n const existing = await journals.get({ id: input.id }, { cache: false });\n if (existing) {\n const storedEntries = await entriesForJournal(db, input.id);\n if (\n existing.status !== 'posted' ||\n existing.tenantId !== input.tenantId ||\n existing.sourceModule !== 'smrt-commerce' ||\n existing.sourceRef !== input.sourceRef ||\n !metadataMatches(existing, input.metadata) ||\n canonicalEntries(storedEntries) !== canonicalEntries(input.entries)\n )\n throw new MoneyValidationError(\n 'FROZEN_DOCUMENT',\n `Deterministic journal ${input.id} conflicts with the frozen invoice snapshot`,\n );\n return existing;\n }\n const journal = await journals.create({\n id: input.id,\n tenantId: input.tenantId,\n date: input.date,\n description: input.description,\n sourceModule: 'smrt-commerce',\n sourceRef: input.sourceRef,\n metadata: input.metadata,\n _insertOnly: true,\n });\n for (const entry of input.entries) await journal.addEntry(entry);\n await journal.post();\n if (!journal.id)\n throw new MoneyValidationError(\n 'INVALID_MONEY_INPUT',\n 'Posted revenue journal is missing its identity',\n );\n return journal;\n}\n\n/**\n * Reload a journal posted inside a money transaction on `db`, so the caller\n * gets an instance whose reads do not run on the finished transaction.\n */\nexport async function rebindJournal(\n db: DatabaseInterface,\n journal: Journal,\n): Promise<Journal> {\n const { JournalCollection } = await import('@happyvertical/smrt-ledgers');\n return (\n (await (\n await JournalCollection.create({ db })\n ).get({ id: required(journal.id, 'Journal ID') }, { cache: false })) ??\n journal\n );\n}\n\n/** Post an issued invoice's revenue journal from its frozen money facts. */\nexport async function recognizeInvoiceRevenue(\n input: Invoice,\n options: RecognizeRevenueOptions,\n): Promise<Journal> {\n return withDocumentMoneyTransaction(input.db, async (tx) =>\n input.withDatabase(tx, async (callerInvoice) => {\n const candidateTenantId = getTenantId() ?? callerInvoice.tenantId;\n await lockTenantMoneyRuntime(\n tx,\n required(candidateTenantId, 'Invoice tenant ID'),\n );\n const invoiceId = required(callerInvoice.id, 'Invoice ID');\n const tenantId = required(candidateTenantId, 'Invoice tenant ID');\n assertTenantAuthority(tenantId);\n const currency = bookCurrency(options.bookCurrency);\n const { invoice } = await lockAndReloadInvoice(tx, invoiceId, tenantId);\n if (invoice.moneyAuthority === 'historical')\n throw new MoneyValidationError(\n 'INVALID_MONEY_INPUT',\n 'Original historical revenue is retained evidence; a new revenue posting requires an explicit reviewed historical accounting contract',\n );\n if (invoice.status === InvoiceStatus.DRAFT || !invoice.moneySnapshotId)\n throw new MoneyValidationError(\n 'FROZEN_DOCUMENT',\n 'Revenue recognition requires an issued frozen invoice',\n );\n if (invoice.currency !== currency)\n throw new MoneyValidationError(\n 'CURRENCY_MISMATCH',\n `Invoice currency ${invoice.currency} does not match book currency ${currency}`,\n );\n\n const lines = await (\n await InvoiceLineItemCollection.create({ db: tx })\n ).findByInvoice(invoiceId);\n const taxes = await (\n await DocumentTaxCollection.create({ db: tx })\n ).findByDocument(tenantId, invoice.kind, invoiceId);\n const built = buildRevenueJournalEntries(\n {\n id: invoiceId,\n number: invoice.invoiceNumber,\n currency: invoice.currency,\n lineAmountType: invoice.lineAmountType,\n subtotalMinor: invoice.subtotal,\n taxMinor: invoice.taxAmount,\n totalMinor: invoice.totalAmount,\n providerTaxMinor: invoice.providerTaxAmount,\n },\n lines.map((line) => ({\n id: required(line.id, 'Invoice line ID'),\n amountMinor: line.amount,\n taxMinor: line.taxAmount,\n revenueAccountId: line.revenueAccountId,\n })),\n taxes.map((tax) => ({\n currency: tax.currency,\n taxCodeId: tax.taxCodeId,\n taxCodeCode: tax.taxCodeCode,\n taxComponentId: tax.taxComponentId,\n liabilityAccountId: tax.liabilityAccountId,\n taxMinor: tax.taxMinor,\n })),\n {\n arAccountId: options.arAccountId,\n revenueAccountId: options.revenueAccountId,\n taxAccountId: options.taxAccountId,\n bookCurrency: currency,\n direction: invoice.kind === 'credit_note' ? -1 : 1,\n },\n );\n await validateAccounts(\n tx,\n tenantId,\n built.entries.map((entry) => entry.accountId),\n );\n const postingKind =\n invoice.kind === 'credit_note'\n ? ('credit-note-revenue' as const)\n : ('invoice-revenue' as const);\n const journalId = await deterministicId([\n postingKind,\n tenantId,\n invoiceId,\n invoice.moneySnapshotId,\n ]);\n const metadata: PostingMetadata = {\n kind: postingKind,\n invoiceId,\n moneySnapshotId: invoice.moneySnapshotId,\n };\n const journal = await createOrReadPostedJournal(tx, {\n id: journalId,\n tenantId,\n sourceRef: `${postingKind}:${invoiceId}:${invoice.moneySnapshotId}`,\n description: `${invoice.kind === 'credit_note' ? 'Credit note' : 'Revenue'}: Invoice ${invoice.invoiceNumber}`,\n date: invoice.issueDate,\n metadata,\n entries: built.entries,\n });\n if (invoice.arJournalId && invoice.arJournalId !== journalId)\n throw new MoneyValidationError(\n 'FROZEN_DOCUMENT',\n 'Invoice already links a different revenue journal',\n );\n invoice.arJournalId = journalId;\n await invoice.saveDerived(DOCUMENT_MONEY_WRITE);\n callerInvoice.arJournalId = journalId;\n return journal;\n }),\n );\n}\n\nfunction reverseEntries(\n entries: readonly JournalEntryData[],\n currency: string,\n): JournalEntryData[] {\n return entries.map((entry, index) => {\n if (\n entry.currency !== currency ||\n !Number.isSafeInteger(entry.debit ?? 0) ||\n !Number.isSafeInteger(entry.credit ?? 0) ||\n (entry.debit ?? 0) < 0 ||\n (entry.credit ?? 0) < 0 ||\n (entry.debit ?? 0) > 0 === (entry.credit ?? 0) > 0\n )\n throw new MoneyValidationError(\n entry.currency !== currency ? 'CURRENCY_MISMATCH' : 'UNSAFE_MONEY',\n `Original journal entry ${index + 1} is not an exact ${currency} movement`,\n );\n return {\n accountId: required(entry.accountId, 'Original journal account ID'),\n debit: entry.credit ?? 0,\n credit: entry.debit ?? 0,\n currency,\n memo: `Reversal: ${entry.memo ?? ''}`,\n };\n });\n}\n\n/** Atomically reverse a posted invoice and move it to CANCELLED. */\nexport async function cancelInvoiceWithRevenueReversal(\n input: Invoice,\n options: CancelRevenueOptions,\n): Promise<Journal> {\n return withDocumentMoneyTransaction(input.db, async (tx) =>\n input.withDatabase(tx, async (callerInvoice) => {\n const candidateTenantId = getTenantId() ?? callerInvoice.tenantId;\n await lockTenantMoneyRuntime(\n tx,\n required(candidateTenantId, 'Invoice tenant ID'),\n );\n const invoiceId = required(callerInvoice.id, 'Invoice ID');\n const tenantId = required(candidateTenantId, 'Invoice tenant ID');\n assertTenantAuthority(tenantId);\n const currency = bookCurrency(options.bookCurrency);\n const { invoice } = await lockAndReloadInvoice(tx, invoiceId, tenantId);\n if (invoice.currency !== currency)\n throw new MoneyValidationError(\n 'CURRENCY_MISMATCH',\n `Invoice currency ${invoice.currency} does not match book currency ${currency}`,\n );\n if (\n (invoice.kind === 'invoice' && invoice.isPaid()) ||\n (invoice.kind === 'credit_note' && invoice.amountPaid > 0)\n )\n throw new MoneyValidationError(\n 'FROZEN_DOCUMENT',\n 'Paid invoices and refunded credit notes cannot be cancelled',\n );\n if (!invoice.arJournalId)\n throw new MoneyValidationError(\n 'FROZEN_DOCUMENT',\n 'Revenue must be posted before using cancellation reversal',\n );\n const snapshotId = required(\n invoice.moneySnapshotId,\n 'Invoice money snapshot ID',\n );\n const originalJournalId = invoice.arJournalId;\n const originalKind =\n invoice.kind === 'credit_note'\n ? ('credit-note-revenue' as const)\n : ('invoice-revenue' as const);\n const { JournalCollection } = await import('@happyvertical/smrt-ledgers');\n const journals = await JournalCollection.create({ db: tx });\n const original = await journals.get(\n { id: originalJournalId },\n { cache: false },\n );\n if (\n original?.status !== 'posted' ||\n original.tenantId !== tenantId ||\n original.sourceModule !== 'smrt-commerce' ||\n original.sourceRef !== `${originalKind}:${invoiceId}:${snapshotId}` ||\n !metadataMatches(original, {\n kind: originalKind,\n invoiceId,\n moneySnapshotId: snapshotId,\n })\n )\n throw new MoneyValidationError(\n 'FROZEN_DOCUMENT',\n 'Invoice revenue journal must be posted and tenant-owned before reversal',\n );\n const originalEntries = await entriesForJournal(tx, originalJournalId);\n const reversalEntries = reverseEntries(originalEntries, currency);\n await validateAccounts(\n tx,\n tenantId,\n reversalEntries.map((entry) => entry.accountId),\n );\n const reversalKind =\n invoice.kind === 'credit_note'\n ? ('credit-note-cancellation-reversal' as const)\n : ('invoice-cancellation-reversal' as const);\n const reversalId = await deterministicId([\n reversalKind,\n tenantId,\n invoiceId,\n snapshotId,\n originalJournalId,\n ]);\n const metadata: PostingMetadata = {\n kind: reversalKind,\n invoiceId,\n moneySnapshotId: snapshotId,\n originalJournalId,\n };\n const reversal = await createOrReadPostedJournal(tx, {\n id: reversalId,\n tenantId,\n sourceRef: `invoice-cancellation:${invoiceId}:${snapshotId}`,\n description: `Cancellation reversal: Invoice ${invoice.invoiceNumber}`,\n date: new Date(),\n metadata,\n entries: reversalEntries,\n });\n if (\n invoice.arReversalJournalId &&\n invoice.arReversalJournalId !== reversalId\n )\n throw new MoneyValidationError(\n 'FROZEN_DOCUMENT',\n 'Invoice already links a different cancellation reversal',\n );\n invoice.arReversalJournalId = reversalId;\n if (invoice.status !== InvoiceStatus.CANCELLED) invoice.cancel();\n await invoice.saveDerived(DOCUMENT_MONEY_WRITE);\n callerInvoice.arReversalJournalId = reversalId;\n callerInvoice.status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