@final-commerce/common 1.1.4-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,2702 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+
19
+ // index.ts
20
+ var index_exports = {};
21
+ __export(index_exports, {
22
+ AttributeType: () => AttributeType,
23
+ CONDITION_OPERATORS: () => CONDITION_OPERATORS,
24
+ COUNTRY_CURRENCIES: () => COUNTRY_CURRENCIES,
25
+ CURRENCY_CONFIG: () => CURRENCY_CONFIG,
26
+ CompanyType: () => CompanyType,
27
+ CurrencyCode: () => CurrencyCode,
28
+ CustomTableAvailability: () => CustomTableAvailability,
29
+ CustomerPlatform: () => CustomerPlatform,
30
+ DEFAULT_CONFIG: () => DEFAULT_CONFIG,
31
+ DEFAULT_CROSS_AXIS_RULES: () => DEFAULT_CROSS_AXIS_RULES,
32
+ DEFAULT_DISPLAY_STATE_MAP: () => DEFAULT_DISPLAY_STATE_MAP,
33
+ DEFAULT_RESOLVED_CONFIG: () => DEFAULT_RESOLVED_CONFIG,
34
+ EUFixedRates: () => EUFixedRates,
35
+ EUROPE: () => EUROPE,
36
+ ExtensionCategory: () => ExtensionCategory,
37
+ FINANCIAL_INVARIANTS: () => FINANCIAL_INVARIANTS,
38
+ FULFILLMENT_STATES: () => FULFILLMENT_STATES,
39
+ FeesCustomBillingStatus: () => FeesCustomBillingStatus,
40
+ InventoryBaseActionEnum: () => InventoryBaseActionEnum,
41
+ InventorySpecificActionType: () => InventorySpecificActionType,
42
+ InvoiceStatus: () => InvoiceStatus,
43
+ LibraryItemType: () => LibraryItemType,
44
+ MenuProject: () => MenuProject,
45
+ NAFixedRates: () => NAFixedRates,
46
+ NORTH_AMERICA: () => NORTH_AMERICA,
47
+ NonRevenueItemType: () => NonRevenueItemType,
48
+ ORDER_STATE_ACTIONS: () => ORDER_STATE_ACTIONS,
49
+ ORDER_STATE_EVENTS: () => ORDER_STATE_EVENTS,
50
+ ORDER_STATE_TOPIC: () => ORDER_STATE_TOPIC,
51
+ OrderPlatform: () => OrderPlatform,
52
+ OtherFixedRates: () => OtherFixedRates,
53
+ OwnerType: () => OwnerType,
54
+ PATH_MODES: () => PATH_MODES,
55
+ PAYMENT_STATES: () => PAYMENT_STATES,
56
+ POS_CROSS_AXIS_RULES: () => POS_CROSS_AXIS_RULES,
57
+ POS_VALID_INITIAL_STATES: () => POS_VALID_INITIAL_STATES,
58
+ PaymentMethod: () => PaymentMethod,
59
+ Platform: () => Platform,
60
+ PreviewImageMode: () => PreviewImageMode,
61
+ PricingLevel: () => PricingLevel,
62
+ PricingPlanEnum: () => PricingPlanEnum,
63
+ PricingRegionEnum: () => PricingRegionEnum,
64
+ ProductStatus: () => ProductStatus,
65
+ ProductType: () => ProductType,
66
+ PublicationAvailability: () => PublicationAvailability,
67
+ PublicationStatus: () => PublicationStatus,
68
+ REGION_MAPPING: () => REGION_MAPPING,
69
+ REPORT_NEGATE_PATHS: () => REPORT_NEGATE_PATHS,
70
+ ReceiptSendChannel: () => ReceiptSendChannel,
71
+ ReceiptType: () => ReceiptType,
72
+ ResidualPaymentMethod: () => ResidualPaymentMethod,
73
+ ResidualStatus: () => ResidualStatus,
74
+ STATE_SCHEMA: () => STATE_SCHEMA,
75
+ STRIPE_SUPPORTED_COUNTRIES: () => STRIPE_SUPPORTED_COUNTRIES,
76
+ StationStatus: () => StationStatus,
77
+ StripeCurrencyCode: () => StripeCurrencyCode,
78
+ StripeStatus: () => StripeStatus,
79
+ TimePeriod: () => TimePeriod,
80
+ TopMetericsSort: () => TopMetericsSort,
81
+ UserTypes: () => UserTypes,
82
+ addAmounts: () => addAmounts,
83
+ amountToString: () => amountToString,
84
+ baseFulfillmentDefinitions: () => baseFulfillmentDefinitions,
85
+ basePaymentDefinitions: () => basePaymentDefinitions,
86
+ buildOrderContext: () => buildOrderContext,
87
+ buildPosPresetConfig: () => buildPosPresetConfig,
88
+ buildResolvedConfig: () => buildResolvedConfig,
89
+ calculatePercentage: () => calculatePercentage,
90
+ canTransition: () => canTransition,
91
+ conditionSummary: () => conditionSummary,
92
+ convertFixedFeeToLocalCurrency: () => convertFixedFeeToLocalCurrency,
93
+ createAmount: () => createAmount,
94
+ crossAxisRuleApplies: () => crossAxisRuleApplies,
95
+ deriveDisplayState: () => deriveDisplayState,
96
+ displayRuleMatchesPair: () => displayRuleMatchesPair,
97
+ divideAmount: () => divideAmount,
98
+ evaluateCondition: () => evaluateCondition,
99
+ evaluateConditionSet: () => evaluateConditionSet,
100
+ formatCurrency: () => formatCurrency,
101
+ formatMinorUnitsToString: () => formatMinorUnitsToString,
102
+ fromMinorUnits: () => fromMinorUnits,
103
+ generateMongoID: () => generateMongoID,
104
+ getAvailableTransitions: () => getAvailableTransitions,
105
+ getCountriesByRegion: () => getCountriesByRegion,
106
+ getCurrencyConfig: () => getCurrencyConfig,
107
+ getCurrentISODate: () => getCurrentISODate,
108
+ getFinancialInvariantViolations: () => getFinancialInvariantViolations,
109
+ getMinorUnitMultiplier: () => getMinorUnitMultiplier,
110
+ getMinorUnits: () => getMinorUnits,
111
+ getPricingRegionFromCountry: () => getPricingRegionFromCountry,
112
+ inferStatesFromLegacyStatus: () => inferStatesFromLegacyStatus,
113
+ isConditionOperator: () => isConditionOperator,
114
+ isFulfillmentState: () => isFulfillmentState,
115
+ isPaymentState: () => isPaymentState,
116
+ isSupportedCurrency: () => isSupportedCurrency,
117
+ mapToLegacyStatus: () => mapToLegacyStatus,
118
+ mergeFragment: () => mergeFragment,
119
+ multiplyAmount: () => multiplyAmount,
120
+ normalizeMongoIdString: () => normalizeMongoIdString,
121
+ parseAmountToMinorUnits: () => parseAmountToMinorUnits,
122
+ parseCurrencyCode: () => parseCurrencyCode,
123
+ parseStripeCurrencyCode: () => parseStripeCurrencyCode,
124
+ removeFragment: () => removeFragment,
125
+ resolveTemplate: () => resolveTemplate,
126
+ setOrderState: () => setOrderState,
127
+ signReportForDisplay: () => signReportForDisplay,
128
+ stringifyMinorUnits: () => stringifyMinorUnits,
129
+ subtractAmounts: () => subtractAmounts,
130
+ toMinorUnits: () => toMinorUnits,
131
+ validateConfig: () => validateConfig,
132
+ validateFragmentCompatibility: () => validateFragmentCompatibility,
133
+ violatesFinancialInvariant: () => violatesFinancialInvariant
134
+ });
135
+ module.exports = __toCommonJS(index_exports);
136
+
137
+ // enums/currency.enum.ts
138
+ var CurrencyCode = /* @__PURE__ */ ((CurrencyCode2) => {
139
+ CurrencyCode2["USD"] = "USD";
140
+ CurrencyCode2["EUR"] = "EUR";
141
+ CurrencyCode2["GBP"] = "GBP";
142
+ CurrencyCode2["CAD"] = "CAD";
143
+ CurrencyCode2["AUD"] = "AUD";
144
+ CurrencyCode2["NZD"] = "NZD";
145
+ CurrencyCode2["CHF"] = "CHF";
146
+ CurrencyCode2["CNY"] = "CNY";
147
+ CurrencyCode2["INR"] = "INR";
148
+ CurrencyCode2["MXN"] = "MXN";
149
+ CurrencyCode2["BRL"] = "BRL";
150
+ CurrencyCode2["ZAR"] = "ZAR";
151
+ CurrencyCode2["SGD"] = "SGD";
152
+ CurrencyCode2["HKD"] = "HKD";
153
+ CurrencyCode2["SEK"] = "SEK";
154
+ CurrencyCode2["NOK"] = "NOK";
155
+ CurrencyCode2["DKK"] = "DKK";
156
+ CurrencyCode2["PLN"] = "PLN";
157
+ CurrencyCode2["THB"] = "THB";
158
+ CurrencyCode2["MYR"] = "MYR";
159
+ CurrencyCode2["PHP"] = "PHP";
160
+ CurrencyCode2["IDR"] = "IDR";
161
+ CurrencyCode2["AED"] = "AED";
162
+ CurrencyCode2["SAR"] = "SAR";
163
+ CurrencyCode2["ILS"] = "ILS";
164
+ CurrencyCode2["TRY"] = "TRY";
165
+ CurrencyCode2["RUB"] = "RUB";
166
+ CurrencyCode2["HTG"] = "HTG";
167
+ CurrencyCode2["BND"] = "BND";
168
+ CurrencyCode2["CRC"] = "CRC";
169
+ CurrencyCode2["BDT"] = "BDT";
170
+ CurrencyCode2["UAH"] = "UAH";
171
+ CurrencyCode2["NGN"] = "NGN";
172
+ CurrencyCode2["AFN"] = "AFN";
173
+ CurrencyCode2["ALL"] = "ALL";
174
+ CurrencyCode2["AMD"] = "AMD";
175
+ CurrencyCode2["ANG"] = "ANG";
176
+ CurrencyCode2["AOA"] = "AOA";
177
+ CurrencyCode2["ARS"] = "ARS";
178
+ CurrencyCode2["AWG"] = "AWG";
179
+ CurrencyCode2["AZN"] = "AZN";
180
+ CurrencyCode2["BAM"] = "BAM";
181
+ CurrencyCode2["BBD"] = "BBD";
182
+ CurrencyCode2["BGN"] = "BGN";
183
+ CurrencyCode2["BMD"] = "BMD";
184
+ CurrencyCode2["BOB"] = "BOB";
185
+ CurrencyCode2["BSD"] = "BSD";
186
+ CurrencyCode2["BTN"] = "BTN";
187
+ CurrencyCode2["BWP"] = "BWP";
188
+ CurrencyCode2["BYN"] = "BYN";
189
+ CurrencyCode2["BZD"] = "BZD";
190
+ CurrencyCode2["COP"] = "COP";
191
+ CurrencyCode2["CZK"] = "CZK";
192
+ CurrencyCode2["DOP"] = "DOP";
193
+ CurrencyCode2["DZD"] = "DZD";
194
+ CurrencyCode2["EGP"] = "EGP";
195
+ CurrencyCode2["ETB"] = "ETB";
196
+ CurrencyCode2["FJD"] = "FJD";
197
+ CurrencyCode2["GEL"] = "GEL";
198
+ CurrencyCode2["GHS"] = "GHS";
199
+ CurrencyCode2["GTQ"] = "GTQ";
200
+ CurrencyCode2["GYD"] = "GYD";
201
+ CurrencyCode2["HNL"] = "HNL";
202
+ CurrencyCode2["IRR"] = "IRR";
203
+ CurrencyCode2["JMD"] = "JMD";
204
+ CurrencyCode2["KES"] = "KES";
205
+ CurrencyCode2["KGS"] = "KGS";
206
+ CurrencyCode2["KHR"] = "KHR";
207
+ CurrencyCode2["KYD"] = "KYD";
208
+ CurrencyCode2["KZT"] = "KZT";
209
+ CurrencyCode2["LAK"] = "LAK";
210
+ CurrencyCode2["LBP"] = "LBP";
211
+ CurrencyCode2["LKR"] = "LKR";
212
+ CurrencyCode2["MAD"] = "MAD";
213
+ CurrencyCode2["MDL"] = "MDL";
214
+ CurrencyCode2["MKD"] = "MKD";
215
+ CurrencyCode2["MMK"] = "MMK";
216
+ CurrencyCode2["MNT"] = "MNT";
217
+ CurrencyCode2["MOP"] = "MOP";
218
+ CurrencyCode2["MUR"] = "MUR";
219
+ CurrencyCode2["MVR"] = "MVR";
220
+ CurrencyCode2["MZN"] = "MZN";
221
+ CurrencyCode2["NAD"] = "NAD";
222
+ CurrencyCode2["NIO"] = "NIO";
223
+ CurrencyCode2["NPR"] = "NPR";
224
+ CurrencyCode2["PAB"] = "PAB";
225
+ CurrencyCode2["PEN"] = "PEN";
226
+ CurrencyCode2["PGK"] = "PGK";
227
+ CurrencyCode2["PKR"] = "PKR";
228
+ CurrencyCode2["QAR"] = "QAR";
229
+ CurrencyCode2["RON"] = "RON";
230
+ CurrencyCode2["RSD"] = "RSD";
231
+ CurrencyCode2["SBD"] = "SBD";
232
+ CurrencyCode2["SRD"] = "SRD";
233
+ CurrencyCode2["SYP"] = "SYP";
234
+ CurrencyCode2["TJS"] = "TJS";
235
+ CurrencyCode2["TMT"] = "TMT";
236
+ CurrencyCode2["TOP"] = "TOP";
237
+ CurrencyCode2["TTD"] = "TTD";
238
+ CurrencyCode2["TZS"] = "TZS";
239
+ CurrencyCode2["UYU"] = "UYU";
240
+ CurrencyCode2["UZS"] = "UZS";
241
+ CurrencyCode2["VES"] = "VES";
242
+ CurrencyCode2["WST"] = "WST";
243
+ CurrencyCode2["XCD"] = "XCD";
244
+ CurrencyCode2["YER"] = "YER";
245
+ CurrencyCode2["ZMW"] = "ZMW";
246
+ CurrencyCode2["CDF"] = "CDF";
247
+ CurrencyCode2["CUP"] = "CUP";
248
+ CurrencyCode2["ERN"] = "ERN";
249
+ CurrencyCode2["FKP"] = "FKP";
250
+ CurrencyCode2["GIP"] = "GIP";
251
+ CurrencyCode2["GMD"] = "GMD";
252
+ CurrencyCode2["KPW"] = "KPW";
253
+ CurrencyCode2["LRD"] = "LRD";
254
+ CurrencyCode2["LSL"] = "LSL";
255
+ CurrencyCode2["MGA"] = "MGA";
256
+ CurrencyCode2["MWK"] = "MWK";
257
+ CurrencyCode2["SCR"] = "SCR";
258
+ CurrencyCode2["SDG"] = "SDG";
259
+ CurrencyCode2["SHP"] = "SHP";
260
+ CurrencyCode2["SLE"] = "SLE";
261
+ CurrencyCode2["SOS"] = "SOS";
262
+ CurrencyCode2["SSP"] = "SSP";
263
+ CurrencyCode2["STN"] = "STN";
264
+ CurrencyCode2["SZL"] = "SZL";
265
+ CurrencyCode2["VED"] = "VED";
266
+ CurrencyCode2["XCG"] = "XCG";
267
+ CurrencyCode2["JPY"] = "JPY";
268
+ CurrencyCode2["KRW"] = "KRW";
269
+ CurrencyCode2["VND"] = "VND";
270
+ CurrencyCode2["CLP"] = "CLP";
271
+ CurrencyCode2["ISK"] = "ISK";
272
+ CurrencyCode2["HUF"] = "HUF";
273
+ CurrencyCode2["TWD"] = "TWD";
274
+ CurrencyCode2["GNF"] = "GNF";
275
+ CurrencyCode2["BIF"] = "BIF";
276
+ CurrencyCode2["DJF"] = "DJF";
277
+ CurrencyCode2["KMF"] = "KMF";
278
+ CurrencyCode2["PYG"] = "PYG";
279
+ CurrencyCode2["RWF"] = "RWF";
280
+ CurrencyCode2["UGX"] = "UGX";
281
+ CurrencyCode2["VUV"] = "VUV";
282
+ CurrencyCode2["XAF"] = "XAF";
283
+ CurrencyCode2["XOF"] = "XOF";
284
+ CurrencyCode2["XPF"] = "XPF";
285
+ CurrencyCode2["KWD"] = "KWD";
286
+ CurrencyCode2["BHD"] = "BHD";
287
+ CurrencyCode2["OMR"] = "OMR";
288
+ CurrencyCode2["JOD"] = "JOD";
289
+ CurrencyCode2["TND"] = "TND";
290
+ CurrencyCode2["LYD"] = "LYD";
291
+ CurrencyCode2["IQD"] = "IQD";
292
+ return CurrencyCode2;
293
+ })(CurrencyCode || {});
294
+
295
+ // enums/core.enum.ts
296
+ var TimePeriod = /* @__PURE__ */ ((TimePeriod2) => {
297
+ TimePeriod2["TODAY"] = "today";
298
+ TimePeriod2["THIS_WEEK"] = "this week";
299
+ TimePeriod2["THIS_MONTH"] = "this month";
300
+ TimePeriod2["THIS_YEAR"] = "this year";
301
+ TimePeriod2["All_TIME"] = "all_time";
302
+ return TimePeriod2;
303
+ })(TimePeriod || {});
304
+ var TopMetericsSort = /* @__PURE__ */ ((TopMetericsSort2) => {
305
+ TopMetericsSort2["TOTAL_PAYMENT_VOLUME"] = "totalPaymentVolume";
306
+ TopMetericsSort2["TOTAL_TRANSACTION"] = "totalTransaction";
307
+ return TopMetericsSort2;
308
+ })(TopMetericsSort || {});
309
+ var CompanyType = /* @__PURE__ */ ((CompanyType2) => {
310
+ CompanyType2["COMPANY"] = "company";
311
+ CompanyType2["ROOT"] = "root";
312
+ CompanyType2["ORGANIZATION"] = "organization";
313
+ return CompanyType2;
314
+ })(CompanyType || {});
315
+ var CustomTableAvailability = /* @__PURE__ */ ((CustomTableAvailability2) => {
316
+ CustomTableAvailability2["PUBLIC"] = "public";
317
+ CustomTableAvailability2["ORGANIZATION"] = "organization";
318
+ return CustomTableAvailability2;
319
+ })(CustomTableAvailability || {});
320
+ var AttributeType = /* @__PURE__ */ ((AttributeType2) => {
321
+ AttributeType2["STRING"] = "string";
322
+ AttributeType2["NUMBER"] = "number";
323
+ AttributeType2["BOOLEAN"] = "boolean";
324
+ AttributeType2["DATE"] = "date";
325
+ AttributeType2["JSON_STRING"] = "json-string";
326
+ return AttributeType2;
327
+ })(AttributeType || {});
328
+ var Platform = /* @__PURE__ */ ((Platform2) => {
329
+ Platform2["WOO_COMMERCE"] = "woo-commerce";
330
+ Platform2["SHOPIFY"] = "shopify";
331
+ Platform2["OLIVER"] = "oliver";
332
+ Platform2["STANDALONE"] = "standalone";
333
+ return Platform2;
334
+ })(Platform || {});
335
+ var OrderPlatform = /* @__PURE__ */ ((OrderPlatform2) => {
336
+ OrderPlatform2["POS"] = "in-store";
337
+ OrderPlatform2["WOO_COMMERCE"] = "woo-commerce";
338
+ return OrderPlatform2;
339
+ })(OrderPlatform || {});
340
+ var CustomerPlatform = /* @__PURE__ */ ((CustomerPlatform2) => {
341
+ CustomerPlatform2["POS"] = "in-store";
342
+ CustomerPlatform2["WOO_COMMERCE"] = "woo-commerce";
343
+ return CustomerPlatform2;
344
+ })(CustomerPlatform || {});
345
+ var StationStatus = /* @__PURE__ */ ((StationStatus2) => {
346
+ StationStatus2["IN_USE"] = "IN_USE";
347
+ StationStatus2["AVAILABLE"] = "AVAILABLE";
348
+ return StationStatus2;
349
+ })(StationStatus || {});
350
+ var InventoryBaseActionEnum = /* @__PURE__ */ ((InventoryBaseActionEnum2) => {
351
+ InventoryBaseActionEnum2["ADD"] = "ADD";
352
+ InventoryBaseActionEnum2["REMOVE"] = "REMOVE";
353
+ InventoryBaseActionEnum2["RECOUNT"] = "RECOUNT";
354
+ InventoryBaseActionEnum2["SKIP"] = "SKIP";
355
+ return InventoryBaseActionEnum2;
356
+ })(InventoryBaseActionEnum || {});
357
+ var InventorySpecificActionType = /* @__PURE__ */ ((InventorySpecificActionType2) => {
358
+ InventorySpecificActionType2["STOCK_RECEIVED"] = "STOCK_RECEIVED";
359
+ InventorySpecificActionType2["INVENTORY_RECOUNT"] = "INVENTORY_RECOUNT";
360
+ InventorySpecificActionType2["DAMAGE"] = "DAMAGE";
361
+ InventorySpecificActionType2["THEFT"] = "THEFT";
362
+ InventorySpecificActionType2["LOSS"] = "LOSS";
363
+ InventorySpecificActionType2["RESTOCK_RETURN"] = "RESTOCK_RETURN";
364
+ InventorySpecificActionType2["REFUND_RESTOCK_RETURN"] = "REFUND_RESTOCK_RETURN";
365
+ InventorySpecificActionType2["REFUND_DAMAGE"] = "REFUND_DAMAGE";
366
+ InventorySpecificActionType2["SALE"] = "SALE";
367
+ InventorySpecificActionType2["TRANSFER"] = "TRANSFER";
368
+ InventorySpecificActionType2["BULK_RECOUNT"] = "BULK_RECOUNT";
369
+ InventorySpecificActionType2["APPLIED_FROM_WOO"] = "APPLIED_FROM_WOO";
370
+ return InventorySpecificActionType2;
371
+ })(InventorySpecificActionType || {});
372
+ var ExtensionCategory = /* @__PURE__ */ ((ExtensionCategory2) => {
373
+ ExtensionCategory2["SYNC"] = "sync";
374
+ ExtensionCategory2["PAYMENT"] = "payment";
375
+ ExtensionCategory2["HUB"] = "hub";
376
+ ExtensionCategory2["BUILDER"] = "builder";
377
+ return ExtensionCategory2;
378
+ })(ExtensionCategory || {});
379
+ var FeesCustomBillingStatus = /* @__PURE__ */ ((FeesCustomBillingStatus2) => {
380
+ FeesCustomBillingStatus2["UNPAID"] = "unpaid";
381
+ FeesCustomBillingStatus2["PAID"] = "paid";
382
+ FeesCustomBillingStatus2["OPEN"] = "open";
383
+ return FeesCustomBillingStatus2;
384
+ })(FeesCustomBillingStatus || {});
385
+ var PricingPlanEnum = /* @__PURE__ */ ((PricingPlanEnum2) => {
386
+ PricingPlanEnum2["DEFAULT"] = "default";
387
+ PricingPlanEnum2["MINIMUM"] = "minimum";
388
+ PricingPlanEnum2["ORGANIZATION"] = "organization";
389
+ PricingPlanEnum2["PLAN"] = "plan";
390
+ PricingPlanEnum2["COMPANY"] = "company";
391
+ return PricingPlanEnum2;
392
+ })(PricingPlanEnum || {});
393
+ var PricingLevel = /* @__PURE__ */ ((PricingLevel2) => {
394
+ PricingLevel2["ORG"] = "org";
395
+ PricingLevel2["PLAN"] = "plan";
396
+ PricingLevel2["DEFAULT"] = "default";
397
+ PricingLevel2["MINIMUM"] = "minimum";
398
+ return PricingLevel2;
399
+ })(PricingLevel || {});
400
+ var PricingRegionEnum = /* @__PURE__ */ ((PricingRegionEnum2) => {
401
+ PricingRegionEnum2["EUROPE"] = "europe";
402
+ PricingRegionEnum2["OTHER"] = "others";
403
+ PricingRegionEnum2["NORTH_AMERICA"] = "northAmerica";
404
+ return PricingRegionEnum2;
405
+ })(PricingRegionEnum || {});
406
+ var MenuProject = /* @__PURE__ */ ((MenuProject2) => {
407
+ MenuProject2["MANAGE"] = "Manage";
408
+ MenuProject2["SCALE"] = "Scale";
409
+ MenuProject2["BUILD"] = "Build";
410
+ MenuProject2["PAY"] = "Pay";
411
+ MenuProject2["RUN"] = "Run";
412
+ return MenuProject2;
413
+ })(MenuProject || {});
414
+ var UserTypes = /* @__PURE__ */ ((UserTypes2) => {
415
+ UserTypes2["COMPANY_OWNER"] = "owner";
416
+ UserTypes2["ORG_USER"] = "organization_user";
417
+ UserTypes2["ORG_OWNER"] = "organization_owner";
418
+ UserTypes2["FINAL_USER"] = "final_user";
419
+ UserTypes2["FINAL_OWNER"] = "final_owner";
420
+ UserTypes2["EMPLOYEE"] = "employee";
421
+ UserTypes2["SUPER_ADMIN"] = "super_admin";
422
+ UserTypes2["MANAGER"] = "manager";
423
+ UserTypes2["ADMIN"] = "admin";
424
+ UserTypes2["ASSISTANT_MANAGER"] = "assistant";
425
+ UserTypes2["CASHIER"] = "cashier";
426
+ UserTypes2["RESELLER"] = "reseller";
427
+ return UserTypes2;
428
+ })(UserTypes || {});
429
+ var OwnerType = /* @__PURE__ */ ((OwnerType2) => {
430
+ OwnerType2["API_KEY"] = "api-key";
431
+ OwnerType2["ORGANIZATION"] = "organization";
432
+ OwnerType2["COMPANY"] = "company";
433
+ return OwnerType2;
434
+ })(OwnerType || {});
435
+ var PublicationAvailability = /* @__PURE__ */ ((PublicationAvailability2) => {
436
+ PublicationAvailability2["GLOBAL"] = "global";
437
+ PublicationAvailability2["PRIVATE"] = "private";
438
+ return PublicationAvailability2;
439
+ })(PublicationAvailability || {});
440
+ var PublicationStatus = /* @__PURE__ */ ((PublicationStatus2) => {
441
+ PublicationStatus2["APPROVED"] = "approved";
442
+ PublicationStatus2["REJECTED"] = "rejected";
443
+ PublicationStatus2["PENDING"] = "pending";
444
+ PublicationStatus2["NOT_APPLICABLE"] = "not_applicable";
445
+ return PublicationStatus2;
446
+ })(PublicationStatus || {});
447
+ var ResidualStatus = /* @__PURE__ */ ((ResidualStatus2) => {
448
+ ResidualStatus2["PAID"] = "paid";
449
+ ResidualStatus2["DUE"] = "due";
450
+ ResidualStatus2["ACCRUING"] = "accruing";
451
+ return ResidualStatus2;
452
+ })(ResidualStatus || {});
453
+ var PreviewImageMode = /* @__PURE__ */ ((PreviewImageMode2) => {
454
+ PreviewImageMode2["STATIC"] = "static";
455
+ PreviewImageMode2["DYNAMIC"] = "dynamic";
456
+ return PreviewImageMode2;
457
+ })(PreviewImageMode || {});
458
+ var LibraryItemType = /* @__PURE__ */ ((LibraryItemType2) => {
459
+ LibraryItemType2["FLOW"] = "flow";
460
+ LibraryItemType2["PAGE"] = "page";
461
+ LibraryItemType2["COMPOSITION"] = "composition";
462
+ LibraryItemType2["LAYOUT"] = "layout";
463
+ return LibraryItemType2;
464
+ })(LibraryItemType || {});
465
+ var ResidualPaymentMethod = /* @__PURE__ */ ((ResidualPaymentMethod2) => {
466
+ ResidualPaymentMethod2["CHEQUE"] = "cheque";
467
+ return ResidualPaymentMethod2;
468
+ })(ResidualPaymentMethod || {});
469
+ var PaymentMethod = /* @__PURE__ */ ((PaymentMethod2) => {
470
+ PaymentMethod2["CUSTOM"] = "Custom";
471
+ PaymentMethod2["CASH"] = "Cash";
472
+ PaymentMethod2["TERMINAL"] = "Terminal";
473
+ PaymentMethod2["CLOUD"] = "Cloud";
474
+ PaymentMethod2["BLUETOOTH"] = "Bluetooth";
475
+ return PaymentMethod2;
476
+ })(PaymentMethod || {});
477
+ var NonRevenueItemType = /* @__PURE__ */ ((NonRevenueItemType2) => {
478
+ NonRevenueItemType2["GIFT_CARD"] = "gift-card";
479
+ return NonRevenueItemType2;
480
+ })(NonRevenueItemType || {});
481
+ var ReceiptSendChannel = /* @__PURE__ */ ((ReceiptSendChannel2) => {
482
+ ReceiptSendChannel2["EMAIL"] = "email";
483
+ ReceiptSendChannel2["TEXT"] = "text";
484
+ return ReceiptSendChannel2;
485
+ })(ReceiptSendChannel || {});
486
+ var ReceiptType = /* @__PURE__ */ ((ReceiptType2) => {
487
+ ReceiptType2["ORDER"] = "order";
488
+ ReceiptType2["REFUND"] = "refund";
489
+ return ReceiptType2;
490
+ })(ReceiptType || {});
491
+ var StripeStatus = /* @__PURE__ */ ((StripeStatus2) => {
492
+ StripeStatus2["ACTIVE"] = "active";
493
+ StripeStatus2["INACTIVE"] = "inactive";
494
+ StripeStatus2["PAYMENT_METHOD_REQUIRED"] = "payment_method_required";
495
+ StripeStatus2["PAYMENT_METHOD_ADDED"] = "payment_method_added";
496
+ return StripeStatus2;
497
+ })(StripeStatus || {});
498
+ var InvoiceStatus = /* @__PURE__ */ ((InvoiceStatus2) => {
499
+ InvoiceStatus2["PAID"] = "paid";
500
+ InvoiceStatus2["PENDING"] = "pending";
501
+ InvoiceStatus2["EXPIRED"] = "expired";
502
+ return InvoiceStatus2;
503
+ })(InvoiceStatus || {});
504
+
505
+ // enums/stripe-currencies.enum.ts
506
+ var StripeCurrencyCode = /* @__PURE__ */ ((StripeCurrencyCode2) => {
507
+ StripeCurrencyCode2["USD"] = "USD";
508
+ StripeCurrencyCode2["EUR"] = "EUR";
509
+ StripeCurrencyCode2["GBP"] = "GBP";
510
+ StripeCurrencyCode2["CAD"] = "CAD";
511
+ StripeCurrencyCode2["AUD"] = "AUD";
512
+ StripeCurrencyCode2["NZD"] = "NZD";
513
+ StripeCurrencyCode2["CHF"] = "CHF";
514
+ StripeCurrencyCode2["CNY"] = "CNY";
515
+ StripeCurrencyCode2["INR"] = "INR";
516
+ StripeCurrencyCode2["MXN"] = "MXN";
517
+ StripeCurrencyCode2["BRL"] = "BRL";
518
+ StripeCurrencyCode2["ZAR"] = "ZAR";
519
+ StripeCurrencyCode2["SGD"] = "SGD";
520
+ StripeCurrencyCode2["HKD"] = "HKD";
521
+ StripeCurrencyCode2["SEK"] = "SEK";
522
+ StripeCurrencyCode2["NOK"] = "NOK";
523
+ StripeCurrencyCode2["DKK"] = "DKK";
524
+ StripeCurrencyCode2["PLN"] = "PLN";
525
+ StripeCurrencyCode2["THB"] = "THB";
526
+ StripeCurrencyCode2["MYR"] = "MYR";
527
+ StripeCurrencyCode2["PHP"] = "PHP";
528
+ StripeCurrencyCode2["IDR"] = "IDR";
529
+ StripeCurrencyCode2["AED"] = "AED";
530
+ StripeCurrencyCode2["SAR"] = "SAR";
531
+ StripeCurrencyCode2["ILS"] = "ILS";
532
+ StripeCurrencyCode2["TRY"] = "TRY";
533
+ StripeCurrencyCode2["RUB"] = "RUB";
534
+ StripeCurrencyCode2["JPY"] = "JPY";
535
+ StripeCurrencyCode2["KRW"] = "KRW";
536
+ StripeCurrencyCode2["VND"] = "VND";
537
+ StripeCurrencyCode2["CLP"] = "CLP";
538
+ StripeCurrencyCode2["ISK"] = "ISK";
539
+ StripeCurrencyCode2["HUF"] = "HUF";
540
+ StripeCurrencyCode2["TWD"] = "TWD";
541
+ StripeCurrencyCode2["KWD"] = "KWD";
542
+ StripeCurrencyCode2["BHD"] = "BHD";
543
+ StripeCurrencyCode2["OMR"] = "OMR";
544
+ StripeCurrencyCode2["JOD"] = "JOD";
545
+ StripeCurrencyCode2["TND"] = "TND";
546
+ StripeCurrencyCode2["LYD"] = "LYD";
547
+ StripeCurrencyCode2["IQD"] = "IQD";
548
+ return StripeCurrencyCode2;
549
+ })(StripeCurrencyCode || {});
550
+
551
+ // enums/product.enum.ts
552
+ var ProductType = /* @__PURE__ */ ((ProductType2) => {
553
+ ProductType2["SIMPLE"] = "simple";
554
+ ProductType2["VARIABLE"] = "variable";
555
+ return ProductType2;
556
+ })(ProductType || {});
557
+ var ProductStatus = /* @__PURE__ */ ((ProductStatus2) => {
558
+ ProductStatus2["ACTIVE"] = "active";
559
+ ProductStatus2["INACTIVE"] = "inactive";
560
+ ProductStatus2["DRAFT"] = "draft";
561
+ return ProductStatus2;
562
+ })(ProductStatus || {});
563
+
564
+ // utils/currency.util.ts
565
+ var CURRENCY_CONFIG = {
566
+ // Major currencies with 2 decimal places
567
+ ["USD" /* USD */]: { minorUnits: 2, symbol: "$", symbolPosition: "prefix" },
568
+ ["EUR" /* EUR */]: { minorUnits: 2, symbol: "\u20AC", symbolPosition: "prefix" },
569
+ ["GBP" /* GBP */]: { minorUnits: 2, symbol: "\xA3", symbolPosition: "prefix" },
570
+ ["CAD" /* CAD */]: { minorUnits: 2, symbol: "CA$", symbolPosition: "prefix" },
571
+ ["AUD" /* AUD */]: { minorUnits: 2, symbol: "A$", symbolPosition: "prefix" },
572
+ ["NZD" /* NZD */]: { minorUnits: 2, symbol: "NZ$", symbolPosition: "prefix" },
573
+ ["CHF" /* CHF */]: { minorUnits: 2, symbol: "CHF", symbolPosition: "prefix" },
574
+ ["CNY" /* CNY */]: { minorUnits: 2, symbol: "\xA5", symbolPosition: "prefix" },
575
+ ["INR" /* INR */]: { minorUnits: 2, symbol: "\u20B9", symbolPosition: "prefix" },
576
+ ["MXN" /* MXN */]: { minorUnits: 2, symbol: "MX$", symbolPosition: "prefix" },
577
+ ["BRL" /* BRL */]: { minorUnits: 2, symbol: "R$", symbolPosition: "prefix" },
578
+ ["ZAR" /* ZAR */]: { minorUnits: 2, symbol: "R", symbolPosition: "prefix" },
579
+ ["SGD" /* SGD */]: { minorUnits: 2, symbol: "S$", symbolPosition: "prefix" },
580
+ ["HKD" /* HKD */]: { minorUnits: 2, symbol: "HK$", symbolPosition: "prefix" },
581
+ ["SEK" /* SEK */]: { minorUnits: 2, symbol: "kr", symbolPosition: "suffix" },
582
+ ["NOK" /* NOK */]: { minorUnits: 2, symbol: "kr", symbolPosition: "suffix" },
583
+ ["DKK" /* DKK */]: { minorUnits: 2, symbol: "kr", symbolPosition: "suffix" },
584
+ ["PLN" /* PLN */]: { minorUnits: 2, symbol: "z\u0142", symbolPosition: "suffix" },
585
+ ["THB" /* THB */]: { minorUnits: 2, symbol: "\u0E3F", symbolPosition: "prefix" },
586
+ ["MYR" /* MYR */]: { minorUnits: 2, symbol: "RM", symbolPosition: "prefix" },
587
+ ["PHP" /* PHP */]: { minorUnits: 2, symbol: "\u20B1", symbolPosition: "prefix" },
588
+ ["IDR" /* IDR */]: { minorUnits: 2, symbol: "Rp", symbolPosition: "prefix" },
589
+ ["AED" /* AED */]: { minorUnits: 2, symbol: "\u062F.\u0625", symbolPosition: "prefix" },
590
+ ["SAR" /* SAR */]: { minorUnits: 2, symbol: "\uFDFC", symbolPosition: "prefix" },
591
+ ["ILS" /* ILS */]: { minorUnits: 2, symbol: "\u20AA", symbolPosition: "prefix" },
592
+ ["TRY" /* TRY */]: { minorUnits: 2, symbol: "\u20BA", symbolPosition: "prefix" },
593
+ ["RUB" /* RUB */]: { minorUnits: 2, symbol: "\u20BD", symbolPosition: "suffix" },
594
+ ["HTG" /* HTG */]: { minorUnits: 2, symbol: "HTG", symbolPosition: "prefix" },
595
+ // New Currencies with 2 decimal places
596
+ ["BND" /* BND */]: { minorUnits: 2, symbol: "BND", symbolPosition: "prefix" },
597
+ ["CRC" /* CRC */]: { minorUnits: 2, symbol: "CRC", symbolPosition: "prefix" },
598
+ ["BDT" /* BDT */]: { minorUnits: 2, symbol: "BDT", symbolPosition: "prefix" },
599
+ ["UAH" /* UAH */]: { minorUnits: 2, symbol: "UAH", symbolPosition: "prefix" },
600
+ ["NGN" /* NGN */]: { minorUnits: 2, symbol: "\u20A6", symbolPosition: "prefix" },
601
+ ["AFN" /* AFN */]: { minorUnits: 2, symbol: "\u060B", symbolPosition: "prefix" },
602
+ ["ALL" /* ALL */]: { minorUnits: 2, symbol: "L", symbolPosition: "suffix" },
603
+ ["AMD" /* AMD */]: { minorUnits: 2, symbol: "\u058F", symbolPosition: "suffix" },
604
+ ["ANG" /* ANG */]: { minorUnits: 2, symbol: "\u0192", symbolPosition: "prefix" },
605
+ ["AOA" /* AOA */]: { minorUnits: 2, symbol: "Kz", symbolPosition: "prefix" },
606
+ ["ARS" /* ARS */]: { minorUnits: 2, symbol: "AR$", symbolPosition: "prefix" },
607
+ ["AWG" /* AWG */]: { minorUnits: 2, symbol: "Afl.", symbolPosition: "prefix" },
608
+ ["AZN" /* AZN */]: { minorUnits: 2, symbol: "\u20BC", symbolPosition: "prefix" },
609
+ ["BAM" /* BAM */]: { minorUnits: 2, symbol: "KM", symbolPosition: "suffix" },
610
+ ["BBD" /* BBD */]: { minorUnits: 2, symbol: "Bds$", symbolPosition: "prefix" },
611
+ ["BGN" /* BGN */]: { minorUnits: 2, symbol: "\u043B\u0432", symbolPosition: "suffix" },
612
+ ["BMD" /* BMD */]: { minorUnits: 2, symbol: "BD$", symbolPosition: "prefix" },
613
+ ["BOB" /* BOB */]: { minorUnits: 2, symbol: "Bs.", symbolPosition: "prefix" },
614
+ ["BSD" /* BSD */]: { minorUnits: 2, symbol: "B$", symbolPosition: "prefix" },
615
+ ["BTN" /* BTN */]: { minorUnits: 2, symbol: "Nu.", symbolPosition: "prefix" },
616
+ ["BWP" /* BWP */]: { minorUnits: 2, symbol: "P", symbolPosition: "prefix" },
617
+ ["BYN" /* BYN */]: { minorUnits: 2, symbol: "Br", symbolPosition: "suffix" },
618
+ ["BZD" /* BZD */]: { minorUnits: 2, symbol: "BZ$", symbolPosition: "prefix" },
619
+ ["COP" /* COP */]: { minorUnits: 2, symbol: "COL$", symbolPosition: "prefix" },
620
+ ["CZK" /* CZK */]: { minorUnits: 2, symbol: "K\u010D", symbolPosition: "suffix" },
621
+ ["DOP" /* DOP */]: { minorUnits: 2, symbol: "RD$", symbolPosition: "prefix" },
622
+ ["DZD" /* DZD */]: { minorUnits: 2, symbol: "DA", symbolPosition: "prefix" },
623
+ ["EGP" /* EGP */]: { minorUnits: 2, symbol: "E\xA3", symbolPosition: "prefix" },
624
+ ["ETB" /* ETB */]: { minorUnits: 2, symbol: "Br", symbolPosition: "prefix" },
625
+ ["FJD" /* FJD */]: { minorUnits: 2, symbol: "FJ$", symbolPosition: "prefix" },
626
+ ["GEL" /* GEL */]: { minorUnits: 2, symbol: "\u20BE", symbolPosition: "prefix" },
627
+ ["GHS" /* GHS */]: { minorUnits: 2, symbol: "\u20B5", symbolPosition: "prefix" },
628
+ ["GTQ" /* GTQ */]: { minorUnits: 2, symbol: "Q", symbolPosition: "prefix" },
629
+ ["GYD" /* GYD */]: { minorUnits: 2, symbol: "G$", symbolPosition: "prefix" },
630
+ ["HNL" /* HNL */]: { minorUnits: 2, symbol: "L", symbolPosition: "prefix" },
631
+ ["IRR" /* IRR */]: { minorUnits: 2, symbol: "\uFDFC", symbolPosition: "prefix" },
632
+ ["JMD" /* JMD */]: { minorUnits: 2, symbol: "J$", symbolPosition: "prefix" },
633
+ ["KES" /* KES */]: { minorUnits: 2, symbol: "KSh", symbolPosition: "prefix" },
634
+ ["KGS" /* KGS */]: { minorUnits: 2, symbol: "\u0441", symbolPosition: "suffix" },
635
+ ["KHR" /* KHR */]: { minorUnits: 2, symbol: "\u17DB", symbolPosition: "prefix" },
636
+ ["KYD" /* KYD */]: { minorUnits: 2, symbol: "CI$", symbolPosition: "prefix" },
637
+ ["KZT" /* KZT */]: { minorUnits: 2, symbol: "\u20B8", symbolPosition: "prefix" },
638
+ ["LAK" /* LAK */]: { minorUnits: 2, symbol: "\u20AD", symbolPosition: "prefix" },
639
+ ["LBP" /* LBP */]: { minorUnits: 2, symbol: "L\xA3", symbolPosition: "prefix" },
640
+ ["LKR" /* LKR */]: { minorUnits: 2, symbol: "Rs", symbolPosition: "prefix" },
641
+ ["MAD" /* MAD */]: { minorUnits: 2, symbol: "DH", symbolPosition: "prefix" },
642
+ ["MDL" /* MDL */]: { minorUnits: 2, symbol: "L", symbolPosition: "suffix" },
643
+ ["MKD" /* MKD */]: { minorUnits: 2, symbol: "\u0434\u0435\u043D", symbolPosition: "suffix" },
644
+ ["MMK" /* MMK */]: { minorUnits: 2, symbol: "K", symbolPosition: "prefix" },
645
+ ["MNT" /* MNT */]: { minorUnits: 2, symbol: "\u20AE", symbolPosition: "prefix" },
646
+ ["MOP" /* MOP */]: { minorUnits: 2, symbol: "MOP$", symbolPosition: "prefix" },
647
+ ["MUR" /* MUR */]: { minorUnits: 2, symbol: "Rs", symbolPosition: "prefix" },
648
+ ["MVR" /* MVR */]: { minorUnits: 2, symbol: "Rf", symbolPosition: "prefix" },
649
+ ["MZN" /* MZN */]: { minorUnits: 2, symbol: "MT", symbolPosition: "prefix" },
650
+ ["NAD" /* NAD */]: { minorUnits: 2, symbol: "N$", symbolPosition: "prefix" },
651
+ ["NIO" /* NIO */]: { minorUnits: 2, symbol: "C$", symbolPosition: "prefix" },
652
+ ["NPR" /* NPR */]: { minorUnits: 2, symbol: "Rs", symbolPosition: "prefix" },
653
+ ["PAB" /* PAB */]: { minorUnits: 2, symbol: "B/.", symbolPosition: "prefix" },
654
+ ["PEN" /* PEN */]: { minorUnits: 2, symbol: "S/", symbolPosition: "prefix" },
655
+ ["PGK" /* PGK */]: { minorUnits: 2, symbol: "K", symbolPosition: "prefix" },
656
+ ["PKR" /* PKR */]: { minorUnits: 2, symbol: "\u20A8", symbolPosition: "prefix" },
657
+ ["QAR" /* QAR */]: { minorUnits: 2, symbol: "QR", symbolPosition: "prefix" },
658
+ ["RON" /* RON */]: { minorUnits: 2, symbol: "lei", symbolPosition: "suffix" },
659
+ ["RSD" /* RSD */]: { minorUnits: 2, symbol: "\u0434\u0438\u043D.", symbolPosition: "suffix" },
660
+ ["SBD" /* SBD */]: { minorUnits: 2, symbol: "SI$", symbolPosition: "prefix" },
661
+ ["SRD" /* SRD */]: { minorUnits: 2, symbol: "Sr$", symbolPosition: "prefix" },
662
+ ["SYP" /* SYP */]: { minorUnits: 2, symbol: "\xA3S", symbolPosition: "prefix" },
663
+ ["TJS" /* TJS */]: { minorUnits: 2, symbol: "SM", symbolPosition: "prefix" },
664
+ ["TMT" /* TMT */]: { minorUnits: 2, symbol: "m.", symbolPosition: "prefix" },
665
+ ["TOP" /* TOP */]: { minorUnits: 2, symbol: "T$", symbolPosition: "prefix" },
666
+ ["TTD" /* TTD */]: { minorUnits: 2, symbol: "TT$", symbolPosition: "prefix" },
667
+ ["TZS" /* TZS */]: { minorUnits: 2, symbol: "TSh", symbolPosition: "prefix" },
668
+ ["UYU" /* UYU */]: { minorUnits: 2, symbol: "$U", symbolPosition: "prefix" },
669
+ ["UZS" /* UZS */]: { minorUnits: 2, symbol: "\u0441\u045E\u043C", symbolPosition: "suffix" },
670
+ ["VES" /* VES */]: { minorUnits: 2, symbol: "Bs.", symbolPosition: "prefix" },
671
+ ["WST" /* WST */]: { minorUnits: 2, symbol: "WS$", symbolPosition: "prefix" },
672
+ ["XCD" /* XCD */]: { minorUnits: 2, symbol: "EC$", symbolPosition: "prefix" },
673
+ ["YER" /* YER */]: { minorUnits: 2, symbol: "\uFDFC", symbolPosition: "prefix" },
674
+ ["ZMW" /* ZMW */]: { minorUnits: 2, symbol: "ZK", symbolPosition: "prefix" },
675
+ ["CDF" /* CDF */]: { minorUnits: 2, symbol: "FC", symbolPosition: "prefix" },
676
+ ["CUP" /* CUP */]: { minorUnits: 2, symbol: "$MN", symbolPosition: "prefix" },
677
+ ["ERN" /* ERN */]: { minorUnits: 2, symbol: "Nfk", symbolPosition: "prefix" },
678
+ ["FKP" /* FKP */]: { minorUnits: 2, symbol: "FK\xA3", symbolPosition: "prefix" },
679
+ ["GIP" /* GIP */]: { minorUnits: 2, symbol: "GI\xA3", symbolPosition: "prefix" },
680
+ ["GMD" /* GMD */]: { minorUnits: 2, symbol: "D", symbolPosition: "prefix" },
681
+ ["KPW" /* KPW */]: { minorUnits: 2, symbol: "KPW", symbolPosition: "prefix" },
682
+ ["LRD" /* LRD */]: { minorUnits: 2, symbol: "L$", symbolPosition: "prefix" },
683
+ ["LSL" /* LSL */]: { minorUnits: 2, symbol: "M", symbolPosition: "prefix" },
684
+ ["MGA" /* MGA */]: { minorUnits: 2, symbol: "Ar", symbolPosition: "prefix" },
685
+ ["MWK" /* MWK */]: { minorUnits: 2, symbol: "MK", symbolPosition: "prefix" },
686
+ ["SCR" /* SCR */]: { minorUnits: 2, symbol: "SR", symbolPosition: "prefix" },
687
+ ["SDG" /* SDG */]: { minorUnits: 2, symbol: "SDG", symbolPosition: "prefix" },
688
+ ["SHP" /* SHP */]: { minorUnits: 2, symbol: "SH\xA3", symbolPosition: "prefix" },
689
+ ["SLE" /* SLE */]: { minorUnits: 2, symbol: "Le", symbolPosition: "prefix" },
690
+ ["SOS" /* SOS */]: { minorUnits: 2, symbol: "SSh", symbolPosition: "prefix" },
691
+ ["SSP" /* SSP */]: { minorUnits: 2, symbol: "SSP", symbolPosition: "prefix" },
692
+ ["STN" /* STN */]: { minorUnits: 2, symbol: "Db", symbolPosition: "prefix" },
693
+ ["SZL" /* SZL */]: { minorUnits: 2, symbol: "E", symbolPosition: "prefix" },
694
+ ["VED" /* VED */]: { minorUnits: 2, symbol: "Bs.D", symbolPosition: "prefix" },
695
+ ["XCG" /* XCG */]: { minorUnits: 2, symbol: "Cg", symbolPosition: "prefix" },
696
+ // Zero decimal currencies
697
+ ["JPY" /* JPY */]: { minorUnits: 0, symbol: "\xA5", symbolPosition: "prefix" },
698
+ ["KRW" /* KRW */]: { minorUnits: 0, symbol: "\u20A9", symbolPosition: "prefix" },
699
+ ["VND" /* VND */]: { minorUnits: 0, symbol: "\u20AB", symbolPosition: "suffix" },
700
+ ["CLP" /* CLP */]: { minorUnits: 0, symbol: "CLP$", symbolPosition: "prefix" },
701
+ ["ISK" /* ISK */]: { minorUnits: 0, symbol: "kr", symbolPosition: "suffix" },
702
+ ["HUF" /* HUF */]: { minorUnits: 0, symbol: "Ft", symbolPosition: "suffix" },
703
+ ["TWD" /* TWD */]: { minorUnits: 0, symbol: "NT$", symbolPosition: "prefix" },
704
+ // New Currencies with 0 decimal places
705
+ ["GNF" /* GNF */]: { minorUnits: 0, symbol: "GNF", symbolPosition: "prefix" },
706
+ ["BIF" /* BIF */]: { minorUnits: 0, symbol: "FBu", symbolPosition: "prefix" },
707
+ ["DJF" /* DJF */]: { minorUnits: 0, symbol: "Fdj", symbolPosition: "prefix" },
708
+ ["KMF" /* KMF */]: { minorUnits: 0, symbol: "CF", symbolPosition: "prefix" },
709
+ ["PYG" /* PYG */]: { minorUnits: 0, symbol: "\u20B2", symbolPosition: "prefix" },
710
+ ["RWF" /* RWF */]: { minorUnits: 0, symbol: "FRw", symbolPosition: "prefix" },
711
+ ["UGX" /* UGX */]: { minorUnits: 0, symbol: "USh", symbolPosition: "prefix" },
712
+ ["VUV" /* VUV */]: { minorUnits: 0, symbol: "VT", symbolPosition: "prefix" },
713
+ ["XAF" /* XAF */]: { minorUnits: 0, symbol: "FCFA", symbolPosition: "suffix" },
714
+ ["XOF" /* XOF */]: { minorUnits: 0, symbol: "CFA", symbolPosition: "suffix" },
715
+ ["XPF" /* XPF */]: { minorUnits: 0, symbol: "\u20A3", symbolPosition: "suffix" },
716
+ // Three decimal currencies
717
+ ["KWD" /* KWD */]: { minorUnits: 3, symbol: "KD", symbolPosition: "prefix" },
718
+ ["BHD" /* BHD */]: { minorUnits: 3, symbol: "BD", symbolPosition: "prefix" },
719
+ ["OMR" /* OMR */]: { minorUnits: 3, symbol: "OMR", symbolPosition: "prefix" },
720
+ ["JOD" /* JOD */]: { minorUnits: 3, symbol: "JD", symbolPosition: "prefix" },
721
+ ["TND" /* TND */]: { minorUnits: 3, symbol: "DT", symbolPosition: "prefix" },
722
+ ["LYD" /* LYD */]: { minorUnits: 3, symbol: "LD", symbolPosition: "prefix" },
723
+ ["IQD" /* IQD */]: { minorUnits: 3, symbol: "IQD", symbolPosition: "prefix" }
724
+ };
725
+ var DEFAULT_CURRENCY_CONFIG = {
726
+ minorUnits: 2,
727
+ symbol: "",
728
+ symbolPosition: "prefix"
729
+ };
730
+ function getCurrencyConfig(currency) {
731
+ const upperCurrency = currency.toUpperCase();
732
+ return CURRENCY_CONFIG[upperCurrency] || DEFAULT_CURRENCY_CONFIG;
733
+ }
734
+ function getMinorUnitMultiplier(currency) {
735
+ const config = getCurrencyConfig(currency);
736
+ return Math.pow(10, config.minorUnits);
737
+ }
738
+ function toMinorUnits(amount, currency) {
739
+ const multiplier = getMinorUnitMultiplier(currency);
740
+ return Math.round(amount * multiplier);
741
+ }
742
+ function fromMinorUnits(minorAmount, currency) {
743
+ const multiplier = getMinorUnitMultiplier(currency);
744
+ return minorAmount / multiplier;
745
+ }
746
+ function formatCurrency(minorAmount, currency, options = {}) {
747
+ const { includeSymbol = true, useGrouping = true } = options;
748
+ const config = getCurrencyConfig(currency);
749
+ const majorAmount = fromMinorUnits(minorAmount, currency);
750
+ const formattedNumber = majorAmount.toLocaleString("en-US", {
751
+ minimumFractionDigits: config.minorUnits,
752
+ maximumFractionDigits: config.minorUnits,
753
+ useGrouping
754
+ });
755
+ if (!includeSymbol || !config.symbol) {
756
+ return formattedNumber;
757
+ }
758
+ if (config.symbolPosition === "suffix") {
759
+ return `${formattedNumber}${config.symbol}`;
760
+ }
761
+ return `${config.symbol}${formattedNumber}`;
762
+ }
763
+ function addAmounts(a, b) {
764
+ return Math.round(a + b);
765
+ }
766
+ function subtractAmounts(a, b) {
767
+ return Math.round(a - b);
768
+ }
769
+ function multiplyAmount(amount, multiplier) {
770
+ return Math.round(amount * multiplier);
771
+ }
772
+ function divideAmount(amount, divisor) {
773
+ if (divisor === 0) {
774
+ throw new Error("Cannot divide by zero");
775
+ }
776
+ return Math.round(amount / divisor);
777
+ }
778
+ function calculatePercentage(amount, percentage) {
779
+ return Math.round(amount * percentage / 100);
780
+ }
781
+ function parseAmountToMinorUnits(amountString, currency) {
782
+ const parsed = parseFloat(amountString);
783
+ if (isNaN(parsed)) {
784
+ return null;
785
+ }
786
+ return toMinorUnits(parsed, currency);
787
+ }
788
+ function isSupportedCurrency(currency) {
789
+ return currency.toUpperCase() in CURRENCY_CONFIG;
790
+ }
791
+ function parseCurrencyCode(value) {
792
+ if (!value || typeof value !== "string") {
793
+ throw new Error(`Currency value is missing or invalid`);
794
+ }
795
+ const validCodes = Object.values(CurrencyCode);
796
+ if (!validCodes.includes(value)) {
797
+ throw new Error(`"${value}" is not a supported CurrencyCode. Supported codes: ${validCodes.join(", ")}`);
798
+ }
799
+ return value;
800
+ }
801
+ function parseStripeCurrencyCode(value) {
802
+ if (!value || typeof value !== "string") {
803
+ throw new Error(`Currency value is missing or invalid`);
804
+ }
805
+ const validCodes = Object.values(StripeCurrencyCode);
806
+ if (!validCodes.includes(value)) {
807
+ throw new Error(`"${value}" is not a supported Stripe CurrencyCode. Supported codes: ${validCodes.join(", ")}`);
808
+ }
809
+ return value;
810
+ }
811
+ function stringifyMinorUnits(minorAmount, minorUnits) {
812
+ const multiplier = Math.pow(10, minorUnits);
813
+ return minorAmount / multiplier;
814
+ }
815
+ function formatMinorUnitsToString(minorAmount, minorUnits) {
816
+ const majorAmount = stringifyMinorUnits(minorAmount, minorUnits);
817
+ return majorAmount.toString();
818
+ }
819
+ function getMinorUnits(currency) {
820
+ return getCurrencyConfig(currency).minorUnits;
821
+ }
822
+ function createAmount(value, currency) {
823
+ if (value === null || value === void 0 || value === "") {
824
+ return void 0;
825
+ }
826
+ const numericValue = typeof value === "string" ? parseFloat(value) : value;
827
+ if (isNaN(numericValue)) {
828
+ return void 0;
829
+ }
830
+ const minorUnits = getMinorUnits(currency);
831
+ const multiplier = Math.pow(10, minorUnits);
832
+ return {
833
+ amount: Math.round(numericValue * multiplier),
834
+ currency,
835
+ minorUnits
836
+ };
837
+ }
838
+ function amountToString(amount) {
839
+ if (!amount) {
840
+ return "";
841
+ }
842
+ const divisor = Math.pow(10, amount.minorUnits);
843
+ const majorValue = amount.amount / divisor;
844
+ return majorValue.toFixed(amount.minorUnits);
845
+ }
846
+
847
+ // constants/pricing.constants.ts
848
+ var REGION_MAPPING = {
849
+ // North America
850
+ US: "northAmerica" /* NORTH_AMERICA */,
851
+ CA: "northAmerica" /* NORTH_AMERICA */,
852
+ MX: "northAmerica" /* NORTH_AMERICA */,
853
+ // Europe
854
+ AT: "europe" /* EUROPE */,
855
+ BE: "europe" /* EUROPE */,
856
+ BG: "europe" /* EUROPE */,
857
+ CH: "europe" /* EUROPE */,
858
+ CY: "europe" /* EUROPE */,
859
+ CZ: "europe" /* EUROPE */,
860
+ DE: "europe" /* EUROPE */,
861
+ DK: "europe" /* EUROPE */,
862
+ EE: "europe" /* EUROPE */,
863
+ ES: "europe" /* EUROPE */,
864
+ FI: "europe" /* EUROPE */,
865
+ FR: "europe" /* EUROPE */,
866
+ GB: "europe" /* EUROPE */,
867
+ // Stripe uses 'GB' (not 'UK')
868
+ GR: "europe" /* EUROPE */,
869
+ HR: "europe" /* EUROPE */,
870
+ HU: "europe" /* EUROPE */,
871
+ IE: "europe" /* EUROPE */,
872
+ IT: "europe" /* EUROPE */,
873
+ LI: "europe" /* EUROPE */,
874
+ LT: "europe" /* EUROPE */,
875
+ LU: "europe" /* EUROPE */,
876
+ LV: "europe" /* EUROPE */,
877
+ MT: "europe" /* EUROPE */,
878
+ NL: "europe" /* EUROPE */,
879
+ NO: "europe" /* EUROPE */,
880
+ PL: "europe" /* EUROPE */,
881
+ PT: "europe" /* EUROPE */,
882
+ RO: "europe" /* EUROPE */,
883
+ SE: "europe" /* EUROPE */,
884
+ SI: "europe" /* EUROPE */,
885
+ SK: "europe" /* EUROPE */,
886
+ GI: "europe" /* EUROPE */,
887
+ // Gibraltar (NEW)
888
+ // Others (Asia-Pacific, Middle East, South America, etc.)
889
+ AE: "others" /* OTHER */,
890
+ // United Arab Emirates
891
+ AU: "others" /* OTHER */,
892
+ // Australia
893
+ BR: "others" /* OTHER */,
894
+ // Brazil (NEW)
895
+ HK: "others" /* OTHER */,
896
+ // Hong Kong
897
+ IN: "others" /* OTHER */,
898
+ // India (NEW)
899
+ JP: "others" /* OTHER */,
900
+ // Japan
901
+ MY: "others" /* OTHER */,
902
+ // Malaysia
903
+ NZ: "others" /* OTHER */,
904
+ // New Zealand
905
+ SG: "others" /* OTHER */,
906
+ // Singapore
907
+ TH: "others" /* OTHER */
908
+ // Thailand
909
+ };
910
+ var STRIPE_SUPPORTED_COUNTRIES = /* @__PURE__ */ new Set([
911
+ // North America
912
+ "US",
913
+ "CA",
914
+ "MX",
915
+ // Europe
916
+ "AT",
917
+ "BE",
918
+ "BG",
919
+ "CH",
920
+ "CY",
921
+ "CZ",
922
+ "DE",
923
+ "DK",
924
+ "EE",
925
+ "ES",
926
+ "FI",
927
+ "FR",
928
+ "GB",
929
+ "GR",
930
+ "HR",
931
+ "HU",
932
+ "IE",
933
+ "IT",
934
+ "LI",
935
+ "LT",
936
+ "LU",
937
+ "LV",
938
+ "MT",
939
+ "NL",
940
+ "NO",
941
+ "PL",
942
+ "PT",
943
+ "RO",
944
+ "SE",
945
+ "SI",
946
+ "SK",
947
+ // Others
948
+ "AE",
949
+ // United Arab Emirates
950
+ "AU",
951
+ // Australia
952
+ "BR",
953
+ // Brazil (NEW)
954
+ "GI",
955
+ // Gibraltar (NEW)
956
+ "HK",
957
+ // Hong Kong
958
+ "IN",
959
+ // India (NEW)
960
+ "JP",
961
+ // Japan
962
+ "MY",
963
+ // Malaysia
964
+ "NZ",
965
+ // New Zealand
966
+ "SG",
967
+ // Singapore
968
+ "TH"
969
+ // Thailand
970
+ ]);
971
+ var NAFixedRates = {
972
+ USD: { rate: 30, country: "United States" },
973
+ CAD: { rate: 20, country: "Canada" },
974
+ MXN: { rate: 300, country: "Mexico" }
975
+ };
976
+ var EUFixedRates = {
977
+ EUR: { rate: 30, country: "European Union" },
978
+ GBP: { rate: 20, country: "Great Britain" },
979
+ CHF: { rate: 30, country: "Switzerland" },
980
+ DKK: { rate: 180, country: "Denmark" },
981
+ NOK: { rate: 200, country: "Norway" },
982
+ SEK: { rate: 180, country: "Sweden" },
983
+ PLN: { rate: 100, country: "Poland" }
984
+ };
985
+ var OtherFixedRates = {
986
+ AUD: { rate: 30, country: "Australia" },
987
+ NZD: { rate: 30, country: "New Zealand" },
988
+ SGD: { rate: 50, country: "Singapore" },
989
+ MYR: { rate: 100, country: "Malaysia" },
990
+ JPY: { rate: 30, country: "Japan" }
991
+ };
992
+ var COUNTRY_CURRENCIES = {
993
+ US: "USD",
994
+ CA: "CAD",
995
+ MX: "MXN",
996
+ AT: "EUR",
997
+ BE: "EUR",
998
+ BG: "BGN",
999
+ CH: "CHF",
1000
+ CY: "EUR",
1001
+ CZ: "CZK",
1002
+ DE: "EUR",
1003
+ DK: "DKK",
1004
+ EE: "EUR",
1005
+ ES: "EUR",
1006
+ FI: "EUR",
1007
+ FR: "EUR",
1008
+ GB: "GBP",
1009
+ GI: "GIP",
1010
+ GR: "EUR",
1011
+ HR: "EUR",
1012
+ HU: "HUF",
1013
+ IE: "EUR",
1014
+ IT: "EUR",
1015
+ LI: "CHF",
1016
+ LT: "EUR",
1017
+ LU: "EUR",
1018
+ LV: "EUR",
1019
+ MT: "EUR",
1020
+ NL: "EUR",
1021
+ NO: "NOK",
1022
+ PL: "PLN",
1023
+ PT: "EUR",
1024
+ RO: "RON",
1025
+ SE: "SEK",
1026
+ SI: "EUR",
1027
+ SK: "EUR",
1028
+ AE: "AED",
1029
+ AU: "AUD",
1030
+ BR: "BRL",
1031
+ HK: "HKD",
1032
+ IN: "INR",
1033
+ JP: "JPY",
1034
+ MY: "MYR",
1035
+ NZ: "NZD",
1036
+ SG: "SGD",
1037
+ TH: "THB"
1038
+ };
1039
+
1040
+ // utils/pricing.util.ts
1041
+ function getPricingRegionFromCountry(countryCode) {
1042
+ const code = (countryCode || "").toUpperCase();
1043
+ if (NORTH_AMERICA.has(code)) return "northAmerica" /* NORTH_AMERICA */;
1044
+ if (EUROPE.has(code)) return "europe" /* EUROPE */;
1045
+ return "others" /* OTHER */;
1046
+ }
1047
+ var NORTH_AMERICA = getCountriesByRegion("northAmerica" /* NORTH_AMERICA */);
1048
+ var EUROPE = getCountriesByRegion("europe" /* EUROPE */);
1049
+ function convertFixedFeeToLocalCurrency(currency, region) {
1050
+ const currencyCode = currency.toUpperCase();
1051
+ let fixedRate;
1052
+ switch (region) {
1053
+ case "northAmerica" /* NORTH_AMERICA */: {
1054
+ fixedRate = NAFixedRates[currencyCode];
1055
+ break;
1056
+ }
1057
+ case "europe" /* EUROPE */: {
1058
+ fixedRate = EUFixedRates[currencyCode];
1059
+ break;
1060
+ }
1061
+ case "others" /* OTHER */: {
1062
+ fixedRate = OtherFixedRates[currencyCode];
1063
+ break;
1064
+ }
1065
+ }
1066
+ return fixedRate?.rate ?? null;
1067
+ }
1068
+ function getCountriesByRegion(region) {
1069
+ const countries = /* @__PURE__ */ new Set();
1070
+ for (const [country, mappedRegion] of Object.entries(REGION_MAPPING)) {
1071
+ if (mappedRegion === region) {
1072
+ countries.add(country);
1073
+ }
1074
+ }
1075
+ return countries;
1076
+ }
1077
+
1078
+ // utils/report-sign.util.ts
1079
+ var REPORT_NEGATE_PATHS = /* @__PURE__ */ new Set([
1080
+ // Sales summary — reductions to revenue
1081
+ "salesSummary.discounts.netDiscounts",
1082
+ "salesSummary.refundsItems",
1083
+ // Settlement — money going out of the merchant
1084
+ "settlementBreakdown.cards.refunded",
1085
+ "settlementBreakdown.cards.processingFees",
1086
+ "settlementBreakdown.cash.refunded",
1087
+ "settlementBreakdown.custom[].refunded",
1088
+ "settlementBreakdown.custom[].processingFees",
1089
+ // Tax breakdown — refunds sub-table renders signed-negative
1090
+ "taxBreakdown.refunds.entries[].taxableSales",
1091
+ "taxBreakdown.refunds.entries[].tax",
1092
+ "taxBreakdown.refunds.total.taxableSales",
1093
+ "taxBreakdown.refunds.total.tax",
1094
+ // Refunds breakdown — reductions and naturally-signed entries
1095
+ "refundsBreakdown.discountsReversed",
1096
+ "refundsBreakdown.cashRoundingRefund",
1097
+ // Fees breakdown — refunded magnitudes are money flowing back out
1098
+ "feesBreakdown.productFee.refundedProductFees",
1099
+ "feesBreakdown.cartFee.refundedCartFees",
1100
+ // Discounts breakdown — refunded magnitudes reverse discount reductions
1101
+ "discountsBreakdown.productDiscounts.refundedProductDiscounts",
1102
+ "discountsBreakdown.cartDiscounts.refundedCartDiscounts",
1103
+ // Staff sales — refunds are money flowing back out
1104
+ "staffSales.staffSales[].refundSales",
1105
+ "staffSales.refundTotal",
1106
+ // Tips — refunds are money flowing back out
1107
+ "tipsBreakdown.tips[].refundAmount"
1108
+ ]);
1109
+ function signReportForDisplay(report) {
1110
+ return negateAtPaths(report, "", REPORT_NEGATE_PATHS);
1111
+ }
1112
+ function negateAtPaths(value, path, paths) {
1113
+ if (Array.isArray(value)) {
1114
+ const next = `${path}[]`;
1115
+ return value.map((item) => negateAtPaths(item, next, paths));
1116
+ }
1117
+ if (value !== null && typeof value === "object") {
1118
+ const out = {};
1119
+ for (const [key, child] of Object.entries(value)) {
1120
+ const next = path ? `${path}.${key}` : key;
1121
+ out[key] = negateAtPaths(child, next, paths);
1122
+ }
1123
+ return out;
1124
+ }
1125
+ if (typeof value === "number" && paths.has(path)) {
1126
+ return value === 0 ? 0 : -value;
1127
+ }
1128
+ return value;
1129
+ }
1130
+
1131
+ // utils/mongo.util.ts
1132
+ function padHex(value, length) {
1133
+ return value.toString(16).padStart(length, "0");
1134
+ }
1135
+ var PROCESS_RANDOM = Array.from(
1136
+ { length: 5 },
1137
+ () => padHex(Math.floor(Math.random() * 256), 2)
1138
+ ).join("");
1139
+ var objectIdCounter = Math.floor(Math.random() * 16777215);
1140
+ function generateMongoID() {
1141
+ const timestamp = padHex(Math.floor(Date.now() / 1e3), 8);
1142
+ objectIdCounter = (objectIdCounter + 1) % 16777216;
1143
+ return timestamp + PROCESS_RANDOM + padHex(objectIdCounter, 6);
1144
+ }
1145
+ function getCurrentISODate() {
1146
+ const now = new Date(Date.now());
1147
+ return now.toISOString();
1148
+ }
1149
+ function normalizeMongoIdString(value) {
1150
+ if (value == null || value === "") {
1151
+ return null;
1152
+ }
1153
+ if (typeof value === "string") {
1154
+ const t = value.trim();
1155
+ return t.length > 0 ? t : null;
1156
+ }
1157
+ if (typeof value === "object" && value !== null && "$oid" in value) {
1158
+ const oid = value.$oid;
1159
+ return typeof oid === "string" && oid.length > 0 ? oid : null;
1160
+ }
1161
+ return null;
1162
+ }
1163
+
1164
+ // order-state-machine/types.ts
1165
+ var PAYMENT_STATES = [
1166
+ "unpaid",
1167
+ "payment_pending",
1168
+ "partially_paid",
1169
+ "paid",
1170
+ "partially_refunded",
1171
+ "refunded",
1172
+ "voided"
1173
+ ];
1174
+ var FULFILLMENT_STATES = [
1175
+ "draft",
1176
+ "pending",
1177
+ "on_hold",
1178
+ "in_progress",
1179
+ "fulfilled",
1180
+ "partially_fulfilled",
1181
+ "returned",
1182
+ "partially_returned",
1183
+ "cancelled"
1184
+ ];
1185
+ function isPaymentState(value) {
1186
+ return PAYMENT_STATES.includes(value);
1187
+ }
1188
+ function isFulfillmentState(value) {
1189
+ return FULFILLMENT_STATES.includes(value);
1190
+ }
1191
+ var CONDITION_OPERATORS = [
1192
+ "eq",
1193
+ "neq",
1194
+ "gt",
1195
+ "gte",
1196
+ "lt",
1197
+ "lte",
1198
+ "in",
1199
+ "notIn",
1200
+ "isEmpty",
1201
+ "isNotEmpty"
1202
+ ];
1203
+ function isConditionOperator(value) {
1204
+ return CONDITION_OPERATORS.includes(value);
1205
+ }
1206
+ var PATH_MODES = [
1207
+ "strict",
1208
+ "permissive"
1209
+ ];
1210
+
1211
+ // order-state-machine/state-schema.ts
1212
+ var PAYMENT_DEFS = [
1213
+ { id: "unpaid", label: "Unpaid", terminal: false },
1214
+ { id: "payment_pending", label: "Payment Pending", terminal: false },
1215
+ { id: "partially_paid", label: "Partially Paid", terminal: false },
1216
+ { id: "paid", label: "Paid", terminal: false },
1217
+ { id: "partially_refunded", label: "Partially Refunded", terminal: false },
1218
+ { id: "refunded", label: "Refunded", terminal: true },
1219
+ { id: "voided", label: "Voided", terminal: true }
1220
+ ];
1221
+ var FULFILLMENT_DEFS = [
1222
+ { id: "draft", label: "Draft", terminal: false },
1223
+ { id: "pending", label: "Pending", terminal: false },
1224
+ { id: "on_hold", label: "On Hold", terminal: false },
1225
+ { id: "in_progress", label: "In Progress", terminal: false },
1226
+ { id: "fulfilled", label: "Fulfilled", terminal: true },
1227
+ { id: "partially_fulfilled", label: "Partially Fulfilled", terminal: false },
1228
+ { id: "returned", label: "Returned", terminal: true },
1229
+ { id: "partially_returned", label: "Partially Returned", terminal: false },
1230
+ { id: "cancelled", label: "Cancelled", terminal: true }
1231
+ ];
1232
+ function basePaymentDefinitions() {
1233
+ return PAYMENT_DEFS.map((d) => ({
1234
+ id: d.id,
1235
+ label: d.label,
1236
+ isBase: true,
1237
+ isTerminal: d.terminal
1238
+ }));
1239
+ }
1240
+ function baseFulfillmentDefinitions() {
1241
+ return FULFILLMENT_DEFS.map((d) => ({
1242
+ id: d.id,
1243
+ label: d.label,
1244
+ isBase: true,
1245
+ isTerminal: d.terminal
1246
+ }));
1247
+ }
1248
+ var STATE_SCHEMA = Object.freeze({
1249
+ paymentStates: Object.freeze(basePaymentDefinitions()),
1250
+ fulfillmentStates: Object.freeze(baseFulfillmentDefinitions())
1251
+ });
1252
+
1253
+ // order-state-machine/financial-invariants.ts
1254
+ var REFUND_ALLOWED_FULFILLMENT = /* @__PURE__ */ new Set(["fulfilled", "returned", "partially_returned", "cancelled"]);
1255
+ var PAYMENT_COLLECTION_ORDER = ["unpaid", "partially_paid", "paid"];
1256
+ var FINANCIAL_INVARIANTS = [
1257
+ {
1258
+ id: "no-leave-refunded",
1259
+ description: "Cannot change payment state after a full refund (no un-refund / reactivation of funds)",
1260
+ check: (from, to) => from?.payment === "refunded" && to.payment !== "refunded"
1261
+ },
1262
+ {
1263
+ id: "no-leave-voided",
1264
+ description: "Cannot un-void payment (voided orders stay voided on the payment axis)",
1265
+ check: (from, to) => from?.payment === "voided" && to.payment !== "voided"
1266
+ },
1267
+ {
1268
+ id: "no-refund-without-fulfillment",
1269
+ description: "Cannot mark payment as fully refunded unless fulfillment is delivered, returned, or cancelled",
1270
+ check: (_from, to) => to.payment === "refunded" && !REFUND_ALLOWED_FULFILLMENT.has(to.fulfillment)
1271
+ },
1272
+ {
1273
+ id: "no-partial-refund-in-draft",
1274
+ description: "Cannot partially refund while order is still in draft fulfillment",
1275
+ check: (_from, to) => to.payment === "partially_refunded" && to.fulfillment === "draft"
1276
+ },
1277
+ {
1278
+ id: "no-payment-regression",
1279
+ description: "Payment cannot regress to a lower collection state without a refund \u2014 collected funds must be returned through the refund flow, not by reverting payment state",
1280
+ check: (from, to) => {
1281
+ if (!from) return false;
1282
+ const fromIdx = PAYMENT_COLLECTION_ORDER.indexOf(from.payment);
1283
+ const toIdx = PAYMENT_COLLECTION_ORDER.indexOf(to.payment);
1284
+ return fromIdx !== -1 && toIdx !== -1 && fromIdx > toIdx;
1285
+ }
1286
+ }
1287
+ ];
1288
+ function getFinancialInvariantViolations(from, to) {
1289
+ const ids = [];
1290
+ for (const inv of FINANCIAL_INVARIANTS) {
1291
+ if (inv.check(from, to)) {
1292
+ ids.push(inv.id);
1293
+ }
1294
+ }
1295
+ return ids;
1296
+ }
1297
+ function violatesFinancialInvariant(from, to) {
1298
+ return getFinancialInvariantViolations(from, to).length > 0;
1299
+ }
1300
+
1301
+ // order-state-machine/default-cross-axis-rules.ts
1302
+ var DEFAULT_CROSS_AXIS_RULES = [
1303
+ {
1304
+ id: "require-payment-before-prep",
1305
+ label: "Require payment before prep",
1306
+ description: "When moving fulfillment to in progress, payment must be paid or partially paid",
1307
+ enabled: true,
1308
+ trigger: { axis: "fulfillment", to: "in_progress" },
1309
+ requires: { axis: "payment", states: ["paid", "partially_paid"] }
1310
+ },
1311
+ {
1312
+ id: "require-fulfillment-or-return-before-full-refund",
1313
+ label: "Require fulfillment or return before full refund",
1314
+ description: "When moving payment to refunded, fulfillment must be fulfilled, returned, partially returned, or cancelled",
1315
+ enabled: true,
1316
+ trigger: { axis: "payment", to: "refunded" },
1317
+ requires: {
1318
+ axis: "fulfillment",
1319
+ states: ["fulfilled", "returned", "partially_returned", "cancelled"]
1320
+ }
1321
+ },
1322
+ {
1323
+ id: "require-return-context-before-partial-refund",
1324
+ label: "Require return path before partial refund",
1325
+ description: "When moving payment to partially refunded, fulfillment must reflect a completed or return path",
1326
+ enabled: true,
1327
+ trigger: { axis: "payment", to: "partially_refunded" },
1328
+ requires: {
1329
+ axis: "fulfillment",
1330
+ states: ["fulfilled", "partially_returned", "returned"]
1331
+ }
1332
+ },
1333
+ {
1334
+ id: "block-fulfillment-when-payment-voided",
1335
+ label: "Block fulfillment completion when payment is voided",
1336
+ description: "When moving fulfillment to fulfilled, payment must not be voided",
1337
+ enabled: true,
1338
+ trigger: { axis: "fulfillment", to: "fulfilled" },
1339
+ requires: {
1340
+ axis: "payment",
1341
+ states: ["unpaid", "partially_paid", "paid", "partially_refunded", "refunded"]
1342
+ }
1343
+ },
1344
+ {
1345
+ id: "require-payment-before-fulfillment-complete",
1346
+ label: "Require payment before fulfillment complete",
1347
+ description: "When moving fulfillment to fulfilled, payment must be paid or partially paid",
1348
+ enabled: true,
1349
+ trigger: { axis: "fulfillment", to: "fulfilled" },
1350
+ requires: { axis: "payment", states: ["paid", "partially_paid"] }
1351
+ }
1352
+ ];
1353
+
1354
+ // order-state-machine/default-config.ts
1355
+ var DEFAULT_EPOCH = /* @__PURE__ */ new Date(0);
1356
+ var PAYMENT_LABELS = new Map(
1357
+ basePaymentDefinitions().map((d) => [d.id, d.label])
1358
+ );
1359
+ var FULFILLMENT_LABELS = new Map(
1360
+ baseFulfillmentDefinitions().map((d) => [d.id, d.label])
1361
+ );
1362
+ var TERMINAL_PAYMENT_STATES = new Set(
1363
+ basePaymentDefinitions().filter((d) => d.isTerminal).map((d) => d.id)
1364
+ );
1365
+ var DISPLAY_LABEL_OVERRIDES = {
1366
+ "unpaid|draft": "In Cart",
1367
+ "unpaid|pending": "Pending Payment",
1368
+ "unpaid|on_hold": "On Hold",
1369
+ "unpaid|cancelled": "Cancelled",
1370
+ "partially_paid|pending": "Deposit Received",
1371
+ "partially_paid|on_hold": "On Hold - Deposit Received",
1372
+ "paid|pending": "Paid - Awaiting Fulfillment",
1373
+ "paid|on_hold": "Paid - On Hold",
1374
+ "paid|fulfilled": "Completed",
1375
+ "partially_refunded|fulfilled": "Partially Refunded",
1376
+ "partially_refunded|partially_returned": "Partially Returned",
1377
+ "refunded|fulfilled": "Refunded",
1378
+ "refunded|returned": "Returned and Refunded",
1379
+ "voided|cancelled": "Cancelled"
1380
+ };
1381
+ function buildDefaultDisplayStateMap() {
1382
+ const rules = [];
1383
+ for (const p of PAYMENT_STATES) {
1384
+ for (const f of FULFILLMENT_STATES) {
1385
+ const key = `${p}|${f}`;
1386
+ const override = DISPLAY_LABEL_OVERRIDES[key];
1387
+ if (TERMINAL_PAYMENT_STATES.has(p) && !override) continue;
1388
+ const label = override ?? `${PAYMENT_LABELS.get(p)} / ${FULFILLMENT_LABELS.get(f)}`;
1389
+ rules.push({ paymentState: p, fulfillmentState: f, label });
1390
+ }
1391
+ }
1392
+ return rules;
1393
+ }
1394
+ var DEFAULT_DISPLAY_STATE_MAP = buildDefaultDisplayStateMap();
1395
+ var DEFAULT_CONFIG = {
1396
+ _id: "default",
1397
+ companyId: "system",
1398
+ version: 1,
1399
+ name: "Default",
1400
+ isDefault: true,
1401
+ paymentPaths: [],
1402
+ fulfillmentPaths: [],
1403
+ paymentPathMode: "permissive",
1404
+ fulfillmentPathMode: "permissive",
1405
+ crossAxisRules: [...DEFAULT_CROSS_AXIS_RULES],
1406
+ transitionConditions: [],
1407
+ validInitialStates: [{ payment: "unpaid", fulfillment: "draft" }],
1408
+ displayStateMap: [...DEFAULT_DISPLAY_STATE_MAP],
1409
+ createdAt: DEFAULT_EPOCH,
1410
+ updatedAt: DEFAULT_EPOCH
1411
+ };
1412
+ function buildResolvedConfig(config) {
1413
+ return {
1414
+ ...config,
1415
+ paymentStates: STATE_SCHEMA.paymentStates,
1416
+ fulfillmentStates: STATE_SCHEMA.fulfillmentStates
1417
+ };
1418
+ }
1419
+ var DEFAULT_RESOLVED_CONFIG = buildResolvedConfig(DEFAULT_CONFIG);
1420
+
1421
+ // order-state-machine/pos-preset.ts
1422
+ var POS_CROSS_AXIS_RULES = [
1423
+ {
1424
+ id: "pos-pay-requires-open-fulfillment",
1425
+ label: "Payments only on open fulfillment states",
1426
+ description: "POS payments are only valid on orders whose fulfillment is open (draft / pending / on_hold) or auto-fulfilled in lock-step (fulfilled). Returned / cancelled / in-progress fulfillment must use refund flows instead.",
1427
+ enabled: true,
1428
+ trigger: { axis: "payment", to: ["payment_pending", "paid", "partially_paid"] },
1429
+ requires: {
1430
+ axis: "fulfillment",
1431
+ states: ["draft", "pending", "on_hold", "fulfilled"]
1432
+ }
1433
+ }
1434
+ ];
1435
+ var POS_VALID_INITIAL_STATES = [
1436
+ { payment: "unpaid", fulfillment: "draft" },
1437
+ { payment: "unpaid", fulfillment: "on_hold" },
1438
+ { payment: "unpaid", fulfillment: "pending" },
1439
+ { payment: "paid", fulfillment: "fulfilled" },
1440
+ { payment: "partially_paid", fulfillment: "draft" },
1441
+ { payment: "partially_paid", fulfillment: "pending" }
1442
+ ];
1443
+ function buildPosPresetConfig(companyId) {
1444
+ return {
1445
+ ...DEFAULT_CONFIG,
1446
+ _id: "pos-preset",
1447
+ companyId: companyId ?? DEFAULT_CONFIG.companyId,
1448
+ name: "POS Preset",
1449
+ crossAxisRules: [...DEFAULT_CROSS_AXIS_RULES, ...POS_CROSS_AXIS_RULES],
1450
+ validInitialStates: [...POS_VALID_INITIAL_STATES],
1451
+ displayStateMap: [...DEFAULT_DISPLAY_STATE_MAP]
1452
+ };
1453
+ }
1454
+
1455
+ // order-state-machine/build-order-context.ts
1456
+ function sumNumbers(items) {
1457
+ if (!items?.length) return 0;
1458
+ let t = 0;
1459
+ for (const x of items) {
1460
+ const n = x.amount;
1461
+ if (typeof n === "number" && Number.isFinite(n)) t += n;
1462
+ }
1463
+ return t;
1464
+ }
1465
+ function sumRefundQuantities(refunds) {
1466
+ if (!refunds?.length) return 0;
1467
+ let t = 0;
1468
+ for (const r of refunds) {
1469
+ const q = r.quantity;
1470
+ if (typeof q === "number" && Number.isFinite(q) && q > 0) t += q;
1471
+ }
1472
+ return t;
1473
+ }
1474
+ function buildOrderContext(order, extras) {
1475
+ const o = order ?? {};
1476
+ const total = typeof o.total === "number" && Number.isFinite(o.total) ? o.total : 0;
1477
+ const balance = typeof o.balance === "number" && Number.isFinite(o.balance) ? o.balance : 0;
1478
+ const paymentMethods = o.paymentMethods ?? [];
1479
+ const refunds = o.refunds ?? o.refund ?? [];
1480
+ const lineItems = o.lineItems ?? [];
1481
+ const totalPaid = sumNumbers(paymentMethods);
1482
+ const totalRefunded = sumRefundQuantities(refunds);
1483
+ const isFullyPaid = total > 0 ? balance <= 0 : totalPaid > 0 && balance <= 0;
1484
+ const hasPartialPayments = totalPaid > 0 && balance > 0;
1485
+ let itemCount = 0;
1486
+ let fulfilledItemCount = 0;
1487
+ let returnedItemCount = 0;
1488
+ for (const li of lineItems) {
1489
+ const q = typeof li.quantity === "number" && Number.isFinite(li.quantity) ? Math.max(0, li.quantity) : 0;
1490
+ itemCount += q;
1491
+ const fq = typeof li.fulfilledQuantity === "number" && Number.isFinite(li.fulfilledQuantity) ? Math.max(0, li.fulfilledQuantity) : 0;
1492
+ fulfilledItemCount += Math.min(fq, q);
1493
+ const rq = typeof li.returnedQuantity === "number" && Number.isFinite(li.returnedQuantity) ? Math.max(0, li.returnedQuantity) : 0;
1494
+ returnedItemCount += Math.min(rq, q);
1495
+ }
1496
+ const isFullyReturned = itemCount > 0 ? returnedItemCount >= itemCount : returnedItemCount > 0;
1497
+ const hasPartialReturns = returnedItemCount > 0 && !isFullyReturned;
1498
+ return {
1499
+ order: {
1500
+ total,
1501
+ balance,
1502
+ paymentMethods,
1503
+ refunds,
1504
+ lineItems
1505
+ },
1506
+ computed: {
1507
+ balance,
1508
+ isFullyPaid,
1509
+ hasPartialPayments,
1510
+ totalPaid,
1511
+ totalRefunded,
1512
+ itemCount,
1513
+ fulfilledItemCount,
1514
+ returnedItemCount,
1515
+ isFullyReturned,
1516
+ hasPartialReturns
1517
+ },
1518
+ splitPayment: extras?.splitPayment
1519
+ };
1520
+ }
1521
+
1522
+ // order-state-machine/display-state.ts
1523
+ function matchesOptional(actual, rule) {
1524
+ if (rule === void 0) return true;
1525
+ return Array.isArray(rule) ? rule.includes(actual) : rule === actual;
1526
+ }
1527
+ function deriveDisplayState(payment, fulfillment, config) {
1528
+ for (const rule of config.displayStateMap) {
1529
+ if (matchesOptional(payment, rule.paymentState) && matchesOptional(fulfillment, rule.fulfillmentState)) {
1530
+ return { label: rule.label, color: rule.color, icon: rule.icon };
1531
+ }
1532
+ }
1533
+ return { label: `${payment} / ${fulfillment}` };
1534
+ }
1535
+ function displayRuleMatchesPair(rule, payment, fulfillment) {
1536
+ return matchesOptional(payment, rule.paymentState) && matchesOptional(fulfillment, rule.fulfillmentState);
1537
+ }
1538
+
1539
+ // order-state-machine/condition-eval.ts
1540
+ function getByPath(root, path) {
1541
+ const parts = path.split(".").filter(Boolean);
1542
+ let cur = root;
1543
+ for (const p of parts) {
1544
+ if (cur === null || cur === void 0) return void 0;
1545
+ if (typeof cur !== "object") return void 0;
1546
+ cur = cur[p];
1547
+ }
1548
+ return cur;
1549
+ }
1550
+ function isEmptyValue(v) {
1551
+ if (v === null || v === void 0) return true;
1552
+ if (typeof v === "string") return v.length === 0;
1553
+ if (Array.isArray(v)) return v.length === 0;
1554
+ return false;
1555
+ }
1556
+ function evaluateCondition(condition, context) {
1557
+ const left = getByPath(context, condition.field);
1558
+ const op = condition.operator;
1559
+ const right = condition.value;
1560
+ let ok = false;
1561
+ switch (op) {
1562
+ case "eq":
1563
+ ok = left === right;
1564
+ break;
1565
+ case "neq":
1566
+ ok = left !== right;
1567
+ break;
1568
+ case "gt":
1569
+ ok = typeof left === "number" && typeof right === "number" && left > right;
1570
+ break;
1571
+ case "gte":
1572
+ ok = typeof left === "number" && typeof right === "number" && left >= right;
1573
+ break;
1574
+ case "lt":
1575
+ ok = typeof left === "number" && typeof right === "number" && left < right;
1576
+ break;
1577
+ case "lte":
1578
+ ok = typeof left === "number" && typeof right === "number" && left <= right;
1579
+ break;
1580
+ case "in":
1581
+ ok = Array.isArray(right) && right.some((r) => r === left);
1582
+ break;
1583
+ case "notIn":
1584
+ ok = Array.isArray(right) && !right.some((r) => r === left);
1585
+ break;
1586
+ case "isEmpty":
1587
+ ok = isEmptyValue(left);
1588
+ break;
1589
+ case "isNotEmpty":
1590
+ ok = !isEmptyValue(left);
1591
+ break;
1592
+ default: {
1593
+ const _exhaustive = op;
1594
+ return {
1595
+ ok: false,
1596
+ failed: {
1597
+ field: condition.field,
1598
+ operator: condition.operator,
1599
+ value: condition.value,
1600
+ reason: `Unknown operator: ${_exhaustive}`
1601
+ }
1602
+ };
1603
+ }
1604
+ }
1605
+ if (!ok) {
1606
+ return {
1607
+ ok: false,
1608
+ failed: {
1609
+ field: condition.field,
1610
+ operator: condition.operator,
1611
+ value: condition.value
1612
+ }
1613
+ };
1614
+ }
1615
+ return { ok: true };
1616
+ }
1617
+ function groupPasses(group, context) {
1618
+ const failed = [];
1619
+ for (const c of group.conditions) {
1620
+ const r = evaluateCondition(c, context);
1621
+ if (!r.ok && r.failed) failed.push(r.failed);
1622
+ }
1623
+ return { ok: failed.length === 0, failed };
1624
+ }
1625
+ function evaluateConditionSet(set, context) {
1626
+ if (!set || set.groups.length === 0) {
1627
+ return { ok: true, failedConditions: [] };
1628
+ }
1629
+ const allFailed = [];
1630
+ for (const g of set.groups) {
1631
+ const { ok, failed } = groupPasses(g, context);
1632
+ if (ok) return { ok: true, failedConditions: [] };
1633
+ allFailed.push(...failed);
1634
+ }
1635
+ return { ok: false, failedConditions: allFailed };
1636
+ }
1637
+ function conditionSummary(c) {
1638
+ return `${c.field} ${c.operator} ${JSON.stringify(c.value)}`;
1639
+ }
1640
+
1641
+ // order-state-machine/engine.ts
1642
+ function pairInInitialList(to, config) {
1643
+ return config.validInitialStates.some(
1644
+ (p) => p.payment === to.payment && p.fulfillment === to.fulfillment
1645
+ );
1646
+ }
1647
+ function triggerTargets(rule) {
1648
+ const t = rule.trigger.to;
1649
+ return Array.isArray(t) ? [...t] : [t];
1650
+ }
1651
+ function crossAxisRuleApplies(rule, from, to) {
1652
+ if (!rule.enabled) return false;
1653
+ const targets = triggerTargets(rule);
1654
+ if (rule.trigger.axis === "fulfillment") {
1655
+ if (!targets.includes(to.fulfillment)) return false;
1656
+ if (from !== null && from.fulfillment === to.fulfillment) return false;
1657
+ return true;
1658
+ }
1659
+ if (!targets.includes(to.payment)) return false;
1660
+ if (from !== null && from.payment === to.payment) return false;
1661
+ return true;
1662
+ }
1663
+ function crossAxisSatisfied(rule, to) {
1664
+ const req = rule.requires;
1665
+ if (req.axis === "payment") {
1666
+ return req.states.includes(to.payment);
1667
+ }
1668
+ return req.states.includes(to.fulfillment);
1669
+ }
1670
+ function firstBlockingCrossAxisRule(from, to, config) {
1671
+ for (const rule of config.crossAxisRules) {
1672
+ if (!crossAxisRuleApplies(rule, from, to)) continue;
1673
+ if (!crossAxisSatisfied(rule, to)) return rule;
1674
+ }
1675
+ return void 0;
1676
+ }
1677
+ function findConditionSet(config, id) {
1678
+ if (!id) return void 0;
1679
+ return config.transitionConditions.find((s) => s.id === id);
1680
+ }
1681
+ function pathExists(paths, fromId, toId) {
1682
+ return paths.some((p) => p.from === fromId && p.to === toId);
1683
+ }
1684
+ function axisTransitionAllowed(mode, paths, fromId, toId) {
1685
+ if (fromId === toId) return true;
1686
+ if (mode === "permissive") return true;
1687
+ return pathExists(paths, fromId, toId);
1688
+ }
1689
+ function collectPathConditionFailures(config, from, to, context) {
1690
+ const failed = [];
1691
+ if (from === null) return { failed };
1692
+ if (from.payment !== to.payment) {
1693
+ const p = config.paymentPaths.find(
1694
+ (x) => x.from === from.payment && x.to === to.payment
1695
+ );
1696
+ const set = findConditionSet(config, p?.conditionSetId);
1697
+ const ev = evaluateConditionSet(set, context);
1698
+ if (!ev.ok) failed.push(...ev.failedConditions);
1699
+ }
1700
+ if (from.fulfillment !== to.fulfillment) {
1701
+ const p = config.fulfillmentPaths.find(
1702
+ (x) => x.from === from.fulfillment && x.to === to.fulfillment
1703
+ );
1704
+ const set = findConditionSet(config, p?.conditionSetId);
1705
+ const ev = evaluateConditionSet(set, context);
1706
+ if (!ev.ok) failed.push(...ev.failedConditions);
1707
+ }
1708
+ return { failed };
1709
+ }
1710
+ function pathBlocked(config, from, to) {
1711
+ if (from === null) return false;
1712
+ if (from.payment !== to.payment && !axisTransitionAllowed(
1713
+ config.paymentPathMode,
1714
+ config.paymentPaths,
1715
+ from.payment,
1716
+ to.payment
1717
+ )) {
1718
+ return true;
1719
+ }
1720
+ if (from.fulfillment !== to.fulfillment && !axisTransitionAllowed(
1721
+ config.fulfillmentPathMode,
1722
+ config.fulfillmentPaths,
1723
+ from.fulfillment,
1724
+ to.fulfillment
1725
+ )) {
1726
+ return true;
1727
+ }
1728
+ return false;
1729
+ }
1730
+ function canTransition(request) {
1731
+ const { from, to, config, context } = request;
1732
+ const fin = getFinancialInvariantViolations(from, to);
1733
+ if (fin.length > 0) {
1734
+ return {
1735
+ allowed: false,
1736
+ blockedBy: "financial_invariant",
1737
+ guard: fin[0],
1738
+ reason: `Blocked by financial invariant: ${fin[0]}`
1739
+ };
1740
+ }
1741
+ const cross = firstBlockingCrossAxisRule(from, to, config);
1742
+ if (cross) {
1743
+ return {
1744
+ allowed: false,
1745
+ blockedBy: "cross_axis_rule",
1746
+ guard: cross.id,
1747
+ reason: `Blocked by cross-axis rule: ${cross.label}`
1748
+ };
1749
+ }
1750
+ if (from === null) {
1751
+ if (!pairInInitialList(to, config)) {
1752
+ return {
1753
+ allowed: false,
1754
+ blockedBy: "path",
1755
+ reason: "Target state is not a valid initial state for new orders"
1756
+ };
1757
+ }
1758
+ } else if (pathBlocked(config, from, to)) {
1759
+ return {
1760
+ allowed: false,
1761
+ blockedBy: "path",
1762
+ reason: "Transition is not allowed by configured path rules"
1763
+ };
1764
+ }
1765
+ if (!request.skipConditionEvaluation) {
1766
+ const cond = collectPathConditionFailures(config, from, to, context);
1767
+ if (cond.failed.length > 0) {
1768
+ return {
1769
+ allowed: false,
1770
+ blockedBy: "condition",
1771
+ reason: "Transition conditions not satisfied",
1772
+ failedConditions: cond.failed
1773
+ };
1774
+ }
1775
+ }
1776
+ return { allowed: true };
1777
+ }
1778
+ function labelForPayment(id, config) {
1779
+ return config.paymentStates.find((s) => s.id === id)?.label ?? id;
1780
+ }
1781
+ function labelForFulfillment(id, config) {
1782
+ return config.fulfillmentStates.find((s) => s.id === id)?.label ?? id;
1783
+ }
1784
+ function transitionDisplayLabel(to, config) {
1785
+ const pay = labelForPayment(to.payment, config);
1786
+ const ful = labelForFulfillment(to.fulfillment, config);
1787
+ const derived = deriveDisplayState(to.payment, to.fulfillment, config).label;
1788
+ if (derived && derived !== `${to.payment} / ${to.fulfillment}`) {
1789
+ return derived;
1790
+ }
1791
+ return `${pay} \xB7 ${ful}`;
1792
+ }
1793
+ function conditionMetLines(config, from, to, context) {
1794
+ const lines = [];
1795
+ const appendForPath = (p) => {
1796
+ const set = findConditionSet(config, p?.conditionSetId);
1797
+ if (!set) return;
1798
+ for (const g of set.groups) {
1799
+ for (const c of g.conditions) {
1800
+ const r = evaluateCondition(c, context);
1801
+ lines.push({
1802
+ met: r.ok,
1803
+ description: conditionSummary(c)
1804
+ });
1805
+ }
1806
+ }
1807
+ };
1808
+ if (from.payment !== to.payment) {
1809
+ const p = config.paymentPaths.find(
1810
+ (x) => x.from === from.payment && x.to === to.payment
1811
+ );
1812
+ appendForPath(p);
1813
+ }
1814
+ if (from.fulfillment !== to.fulfillment) {
1815
+ const p = config.fulfillmentPaths.find(
1816
+ (x) => x.from === from.fulfillment && x.to === to.fulfillment
1817
+ );
1818
+ appendForPath(p);
1819
+ }
1820
+ return lines;
1821
+ }
1822
+ function getAvailableTransitions(current, config, context) {
1823
+ const candidates = [];
1824
+ for (const s of config.paymentStates) {
1825
+ if (s.id === current.payment) continue;
1826
+ candidates.push({ payment: s.id, fulfillment: current.fulfillment });
1827
+ }
1828
+ for (const s of config.fulfillmentStates) {
1829
+ if (s.id === current.fulfillment) continue;
1830
+ candidates.push({ payment: current.payment, fulfillment: s.id });
1831
+ }
1832
+ const out = [];
1833
+ const seen = /* @__PURE__ */ new Set();
1834
+ for (const to of candidates) {
1835
+ const key = `${to.payment}:${to.fulfillment}`;
1836
+ if (seen.has(key)) continue;
1837
+ seen.add(key);
1838
+ const result = canTransition({
1839
+ from: current,
1840
+ to,
1841
+ config,
1842
+ context
1843
+ });
1844
+ if (!result.allowed) continue;
1845
+ out.push({
1846
+ to,
1847
+ displayLabel: transitionDisplayLabel(to, config),
1848
+ conditions: conditionMetLines(config, current, to, context)
1849
+ });
1850
+ }
1851
+ return out;
1852
+ }
1853
+
1854
+ // order-state-machine/validate-config.ts
1855
+ function paymentStateIds(config) {
1856
+ return new Set(config.paymentStates.map((s) => s.id));
1857
+ }
1858
+ function fulfillmentStateIds(config) {
1859
+ return new Set(config.fulfillmentStates.map((s) => s.id));
1860
+ }
1861
+ var VALID_OPERATORS = new Set(CONDITION_OPERATORS);
1862
+ function validateConditionShape(c, path, errors) {
1863
+ if (!VALID_OPERATORS.has(c.operator)) {
1864
+ errors.push({
1865
+ code: "invalid_condition_operator",
1866
+ message: `Unknown operator "${c.operator}"`,
1867
+ path
1868
+ });
1869
+ return;
1870
+ }
1871
+ const needsNumberCompare = ["gt", "gte", "lt", "lte"].includes(c.operator);
1872
+ if (needsNumberCompare && typeof c.value !== "number") {
1873
+ errors.push({
1874
+ code: "invalid_condition_value_type",
1875
+ message: `Operator "${c.operator}" requires a numeric value`,
1876
+ path: `${path}.value`
1877
+ });
1878
+ }
1879
+ if ((c.operator === "in" || c.operator === "notIn") && !Array.isArray(c.value)) {
1880
+ errors.push({
1881
+ code: "invalid_condition_value_type",
1882
+ message: `Operator "${c.operator}" requires an array value`,
1883
+ path: `${path}.value`
1884
+ });
1885
+ }
1886
+ }
1887
+ function validationContext() {
1888
+ return buildOrderContext({
1889
+ total: 100,
1890
+ balance: 0,
1891
+ paymentMethods: [{ amount: 100 }],
1892
+ lineItems: [{ quantity: 1, fulfilledQuantity: 1, returnedQuantity: 0 }]
1893
+ });
1894
+ }
1895
+ function pairKey(p) {
1896
+ return `${p.payment}\0${p.fulfillment}`;
1897
+ }
1898
+ function validateConfig(config) {
1899
+ const errors = [];
1900
+ const warnings = [];
1901
+ if (!Number.isFinite(config.version) || config.version < 1) {
1902
+ errors.push({
1903
+ code: "invalid_version",
1904
+ message: "version must be a finite number >= 1",
1905
+ path: "version"
1906
+ });
1907
+ }
1908
+ if (!config.validInitialStates?.length) {
1909
+ errors.push({
1910
+ code: "missing_initial_states",
1911
+ message: "validInitialStates must contain at least one pair",
1912
+ path: "validInitialStates"
1913
+ });
1914
+ }
1915
+ const payIds = paymentStateIds(config);
1916
+ const fulIds = fulfillmentStateIds(config);
1917
+ config.validInitialStates?.forEach((pair, i) => {
1918
+ if (!payIds.has(pair.payment)) {
1919
+ errors.push({
1920
+ code: "initial_unknown_payment",
1921
+ message: `validInitialStates[${i}].payment "${pair.payment}" is not defined`,
1922
+ path: `validInitialStates[${i}].payment`
1923
+ });
1924
+ }
1925
+ if (!fulIds.has(pair.fulfillment)) {
1926
+ errors.push({
1927
+ code: "initial_unknown_fulfillment",
1928
+ message: `validInitialStates[${i}].fulfillment "${pair.fulfillment}" is not defined`,
1929
+ path: `validInitialStates[${i}].fulfillment`
1930
+ });
1931
+ }
1932
+ });
1933
+ const conditionSetIds = new Set(config.transitionConditions.map((s) => s.id));
1934
+ config.transitionConditions.forEach((set, si) => {
1935
+ set.groups.forEach((g, gi) => {
1936
+ g.conditions.forEach((c, ci) => {
1937
+ validateConditionShape(
1938
+ c,
1939
+ `transitionConditions[${si}].groups[${gi}].conditions[${ci}]`,
1940
+ errors
1941
+ );
1942
+ });
1943
+ });
1944
+ });
1945
+ const pathConditionRef = (paths, axis) => {
1946
+ paths.forEach((p, i) => {
1947
+ if (p.conditionSetId && !conditionSetIds.has(p.conditionSetId)) {
1948
+ errors.push({
1949
+ code: "unknown_condition_set",
1950
+ message: `${axis}Paths[${i}] references unknown conditionSetId "${p.conditionSetId}"`,
1951
+ path: `${axis}Paths[${i}].conditionSetId`
1952
+ });
1953
+ }
1954
+ });
1955
+ };
1956
+ pathConditionRef(config.paymentPaths, "payment");
1957
+ pathConditionRef(config.fulfillmentPaths, "fulfillment");
1958
+ config.paymentPaths.forEach((path, i) => {
1959
+ if (!payIds.has(path.from) || !payIds.has(path.to)) {
1960
+ errors.push({
1961
+ code: "payment_path_unknown_state",
1962
+ message: `paymentPaths[${i}] references unknown payment state`,
1963
+ path: `paymentPaths[${i}]`
1964
+ });
1965
+ return;
1966
+ }
1967
+ for (const f of config.fulfillmentStates) {
1968
+ const from = { payment: path.from, fulfillment: f.id };
1969
+ const to = { payment: path.to, fulfillment: f.id };
1970
+ if (getFinancialInvariantViolations(null, from).length > 0) continue;
1971
+ const v = getFinancialInvariantViolations(from, to);
1972
+ if (v.length > 0) {
1973
+ errors.push({
1974
+ code: "payment_path_violates_financial_invariant",
1975
+ message: `paymentPaths[${i}] (${path.from}\u2192${path.to}) with fulfillment "${f.id}" violates invariant(s): ${v.join(", ")}`,
1976
+ path: `paymentPaths[${i}]`
1977
+ });
1978
+ }
1979
+ }
1980
+ });
1981
+ config.fulfillmentPaths.forEach((path, i) => {
1982
+ if (!fulIds.has(path.from) || !fulIds.has(path.to)) {
1983
+ errors.push({
1984
+ code: "fulfillment_path_unknown_state",
1985
+ message: `fulfillmentPaths[${i}] references unknown fulfillment state`,
1986
+ path: `fulfillmentPaths[${i}]`
1987
+ });
1988
+ return;
1989
+ }
1990
+ for (const p of config.paymentStates) {
1991
+ const from = { payment: p.id, fulfillment: path.from };
1992
+ const to = { payment: p.id, fulfillment: path.to };
1993
+ if (getFinancialInvariantViolations(null, from).length > 0) continue;
1994
+ const v = getFinancialInvariantViolations(from, to);
1995
+ if (v.length > 0) {
1996
+ errors.push({
1997
+ code: "fulfillment_path_violates_financial_invariant",
1998
+ message: `fulfillmentPaths[${i}] (${path.from}\u2192${path.to}) with payment "${p.id}" violates invariant(s): ${v.join(", ")}`,
1999
+ path: `fulfillmentPaths[${i}]`
2000
+ });
2001
+ }
2002
+ }
2003
+ });
2004
+ config.crossAxisRules.forEach((rule, i) => {
2005
+ const req = rule.requires;
2006
+ if (req.axis === "payment") {
2007
+ for (const id of req.states) {
2008
+ if (!payIds.has(id)) {
2009
+ errors.push({
2010
+ code: "cross_axis_unknown_payment",
2011
+ message: `crossAxisRules[${i}] requires unknown payment state "${id}"`,
2012
+ path: `crossAxisRules[${i}].requires.states`
2013
+ });
2014
+ }
2015
+ }
2016
+ } else {
2017
+ for (const id of req.states) {
2018
+ if (!fulIds.has(id)) {
2019
+ errors.push({
2020
+ code: "cross_axis_unknown_fulfillment",
2021
+ message: `crossAxisRules[${i}] requires unknown fulfillment state "${id}"`,
2022
+ path: `crossAxisRules[${i}].requires.states`
2023
+ });
2024
+ }
2025
+ }
2026
+ }
2027
+ const trig = rule.trigger;
2028
+ const targets = Array.isArray(trig.to) ? trig.to : [trig.to];
2029
+ if (trig.axis === "payment") {
2030
+ for (const id of targets) {
2031
+ if (!payIds.has(id)) {
2032
+ errors.push({
2033
+ code: "cross_axis_trigger_unknown_payment",
2034
+ message: `crossAxisRules[${i}] triggers on unknown payment state "${id}"`,
2035
+ path: `crossAxisRules[${i}].trigger.to`
2036
+ });
2037
+ }
2038
+ }
2039
+ } else {
2040
+ for (const id of targets) {
2041
+ if (!fulIds.has(id)) {
2042
+ errors.push({
2043
+ code: "cross_axis_trigger_unknown_fulfillment",
2044
+ message: `crossAxisRules[${i}] triggers on unknown fulfillment state "${id}"`,
2045
+ path: `crossAxisRules[${i}].trigger.to`
2046
+ });
2047
+ }
2048
+ }
2049
+ }
2050
+ });
2051
+ strictAxisReachability(config, "payment", payIds, warnings);
2052
+ strictAxisReachability(config, "fulfillment", fulIds, warnings);
2053
+ combinedReachability(config, warnings);
2054
+ if (!config.displayStateMap.length) {
2055
+ warnings.push({
2056
+ code: "empty_display_map",
2057
+ message: "displayStateMap is empty; UI will fall back to raw state pair labels",
2058
+ path: "displayStateMap"
2059
+ });
2060
+ } else {
2061
+ const missingDisplay = [];
2062
+ for (const p of PAYMENT_STATES) {
2063
+ for (const f of FULFILLMENT_STATES) {
2064
+ if (!payIds.has(p) || !fulIds.has(f)) continue;
2065
+ const matched = config.displayStateMap.some(
2066
+ (rule) => displayRuleMatchesPair(rule, p, f)
2067
+ );
2068
+ if (!matched) missingDisplay.push(`${p}/${f}`);
2069
+ }
2070
+ }
2071
+ if (missingDisplay.length > 0) {
2072
+ const sample = missingDisplay.slice(0, 8).join(", ");
2073
+ const more = missingDisplay.length > 8 ? ` (+${missingDisplay.length - 8} more)` : "";
2074
+ warnings.push({
2075
+ code: "display_map_missing_combos",
2076
+ message: `No displayStateMap rule matches ${missingDisplay.length} base pair(s): ${sample}${more}`,
2077
+ path: "displayStateMap"
2078
+ });
2079
+ }
2080
+ }
2081
+ refundReturnPathWarnings(config, payIds, fulIds, warnings);
2082
+ if (config.paymentPathMode === "strict" && config.paymentPaths.length === 0) {
2083
+ errors.push({
2084
+ code: "strict_payment_paths_empty",
2085
+ message: "paymentPathMode is strict but paymentPaths is empty",
2086
+ path: "paymentPaths"
2087
+ });
2088
+ }
2089
+ if (config.fulfillmentPathMode === "strict" && config.fulfillmentPaths.length === 0) {
2090
+ errors.push({
2091
+ code: "strict_fulfillment_paths_empty",
2092
+ message: "fulfillmentPathMode is strict but fulfillmentPaths is empty",
2093
+ path: "fulfillmentPaths"
2094
+ });
2095
+ }
2096
+ return {
2097
+ valid: errors.length === 0,
2098
+ errors,
2099
+ warnings
2100
+ };
2101
+ }
2102
+ function strictAxisReachability(config, axis, ids, warnings) {
2103
+ const mode = axis === "payment" ? config.paymentPathMode : config.fulfillmentPathMode;
2104
+ const paths = axis === "payment" ? config.paymentPaths : config.fulfillmentPaths;
2105
+ if (mode !== "strict" || paths.length === 0) return;
2106
+ const reachable = /* @__PURE__ */ new Set();
2107
+ const initials = new Set(
2108
+ config.validInitialStates.map((p) => axis === "payment" ? p.payment : p.fulfillment)
2109
+ );
2110
+ for (const id of initials) {
2111
+ if (ids.has(id)) bfsAxis(id, paths, reachable);
2112
+ }
2113
+ const stateRows = axis === "payment" ? config.paymentStates : config.fulfillmentStates;
2114
+ for (const id of stateRows) {
2115
+ if (!reachable.has(id.id)) {
2116
+ warnings.push({
2117
+ code: `${axis}_state_unreachable_strict`,
2118
+ message: `State "${id.id}" may be unreachable from valid initial ${axis} states under strict paths`,
2119
+ path: axis === "payment" ? "paymentPaths" : "fulfillmentPaths"
2120
+ });
2121
+ }
2122
+ if (!id.isTerminal) {
2123
+ const hasOut = paths.some((p) => p.from === id.id && p.to !== id.id);
2124
+ if (!hasOut) {
2125
+ warnings.push({
2126
+ code: `${axis}_nonterminal_no_outbound`,
2127
+ message: `Non-terminal ${axis} state "${id.id}" has no strict outbound path`,
2128
+ path: axis === "payment" ? "paymentPaths" : "fulfillmentPaths"
2129
+ });
2130
+ }
2131
+ }
2132
+ }
2133
+ }
2134
+ function bfsAxis(start, paths, reachable) {
2135
+ const q = [start];
2136
+ reachable.add(start);
2137
+ while (q.length) {
2138
+ const cur = q.pop();
2139
+ for (const p of paths) {
2140
+ if (p.from !== cur) continue;
2141
+ if (!reachable.has(p.to)) {
2142
+ reachable.add(p.to);
2143
+ q.push(p.to);
2144
+ }
2145
+ }
2146
+ }
2147
+ }
2148
+ function combinedReachability(config, warnings) {
2149
+ const ctx = validationContext();
2150
+ const payIds = config.paymentStates.map((s) => s.id);
2151
+ const fulIds = config.fulfillmentStates.map((s) => s.id);
2152
+ const seen = /* @__PURE__ */ new Set();
2153
+ const queue = [...config.validInitialStates];
2154
+ for (const p of queue) {
2155
+ seen.add(pairKey(p));
2156
+ }
2157
+ while (queue.length) {
2158
+ const cur = queue.pop();
2159
+ for (const np of payIds) {
2160
+ if (np === cur.payment) continue;
2161
+ const to = { payment: np, fulfillment: cur.fulfillment };
2162
+ const r = canTransition({
2163
+ from: cur,
2164
+ to,
2165
+ config,
2166
+ context: ctx,
2167
+ skipConditionEvaluation: true
2168
+ });
2169
+ const k = pairKey(to);
2170
+ if (r.allowed && !seen.has(k)) {
2171
+ seen.add(k);
2172
+ queue.push(to);
2173
+ }
2174
+ }
2175
+ for (const nf of fulIds) {
2176
+ if (nf === cur.fulfillment) continue;
2177
+ const to = { payment: cur.payment, fulfillment: nf };
2178
+ const r = canTransition({
2179
+ from: cur,
2180
+ to,
2181
+ config,
2182
+ context: ctx,
2183
+ skipConditionEvaluation: true
2184
+ });
2185
+ const k = pairKey(to);
2186
+ if (r.allowed && !seen.has(k)) {
2187
+ seen.add(k);
2188
+ queue.push(to);
2189
+ }
2190
+ }
2191
+ }
2192
+ const total = payIds.length * fulIds.length;
2193
+ if (seen.size < total && (config.paymentPathMode === "strict" || config.fulfillmentPathMode === "strict")) {
2194
+ warnings.push({
2195
+ code: "combined_pairs_not_all_reachable",
2196
+ message: "Some payment\xD7fulfillment pairs appear unreachable under current paths, cross-axis rules, and financial invariants (structural check with generic context)",
2197
+ path: "validInitialStates"
2198
+ });
2199
+ }
2200
+ }
2201
+ function refundReturnPathWarnings(config, payIds, fulIds, warnings) {
2202
+ const hasReturned = config.fulfillmentPaths.some(
2203
+ (p) => p.to === "returned" || p.from === "returned"
2204
+ );
2205
+ const hasRefunded = config.paymentPaths.some(
2206
+ (p) => p.to === "refunded" || p.from === "refunded"
2207
+ );
2208
+ if (fulIds.has("returned") && hasReturned && payIds.has("refunded") && !hasRefunded && config.paymentPathMode === "strict") {
2209
+ warnings.push({
2210
+ code: "refund_path_missing_for_return",
2211
+ message: 'Fulfillment paths mention "returned" but no strict payment path touches "refunded"; verify refund workflow',
2212
+ path: "paymentPaths"
2213
+ });
2214
+ }
2215
+ }
2216
+
2217
+ // order-state-machine/set-order-state.ts
2218
+ function mapToLegacyStatus(pair) {
2219
+ const { payment, fulfillment } = pair;
2220
+ if (payment === "voided") return "park-deleted";
2221
+ if (payment === "refunded") return "refunded";
2222
+ if (payment === "partially_refunded") return "partial-refund";
2223
+ if (payment === "paid") return "completed";
2224
+ if (fulfillment === "draft") return "in-cart";
2225
+ if (fulfillment === "on_hold") return "parked";
2226
+ if (fulfillment === "pending") return "parked";
2227
+ if (fulfillment === "cancelled") return "park-deleted";
2228
+ return "parked";
2229
+ }
2230
+ function setOrderState(order, paymentState, fulfillmentState, config, options) {
2231
+ order.paymentState = paymentState;
2232
+ order.fulfillmentState = fulfillmentState;
2233
+ const display = deriveDisplayState(paymentState, fulfillmentState, config);
2234
+ order.displayState = display.label;
2235
+ if (options?.includeLegacyStatus !== false) {
2236
+ order.status = mapToLegacyStatus({ payment: paymentState, fulfillment: fulfillmentState });
2237
+ }
2238
+ }
2239
+
2240
+ // order-state-machine/legacy-infer.ts
2241
+ function normalizeStatus(raw) {
2242
+ return (raw ?? "").trim().toLowerCase();
2243
+ }
2244
+ function hasRefundActivity(order) {
2245
+ const refunds = order.refunds ?? order.refund ?? [];
2246
+ return refunds.some((r) => {
2247
+ const q = r.quantity;
2248
+ return typeof q === "number" && q > 0;
2249
+ });
2250
+ }
2251
+ function inferStatesFromLegacyStatus(order) {
2252
+ const status = normalizeStatus(order.status);
2253
+ if (status === "completed") {
2254
+ return { payment: "paid", fulfillment: "fulfilled" };
2255
+ }
2256
+ if (status === "in-cart") {
2257
+ return { payment: "unpaid", fulfillment: "draft" };
2258
+ }
2259
+ if (status === "park-deleted") {
2260
+ return { payment: "voided", fulfillment: "cancelled" };
2261
+ }
2262
+ if (status === "refunded") {
2263
+ return { payment: "refunded", fulfillment: "returned" };
2264
+ }
2265
+ if (status === "partial-refund" || status === "partial_refund") {
2266
+ return { payment: "partially_refunded", fulfillment: "partially_returned" };
2267
+ }
2268
+ if (status === "parked") {
2269
+ const ctx = order.paymentMethods ?? [];
2270
+ const paid = ctx.reduce((s, m) => {
2271
+ const a = m.amount;
2272
+ return s + (typeof a === "number" && Number.isFinite(a) ? a : 0);
2273
+ }, 0);
2274
+ const partial = paid > 0 || typeof order.balance === "number" && typeof order.total === "number" && order.total > 0 && order.balance > 0 && order.balance < order.total;
2275
+ return {
2276
+ payment: partial ? "partially_paid" : "unpaid",
2277
+ fulfillment: "on_hold"
2278
+ };
2279
+ }
2280
+ if (status === "" && hasRefundActivity(order)) {
2281
+ return { payment: "partially_refunded", fulfillment: "partially_returned" };
2282
+ }
2283
+ return { payment: "unpaid", fulfillment: "pending" };
2284
+ }
2285
+
2286
+ // order-state-machine/resolve-template.ts
2287
+ function resolveTemplate(templateJson, params, values = {}) {
2288
+ const resolvedValues = {};
2289
+ for (const param of params) {
2290
+ const raw = values[param.key] ?? param.default;
2291
+ if (raw === void 0 || raw === null) {
2292
+ throw new Error(`Missing required parameter: "${param.key}" (${param.label})`);
2293
+ }
2294
+ validateParamValue(param, raw);
2295
+ resolvedValues[param.key] = raw;
2296
+ }
2297
+ let resolved = templateJson;
2298
+ for (const [key, value] of Object.entries(resolvedValues)) {
2299
+ const placeholder = `{{${key}}}`;
2300
+ const replacement = typeof value === "string" ? escapeJsonString(value) : String(value);
2301
+ resolved = replaceAll(resolved, placeholder, replacement);
2302
+ }
2303
+ let fragment;
2304
+ try {
2305
+ fragment = JSON.parse(resolved);
2306
+ } catch (err) {
2307
+ throw new Error(
2308
+ `Fragment template produced invalid JSON after substitution: ${err.message}`
2309
+ );
2310
+ }
2311
+ return { fragment, resolvedValues };
2312
+ }
2313
+ function validateParamValue(param, value) {
2314
+ const { key, label, type } = param;
2315
+ if (type === "string" && typeof value !== "string") {
2316
+ throw new Error(`Parameter "${key}" (${label}) must be a string, got ${typeof value}`);
2317
+ }
2318
+ if (type === "number") {
2319
+ if (typeof value !== "number" || Number.isNaN(value)) {
2320
+ throw new Error(`Parameter "${key}" (${label}) must be a number`);
2321
+ }
2322
+ if (param.min !== void 0 && value < param.min) {
2323
+ throw new Error(`Parameter "${key}" (${label}) must be >= ${param.min}`);
2324
+ }
2325
+ if (param.max !== void 0 && value > param.max) {
2326
+ throw new Error(`Parameter "${key}" (${label}) must be <= ${param.max}`);
2327
+ }
2328
+ }
2329
+ if (type === "boolean" && typeof value !== "boolean") {
2330
+ throw new Error(`Parameter "${key}" (${label}) must be a boolean`);
2331
+ }
2332
+ if (param.options && param.options.length > 0 && !param.options.includes(String(value))) {
2333
+ throw new Error(
2334
+ `Parameter "${key}" (${label}) must be one of: ${param.options.join(", ")}`
2335
+ );
2336
+ }
2337
+ }
2338
+ function escapeJsonString(value) {
2339
+ return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t");
2340
+ }
2341
+ function replaceAll(str, search, replacement) {
2342
+ let result = str;
2343
+ let idx = result.indexOf(search);
2344
+ while (idx !== -1) {
2345
+ result = result.slice(0, idx) + replacement + result.slice(idx + search.length);
2346
+ idx = result.indexOf(search, idx + replacement.length);
2347
+ }
2348
+ return result;
2349
+ }
2350
+
2351
+ // order-state-machine/validate-fragment.ts
2352
+ function validateFragmentCompatibility(config, fragment) {
2353
+ const errors = [];
2354
+ validateStateReferences(fragment, errors);
2355
+ validatePathUniqueness(config, fragment, errors);
2356
+ validateConditionSetUniqueness(config, fragment, errors);
2357
+ validateCrossAxisRuleUniqueness(config, fragment, errors);
2358
+ return { valid: errors.length === 0, errors };
2359
+ }
2360
+ function validateStateReferences(fragment, errors) {
2361
+ for (const path of fragment.paymentPaths ?? []) {
2362
+ if (!isPaymentState(path.from)) {
2363
+ errors.push({
2364
+ code: "invalid_payment_state",
2365
+ message: `Unknown payment state "${path.from}" in paymentPaths`,
2366
+ path: `paymentPaths[from=${path.from}]`
2367
+ });
2368
+ }
2369
+ if (!isPaymentState(path.to)) {
2370
+ errors.push({
2371
+ code: "invalid_payment_state",
2372
+ message: `Unknown payment state "${path.to}" in paymentPaths`,
2373
+ path: `paymentPaths[to=${path.to}]`
2374
+ });
2375
+ }
2376
+ }
2377
+ for (const path of fragment.fulfillmentPaths ?? []) {
2378
+ if (!isFulfillmentState(path.from)) {
2379
+ errors.push({
2380
+ code: "invalid_fulfillment_state",
2381
+ message: `Unknown fulfillment state "${path.from}" in fulfillmentPaths`,
2382
+ path: `fulfillmentPaths[from=${path.from}]`
2383
+ });
2384
+ }
2385
+ if (!isFulfillmentState(path.to)) {
2386
+ errors.push({
2387
+ code: "invalid_fulfillment_state",
2388
+ message: `Unknown fulfillment state "${path.to}" in fulfillmentPaths`,
2389
+ path: `fulfillmentPaths[to=${path.to}]`
2390
+ });
2391
+ }
2392
+ }
2393
+ for (const rule of fragment.crossAxisRules ?? []) {
2394
+ const triggerStates = Array.isArray(rule.trigger.to) ? rule.trigger.to : [rule.trigger.to];
2395
+ const check = rule.trigger.axis === "payment" ? isPaymentState : isFulfillmentState;
2396
+ for (const s of triggerStates) {
2397
+ if (!check(s)) {
2398
+ errors.push({
2399
+ code: `invalid_${rule.trigger.axis}_state`,
2400
+ message: `Unknown ${rule.trigger.axis} state "${s}" in crossAxisRule "${rule.id}" trigger`,
2401
+ path: `crossAxisRules[${rule.id}].trigger.to`
2402
+ });
2403
+ }
2404
+ }
2405
+ const reqCheck = rule.requires.axis === "payment" ? isPaymentState : isFulfillmentState;
2406
+ for (const s of rule.requires.states) {
2407
+ if (!reqCheck(s)) {
2408
+ errors.push({
2409
+ code: `invalid_${rule.requires.axis}_state`,
2410
+ message: `Unknown ${rule.requires.axis} state "${s}" in crossAxisRule "${rule.id}" requires`,
2411
+ path: `crossAxisRules[${rule.id}].requires.states`
2412
+ });
2413
+ }
2414
+ }
2415
+ }
2416
+ for (const pair of fragment.validInitialStates ?? []) {
2417
+ if (!isPaymentState(pair.payment)) {
2418
+ errors.push({
2419
+ code: "invalid_payment_state",
2420
+ message: `Unknown payment state "${pair.payment}" in validInitialStates`,
2421
+ path: "validInitialStates"
2422
+ });
2423
+ }
2424
+ if (!isFulfillmentState(pair.fulfillment)) {
2425
+ errors.push({
2426
+ code: "invalid_fulfillment_state",
2427
+ message: `Unknown fulfillment state "${pair.fulfillment}" in validInitialStates`,
2428
+ path: "validInitialStates"
2429
+ });
2430
+ }
2431
+ }
2432
+ for (const rule of fragment.displayStateMap ?? []) {
2433
+ const pStates = rule.paymentState ? Array.isArray(rule.paymentState) ? rule.paymentState : [rule.paymentState] : [];
2434
+ for (const s of pStates) {
2435
+ if (!isPaymentState(s)) {
2436
+ errors.push({
2437
+ code: "invalid_payment_state",
2438
+ message: `Unknown payment state "${s}" in displayStateMap rule "${rule.label}"`,
2439
+ path: "displayStateMap"
2440
+ });
2441
+ }
2442
+ }
2443
+ const fStates = rule.fulfillmentState ? Array.isArray(rule.fulfillmentState) ? rule.fulfillmentState : [rule.fulfillmentState] : [];
2444
+ for (const s of fStates) {
2445
+ if (!isFulfillmentState(s)) {
2446
+ errors.push({
2447
+ code: "invalid_fulfillment_state",
2448
+ message: `Unknown fulfillment state "${s}" in displayStateMap rule "${rule.label}"`,
2449
+ path: "displayStateMap"
2450
+ });
2451
+ }
2452
+ }
2453
+ }
2454
+ }
2455
+ function validatePathUniqueness(config, fragment, errors) {
2456
+ const existingPaymentEdges = new Set(
2457
+ config.paymentPaths.map((p) => `${p.from}->${p.to}`)
2458
+ );
2459
+ for (const path of fragment.paymentPaths ?? []) {
2460
+ const edge = `${path.from}->${path.to}`;
2461
+ if (existingPaymentEdges.has(edge)) {
2462
+ errors.push({
2463
+ code: "duplicate_payment_path",
2464
+ message: `Payment path ${path.from} \u2192 ${path.to} already exists in the config`,
2465
+ path: `paymentPaths[${edge}]`
2466
+ });
2467
+ }
2468
+ }
2469
+ const existingFulfillmentEdges = new Set(
2470
+ config.fulfillmentPaths.map((p) => `${p.from}->${p.to}`)
2471
+ );
2472
+ for (const path of fragment.fulfillmentPaths ?? []) {
2473
+ const edge = `${path.from}->${path.to}`;
2474
+ if (existingFulfillmentEdges.has(edge)) {
2475
+ errors.push({
2476
+ code: "duplicate_fulfillment_path",
2477
+ message: `Fulfillment path ${path.from} \u2192 ${path.to} already exists in the config`,
2478
+ path: `fulfillmentPaths[${edge}]`
2479
+ });
2480
+ }
2481
+ }
2482
+ }
2483
+ function validateConditionSetUniqueness(config, fragment, errors) {
2484
+ const existingIds = new Set(config.transitionConditions.map((c) => c.id));
2485
+ for (const cond of fragment.transitionConditions ?? []) {
2486
+ if (existingIds.has(cond.id)) {
2487
+ errors.push({
2488
+ code: "duplicate_condition_set_id",
2489
+ message: `Condition set ID "${cond.id}" already exists in the config`,
2490
+ path: `transitionConditions[${cond.id}]`
2491
+ });
2492
+ }
2493
+ }
2494
+ }
2495
+ function validateCrossAxisRuleUniqueness(config, fragment, errors) {
2496
+ const existingIds = new Set(config.crossAxisRules.map((r) => r.id));
2497
+ for (const rule of fragment.crossAxisRules ?? []) {
2498
+ if (existingIds.has(rule.id)) {
2499
+ errors.push({
2500
+ code: "duplicate_cross_axis_rule_id",
2501
+ message: `Cross-axis rule ID "${rule.id}" already exists in the config`,
2502
+ path: `crossAxisRules[${rule.id}]`
2503
+ });
2504
+ }
2505
+ }
2506
+ }
2507
+
2508
+ // order-state-machine/merge-fragment.ts
2509
+ function displayRuleKey(rule) {
2510
+ const p = rule.paymentState;
2511
+ const f = rule.fulfillmentState;
2512
+ const pKey = p === void 0 ? "*" : Array.isArray(p) ? p.slice().sort().join(",") : p;
2513
+ const fKey = f === void 0 ? "*" : Array.isArray(f) ? f.slice().sort().join(",") : f;
2514
+ return `${pKey}|${fKey}`;
2515
+ }
2516
+ function mergeFragment(config, fragment, extensionId) {
2517
+ const merged = JSON.parse(JSON.stringify(config));
2518
+ for (const path of fragment.paymentPaths ?? []) {
2519
+ merged.paymentPaths.push({ ...path, _sourceExtensionId: extensionId });
2520
+ }
2521
+ for (const path of fragment.fulfillmentPaths ?? []) {
2522
+ merged.fulfillmentPaths.push({ ...path, _sourceExtensionId: extensionId });
2523
+ }
2524
+ for (const rule of fragment.crossAxisRules ?? []) {
2525
+ merged.crossAxisRules.push({ ...rule, _sourceExtensionId: extensionId });
2526
+ }
2527
+ for (const cond of fragment.transitionConditions ?? []) {
2528
+ merged.transitionConditions.push({ ...cond, _sourceExtensionId: extensionId });
2529
+ }
2530
+ for (const pair of fragment.validInitialStates ?? []) {
2531
+ merged.validInitialStates.push(pair);
2532
+ }
2533
+ for (const rule of fragment.displayStateMap ?? []) {
2534
+ const tagged = { ...rule, _sourceExtensionId: extensionId };
2535
+ const key = displayRuleKey(tagged);
2536
+ const existingIdx = merged.displayStateMap.findIndex(
2537
+ (r) => displayRuleKey(r) === key
2538
+ );
2539
+ if (existingIdx !== -1) {
2540
+ merged.displayStateMap[existingIdx] = tagged;
2541
+ } else {
2542
+ merged.displayStateMap.push(tagged);
2543
+ }
2544
+ }
2545
+ return merged;
2546
+ }
2547
+
2548
+ // order-state-machine/remove-fragment.ts
2549
+ function removeFragment(config, extensionId) {
2550
+ const cleaned = JSON.parse(JSON.stringify(config));
2551
+ cleaned.paymentPaths = cleaned.paymentPaths.filter(
2552
+ (p) => p._sourceExtensionId !== extensionId
2553
+ );
2554
+ cleaned.fulfillmentPaths = cleaned.fulfillmentPaths.filter(
2555
+ (p) => p._sourceExtensionId !== extensionId
2556
+ );
2557
+ cleaned.crossAxisRules = cleaned.crossAxisRules.filter(
2558
+ (r) => r._sourceExtensionId !== extensionId
2559
+ );
2560
+ cleaned.transitionConditions = cleaned.transitionConditions.filter(
2561
+ (c) => c._sourceExtensionId !== extensionId
2562
+ );
2563
+ cleaned.displayStateMap = cleaned.displayStateMap.filter(
2564
+ (d) => d._sourceExtensionId !== extensionId
2565
+ );
2566
+ return cleaned;
2567
+ }
2568
+
2569
+ // order-state-machine/actions.ts
2570
+ var ORDER_STATE_ACTIONS = {
2571
+ getOrderStateConfig: "getOrderStateConfig",
2572
+ getAvailableTransitions: "getAvailableTransitions",
2573
+ getOrderDisplayState: "getOrderDisplayState",
2574
+ transitionOrderState: "transitionOrderState",
2575
+ getStateConfigFragment: "getStateConfigFragment",
2576
+ saveStateConfigFragment: "saveStateConfigFragment",
2577
+ deleteStateConfigFragment: "deleteStateConfigFragment"
2578
+ };
2579
+
2580
+ // order-state-machine/pubsub.ts
2581
+ var ORDER_STATE_TOPIC = "order-state";
2582
+ var ORDER_STATE_EVENTS = {
2583
+ stateTransitionCompleted: "state-transition-completed",
2584
+ stateTransitionBlocked: "state-transition-blocked",
2585
+ configUpdated: "config-updated"
2586
+ };
2587
+ // Annotate the CommonJS export names for ESM import in node:
2588
+ 0 && (module.exports = {
2589
+ AttributeType,
2590
+ CONDITION_OPERATORS,
2591
+ COUNTRY_CURRENCIES,
2592
+ CURRENCY_CONFIG,
2593
+ CompanyType,
2594
+ CurrencyCode,
2595
+ CustomTableAvailability,
2596
+ CustomerPlatform,
2597
+ DEFAULT_CONFIG,
2598
+ DEFAULT_CROSS_AXIS_RULES,
2599
+ DEFAULT_DISPLAY_STATE_MAP,
2600
+ DEFAULT_RESOLVED_CONFIG,
2601
+ EUFixedRates,
2602
+ EUROPE,
2603
+ ExtensionCategory,
2604
+ FINANCIAL_INVARIANTS,
2605
+ FULFILLMENT_STATES,
2606
+ FeesCustomBillingStatus,
2607
+ InventoryBaseActionEnum,
2608
+ InventorySpecificActionType,
2609
+ InvoiceStatus,
2610
+ LibraryItemType,
2611
+ MenuProject,
2612
+ NAFixedRates,
2613
+ NORTH_AMERICA,
2614
+ NonRevenueItemType,
2615
+ ORDER_STATE_ACTIONS,
2616
+ ORDER_STATE_EVENTS,
2617
+ ORDER_STATE_TOPIC,
2618
+ OrderPlatform,
2619
+ OtherFixedRates,
2620
+ OwnerType,
2621
+ PATH_MODES,
2622
+ PAYMENT_STATES,
2623
+ POS_CROSS_AXIS_RULES,
2624
+ POS_VALID_INITIAL_STATES,
2625
+ PaymentMethod,
2626
+ Platform,
2627
+ PreviewImageMode,
2628
+ PricingLevel,
2629
+ PricingPlanEnum,
2630
+ PricingRegionEnum,
2631
+ ProductStatus,
2632
+ ProductType,
2633
+ PublicationAvailability,
2634
+ PublicationStatus,
2635
+ REGION_MAPPING,
2636
+ REPORT_NEGATE_PATHS,
2637
+ ReceiptSendChannel,
2638
+ ReceiptType,
2639
+ ResidualPaymentMethod,
2640
+ ResidualStatus,
2641
+ STATE_SCHEMA,
2642
+ STRIPE_SUPPORTED_COUNTRIES,
2643
+ StationStatus,
2644
+ StripeCurrencyCode,
2645
+ StripeStatus,
2646
+ TimePeriod,
2647
+ TopMetericsSort,
2648
+ UserTypes,
2649
+ addAmounts,
2650
+ amountToString,
2651
+ baseFulfillmentDefinitions,
2652
+ basePaymentDefinitions,
2653
+ buildOrderContext,
2654
+ buildPosPresetConfig,
2655
+ buildResolvedConfig,
2656
+ calculatePercentage,
2657
+ canTransition,
2658
+ conditionSummary,
2659
+ convertFixedFeeToLocalCurrency,
2660
+ createAmount,
2661
+ crossAxisRuleApplies,
2662
+ deriveDisplayState,
2663
+ displayRuleMatchesPair,
2664
+ divideAmount,
2665
+ evaluateCondition,
2666
+ evaluateConditionSet,
2667
+ formatCurrency,
2668
+ formatMinorUnitsToString,
2669
+ fromMinorUnits,
2670
+ generateMongoID,
2671
+ getAvailableTransitions,
2672
+ getCountriesByRegion,
2673
+ getCurrencyConfig,
2674
+ getCurrentISODate,
2675
+ getFinancialInvariantViolations,
2676
+ getMinorUnitMultiplier,
2677
+ getMinorUnits,
2678
+ getPricingRegionFromCountry,
2679
+ inferStatesFromLegacyStatus,
2680
+ isConditionOperator,
2681
+ isFulfillmentState,
2682
+ isPaymentState,
2683
+ isSupportedCurrency,
2684
+ mapToLegacyStatus,
2685
+ mergeFragment,
2686
+ multiplyAmount,
2687
+ normalizeMongoIdString,
2688
+ parseAmountToMinorUnits,
2689
+ parseCurrencyCode,
2690
+ parseStripeCurrencyCode,
2691
+ removeFragment,
2692
+ resolveTemplate,
2693
+ setOrderState,
2694
+ signReportForDisplay,
2695
+ stringifyMinorUnits,
2696
+ subtractAmounts,
2697
+ toMinorUnits,
2698
+ validateConfig,
2699
+ validateFragmentCompatibility,
2700
+ violatesFinancialInvariant
2701
+ });
2702
+ //# sourceMappingURL=index.js.map