@happyvertical/smrt-commerce 0.57.3 → 0.57.5

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 (168) hide show
  1. package/AGENTS.md +20 -0
  2. package/README.md +130 -0
  3. package/agents/accounting-snapshot-mapper.md +11 -0
  4. package/agents/contract-billing-schedules.md +67 -0
  5. package/agents/contract-money.md +81 -0
  6. package/agents/customer-funds.md +96 -0
  7. package/agents/historical-sales.md +150 -0
  8. package/agents/money-calculator.md +36 -0
  9. package/agents/money-model.md +6 -3
  10. package/agents/observed-purchase-prices.md +37 -0
  11. package/agents/ordinary-accounting.md +72 -0
  12. package/agents/payment-allocations.md +59 -0
  13. package/agents/received-sales-contract-money.md +38 -0
  14. package/dist/accounting-snapshot.d.ts +8 -1
  15. package/dist/accounting-snapshot.d.ts.map +1 -1
  16. package/dist/accounting-steps-internal.d.ts +49 -0
  17. package/dist/accounting-steps-internal.d.ts.map +1 -0
  18. package/dist/allocation-integrity.d.ts.map +1 -1
  19. package/dist/chunks/{ContractLineItemCollection-BZcrlrrY.js → ContractLineItemCollection-D5hBzrct.js} +6 -6
  20. package/dist/chunks/{ContractLineItemCollection-BZcrlrrY.js.map → ContractLineItemCollection-D5hBzrct.js.map} +1 -1
  21. package/dist/chunks/DocumentTaxCollection-C6cI5U89.js +4395 -0
  22. package/dist/chunks/DocumentTaxCollection-C6cI5U89.js.map +1 -0
  23. package/dist/chunks/HistoricalCustomerFundsCollections-B5x8gTW3.js +170 -0
  24. package/dist/chunks/HistoricalCustomerFundsCollections-B5x8gTW3.js.map +1 -0
  25. package/dist/chunks/{InvoiceCollection-cinzAqt6.js → InvoiceCollection-BolwughC.js} +133 -18
  26. package/dist/chunks/InvoiceCollection-BolwughC.js.map +1 -0
  27. package/dist/chunks/{TaxCodeCollection-DaBOPG9c.js → TaxCodeCollection-CW-tWjkU.js} +3 -4
  28. package/dist/chunks/TaxCodeCollection-CW-tWjkU.js.map +1 -0
  29. package/dist/chunks/{TaxComponentCollection-C4zxnyVu.js → TaxComponentCollection-BiJ9aAe8.js} +3 -3
  30. package/dist/chunks/{TaxComponentCollection-C4zxnyVu.js.map → TaxComponentCollection-BiJ9aAe8.js.map} +1 -1
  31. package/dist/chunks/{allocation-integrity-WmWyXhtG.js → allocation-integrity-CH-i-hsY.js} +7 -7
  32. package/dist/chunks/{allocation-integrity-WmWyXhtG.js.map → allocation-integrity-CH-i-hsY.js.map} +1 -1
  33. package/dist/chunks/{contract-money-EuToOghh.js → contract-money-BMsq4cpL.js} +45 -12
  34. package/dist/chunks/contract-money-BMsq4cpL.js.map +1 -0
  35. package/dist/chunks/customer-funds-internal-BQzoJXK5.js +24 -0
  36. package/dist/chunks/customer-funds-internal-BQzoJXK5.js.map +1 -0
  37. package/dist/chunks/{detect-CY9ufaFb.js → detect-DAE-_NAk.js} +5 -2
  38. package/dist/chunks/{detect-CY9ufaFb.js.map → detect-DAE-_NAk.js.map} +1 -1
  39. package/dist/chunks/historical-commerce-internal-C9ButfuH.js +18 -0
  40. package/dist/chunks/historical-commerce-internal-C9ButfuH.js.map +1 -0
  41. package/dist/chunks/{invoice-posting-C2i5dOVZ.js → invoice-posting-IXic4UEP.js} +5 -5
  42. package/dist/chunks/invoice-posting-IXic4UEP.js.map +1 -0
  43. package/dist/chunks/retention-accounting-c7kY7gFU.js +2738 -0
  44. package/dist/chunks/retention-accounting-c7kY7gFU.js.map +1 -0
  45. package/dist/chunks/retention-accounting-internal-DNxLLVvK.js +30 -0
  46. package/dist/chunks/retention-accounting-internal-DNxLLVvK.js.map +1 -0
  47. package/dist/chunks/{tenant-money-barrier-6TlqUeVj.js → tenant-money-barrier-DEVLrpaB.js} +5 -5
  48. package/dist/chunks/{tenant-money-barrier-6TlqUeVj.js.map → tenant-money-barrier-DEVLrpaB.js.map} +1 -1
  49. package/dist/chunks/types-Bbm0Xflc.js.map +1 -1
  50. package/dist/collections/DocumentTaxCollection.d.ts +4 -1
  51. package/dist/collections/DocumentTaxCollection.d.ts.map +1 -1
  52. package/dist/collections/HistoricalCustomerFundsCollections.d.ts +10 -0
  53. package/dist/collections/HistoricalCustomerFundsCollections.d.ts.map +1 -0
  54. package/dist/collections/HistoricalSalesLineCollection.d.ts +6 -0
  55. package/dist/collections/HistoricalSalesLineCollection.d.ts.map +1 -0
  56. package/dist/collections/PaymentAllocationCollection.d.ts +2 -6
  57. package/dist/collections/PaymentAllocationCollection.d.ts.map +1 -1
  58. package/dist/collections/PurchasePriceObservationCollection.d.ts +6 -0
  59. package/dist/collections/PurchasePriceObservationCollection.d.ts.map +1 -0
  60. package/dist/collections/index.d.ts +1 -0
  61. package/dist/collections/index.d.ts.map +1 -1
  62. package/dist/contract-billing-schedule.d.ts +83 -0
  63. package/dist/contract-billing-schedule.d.ts.map +1 -0
  64. package/dist/contract-money.d.ts +2 -0
  65. package/dist/contract-money.d.ts.map +1 -1
  66. package/dist/customer-funds-internal.d.ts +6 -0
  67. package/dist/customer-funds-internal.d.ts.map +1 -0
  68. package/dist/customer-funds.d.ts +108 -0
  69. package/dist/customer-funds.d.ts.map +1 -0
  70. package/dist/document-money.d.ts +11 -0
  71. package/dist/document-money.d.ts.map +1 -1
  72. package/dist/historical-commerce-internal.d.ts +3 -0
  73. package/dist/historical-commerce-internal.d.ts.map +1 -0
  74. package/dist/historical-customer-funds-types.d.ts +113 -0
  75. package/dist/historical-customer-funds-types.d.ts.map +1 -0
  76. package/dist/historical-customer-funds.d.ts +23 -0
  77. package/dist/historical-customer-funds.d.ts.map +1 -0
  78. package/dist/historical-funds-internal.d.ts +5 -0
  79. package/dist/historical-funds-internal.d.ts.map +1 -0
  80. package/dist/historical-sales-money.d.ts +22 -0
  81. package/dist/historical-sales-money.d.ts.map +1 -0
  82. package/dist/historical-sales-reports.d.ts +31 -0
  83. package/dist/historical-sales-reports.d.ts.map +1 -0
  84. package/dist/historical-sales-types.d.ts +106 -0
  85. package/dist/historical-sales-types.d.ts.map +1 -0
  86. package/dist/historical-sales-validation.d.ts +12 -0
  87. package/dist/historical-sales-validation.d.ts.map +1 -0
  88. package/dist/index.d.ts +22 -0
  89. package/dist/index.d.ts.map +1 -1
  90. package/dist/index.js +1668 -1643
  91. package/dist/index.js.map +1 -1
  92. package/dist/invoice-accounting-sync.d.ts +0 -1
  93. package/dist/invoice-accounting-sync.d.ts.map +1 -1
  94. package/dist/invoice-mcp.d.ts.map +1 -1
  95. package/dist/invoice-posting.d.ts.map +1 -1
  96. package/dist/invoice-retention.d.ts +16 -0
  97. package/dist/invoice-retention.d.ts.map +1 -0
  98. package/dist/invoices.d.ts +3 -0
  99. package/dist/invoices.d.ts.map +1 -1
  100. package/dist/invoices.js +2 -2
  101. package/dist/manifest.json +7626 -4446
  102. package/dist/models/Contract.d.ts +14 -0
  103. package/dist/models/Contract.d.ts.map +1 -1
  104. package/dist/models/DocumentTax.d.ts +2 -0
  105. package/dist/models/DocumentTax.d.ts.map +1 -1
  106. package/dist/models/HistoricalCustomerFunds.d.ts +36 -0
  107. package/dist/models/HistoricalCustomerFunds.d.ts.map +1 -0
  108. package/dist/models/HistoricalCustomerFundsAllocation.d.ts +32 -0
  109. package/dist/models/HistoricalCustomerFundsAllocation.d.ts.map +1 -0
  110. package/dist/models/HistoricalSalesLine.d.ts +29 -0
  111. package/dist/models/HistoricalSalesLine.d.ts.map +1 -0
  112. package/dist/models/Invoice.d.ts +12 -1
  113. package/dist/models/Invoice.d.ts.map +1 -1
  114. package/dist/models/Payment.d.ts +9 -1
  115. package/dist/models/Payment.d.ts.map +1 -1
  116. package/dist/models/PaymentAllocation.d.ts +3 -1
  117. package/dist/models/PaymentAllocation.d.ts.map +1 -1
  118. package/dist/models/PaymentIntent.d.ts.map +1 -1
  119. package/dist/models/Payout.d.ts.map +1 -1
  120. package/dist/models/PurchasePriceObservation.d.ts +15 -0
  121. package/dist/models/PurchasePriceObservation.d.ts.map +1 -0
  122. package/dist/models/TaxCode.d.ts +1 -1
  123. package/dist/models/TaxCode.d.ts.map +1 -1
  124. package/dist/models/index.d.ts +1 -0
  125. package/dist/models/index.d.ts.map +1 -1
  126. package/dist/money.d.ts +5 -1
  127. package/dist/money.d.ts.map +1 -1
  128. package/dist/money.js +62 -15
  129. package/dist/money.js.map +1 -1
  130. package/dist/observed-purchase-price-internal.d.ts +3 -0
  131. package/dist/observed-purchase-price-internal.d.ts.map +1 -0
  132. package/dist/observed-purchase-price.d.ts +71 -0
  133. package/dist/observed-purchase-price.d.ts.map +1 -0
  134. package/dist/ordinary-accounting-internal.d.ts +3 -0
  135. package/dist/ordinary-accounting-internal.d.ts.map +1 -0
  136. package/dist/ordinary-accounting.d.ts +104 -0
  137. package/dist/ordinary-accounting.d.ts.map +1 -0
  138. package/dist/received-purchase-money.d.ts +87 -0
  139. package/dist/received-purchase-money.d.ts.map +1 -0
  140. package/dist/recipes.d.ts +4 -1
  141. package/dist/recipes.d.ts.map +1 -1
  142. package/dist/retention-accounting-internal.d.ts +3 -0
  143. package/dist/retention-accounting-internal.d.ts.map +1 -0
  144. package/dist/retention-accounting.d.ts +143 -0
  145. package/dist/retention-accounting.d.ts.map +1 -0
  146. package/dist/retention-money.d.ts +43 -0
  147. package/dist/retention-money.d.ts.map +1 -0
  148. package/dist/smrt-knowledge.json +1872 -113
  149. package/dist/tax/cookbook.d.ts.map +1 -1
  150. package/dist/tax-summary.d.ts +1 -0
  151. package/dist/tax-summary.d.ts.map +1 -1
  152. package/dist/types/index.d.ts +20 -1
  153. package/dist/types/index.d.ts.map +1 -1
  154. package/package.json +16 -16
  155. package/dist/chunks/CustomerCollection-BIPH2ZUx.js +0 -99
  156. package/dist/chunks/CustomerCollection-BIPH2ZUx.js.map +0 -1
  157. package/dist/chunks/DocumentTaxCollection-DDzlywMW.js +0 -1666
  158. package/dist/chunks/DocumentTaxCollection-DDzlywMW.js.map +0 -1
  159. package/dist/chunks/InvoiceCollection-cinzAqt6.js.map +0 -1
  160. package/dist/chunks/TaxCodeCollection-DaBOPG9c.js.map +0 -1
  161. package/dist/chunks/VendorCollection-D6ZcUYy8.js +0 -100
  162. package/dist/chunks/VendorCollection-D6ZcUYy8.js.map +0 -1
  163. package/dist/chunks/calculations-C9daQLsh.js +0 -82
  164. package/dist/chunks/calculations-C9daQLsh.js.map +0 -1
  165. package/dist/chunks/contract-money-EuToOghh.js.map +0 -1
  166. package/dist/chunks/document-money-DV5t4vlK.js +0 -1186
  167. package/dist/chunks/document-money-DV5t4vlK.js.map +0 -1
  168. package/dist/chunks/invoice-posting-C2i5dOVZ.js.map +0 -1
@@ -1,1666 +0,0 @@
1
- import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
2
- import { i as CustomerType, n as ContractType, p as VendorStatus, r as CustomerStatus, t as ContractStatus } from "./types-Bbm0Xflc.js";
3
- import { MoneyValidationError, assertIntegerMinorUnits } from "../money.js";
4
- import { a as assertCommerceMoneySchemaCurrent, f as DOCUMENT_MONEY_READ_REBIND, p as DOCUMENT_MONEY_WRITE } from "./detect-CY9ufaFb.js";
5
- import { n as withTenantMoneyCollectionRead } from "./tenant-money-barrier-6TlqUeVj.js";
6
- import { SmrtCollection, SmrtObject, crossPackageRef, field, foreignKey, smrt } from "@happyvertical/smrt-core";
7
- import { TenantScoped, getTenantId, queryGlobal, queryWithGlobals, tenantId, withTenant } from "@happyvertical/smrt-tenancy";
8
- //#region src/party-contacts.ts
9
- var DEFAULT_PARTY_CONTACT_FIELD_NAMES = {
10
- contactId: "contactId",
11
- contactName: "contactName",
12
- contactLabel: "contactLabel",
13
- contactEmail: "contactEmail",
14
- contactPhone: "contactPhone",
15
- contactAddress: "contactAddress",
16
- contactCount: "contactCount"
17
- };
18
- var PARTY_CONTACT_MAX_LENGTHS = {
19
- name: 160,
20
- label: 80,
21
- email: 320,
22
- phone: 80,
23
- address: 500
24
- };
25
- var FIELDS = [
26
- "name",
27
- "label",
28
- "email",
29
- "phone",
30
- "address"
31
- ];
32
- var PartyContactValidationError = class extends Error {
33
- /** Errors aligned with the submitted rows; `undefined` for a valid row. */
34
- errors;
35
- constructor(errors) {
36
- super("One or more contact rows are invalid");
37
- this.name = "PartyContactValidationError";
38
- this.errors = errors;
39
- }
40
- };
41
- var PartyContactPayloadError = class extends Error {
42
- reason;
43
- constructor(reason, message) {
44
- super(message);
45
- this.name = "PartyContactPayloadError";
46
- this.reason = reason;
47
- }
48
- };
49
- var PartyContactPartyNotFoundError = class extends Error {
50
- constructor(partyId) {
51
- super(`Customer or vendor ${partyId} was not found`);
52
- this.name = "PartyContactPartyNotFoundError";
53
- }
54
- };
55
- function text(value) {
56
- return typeof value === "string" ? value : "";
57
- }
58
- function normalizePartyContacts(value) {
59
- let input = value;
60
- if (typeof input === "string") try {
61
- input = JSON.parse(input);
62
- } catch {
63
- return [];
64
- }
65
- if (!Array.isArray(input)) return [];
66
- const contacts = [];
67
- for (const entry of input) {
68
- if (!entry || typeof entry !== "object") continue;
69
- const row = entry;
70
- contacts.push({
71
- id: text(row.id) || globalThis.crypto.randomUUID(),
72
- name: text(row.name),
73
- label: text(row.label),
74
- email: text(row.email),
75
- phone: text(row.phone),
76
- address: text(row.address)
77
- });
78
- }
79
- return contacts;
80
- }
81
- function readPartyContactRows(form, fieldNames = {}) {
82
- const names = {
83
- ...DEFAULT_PARTY_CONTACT_FIELD_NAMES,
84
- ...fieldNames
85
- };
86
- const column = (name) => form.getAll(name).map(text);
87
- const columns = {
88
- id: column(names.contactId),
89
- name: column(names.contactName),
90
- label: column(names.contactLabel),
91
- email: column(names.contactEmail),
92
- phone: column(names.contactPhone),
93
- address: column(names.contactAddress)
94
- };
95
- const markers = column(names.contactCount);
96
- if (markers.length !== 1) throw new PartyContactPayloadError(markers.length === 0 ? "missing" : "misaligned", markers.length === 0 ? `Contact payload has no ${names.contactCount} marker; the contact fields were not posted under these names` : `Contact payload has ${markers.length} ${names.contactCount} markers`);
97
- const count = columns.id.length;
98
- if (markers[0] !== String(count)) throw new PartyContactPayloadError("misaligned", `Contact payload is misaligned: ${names.contactCount} is ${markers[0]} but ${count} contact ids were posted`);
99
- for (const [key, values] of Object.entries(columns)) if (values.length !== count) throw new PartyContactPayloadError("misaligned", `Contact payload is misaligned: ${count} contact ids but ${values.length} ${key} values`);
100
- return columns.id.map((id, index) => ({
101
- id,
102
- name: columns.name[index],
103
- label: columns.label[index],
104
- email: columns.email[index],
105
- phone: columns.phone[index],
106
- address: columns.address[index]
107
- }));
108
- }
109
- function defaultParseRemoveIntent(intent) {
110
- const match = /^removeContact:(\d+)$/.exec(intent);
111
- return match ? Number(match[1]) : void 0;
112
- }
113
- function applyPartyContactIntent(rows, intent, intents = {}) {
114
- if (intent === (intents.addIntent ?? "addContact")) return {
115
- contacts: [...rows, {}],
116
- handled: true
117
- };
118
- const index = (intents.parseRemoveIntent ?? defaultParseRemoveIntent)(intent);
119
- if (index !== void 0) return {
120
- contacts: rows.filter((_, position) => position !== index),
121
- handled: true
122
- };
123
- return {
124
- contacts: [...rows],
125
- handled: false
126
- };
127
- }
128
- var EMAIL = /^[^\s@]+@[^\s@]+$/;
129
- function validatePartyContactRows(rows) {
130
- const contacts = [];
131
- const errors = [];
132
- let invalid = false;
133
- rows.forEach((row, index) => {
134
- const trimmed = { id: text(row.id).trim() };
135
- let rowErrors;
136
- for (const field of FIELDS) {
137
- const value = text(row[field]).trim();
138
- trimmed[field] = value;
139
- if (value.length > PARTY_CONTACT_MAX_LENGTHS[field]) rowErrors = {
140
- ...rowErrors,
141
- [field]: "too_long"
142
- };
143
- }
144
- if (trimmed.email && !rowErrors?.email && !EMAIL.test(trimmed.email)) rowErrors = {
145
- ...rowErrors,
146
- email: "invalid_email"
147
- };
148
- errors[index] = rowErrors;
149
- if (rowErrors) invalid = true;
150
- if (FIELDS.some((field) => trimmed[field])) contacts.push(trimmed);
151
- });
152
- return invalid ? {
153
- contacts,
154
- errors
155
- } : { contacts };
156
- }
157
- async function savePartyContacts(collection, partyId, posted, options = {}) {
158
- const rows = Array.isArray(posted) ? posted : readPartyContactRows(posted, options.fieldNames);
159
- const party = await collection.get({ id: partyId });
160
- if (!party || options.expectedTenantId !== void 0 && party.tenantId !== options.expectedTenantId) throw new PartyContactPartyNotFoundError(partyId);
161
- const validation = validatePartyContactRows(rows);
162
- const { contacts } = validation;
163
- const errors = validation.errors ?? rows.map(() => void 0);
164
- const saved = new Set(normalizePartyContacts(party.contacts).map((c) => c.id));
165
- let invalid = validation.errors !== void 0;
166
- rows.forEach((row, index) => {
167
- const id = text(row.id).trim();
168
- if (id && !saved.has(id)) {
169
- errors[index] = {
170
- ...errors[index],
171
- id: "unknown_contact"
172
- };
173
- invalid = true;
174
- }
175
- });
176
- if (invalid) throw new PartyContactValidationError(errors);
177
- const seen = /* @__PURE__ */ new Set();
178
- party.contacts = contacts.map((row) => {
179
- const id = row.id && !seen.has(row.id) ? row.id : globalThis.crypto.randomUUID();
180
- seen.add(id);
181
- return {
182
- id,
183
- name: row.name ?? "",
184
- label: row.label ?? "",
185
- email: row.email ?? "",
186
- phone: row.phone ?? "",
187
- address: row.address ?? ""
188
- };
189
- });
190
- await party.save();
191
- return party.contacts;
192
- }
193
- //#endregion
194
- //#region src/models/Customer.ts
195
- var __defProp$3 = Object.defineProperty;
196
- var __getOwnPropDesc$3 = Object.getOwnPropertyDescriptor;
197
- var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, {
198
- enumerable: true,
199
- configurable: true,
200
- writable: true,
201
- value
202
- }) : obj[key] = value;
203
- var __decorateClass$3 = (decorators, target, key, kind) => {
204
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$3(target, key) : target;
205
- for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
206
- if (kind && result) __defProp$3(target, key, result);
207
- return result;
208
- };
209
- var __publicField$3 = (obj, key, value) => __defNormalProp$3(obj, typeof key !== "symbol" ? key + "" : key, value);
210
- var Customer = class extends SmrtObject {
211
- tenantId = null;
212
- profileId = "";
213
- creditLimit = 0;
214
- paymentTerms = "";
215
- taxExempt = false;
216
- taxId = "";
217
- defaultTaxCodeId = "";
218
- defaultShippingAddress = {};
219
- defaultBillingAddress = {};
220
- status = CustomerStatus.ACTIVE;
221
- customerType = CustomerType.DTC;
222
- notes = "";
223
- contacts = [];
224
- constructor(options = {}) {
225
- super(options);
226
- if (options.tenantId !== void 0) this.tenantId = options.tenantId;
227
- if (options.profileId !== void 0) this.profileId = options.profileId;
228
- if (options.creditLimit !== void 0) this.creditLimit = options.creditLimit;
229
- if (options.paymentTerms !== void 0) this.paymentTerms = options.paymentTerms;
230
- if (options.taxExempt !== void 0) this.taxExempt = options.taxExempt;
231
- if (options.taxId !== void 0) this.taxId = options.taxId;
232
- if (options.defaultTaxCodeId !== void 0) this.defaultTaxCodeId = options.defaultTaxCodeId;
233
- if (options.defaultShippingAddress !== void 0) this.defaultShippingAddress = options.defaultShippingAddress;
234
- if (options.defaultBillingAddress !== void 0) this.defaultBillingAddress = options.defaultBillingAddress;
235
- if (options.status !== void 0) this.status = options.status;
236
- if (options.customerType !== void 0 && options.customerType !== null) this.customerType = options.customerType;
237
- if (options.notes !== void 0) this.notes = options.notes;
238
- if (options.contacts !== void 0) this.contacts = normalizePartyContacts(options.contacts);
239
- }
240
- /**
241
- * Re-normalize contacts after the framework's option-override pass, which
242
- * re-applies raw option values (including a stored JSON string).
243
- */
244
- async initialize() {
245
- await super.initialize();
246
- this.contacts = normalizePartyContacts(this.contacts);
247
- return this;
248
- }
249
- /** Save with a final contacts normalization against direct assignment. */
250
- async save() {
251
- this.contacts = normalizePartyContacts(this.contacts);
252
- return super.save();
253
- }
254
- /**
255
- * Convenience predicate: is this a wholesale customer?
256
- */
257
- isWholesale() {
258
- return this.customerType === CustomerType.WHOLESALE;
259
- }
260
- /**
261
- * Check if customer is active
262
- */
263
- isActive() {
264
- return this.status === CustomerStatus.ACTIVE;
265
- }
266
- /**
267
- * Check if customer has available credit
268
- */
269
- hasAvailableCredit(amount) {
270
- return this.creditLimit >= amount;
271
- }
272
- /**
273
- * Get the profile ID for external lookup.
274
- *
275
- * To get the actual Profile object, use the ProfileCollection from smrt-profiles:
276
- * ```typescript
277
- * const profiles = await ProfileCollection.create(options);
278
- * const profile = await profiles.get({ id: customer.profileId });
279
- * ```
280
- *
281
- * @returns The profile ID or empty string if not set
282
- */
283
- getProfileId() {
284
- return this.profileId;
285
- }
286
- };
287
- __publicField$3(Customer, "__smrtPackage__", "@happyvertical/smrt-commerce");
288
- __decorateClass$3([tenantId({ nullable: true })], Customer.prototype, "tenantId", 2);
289
- __decorateClass$3([crossPackageRef("@happyvertical/smrt-profiles:Profile", { description: "Links this customer to their profile record, where their name and contact details are kept." })], Customer.prototype, "profileId", 2);
290
- __decorateClass$3([field({
291
- description: "The most this customer may owe you at one time. Leave it at zero if you do not set limits.",
292
- ui: { format: "money" }
293
- })], Customer.prototype, "creditLimit", 2);
294
- __decorateClass$3([field({ description: "How long the customer has to pay, written the way you would say it, for example \"Net 30\"." })], Customer.prototype, "paymentTerms", 2);
295
- __decorateClass$3([field({ description: "Turn this on if you do not charge this customer sales tax." })], Customer.prototype, "taxExempt", 2);
296
- __decorateClass$3([field({
297
- sensitive: true,
298
- description: "The tax or VAT number of the customer, kept on file for tax-exempt sales."
299
- })], Customer.prototype, "taxId", 2);
300
- __decorateClass$3([foreignKey("TaxCode", { description: "The tax code normally used when selling to this customer." })], Customer.prototype, "defaultTaxCodeId", 2);
301
- __decorateClass$3([field({ description: "Where you usually send goods to this customer, so you do not retype it on every order." })], Customer.prototype, "defaultShippingAddress", 2);
302
- __decorateClass$3([field({ description: "Where you send invoices to this customer." })], Customer.prototype, "defaultBillingAddress", 2);
303
- __decorateClass$3([field({ description: "Whether you are still dealing with this customer: active, inactive or suspended." })], Customer.prototype, "status", 2);
304
- __decorateClass$3([field({ description: "The kind of customer: a direct shopper, a wholesale buyer or a retail customer." })], Customer.prototype, "customerType", 2);
305
- __decorateClass$3([field({
306
- description: "Anything worth remembering about this customer.",
307
- ui: { widget: "textarea" }
308
- })], Customer.prototype, "notes", 2);
309
- __decorateClass$3([field({ description: "The people you deal with at this customer, with their role and how to reach them." })], Customer.prototype, "contacts", 2);
310
- Customer = __decorateClass$3([TenantScoped({ mode: "optional" }), smrt({
311
- api: { include: [
312
- "list",
313
- "get",
314
- "create",
315
- "update"
316
- ] },
317
- mcp: { include: ["list", "get"] },
318
- cli: { skipApiCheck: true }
319
- })], Customer);
320
- //#endregion
321
- //#region src/models/Vendor.ts
322
- var __defProp$2 = Object.defineProperty;
323
- var __getOwnPropDesc$2 = Object.getOwnPropertyDescriptor;
324
- var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, {
325
- enumerable: true,
326
- configurable: true,
327
- writable: true,
328
- value
329
- }) : obj[key] = value;
330
- var __decorateClass$2 = (decorators, target, key, kind) => {
331
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$2(target, key) : target;
332
- for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
333
- if (kind && result) __defProp$2(target, key, result);
334
- return result;
335
- };
336
- var __publicField$2 = (obj, key, value) => __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
337
- var Vendor = class extends SmrtObject {
338
- tenantId = null;
339
- profileId = "";
340
- leadTimeDays = 0;
341
- minimumOrderAmount = 0;
342
- paymentTerms = "";
343
- currency = "USD";
344
- taxId = "";
345
- defaultTaxCodeId = "";
346
- defaultContactEmail = "";
347
- defaultContactPhone = "";
348
- status = VendorStatus.ACTIVE;
349
- notes = "";
350
- payoutAddresses = {};
351
- contacts = [];
352
- constructor(options = {}) {
353
- super(options);
354
- if (options.tenantId !== void 0) this.tenantId = options.tenantId;
355
- if (options.profileId !== void 0) this.profileId = options.profileId;
356
- if (options.leadTimeDays !== void 0) this.leadTimeDays = options.leadTimeDays;
357
- if (options.minimumOrderAmount !== void 0) this.minimumOrderAmount = options.minimumOrderAmount;
358
- if (options.paymentTerms !== void 0) this.paymentTerms = options.paymentTerms;
359
- if (options.currency !== void 0) this.currency = options.currency;
360
- if (options.taxId !== void 0) this.taxId = options.taxId;
361
- if (options.defaultTaxCodeId !== void 0) this.defaultTaxCodeId = options.defaultTaxCodeId;
362
- if (options.defaultContactEmail !== void 0) this.defaultContactEmail = options.defaultContactEmail;
363
- if (options.defaultContactPhone !== void 0) this.defaultContactPhone = options.defaultContactPhone;
364
- if (options.status !== void 0) this.status = options.status;
365
- if (options.notes !== void 0) this.notes = options.notes;
366
- if (options.payoutAddresses !== void 0) this.payoutAddresses = Vendor.normalizePayoutAddresses(options.payoutAddresses);
367
- if (options.contacts !== void 0) this.contacts = normalizePartyContacts(options.contacts);
368
- }
369
- /**
370
- * The framework's {@link SmrtObject.initialize} re-applies `options` keys on
371
- * top of constructor-set values so option data always wins over field
372
- * initializers. That means our constructor's normalization runs *before*
373
- * `initializePropertiesFromOptions` overwrites `payoutAddresses` with the
374
- * raw cloned value. Re-normalize once super has finished so consumers
375
- * who pass a string, a partially-typed map, or `null` end up with a
376
- * clean `Record<string, string>` before any save / read happens.
377
- */
378
- async initialize() {
379
- await super.initialize();
380
- this.payoutAddresses = Vendor.normalizePayoutAddresses(this.payoutAddresses);
381
- this.contacts = normalizePartyContacts(this.contacts);
382
- return this;
383
- }
384
- /**
385
- * Save with a final normalization pass so direct field assignments
386
- * (`vendor.payoutAddresses = somethingFunny`) can't smuggle non-string
387
- * values into the persisted row.
388
- */
389
- async save() {
390
- this.payoutAddresses = Vendor.normalizePayoutAddresses(this.payoutAddresses);
391
- this.contacts = normalizePartyContacts(this.contacts);
392
- return super.save();
393
- }
394
- /**
395
- * Check if vendor is active
396
- */
397
- isActive() {
398
- return this.status === VendorStatus.ACTIVE;
399
- }
400
- /**
401
- * Check if order meets minimum requirements
402
- */
403
- meetsMinimumOrder(amount) {
404
- return amount >= this.minimumOrderAmount;
405
- }
406
- /**
407
- * Get the profile ID for external lookup.
408
- *
409
- * To get the actual Profile object, use the ProfileCollection from smrt-profiles:
410
- * ```typescript
411
- * const profiles = await ProfileCollection.create(options);
412
- * const profile = await profiles.get({ id: vendor.profileId });
413
- * ```
414
- *
415
- * @returns The profile ID or empty string if not set
416
- */
417
- getProfileId() {
418
- return this.profileId;
419
- }
420
- /**
421
- * Look up the payout destination for a single currency. Returns
422
- * `undefined` if the vendor has no entry for that currency — caller's
423
- * job to decide whether that means "skip the option" or "raise a
424
- * configuration error". The lookup is case-sensitive; the contract is
425
- * that the currency code passed in matches exactly what was stored
426
- * (`USDC-base`, not `usdc-base`).
427
- */
428
- getPayoutAddress(currency) {
429
- const map = this.payoutAddresses;
430
- if (!map || typeof map !== "object") return void 0;
431
- const value = map[currency];
432
- return typeof value === "string" ? value : void 0;
433
- }
434
- /**
435
- * Set the payout destination for a single currency. Mutates the live
436
- * map and returns `this` for chaining. Use {@link clearPayoutAddress}
437
- * to remove a single entry.
438
- */
439
- setPayoutAddress(currency, destination) {
440
- this.payoutAddresses = {
441
- ...this.payoutAddresses ?? {},
442
- [currency]: destination
443
- };
444
- return this;
445
- }
446
- /**
447
- * Remove a single currency entry from the payout map. No-op if the
448
- * currency was already absent.
449
- */
450
- clearPayoutAddress(currency) {
451
- if (!this.payoutAddresses || !(currency in this.payoutAddresses)) return this;
452
- const next = { ...this.payoutAddresses };
453
- delete next[currency];
454
- this.payoutAddresses = next;
455
- return this;
456
- }
457
- /**
458
- * Normalize an input value (object, pre-serialized JSON string, or
459
- * `null`/`undefined`) into a plain `Record<string, string>`. Used by
460
- * the constructor so consumers can pass either shape into
461
- * `VendorCollection.create({ payoutAddresses: ... })`.
462
- *
463
- * Non-string values inside an input object are silently dropped — a
464
- * `Record<string, string>` invariant is what consumers downstream
465
- * (`PaymentIntent` builders, payout SDK adapters) rely on.
466
- */
467
- static normalizePayoutAddresses(value) {
468
- if (value == null) return {};
469
- let parsed = value;
470
- if (typeof value === "string") try {
471
- parsed = JSON.parse(value);
472
- } catch {
473
- return {};
474
- }
475
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
476
- const out = {};
477
- for (const [key, v] of Object.entries(parsed)) if (typeof v === "string") out[key] = v;
478
- return out;
479
- }
480
- };
481
- __publicField$2(Vendor, "__smrtPackage__", "@happyvertical/smrt-commerce");
482
- __decorateClass$2([tenantId({ nullable: true })], Vendor.prototype, "tenantId", 2);
483
- __decorateClass$2([crossPackageRef("@happyvertical/smrt-profiles:Profile", { description: "Links this vendor to their profile record, where their name and contact details are kept." })], Vendor.prototype, "profileId", 2);
484
- __decorateClass$2([field({ description: "How many days the vendor usually takes between your order and delivery." })], Vendor.prototype, "leadTimeDays", 2);
485
- __decorateClass$2([field({
486
- description: "The smallest order the vendor will accept.",
487
- ui: { format: "money" }
488
- })], Vendor.prototype, "minimumOrderAmount", 2);
489
- __decorateClass$2([field({ description: "How long you have to pay this vendor, written the way you would say it, for example \"Net 30\"." })], Vendor.prototype, "paymentTerms", 2);
490
- __decorateClass$2([field({
491
- description: "The currency this vendor bills you in.",
492
- ui: { widget: "currency" }
493
- })], Vendor.prototype, "currency", 2);
494
- __decorateClass$2([field({
495
- sensitive: true,
496
- description: "The vendor tax or VAT registration number kept on file."
497
- })], Vendor.prototype, "taxId", 2);
498
- __decorateClass$2([foreignKey("TaxCode", { description: "The tax code normally used when buying from this vendor." })], Vendor.prototype, "defaultTaxCodeId", 2);
499
- __decorateClass$2([field({
500
- description: "The email address you normally use to reach this vendor.",
501
- ui: { widget: "email" }
502
- })], Vendor.prototype, "defaultContactEmail", 2);
503
- __decorateClass$2([field({
504
- description: "The phone number you normally use to reach this vendor.",
505
- ui: { widget: "phone" }
506
- })], Vendor.prototype, "defaultContactPhone", 2);
507
- __decorateClass$2([field({ description: "Whether you still buy from this vendor: active, inactive or suspended." })], Vendor.prototype, "status", 2);
508
- __decorateClass$2([field({
509
- description: "Anything worth remembering about this vendor.",
510
- ui: { widget: "textarea" }
511
- })], Vendor.prototype, "notes", 2);
512
- __decorateClass$2([field({
513
- sensitive: true,
514
- description: "Where payments to this vendor should be sent."
515
- })], Vendor.prototype, "payoutAddresses", 2);
516
- __decorateClass$2([field({ description: "The people you deal with at this vendor, with their role and how to reach them." })], Vendor.prototype, "contacts", 2);
517
- Vendor = __decorateClass$2([TenantScoped({ mode: "optional" }), smrt({
518
- api: { include: [
519
- "list",
520
- "get",
521
- "create",
522
- "update"
523
- ] },
524
- mcp: { include: ["list", "get"] },
525
- cli: { skipApiCheck: true }
526
- })], Vendor);
527
- //#endregion
528
- //#region src/models/Contract.ts
529
- var __defProp$1 = Object.defineProperty;
530
- var __getOwnPropDesc$1 = Object.getOwnPropertyDescriptor;
531
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, {
532
- enumerable: true,
533
- configurable: true,
534
- writable: true,
535
- value
536
- }) : obj[key] = value;
537
- var __decorateClass$1 = (decorators, target, key, kind) => {
538
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$1(target, key) : target;
539
- for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
540
- if (kind && result) __defProp$1(target, key, result);
541
- return result;
542
- };
543
- var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
544
- var CONTRACT_STATUS_TRANSITIONS = {
545
- [ContractStatus.DRAFT]: [
546
- ContractStatus.SENT,
547
- ContractStatus.ACCEPTED,
548
- ContractStatus.DECLINED,
549
- ContractStatus.CANCELLED
550
- ],
551
- [ContractStatus.SENT]: [
552
- ContractStatus.ACCEPTED,
553
- ContractStatus.DECLINED,
554
- ContractStatus.CANCELLED
555
- ],
556
- [ContractStatus.ACCEPTED]: [ContractStatus.COMPLETED, ContractStatus.CANCELLED],
557
- [ContractStatus.DECLINED]: [],
558
- [ContractStatus.COMPLETED]: [],
559
- [ContractStatus.CANCELLED]: []
560
- };
561
- var loadedContractStatus = /* @__PURE__ */ new WeakMap();
562
- function classifyContractPurchase(contract) {
563
- return "vendorId" in contract;
564
- }
565
- function isContractSnapshotReportEligible(contract) {
566
- return !(contract instanceof SupplierQuote) && contract.status !== ContractStatus.DRAFT && contract.status !== ContractStatus.CANCELLED;
567
- }
568
- var Contract = class extends SmrtObject {
569
- /** @internal Collection read guard returns this snapshot on its root DB. */
570
- rebindMoneyRead(capability, db) {
571
- if (capability !== DOCUMENT_MONEY_READ_REBIND) throw new Error("Contract read rebinding requires the owning capability");
572
- this._db = db;
573
- this.options.db = db;
574
- return this;
575
- }
576
- tenantId = null;
577
- contractType = ContractType.ORDER;
578
- status = ContractStatus.DRAFT;
579
- subtotal = 0;
580
- discountTotal = 0;
581
- taxAmount = 0;
582
- totalAmount = 0;
583
- currency = "USD";
584
- /** Pricing interpretation fixed before the Contract leaves draft. */
585
- lineAmountType = "exclusive";
586
- /** Component rounding scope fixed before the Contract leaves draft. */
587
- taxRoundingScope = "line";
588
- /** Immutable seller registration snapshot once the Contract leaves draft. */
589
- sellerTaxRegistrationsJson = "[]";
590
- get sellerTaxRegistrations() {
591
- try {
592
- const value = JSON.parse(this.sellerTaxRegistrationsJson);
593
- if (!Array.isArray(value)) return [];
594
- return value.filter((entry) => !!entry && typeof entry === "object" && typeof entry.taxComponentId === "string" && typeof entry.number === "string" && typeof entry.label === "string");
595
- } catch {
596
- return [];
597
- }
598
- }
599
- set sellerTaxRegistrations(value) {
600
- this.sellerTaxRegistrationsJson = JSON.stringify(value);
601
- }
602
- /** Immutable customer or vendor tax identifier snapshot after issue. */
603
- partyTaxId = "";
604
- /** Stable issue/freeze identity, independent of lifecycle updated_at. */
605
- moneySnapshotId = "";
606
- issueDate = /* @__PURE__ */ new Date();
607
- dueDate = null;
608
- expiryDate = null;
609
- reference = "";
610
- notes = "";
611
- terms = "";
612
- channelId = "";
613
- constructor(options = {}) {
614
- super(options);
615
- if (options.tenantId !== void 0) this.tenantId = options.tenantId;
616
- if (options.contractType !== void 0) this.contractType = options.contractType;
617
- if (options.status !== void 0) this.status = options.status;
618
- if (options.subtotal !== void 0) this.subtotal = options.subtotal;
619
- if (options.discountTotal !== void 0) this.discountTotal = options.discountTotal;
620
- if (options.taxAmount !== void 0) this.taxAmount = options.taxAmount;
621
- if (options.totalAmount !== void 0) this.totalAmount = options.totalAmount;
622
- if (options.currency !== void 0) this.currency = options.currency;
623
- if (options.lineAmountType !== void 0) this.lineAmountType = options.lineAmountType;
624
- if (options.taxRoundingScope !== void 0) this.taxRoundingScope = options.taxRoundingScope;
625
- if (options.sellerTaxRegistrationsJson !== void 0) this.sellerTaxRegistrationsJson = options.sellerTaxRegistrationsJson;
626
- if (options.sellerTaxRegistrations !== void 0) this.sellerTaxRegistrations = structuredClone(options.sellerTaxRegistrations);
627
- if (options.partyTaxId !== void 0) this.partyTaxId = options.partyTaxId;
628
- if (options.moneySnapshotId !== void 0) this.moneySnapshotId = options.moneySnapshotId;
629
- if (options.issueDate !== void 0) this.issueDate = options.issueDate;
630
- if (options.dueDate !== void 0) this.dueDate = options.dueDate;
631
- if (options.expiryDate !== void 0) this.expiryDate = options.expiryDate;
632
- if (options.reference !== void 0) this.reference = options.reference;
633
- if (options.notes !== void 0) this.notes = options.notes;
634
- if (options.terms !== void 0) this.terms = options.terms;
635
- if (options.channelId !== void 0) this.channelId = options.channelId;
636
- }
637
- /**
638
- * Check if contract is in draft state
639
- */
640
- isDraft() {
641
- return this.status === ContractStatus.DRAFT;
642
- }
643
- /**
644
- * Check if contract is accepted
645
- */
646
- isAccepted() {
647
- return this.status === ContractStatus.ACCEPTED;
648
- }
649
- /**
650
- * Check if contract is completed
651
- */
652
- isCompleted() {
653
- return this.status === ContractStatus.COMPLETED;
654
- }
655
- /**
656
- * Check if contract is expired (for estimates)
657
- */
658
- isExpired() {
659
- if (!this.expiryDate) return false;
660
- return /* @__PURE__ */ new Date() > this.expiryDate;
661
- }
662
- /**
663
- * Check if contract is overdue
664
- */
665
- isOverdue() {
666
- if (!this.dueDate) return false;
667
- if (this.status === ContractStatus.COMPLETED) return false;
668
- return /* @__PURE__ */ new Date() > this.dueDate;
669
- }
670
- /**
671
- * Calculate and update totals from line items
672
- */
673
- async recalculateTotals() {
674
- const { recalculateContractTotals } = await import("./contract-money-EuToOghh.js");
675
- await recalculateContractTotals(this);
676
- }
677
- /**
678
- * Capture the status the row was loaded with so the save-time transition
679
- * guard can reject illegal status flips made via raw field assignment
680
- * (mass-assignment on the generated update route, a stale caller, etc.).
681
- * Only persisted rows carry a prior status.
682
- */
683
- async initialize() {
684
- await super.initialize();
685
- if (this.isPersisted) {
686
- const { assertHydratedMoneyRowCurrent } = await import("./detect-CY9ufaFb.js").then((n) => n.c);
687
- await assertHydratedMoneyRowCurrent(this);
688
- }
689
- if (await this.isSaved()) loadedContractStatus.set(this, this.status);
690
- return this;
691
- }
692
- /**
693
- * Validate the amounts and the status transition before persisting, then
694
- * save. Inherited by every STI subtype (Estimate/Order/Lease/.../LicenseSale),
695
- * so a forged `status` on any of them is caught here. LicenseSale layers its
696
- * own rights-immutability guard on top via `super.save()`. See S5 audit
697
- * #1390.
698
- *
699
- * `subtotal` / `taxAmount` / `totalAmount` are mass-assignable on the
700
- * generated create/update routes, so the minor-units check runs on every
701
- * write surface (#2401).
702
- */
703
- async save() {
704
- const { saveContract } = await import("./contract-money-EuToOghh.js");
705
- return await saveContract(this);
706
- }
707
- /** @internal Contract aggregate persistence only. */
708
- async saveDerived(capability) {
709
- if (capability !== DOCUMENT_MONEY_WRITE) throw new Error("Contract money write capability is required");
710
- assertIntegerMinorUnits("Contract", this.reference || this.id || "<new>", [
711
- ["subtotal", this.subtotal],
712
- ["discountTotal", this.discountTotal],
713
- ["taxAmount", this.taxAmount],
714
- ["totalAmount", this.totalAmount]
715
- ]);
716
- const prior = await this.resolvePriorStatus();
717
- this.assertContractStatusTransition(prior);
718
- const result = await super.save();
719
- loadedContractStatus.set(this, this.status);
720
- return result;
721
- }
722
- /**
723
- * Reject an illegal status flip done via raw assignment. No-op transitions
724
- * and brand-new rows are always allowed.
725
- */
726
- assertContractStatusTransition(prior) {
727
- if (prior === void 0) return;
728
- if (prior === this.status) return;
729
- if (!(CONTRACT_STATUS_TRANSITIONS[prior] ?? []).includes(this.status)) throw new Error(`Contract ${this.reference || this.id}: illegal status transition '${prior}' \u2192 '${this.status}'.`);
730
- }
731
- /**
732
- * Resolve the AUTHORITATIVE prior status (S5 audit #1390 round 5, codex
733
- * MEDIUM#2). The WeakMap is only populated when {@link initialize} loaded the
734
- * row from the DB; it is empty for an instance built via
735
- * `collection.create({ id: <existing>, _skipLoad: true })` — the upsert path
736
- * that lets a caller write onto an existing row without hydrating it. Trusting
737
- * an empty WeakMap there would treat the write as a brand-new row and skip the
738
- * transition guard entirely (a poisonable prior-state). Mirrors the
739
- * authoritative-prior-load applied to Payment/PaymentIntent/Invoice/Payout.
740
- *
741
- * So when this instance carries an `id`, read the persisted row straight from
742
- * the database and treat its `status` as the prior — a create-onto-existing is
743
- * an update. Only when no row exists in the DB (truly new) do we fall back to
744
- * the WeakMap (which is also empty then), i.e. `undefined` = genuinely new.
745
- * The raw row's `status` column is single-word (no snake_case transform).
746
- */
747
- async resolvePriorStatus() {
748
- if (this.id) try {
749
- const row = await this.db.get(this.tableName, { id: this.id });
750
- if (row && row.status != null) return row.status;
751
- } catch {}
752
- return loadedContractStatus.get(this);
753
- }
754
- };
755
- __publicField$1(Contract, "__smrtPackage__", "@happyvertical/smrt-commerce");
756
- /**
757
- * STI discriminator field
758
- */
759
- __publicField$1(Contract, "_stiField", "contractType");
760
- __decorateClass$1([tenantId({ nullable: true })], Contract.prototype, "tenantId", 2);
761
- __decorateClass$1([field({ description: "The kind of contract: order, estimate, lease, agreement and so on." })], Contract.prototype, "contractType", 2);
762
- __decorateClass$1([field({ description: "Where the order or agreement stands, for example draft, sent, accepted or completed." })], Contract.prototype, "status", 2);
763
- __decorateClass$1([field({
764
- description: "The amount before tax.",
765
- ui: { format: "money" }
766
- })], Contract.prototype, "subtotal", 2);
767
- __decorateClass$1([field({ ui: { format: "money" } })], Contract.prototype, "discountTotal", 2);
768
- __decorateClass$1([field({
769
- description: "The tax charged.",
770
- ui: { format: "money" }
771
- })], Contract.prototype, "taxAmount", 2);
772
- __decorateClass$1([field({
773
- description: "The full amount, tax included.",
774
- ui: { format: "money" }
775
- })], Contract.prototype, "totalAmount", 2);
776
- __decorateClass$1([field({
777
- description: "The currency of the amounts.",
778
- ui: { widget: "currency" }
779
- })], Contract.prototype, "currency", 2);
780
- __decorateClass$1([field({ description: "The date it was issued or placed." })], Contract.prototype, "issueDate", 2);
781
- __decorateClass$1([field({ description: "The date payment or delivery is due." })], Contract.prototype, "dueDate", 2);
782
- __decorateClass$1([field({ description: "The last day the price or offer is good for." })], Contract.prototype, "expiryDate", 2);
783
- __decorateClass$1([field({ description: "Your own number or note for finding this later, such as a purchase order or quote number." })], Contract.prototype, "reference", 2);
784
- __decorateClass$1([field({
785
- description: "Anything worth remembering about this.",
786
- ui: { widget: "textarea" }
787
- })], Contract.prototype, "notes", 2);
788
- __decorateClass$1([field({
789
- description: "The conditions agreed, such as deposits, payment or delivery conditions.",
790
- ui: { widget: "textarea" }
791
- })], Contract.prototype, "terms", 2);
792
- __decorateClass$1([field({ description: "Where it came from, for example your shop, a marketplace or a phone call." })], Contract.prototype, "channelId", 2);
793
- Contract = __decorateClass$1([TenantScoped({ mode: "optional" }), smrt({
794
- tableStrategy: "sti",
795
- api: { include: [
796
- "list",
797
- "get",
798
- "create",
799
- "update"
800
- ] },
801
- mcp: { include: ["list", "get"] },
802
- cli: { skipApiCheck: true }
803
- })], Contract);
804
- var SalesContract = class extends Contract {
805
- customerId = null;
806
- constructor(options = {}) {
807
- super(options);
808
- if (options.customerId !== void 0) this.customerId = options.customerId;
809
- }
810
- };
811
- __publicField$1(SalesContract, "__smrtPackage__", "@happyvertical/smrt-commerce");
812
- __decorateClass$1([foreignKey(Customer, { description: "The customer a sales order or agreement is for." })], SalesContract.prototype, "customerId", 2);
813
- SalesContract = __decorateClass$1([TenantScoped({ mode: "optional" }), smrt({ abstract: true })], SalesContract);
814
- var PurchaseContract = class extends Contract {
815
- vendorId = null;
816
- constructor(options = {}) {
817
- super(options);
818
- if (options.vendorId !== void 0) this.vendorId = options.vendorId;
819
- }
820
- };
821
- __publicField$1(PurchaseContract, "__smrtPackage__", "@happyvertical/smrt-commerce");
822
- __decorateClass$1([foreignKey(Vendor, { description: "The vendor supplying this quote or purchase contract." })], PurchaseContract.prototype, "vendorId", 2);
823
- PurchaseContract = __decorateClass$1([TenantScoped({ mode: "optional" }), smrt({ abstract: true })], PurchaseContract);
824
- var Estimate = class extends SalesContract {
825
- customerId = null;
826
- contractType = ContractType.ESTIMATE;
827
- constructor(options = {}) {
828
- super(options);
829
- if (options.customerId !== void 0) this.customerId = options.customerId;
830
- }
831
- };
832
- __publicField$1(Estimate, "__smrtPackage__", "@happyvertical/smrt-commerce");
833
- __decorateClass$1([foreignKey(Customer, { required: true })], Estimate.prototype, "customerId", 2);
834
- Estimate = __decorateClass$1([TenantScoped({ mode: "optional" }), smrt()], Estimate);
835
- var Order = class extends SalesContract {
836
- customerId = null;
837
- contractType = ContractType.ORDER;
838
- constructor(options = {}) {
839
- super(options);
840
- if (options.customerId !== void 0) this.customerId = options.customerId;
841
- }
842
- };
843
- __publicField$1(Order, "__smrtPackage__", "@happyvertical/smrt-commerce");
844
- __decorateClass$1([foreignKey(Customer, { required: true })], Order.prototype, "customerId", 2);
845
- Order = __decorateClass$1([TenantScoped({ mode: "optional" }), smrt()], Order);
846
- var Lease = class extends SalesContract {
847
- customerId = null;
848
- contractType = ContractType.LEASE;
849
- constructor(options = {}) {
850
- super(options);
851
- if (options.customerId !== void 0) this.customerId = options.customerId;
852
- }
853
- };
854
- __publicField$1(Lease, "__smrtPackage__", "@happyvertical/smrt-commerce");
855
- __decorateClass$1([foreignKey(Customer, { required: true })], Lease.prototype, "customerId", 2);
856
- Lease = __decorateClass$1([TenantScoped({ mode: "optional" }), smrt()], Lease);
857
- var Agreement = class extends SalesContract {
858
- customerId = null;
859
- contractType = ContractType.AGREEMENT;
860
- constructor(options = {}) {
861
- super(options);
862
- if (options.customerId !== void 0) this.customerId = options.customerId;
863
- }
864
- };
865
- __publicField$1(Agreement, "__smrtPackage__", "@happyvertical/smrt-commerce");
866
- __decorateClass$1([foreignKey(Customer, { required: true })], Agreement.prototype, "customerId", 2);
867
- Agreement = __decorateClass$1([TenantScoped({ mode: "optional" }), smrt()], Agreement);
868
- var SupplierQuote = class extends PurchaseContract {
869
- vendorId = null;
870
- contractType = ContractType.SUPPLIER_QUOTE;
871
- constructor(options = {}) {
872
- super(options);
873
- if (options.vendorId !== void 0) this.vendorId = options.vendorId;
874
- }
875
- };
876
- __publicField$1(SupplierQuote, "__smrtPackage__", "@happyvertical/smrt-commerce");
877
- __decorateClass$1([foreignKey(Vendor, { required: true })], SupplierQuote.prototype, "vendorId", 2);
878
- SupplierQuote = __decorateClass$1([TenantScoped({ mode: "optional" }), smrt()], SupplierQuote);
879
- var PurchaseOrder = class extends PurchaseContract {
880
- vendorId = null;
881
- contractType = ContractType.PURCHASE_ORDER;
882
- expectedDate = "";
883
- shipTo = "";
884
- /** Construct a purchase order with its optional delivery header. */
885
- constructor(options = {}) {
886
- super(options);
887
- if (options.vendorId !== void 0) this.vendorId = options.vendorId;
888
- if (options.expectedDate !== void 0) this.expectedDate = options.expectedDate;
889
- if (options.shipTo !== void 0) this.shipTo = options.shipTo;
890
- }
891
- };
892
- __publicField$1(PurchaseOrder, "__smrtPackage__", "@happyvertical/smrt-commerce");
893
- __decorateClass$1([foreignKey(Vendor, { required: true })], PurchaseOrder.prototype, "vendorId", 2);
894
- __decorateClass$1([field({ description: "The date you expect the delivery, as YYYY-MM-DD. Leave blank if it is not known." })], PurchaseOrder.prototype, "expectedDate", 2);
895
- __decorateClass$1([field({ description: "Where this order should be delivered, including any delivery instructions." })], PurchaseOrder.prototype, "shipTo", 2);
896
- PurchaseOrder = __decorateClass$1([TenantScoped({ mode: "optional" }), smrt()], PurchaseOrder);
897
- var WholesaleOrder = class extends SalesContract {
898
- customerId = null;
899
- contractType = ContractType.WHOLESALE_ORDER;
900
- constructor(options = {}) {
901
- super(options);
902
- if (options.customerId !== void 0) this.customerId = options.customerId;
903
- }
904
- };
905
- __publicField$1(WholesaleOrder, "__smrtPackage__", "@happyvertical/smrt-commerce");
906
- __decorateClass$1([foreignKey(Customer, { required: true })], WholesaleOrder.prototype, "customerId", 2);
907
- WholesaleOrder = __decorateClass$1([TenantScoped({ mode: "optional" }), smrt()], WholesaleOrder);
908
- var ProductionOrder = class extends PurchaseContract {
909
- contractType = ContractType.PRODUCTION_ORDER;
910
- /**
911
- * Plain string reference to the upstream product the order is asked
912
- * to make. Cross-package id; never `@foreignKey()`. Required by
913
- * `ProductionService.consumeMaterials` unless `bomId` is supplied.
914
- */
915
- productId = "";
916
- /**
917
- * Optional explicit BOM revision the order locked to at posting
918
- * time. When set, manufacturing uses this exact row even if the
919
- * product's active BOM has since changed. When empty, falls back
920
- * to the active BOM for `productId`.
921
- */
922
- bomId = "";
923
- };
924
- __publicField$1(ProductionOrder, "__smrtPackage__", "@happyvertical/smrt-commerce");
925
- ProductionOrder = __decorateClass$1([TenantScoped({ mode: "optional" }), smrt()], ProductionOrder);
926
- var Cart = class extends SalesContract {
927
- contractType = ContractType.CART;
928
- };
929
- __publicField$1(Cart, "__smrtPackage__", "@happyvertical/smrt-commerce");
930
- Cart = __decorateClass$1([TenantScoped({ mode: "optional" }), smrt()], Cart);
931
- var issuedRightsSnapshot = /* @__PURE__ */ new WeakMap();
932
- var LicenseSale = class extends SalesContract {
933
- contractType = ContractType.LICENSE_SALE;
934
- /**
935
- * Plain string reference to the upstream `Sku` (from
936
- * `@happyvertical/smrt-products`) that this license was sold against.
937
- * Cross-package id; never `@foreignKey()`.
938
- */
939
- skuId = "";
940
- /**
941
- * Plain string reference to the `Payment` that satisfied the
942
- * purchase. Cross-model reference matches the rest of the
943
- * package's convention.
944
- */
945
- paymentId = "";
946
- /**
947
- * The licensee's email address — the primary identity carried
948
- * forward into PDF generation and any downstream hash-registry
949
- * publication. Required; without it, downstream rights cannot be
950
- * attributed.
951
- */
952
- licenseeEmail = "";
953
- /**
954
- * Optional legal-entity name of the licensee for purchases that
955
- * warrant it (typically high-tier B2B licenses). Empty string for
956
- * individual-buyer licenses where the email *is* the legal identity.
957
- */
958
- licenseeLegalEntity = "";
959
- /**
960
- * Optional ISO-3166 jurisdiction code of the licensee, captured for
961
- * tax / disclosure / governing-law purposes. Empty when not
962
- * required.
963
- */
964
- licenseeJurisdiction = "";
965
- /** Permitted media — `web,print,social`, `broadcast`, etc. */
966
- rightsMedium = "";
967
- /** Distribution scope — `worldwide`, `territorial`, `private`, etc. */
968
- rightsDistributionScope = "";
969
- /** Exclusivity — `exclusive` / `non-exclusive` / `co-exclusive`. */
970
- rightsExclusivity = "";
971
- /** Duration — `perpetual` / `12-months` / `event-only`, etc. */
972
- rightsDuration = "";
973
- /** Territory — ISO-3166 list, `worldwide`, region name, etc. */
974
- rightsTerritory = "";
975
- /** Whether the licensee may sublicense the rights. */
976
- rightsSublicensing = false;
977
- /** Whether the licensee may create derivative works. */
978
- rightsDerivatives = false;
979
- /** URL of the signed PDF (typically a cloud-storage public URL). */
980
- pdfUrl = "";
981
- /**
982
- * SHA-256 of the signed PDF bytes (hex string, no `0x` prefix).
983
- * Lets downstream consumers verify the PDF the licensee holds is
984
- * the one this row was issued for, without re-fetching.
985
- */
986
- pdfHash = "";
987
- /**
988
- * Optional reference to an on-chain hash-registry entry — set when
989
- * the LicenseSale's `pdfHash` has been anchored on a public chain
990
- * for tamper-evidence. Format is whatever the hash-registry
991
- * service emits (e.g. `chain:tx-hash:log-index`). Empty for
992
- * deployments that don't publish hashes on-chain.
993
- */
994
- onChainHashRegistryRef = "";
995
- constructor(options = {}) {
996
- super(options);
997
- if (options.skuId !== void 0) this.skuId = options.skuId;
998
- if (options.paymentId !== void 0) this.paymentId = options.paymentId;
999
- if (options.licenseeEmail !== void 0) this.licenseeEmail = options.licenseeEmail;
1000
- if (options.licenseeLegalEntity !== void 0) this.licenseeLegalEntity = options.licenseeLegalEntity;
1001
- if (options.licenseeJurisdiction !== void 0) this.licenseeJurisdiction = options.licenseeJurisdiction;
1002
- if (options.rightsMedium !== void 0) this.rightsMedium = options.rightsMedium;
1003
- if (options.rightsDistributionScope !== void 0) this.rightsDistributionScope = options.rightsDistributionScope;
1004
- if (options.rightsExclusivity !== void 0) this.rightsExclusivity = options.rightsExclusivity;
1005
- if (options.rightsDuration !== void 0) this.rightsDuration = options.rightsDuration;
1006
- if (options.rightsTerritory !== void 0) this.rightsTerritory = options.rightsTerritory;
1007
- if (options.rightsSublicensing !== void 0) this.rightsSublicensing = options.rightsSublicensing;
1008
- if (options.rightsDerivatives !== void 0) this.rightsDerivatives = options.rightsDerivatives;
1009
- if (options.pdfUrl !== void 0) this.pdfUrl = options.pdfUrl;
1010
- if (options.pdfHash !== void 0) this.pdfHash = options.pdfHash;
1011
- if (options.onChainHashRegistryRef !== void 0) this.onChainHashRegistryRef = options.onChainHashRegistryRef;
1012
- }
1013
- /**
1014
- * Once `super.initialize()` has applied the framework's option-
1015
- * override pass, capture the rights snapshot if (and only if) the
1016
- * row arrived already issued. That's how the immutability guard
1017
- * tells "freshly drafting a license" (snapshot still mutable) apart
1018
- * from "loaded an already-issued row" (snapshot frozen).
1019
- */
1020
- async initialize() {
1021
- await super.initialize();
1022
- if (this.status === ContractStatus.ACCEPTED && await this.isSaved()) issuedRightsSnapshot.set(this, this.serializeRightsSnapshot());
1023
- return this;
1024
- }
1025
- /**
1026
- * Return the current rights snapshot as a typed object. Read-only
1027
- * for callers — mutation should go through assignment to the
1028
- * individual `rights*` fields, gated by the issued-immutability
1029
- * guard.
1030
- */
1031
- getRightsSnapshot() {
1032
- return {
1033
- medium: this.rightsMedium,
1034
- distributionScope: this.rightsDistributionScope,
1035
- exclusivity: this.rightsExclusivity,
1036
- duration: this.rightsDuration,
1037
- territory: this.rightsTerritory,
1038
- sublicensing: this.rightsSublicensing,
1039
- derivatives: this.rightsDerivatives
1040
- };
1041
- }
1042
- /**
1043
- * Revoke an issued license — moves status to `CANCELLED` without
1044
- * touching the rights snapshot (which stays frozen). Throws if
1045
- * called on a non-issued license; a draft license should be
1046
- * deleted, not revoked.
1047
- */
1048
- revoke() {
1049
- if (this.status !== ContractStatus.ACCEPTED) throw new Error(`LicenseSale ${this.id ?? "<new>"}: cannot revoke from status '${this.status}' \u2014 only ACCEPTED licenses can be revoked`);
1050
- this.status = ContractStatus.CANCELLED;
1051
- }
1052
- /**
1053
- * Save with the immutability check: if the row was loaded with
1054
- * `ACCEPTED` status, the rights snapshot at save time must match
1055
- * the snapshot at load time. Anything else means an out-of-band
1056
- * mutation crept in and we surface it instead of letting the row
1057
- * drift silently.
1058
- *
1059
- * Newly-drafted licenses (where the row was constructed without
1060
- * `ACCEPTED` status) capture their snapshot at the moment the
1061
- * caller transitions to `ACCEPTED` and saves — `validateImmutable`
1062
- * picks that up post-save on the next call.
1063
- */
1064
- async save() {
1065
- this.validateImmutable();
1066
- const result = await super.save();
1067
- if (this.status === ContractStatus.ACCEPTED && !issuedRightsSnapshot.has(this)) issuedRightsSnapshot.set(this, this.serializeRightsSnapshot());
1068
- return result;
1069
- }
1070
- /**
1071
- * Compare the current rights against the captured snapshot
1072
- * (populated either at load time by `initialize` or at first
1073
- * issuance by `save`). Throws on mismatch.
1074
- */
1075
- validateImmutable() {
1076
- const captured = issuedRightsSnapshot.get(this);
1077
- if (!captured) return;
1078
- if (captured !== this.serializeRightsSnapshot()) throw new Error(`LicenseSale ${this.id ?? "<new>"}: rights snapshot is immutable once issued (status=ACCEPTED). Use revoke() to cancel the existing license and issue a new one with the updated rights.`);
1079
- }
1080
- serializeRightsSnapshot() {
1081
- return JSON.stringify({
1082
- medium: this.rightsMedium,
1083
- distributionScope: this.rightsDistributionScope,
1084
- exclusivity: this.rightsExclusivity,
1085
- duration: this.rightsDuration,
1086
- territory: this.rightsTerritory,
1087
- sublicensing: this.rightsSublicensing,
1088
- derivatives: this.rightsDerivatives
1089
- });
1090
- }
1091
- };
1092
- __publicField$1(LicenseSale, "__smrtPackage__", "@happyvertical/smrt-commerce");
1093
- LicenseSale = __decorateClass$1([TenantScoped({ mode: "optional" }), smrt()], LicenseSale);
1094
- //#endregion
1095
- //#region src/collections/PurchaseContractCollection.ts
1096
- var PurchaseContractCollection = class extends SmrtCollection {
1097
- static _itemClass = PurchaseContract;
1098
- async findByVendor(vendorId) {
1099
- return this.list({
1100
- where: { vendorId },
1101
- orderBy: "created_at DESC"
1102
- });
1103
- }
1104
- };
1105
- //#endregion
1106
- //#region src/collections/SalesContractCollection.ts
1107
- var SalesContractCollection = class extends SmrtCollection {
1108
- static _itemClass = SalesContract;
1109
- async findByCustomer(customerId) {
1110
- return this.list({
1111
- where: { customerId },
1112
- orderBy: "created_at DESC"
1113
- });
1114
- }
1115
- };
1116
- //#endregion
1117
- //#region src/collections/ContractCollection.ts
1118
- var ContractCollection = class extends SmrtCollection {
1119
- static _itemClass = Contract;
1120
- async withMoneyRead(operation) {
1121
- const rootDb = this.db;
1122
- const tenantId = getTenantId();
1123
- if (!tenantId) {
1124
- await assertCommerceMoneySchemaCurrent(rootDb);
1125
- return operation();
1126
- }
1127
- const result = await withTenantMoneyCollectionRead(rootDb, tenantId, (boundDb) => this.withDatabase(boundDb, operation));
1128
- if (result instanceof Contract) result.rebindMoneyRead(DOCUMENT_MONEY_READ_REBIND, rootDb);
1129
- else if (Array.isArray(result)) {
1130
- for (const item of result) if (item instanceof Contract) item.rebindMoneyRead(DOCUMENT_MONEY_READ_REBIND, rootDb);
1131
- }
1132
- return result;
1133
- }
1134
- async get(filter, options = {}) {
1135
- return this.withMoneyRead(() => super.get(filter, options));
1136
- }
1137
- async list(options = {}) {
1138
- return this.withMoneyRead(() => super.list(options));
1139
- }
1140
- /**
1141
- * Find contracts by customer
1142
- *
1143
- * @param customerId - Customer ID
1144
- * @returns Array of contracts
1145
- * @deprecated Use SalesContractCollection.findByCustomer.
1146
- */
1147
- async findByCustomer(customerId) {
1148
- return (await SalesContractCollection.create({
1149
- ...this.options,
1150
- db: this.db
1151
- })).findByCustomer(customerId);
1152
- }
1153
- /**
1154
- * Find contracts by vendor
1155
- *
1156
- * @param vendorId - Vendor ID
1157
- * @returns Array of contracts
1158
- * @deprecated Use PurchaseContractCollection.findByVendor.
1159
- */
1160
- async findByVendor(vendorId) {
1161
- return (await PurchaseContractCollection.create({
1162
- ...this.options,
1163
- db: this.db
1164
- })).findByVendor(vendorId);
1165
- }
1166
- /**
1167
- * Hydrate a bounded tenant/date report candidate set once, retaining exact
1168
- * STI descendants so callers can classify custom purchase types safely.
1169
- */
1170
- async listSnapshotReportContracts(options) {
1171
- return (await this.list({
1172
- where: {
1173
- tenantId: options.tenantId,
1174
- "issueDate >=": options.from.toISOString(),
1175
- "issueDate <=": options.to.toISOString()
1176
- },
1177
- orderBy: "issueDate ASC"
1178
- })).filter(isContractSnapshotReportEligible);
1179
- }
1180
- /**
1181
- * Find contracts by type (STI)
1182
- *
1183
- * @param contractType - Contract type
1184
- * @returns Array of contracts
1185
- */
1186
- async findByType(contractType) {
1187
- return await this.list({
1188
- where: { contractType },
1189
- orderBy: "created_at DESC"
1190
- });
1191
- }
1192
- /**
1193
- * Find contracts by status
1194
- *
1195
- * @param status - Contract status
1196
- * @returns Array of contracts
1197
- */
1198
- async findByStatus(status) {
1199
- return await this.list({
1200
- where: { status },
1201
- orderBy: "created_at DESC"
1202
- });
1203
- }
1204
- /**
1205
- * Find all draft contracts
1206
- *
1207
- * @returns Array of draft contracts
1208
- */
1209
- async findDrafts() {
1210
- return await this.findByStatus(ContractStatus.DRAFT);
1211
- }
1212
- /**
1213
- * Find all accepted contracts
1214
- *
1215
- * @returns Array of accepted contracts
1216
- */
1217
- async findAccepted() {
1218
- return await this.findByStatus(ContractStatus.ACCEPTED);
1219
- }
1220
- /**
1221
- * Find overdue contracts
1222
- *
1223
- * @returns Array of overdue contracts
1224
- */
1225
- async findOverdue() {
1226
- const now = (/* @__PURE__ */ new Date()).toISOString();
1227
- return (await this.list({
1228
- where: { "dueDate <": now },
1229
- orderBy: "dueDate ASC"
1230
- })).filter((c) => c.status !== ContractStatus.COMPLETED && c.status !== ContractStatus.CANCELLED);
1231
- }
1232
- /**
1233
- * Find expired estimates/quotes
1234
- *
1235
- * @returns Array of expired estimates
1236
- */
1237
- async findExpired() {
1238
- const now = (/* @__PURE__ */ new Date()).toISOString();
1239
- return (await this.list({
1240
- where: {
1241
- contractType: ContractType.ESTIMATE,
1242
- "expiryDate <": now
1243
- },
1244
- orderBy: "expiryDate ASC"
1245
- })).filter((c) => c.status !== ContractStatus.ACCEPTED && c.status !== ContractStatus.DECLINED && c.status !== ContractStatus.CANCELLED);
1246
- }
1247
- /**
1248
- * Find contracts in date range
1249
- *
1250
- * @param startDate - Start date
1251
- * @param endDate - End date
1252
- * @returns Array of contracts
1253
- */
1254
- async findByDateRange(startDate, endDate) {
1255
- return await this.list({
1256
- where: {
1257
- "issueDate >=": startDate.toISOString(),
1258
- "issueDate <=": endDate.toISOString()
1259
- },
1260
- orderBy: "issueDate DESC"
1261
- });
1262
- }
1263
- /**
1264
- * Find all contracts belonging to a specific tenant
1265
- *
1266
- * @param tenantId - Tenant ID
1267
- * @returns Array of contracts for the tenant
1268
- */
1269
- async findByTenant(tenantId) {
1270
- return this.list({ where: { tenantId } });
1271
- }
1272
- /**
1273
- * Find all global contracts (not associated with any tenant).
1274
- *
1275
- * Routes through the shared tenant-global helper so it does not throw under
1276
- * an active tenant context (an explicit `tenant_id IS NULL` filter would be
1277
- * flagged as an isolation violation). (#1600)
1278
- *
1279
- * @returns Array of global contracts
1280
- */
1281
- async findGlobal() {
1282
- return queryGlobal(this);
1283
- }
1284
- /**
1285
- * Find contracts for a tenant including global contracts.
1286
- *
1287
- * Fails closed if an active tenant context requests a different tenant's
1288
- * rows; the admin/system path keeps the cross-tenant capability. (#1600)
1289
- *
1290
- * @param tenantId - Tenant ID
1291
- * @returns Array of tenant-specific and global contracts
1292
- */
1293
- async findWithGlobals(tenantId) {
1294
- return queryWithGlobals(this, tenantId, "Contract.findWithGlobals");
1295
- }
1296
- };
1297
- //#endregion
1298
- //#region src/models/DocumentTax.ts
1299
- var __defProp = Object.defineProperty;
1300
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
1301
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, {
1302
- enumerable: true,
1303
- configurable: true,
1304
- writable: true,
1305
- value
1306
- }) : obj[key] = value;
1307
- var __decorateClass = (decorators, target, key, kind) => {
1308
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
1309
- for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
1310
- if (kind && result) __defProp(target, key, result);
1311
- return result;
1312
- };
1313
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
1314
- var DocumentTax = class extends SmrtObject {
1315
- tenantId = "";
1316
- documentType = "invoice";
1317
- documentId = "";
1318
- currency = "USD";
1319
- taxCodeId = null;
1320
- taxCodeCode = null;
1321
- kind = null;
1322
- taxComponentId = null;
1323
- taxComponentName = null;
1324
- percent = null;
1325
- liabilityAccountId = null;
1326
- taxableMinor = 0;
1327
- taxMinor = 0;
1328
- recoverableMinor = 0;
1329
- constructor(options = {}) {
1330
- super(options);
1331
- if (options.tenantId !== void 0) this.tenantId = options.tenantId;
1332
- if (options.documentType !== void 0) this.documentType = options.documentType;
1333
- if (options.documentId !== void 0) this.documentId = options.documentId;
1334
- if (options.currency !== void 0) this.currency = options.currency;
1335
- if (options.taxCodeId !== void 0) this.taxCodeId = options.taxCodeId;
1336
- if (options.taxCodeCode !== void 0) this.taxCodeCode = options.taxCodeCode;
1337
- if (options.kind !== void 0) this.kind = options.kind;
1338
- if (options.taxComponentId !== void 0) this.taxComponentId = options.taxComponentId;
1339
- if (options.taxComponentName !== void 0) this.taxComponentName = options.taxComponentName;
1340
- if (options.percent !== void 0) this.percent = options.percent;
1341
- if (options.liabilityAccountId !== void 0) this.liabilityAccountId = options.liabilityAccountId;
1342
- if (options.taxableMinor !== void 0) this.taxableMinor = options.taxableMinor;
1343
- if (options.taxMinor !== void 0) this.taxMinor = options.taxMinor;
1344
- if (options.recoverableMinor !== void 0) this.recoverableMinor = options.recoverableMinor;
1345
- }
1346
- assertValidDerivedRow() {
1347
- if (![
1348
- "invoice",
1349
- "contract",
1350
- "credit_note"
1351
- ].includes(this.documentType)) throw new MoneyValidationError("INVALID_MONEY_INPUT", `Unknown document tax type: ${this.documentType}`);
1352
- for (const [label, value] of [
1353
- ["tenantId", this.tenantId],
1354
- ["documentId", this.documentId],
1355
- ["currency", this.currency]
1356
- ]) if (!value || value.trim() !== value) throw new MoneyValidationError("INVALID_MONEY_INPUT", `DocumentTax ${label} must be a nonempty value`);
1357
- for (const [label, value] of [
1358
- ["taxableMinor", this.taxableMinor],
1359
- ["taxMinor", this.taxMinor],
1360
- ["recoverableMinor", this.recoverableMinor]
1361
- ]) if (!Number.isSafeInteger(value)) throw new MoneyValidationError("UNSAFE_MONEY", `DocumentTax ${label} must be safe integer minor units`);
1362
- if (this.taxCodeId === null) {
1363
- if (this.taxComponentId !== null || this.taxCodeCode !== null || this.kind !== null || this.taxComponentName !== null || this.percent !== null || this.liabilityAccountId !== null || this.taxMinor !== 0 || this.recoverableMinor !== 0) throw new MoneyValidationError("INVALID_MONEY_INPUT", "An unassigned DocumentTax row cannot carry code/component snapshots or tax");
1364
- return;
1365
- }
1366
- if (!this.taxCodeCode || !this.kind) throw new MoneyValidationError("INVALID_MONEY_INPUT", "Assigned DocumentTax rows require code and kind snapshots");
1367
- if (this.taxComponentId === null) {
1368
- if (this.kind === "taxable" || this.taxComponentName !== null || this.percent !== null || this.liabilityAccountId !== null || this.taxMinor !== 0 || this.recoverableMinor !== 0) throw new MoneyValidationError("INVALID_MONEY_INPUT", "Component-less DocumentTax rows must be non-taxable zero-tax snapshots");
1369
- return;
1370
- }
1371
- if (this.kind !== "taxable" || !this.taxComponentName || !this.percent) throw new MoneyValidationError("INVALID_MONEY_INPUT", "Component DocumentTax rows require taxable component snapshots");
1372
- if (this.recoverableMinor !== 0 && this.recoverableMinor !== this.taxMinor) throw new MoneyValidationError("INVALID_MONEY_INPUT", "DocumentTax recoverableMinor must be zero or the component tax total");
1373
- }
1374
- async save() {
1375
- throw new MoneyValidationError("FROZEN_DOCUMENT", "DocumentTax rows are derived and cannot be saved directly");
1376
- }
1377
- async delete(_options = {}) {
1378
- throw new MoneyValidationError("FROZEN_DOCUMENT", "DocumentTax rows are derived and cannot be deleted directly");
1379
- }
1380
- /** @internal Aggregate persistence only. */
1381
- async saveDerived(capability) {
1382
- if (capability !== DOCUMENT_MONEY_WRITE) throw new MoneyValidationError("FROZEN_DOCUMENT", "DocumentTax write capability is required");
1383
- this.assertValidDerivedRow();
1384
- return await super.save();
1385
- }
1386
- /** @internal Aggregate persistence only. */
1387
- async deleteDerived(capability, options = {}) {
1388
- if (capability !== DOCUMENT_MONEY_WRITE) throw new MoneyValidationError("FROZEN_DOCUMENT", "DocumentTax write capability is required");
1389
- await super.delete(options);
1390
- }
1391
- };
1392
- __publicField(DocumentTax, "__smrtPackage__", "@happyvertical/smrt-commerce");
1393
- __decorateClass([tenantId()], DocumentTax.prototype, "tenantId", 2);
1394
- __decorateClass([field({ required: true })], DocumentTax.prototype, "documentType", 2);
1395
- __decorateClass([field({ required: true })], DocumentTax.prototype, "documentId", 2);
1396
- __decorateClass([field({ required: true })], DocumentTax.prototype, "currency", 2);
1397
- __decorateClass([field({ nullable: true })], DocumentTax.prototype, "taxCodeId", 2);
1398
- __decorateClass([field({ nullable: true })], DocumentTax.prototype, "taxCodeCode", 2);
1399
- __decorateClass([field({ nullable: true })], DocumentTax.prototype, "kind", 2);
1400
- __decorateClass([field({ nullable: true })], DocumentTax.prototype, "taxComponentId", 2);
1401
- __decorateClass([field({ nullable: true })], DocumentTax.prototype, "taxComponentName", 2);
1402
- __decorateClass([field({
1403
- type: "decimal",
1404
- nullable: true
1405
- })], DocumentTax.prototype, "percent", 2);
1406
- __decorateClass([field({ nullable: true })], DocumentTax.prototype, "liabilityAccountId", 2);
1407
- __decorateClass([field({
1408
- description: "Tax-exclusive base in integer minor units.",
1409
- ui: { format: "money" }
1410
- })], DocumentTax.prototype, "taxableMinor", 2);
1411
- __decorateClass([field({
1412
- description: "Tax total in integer minor units.",
1413
- ui: { format: "money" }
1414
- })], DocumentTax.prototype, "taxMinor", 2);
1415
- __decorateClass([field({
1416
- description: "Recoverable purchase tax in integer minor units.",
1417
- ui: { format: "money" }
1418
- })], DocumentTax.prototype, "recoverableMinor", 2);
1419
- DocumentTax = __decorateClass([TenantScoped({ mode: "required" }), smrt({
1420
- tableName: "document_taxes",
1421
- conflictColumns: [
1422
- "document_type",
1423
- "document_id",
1424
- "tax_code_id",
1425
- "tax_component_id"
1426
- ],
1427
- api: { include: ["list", "get"] },
1428
- mcp: { include: ["list", "get"] },
1429
- cli: { include: ["list", "get"] }
1430
- })], DocumentTax);
1431
- //#endregion
1432
- //#region src/collections/DocumentTaxCollection.ts
1433
- var DocumentTaxCollection_exports = /* @__PURE__ */ __exportAll({ DocumentTaxCollection: () => DocumentTaxCollection });
1434
- var TAX_CODE_KINDS = /* @__PURE__ */ new Set([
1435
- "taxable",
1436
- "zero-rated",
1437
- "exempt",
1438
- "out-of-scope"
1439
- ]);
1440
- function requiredText(value, label) {
1441
- if (typeof value !== "string" || !value.trim()) throw new Error(`Invoice tax report ${label} must be a nonempty string.`);
1442
- return value;
1443
- }
1444
- function storedMinor(value, label) {
1445
- const parsed = typeof value === "bigint" ? Number(value) : typeof value === "number" ? value : typeof value === "string" && /^-?\d+$/.test(value) ? Number(value) : NaN;
1446
- if (!Number.isSafeInteger(parsed)) throw new RangeError(`Invoice tax report ${label} must be a safe integer minor-unit value.`);
1447
- return parsed;
1448
- }
1449
- function reportDate(value, label) {
1450
- const date = new Date(String(value));
1451
- if (Number.isNaN(date.getTime())) throw new Error(`Invoice tax report ${label} must be a valid date.`);
1452
- return date.toISOString();
1453
- }
1454
- function invoiceDocumentType(value) {
1455
- if (value === "invoice" || value === "credit_note") return value;
1456
- throw new Error("Invoice tax report document type must be invoice or credit_note.");
1457
- }
1458
- function invoiceKind(value) {
1459
- if (value === "invoice" || value === "credit_note") return value;
1460
- throw new Error("Invoice tax report kind must be invoice or credit_note.");
1461
- }
1462
- function contractDocumentType(value) {
1463
- if (value === "contract") return value;
1464
- throw new Error("Contract tax report document type must be contract.");
1465
- }
1466
- function taxCodeKind(value) {
1467
- return typeof value === "string" && TAX_CODE_KINDS.has(value) ? value : null;
1468
- }
1469
- function assertReportFactOptions(options) {
1470
- if (!options.tenantId?.trim()) throw new Error("Invoice tax report facts require a tenant.");
1471
- if (!(options.from instanceof Date) || Number.isNaN(options.from.getTime())) throw new Error("Invoice tax report facts require a valid start date.");
1472
- if (!(options.to instanceof Date) || Number.isNaN(options.to.getTime())) throw new Error("Invoice tax report facts require a valid end date.");
1473
- if (options.from > options.to) throw new Error("Invoice tax report facts require an ordered date range.");
1474
- if (options.currency !== void 0 && !options.currency.trim()) throw new Error("Invoice tax report currency must be nonempty when supplied.");
1475
- }
1476
- function compareCodeUnits(left, right) {
1477
- return left < right ? -1 : left > right ? 1 : 0;
1478
- }
1479
- function identity(row) {
1480
- return `${row.taxCodeId === null ? "0:" : `1:${row.taxCodeId}`}\0${row.taxComponentId === null ? "0:" : `1:${row.taxComponentId}`}`;
1481
- }
1482
- var BUSINESS_FIELDS = [
1483
- "tenantId",
1484
- "documentType",
1485
- "documentId",
1486
- "currency",
1487
- "taxCodeId",
1488
- "taxCodeCode",
1489
- "kind",
1490
- "taxComponentId",
1491
- "taxComponentName",
1492
- "percent",
1493
- "liabilityAccountId",
1494
- "taxableMinor",
1495
- "taxMinor",
1496
- "recoverableMinor"
1497
- ];
1498
- function unchanged(row, input) {
1499
- return BUSINESS_FIELDS.every((field) => {
1500
- const persisted = row[field];
1501
- const proposed = input[field];
1502
- if (field === "percent" && persisted !== null && proposed !== null) return String(persisted) === String(proposed);
1503
- return (persisted ?? null) === (proposed ?? null);
1504
- });
1505
- }
1506
- var DocumentTaxCollection = class extends SmrtCollection {
1507
- static _itemClass = DocumentTax;
1508
- /**
1509
- * Read immutable commerce document-tax snapshots for one tenant.
1510
- *
1511
- * Invoice/credit rows join their shared storage by identity and tenant.
1512
- * Purchase Contract rows first use the Contract owner's bounded hydrated
1513
- * candidate API so custom PurchaseContract descendants retain their STI
1514
- * classification. The query then joins only those candidate ids by identity
1515
- * and tenant. Stored snapshots remain authoritative; this never recalculates
1516
- * money or resolves present-day tax configuration.
1517
- */
1518
- async listReportFacts(options) {
1519
- assertReportFactOptions(options);
1520
- const [invoiceFacts, purchaseFacts] = await Promise.all([this.listInvoiceReportFacts(options), this.listPurchaseContractReportFacts(options)]);
1521
- return [...invoiceFacts, ...purchaseFacts].sort((left, right) => left.issueDate.localeCompare(right.issueDate) || left.documentId.localeCompare(right.documentId) || String(left.taxCodeId).localeCompare(String(right.taxCodeId)) || String(left.taxComponentId).localeCompare(String(right.taxComponentId)));
1522
- }
1523
- async listInvoiceReportFacts(options) {
1524
- const currencyClause = options.currency ? " AND d.currency = ?" : "";
1525
- return (await this.db.query(`SELECT d.tenant_id, d.document_type, d.document_id, d.currency, d.tax_code_id, d.kind,
1526
- d.tax_component_id, d.tax_component_name, d.liability_account_id,
1527
- d.taxable_minor, d.tax_minor, d.recoverable_minor,
1528
- i.kind AS invoice_kind, i.invoice_number, i.customer_id, i.issue_date, i.status
1529
- FROM document_taxes d
1530
- JOIN invoices i
1531
- ON CAST(i.id AS TEXT) = CAST(d.document_id AS TEXT)
1532
- AND i.tenant_id = d.tenant_id
1533
- WHERE CAST(d.tenant_id AS TEXT) = ?
1534
- AND CAST(i.tenant_id AS TEXT) = ?
1535
- AND (
1536
- (d.document_type = 'invoice' AND i.kind = 'invoice')
1537
- OR (d.document_type = 'credit_note' AND i.kind = 'credit_note')
1538
- )
1539
- AND i.status NOT IN ('draft', 'cancelled')
1540
- AND i.issue_date >= ?
1541
- AND i.issue_date <= ?${currencyClause}
1542
- ORDER BY i.issue_date ASC, i.id ASC, d.tax_code_id ASC, d.tax_component_id ASC`, options.tenantId, options.tenantId, options.from.toISOString(), options.to.toISOString(), ...options.currency ? [options.currency] : [])).rows.map((row) => ({
1543
- tenantId: requiredText(row.tenant_id, "tenant id"),
1544
- documentType: invoiceDocumentType(row.document_type),
1545
- documentId: requiredText(row.document_id, "document id"),
1546
- documentNumber: requiredText(row.invoice_number, "invoice number"),
1547
- partyId: typeof row.customer_id === "string" && row.customer_id.trim() ? row.customer_id : null,
1548
- documentKind: invoiceKind(row.invoice_kind),
1549
- issueDate: reportDate(row.issue_date, "issue date"),
1550
- status: requiredText(row.status, "invoice status"),
1551
- direction: "sales",
1552
- currency: requiredText(row.currency, "currency"),
1553
- taxCodeId: row.tax_code_id == null ? null : String(row.tax_code_id),
1554
- taxCodeKind: taxCodeKind(row.kind),
1555
- taxableMinor: storedMinor(row.taxable_minor, "taxable minor"),
1556
- taxMinor: storedMinor(row.tax_minor, "tax minor"),
1557
- recoverableMinor: storedMinor(row.recoverable_minor, "recoverable minor"),
1558
- taxComponentId: row.tax_component_id == null ? null : String(row.tax_component_id),
1559
- componentName: row.tax_component_name == null ? null : String(row.tax_component_name),
1560
- liabilityAccountId: row.liability_account_id == null ? null : String(row.liability_account_id),
1561
- commitmentId: null,
1562
- commitmentLineId: null
1563
- }));
1564
- }
1565
- async listPurchaseContractReportFacts(options) {
1566
- const purchases = (await withTenant({ tenantId: options.tenantId }, () => ContractCollection.create({ db: this.db }).then((collection) => collection.listSnapshotReportContracts({
1567
- tenantId: options.tenantId,
1568
- from: options.from,
1569
- to: options.to
1570
- })))).filter(classifyContractPurchase);
1571
- const ids = purchases.flatMap((contract) => contract.id ? [contract.id] : []);
1572
- if (ids.length === 0) return [];
1573
- const byId = new Map(purchases.flatMap((contract) => contract.id ? [[contract.id, contract]] : []));
1574
- const placeholders = ids.map(() => "?").join(", ");
1575
- const currencyClause = options.currency ? " AND d.currency = ?" : "";
1576
- return (await this.db.query(`SELECT d.tenant_id, d.document_type, d.document_id, d.currency, d.tax_code_id, d.kind,
1577
- d.tax_component_id, d.tax_component_name, d.liability_account_id,
1578
- d.taxable_minor, d.tax_minor, d.recoverable_minor
1579
- FROM document_taxes d
1580
- JOIN contracts c
1581
- ON CAST(c.id AS TEXT) = CAST(d.document_id AS TEXT)
1582
- AND c.tenant_id = d.tenant_id
1583
- WHERE CAST(d.tenant_id AS TEXT) = ?
1584
- AND CAST(c.tenant_id AS TEXT) = ?
1585
- AND d.document_type = 'contract'
1586
- AND c.status NOT IN ('draft', 'cancelled')
1587
- AND CAST(d.document_id AS TEXT) IN (${placeholders})${currencyClause}
1588
- ORDER BY c.issue_date ASC, c.id ASC, d.tax_code_id ASC, d.tax_component_id ASC`, options.tenantId, options.tenantId, ...ids, ...options.currency ? [options.currency] : [])).rows.flatMap((row) => {
1589
- const documentId = requiredText(row.document_id, "contract id");
1590
- const contract = byId.get(documentId);
1591
- if (!contract) return [];
1592
- return [{
1593
- tenantId: requiredText(row.tenant_id, "tenant id"),
1594
- documentType: contractDocumentType(row.document_type),
1595
- documentId,
1596
- documentNumber: contract.reference.trim() || documentId,
1597
- partyId: "vendorId" in contract && typeof contract.vendorId === "string" && contract.vendorId.trim() ? contract.vendorId : null,
1598
- documentKind: "contract",
1599
- issueDate: reportDate(contract.issueDate, "contract issue date"),
1600
- status: requiredText(contract.status, "contract status"),
1601
- direction: "purchase",
1602
- currency: requiredText(row.currency, "currency"),
1603
- taxCodeId: row.tax_code_id == null ? null : String(row.tax_code_id),
1604
- taxCodeKind: taxCodeKind(row.kind),
1605
- taxableMinor: storedMinor(row.taxable_minor, "taxable minor"),
1606
- taxMinor: storedMinor(row.tax_minor, "tax minor"),
1607
- recoverableMinor: storedMinor(row.recoverable_minor, "recoverable minor"),
1608
- taxComponentId: row.tax_component_id == null ? null : String(row.tax_component_id),
1609
- componentName: row.tax_component_name == null ? null : String(row.tax_component_name),
1610
- liabilityAccountId: row.liability_account_id == null ? null : String(row.liability_account_id),
1611
- commitmentId: documentId,
1612
- commitmentLineId: null
1613
- }];
1614
- });
1615
- }
1616
- async findByDocument(tenantId, documentType, documentId) {
1617
- return this.list({
1618
- where: {
1619
- tenantId,
1620
- documentType,
1621
- documentId
1622
- },
1623
- orderBy: ["taxCodeId ASC", "taxComponentId ASC"]
1624
- });
1625
- }
1626
- /**
1627
- * Replace one draft document's derived rows on the caller's transaction.
1628
- * Unchanged rows are not saved, preserving their exact persisted bytes.
1629
- *
1630
- * @internal Aggregate persistence only.
1631
- */
1632
- async replaceDerivedForDocument(capability, input) {
1633
- if (capability !== DOCUMENT_MONEY_WRITE) throw new MoneyValidationError("FROZEN_DOCUMENT", "DocumentTax write capability is required");
1634
- const desired = /* @__PURE__ */ new Map();
1635
- for (const row of input.rows) {
1636
- if (row.tenantId !== input.tenantId || row.documentType !== input.documentType || row.documentId !== input.documentId) throw new MoneyValidationError("INVALID_MONEY_INPUT", "DocumentTax replacement rows must share tenant and document identity");
1637
- const key = identity(row);
1638
- if (desired.has(key)) throw new MoneyValidationError("INVALID_MONEY_INPUT", "DocumentTax replacement contains a duplicate code/component identity");
1639
- desired.set(key, row);
1640
- }
1641
- const existing = await this.findByDocument(input.tenantId, input.documentType, input.documentId);
1642
- const byIdentity = new Map(existing.map((row) => [identity(row), row]));
1643
- const result = [];
1644
- for (const [key, rowInput] of [...desired].sort(([left], [right]) => compareCodeUnits(left, right))) {
1645
- const current = byIdentity.get(key);
1646
- if (current) {
1647
- byIdentity.delete(key);
1648
- if (!unchanged(current, rowInput)) {
1649
- Object.assign(current, rowInput);
1650
- await current.saveDerived(capability);
1651
- }
1652
- result.push(current);
1653
- continue;
1654
- }
1655
- const created = await this.createUnsaved(rowInput);
1656
- await created.saveDerived(capability);
1657
- result.push(created);
1658
- }
1659
- for (const stale of [...byIdentity.values()].sort((left, right) => compareCodeUnits(String(left.id), String(right.id)))) await stale.deleteDerived(capability, { expectedUpdatedAt: stale.updated_at ?? void 0 });
1660
- return result;
1661
- }
1662
- };
1663
- //#endregion
1664
- export { normalizePartyContacts as A, Customer as C, PartyContactPayloadError as D, PartyContactPartyNotFoundError as E, savePartyContacts as M, validatePartyContactRows as N, PartyContactValidationError as O, Vendor as S, PARTY_CONTACT_MAX_LENGTHS as T, SalesContract as _, SalesContractCollection as a, classifyContractPurchase as b, Cart as c, Lease as d, LicenseSale as f, PurchaseOrder as g, PurchaseContract as h, ContractCollection as i, readPartyContactRows as j, applyPartyContactIntent as k, Contract as l, ProductionOrder as m, DocumentTaxCollection_exports as n, PurchaseContractCollection as o, Order as p, DocumentTax as r, Agreement as s, DocumentTaxCollection as t, Estimate as u, SupplierQuote as v, DEFAULT_PARTY_CONTACT_FIELD_NAMES as w, isContractSnapshotReportEligible as x, WholesaleOrder as y };
1665
-
1666
- //# sourceMappingURL=DocumentTaxCollection-DDzlywMW.js.map