@happyvertical/smrt-commerce 0.56.0 → 0.56.2

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.
Files changed (213) hide show
  1. package/AGENTS.md +9 -8
  2. package/README.md +98 -4
  3. package/agents/accounting-snapshot-mapper.md +111 -0
  4. package/agents/contract-money.md +24 -0
  5. package/agents/cost-billing.md +7 -2
  6. package/agents/customer-vendor-ui.md +7 -1
  7. package/agents/document-money.md +127 -0
  8. package/agents/invoice-calculations.md +14 -2
  9. package/agents/line-amount-migration.md +50 -0
  10. package/agents/minor-unit-migration.md +20 -0
  11. package/agents/money-calculator.md +45 -0
  12. package/agents/money-model.md +113 -0
  13. package/agents/revenue-journal.md +23 -0
  14. package/agents/tax-codes.md +48 -0
  15. package/agents/tax-summary.md +128 -0
  16. package/dist/accounting-snapshot.d.ts +79 -0
  17. package/dist/accounting-snapshot.d.ts.map +1 -0
  18. package/dist/billing/runtime.d.ts +2 -0
  19. package/dist/billing/runtime.d.ts.map +1 -1
  20. package/dist/chunks/ContractLineItemCollection--BrGMtNz.js +265 -0
  21. package/dist/chunks/ContractLineItemCollection--BrGMtNz.js.map +1 -0
  22. package/dist/chunks/CustomerCollection-CjGaZSpf.js +99 -0
  23. package/dist/chunks/CustomerCollection-CjGaZSpf.js.map +1 -0
  24. package/dist/chunks/DocumentTaxCollection-KOkaQT2M.js +1659 -0
  25. package/dist/chunks/DocumentTaxCollection-KOkaQT2M.js.map +1 -0
  26. package/dist/chunks/InvoiceCollection-BUe_8FT1.js +1047 -0
  27. package/dist/chunks/InvoiceCollection-BUe_8FT1.js.map +1 -0
  28. package/dist/chunks/InvoiceLineItemCollection-CPQGghyd.js +468 -0
  29. package/dist/chunks/InvoiceLineItemCollection-CPQGghyd.js.map +1 -0
  30. package/dist/chunks/TaxCodeCollection-DF2eaJed.js +149 -0
  31. package/dist/chunks/TaxCodeCollection-DF2eaJed.js.map +1 -0
  32. package/dist/chunks/TaxComponentCollection-3x24xSNh.js +129 -0
  33. package/dist/chunks/TaxComponentCollection-3x24xSNh.js.map +1 -0
  34. package/dist/chunks/TaxSettingsCollection-DYYF-In-.js +319 -0
  35. package/dist/chunks/TaxSettingsCollection-DYYF-In-.js.map +1 -0
  36. package/dist/chunks/{money-DfrRxrel.js → allocation-integrity-Cq0g6CfO.js} +7 -12
  37. package/dist/chunks/allocation-integrity-Cq0g6CfO.js.map +1 -0
  38. package/dist/chunks/{calculations-Bz7RB3qK.js → calculations-DaHR17il.js} +134 -54
  39. package/dist/chunks/calculations-DaHR17il.js.map +1 -0
  40. package/dist/chunks/credit-allocation-yspz0Lab.js +121 -0
  41. package/dist/chunks/credit-allocation-yspz0Lab.js.map +1 -0
  42. package/dist/chunks/document-money-oUDvdjOf.js +860 -0
  43. package/dist/chunks/document-money-oUDvdjOf.js.map +1 -0
  44. package/dist/chunks/invoice-posting-CF3fE_Ec.js +229 -0
  45. package/dist/chunks/invoice-posting-CF3fE_Ec.js.map +1 -0
  46. package/dist/chunks/money-rational-CcW7gzG5.js +64 -0
  47. package/dist/chunks/money-rational-CcW7gzG5.js.map +1 -0
  48. package/dist/chunks/revenue-journal-DY9fro8E.js +140 -0
  49. package/dist/chunks/revenue-journal-DY9fro8E.js.map +1 -0
  50. package/dist/chunks/rolldown-runtime-D7D4PA-g.js +13 -0
  51. package/dist/chunks/tenant-money-barrier-y6EAa6vY.js +135 -0
  52. package/dist/chunks/tenant-money-barrier-y6EAa6vY.js.map +1 -0
  53. package/dist/chunks/{types-zVnIjSOk.js → types-Bbm0Xflc.js} +4 -14
  54. package/dist/chunks/types-Bbm0Xflc.js.map +1 -0
  55. package/dist/chunks/{units-BpZ0_Dpk.js → units-CNcjH_eE.js} +2 -2
  56. package/dist/chunks/{units-BpZ0_Dpk.js.map → units-CNcjH_eE.js.map} +1 -1
  57. package/dist/collections/ContractCollection.d.ts +35 -1
  58. package/dist/collections/ContractCollection.d.ts.map +1 -1
  59. package/dist/collections/ContractLineItemCollection.d.ts +26 -1
  60. package/dist/collections/ContractLineItemCollection.d.ts.map +1 -1
  61. package/dist/collections/DocumentTaxCollection.d.ts +75 -0
  62. package/dist/collections/DocumentTaxCollection.d.ts.map +1 -0
  63. package/dist/collections/InvoiceCollection.d.ts +26 -1
  64. package/dist/collections/InvoiceCollection.d.ts.map +1 -1
  65. package/dist/collections/InvoiceLineItemCollection.d.ts +26 -1
  66. package/dist/collections/InvoiceLineItemCollection.d.ts.map +1 -1
  67. package/dist/collections/MoneyMigrationDocumentCollection.d.ts +12 -0
  68. package/dist/collections/MoneyMigrationDocumentCollection.d.ts.map +1 -0
  69. package/dist/collections/PaymentAllocationCollection.d.ts +2 -0
  70. package/dist/collections/PaymentAllocationCollection.d.ts.map +1 -1
  71. package/dist/collections/TaxCodeCollection.d.ts +7 -0
  72. package/dist/collections/TaxCodeCollection.d.ts.map +1 -0
  73. package/dist/collections/TaxComponentCollection.d.ts +6 -0
  74. package/dist/collections/TaxComponentCollection.d.ts.map +1 -0
  75. package/dist/collections/TaxSettingsCollection.d.ts +16 -0
  76. package/dist/collections/TaxSettingsCollection.d.ts.map +1 -0
  77. package/dist/collections/TaxSummaryReportCollection.d.ts +151 -0
  78. package/dist/collections/TaxSummaryReportCollection.d.ts.map +1 -0
  79. package/dist/collections/index.d.ts +6 -0
  80. package/dist/collections/index.d.ts.map +1 -1
  81. package/dist/commerce-money-tools.d.ts +9 -0
  82. package/dist/commerce-money-tools.d.ts.map +1 -0
  83. package/dist/contract-money.d.ts +27 -0
  84. package/dist/contract-money.d.ts.map +1 -0
  85. package/dist/cost-billing.d.ts +0 -1
  86. package/dist/cost-billing.d.ts.map +1 -1
  87. package/dist/cost-billing.js +10 -15
  88. package/dist/cost-billing.js.map +1 -1
  89. package/dist/credit-allocation.d.ts +48 -0
  90. package/dist/credit-allocation.d.ts.map +1 -0
  91. package/dist/document-money-internal.d.ts +44 -0
  92. package/dist/document-money-internal.d.ts.map +1 -0
  93. package/dist/document-money.d.ts +85 -0
  94. package/dist/document-money.d.ts.map +1 -0
  95. package/dist/index.d.ts +15 -4
  96. package/dist/index.d.ts.map +1 -1
  97. package/dist/index.js +5411 -4249
  98. package/dist/index.js.map +1 -1
  99. package/dist/invoice-accounting-sync.d.ts +96 -0
  100. package/dist/invoice-accounting-sync.d.ts.map +1 -0
  101. package/dist/invoice-mcp.d.ts +16 -0
  102. package/dist/invoice-mcp.d.ts.map +1 -0
  103. package/dist/invoice-posting.d.ts +9 -0
  104. package/dist/invoice-posting.d.ts.map +1 -0
  105. package/dist/invoice-record-screen.d.ts +60 -0
  106. package/dist/invoice-record-screen.d.ts.map +1 -0
  107. package/dist/invoices.d.ts +2 -0
  108. package/dist/invoices.d.ts.map +1 -1
  109. package/dist/invoices.js +3 -2
  110. package/dist/manifest.json +12804 -6095
  111. package/dist/migrations/commerceLineAmounts.d.ts +84 -0
  112. package/dist/migrations/commerceLineAmounts.d.ts.map +1 -0
  113. package/dist/migrations/partyLinks.d.ts.map +1 -1
  114. package/dist/models/Contract.d.ts +34 -4
  115. package/dist/models/Contract.d.ts.map +1 -1
  116. package/dist/models/ContractLineItem.d.ts +43 -6
  117. package/dist/models/ContractLineItem.d.ts.map +1 -1
  118. package/dist/models/Customer.d.ts +7 -0
  119. package/dist/models/Customer.d.ts.map +1 -1
  120. package/dist/models/DocumentTax.d.ts +50 -0
  121. package/dist/models/DocumentTax.d.ts.map +1 -0
  122. package/dist/models/Invoice.d.ts +46 -2
  123. package/dist/models/Invoice.d.ts.map +1 -1
  124. package/dist/models/InvoiceLineItem.d.ts +46 -5
  125. package/dist/models/InvoiceLineItem.d.ts.map +1 -1
  126. package/dist/models/MoneyMigrationDocument.d.ts +28 -0
  127. package/dist/models/MoneyMigrationDocument.d.ts.map +1 -0
  128. package/dist/models/Payment.d.ts +5 -1
  129. package/dist/models/Payment.d.ts.map +1 -1
  130. package/dist/models/PaymentAllocation.d.ts.map +1 -1
  131. package/dist/models/TaxCode.d.ts +22 -0
  132. package/dist/models/TaxCode.d.ts.map +1 -0
  133. package/dist/models/TaxComponent.d.ts +21 -0
  134. package/dist/models/TaxComponent.d.ts.map +1 -0
  135. package/dist/models/TaxSettings.d.ts +33 -0
  136. package/dist/models/TaxSettings.d.ts.map +1 -0
  137. package/dist/models/TaxSummaryReport.d.ts +35 -0
  138. package/dist/models/TaxSummaryReport.d.ts.map +1 -0
  139. package/dist/models/Vendor.d.ts +9 -0
  140. package/dist/models/Vendor.d.ts.map +1 -1
  141. package/dist/models/index.d.ts +7 -1
  142. package/dist/models/index.d.ts.map +1 -1
  143. package/dist/money-rational.d.ts +15 -0
  144. package/dist/money-rational.d.ts.map +1 -0
  145. package/dist/money.d.ts +106 -25
  146. package/dist/money.d.ts.map +1 -1
  147. package/dist/money.js +274 -0
  148. package/dist/money.js.map +1 -0
  149. package/dist/recipes.d.ts +15 -15
  150. package/dist/revenue-journal.d.ts +61 -0
  151. package/dist/revenue-journal.d.ts.map +1 -0
  152. package/dist/smrt-knowledge.json +9621 -7592
  153. package/dist/svelte/components/InvoiceActions.svelte +12 -0
  154. package/dist/svelte/components/InvoiceActions.svelte.d.ts +5 -0
  155. package/dist/svelte/components/InvoiceActions.svelte.d.ts.map +1 -1
  156. package/dist/svelte/components/InvoiceEditor.svelte +15 -1
  157. package/dist/svelte/components/InvoiceEditor.svelte.d.ts.map +1 -1
  158. package/dist/svelte/components/InvoiceLineItems.svelte +3 -3
  159. package/dist/svelte/components/InvoiceRecordScreen.svelte +94 -0
  160. package/dist/svelte/components/InvoiceRecordScreen.svelte.d.ts +21 -0
  161. package/dist/svelte/components/InvoiceRecordScreen.svelte.d.ts.map +1 -0
  162. package/dist/svelte/components/InvoiceTotals.svelte +2 -2
  163. package/dist/svelte/components/MoneyInvoiceEditor.svelte +282 -0
  164. package/dist/svelte/components/MoneyInvoiceEditor.svelte.d.ts +31 -0
  165. package/dist/svelte/components/MoneyInvoiceEditor.svelte.d.ts.map +1 -0
  166. package/dist/svelte/components/PurchaseOrderEditor.svelte +53 -1
  167. package/dist/svelte/components/PurchaseOrderEditor.svelte.d.ts +5 -0
  168. package/dist/svelte/components/PurchaseOrderEditor.svelte.d.ts.map +1 -1
  169. package/dist/svelte/components/QuoteEditor.svelte +54 -1
  170. package/dist/svelte/components/QuoteEditor.svelte.d.ts +5 -0
  171. package/dist/svelte/components/QuoteEditor.svelte.d.ts.map +1 -1
  172. package/dist/svelte/i18n.d.ts +16 -0
  173. package/dist/svelte/i18n.d.ts.map +1 -1
  174. package/dist/svelte/i18n.js +16 -0
  175. package/dist/svelte/index.d.ts +7 -2
  176. package/dist/svelte/index.d.ts.map +1 -1
  177. package/dist/svelte/index.js +4 -1
  178. package/dist/svelte/invoices/calculations.d.ts +7 -2
  179. package/dist/svelte/invoices/calculations.d.ts.map +1 -1
  180. package/dist/svelte/invoices/calculations.js +141 -47
  181. package/dist/svelte/invoices/money-editor.d.ts +123 -0
  182. package/dist/svelte/invoices/money-editor.d.ts.map +1 -0
  183. package/dist/svelte/invoices/money-editor.js +101 -0
  184. package/dist/svelte/invoices/types.d.ts +5 -1
  185. package/dist/svelte/invoices/types.d.ts.map +1 -1
  186. package/dist/svelte/purchasing-i18n.d.ts +5 -0
  187. package/dist/svelte/purchasing-i18n.d.ts.map +1 -1
  188. package/dist/svelte/purchasing-i18n.js +5 -0
  189. package/dist/svelte/quote-i18n.d.ts +5 -0
  190. package/dist/svelte/quote-i18n.d.ts.map +1 -1
  191. package/dist/svelte/quote-i18n.js +5 -0
  192. package/dist/tax/cookbook.d.ts +22 -0
  193. package/dist/tax/cookbook.d.ts.map +1 -0
  194. package/dist/tax/example-pack.d.ts +25 -0
  195. package/dist/tax/example-pack.d.ts.map +1 -0
  196. package/dist/tax/identity.d.ts +5 -0
  197. package/dist/tax/identity.d.ts.map +1 -0
  198. package/dist/tax/index.d.ts +4 -0
  199. package/dist/tax/index.d.ts.map +1 -0
  200. package/dist/tax/legacy.d.ts +48 -0
  201. package/dist/tax/legacy.d.ts.map +1 -0
  202. package/dist/tax-summary-report-adapter.d.ts +37 -0
  203. package/dist/tax-summary-report-adapter.d.ts.map +1 -0
  204. package/dist/tax-summary.d.ts +129 -0
  205. package/dist/tax-summary.d.ts.map +1 -0
  206. package/dist/tenant-money-barrier.d.ts +66 -0
  207. package/dist/tenant-money-barrier.d.ts.map +1 -0
  208. package/dist/types/index.d.ts +138 -1
  209. package/dist/types/index.d.ts.map +1 -1
  210. package/package.json +19 -11
  211. package/dist/chunks/calculations-Bz7RB3qK.js.map +0 -1
  212. package/dist/chunks/money-DfrRxrel.js.map +0 -1
  213. package/dist/chunks/types-zVnIjSOk.js.map +0 -1
@@ -0,0 +1,140 @@
1
+ import { MoneyValidationError } from "../money.js";
2
+ import { ISO_4217_MINOR_UNITS } from "@happyvertical/smrt-ui/currency";
3
+ //#region src/revenue-journal.ts
4
+ var MAX_SAFE_MONEY = BigInt(Number.MAX_SAFE_INTEGER);
5
+ function fail(code, message) {
6
+ throw new MoneyValidationError(code, message);
7
+ }
8
+ function identifier(value, label) {
9
+ if (typeof value !== "string" || value.length === 0 || value.trim() !== value) fail("INVALID_MONEY_INPUT", `${label} must be a nonempty value`);
10
+ return value;
11
+ }
12
+ function money(value, label) {
13
+ if (!Number.isSafeInteger(value)) fail("UNSAFE_MONEY", `${label} must be safe integer minor units`);
14
+ return BigInt(value);
15
+ }
16
+ function safe(value, label) {
17
+ if (value > MAX_SAFE_MONEY || value < -MAX_SAFE_MONEY) fail("UNSAFE_MONEY", `${label} exceeds safe integer minor units`);
18
+ return Number(value);
19
+ }
20
+ function currency(value, label) {
21
+ if (typeof value !== "string" || value !== value.toUpperCase() || !ISO_4217_MINOR_UNITS.has(value) || ISO_4217_MINOR_UNITS.get(value) === null) fail("INVALID_MONEY_INPUT", `${label} must be a supported ISO 4217 code`);
22
+ return value;
23
+ }
24
+ function compareCodeUnits(left, right) {
25
+ return left < right ? -1 : left > right ? 1 : 0;
26
+ }
27
+ function add(group, key, value) {
28
+ group.set(key, (group.get(key) ?? 0n) + value);
29
+ }
30
+ function entry(accountId, movement, documentCurrency, memo) {
31
+ if (movement === 0n) return null;
32
+ const amount = safe(movement < 0n ? -movement : movement, "Journal entry");
33
+ return movement > 0n ? {
34
+ accountId,
35
+ debit: amount,
36
+ currency: documentCurrency,
37
+ memo
38
+ } : {
39
+ accountId,
40
+ credit: amount,
41
+ currency: documentCurrency,
42
+ memo
43
+ };
44
+ }
45
+ function buildRevenueJournalEntries(document, lines, taxes, options) {
46
+ identifier(document.id, "Document ID");
47
+ const documentCurrency = currency(document.currency, "Document currency");
48
+ const bookCurrency = currency(options.bookCurrency, "Book currency");
49
+ if (documentCurrency !== bookCurrency) fail("CURRENCY_MISMATCH", `Document currency ${documentCurrency} does not match book currency ${bookCurrency}`);
50
+ if (document.lineAmountType !== "exclusive" && document.lineAmountType !== "inclusive" && document.lineAmountType !== "none") fail("INVALID_MONEY_INPUT", "Unknown line amount type");
51
+ if (options.direction !== void 0 && options.direction !== 1 && options.direction !== -1) fail("INVALID_MONEY_INPUT", "Journal direction must be 1 or -1");
52
+ const direction = BigInt(options.direction ?? 1);
53
+ const arAccountId = identifier(options.arAccountId, "AR account ID");
54
+ const fallbackRevenue = identifier(options.revenueAccountId, "Revenue account ID");
55
+ const fallbackTax = options.taxAccountId ?? null;
56
+ if (fallbackTax !== null) identifier(fallbackTax, "Tax account ID");
57
+ const subtotal = money(document.subtotalMinor, "Document subtotal");
58
+ const documentTax = money(document.taxMinor, "Document tax");
59
+ const total = money(document.totalMinor, "Document total");
60
+ const providerTax = money(document.providerTaxMinor, "Provider tax");
61
+ if (subtotal + documentTax !== total) fail("INVALID_MONEY_INPUT", "Document subtotal plus tax must equal total");
62
+ const revenueGroups = /* @__PURE__ */ new Map();
63
+ const lineIds = /* @__PURE__ */ new Set();
64
+ let lineNetTotal = 0n;
65
+ let lineTaxTotal = 0n;
66
+ for (const line of lines) {
67
+ const lineId = identifier(line.id, "Line ID");
68
+ if (lineIds.has(lineId)) fail("INVALID_MONEY_INPUT", `Duplicate line ID: ${lineId}`);
69
+ lineIds.add(lineId);
70
+ const amount = money(line.amountMinor, `Line ${lineId} amount`);
71
+ const tax = money(line.taxMinor, `Line ${lineId} tax`);
72
+ const net = document.lineAmountType === "inclusive" ? amount - tax : amount;
73
+ add(revenueGroups, line.revenueAccountId ? identifier(line.revenueAccountId, `Line ${lineId} revenue account ID`) : fallbackRevenue, net);
74
+ lineNetTotal += net;
75
+ lineTaxTotal += tax;
76
+ }
77
+ if (lineNetTotal !== subtotal) fail("INVALID_MONEY_INPUT", "Stored line net total does not match document subtotal");
78
+ if (lineTaxTotal + providerTax !== documentTax) fail("INVALID_MONEY_INPUT", "Stored line tax plus provider tax does not match document tax");
79
+ const taxGroups = /* @__PURE__ */ new Map();
80
+ const warnings = [];
81
+ const taxRowIds = /* @__PURE__ */ new Set();
82
+ let componentTaxTotal = 0n;
83
+ for (const row of taxes) {
84
+ if (currency(row.currency, "DocumentTax currency") !== documentCurrency) fail("CURRENCY_MISMATCH", "DocumentTax currency does not match document currency");
85
+ const tax = money(row.taxMinor, "DocumentTax tax");
86
+ if (tax === 0n) continue;
87
+ if (row.taxComponentId === null) fail("INVALID_MONEY_INPUT", "A nonzero DocumentTax row requires a component");
88
+ const componentId = identifier(row.taxComponentId, "Tax component ID");
89
+ const taxCodeId = identifier(row.taxCodeId, "Tax code ID");
90
+ const taxCodeCode = identifier(row.taxCodeCode, "Tax code code");
91
+ const taxRowId = `${taxCodeId}\0${componentId}`;
92
+ if (taxRowIds.has(taxRowId)) fail("INVALID_MONEY_INPUT", `Duplicate DocumentTax code/component row: ${taxCodeId}/${componentId}`);
93
+ taxRowIds.add(taxRowId);
94
+ const accountId = row.liabilityAccountId ? identifier(row.liabilityAccountId, "Tax liability account ID") : fallbackTax;
95
+ if (accountId === null) fail("INVALID_MONEY_INPUT", `Tax component ${componentId} has no posting account`);
96
+ add(taxGroups, accountId, tax);
97
+ componentTaxTotal += tax;
98
+ if (row.liabilityAccountId === null && taxCodeCode.startsWith("legacy-")) warnings.push({
99
+ code: "LEGACY_TAX_ACCOUNT_FALLBACK",
100
+ taxCodeId,
101
+ taxCodeCode,
102
+ taxComponentId: componentId,
103
+ accountId
104
+ });
105
+ }
106
+ if (componentTaxTotal !== lineTaxTotal) fail("INVALID_MONEY_INPUT", "Stored component tax does not match stored line tax");
107
+ if (providerTax !== 0n && fallbackTax === null) fail("INVALID_MONEY_INPUT", "Provider tax requires a fallback tax account");
108
+ const label = document.number ?? document.id;
109
+ const entries = [];
110
+ const ar = entry(arAccountId, total * direction, documentCurrency, `Receivable: ${label}`);
111
+ if (ar) entries.push(ar);
112
+ for (const [accountId, amount] of [...revenueGroups].sort(([a], [b]) => compareCodeUnits(a, b))) {
113
+ const built = entry(accountId, -amount * direction, documentCurrency, `Revenue: ${label}`);
114
+ if (built) entries.push(built);
115
+ }
116
+ for (const [accountId, amount] of [...taxGroups].sort(([a], [b]) => compareCodeUnits(a, b))) {
117
+ const built = entry(accountId, -amount * direction, documentCurrency, `Tax: ${label}`);
118
+ if (built) entries.push(built);
119
+ }
120
+ if (providerTax !== 0n) {
121
+ const built = entry(fallbackTax, -providerTax * direction, documentCurrency, `Provider tax: ${label}`);
122
+ if (built) entries.push(built);
123
+ }
124
+ let debits = 0n;
125
+ let credits = 0n;
126
+ for (const built of entries) {
127
+ debits += BigInt(built.debit ?? 0);
128
+ credits += BigInt(built.credit ?? 0);
129
+ }
130
+ if (debits !== credits) fail("INVALID_MONEY_INPUT", "Built journal entries are not balanced");
131
+ safe(debits, "Journal debit total");
132
+ return {
133
+ entries,
134
+ warnings
135
+ };
136
+ }
137
+ //#endregion
138
+ export { buildRevenueJournalEntries as t };
139
+
140
+ //# sourceMappingURL=revenue-journal-DY9fro8E.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"revenue-journal-DY9fro8E.js","names":[],"sources":["../../src/revenue-journal.ts"],"sourcesContent":["/** Pure journal-entry construction from frozen commercial money snapshots. */\n\nimport { ISO_4217_MINOR_UNITS } from '@happyvertical/smrt-ui/currency';\nimport { MoneyValidationError } from './money.js';\n\nconst MAX_SAFE_MONEY = BigInt(Number.MAX_SAFE_INTEGER);\n\nexport interface RevenueJournalDocumentInput {\n id: string;\n number?: string | null;\n currency: string;\n lineAmountType: 'exclusive' | 'inclusive' | 'none';\n subtotalMinor: number;\n taxMinor: number;\n totalMinor: number;\n providerTaxMinor: number;\n}\n\nexport interface RevenueJournalLineInput {\n id: string;\n /** Stored gross-for-inclusive or net-for-exclusive line amount. */\n amountMinor: number;\n /** Stored total line tax, excluding document-level provider tax. */\n taxMinor: number;\n revenueAccountId?: string | null;\n}\n\n/** Stored DocumentTax snapshot fields used by revenue posting. */\nexport interface RevenueJournalTaxInput {\n currency: string;\n taxCodeId: string | null;\n taxCodeCode: string | null;\n taxComponentId: string | null;\n liabilityAccountId: string | null;\n taxMinor: number;\n}\n\nexport interface RevenueJournalOptions {\n arAccountId: string;\n revenueAccountId: string;\n taxAccountId?: string | null;\n /** Explicit ledger book currency; conversion is outside this helper. */\n bookCurrency: string;\n /** Use -1 for an exact reversal or credit direction. */\n direction?: 1 | -1;\n}\n\nexport interface RevenueJournalEntry {\n accountId: string;\n debit?: number;\n credit?: number;\n currency: string;\n memo: string;\n}\n\nexport interface RevenueJournalWarning {\n code: 'LEGACY_TAX_ACCOUNT_FALLBACK';\n taxCodeId: string;\n taxCodeCode: string;\n taxComponentId: string;\n accountId: string;\n}\n\nexport interface RevenueJournalResult {\n entries: RevenueJournalEntry[];\n warnings: RevenueJournalWarning[];\n}\n\nfunction fail(\n code: 'INVALID_MONEY_INPUT' | 'UNSAFE_MONEY' | 'CURRENCY_MISMATCH',\n message: string,\n): never {\n throw new MoneyValidationError(code, message);\n}\n\nfunction identifier(value: string | null | undefined, label: string): string {\n if (typeof value !== 'string' || value.length === 0 || value.trim() !== value)\n fail('INVALID_MONEY_INPUT', `${label} must be a nonempty value`);\n return value;\n}\n\nfunction money(value: number, label: string): bigint {\n if (!Number.isSafeInteger(value))\n fail('UNSAFE_MONEY', `${label} must be safe integer minor units`);\n return BigInt(value);\n}\n\nfunction safe(value: bigint, label: string): number {\n if (value > MAX_SAFE_MONEY || value < -MAX_SAFE_MONEY)\n fail('UNSAFE_MONEY', `${label} exceeds safe integer minor units`);\n return Number(value);\n}\n\nfunction currency(value: string, label: string): string {\n if (\n typeof value !== 'string' ||\n value !== value.toUpperCase() ||\n !ISO_4217_MINOR_UNITS.has(value) ||\n ISO_4217_MINOR_UNITS.get(value) === null\n ) {\n fail('INVALID_MONEY_INPUT', `${label} must be a supported ISO 4217 code`);\n }\n return value;\n}\n\nfunction compareCodeUnits(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0;\n}\n\nfunction add(group: Map<string, bigint>, key: string, value: bigint): void {\n group.set(key, (group.get(key) ?? 0n) + value);\n}\n\nfunction entry(\n accountId: string,\n movement: bigint,\n documentCurrency: string,\n memo: string,\n): RevenueJournalEntry | null {\n if (movement === 0n) return null;\n const amount = safe(movement < 0n ? -movement : movement, 'Journal entry');\n return movement > 0n\n ? { accountId, debit: amount, currency: documentCurrency, memo }\n : { accountId, credit: amount, currency: documentCurrency, memo };\n}\n\n/**\n * Build balanced entries from persisted values only. Positive source amounts\n * debit receivables and credit revenue/tax; direction -1 swaps those sides.\n */\nexport function buildRevenueJournalEntries(\n document: RevenueJournalDocumentInput,\n lines: readonly RevenueJournalLineInput[],\n taxes: readonly RevenueJournalTaxInput[],\n options: RevenueJournalOptions,\n): RevenueJournalResult {\n identifier(document.id, 'Document ID');\n const documentCurrency = currency(document.currency, 'Document currency');\n const bookCurrency = currency(options.bookCurrency, 'Book currency');\n if (documentCurrency !== bookCurrency)\n fail(\n 'CURRENCY_MISMATCH',\n `Document currency ${documentCurrency} does not match book currency ${bookCurrency}`,\n );\n if (\n document.lineAmountType !== 'exclusive' &&\n document.lineAmountType !== 'inclusive' &&\n document.lineAmountType !== 'none'\n ) {\n fail('INVALID_MONEY_INPUT', 'Unknown line amount type');\n }\n if (\n options.direction !== undefined &&\n options.direction !== 1 &&\n options.direction !== -1\n )\n fail('INVALID_MONEY_INPUT', 'Journal direction must be 1 or -1');\n const direction = BigInt(options.direction ?? 1);\n const arAccountId = identifier(options.arAccountId, 'AR account ID');\n const fallbackRevenue = identifier(\n options.revenueAccountId,\n 'Revenue account ID',\n );\n const fallbackTax = options.taxAccountId ?? null;\n if (fallbackTax !== null) identifier(fallbackTax, 'Tax account ID');\n\n const subtotal = money(document.subtotalMinor, 'Document subtotal');\n const documentTax = money(document.taxMinor, 'Document tax');\n const total = money(document.totalMinor, 'Document total');\n const providerTax = money(document.providerTaxMinor, 'Provider tax');\n if (subtotal + documentTax !== total)\n fail('INVALID_MONEY_INPUT', 'Document subtotal plus tax must equal total');\n\n const revenueGroups = new Map<string, bigint>();\n const lineIds = new Set<string>();\n let lineNetTotal = 0n;\n let lineTaxTotal = 0n;\n for (const line of lines) {\n const lineId = identifier(line.id, 'Line ID');\n if (lineIds.has(lineId))\n fail('INVALID_MONEY_INPUT', `Duplicate line ID: ${lineId}`);\n lineIds.add(lineId);\n const amount = money(line.amountMinor, `Line ${lineId} amount`);\n const tax = money(line.taxMinor, `Line ${lineId} tax`);\n const net = document.lineAmountType === 'inclusive' ? amount - tax : amount;\n const accountId = line.revenueAccountId\n ? identifier(line.revenueAccountId, `Line ${lineId} revenue account ID`)\n : fallbackRevenue;\n add(revenueGroups, accountId, net);\n lineNetTotal += net;\n lineTaxTotal += tax;\n }\n if (lineNetTotal !== subtotal)\n fail(\n 'INVALID_MONEY_INPUT',\n 'Stored line net total does not match document subtotal',\n );\n if (lineTaxTotal + providerTax !== documentTax)\n fail(\n 'INVALID_MONEY_INPUT',\n 'Stored line tax plus provider tax does not match document tax',\n );\n\n const taxGroups = new Map<string, bigint>();\n const warnings: RevenueJournalWarning[] = [];\n const taxRowIds = new Set<string>();\n let componentTaxTotal = 0n;\n for (const row of taxes) {\n if (currency(row.currency, 'DocumentTax currency') !== documentCurrency)\n fail(\n 'CURRENCY_MISMATCH',\n 'DocumentTax currency does not match document currency',\n );\n const tax = money(row.taxMinor, 'DocumentTax tax');\n if (tax === 0n) continue;\n if (row.taxComponentId === null)\n fail(\n 'INVALID_MONEY_INPUT',\n 'A nonzero DocumentTax row requires a component',\n );\n const componentId = identifier(row.taxComponentId, 'Tax component ID');\n const taxCodeId = identifier(row.taxCodeId, 'Tax code ID');\n const taxCodeCode = identifier(row.taxCodeCode, 'Tax code code');\n const taxRowId = `${taxCodeId}\\0${componentId}`;\n if (taxRowIds.has(taxRowId))\n fail(\n 'INVALID_MONEY_INPUT',\n `Duplicate DocumentTax code/component row: ${taxCodeId}/${componentId}`,\n );\n taxRowIds.add(taxRowId);\n const accountId = row.liabilityAccountId\n ? identifier(row.liabilityAccountId, 'Tax liability account ID')\n : fallbackTax;\n if (accountId === null)\n fail(\n 'INVALID_MONEY_INPUT',\n `Tax component ${componentId} has no posting account`,\n );\n add(taxGroups, accountId, tax);\n componentTaxTotal += tax;\n if (row.liabilityAccountId === null && taxCodeCode.startsWith('legacy-')) {\n warnings.push({\n code: 'LEGACY_TAX_ACCOUNT_FALLBACK',\n taxCodeId,\n taxCodeCode,\n taxComponentId: componentId,\n accountId,\n });\n }\n }\n if (componentTaxTotal !== lineTaxTotal)\n fail(\n 'INVALID_MONEY_INPUT',\n 'Stored component tax does not match stored line tax',\n );\n if (providerTax !== 0n && fallbackTax === null)\n fail('INVALID_MONEY_INPUT', 'Provider tax requires a fallback tax account');\n\n const label = document.number ?? document.id;\n const entries: RevenueJournalEntry[] = [];\n const ar = entry(\n arAccountId,\n total * direction,\n documentCurrency,\n `Receivable: ${label}`,\n );\n if (ar) entries.push(ar);\n for (const [accountId, amount] of [...revenueGroups].sort(([a], [b]) =>\n compareCodeUnits(a, b),\n )) {\n const built = entry(\n accountId,\n -amount * direction,\n documentCurrency,\n `Revenue: ${label}`,\n );\n if (built) entries.push(built);\n }\n for (const [accountId, amount] of [...taxGroups].sort(([a], [b]) =>\n compareCodeUnits(a, b),\n )) {\n const built = entry(\n accountId,\n -amount * direction,\n documentCurrency,\n `Tax: ${label}`,\n );\n if (built) entries.push(built);\n }\n if (providerTax !== 0n) {\n const built = entry(\n fallbackTax as string,\n -providerTax * direction,\n documentCurrency,\n `Provider tax: ${label}`,\n );\n if (built) entries.push(built);\n }\n\n let debits = 0n;\n let credits = 0n;\n for (const built of entries) {\n debits += BigInt(built.debit ?? 0);\n credits += BigInt(built.credit ?? 0);\n }\n if (debits !== credits)\n fail('INVALID_MONEY_INPUT', 'Built journal entries are not balanced');\n safe(debits, 'Journal debit total');\n return { entries, warnings };\n}\n"],"mappings":";;;AAKA,IAAM,iBAAiB,OAAO,OAAO,gBAAgB;AA+DrD,SAAS,KACP,MACA,SACO;CACP,MAAM,IAAI,qBAAqB,MAAM,OAAO;AAC9C;AAEA,SAAS,WAAW,OAAkC,OAAuB;CAC3E,IAAI,OAAO,UAAU,YAAY,MAAM,WAAW,KAAK,MAAM,KAAK,MAAM,OACtE,KAAK,uBAAuB,GAAG,MAAK,0BAA2B;CACjE,OAAO;AACT;AAEA,SAAS,MAAM,OAAe,OAAuB;CACnD,IAAI,CAAC,OAAO,cAAc,KAAK,GAC7B,KAAK,gBAAgB,GAAG,MAAK,kCAAmC;CAClE,OAAO,OAAO,KAAK;AACrB;AAEA,SAAS,KAAK,OAAe,OAAuB;CAClD,IAAI,QAAQ,kBAAkB,QAAQ,CAAC,gBACrC,KAAK,gBAAgB,GAAG,MAAK,kCAAmC;CAClE,OAAO,OAAO,KAAK;AACrB;AAEA,SAAS,SAAS,OAAe,OAAuB;CACtD,IACE,OAAO,UAAU,YACjB,UAAU,MAAM,YAAY,KAC5B,CAAC,qBAAqB,IAAI,KAAK,KAC/B,qBAAqB,IAAI,KAAK,MAAM,MAEpC,KAAK,uBAAuB,GAAG,MAAK,mCAAoC;CAE1E,OAAO;AACT;AAEA,SAAS,iBAAiB,MAAc,OAAuB;CAC7D,OAAO,OAAO,QAAQ,KAAK,OAAO,QAAQ,IAAI;AAChD;AAEA,SAAS,I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AS,SAAS;EAC3B,UAAU,OAAO,MAAM,SAAS,CAAC;EACjC,WAAW,OAAO,MAAM,UAAU,CAAC;CACrC;CACA,IAAI,WAAW,SACb,KAAK,uBAAuB,wCAAwC;CACtE,KAAK,QAAQ,qBAAqB;CAClC,OAAO;EAAE;EAAS;CAAS;AAC7B"}
@@ -0,0 +1,13 @@
1
+ //#region \0rolldown/runtime.js
2
+ var __defProp = Object.defineProperty;
3
+ var __exportAll = (all, no_symbols) => {
4
+ let target = {};
5
+ for (var name in all) __defProp(target, name, {
6
+ get: all[name],
7
+ enumerable: true
8
+ });
9
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
10
+ return target;
11
+ };
12
+ //#endregion
13
+ export { __exportAll as t };
@@ -0,0 +1,135 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
2
+ import { MoneyValidationError } from "../money.js";
3
+ import { t as TaxSettingsCollection, u as withDocumentMoneyTransaction } from "./TaxSettingsCollection-DYYF-In-.js";
4
+ //#region src/tenant-money-barrier.ts
5
+ var tenant_money_barrier_exports = /* @__PURE__ */ __exportAll({
6
+ lockTenantMoneyMigrationClaim: () => lockTenantMoneyMigrationClaim,
7
+ lockTenantMoneyMigrationOwner: () => lockTenantMoneyMigrationOwner,
8
+ lockTenantMoneyRuntime: () => lockTenantMoneyRuntime,
9
+ withTenantMoneyCollectionRead: () => withTenantMoneyCollectionRead,
10
+ withTenantMoneyMigration: () => withTenantMoneyMigration,
11
+ withTenantMoneyRuntime: () => withTenantMoneyRuntime
12
+ });
13
+ function requiredText(value, label) {
14
+ if (!value || value.trim() !== value) throw new MoneyValidationError("INVALID_MONEY_INPUT", `${label} must be a nonempty trimmed string`);
15
+ return value;
16
+ }
17
+ async function hasSettingsStorage(db) {
18
+ return !db.tableExists || await db.tableExists("tax_settings");
19
+ }
20
+ var activeRuntimeScopes = /* @__PURE__ */ new WeakMap();
21
+ var activeMigrationScopes = /* @__PURE__ */ new WeakMap();
22
+ function runtimeScope(db, tenantId, barrier) {
23
+ return {
24
+ db,
25
+ tenantId,
26
+ barrier,
27
+ phase: "runtime"
28
+ };
29
+ }
30
+ async function lockTenantMoneyRuntime(tx, tenantId, requirement = "legacy-or-v2") {
31
+ requiredText(tenantId, "Money tenant");
32
+ if (!await hasSettingsStorage(tx)) {
33
+ if (requirement === "v2") throw new MoneyValidationError("INVALID_MONEY_INPUT", "Money v2 requires tenant tax settings storage");
34
+ return {
35
+ moneyModel: "legacy",
36
+ settings: null,
37
+ persistedBarrier: false
38
+ };
39
+ }
40
+ const settings = await (await TaxSettingsCollection.create({ db: tx })).lockForTenant(tenantId);
41
+ if (!settings) throw new MoneyValidationError("INVALID_MONEY_INPUT", "Tenant money settings could not be materialized");
42
+ if (settings.moneyModel === "migrating") throw new MoneyValidationError("FROZEN_DOCUMENT", "Tenant money migration is in progress");
43
+ if (settings.moneyModel === "v2") return {
44
+ moneyModel: "v2",
45
+ settings,
46
+ persistedBarrier: true
47
+ };
48
+ if (requirement === "v2") throw new MoneyValidationError("INVALID_MONEY_INPUT", "Money v2 is not active for this tenant");
49
+ return {
50
+ moneyModel: "legacy",
51
+ settings,
52
+ persistedBarrier: true
53
+ };
54
+ }
55
+ async function withTenantMoneyRuntime(db, tenantId, requirement, operation, existingScope) {
56
+ requiredText(tenantId, "Money tenant");
57
+ if (existingScope) {
58
+ if (existingScope.phase !== "runtime" || existingScope.db !== db || existingScope.tenantId !== tenantId || requirement === "v2" && existingScope.barrier.moneyModel !== "v2") throw new MoneyValidationError("INVALID_MONEY_INPUT", "Tenant money runtime scope does not match the requested executor");
59
+ return operation(existingScope);
60
+ }
61
+ return withDocumentMoneyTransaction(db, async (tx) => {
62
+ const active = activeRuntimeScopes.get(tx)?.get(tenantId);
63
+ if (active) {
64
+ if (requirement === "v2" && active.barrier.moneyModel !== "v2") throw new MoneyValidationError("INVALID_MONEY_INPUT", "Money v2 is not active for this tenant");
65
+ return operation(active);
66
+ }
67
+ const scope = runtimeScope(tx, tenantId, await lockTenantMoneyRuntime(tx, tenantId, requirement));
68
+ const scopes = activeRuntimeScopes.get(tx) ?? /* @__PURE__ */ new Map();
69
+ scopes.set(tenantId, scope);
70
+ activeRuntimeScopes.set(tx, scopes);
71
+ try {
72
+ return await operation(scope);
73
+ } finally {
74
+ scopes.delete(tenantId);
75
+ if (scopes.size === 0) activeRuntimeScopes.delete(tx);
76
+ }
77
+ });
78
+ }
79
+ async function withTenantMoneyMigration(db, tenantId, migrationId, operation, existingScope) {
80
+ requiredText(tenantId, "Money migration tenant");
81
+ requiredText(migrationId, "Money migration owner");
82
+ if (existingScope) {
83
+ if (existingScope.phase !== "migration" || existingScope.db !== db || existingScope.tenantId !== tenantId || existingScope.migrationId !== migrationId) throw new MoneyValidationError("INVALID_MONEY_INPUT", "Tenant money migration scope does not match the requested executor");
84
+ return operation(existingScope);
85
+ }
86
+ return withDocumentMoneyTransaction(db, async (tx) => {
87
+ const active = activeMigrationScopes.get(tx)?.get(tenantId);
88
+ if (active) {
89
+ if (active.migrationId !== migrationId) throw new MoneyValidationError("FROZEN_DOCUMENT", "Tenant money migration owner does not match");
90
+ return operation(active);
91
+ }
92
+ const scope = {
93
+ db: tx,
94
+ tenantId,
95
+ migrationId,
96
+ settings: await lockTenantMoneyMigrationOwner(tx, tenantId, migrationId),
97
+ phase: "migration"
98
+ };
99
+ const scopes = activeMigrationScopes.get(tx) ?? /* @__PURE__ */ new Map();
100
+ scopes.set(tenantId, scope);
101
+ activeMigrationScopes.set(tx, scopes);
102
+ try {
103
+ return await operation(scope);
104
+ } finally {
105
+ scopes.delete(tenantId);
106
+ if (scopes.size === 0) activeMigrationScopes.delete(tx);
107
+ }
108
+ });
109
+ }
110
+ async function withTenantMoneyCollectionRead(db, tenantId, operation) {
111
+ const migration = activeMigrationScopes.get(db)?.get(tenantId);
112
+ if (migration) return operation(migration.db);
113
+ return withTenantMoneyRuntime(db, tenantId, "legacy-or-v2", (scope) => operation(scope.db));
114
+ }
115
+ async function lockTenantMoneyMigrationClaim(tx, tenantId) {
116
+ requiredText(tenantId, "Money migration tenant");
117
+ if (!await hasSettingsStorage(tx)) throw new MoneyValidationError("INVALID_MONEY_INPUT", "Money migration requires installed tax settings storage");
118
+ const settings = await (await TaxSettingsCollection.create({ db: tx })).lockForTenant(tenantId);
119
+ if (!settings) throw new MoneyValidationError("INVALID_MONEY_INPUT", "Tenant money settings could not be materialized");
120
+ if (settings.moneyModel === "v2") throw new MoneyValidationError("FROZEN_DOCUMENT", "Tenant money model is already v2");
121
+ if (settings.moneyModel === "migrating") throw new MoneyValidationError("FROZEN_DOCUMENT", "Tenant money migration is already in progress");
122
+ return settings;
123
+ }
124
+ async function lockTenantMoneyMigrationOwner(tx, tenantId, migrationId) {
125
+ requiredText(tenantId, "Money migration tenant");
126
+ requiredText(migrationId, "Money migration owner");
127
+ if (!await hasSettingsStorage(tx)) throw new MoneyValidationError("INVALID_MONEY_INPUT", "Money migration requires installed tax settings storage");
128
+ const settings = await (await TaxSettingsCollection.create({ db: tx })).lockForTenant(tenantId, false);
129
+ if (settings?.moneyModel !== "migrating" || settings.moneyMigrationId !== migrationId) throw new MoneyValidationError("FROZEN_DOCUMENT", "Tenant money migration owner does not match");
130
+ return settings;
131
+ }
132
+ //#endregion
133
+ export { withTenantMoneyMigration as a, withTenantMoneyCollectionRead as i, lockTenantMoneyRuntime as n, withTenantMoneyRuntime as o, tenant_money_barrier_exports as r, lockTenantMoneyMigrationOwner as t };
134
+
135
+ //# sourceMappingURL=tenant-money-barrier-y6EAa6vY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tenant-money-barrier-y6EAa6vY.js","names":[],"sources":["../../src/tenant-money-barrier.ts"],"sourcesContent":["/** Shared tenant serialization barrier for commerce money runtime and migration. */\n\nimport type { DatabaseInterface } from '@happyvertical/smrt-core/migrations';\nimport { TaxSettingsCollection } from './collections/TaxSettingsCollection.js';\nimport { withDocumentMoneyTransaction } from './document-money-internal.js';\nimport type { TaxSettings } from './models/TaxSettings.js';\nimport { MoneyValidationError } from './money.js';\n\nexport type TenantMoneyRuntimeRequirement = 'legacy-or-v2' | 'v2';\n\nexport type TenantMoneyRuntimeBarrier =\n | {\n readonly moneyModel: 'legacy';\n readonly settings: null;\n readonly persistedBarrier: false;\n }\n | {\n readonly moneyModel: 'legacy';\n readonly settings: TaxSettings;\n readonly persistedBarrier: true;\n }\n | {\n readonly moneyModel: 'v2';\n readonly settings: TaxSettings;\n readonly persistedBarrier: true;\n };\n\ndeclare const tenantMoneyScopeBrand: unique symbol;\n\n/** Transaction-affine proof that a tenant marker is locked on `db`. */\nexport interface TenantMoneyRuntimeScope {\n readonly db: DatabaseInterface;\n readonly tenantId: string;\n readonly barrier: TenantMoneyRuntimeBarrier;\n readonly phase: 'runtime';\n readonly [tenantMoneyScopeBrand]: true;\n}\n\ndeclare const tenantMoneyMigrationScopeBrand: unique symbol;\n\n/** Transaction-affine proof held only by the active migration owner. */\nexport interface TenantMoneyMigrationScope {\n readonly db: DatabaseInterface;\n readonly tenantId: string;\n readonly migrationId: string;\n readonly settings: TaxSettings;\n readonly phase: 'migration';\n readonly [tenantMoneyMigrationScopeBrand]: true;\n}\n\nfunction requiredText(value: string, label: string): string {\n if (!value || value.trim() !== value)\n throw new MoneyValidationError(\n 'INVALID_MONEY_INPUT',\n `${label} must be a nonempty trimmed string`,\n );\n return value;\n}\n\nasync function hasSettingsStorage(db: DatabaseInterface): Promise<boolean> {\n return !db.tableExists || (await db.tableExists('tax_settings'));\n}\n\nconst activeRuntimeScopes = new WeakMap<\n object,\n Map<string, TenantMoneyRuntimeScope>\n>();\nconst activeMigrationScopes = new WeakMap<\n object,\n Map<string, TenantMoneyMigrationScope>\n>();\n\nfunction runtimeScope(\n db: DatabaseInterface,\n tenantId: string,\n barrier: TenantMoneyRuntimeBarrier,\n): TenantMoneyRuntimeScope {\n return {\n db,\n tenantId,\n barrier,\n phase: 'runtime',\n } as TenantMoneyRuntimeScope;\n}\n\n/**\n * Lock and re-read the tenant money marker before any runtime money work.\n *\n * Older schemas without TaxSettings stay byte-compatible legacy and are never\n * modified. Once the table exists, a missing deterministic legacy row is\n * materialized solely to provide the serialization point shared by migration.\n */\nexport async function lockTenantMoneyRuntime(\n tx: DatabaseInterface,\n tenantId: string,\n requirement: TenantMoneyRuntimeRequirement = 'legacy-or-v2',\n): Promise<TenantMoneyRuntimeBarrier> {\n requiredText(tenantId, 'Money tenant');\n if (!(await hasSettingsStorage(tx))) {\n if (requirement === 'v2')\n throw new MoneyValidationError(\n 'INVALID_MONEY_INPUT',\n 'Money v2 requires tenant tax settings storage',\n );\n return {\n moneyModel: 'legacy',\n settings: null,\n persistedBarrier: false,\n };\n }\n const collection = await TaxSettingsCollection.create({ db: tx });\n const settings = await collection.lockForTenant(tenantId);\n if (!settings)\n throw new MoneyValidationError(\n 'INVALID_MONEY_INPUT',\n 'Tenant money settings could not be materialized',\n );\n if (settings.moneyModel === 'migrating')\n throw new MoneyValidationError(\n 'FROZEN_DOCUMENT',\n 'Tenant money migration is in progress',\n );\n if (settings.moneyModel === 'v2')\n return { moneyModel: 'v2', settings, persistedBarrier: true };\n if (requirement === 'v2')\n throw new MoneyValidationError(\n 'INVALID_MONEY_INPUT',\n 'Money v2 is not active for this tenant',\n );\n return { moneyModel: 'legacy', settings, persistedBarrier: true };\n}\n\n/**\n * Run tenant money work under the shared marker lock on exactly one executor.\n *\n * Supplying an existing scope proves re-entry on the same executor. Calls made\n * through the owning transaction wrapper also reuse its exact registered\n * executor. No optional adapter-property heuristic can grant this capability.\n */\nexport async function withTenantMoneyRuntime<T>(\n db: DatabaseInterface,\n tenantId: string,\n requirement: TenantMoneyRuntimeRequirement,\n operation: (scope: TenantMoneyRuntimeScope) => Promise<T>,\n existingScope?: TenantMoneyRuntimeScope,\n): Promise<T> {\n requiredText(tenantId, 'Money tenant');\n if (existingScope) {\n if (\n existingScope.phase !== 'runtime' ||\n existingScope.db !== db ||\n existingScope.tenantId !== tenantId ||\n (requirement === 'v2' && existingScope.barrier.moneyModel !== 'v2')\n )\n throw new MoneyValidationError(\n 'INVALID_MONEY_INPUT',\n 'Tenant money runtime scope does not match the requested executor',\n );\n return operation(existingScope);\n }\n return withDocumentMoneyTransaction(db, async (tx) => {\n const active = activeRuntimeScopes.get(tx as object)?.get(tenantId);\n if (active) {\n if (requirement === 'v2' && active.barrier.moneyModel !== 'v2')\n throw new MoneyValidationError(\n 'INVALID_MONEY_INPUT',\n 'Money v2 is not active for this tenant',\n );\n return operation(active);\n }\n const barrier = await lockTenantMoneyRuntime(tx, tenantId, requirement);\n const scope = runtimeScope(tx, tenantId, barrier);\n const scopes = activeRuntimeScopes.get(tx as object) ?? new Map();\n scopes.set(tenantId, scope);\n activeRuntimeScopes.set(tx as object, scopes);\n try {\n return await operation(scope);\n } finally {\n scopes.delete(tenantId);\n if (scopes.size === 0) activeRuntimeScopes.delete(tx as object);\n }\n });\n}\n\n/**\n * Run migration work under the exact owner marker and transaction executor.\n * This is the only scope that lets guarded collections read while the marker\n * is `migrating`; possession cannot be inferred from adapter shape.\n */\nexport async function withTenantMoneyMigration<T>(\n db: DatabaseInterface,\n tenantId: string,\n migrationId: string,\n operation: (scope: TenantMoneyMigrationScope) => Promise<T>,\n existingScope?: TenantMoneyMigrationScope,\n): Promise<T> {\n requiredText(tenantId, 'Money migration tenant');\n requiredText(migrationId, 'Money migration owner');\n if (existingScope) {\n if (\n existingScope.phase !== 'migration' ||\n existingScope.db !== db ||\n existingScope.tenantId !== tenantId ||\n existingScope.migrationId !== migrationId\n )\n throw new MoneyValidationError(\n 'INVALID_MONEY_INPUT',\n 'Tenant money migration scope does not match the requested executor',\n );\n return operation(existingScope);\n }\n return withDocumentMoneyTransaction(db, async (tx) => {\n const active = activeMigrationScopes.get(tx as object)?.get(tenantId);\n if (active) {\n if (active.migrationId !== migrationId)\n throw new MoneyValidationError(\n 'FROZEN_DOCUMENT',\n 'Tenant money migration owner does not match',\n );\n return operation(active);\n }\n const settings = await lockTenantMoneyMigrationOwner(\n tx,\n tenantId,\n migrationId,\n );\n const scope = {\n db: tx,\n tenantId,\n migrationId,\n settings,\n phase: 'migration',\n } as TenantMoneyMigrationScope;\n const scopes = activeMigrationScopes.get(tx as object) ?? new Map();\n scopes.set(tenantId, scope);\n activeMigrationScopes.set(tx as object, scopes);\n try {\n return await operation(scope);\n } finally {\n scopes.delete(tenantId);\n if (scopes.size === 0) activeMigrationScopes.delete(tx as object);\n }\n });\n}\n\n/** @internal Guard a generated collection read for runtime or migration. */\nexport async function withTenantMoneyCollectionRead<T>(\n db: DatabaseInterface,\n tenantId: string,\n operation: (boundDb: DatabaseInterface) => Promise<T>,\n): Promise<T> {\n const migration = activeMigrationScopes.get(db as object)?.get(tenantId);\n if (migration) return operation(migration.db);\n return withTenantMoneyRuntime(db, tenantId, 'legacy-or-v2', (scope) =>\n operation(scope.db),\n );\n}\n\n/** Lock a tenant at the legacy marker before the caller claims migration. */\nexport async function lockTenantMoneyMigrationClaim(\n tx: DatabaseInterface,\n tenantId: string,\n): Promise<TaxSettings> {\n requiredText(tenantId, 'Money migration tenant');\n if (!(await hasSettingsStorage(tx)))\n throw new MoneyValidationError(\n 'INVALID_MONEY_INPUT',\n 'Money migration requires installed tax settings storage',\n );\n const collection = await TaxSettingsCollection.create({ db: tx });\n const settings = await collection.lockForTenant(tenantId);\n if (!settings)\n throw new MoneyValidationError(\n 'INVALID_MONEY_INPUT',\n 'Tenant money settings could not be materialized',\n );\n if (settings.moneyModel === 'v2')\n throw new MoneyValidationError(\n 'FROZEN_DOCUMENT',\n 'Tenant money model is already v2',\n );\n if (settings.moneyModel === 'migrating')\n throw new MoneyValidationError(\n 'FROZEN_DOCUMENT',\n 'Tenant money migration is already in progress',\n );\n return settings;\n}\n\n/** Lock and verify the exact owner of an active tenant migration. */\nexport async function lockTenantMoneyMigrationOwner(\n tx: DatabaseInterface,\n tenantId: string,\n migrationId: string,\n): Promise<TaxSettings> {\n requiredText(tenantId, 'Money migration tenant');\n requiredText(migrationId, 'Money migration owner');\n if (!(await hasSettingsStorage(tx)))\n throw new MoneyValidationError(\n 'INVALID_MONEY_INPUT',\n 'Money migration requires installed tax settings storage',\n );\n const collection = await TaxSettingsCollection.create({ db: tx });\n const settings = await collection.lockForTenant(tenantId, false);\n if (\n settings?.moneyModel !== 'migrating' ||\n settings.moneyMigrationId !== migrationId\n )\n throw new MoneyValidationError(\n 'FROZEN_DOCUMENT',\n 'Tenant money migration owner does not match',\n );\n return settings;\n}\n"],"mappings":";;;;;;;;;;;;AAkDA,SAAS,aAAa,OAAe,OAAuB;CAC1D,IAAI,CAAC,SAAS,MAAM,KAAK,MAAM,OAC7B,MAAM,IAAI,qBACR,uBACA,GAAG,MAAK,mCACV;CACF,OAAO;AACT;AAEA,eAAe,mBAAmB,IAAyC;CACzE,OAAO,CAAC,GAAG,eAAgB,MAAM,GAAG,YAAY,cAAc;AAChE;AAEA,IAAM,sCAAsB,IAAI,QAG9B;AACF,IAAM,wCAAwB,IAAI,QAGhC;AAEF,SAAS,aACP,IACA,UACA,SACyB;CACzB,OAAO;EACL;EACA;EACA;EACA,OAAO;CACT;AACF;AASA,eAAsB,uBACpB,IACA,UACA,cAA6C,gBACT;CACpC,aAAa,UAAU,cAAc;CACrC,IAAI,CAAE,MAAM,mBAAmB,EAAE,GAAI;EACnC,IAAI,gBAAgB,MAClB,MAAM,IAAI,qBACR,uBACA,+CACF;EACF,OAAO;GACL,YAAY;GACZ,UAAU;GACV,kBAAkB;EACpB;CACF;CAEA,MAAM,WAAW,OAAM,MADE,sBAAsB,OAAO,EAAE,IAAI,GAAG,CAAC,EAAA,CAC9B,cAAc,QAAQ;CACxD,IAAI,CAAC,UACH,MAAM,IAAI,qBACR,uBACA,iDACF;CACF,IAAI,SAAS,eAAe,aAC1B,MAAM,IAAI,qBACR,mBACA,uCACF;CACF,IAAI,SAAS,eAAe,MAC1B,OAAO;EAAE,YAAY;EAAM;EAAU,kBAAkB;CAAK;CAC9D,IAAI,gBAAgB,MAClB,MAAM,IAAI,q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,uBAAuB;CACjD,IAAI,CAAE,MAAM,mBAAmB,EAAE,GAC/B,MAAM,IAAI,qBACR,uBACA,yDACF;CAEF,MAAM,WAAW,OAAM,MADE,sBAAsB,OAAO,EAAE,IAAI,GAAG,CAAC,EAAA,CAC9B,cAAc,UAAU,KAAK;CAC/D,IACE,UAAU,eAAe,eACzB,SAAS,qBAAqB,aAE9B,MAAM,IAAI,qBACR,mBACA,6CACF;CACF,OAAO;AACT"}
@@ -1,15 +1,4 @@
1
- //#region \0rolldown/runtime.js
2
- var __defProp = Object.defineProperty;
3
- var __exportAll = (all, no_symbols) => {
4
- let target = {};
5
- for (var name in all) __defProp(target, name, {
6
- get: all[name],
7
- enumerable: true
8
- });
9
- if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
10
- return target;
11
- };
12
- //#endregion
1
+ import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
13
2
  //#region src/types/index.ts
14
3
  var types_exports = /* @__PURE__ */ __exportAll({
15
4
  ContractStatus: () => ContractStatus,
@@ -49,6 +38,7 @@ var ContractType = /* @__PURE__ */ ((ContractType2) => {
49
38
  ContractType2["ORDER"] = "order";
50
39
  ContractType2["LEASE"] = "lease";
51
40
  ContractType2["AGREEMENT"] = "agreement";
41
+ ContractType2["SUPPLIER_QUOTE"] = "supplier_quote";
52
42
  ContractType2["PURCHASE_ORDER"] = "purchase_order";
53
43
  ContractType2["WHOLESALE_ORDER"] = "wholesale_order";
54
44
  ContractType2["PRODUCTION_ORDER"] = "production_order";
@@ -132,6 +122,6 @@ var InvoiceStatus = /* @__PURE__ */ ((InvoiceStatus2) => {
132
122
  return InvoiceStatus2;
133
123
  })(InvoiceStatus || {});
134
124
  //#endregion
135
- export { FulfillmentStatus as a, PaymentInstrumentStatus as c, PaymentStatus as d, PayoutStatus as f, __exportAll as h, CustomerType as i, PaymentIntentStatus as l, types_exports as m, ContractType as n, FulfillmentType as o, VendorStatus as p, CustomerStatus as r, InvoiceStatus as s, ContractStatus as t, PaymentMethod as u };
125
+ export { FulfillmentStatus as a, PaymentInstrumentStatus as c, PaymentStatus as d, PayoutStatus as f, CustomerType as i, PaymentIntentStatus as l, types_exports as m, ContractType as n, FulfillmentType as o, VendorStatus as p, CustomerStatus as r, InvoiceStatus as s, ContractStatus as t, PaymentMethod as u };
136
126
 
137
- //# sourceMappingURL=types-zVnIjSOk.js.map
127
+ //# sourceMappingURL=types-Bbm0Xflc.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types-Bbm0Xflc.js","names":["CustomerStatus","CustomerType","VendorStatus","ContractType","ContractStatus","FulfillmentType","FulfillmentStatus","PaymentMethod","PaymentStatus","PaymentInstrumentStatus","PayoutStatus","PaymentIntentStatus","InvoiceStatus"],"sources":["../../src/types/index.ts"],"sourcesContent":["/**\n * Commerce package type definitions\n * @packageDocumentation\n */\n\nimport type { SmrtObjectOptions } from '@happyvertical/smrt-core';\nimport type {\n InvoiceCalculationContext,\n InvoiceLineDraft,\n} from '../svelte/invoices/calculations.js';\n\n// ============================================================================\n// Customer/Vendor Types\n// ============================================================================\n\nexport enum CustomerStatus {\n ACTIVE = 'active',\n INACTIVE = 'inactive',\n SUSPENDED = 'suspended',\n}\n\n/**\n * Customer classification — drives channel access, pricing tier, and credit terms.\n *\n * - DTC: direct-to-consumer (end shopper). Pays via storefront checkout.\n * - WHOLESALE: B2B buyer with negotiated terms (NET-30, line sheets, etc.).\n * - RETAIL: in-store walk-in / point-of-sale customer.\n */\nexport enum CustomerType {\n DTC = 'dtc',\n WHOLESALE = 'wholesale',\n RETAIL = 'retail',\n}\n\nexport enum VendorStatus {\n ACTIVE = 'active',\n INACTIVE = 'inactive',\n SUSPENDED = 'suspended',\n}\n\n// ============================================================================\n// Contract Types\n// ============================================================================\n\nexport enum ContractType {\n ESTIMATE = 'estimate',\n ORDER = 'order',\n LEASE = 'lease',\n AGREEMENT = 'agreement',\n SUPPLIER_QUOTE = 'supplier_quote',\n PURCHASE_ORDER = 'purchase_order',\n WHOLESALE_ORDER = 'wholesale_order',\n PRODUCTION_ORDER = 'production_order',\n CART = 'cart',\n /**\n * Industry-neutral licensing primitive. The `LicenseSale` STI subtype\n * carries an immutable rights snapshot, a licensee email, optional\n * legal-entity / jurisdiction fields, and a signed-PDF reference.\n * Any application that sells rights for a fee (stock media,\n * music licensing, code-asset marketplace, license keys, etc.)\n * uses this subtype.\n */\n LICENSE_SALE = 'license_sale',\n}\n\nexport enum ContractStatus {\n DRAFT = 'draft',\n SENT = 'sent',\n ACCEPTED = 'accepted',\n DECLINED = 'declined',\n COMPLETED = 'completed',\n CANCELLED = 'cancelled',\n}\n\n// ============================================================================\n// Fulfillment Types\n// ============================================================================\n\nexport enum FulfillmentType {\n SHIPMENT = 'shipment',\n DELIVERY = 'delivery',\n PICKUP = 'pickup',\n DIGITAL = 'digital',\n SERVICE = 'service',\n}\n\nexport enum FulfillmentStatus {\n PENDING = 'pending',\n PROCESSING = 'processing',\n SHIPPED = 'shipped',\n DELIVERED = 'delivered',\n CANCELLED = 'cancelled',\n}\n\n// ============================================================================\n// Payment Types\n// ============================================================================\n\nexport enum PaymentMethod {\n CASH = 'cash',\n CHECK = 'check',\n CREDIT_CARD = 'credit_card',\n BANK_TRANSFER = 'bank_transfer',\n CRYPTO = 'crypto',\n OTHER = 'other',\n}\n\nexport enum PaymentStatus {\n PENDING = 'pending',\n COMPLETED = 'completed',\n FAILED = 'failed',\n REFUNDED = 'refunded',\n CANCELLED = 'cancelled',\n}\n\nexport type PaymentKind = 'payment' | 'refund';\n\n/**\n * Lifecycle status for a saved {@link PaymentInstrument} (card on file).\n * `active` while chargeable, `expired` once the card lapses, `removed` when the\n * customer detaches it.\n */\nexport enum PaymentInstrumentStatus {\n ACTIVE = 'active',\n EXPIRED = 'expired',\n REMOVED = 'removed',\n}\n\n// ============================================================================\n// Payout Types\n// ============================================================================\n\n/**\n * Status machine for {@link Payout}.\n *\n * `pending → sent → confirmed → failed`. `failed` is terminal but the\n * model exposes a dedicated `resetFromFailed()` so an operator can\n * deliberately requeue a payout after fixing the underlying problem;\n * the reset moves the row back to `pending` and clears the failure\n * metadata.\n *\n * Skipping intermediate states is rejected — a `pending` payout cannot\n * jump straight to `confirmed`, and a `sent` payout cannot regress to\n * `pending` without going through `resetFromFailed()` first.\n */\nexport enum PayoutStatus {\n PENDING = 'pending',\n SENT = 'sent',\n CONFIRMED = 'confirmed',\n FAILED = 'failed',\n}\n\n// ============================================================================\n// PaymentIntent Types\n// ============================================================================\n\n/**\n * Status machine for {@link PaymentIntent}.\n *\n * `awaiting_payment → paid → (issued | retired)`, with `expired` and\n * `cancelled` as alternate terminal states reachable from\n * `awaiting_payment`.\n *\n * - `AWAITING_PAYMENT` — open quote, accepting any of the listed\n * payment options.\n * - `PAID` — one option was satisfied by an incoming payment. The\n * other options are implicitly retired; later inbound funds to a\n * retired option must be flagged for refund by the consumer.\n * - `ISSUED` — downstream rights / contract / fulfillment have been\n * created and linked. Terminal happy-path state.\n * - `RETIRED` — paid but the satisfaction was reversed (refund,\n * chargeback, etc.). Terminal.\n * - `EXPIRED` — the USD-price-lock window passed without payment.\n * Terminal.\n * - `CANCELLED` — the buyer or the system explicitly cancelled the\n * intent before it was paid. Terminal.\n */\nexport enum PaymentIntentStatus {\n AWAITING_PAYMENT = 'awaiting_payment',\n PAID = 'paid',\n ISSUED = 'issued',\n RETIRED = 'retired',\n EXPIRED = 'expired',\n CANCELLED = 'cancelled',\n}\n\n/**\n * One way for a {@link PaymentIntent} to be satisfied. The intent lists\n * an array of these; satisfying any one of them transitions the intent\n * to `PAID` and implicitly retires the rest.\n *\n * Industry-neutral: a marketplace that accepts USDC-on-Base and BTC\n * lists two options; a SaaS billing flow that accepts Stripe and\n * PayPal lists two; a kiosk that accepts only one rail lists one.\n */\nexport interface PaymentOption {\n /**\n * Stable id of the `PaymentBackend` adapter that fulfills this\n * option — must match a `backendId` the consumer's payment-routing\n * layer recognises. Examples: `base-usdc`, `solana-usdc`, `btc`,\n * `stripe`, `paypal`.\n */\n backendId: string;\n /**\n * Payout-rail-qualified currency code, e.g. `USDC-base`, `BTC`,\n * `USD-stripe`. The same convention used by\n * `Vendor.payoutAddresses` and `Payment.nativeCurrency`.\n */\n currency: string;\n /**\n * Optional chain identifier for blockchain-backed options (`base`,\n * `ethereum`, `solana`, ...). Pure-fiat options leave this empty.\n */\n chain?: string;\n /**\n * Destination address / account id the buyer should send funds to\n * for this option (EVM address, BTC address, Stripe payment-intent\n * id, etc.).\n */\n payTo: string;\n /**\n * Amount denominated in `currency`. Stored at decimal precision —\n * a USDC option might be `199.0`, a BTC option `0.00713`.\n */\n nativeAmount: number;\n /**\n * Optional on-chain memo / payment reference (Solana memo, BTC OP_RETURN\n * tag, Stripe metadata key). Some backends use this to disambiguate\n * which intent an inbound payment satisfies.\n */\n memo?: string;\n /**\n * Whether this option supports the x402 HTTP-402 payment-required\n * flow. Consumers that build agent-driven flows use this flag to\n * filter the offered options.\n */\n x402Capable?: boolean;\n /**\n * Optional per-option expiry — when a single rail's quote becomes\n * stale earlier than the intent-wide price-lock window (e.g. a\n * volatile-currency option that re-quotes more aggressively). ISO\n * 8601 string. Empty / missing means \"inherit the intent's\n * `priceLockExpiresAt`\".\n */\n expiresAt?: string;\n}\n\n// ============================================================================\n// Invoice Types\n// ============================================================================\n\nexport enum InvoiceStatus {\n DRAFT = 'draft',\n SENT = 'sent',\n VIEWED = 'viewed',\n PARTIAL = 'partial',\n PAID = 'paid',\n OVERDUE = 'overdue',\n CANCELLED = 'cancelled',\n WRITTEN_OFF = 'written_off',\n}\n\n// ============================================================================\n// Common Interfaces\n// ============================================================================\n\n/**\n * Address structure used for billing and shipping\n */\nexport interface Address {\n street1?: string;\n street2?: string;\n city?: string;\n state?: string;\n postalCode?: string;\n country?: string;\n}\n\n/**\n * A person to reach at a customer or vendor, stored on the party row\n * (`Customer.contacts` / `Vendor.contacts`, #3501). Every field is plain\n * text; `id` is a stable random identifier assigned when the row is first\n * saved. Write rows through `savePartyContacts()`.\n */\nexport interface PartyContact {\n id: string;\n name: string;\n /** Role or relationship, for example \"Accounts payable\". */\n label: string;\n email: string;\n phone: string;\n address: string;\n}\n\n/**\n * Options for recording a payment with ledger integration\n */\nexport interface RecordPaymentOptions {\n /** The ledger to record the journal entry in */\n ledgerId: string;\n /** Account ID for receivables (credit side) */\n receivablesAccountId: string;\n /** Account ID for cash/bank (debit side) */\n cashAccountId: string;\n}\n\n/**\n * Options for recognizing revenue on an invoice\n */\nexport interface RecognizeRevenueOptions {\n /** Account ID for accounts receivable (debit side) */\n arAccountId: string;\n /** Account ID for revenue (credit side) */\n revenueAccountId: string;\n /** Account ID for tax payable (credit side, optional) */\n taxAccountId?: string;\n /** Explicit ledger book currency. Required when the tenant uses money v2. */\n bookCurrency?: string;\n}\n\n/** Options for atomically cancelling a posted money-v2 invoice. */\nexport interface CancelRevenueOptions {\n /** Explicit ledger book currency; required for money-v2 cancellation. */\n bookCurrency?: string;\n}\n\n// ============================================================================\n// Accounting-provider sync shapes\n// ============================================================================\n\n/**\n * A single line item in the format expected by `@happyvertical/accounting`\n * providers (QBO, Stripe, …). Mirrors the object built by\n * {@link InvoiceLineItem.toAccountingLineItem}. The SDK isn't a dependency of\n * this package, so the shape is declared locally rather than imported.\n */\nexport interface AccountingLineItemInput {\n description: string;\n sku?: string;\n quantity: number;\n unitPrice: number;\n discount?: number;\n taxRate?: number;\n amount: number;\n periodStart?: Date;\n periodEnd?: Date;\n}\n\n/**\n * An invoice in the format expected by `@happyvertical/accounting` providers.\n * Mirrors the object built by {@link Invoice.toAccountingInput}; money is in\n * currency **major** units, as the SDK expects.\n */\nexport interface AccountingInvoiceInput {\n id: string;\n externalId?: string;\n invoiceNumber: string;\n customerId: string;\n customerExternalId?: string;\n issueDate: Date;\n dueDate: Date;\n lineItems: AccountingLineItemInput[];\n subtotal: number;\n taxAmount: number;\n totalAmount: number;\n currency: string;\n reference?: string;\n memo?: string;\n idempotencyKey?: string;\n quickbooksRequest?: {\n readonly requestId: string;\n readonly realmId: string;\n readonly environment: 'sandbox' | 'production';\n readonly payloadHash: string;\n };\n quickbooksMapping?: {\n globalTaxCalculation: 'TaxExcluded' | 'NotApplicable';\n };\n}\n\n// ============================================================================\n// Model constructor option interfaces\n//\n// Each model's `constructor(options)` accepts a partial bag of its own fields.\n// Declaring a dedicated `XxxOptions extends SmrtObjectOptions` interface keeps\n// the constructors strongly typed (no `any`) while still allowing the\n// framework's base options (db, ai, fs, _className, …) through.\n// ============================================================================\n\n/**\n * Constructor options for {@link Customer}.\n */\nexport interface CustomerOptions extends SmrtObjectOptions {\n tenantId?: string | null;\n profileId?: string;\n creditLimit?: number;\n paymentTerms?: string;\n taxExempt?: boolean;\n taxId?: string;\n defaultTaxCodeId?: string;\n defaultShippingAddress?: Address;\n defaultBillingAddress?: Address;\n status?: CustomerStatus;\n customerType?: CustomerType | null;\n notes?: string;\n contacts?: PartyContact[] | string | null;\n}\n\n/**\n * Constructor options for {@link Vendor}.\n */\nexport interface VendorOptions extends SmrtObjectOptions {\n tenantId?: string | null;\n profileId?: string;\n leadTimeDays?: number;\n minimumOrderAmount?: number;\n paymentTerms?: string;\n currency?: string;\n taxId?: string;\n defaultTaxCodeId?: string;\n defaultContactEmail?: string;\n defaultContactPhone?: string;\n status?: VendorStatus;\n notes?: string;\n payoutAddresses?: Record<string, string> | string | null;\n contacts?: PartyContact[] | string | null;\n}\n\n/** A component reference stored in a tax code's ordered component list. */\nexport interface TaxCodePart {\n taxComponentId: string;\n compound: boolean;\n}\n\nexport interface TaxComponentOptions extends SmrtObjectOptions {\n tenantId?: string | null;\n name?: string;\n percent?: string;\n liabilityAccountId?: string;\n recoverable?: boolean;\n active?: boolean;\n}\n\nexport interface TaxCodeOptions extends SmrtObjectOptions {\n tenantId?: string | null;\n code?: string;\n name?: string;\n kind?: 'taxable' | 'zero-rated' | 'exempt' | 'out-of-scope';\n appliesTo?: 'sales' | 'purchases' | 'both';\n components?: TaxCodePart[];\n active?: boolean;\n}\n\nexport interface TaxRegistrationOptions {\n taxComponentId: string;\n number: string;\n label: string;\n}\n\nexport interface TaxSettingsOptions extends SmrtObjectOptions {\n tenantId?: string;\n defaultSalesTaxCodeId?: string;\n defaultPurchaseTaxCodeId?: string;\n defaultLineAmountType?: 'exclusive' | 'inclusive' | 'none';\n taxRoundingScope?: 'line' | 'document';\n taxRegistrations?: TaxRegistrationOptions[];\n moneyModel?: 'legacy' | 'migrating' | 'v2';\n moneyMigrationId?: string;\n}\n\n/**\n * Constructor options for {@link Contract} and its STI subtypes.\n */\nexport interface ContractOptions extends SmrtObjectOptions {\n tenantId?: string | null;\n contractType?: ContractType;\n status?: ContractStatus;\n subtotal?: number;\n discountTotal?: number;\n taxAmount?: number;\n totalAmount?: number;\n currency?: string;\n issueDate?: Date;\n dueDate?: Date | null;\n expiryDate?: Date | null;\n reference?: string;\n notes?: string;\n terms?: string;\n channelId?: string;\n lineAmountType?: 'exclusive' | 'inclusive' | 'none';\n taxRoundingScope?: 'line' | 'document';\n sellerTaxRegistrations?: TaxRegistrationOptions[];\n sellerTaxRegistrationsJson?: string;\n partyTaxId?: string;\n moneySnapshotId?: string;\n}\n\nexport interface SalesContractOptions extends ContractOptions {\n customerId?: string | null;\n}\n\nexport interface PurchaseContractOptions extends ContractOptions {\n vendorId?: string | null;\n}\n\n/** Purchase-order header options stored in the existing STI metadata. */\nexport interface PurchaseOrderOptions extends PurchaseContractOptions {\n /** Expected delivery calendar date (YYYY-MM-DD); empty means unspecified. */\n expectedDate?: string;\n /** Delivery address/instructions snapshot. */\n shipTo?: string;\n}\n\n/**\n * Constructor options for {@link LicenseSale} (Contract STI subtype). Extends\n * {@link ContractOptions} with the licensing-specific meta fields.\n */\nexport interface LicenseSaleOptions extends SalesContractOptions {\n skuId?: string;\n paymentId?: string;\n licenseeEmail?: string;\n licenseeLegalEntity?: string;\n licenseeJurisdiction?: string;\n rightsMedium?: string;\n rightsDistributionScope?: string;\n rightsExclusivity?: string;\n rightsDuration?: string;\n rightsTerritory?: string;\n rightsSublicensing?: boolean;\n rightsDerivatives?: boolean;\n pdfUrl?: string;\n pdfHash?: string;\n onChainHashRegistryRef?: string;\n}\n\n/**\n * Constructor options for {@link ContractLineItem}.\n */\nexport interface ContractLineItemOptions extends SmrtObjectOptions {\n tenantId?: string | null;\n contractId?: string;\n description?: string;\n quantity?: number;\n unitPrice?: number;\n discount?: number;\n discountType?: 'none' | 'percent' | 'amount';\n discountRate?: string;\n taxRate?: number;\n taxMode?: 'inherit' | 'override';\n taxCodeId?: string | null;\n taxCodeCode?: string | null;\n taxCodeName?: string | null;\n taxComponents?: ContractTaxComponentSnapshot[];\n taxComponentsJson?: string | null;\n taxAmount?: number;\n legacyAmount?: number | null;\n moneySnapshotId?: string;\n amount?: number;\n productId?: string;\n sku?: string;\n startDate?: Date | null;\n endDate?: Date | null;\n billingPeriod?: string;\n sortOrder?: number;\n}\n\n/** Immutable component tax allocation for one Contract line. */\nexport interface ContractTaxComponentSnapshot {\n taxComponentId: string;\n name: string;\n percent: string;\n taxMinor: number;\n}\n\n/**\n * How the provider collects an invoice (#3190): `charge_automatically`\n * charges the payer's saved card; `send_invoice` asks the payer to pay. Empty\n * for an invoice never pushed to a provider, or pushed before it was recorded.\n */\nexport type InvoiceCollectionMethod =\n | ''\n | 'send_invoice'\n | 'charge_automatically';\n\nexport type InvoiceKind = 'invoice' | 'credit_note';\n\n/** Frozen source pricing plus the one authoritative credit calculation basis. */\nexport type InvoiceCreditCalculationBasis =\n | {\n kind: 'quantity';\n quantity: string;\n sourceQuantity: string;\n sourceUnitPrice: number;\n sourceDiscountType: 'none' | 'percent' | 'amount';\n sourceDiscountRate: string;\n sourceDiscountMinor: number;\n }\n | {\n kind: 'net_amount';\n netMinor: number;\n sourceQuantity: string;\n sourceUnitPrice: number;\n sourceDiscountType: 'none' | 'percent' | 'amount';\n sourceDiscountRate: string;\n sourceDiscountMinor: number;\n };\n\n/**\n * Constructor options for {@link Invoice}.\n */\nexport interface InvoiceOptions extends SmrtObjectOptions {\n kind?: InvoiceKind;\n creditedInvoiceId?: string | null;\n creditedAmount?: number;\n tenantId?: string | null;\n customerId?: string;\n contractId?: string;\n invoiceNumber?: string;\n reference?: string;\n issueDate?: Date;\n dueDate?: Date;\n paidDate?: Date | null;\n subtotal?: number;\n taxAmount?: number;\n providerTaxAmount?: number;\n totalAmount?: number;\n amountPaid?: number;\n currency?: string;\n status?: InvoiceStatus;\n arJournalId?: string;\n arReversalJournalId?: string | null;\n revenueJournalId?: string;\n externalId?: string;\n customerExternalId?: string;\n externalProvider?: string;\n syncedAt?: Date | null;\n collectionMethod?: InvoiceCollectionMethod;\n sentAt?: Date | null;\n viewedAt?: Date | null;\n remindersSent?: number;\n lastReminderAt?: Date | null;\n notes?: string;\n customerNotes?: string;\n terms?: string;\n lineAmountType?: 'exclusive' | 'inclusive' | 'none';\n taxRoundingScope?: 'line' | 'document';\n discountTotal?: number;\n sellerTaxRegistrations?: TaxRegistrationOptions[];\n sellerTaxRegistrationsJson?: string;\n partyTaxId?: string;\n moneySnapshotId?: string;\n accountingSyncStateJson?: string;\n}\n\nexport interface InvoiceTaxComponentSnapshot {\n taxComponentId: string;\n name: string;\n percent: string;\n taxMinor: number;\n}\n\n/** Retained editing modes, validated against resolved model fields before reuse. */\nexport interface InvoiceLineEditorState {\n /** Lossless editor draft; never authoritative for ordinary model saves. */\n draft: InvoiceLineDraft;\n /** Context used to resolve that draft; caller authority must still match on reload. */\n context: InvoiceCalculationContext;\n}\n\n/** Constructor options for {@link InvoiceLineItem}. */\nexport interface InvoiceLineItemOptions extends SmrtObjectOptions {\n creditedLineId?: string | null;\n creditCalculationBasis?: InvoiceCreditCalculationBasis | null;\n creditCalculationBasisJson?: string;\n /** Optional retained editor modes and their original calculation context. */\n invoiceEditorState?: InvoiceLineEditorState | null;\n /** Serialized editor state loaded from persistence; malformed JSON is ignored. */\n invoiceEditorStateJson?: string;\n tenantId?: string | null;\n invoiceId?: string;\n description?: string;\n sku?: string;\n productId?: string | null;\n quantity?: number;\n unitPrice?: number;\n discount?: number;\n discountType?: 'none' | 'percent' | 'amount';\n discountRate?: string;\n taxRate?: number;\n taxMode?: 'inherit' | 'override';\n taxCodeId?: string | null;\n taxCodeCode?: string | null;\n taxCodeName?: string | null;\n taxComponents?: InvoiceTaxComponentSnapshot[];\n taxComponentsJson?: string | null;\n taxAmount?: number;\n legacyAmount?: number | null;\n moneySnapshotId?: string;\n amount?: number;\n sourceType?: string;\n sourceId?: string;\n periodStart?: Date | null;\n periodEnd?: Date | null;\n revenueAccountId?: string | null;\n sortOrder?: number;\n}\n\n/**\n * Constructor options for {@link Fulfillment}.\n */\nexport interface FulfillmentOptions extends SmrtObjectOptions {\n tenantId?: string | null;\n contractId?: string;\n fulfillmentType?: FulfillmentType;\n status?: FulfillmentStatus;\n trackingNumber?: string;\n carrier?: string;\n shippingAddress?: Address;\n shippedAt?: Date | null;\n deliveredAt?: Date | null;\n estimatedDelivery?: Date | null;\n notes?: string;\n}\n\n/**\n * Constructor options for {@link FulfillmentLineItem}.\n */\nexport interface FulfillmentLineItemOptions extends SmrtObjectOptions {\n tenantId?: string | null;\n fulfillmentId?: string;\n contractLineItemId?: string;\n quantityFulfilled?: number;\n notes?: string;\n}\n\n/**\n * Constructor options for {@link Payment}.\n */\nexport interface PaymentOptions extends SmrtObjectOptions {\n kind?: PaymentKind;\n tenantId?: string | null;\n contractId?: string | null;\n customerId?: string | null;\n amount?: number;\n currency?: string;\n method?: PaymentMethod;\n status?: PaymentStatus;\n transactionId?: string;\n reference?: string;\n journalId?: string;\n paidAt?: Date | null;\n notes?: string;\n externalId?: string;\n externalProvider?: string;\n syncedAt?: Date | null;\n backendId?: string;\n backendTxRef?: string;\n nativeAmount?: number;\n nativeCurrency?: string;\n usdAtQuote?: number;\n usdAtConfirmation?: number;\n}\n\n/**\n * Constructor options for {@link PaymentInstrument}.\n */\nexport interface PaymentInstrumentOptions extends SmrtObjectOptions {\n tenantId?: string | null;\n customerId?: string;\n backendId?: string;\n providerCustomerId?: string;\n providerPaymentMethodId?: string;\n type?: string;\n brand?: string;\n last4?: string;\n expMonth?: number;\n expYear?: number;\n isDefault?: boolean;\n status?: PaymentInstrumentStatus;\n}\n\n/**\n * Constructor options for {@link PaymentAllocation}.\n */\nexport interface PaymentAllocationOptions extends SmrtObjectOptions {\n tenantId?: string | null;\n paymentId?: string;\n invoiceId?: string;\n amount?: number;\n allocatedAt?: Date;\n allocatedBy?: string;\n notes?: string;\n}\n\n/**\n * Constructor options for {@link PaymentIntent}.\n */\nexport interface PaymentIntentOptions extends SmrtObjectOptions {\n tenantId?: string | null;\n skuId?: string;\n offeringRef?: string;\n licenseeEmail?: string;\n customerId?: string;\n paymentOptions?: PaymentOption[] | string;\n usdPriceLocked?: number;\n priceLockWindowMs?: number;\n priceLockExpiresAt?: Date | number | string | null;\n status?: PaymentIntentStatus;\n idempotencyKey?: string;\n paidOptionBackendId?: string;\n paymentId?: string;\n paidAt?: Date | number | string | null;\n issuedAt?: Date | number | string | null;\n expiredAt?: Date | number | string | null;\n cancelledAt?: Date | number | string | null;\n retiredAt?: Date | number | string | null;\n notes?: string;\n}\n\n/**\n * Constructor options for {@link Payout}.\n */\nexport interface PayoutOptions extends SmrtObjectOptions {\n tenantId?: string | null;\n paymentId?: string;\n vendorId?: string;\n grossAmount?: number;\n operatorFee?: number;\n supplierNet?: number;\n currency?: string;\n backendId?: string;\n backendTxRef?: string;\n status?: PayoutStatus;\n sentAt?: Date | number | string | null;\n confirmedAt?: Date | number | string | null;\n failedAt?: Date | number | string | null;\n failureReason?: string;\n notes?: string;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAeO,IAAK,iBAAL,kBAAKA,oBAAL;CACLA,gBAAA,YAAS;CACTA,gBAAA,cAAW;CACXA,gBAAA,eAAY;CAHF,OAAAA;AAAA,EAAA,CAAA,kBAAA,CAAA,CAAA;AAaL,IAAK,eAAL,kBAAKC,kBAAL;CACLA,cAAA,SAAM;CACNA,cAAA,eAAY;CACZA,cAAA,YAAS;CAHC,OA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IAAK,gBAAL,kBAAKC,mBAAL;CACLA,eAAA,aAAU;CACVA,eAAA,eAAY;CACZA,eAAA,YAAS;CACTA,eAAA,cAAW;CACXA,eAAA,eAAY;CALF,OAAAA;AAAA,EAAA,CAAA,iBAAA,CAAA,CAAA;AAeL,IAAK,0BAAL,kBAAKC,6BAAL;CACLA,yBAAA,YAAS;CACTA,yBAAA,aAAU;CACVA,yBAAA,aAAU;CAHA,OAAAA;AAAA,EAAA,CAAA,2BAAA,CAAA,CAAA;AAuBL,IAAK,eAAL,kBAAKC,kBAAL;CACLA,cAAA,aAAU;CACVA,cAAA,UAAO;CACPA,cAAA,eAAY;CACZA,cAAA,YAAS;CAJC,OAAAA;AAAA,EAAA,CAAA,gBAAA,CAAA,CAAA;AAgCL,IAAK,sBAAL,kBAAKC,yBAAL;CACLA,qBAAA,sBAAmB;CACnBA,qBAAA,UAAO;CACPA,qBAAA,YAAS;CACTA,qBAAA,aAAU;CACVA,qBAAA,aAAU;CACVA,qBAAA,eAAY;CANF,OAAAA;AAAA,EAAA,CAAA,uBAAA,CAAA,CAAA;AA0EL,IAAK,gBAAL,kBAAKC,mBAAL;CACLA,eAAA,WAAQ;CACRA,eAAA,UAAO;CACPA,eAAA,YAAS;CACTA,eAAA,aAAU;CACVA,eAAA,UAAO;CACPA,eAAA,aAAU;CACVA,eAAA,eAAY;CACZA,eAAA,iBAAc;CARJ,OAAAA;AAAA,EAAA,CAAA,iBAAA,CAAA,CAAA"}
@@ -1,4 +1,4 @@
1
- import { a as currencyMinorUnitExponent, o as normalizeCurrency } from "./calculations-Bz7RB3qK.js";
1
+ import { a as currencyMinorUnitExponent, o as normalizeCurrency } from "./calculations-DaHR17il.js";
2
2
  //#region src/billing/units.ts
3
3
  function minorToMajorUnits(amount, currency) {
4
4
  if (!Number.isSafeInteger(amount)) throw new Error(`Amount ${amount} must be a safe integer number of minor units.`);
@@ -42,4 +42,4 @@ function tenantKey(id) {
42
42
  //#endregion
43
43
  export { majorToMinorUnits as a, isUuid as i, deterministicId as n, minorToMajorUnits as o, isTenantId as r, tenantKey as s, canonicalTenantId as t };
44
44
 
45
- //# sourceMappingURL=units-BpZ0_Dpk.js.map
45
+ //# sourceMappingURL=units-CNcjH_eE.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"units-BpZ0_Dpk.js","names":[],"sources":["../../src/billing/units.ts"],"sourcesContent":["/**\n * Money-unit and identity helpers for billing-period close (#3060).\n *\n * Commerce stores money as integer minor units. `@happyvertical/accounting`\n * takes and returns currency *major* units and converts to the provider's own\n * representation itself, so the only conversion this package performs is the\n * ISO 4217 one: minor units ÷ 10^exponent.\n */\n\nimport {\n currencyMinorUnitExponent,\n normalizeCurrency,\n} from '../svelte/invoices/currency.js';\n\nexport {\n currencyMinorUnitExponent,\n normalizeCurrency,\n} from '../svelte/invoices/currency.js';\n\n/** Integer minor units → major units (`1999` USD → `19.99`). */\nexport function minorToMajorUnits(amount: number, currency: string): number {\n if (!Number.isSafeInteger(amount)) {\n throw new Error(\n `Amount ${amount} must be a safe integer number of minor units.`,\n );\n }\n return amount / 10 ** currencyMinorUnitExponent(currency);\n}\n\n/**\n * Major units → integer minor units. Rejects a value that is not a whole\n * number of minor units instead of rounding it: a provider amount that does\n * not round-trip exactly means the two sides disagree about the currency.\n */\nexport function majorToMinorUnits(amount: number, currency: string): number {\n if (!Number.isFinite(amount)) {\n throw new Error(`Provider amount ${amount} is not a finite number.`);\n }\n const scaled = amount * 10 ** currencyMinorUnitExponent(currency);\n const minor = Math.round(scaled);\n if (Math.abs(scaled - minor) > 1e-6 || !Number.isSafeInteger(minor)) {\n throw new Error(\n `Provider amount ${amount} ${normalizeCurrency(currency)} is not a whole number of minor units.`,\n );\n }\n return minor;\n}\n\n/**\n * A stable UUID derived from its parts (SHA-256, version/variant bits set).\n * Deterministic ids are what make every period-close write replay-safe: a\n * retry recomputes the same identity instead of creating a second row.\n */\nexport async function deterministicId(parts: string[]): Promise<string> {\n const bytes = new TextEncoder().encode(JSON.stringify(parts));\n const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', bytes));\n const uuid = digest.slice(0, 16);\n uuid[6] = (uuid[6] & 0x0f) | 0x50;\n uuid[8] = (uuid[8] & 0x3f) | 0x80;\n const hex = Array.from(uuid, (byte) => byte.toString(16).padStart(2, '0'));\n const joined = hex.join('');\n return [\n joined.slice(0, 8),\n joined.slice(8, 12),\n joined.slice(12, 16),\n joined.slice(16, 20),\n joined.slice(20),\n ].join('-');\n}\n\nconst UUID_PATTERN =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/** Validate and lower-case a tenant UUID. */\nexport function canonicalTenantId(id: string, label = 'Tenant ID'): string {\n if (typeof id !== 'string' || !UUID_PATTERN.test(id)) {\n throw new Error(`${label} must be a UUID.`);\n }\n return id.toLowerCase();\n}\n\n/** Whether `id` is a UUID (any case), such as a billing record id. */\nexport function isUuid(id: string): boolean {\n return typeof id === 'string' && UUID_PATTERN.test(id);\n}\n\n/** Whether `id` is a tenant UUID (any case). */\nexport function isTenantId(id: string): boolean {\n return typeof id === 'string' && UUID_PATTERN.test(id);\n}\n\n/** Lower-case a possibly-empty tenant id for comparison. */\nexport function tenantKey(id: string | null | undefined): string {\n return id ? String(id).toLowerCase() : '';\n}\n"],"mappings":";;AAoBO,SAAS,kBAAkB,QAAgB,UAA0B;CAC1E,IAAI,CAAC,OAAO,cAAc,MAAM,GAC9B,MAAM,IAAI,MACR,UAAU,OAAM,+CAClB;CAEF,OAAO,SAAS,MAAM,0BAA0B,QAAQ;AAC1D;AAOO,SAAS,kBAAkB,QAAgB,UAA0B;CAC1E,IAAI,CAAC,OAAO,SAAS,MAAM,GACzB,MAAM,IAAI,MAAM,mBAAmB,OAAM,yBAA0B;CAErE,MAAM,SAAS,SAAS,MAAM,0BAA0B,QAAQ;CAChE,MAAM,QAAQ,KAAK,MAAM,MAAM;CAC/B,IAAI,KAAK,IAAI,SAAS,KAAK,I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**\n * Money-unit and identity helpers for billing-period close (#3060).\n *\n * Commerce stores money as integer minor units. `@happyvertical/accounting`\n * takes and returns currency *major* units and converts to the provider's own\n * representation itself, so the only conversion this package performs is the\n * ISO 4217 one: minor units ÷ 10^exponent.\n */\n\nimport {\n currencyMinorUnitExponent,\n normalizeCurrency,\n} from '../svelte/invoices/currency.js';\n\nexport {\n currencyMinorUnitExponent,\n normalizeCurrency,\n} from '../svelte/invoices/currency.js';\n\n/** Integer minor units → major units (`1999` USD → `19.99`). */\nexport function minorToMajorUnits(amount: number, currency: string): number {\n if (!Number.isSafeInteger(amount)) {\n throw new Error(\n `Amount ${amount} must be a safe integer number of minor units.`,\n );\n }\n return amount / 10 ** currencyMinorUnitExponent(currency);\n}\n\n/**\n * Major units → integer minor units. Rejects a value that is not a whole\n * number of minor units instead of rounding it: a provider amount that does\n * not round-trip exactly means the two sides disagree about the currency.\n */\nexport function majorToMinorUnits(amount: number, currency: string): number {\n if (!Number.isFinite(amount)) {\n throw new Error(`Provider amount ${amount} is not a finite number.`);\n }\n const scaled = amount * 10 ** currencyMinorUnitExponent(currency);\n const minor = Math.round(scaled);\n if (Math.abs(scaled - minor) > 1e-6 || !Number.isSafeInteger(minor)) {\n throw new Error(\n `Provider amount ${amount} ${normalizeCurrency(currency)} is not a whole number of minor units.`,\n );\n }\n return minor;\n}\n\n/**\n * A stable UUID derived from its parts (SHA-256, version/variant bits set).\n * Deterministic ids are what make every period-close write replay-safe: a\n * retry recomputes the same identity instead of creating a second row.\n */\nexport async function deterministicId(parts: string[]): Promise<string> {\n const bytes = new TextEncoder().encode(JSON.stringify(parts));\n const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', bytes));\n const uuid = digest.slice(0, 16);\n uuid[6] = (uuid[6] & 0x0f) | 0x50;\n uuid[8] = (uuid[8] & 0x3f) | 0x80;\n const hex = Array.from(uuid, (byte) => byte.toString(16).padStart(2, '0'));\n const joined = hex.join('');\n return [\n joined.slice(0, 8),\n joined.slice(8, 12),\n joined.slice(12, 16),\n joined.slice(16, 20),\n joined.slice(20),\n ].join('-');\n}\n\nconst UUID_PATTERN =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/** Validate and lower-case a tenant UUID. */\nexport function canonicalTenantId(id: string, label = 'Tenant ID'): string {\n if (typeof id !== 'string' || !UUID_PATTERN.test(id)) {\n throw new Error(`${label} must be a UUID.`);\n }\n return id.toLowerCase();\n}\n\n/** Whether `id` is a UUID (any case), such as a billing record id. */\nexport function isUuid(id: string): boolean {\n return typeof id === 'string' && UUID_PATTERN.test(id);\n}\n\n/** Whether `id` is a tenant UUID (any case). */\nexport function isTenantId(id: string): boolean {\n return typeof id === 'string' && UUID_PATTERN.test(id);\n}\n\n/** Lower-case a possibly-empty tenant id for comparison. */\nexport function tenantKey(id: string | null | undefined): string {\n return id ? String(id).toLowerCase() : '';\n}\n"],"mappings":";;AAoBO,SAAS,kBAAkB,QAAgB,UAA0B;CAC1E,IAAI,CAAC,OAAO,cAAc,MAAM,GAC9B,MAAM,IAAI,MACR,UAAU,OAAM,+CAClB;CAEF,OAAO,SAAS,MAAM,0BAA0B,QAAQ;AAC1D;AAOO,SAAS,kBAAkB,QAAgB,UAA0B;CAC1E,IAAI,CAAC,OAAO,SAAS,MAAM,GACzB,MAAM,IAAI,MAAM,mBAAmB,OAAM,yBAA0B;CAErE,MAAM,SAAS,SAAS,MAAM,0BAA0B,QAAQ;CAChE,MAAM,QAAQ,KAAK,MAAM,MAAM;CAC/B,IAAI,KAAK,IAAI,SAAS,KAAK,IAAI,QAAQ,CAAC,OAAO,cAAc,KAAK,GAChE,MAAM,IAAI,MACR,mBAAmB,OAAM,GAAI,kBAAkB,QAAQ,EAAC,uCAC1D;CAEF,OAAO;AACT;AAOA,eAAsB,gBAAgB,OAAkC;CACtE,MAAM,QAAQ,IAAI,YAAY,CAAA,CAAE,OAAO,KAAK,UAAU,KAAK,CAAC;CAE5D,MAAM,OAAO,IADM,WAAW,MAAM,OAAO,OAAO,OAAO,WAAW,KAAK,CAC5D,CAAA,CAAO,MAAM,GAAG,EAAE;CAC/B,KAAK,KAAM,KAAK,KAAK,KAAQ;CAC7B,KAAK,KAAM,KAAK,KAAK,KAAQ;CAE7B,MAAM,SADM,MAAM,KAAK,OAAO,SAAS,KAAK,SAAS,EAAE,CAAA,CAAE,SAAS,GAAG,GAAG,CACzD,CAAA,CAAI,KAAK,EAAE;CAC1B,OAAO;EACL,OAAO,MAAM,GAAG,CAAC;EACjB,OAAO,MAAM,GAAG,EAAE;EAClB,OAAO,MAAM,IAAI,EAAE;EACnB,OAAO,MAAM,IAAI,EAAE;EACnB,OAAO,MAAM,EAAE;CACjB,CAAA,CAAE,KAAK,GAAG;AACZ;AAEA,IAAM,eACJ;AAGK,SAAS,kBAAkB,IAAY,QAAQ,aAAqB;CACzE,IAAI,OAAO,OAAO,YAAY,CAAC,aAAa,KAAK,EAAE,GACjD,MAAM,IAAI,MAAM,GAAG,MAAK,iBAAkB;CAE5C,OAAO,GAAG,YAAY;AACxB;AAGO,SAAS,OAAO,IAAqB;CAC1C,OAAO,OAAO,OAAO,YAAY,aAAa,KAAK,EAAE;AACvD;AAGO,SAAS,WAAW,IAAqB;CAC9C,OAAO,OAAO,OAAO,YAAY,aAAa,KAAK,EAAE;AACvD;AAGO,SAAS,UAAU,IAAuC;CAC/D,OAAO,KAAK,OAAO,EAAE,CAAA,CAAE,YAAY,IAAI;AACzC"}
@@ -2,11 +2,36 @@
2
2
  * ContractCollection - Collection manager for Contract objects (STI)
3
3
  * @packageDocumentation
4
4
  */
5
- import { SmrtCollection } from '@happyvertical/smrt-core';
5
+ import { SmrtCollection, type SmrtListOptions, type SmrtObject, type SmrtSelectedRow, type SmrtSelectField, type SmrtStiReadScope, type SmrtWhereClause } from '@happyvertical/smrt-core';
6
6
  import { Contract } from '../models/Contract.js';
7
7
  import { ContractStatus, ContractType } from '../types/index.js';
8
8
  export declare class ContractCollection extends SmrtCollection<Contract> {
9
9
  static readonly _itemClass: typeof Contract;
10
+ private withMoneyRead;
11
+ get(filter: string | SmrtWhereClause<Contract>, options?: Parameters<SmrtCollection<Contract>['get']>[1]): Promise<Contract | null>;
12
+ list<const Select extends readonly SmrtSelectField<Contract>[]>(options: Omit<SmrtListOptions<Contract>, 'select' | 'stiScope'> & {
13
+ select: Select;
14
+ include?: never;
15
+ stiScope: SmrtStiReadScope;
16
+ }): Promise<Record<string, unknown>[]>;
17
+ list<const Select extends readonly SmrtSelectField<Contract>[]>(options: Omit<SmrtListOptions<Contract>, 'select' | 'stiScope'> & {
18
+ select: Select;
19
+ include?: never;
20
+ stiScope?: undefined;
21
+ }): Promise<SmrtSelectedRow<Contract, Select>[]>;
22
+ list(options: Omit<SmrtListOptions<Contract>, 'select' | 'stiScope'> & {
23
+ select?: undefined;
24
+ stiScope: SmrtStiReadScope;
25
+ }): Promise<SmrtObject[]>;
26
+ list(options?: undefined): Promise<Contract[]>;
27
+ list(options: Omit<SmrtListOptions<Contract>, 'select' | 'stiScope'> & {
28
+ select?: undefined;
29
+ stiScope?: undefined;
30
+ }): Promise<Contract[]>;
31
+ list(options: (Omit<SmrtListOptions<Contract>, 'select'> & {
32
+ select?: undefined;
33
+ }) | undefined): Promise<SmrtObject[]>;
34
+ list(options: SmrtListOptions<Contract> | undefined): Promise<SmrtObject[] | Record<string, unknown>[]>;
10
35
  /**
11
36
  * Find contracts by customer
12
37
  *
@@ -23,6 +48,15 @@ export declare class ContractCollection extends SmrtCollection<Contract> {
23
48
  * @deprecated Use PurchaseContractCollection.findByVendor.
24
49
  */
25
50
  findByVendor(vendorId: string): Promise<Contract[]>;
51
+ /**
52
+ * Hydrate a bounded tenant/date report candidate set once, retaining exact
53
+ * STI descendants so callers can classify custom purchase types safely.
54
+ */
55
+ listSnapshotReportContracts(options: {
56
+ tenantId: string;
57
+ from: Date;
58
+ to: Date;
59
+ }): Promise<Contract[]>;
26
60
  /**
27
61
  * Find contracts by type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SmrtCollection } from '@happyvertical/smrt-core';
5
+ import { SmrtCollection, type SmrtListOptions, type SmrtObject, type SmrtSelectedRow, type SmrtSelectField, type SmrtStiReadScope, type SmrtWhereClause } from '@happyvertical/smrt-core';
6
6
  import { ContractLineItem } from '../models/ContractLineItem.js';
7
7
  export declare class ContractLineItemCollection extends SmrtCollection<ContractLineItem> {
8
8
  static readonly _itemClass: typeof ContractLineItem;
9
+ private withMoneyRead;
10
+ get(filter: string | SmrtWhereClause<ContractLineItem>, options?: Parameters<SmrtCollection<ContractLineItem>['get']>[1]): Promise<ContractLineItem | null>;
11
+ list<const Select extends readonly SmrtSelectField<ContractLineItem>[]>(options: Omit<SmrtListOptions<ContractLineItem>, 'select' | 'stiScope'> & {
12
+ select: Select;
13
+ include?: never;
14
+ stiScope: SmrtStiReadScope;
15
+ }): Promise<Record<string, unknown>[]>;
16
+ list<const Select extends readonly SmrtSelectField<ContractLineItem>[]>(options: Omit<SmrtListOptions<ContractLineItem>, 'select' | 'stiScope'> & {
17
+ select: Select;
18
+ include?: never;
19
+ stiScope?: undefined;
20
+ }): Promise<SmrtSelectedRow<ContractLineItem, Select>[]>;
21
+ list(options: Omit<SmrtListOptions<ContractLineItem>, 'select' | 'stiScope'> & {
22
+ select?: undefined;
23
+ stiScope: SmrtStiReadScope;
24
+ }): Promise<SmrtObject[]>;
25
+ list(options?: undefined): Promise<ContractLineItem[]>;
26
+ list(options: Omit<SmrtListOptions<ContractLineItem>, 'select' | 'stiScope'> & {
27
+ select?: undefined;
28
+ stiScope?: undefined;
29
+ }): Promise<ContractLineItem[]>;
30
+ list(options: (Omit<SmrtListOptions<ContractLineItem>, 'select'> & {
31
+ select?: undefined;
32
+ }) | undefined): Promise<SmrtObject[]>;
33
+ list(options: SmrtListOptions<ContractLineItem> | undefined): Promise<SmrtObject[] | Record<string, unknown>[]>;
9
34
  /**
10
35
  * Find contract line items by their parent contract.
11
36
  *
@@ -1 +1 @@
1
- {"version":3,"file":"ContractLineItemCollection.d.ts","sourceRoot":"","sources":["../../src/collections/ContractLineItemCollection.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAE1D,OAAO,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AAEjE,qBAAa,0BAA2B,SAAQ,cAAc,CAAC,gBAAgB,CAAC;IAC9E,MAAM,CAAC,QAAQ,CAAC,UAAU,0BAAoB;IAE9C;;;;;OAKG;IACG,cAAc,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,EAAE,CAAC;IAWrE;;;;;OAKG;IACG,YAAY,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,EAAE,CAAC;IAIjE;;;;;;;;OAQG;IACG,UAAU,IAAI,OAAO,CAAC,gBAAgB,EAAE,CAAC;IAI/C;;;;;;;;OAQG;IACG,eAAe,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,EAAE,CAAC;CAOrE"}
1
+ {"version":3,"file":"ContractLineItemCollection.d.ts","sourceRoot":"","sources":["../../src/collections/ContractLineItemCollection.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EACL,cAAc,EACd,KAAK,eAAe,EACpB,KAAK,UAAU,EACf,KAAK,eAAe,EACpB,KAAK,eAAe,EACpB,KAAK,gBAAgB,EACrB,KAAK,eAAe,EACrB,MAAM,0BAA0B,CAAC;AAOlC,OAAO,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AAGjE,qBAAa,0BAA2B,SAAQ,cAAc,CAAC,gBAAgB,CAAC;IAC9E,MAAM,CAAC,QAAQ,CAAC,UAAU,0BAAoB;YAEhC,aAAa;IAkBZ,GAAG,CAChB,MAAM,EAAE,MAAM,GAAG,eAAe,CAAC,gBAAgB,CAAC,EAClD,OAAO,GAAE,UAAU,CAAC,cAAc,CAAC,gBAAgB,CAAC,CAAC,KAAK,CAAC,CAAC,CAA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