@final-commerce/common 2.12.1-preprod.1 → 2.13.0-staging2.1

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 CHANGED
@@ -40,8 +40,6 @@ __export(index_exports, {
40
40
  CONDITION_OPERATORS: () => CONDITION_OPERATORS,
41
41
  COUNTRY_CURRENCIES: () => COUNTRY_CURRENCIES,
42
42
  CURRENCY_CONFIG: () => CURRENCY_CONFIG,
43
- CUSTOMER_CONTACT_VERIFIED: () => CUSTOMER_CONTACT_VERIFIED,
44
- CUSTOMER_EMAIL_TAKEN: () => CUSTOMER_EMAIL_TAKEN,
45
43
  CompanyType: () => CompanyType,
46
44
  CurrencyCode: () => CurrencyCode,
47
45
  CustomTableAvailability: () => CustomTableAvailability,
@@ -51,7 +49,6 @@ __export(index_exports, {
51
49
  DEFAULT_DISPLAY_STATE_MAP: () => DEFAULT_DISPLAY_STATE_MAP,
52
50
  DEFAULT_HOLD_MINUTES: () => DEFAULT_HOLD_MINUTES,
53
51
  DEFAULT_RESOLVED_CONFIG: () => DEFAULT_RESOLVED_CONFIG,
54
- DEFAULT_SHELL_SETTINGS: () => DEFAULT_SHELL_SETTINGS,
55
52
  DEFAULT_UNIT_ID: () => DEFAULT_UNIT_ID,
56
53
  DualWriteStrategy: () => DualWriteStrategy,
57
54
  EUFixedRates: () => EUFixedRates,
@@ -80,7 +77,6 @@ __export(index_exports, {
80
77
  ORDER_STATE_TOPIC: () => ORDER_STATE_TOPIC,
81
78
  OrderPlatform: () => OrderPlatform,
82
79
  OtherFixedRates: () => OtherFixedRates,
83
- OutOfProvinceTaxes: () => OutOfProvinceTaxes,
84
80
  OwnerType: () => OwnerType,
85
81
  PATH_MODES: () => PATH_MODES,
86
82
  PAYMENT_CHANNELS: () => PAYMENT_CHANNELS,
@@ -108,18 +104,7 @@ __export(index_exports, {
108
104
  ResidualPaymentMethod: () => ResidualPaymentMethod,
109
105
  ResidualStatus: () => ResidualStatus,
110
106
  ResourceAvailabilityState: () => ResourceAvailabilityState,
111
- SHELL_FLOW_SETTINGS_PREFIX: () => SHELL_FLOW_SETTINGS_PREFIX,
112
- SHELL_FLOW_TIPS_KEY: () => SHELL_FLOW_TIPS_KEY,
113
- SHELL_TIP_LABEL_MAX_LENGTH: () => SHELL_TIP_LABEL_MAX_LENGTH,
114
- SHELL_TIP_PERCENT_MAX: () => SHELL_TIP_PERCENT_MAX,
115
- SHELL_TIP_PERCENT_MIN: () => SHELL_TIP_PERCENT_MIN,
116
107
  SHIPPING_COUNTRIES: () => SHIPPING_COUNTRIES,
117
- SHOPPER_CONSENT_SOURCES: () => SHOPPER_CONSENT_SOURCES,
118
- SHOPPER_ERROR_CODES: () => SHOPPER_ERROR_CODES,
119
- SHOPPER_RETURN_DECLINE_REASON_MAX: () => SHOPPER_RETURN_DECLINE_REASON_MAX,
120
- SHOPPER_RETURN_METHODS: () => SHOPPER_RETURN_METHODS,
121
- SHOPPER_RETURN_STATUSES: () => SHOPPER_RETURN_STATUSES,
122
- STANDARD_TAX_TYPE: () => STANDARD_TAX_TYPE,
123
108
  STATE_SCHEMA: () => STATE_SCHEMA,
124
109
  STRIPE_SUPPORTED_COUNTRIES: () => STRIPE_SUPPORTED_COUNTRIES,
125
110
  SYSTEM_FAMILIES: () => SYSTEM_FAMILIES,
@@ -137,11 +122,6 @@ __export(index_exports, {
137
122
  StationStatus: () => StationStatus,
138
123
  StripeCurrencyCode: () => StripeCurrencyCode,
139
124
  StripeStatus: () => StripeStatus,
140
- TAX_EXCEPTION_REASON_MAX: () => TAX_EXCEPTION_REASON_MAX,
141
- TaxExceptionSource: () => TaxExceptionSource,
142
- TaxRegistrationKind: () => TaxRegistrationKind,
143
- TaxSource: () => TaxSource,
144
- TaxWarningCode: () => TaxWarningCode,
145
125
  TimePeriod: () => TimePeriod,
146
126
  TopMetericsSort: () => TopMetericsSort,
147
127
  UserTypes: () => UserTypes,
@@ -156,13 +136,14 @@ __export(index_exports, {
156
136
  ancestorChain: () => ancestorChain,
157
137
  applyAssignment: () => applyAssignment,
158
138
  assertUnitSane: () => assertUnitSane,
159
- automaticTaxTableVersion: () => automaticTaxTableVersion,
139
+ attachResolvedUnits: () => attachResolvedUnits,
160
140
  availableIn: () => availableIn,
141
+ bankersRoundDiv: () => bankersRoundDiv,
161
142
  baseFor: () => baseFor,
162
143
  baseFulfillmentDefinitions: () => baseFulfillmentDefinitions,
163
144
  baseOf: () => baseOf,
164
145
  basePaymentDefinitions: () => basePaymentDefinitions,
165
- buildAutomaticTaxTable: () => buildAutomaticTaxTable,
146
+ bookCostPerUnit: () => bookCostPerUnit,
166
147
  buildAvailability: () => buildAvailability,
167
148
  buildGrid: () => buildGrid,
168
149
  buildOrderContext: () => buildOrderContext,
@@ -170,9 +151,11 @@ __export(index_exports, {
170
151
  buildResolvedConfig: () => buildResolvedConfig,
171
152
  calculatePercentage: () => calculatePercentage,
172
153
  canTransition: () => canTransition,
173
- cardFromProcessorData: () => cardFromProcessorData,
174
154
  cheapestCompositeItem: () => cheapestCompositeItem,
175
155
  cheapestCompositePrice: () => cheapestCompositePrice,
156
+ componentUnitsPerLine: () => componentUnitsPerLine,
157
+ compositeCostOfKnown: () => compositeCostOfKnown,
158
+ compositeCostRange: () => compositeCostRange,
176
159
  compositeItemCost: () => compositeItemCost,
177
160
  compositeItemUnavailable: () => compositeItemUnavailable,
178
161
  compositeMakeable: () => compositeMakeable,
@@ -181,6 +164,7 @@ __export(index_exports, {
181
164
  compositeVariantInStock: () => compositeVariantInStock,
182
165
  conditionSummary: () => conditionSummary,
183
166
  convertFixedFeeToLocalCurrency: () => convertFixedFeeToLocalCurrency,
167
+ costPriceChangeStamp: () => costPriceChangeStamp,
184
168
  createAmount: () => createAmount,
185
169
  crossAxisRuleApplies: () => crossAxisRuleApplies,
186
170
  currentAssignees: () => currentAssignees,
@@ -189,17 +173,14 @@ __export(index_exports, {
189
173
  deriveUnitId: () => deriveUnitId,
190
174
  displayRuleMatchesPair: () => displayRuleMatchesPair,
191
175
  divideAmount: () => divideAmount,
192
- emailKey: () => emailKey,
193
176
  evaluateCondition: () => evaluateCondition,
194
177
  evaluateConditionSet: () => evaluateConditionSet,
195
178
  extendPrice: () => extendPrice,
196
179
  extendPriceFor: () => extendPriceFor,
197
- flowSettingsFromShellSettings: () => flowSettingsFromShellSettings,
198
180
  formatCurrency: () => formatCurrency,
199
181
  formatInUnit: () => formatInUnit,
200
182
  formatMinorUnitsToString: () => formatMinorUnitsToString,
201
183
  formatQuantity: () => formatQuantity,
202
- formatShippingDuration: () => formatShippingDuration,
203
184
  fromBase: () => fromBase,
204
185
  fromMinorUnits: () => fromMinorUnits,
205
186
  generateMongoID: () => generateMongoID,
@@ -221,6 +202,7 @@ __export(index_exports, {
221
202
  hasSellableChoice: () => hasSellableChoice,
222
203
  holdExpiresAt: () => holdExpiresAt,
223
204
  inferStatesFromLegacyStatus: () => inferStatesFromLegacyStatus,
205
+ innerCompositeOption: () => innerCompositeOption,
224
206
  isAdyenRolloutCountry: () => isAdyenRolloutCountry,
225
207
  isAffirmCountry: () => isAffirmCountry,
226
208
  isAffirmPricePlan: () => isAffirmPricePlan,
@@ -228,17 +210,19 @@ __export(index_exports, {
228
210
  isConditionOperator: () => isConditionOperator,
229
211
  isFulfillmentState: () => isFulfillmentState,
230
212
  isInCart: () => isInCart,
213
+ isInnerComposite: () => isInnerComposite,
231
214
  isPaymentState: () => isPaymentState,
232
- isShellTipPercent: () => isShellTipPercent,
233
215
  isSupportedCurrency: () => isSupportedCurrency,
234
216
  isSystemFamilyCode: () => isSystemFamilyCode,
235
217
  isValidQuantity: () => isValidQuantity,
236
218
  isWhole: () => isWhole,
219
+ landedCostPerUnit: () => landedCostPerUnit,
237
220
  lineStockMoves: () => lineStockMoves,
238
221
  listCountries: () => listCountries,
239
222
  listProvinces: () => listProvinces,
240
223
  listShippingCountries: () => listShippingCountries,
241
224
  mapToLegacyStatus: () => mapToLegacyStatus,
225
+ marginPercentOf: () => marginPercentOf,
242
226
  maxPrecisionFor: () => maxPrecisionFor,
243
227
  mergeFragment: () => mergeFragment,
244
228
  modifiersSellable: () => modifiersSellable,
@@ -249,13 +233,11 @@ __export(index_exports, {
249
233
  normalizeMongoIdString: () => normalizeMongoIdString,
250
234
  normalizePostCode: () => normalizePostCode,
251
235
  normalizeProvince: () => normalizeProvince,
252
- normalizeShopperEmail: () => normalizeShopperEmail,
253
236
  occupancyIn: () => occupancyIn,
254
237
  orderAssignments: () => orderAssignments,
255
238
  parseAmountToMinorUnits: () => parseAmountToMinorUnits,
256
239
  parseCurrencyCode: () => parseCurrencyCode,
257
240
  parseStripeCurrencyCode: () => parseStripeCurrencyCode,
258
- phoneKey: () => phoneKey,
259
241
  placeKey: () => placeKey,
260
242
  planWindow: () => planWindow,
261
243
  poolDemand: () => poolDemand,
@@ -266,29 +248,19 @@ __export(index_exports, {
266
248
  presentAt: () => presentAt,
267
249
  priceForTotal: () => priceForTotal,
268
250
  provincesForPostCode: () => provincesForPostCode,
269
- readShellTipSettings: () => readShellTipSettings,
270
- registrationPlacesByKind: () => registrationPlacesByKind,
271
251
  removeFragment: () => removeFragment,
272
252
  resolveFamily: () => resolveFamily,
273
253
  resolveModifiersForProduct: () => resolveModifiersForProduct,
274
- resolveShellSettings: () => resolveShellSettings,
275
- resolveShellSettingsWithSources: () => resolveShellSettingsWithSources,
276
254
  resolveShipping: () => resolveShipping,
277
255
  resolveTemplate: () => resolveTemplate,
278
256
  resolveUnit: () => resolveUnit,
279
257
  roundToPrecision: () => roundToPrecision,
280
258
  sameFamily: () => sameFamily,
281
259
  setOrderState: () => setOrderState,
282
- sha1Hex: () => sha1Hex,
283
- shellSettingsFromCompanyTips: () => shellSettingsFromCompanyTips,
284
- shellSettingsFromFlowSettings: () => shellSettingsFromFlowSettings,
285
- shellSettingsProblems: () => shellSettingsProblems,
286
- shellTipSettingsProblems: () => shellTipSettingsProblems,
287
- shippingDuration: () => shippingDuration,
260
+ shelfComponents: () => shelfComponents,
288
261
  shipsToCountry: () => shipsToCountry,
289
262
  shopDayKey: () => shopDayKey,
290
263
  shopDayRange: () => shopDayRange,
291
- shopperPaymentsOf: () => shopperPaymentsOf,
292
264
  signReportForDisplay: () => signReportForDisplay,
293
265
  slotsForWindow: () => slotsForWindow,
294
266
  stringifyMinorUnits: () => stringifyMinorUnits,
@@ -299,7 +271,9 @@ __export(index_exports, {
299
271
  validateFragmentCompatibility: () => validateFragmentCompatibility,
300
272
  validateOrderStatuses: () => validateOrderStatuses,
301
273
  validateShippingZone: () => validateShippingZone,
302
- verifiedContactChange: () => verifiedContactChange,
274
+ variantCostAtSale: () => variantCostAtSale,
275
+ variantDisplayName: () => variantDisplayName,
276
+ variantLabel: () => variantLabel,
303
277
  violatesFinancialInvariant: () => violatesFinancialInvariant,
304
278
  windowEndsAt: () => windowEndsAt,
305
279
  withinPresence: () => withinPresence
@@ -849,30 +823,6 @@ var ShippingZoneError = /* @__PURE__ */ ((ShippingZoneError2) => {
849
823
  return ShippingZoneError2;
850
824
  })(ShippingZoneError || {});
851
825
 
852
- // enums/tax.enum.ts
853
- var TaxRegistrationKind = /* @__PURE__ */ ((TaxRegistrationKind2) => {
854
- TaxRegistrationKind2["GST_HST"] = "GST_HST";
855
- TaxRegistrationKind2["PST"] = "PST";
856
- TaxRegistrationKind2["QST"] = "QST";
857
- return TaxRegistrationKind2;
858
- })(TaxRegistrationKind || {});
859
- var TaxSource = /* @__PURE__ */ ((TaxSource2) => {
860
- TaxSource2["MERCHANT"] = "merchant";
861
- TaxSource2["AUTOMATIC"] = "automatic";
862
- return TaxSource2;
863
- })(TaxSource || {});
864
- var OutOfProvinceTaxes = /* @__PURE__ */ ((OutOfProvinceTaxes2) => {
865
- OutOfProvinceTaxes2["AUTOMATIC"] = "automatic";
866
- OutOfProvinceTaxes2["HOME"] = "home";
867
- return OutOfProvinceTaxes2;
868
- })(OutOfProvinceTaxes || {});
869
- var TaxWarningCode = /* @__PURE__ */ ((TaxWarningCode2) => {
870
- TaxWarningCode2["NOT_REGISTERED"] = "NOT_REGISTERED";
871
- TaxWarningCode2["NO_RULES_FOR_PLACE"] = "NO_RULES_FOR_PLACE";
872
- TaxWarningCode2["NO_TABLE"] = "NO_TABLE";
873
- return TaxWarningCode2;
874
- })(TaxWarningCode || {});
875
-
876
826
  // enums/sales-line.enum.ts
877
827
  var SalesLineAction = /* @__PURE__ */ ((SalesLineAction2) => {
878
828
  SalesLineAction2["SALE"] = "sale";
@@ -1351,6 +1301,16 @@ function resolveUnit(unitId, companyUnits = []) {
1351
1301
  if (!unit2) throw new Error(`Unknown measurement unit: ${unitId}`);
1352
1302
  return unit2;
1353
1303
  }
1304
+ function attachResolvedUnits(variants, companyUnits, logLabel = "attachUnits") {
1305
+ for (const variant of variants)
1306
+ if (variant.unitId)
1307
+ try {
1308
+ variant.unit = resolveUnit(variant.unitId, companyUnits);
1309
+ } catch (error) {
1310
+ console.error(`[${logLabel}] unit ${variant.unitId} does not resolve. ${error.message}`);
1311
+ }
1312
+ return variants;
1313
+ }
1354
1314
  function resolveFamily(familyId, companyFamilies = []) {
1355
1315
  const family = SYSTEM_FAMILIES.find((f) => f.familyId === familyId) ?? companyFamilies.find((f) => f.familyId === familyId);
1356
1316
  if (!family) throw new Error(`Unknown measurement unit family: ${familyId}`);
@@ -1891,6 +1851,66 @@ function hasSellableChoice(modifier, outletId) {
1891
1851
  }
1892
1852
  var modifiersSellable = (modifiers, outletId) => modifiers.every((modifier) => !modifier.required || hasSellableChoice(modifier, outletId));
1893
1853
 
1854
+ // utils/line-stock-moves.util.ts
1855
+ function lineStockMoves(item, quantity, reservations = []) {
1856
+ const sign = Math.sign(quantity);
1857
+ const pool = (stockVariantId) => stockVariantId ? { stockVariantId: stockVariantId.toString() } : {};
1858
+ if (!item.components?.length)
1859
+ return [
1860
+ {
1861
+ productId: item.productId.toString(),
1862
+ variantId: item.variantId.toString(),
1863
+ fields: {
1864
+ quantity,
1865
+ ...item.stockQuantity != null ? { stockQuantity: sign * item.stockQuantity, unitId: item.unitId?.toString() } : {},
1866
+ ...pool(item.stockVariantId)
1867
+ }
1868
+ }
1869
+ ];
1870
+ const booked = new Set(
1871
+ reservations.filter((reservation) => reservation.lineItemInternalId && reservation.lineItemInternalId === item.internalId).map((reservation) => reservation.componentIndex)
1872
+ );
1873
+ return shelfComponents(item.components).flatMap(({ component, componentIndex, parentUnits }) => {
1874
+ if (booked.has(componentIndex)) return [];
1875
+ if (component.unitId && component.stockQuantity == null)
1876
+ throw new Error(
1877
+ `Composite ${item.productId?.toString()} component ${component.variantId.toString()} is sold in ${component.unitId.toString()} but carries no stockQuantity`
1878
+ );
1879
+ return [
1880
+ {
1881
+ productId: component.productId.toString(),
1882
+ variantId: component.variantId.toString(),
1883
+ componentIndex,
1884
+ fields: {
1885
+ quantity: component.quantity * parentUnits * quantity,
1886
+ ...component.stockQuantity != null ? { stockQuantity: component.stockQuantity * parentUnits * quantity, unitId: component.unitId?.toString() } : {},
1887
+ ...pool(component.stockVariantId),
1888
+ ...item.productId ? { compositeProductId: item.productId.toString() } : {},
1889
+ ...item.name ? { compositeName: item.name } : {}
1890
+ }
1891
+ }
1892
+ ];
1893
+ });
1894
+ }
1895
+ function componentUnitsPerLine(components, index) {
1896
+ const component = components[index];
1897
+ if (!component) throw new Error(`No component ${index} on the line`);
1898
+ if (component.parentIndex == null) return component.quantity;
1899
+ if (component.parentIndex >= index)
1900
+ throw new Error(`Component ${index} points to parent ${component.parentIndex}, which is not before it`);
1901
+ return component.quantity * componentUnitsPerLine(components, component.parentIndex);
1902
+ }
1903
+ var isInnerComposite = (components, index) => components.some((child) => child.parentIndex === index);
1904
+ var shelfComponents = (components) => components.flatMap(
1905
+ (component, componentIndex) => isInnerComposite(components, componentIndex) ? [] : [
1906
+ {
1907
+ component,
1908
+ componentIndex,
1909
+ parentUnits: component.parentIndex == null ? 1 : componentUnitsPerLine(components, component.parentIndex)
1910
+ }
1911
+ ]
1912
+ );
1913
+
1894
1914
  // utils/composite-availability.util.ts
1895
1915
  function poolStockAt(rows, outletId) {
1896
1916
  if (!rows.some((row) => row.manageStock === true)) return null;
@@ -2029,7 +2049,9 @@ function poolDemand(lines) {
2029
2049
  (demand.get(poolOf(line)) ?? 0) + (line.unit ? toBase(line.quantity * times, line.unit) : line.quantity * times)
2030
2050
  );
2031
2051
  for (const line of lines) {
2032
- if (line.components) for (const component of line.components) add(component, line.quantity);
2052
+ if (line.components)
2053
+ for (const { component, parentUnits } of shelfComponents(line.components))
2054
+ add(component, line.quantity * parentUnits);
2033
2055
  else add(line, 1);
2034
2056
  }
2035
2057
  return demand;
@@ -2071,224 +2093,76 @@ function compositeReservationMismatches(order) {
2071
2093
  });
2072
2094
  }
2073
2095
 
2074
- // utils/line-stock-moves.util.ts
2075
- function lineStockMoves(item, quantity, reservations = []) {
2076
- const sign = Math.sign(quantity);
2077
- const pool = (stockVariantId) => stockVariantId ? { stockVariantId: stockVariantId.toString() } : {};
2078
- if (!item.components?.length)
2079
- return [
2080
- {
2081
- productId: item.productId.toString(),
2082
- variantId: item.variantId.toString(),
2083
- fields: {
2084
- quantity,
2085
- ...item.stockQuantity != null ? { stockQuantity: sign * item.stockQuantity, unitId: item.unitId?.toString() } : {},
2086
- ...pool(item.stockVariantId)
2087
- }
2088
- }
2089
- ];
2090
- const booked = new Set(
2091
- reservations.filter((reservation) => reservation.lineItemInternalId && reservation.lineItemInternalId === item.internalId).map((reservation) => reservation.componentIndex)
2092
- );
2093
- return item.components.flatMap((component, componentIndex) => {
2094
- if (booked.has(componentIndex)) return [];
2095
- if (component.unitId && component.stockQuantity == null)
2096
- throw new Error(
2097
- `Composite ${item.productId?.toString()} component ${component.variantId.toString()} is sold in ${component.unitId.toString()} but carries no stockQuantity`
2098
- );
2099
- return [
2100
- {
2101
- productId: component.productId.toString(),
2102
- variantId: component.variantId.toString(),
2103
- componentIndex,
2104
- fields: {
2105
- quantity: component.quantity * quantity,
2106
- ...component.stockQuantity != null ? { stockQuantity: component.stockQuantity * quantity, unitId: component.unitId?.toString() } : {},
2107
- ...pool(component.stockVariantId),
2108
- ...item.productId ? { compositeProductId: item.productId.toString() } : {},
2109
- ...item.name ? { compositeName: item.name } : {}
2110
- }
2111
- }
2112
- ];
2096
+ // utils/variant-cost.util.ts
2097
+ function variantCostAtSale({
2098
+ costPrice,
2099
+ costPriceUpdatedAt,
2100
+ landedCost,
2101
+ lastReceivedAt
2102
+ }) {
2103
+ if (landedCost == null) return costPrice ?? null;
2104
+ if (costPrice == null) return landedCost;
2105
+ if (!costPriceUpdatedAt || !lastReceivedAt) return costPrice;
2106
+ return new Date(lastReceivedAt).getTime() > new Date(costPriceUpdatedAt).getTime() ? landedCost : costPrice;
2107
+ }
2108
+ function compositeCostOfKnown(items) {
2109
+ const known = items.filter((item) => item.cost !== null);
2110
+ if (!known.length) return null;
2111
+ return known.reduce((sum, { cost, quantity }) => sum + extendPrice(cost, quantity), 0);
2112
+ }
2113
+ function compositeCostRange(parts) {
2114
+ const missing = new Set(parts.flatMap((part) => part.options.flatMap((option) => option.missing)));
2115
+ const [low, high] = [pickedEnd(parts, "low"), pickedEnd(parts, "high")];
2116
+ const [lowCost, highCost] = [low.length ? compositeCostOfKnown(low) : 0, compositeCostOfKnown(high)];
2117
+ return { range: lowCost === null || highCost === null ? null : [lowCost, highCost], missing: [...missing] };
2118
+ }
2119
+ function innerCompositeOption(name, quantity, cost) {
2120
+ const [low, high] = cost.range ?? [null, null];
2121
+ return { name, quantity, low, high, missing: cost.range === null && !cost.missing.length ? [name] : cost.missing };
2122
+ }
2123
+ function variantLabel(variant, variantCount) {
2124
+ if (variantCount === 1) return "";
2125
+ const attributes = (variant.attributes ?? []).map((attribute) => attribute.value ?? attribute.values?.[0] ?? "");
2126
+ return attributes.filter(Boolean).join(" / ") || variant.name || variant.sku || "";
2127
+ }
2128
+ function variantDisplayName(productName, variant, variantCount) {
2129
+ const label = variantLabel(variant, variantCount);
2130
+ return label ? `${productName} \xB7 ${label}` : productName;
2131
+ }
2132
+ function pickedEnd(parts, end) {
2133
+ return parts.flatMap((part) => {
2134
+ if (!part.options.length) return [];
2135
+ const byCost = part.options.flatMap(({ quantity, [end]: cost }) => cost === null ? [] : [{ cost, quantity }]).sort((a, b) => extendPrice(a.cost, a.quantity) - extendPrice(b.cost, b.quantity));
2136
+ const pick = (end === "low" ? byCost[0] : byCost[byCost.length - 1]) ?? { cost: null, quantity: 1 };
2137
+ return Array(end === "low" ? part.minPicks : part.maxPicks).fill(pick);
2113
2138
  });
2114
2139
  }
2115
-
2116
- // utils/shell-settings.util.ts
2117
- var DEFAULT_SHELL_SETTINGS = {
2118
- pinSwitchUser: false,
2119
- pinSession: false,
2120
- stationLock: 0,
2121
- buildTimeout: 0,
2122
- lockedAccess: false,
2123
- cashManagement: true,
2124
- tips: {
2125
- enabled: true,
2126
- tip1: { label: "Good", value: 15 },
2127
- tip2: { label: "Great", value: 18 },
2128
- tip3: { label: "Amazing!", value: 25 },
2129
- customTipLabel: "Custom",
2130
- noTipLabel: "No tip"
2131
- }
2132
- };
2133
- var FIELD_ORDER = ["station"];
2134
- var TIP_ORDER = ["station", "outlet", "flow", "company"];
2135
- var TOP_FIELDS = [
2136
- "pinSwitchUser",
2137
- "pinSession",
2138
- "stationLock",
2139
- "buildTimeout",
2140
- "lockedAccess",
2141
- "cashManagement"
2142
- ];
2143
- var TIP_FIELDS = ["enabled", "tip1", "tip2", "tip3", "customTipLabel", "noTipLabel"];
2144
- function pick(levels, order, read, fallback) {
2145
- for (const level of order) {
2146
- const settings = levels[level];
2147
- if (!settings) continue;
2148
- const value = read(settings);
2149
- if (value !== void 0 && value !== null) return { value, source: level };
2150
- }
2151
- return { value: fallback, source: "default" };
2152
- }
2153
- function resolveShellSettingsWithSources(levels) {
2154
- const settings = { ...DEFAULT_SHELL_SETTINGS, tips: { ...DEFAULT_SHELL_SETTINGS.tips } };
2155
- const sources = { fields: {}, tips: {} };
2156
- for (const field of TOP_FIELDS) {
2157
- const { value, source } = pick(levels, FIELD_ORDER, (s) => s[field], DEFAULT_SHELL_SETTINGS[field]);
2158
- settings[field] = value;
2159
- sources.fields[field] = source;
2160
- }
2161
- for (const field of TIP_FIELDS) {
2162
- const { value, source } = pick(levels, TIP_ORDER, (s) => s.tips?.[field], DEFAULT_SHELL_SETTINGS.tips[field]);
2163
- settings.tips[field] = value;
2164
- sources.tips[field] = source;
2165
- }
2166
- return { settings, sources };
2167
- }
2168
- function resolveShellSettings(levels) {
2169
- return resolveShellSettingsWithSources(levels).settings;
2170
- }
2171
- var SHELL_TIP_PERCENT_MIN = 1;
2172
- var SHELL_TIP_PERCENT_MAX = 100;
2173
- var SHELL_TIP_LABEL_MAX_LENGTH = 20;
2174
- var isLabel = (raw) => typeof raw === "string" && raw.trim().length > 0 && raw.length <= SHELL_TIP_LABEL_MAX_LENGTH;
2175
- var isShellTipPercent = (raw) => typeof raw === "number" && Number.isInteger(raw) && raw >= SHELL_TIP_PERCENT_MIN && raw <= SHELL_TIP_PERCENT_MAX;
2176
- function shellTipSettingsProblems(tips) {
2177
- if (!tips) return [];
2178
- const problems = [];
2179
- if (tips.enabled !== void 0 && typeof tips.enabled !== "boolean") {
2180
- problems.push({ field: "tips.enabled", code: "boolean" });
2181
- }
2182
- for (const key of ["tip1", "tip2", "tip3"]) {
2183
- const option = tips[key];
2184
- if (option === void 0) continue;
2185
- if (!option || typeof option !== "object") {
2186
- problems.push({ field: `tips.${key}`, code: "preset" });
2187
- continue;
2188
- }
2189
- if (!isShellTipPercent(option.value)) problems.push({ field: `tips.${key}`, code: "percent" });
2190
- if (!isLabel(option.label)) problems.push({ field: `tips.${key}`, code: "label" });
2191
- }
2192
- for (const key of ["customTipLabel", "noTipLabel"]) {
2193
- if (tips[key] !== void 0 && !isLabel(tips[key])) problems.push({ field: `tips.${key}`, code: "label" });
2194
- }
2195
- return problems;
2196
- }
2197
- function shellSettingsProblems(settings) {
2198
- if (!settings) return [];
2199
- const problems = [];
2200
- for (const field of ["pinSwitchUser", "pinSession", "lockedAccess", "cashManagement"]) {
2201
- if (settings[field] !== void 0 && typeof settings[field] !== "boolean")
2202
- problems.push({ field, code: "boolean" });
2203
- }
2204
- for (const field of ["stationLock", "buildTimeout"]) {
2205
- const value = settings[field];
2206
- if (value !== void 0 && !(typeof value === "number" && Number.isInteger(value) && value >= 0)) {
2207
- problems.push({ field, code: "timeout" });
2208
- }
2209
- }
2210
- return [...problems, ...shellTipSettingsProblems(settings.tips)];
2211
- }
2212
- var SHELL_FLOW_SETTINGS_PREFIX = "flowSettingsKey";
2213
- var SHELL_FLOW_TIPS_KEY = `${SHELL_FLOW_SETTINGS_PREFIX}.tips`;
2214
- var readBoolean = (raw) => {
2215
- if (raw === void 0 || raw === "") return void 0;
2216
- const v = raw.trim().toLowerCase();
2217
- if (v === "true") return true;
2218
- if (v === "false") return false;
2219
- return void 0;
2220
- };
2221
- function readTipOption(raw) {
2222
- if (!raw || typeof raw !== "object") return void 0;
2223
- const { label, value } = raw;
2224
- const n = typeof value === "number" ? value : parseFloat(String(value ?? ""));
2225
- if (typeof label !== "string" || !Number.isFinite(n) || n < 0) return void 0;
2226
- return { label, value: n };
2227
- }
2228
- function readShellTipSettings(raw) {
2229
- if (!raw || typeof raw !== "object") return void 0;
2230
- const r = raw;
2231
- const tips = {};
2232
- if (typeof r.enabled === "boolean") tips.enabled = r.enabled;
2233
- const tip1 = readTipOption(r.tip1);
2234
- const tip2 = readTipOption(r.tip2);
2235
- const tip3 = readTipOption(r.tip3);
2236
- if (tip1) tips.tip1 = tip1;
2237
- if (tip2) tips.tip2 = tip2;
2238
- if (tip3) tips.tip3 = tip3;
2239
- if (typeof r.customTipLabel === "string") tips.customTipLabel = r.customTipLabel;
2240
- if (typeof r.noTipLabel === "string") tips.noTipLabel = r.noTipLabel;
2241
- return Object.keys(tips).length > 0 ? tips : void 0;
2242
- }
2243
- var parseJson = (raw) => {
2244
- if (!raw) return void 0;
2245
- try {
2246
- return JSON.parse(raw);
2247
- } catch {
2248
- return void 0;
2140
+ function costPriceChangeStamp(next, stored) {
2141
+ if (next === void 0 || next === (stored ?? null)) return {};
2142
+ return { costPriceUpdatedAt: /* @__PURE__ */ new Date() };
2143
+ }
2144
+ function bankersRoundDiv(numerator, denominator) {
2145
+ if (denominator === 0n) return 0n;
2146
+ const negative = numerator < 0n !== denominator < 0n;
2147
+ const n = numerator < 0n ? -numerator : numerator;
2148
+ const d = denominator < 0n ? -denominator : denominator;
2149
+ const quotient = n / d;
2150
+ const twiceRemainder = n % d * 2n;
2151
+ let result;
2152
+ if (twiceRemainder < d) {
2153
+ result = quotient;
2154
+ } else if (twiceRemainder > d) {
2155
+ result = quotient + 1n;
2156
+ } else {
2157
+ result = quotient % 2n === 0n ? quotient : quotient + 1n;
2249
2158
  }
2250
- };
2251
- function shellSettingsFromFlowSettings(dict) {
2252
- const tips = readShellTipSettings(parseJson(dict?.[SHELL_FLOW_TIPS_KEY]));
2253
- return tips ? { tips } : {};
2254
- }
2255
- function flowSettingsFromShellSettings(settings) {
2256
- return settings.tips && Object.keys(settings.tips).length > 0 ? { [SHELL_FLOW_TIPS_KEY]: JSON.stringify(settings.tips) } : {};
2159
+ return negative ? -result : result;
2257
2160
  }
2258
- function shellSettingsFromCompanyTips(enabled, options) {
2259
- const tips = {
2260
- ...readShellTipSettings(typeof options === "string" ? parseJson(options) : options)
2261
- };
2262
- const on = typeof enabled === "boolean" ? enabled : readBoolean(typeof enabled === "string" ? enabled : void 0);
2263
- if (on !== void 0) tips.enabled = on;
2264
- return Object.keys(tips).length > 0 ? { tips } : {};
2265
- }
2266
-
2267
- // utils/contact-keys.util.ts
2268
- function emailKey(email) {
2269
- const key = email?.trim().toLowerCase();
2270
- return key && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(key) ? key : null;
2271
- }
2272
- function phoneKey(phone) {
2273
- const raw = phone?.trim();
2274
- if (!raw) return null;
2275
- const digits = raw.replace(/\D/g, "");
2276
- if (raw.startsWith("+")) return digits.length >= 8 && digits.length <= 15 ? `+${digits}` : null;
2277
- if (digits.length === 10) return `+1${digits}`;
2278
- if (digits.length === 11 && digits.startsWith("1")) return `+${digits}`;
2279
- return null;
2280
- }
2281
- var CUSTOMER_CONTACT_VERIFIED = "CUSTOMER_CONTACT_VERIFIED";
2282
- var CUSTOMER_EMAIL_TAKEN = "CUSTOMER_EMAIL_TAKEN";
2283
- function sameContact(a, b, key) {
2284
- return (key(a) ?? a?.trim().toLowerCase() ?? "") === (key(b) ?? b?.trim().toLowerCase() ?? "");
2285
- }
2286
- function verifiedContactChange(existing, change) {
2287
- if (!existing.verifiedShopperAt) return null;
2288
- if (change.email !== void 0 && !sameContact(existing.email, change.email, emailKey)) return "email";
2289
- if (change.phone !== void 0 && !sameContact(existing.phone, change.phone, phoneKey)) return "phone";
2290
- return null;
2161
+ function landedCostPerUnit(landedValue, baseQuantity, ratioToBase = 1) {
2162
+ return Number(bankersRoundDiv(BigInt(Math.round(landedValue * ratioToBase)), BigInt(baseQuantity)));
2291
2163
  }
2164
+ var bookCostPerUnit = (book, ratioToBase) => book && book.totalQuantity > 0 && ratioToBase ? landedCostPerUnit(book.totalLandedValue, book.totalQuantity, ratioToBase) : null;
2165
+ var marginPercentOf = (grossProfit, costedGross) => grossProfit === null || !costedGross ? null : grossProfit * 100 / costedGross;
2292
2166
 
2293
2167
  // units/family-code.ts
2294
2168
  var MAX_SLUG_LENGTH = 32;
@@ -2332,7 +2206,6 @@ var FULFILLMENT_STATES = [
2332
2206
  "in_progress",
2333
2207
  "fulfilled",
2334
2208
  "partially_fulfilled",
2335
- "return_pending",
2336
2209
  "returned",
2337
2210
  "partially_returned",
2338
2211
  "cancelled"
@@ -2358,7 +2231,10 @@ var CONDITION_OPERATORS = [
2358
2231
  function isConditionOperator(value) {
2359
2232
  return CONDITION_OPERATORS.includes(value);
2360
2233
  }
2361
- var PATH_MODES = ["strict", "permissive"];
2234
+ var PATH_MODES = [
2235
+ "strict",
2236
+ "permissive"
2237
+ ];
2362
2238
 
2363
2239
  // order-state-machine/state-schema.ts
2364
2240
  var PAYMENT_DEFS = [
@@ -2379,9 +2255,6 @@ var FULFILLMENT_DEFS = [
2379
2255
  { id: "in_progress", label: "In Progress", terminal: false },
2380
2256
  { id: "fulfilled", label: "Fulfilled", terminal: true },
2381
2257
  { id: "partially_fulfilled", label: "Partially Fulfilled", terminal: false },
2382
- // The store accepted the shopper's return request: the goods are on their way back, no money has moved yet.
2383
- // The refund lands `partially_returned` / `returned` as it does from `fulfilled`.
2384
- { id: "return_pending", label: "Return Accepted", terminal: false },
2385
2258
  { id: "returned", label: "Returned", terminal: true },
2386
2259
  { id: "partially_returned", label: "Partially Returned", terminal: false },
2387
2260
  { id: "cancelled", label: "Cancelled", terminal: true }
@@ -2411,8 +2284,6 @@ var STATE_SCHEMA = Object.freeze({
2411
2284
  var REFUND_ALLOWED_FULFILLMENT = /* @__PURE__ */ new Set(["fulfilled", "returned", "partially_returned", "cancelled"]);
2412
2285
  var PAYMENT_COLLECTION_ORDER = ["unpaid", "partially_paid", "paid"];
2413
2286
  var UNRETURNED_MONEY_STATES = /* @__PURE__ */ new Set(["partially_paid", "paid", "partially_refunded"]);
2414
- var RETURN_FROM_FULFILLMENT = /* @__PURE__ */ new Set(["fulfilled", "partially_fulfilled", "partially_returned"]);
2415
- var RETURN_PENDING_PAYMENTS = /* @__PURE__ */ new Set(["paid", "partially_refunded"]);
2416
2287
  var REFUNDED_FULFILLMENT_LANDINGS = /* @__PURE__ */ new Set(["returned", "cancelled"]);
2417
2288
  var FINANCIAL_INVARIANTS = [
2418
2289
  {
@@ -2460,11 +2331,6 @@ var FINANCIAL_INVARIANTS = [
2460
2331
  description: "A voided order exists only at cancelled fulfillment: a voided order cannot re-enter fulfillment, and a voided \xD7 non-cancelled pair cannot be materialized from nothing (complements no-leave-voided, which only freezes the payment axis). Moves INTO voided from a live payment state are the void flow\u2019s concern, not this rule\u2019s",
2461
2332
  check: (from, to) => (from === null || from.payment === "voided") && to.payment === "voided" && to.fulfillment !== "cancelled"
2462
2333
  },
2463
- {
2464
- id: "return-pending-needs-goods-out",
2465
- description: "Fulfillment enters return_pending (return accepted) only from fulfilled, partially_fulfilled or partially_returned, and holds it only while payment is paid or partially_refunded \u2014 goods must have gone out and money must still be held",
2466
- check: (from, to) => to.fulfillment === "return_pending" && (!RETURN_PENDING_PAYMENTS.has(to.payment) || from?.fulfillment !== "return_pending" && !(from && RETURN_FROM_FULFILLMENT.has(from.fulfillment)))
2467
- },
2468
2334
  {
2469
2335
  id: "no-reopen-refunded-fulfillment",
2470
2336
  description: "A fully refunded order cannot re-enter fulfillment \u2014 it may only relabel between its canonical landings, returned and cancelled (complements no-leave-refunded, which only freezes the payment axis)",
@@ -2556,9 +2422,7 @@ var DISPLAY_LABEL_OVERRIDES = {
2556
2422
  "paid|on_hold": "Parked - Paid",
2557
2423
  "paid|fulfilled": "Completed",
2558
2424
  "partially_refunded|fulfilled": "Partially Refunded",
2559
- "partially_refunded|partially_returned": "Partially Refunded",
2560
- "paid|return_pending": "Return Accepted",
2561
- "partially_refunded|return_pending": "Return Accepted"
2425
+ "partially_refunded|partially_returned": "Partially Refunded"
2562
2426
  };
2563
2427
  var TERMINAL_LABEL_OVERRIDES = {
2564
2428
  voided: "Cancelled"
@@ -2700,7 +2564,6 @@ function buildOrderContext(order, extras) {
2700
2564
  }
2701
2565
 
2702
2566
  // order-state-machine/display-state.ts
2703
- var ATOMS_ADDED_AFTER_SNAPSHOT = /* @__PURE__ */ new Set(["return_pending"]);
2704
2567
  function atomLabel(atom, defs) {
2705
2568
  return defs.find((d) => d.id === atom)?.label ?? atom;
2706
2569
  }
@@ -2714,10 +2577,6 @@ function deriveDisplayState(payment, fulfillment, config) {
2714
2577
  return { label: rule.label, color: rule.color, icon: rule.icon };
2715
2578
  }
2716
2579
  }
2717
- if (ATOMS_ADDED_AFTER_SNAPSHOT.has(fulfillment)) {
2718
- const fallback = DEFAULT_DISPLAY_STATE_MAP.find((rule) => displayRuleMatchesPair(rule, payment, fulfillment));
2719
- if (fallback) return { label: fallback.label, color: fallback.color, icon: fallback.icon };
2720
- }
2721
2580
  return {
2722
2581
  label: `${atomLabel(payment, STATE_SCHEMA.paymentStates)} / ${atomLabel(fulfillment, STATE_SCHEMA.fulfillmentStates)}`
2723
2582
  };
@@ -4505,8 +4364,6 @@ function quote(option, zoneId, itemsTotal) {
4505
4364
  amountToFree: freeOver != null && amount > 0 ? freeOver - itemsTotal : null,
4506
4365
  minDays: option.minDays ?? null,
4507
4366
  maxDays: option.maxDays ?? null,
4508
- minMinutes: option.minMinutes ?? null,
4509
- maxMinutes: option.maxMinutes ?? null,
4510
4367
  outletId: option.outletId ?? null
4511
4368
  };
4512
4369
  }
@@ -4521,21 +4378,6 @@ function countriesShippedTo(zones) {
4521
4378
  return [...countries].sort();
4522
4379
  }
4523
4380
 
4524
- // shipping/time.ts
4525
- function shippingDuration(minMinutes, maxMinutes) {
4526
- const min = minMinutes ?? maxMinutes;
4527
- const max = maxMinutes ?? minMinutes;
4528
- if (min == null || max == null) return null;
4529
- const wholeHours = max > 0 && min % 60 === 0 && max % 60 === 0;
4530
- return wholeHours ? { unit: "hour", min: min / 60, max: max / 60 } : { unit: "minute", min, max };
4531
- }
4532
- function formatShippingDuration(minMinutes, maxMinutes, locale, display = "long") {
4533
- const duration = shippingDuration(minMinutes, maxMinutes);
4534
- if (!duration) return null;
4535
- const unit2 = new Intl.NumberFormat(locale ?? "en", { style: "unit", unit: duration.unit, unitDisplay: display });
4536
- return duration.min === duration.max ? unit2.format(duration.max) : `${duration.min}\u2013${unit2.format(duration.max)}`;
4537
- }
4538
-
4539
4381
  // shipping/validate.ts
4540
4382
  function validateShippingZone(zone) {
4541
4383
  const problems = [...placeProblems(zone)];
@@ -4564,15 +4406,7 @@ function fitsKind(place, kind) {
4564
4406
  return false;
4565
4407
  }
4566
4408
  var isAmount = (value) => Number.isInteger(value) && value >= 0;
4567
- var isTime = (value) => value == null || isAmount(value);
4568
- var inOrder = (min, max) => (min ?? 0) <= (max ?? Infinity);
4569
- function timeIsValid(option) {
4570
- const { minDays, maxDays, minMinutes, maxMinutes } = option;
4571
- if (![minDays, maxDays, minMinutes, maxMinutes].every(isTime)) return false;
4572
- const hasDays = minDays != null || maxDays != null;
4573
- const hasMinutes = minMinutes != null || maxMinutes != null;
4574
- return !(hasDays && hasMinutes) && inOrder(minDays, maxDays) && inOrder(minMinutes, maxMinutes);
4575
- }
4409
+ var isDays = (value) => value == null || isAmount(value);
4576
4410
  function optionProblems(option) {
4577
4411
  const problems = [];
4578
4412
  const isPickup = option.type === "pickup" /* PICKUP */;
@@ -4580,7 +4414,9 @@ function optionProblems(option) {
4580
4414
  problems.push("INVALID_PRICE" /* INVALID_PRICE */);
4581
4415
  }
4582
4416
  if (!isPickup && !option.name?.trim()) problems.push("MISSING_NAME" /* MISSING_NAME */);
4583
- if (!timeIsValid(option)) problems.push("INVALID_DAYS" /* INVALID_DAYS */);
4417
+ if (!isDays(option.minDays) || !isDays(option.maxDays) || (option.minDays ?? 0) > (option.maxDays ?? Infinity)) {
4418
+ problems.push("INVALID_DAYS" /* INVALID_DAYS */);
4419
+ }
4584
4420
  if (!tiersAreValid(option)) problems.push("INVALID_TIERS" /* INVALID_TIERS */);
4585
4421
  if (option.channels.length === 0) problems.push("NO_CHANNEL" /* NO_CHANNEL */);
4586
4422
  if (isPickup && !option.outletId) problems.push("PICKUP_WITHOUT_STORE" /* PICKUP_WITHOUT_STORE */);
@@ -4592,224 +4428,6 @@ function tiersAreValid(option) {
4592
4428
  return tiers.every((tier) => Number.isInteger(tier.from) && tier.from > 0 && isAmount(tier.price)) && new Set(froms).size === froms.length;
4593
4429
  }
4594
4430
 
4595
- // tax/sha1.ts
4596
- function utf8Bytes(text) {
4597
- const bytes = [];
4598
- for (const char of text) {
4599
- const cp = char.codePointAt(0);
4600
- if (cp < 128) bytes.push(cp);
4601
- else if (cp < 2048) bytes.push(192 | cp >> 6, 128 | cp & 63);
4602
- else if (cp < 65536) bytes.push(224 | cp >> 12, 128 | cp >> 6 & 63, 128 | cp & 63);
4603
- else bytes.push(240 | cp >> 18, 128 | cp >> 12 & 63, 128 | cp >> 6 & 63, 128 | cp & 63);
4604
- }
4605
- return bytes;
4606
- }
4607
- var rotl = (x, n) => x << n | x >>> 32 - n;
4608
- function sha1Hex(text) {
4609
- const bytes = utf8Bytes(text);
4610
- const bitLength = bytes.length * 8;
4611
- bytes.push(128);
4612
- while (bytes.length % 64 !== 56) bytes.push(0);
4613
- const high = Math.floor(bitLength / 4294967296);
4614
- for (const word of [high, bitLength >>> 0])
4615
- bytes.push(word >>> 24 & 255, word >>> 16 & 255, word >>> 8 & 255, word & 255);
4616
- const h = [1732584193, 4023233417, 2562383102, 271733878, 3285377520];
4617
- const w = new Array(80);
4618
- for (let offset = 0; offset < bytes.length; offset += 64) {
4619
- for (let i = 0; i < 16; i++) {
4620
- const j = offset + i * 4;
4621
- w[i] = bytes[j] << 24 | bytes[j + 1] << 16 | bytes[j + 2] << 8 | bytes[j + 3];
4622
- }
4623
- for (let i = 16; i < 80; i++) w[i] = rotl(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);
4624
- let [a, b, c, d, e] = h;
4625
- for (let i = 0; i < 80; i++) {
4626
- const [f, k] = i < 20 ? [b & c | ~b & d, 1518500249] : i < 40 ? [b ^ c ^ d, 1859775393] : i < 60 ? [b & c | b & d | c & d, 2400959708] : [b ^ c ^ d, 3395469782];
4627
- const t = rotl(a, 5) + f + e + k + w[i] | 0;
4628
- e = d;
4629
- d = c;
4630
- c = rotl(b, 30);
4631
- b = a;
4632
- a = t;
4633
- }
4634
- h[0] = h[0] + a | 0;
4635
- h[1] = h[1] + b | 0;
4636
- h[2] = h[2] + c | 0;
4637
- h[3] = h[3] + d | 0;
4638
- h[4] = h[4] + e | 0;
4639
- }
4640
- return h.map((x) => (x >>> 0).toString(16).padStart(8, "0")).join("");
4641
- }
4642
-
4643
- // tax/table.ts
4644
- var STANDARD_TAX_TYPE = "standard";
4645
- var TYPE_FIELDS = ["key", "name", "description", "sortOrder", "active"];
4646
- var RATE_FIELDS = [
4647
- "code",
4648
- "name",
4649
- "kind",
4650
- "places",
4651
- "rate",
4652
- "from",
4653
- "to",
4654
- "order",
4655
- "compound",
4656
- "registrationPlace",
4657
- "harmonized",
4658
- "parts",
4659
- "sourceUrl",
4660
- "status"
4661
- ];
4662
- var RULE_FIELDS = ["taxType", "codes", "rate", "from", "to", "sourceUrl", "status", "note"];
4663
- function canonical(row, fields) {
4664
- return JSON.stringify(fields.map((field) => row[field] ?? null));
4665
- }
4666
- var sortedCanonical = (rows, fields) => rows.map((row) => canonical(row, fields)).sort();
4667
- function automaticTaxTableVersion(table) {
4668
- return sha1Hex(
4669
- JSON.stringify([
4670
- sortedCanonical(table.types, TYPE_FIELDS),
4671
- sortedCanonical(table.rates, RATE_FIELDS),
4672
- sortedCanonical(table.rules, RULE_FIELDS)
4673
- ])
4674
- );
4675
- }
4676
- var toTypeRow = ({ key, name, description, sortOrder, active }) => ({
4677
- key,
4678
- name,
4679
- description,
4680
- sortOrder,
4681
- active
4682
- });
4683
- var toRateRow = (rate) => ({
4684
- code: rate.code,
4685
- name: rate.name,
4686
- kind: rate.kind,
4687
- places: rate.places,
4688
- rate: rate.rate,
4689
- from: rate.from,
4690
- to: rate.to,
4691
- order: rate.order,
4692
- compound: rate.compound,
4693
- registrationPlace: rate.registrationPlace,
4694
- harmonized: rate.harmonized,
4695
- parts: rate.parts?.map(({ code, name, rate: partRate, level }) => ({ code, name, rate: partRate, level })),
4696
- sourceUrl: rate.sourceUrl,
4697
- status: rate.status
4698
- });
4699
- var toRuleRow = ({
4700
- taxType,
4701
- codes: codes2,
4702
- rate,
4703
- from,
4704
- to,
4705
- sourceUrl,
4706
- status,
4707
- note
4708
- }) => ({
4709
- taxType,
4710
- codes: codes2,
4711
- rate,
4712
- from,
4713
- to,
4714
- sourceUrl,
4715
- status,
4716
- note
4717
- });
4718
- function buildAutomaticTaxTable(rows) {
4719
- const table = {
4720
- types: [...rows.types].sort((a, b) => a.sortOrder - b.sortOrder).map(toTypeRow),
4721
- rates: rows.rates.map(toRateRow),
4722
- rules: rows.rules.map(toRuleRow)
4723
- };
4724
- return { version: automaticTaxTableVersion(table), ...table };
4725
- }
4726
- function registrationPlacesByKind(rates) {
4727
- const places = /* @__PURE__ */ new Map();
4728
- for (const rate of rates) {
4729
- const list = places.get(rate.kind) ?? [];
4730
- if (!list.includes(rate.registrationPlace)) list.push(rate.registrationPlace);
4731
- places.set(rate.kind, list);
4732
- }
4733
- return places;
4734
- }
4735
-
4736
- // tax/exceptions.ts
4737
- var TaxExceptionSource = /* @__PURE__ */ ((TaxExceptionSource2) => {
4738
- TaxExceptionSource2["PRODUCT"] = "product";
4739
- TaxExceptionSource2["CATEGORY"] = "category";
4740
- return TaxExceptionSource2;
4741
- })(TaxExceptionSource || {});
4742
- var TAX_EXCEPTION_REASON_MAX = 200;
4743
-
4744
- // shopper/types.ts
4745
- var SHOPPER_CONSENT_SOURCES = ["checkout", "my-account", "store-account"];
4746
- var SHOPPER_RETURN_METHODS = ["mail", "in-store"];
4747
- var SHOPPER_RETURN_STATUSES = ["requested", "accepted", "declined"];
4748
- var SHOPPER_RETURN_DECLINE_REASON_MAX = 500;
4749
- var SHOPPER_ERROR_CODES = {
4750
- ORDER_NOT_FOUND: "ORDER_NOT_FOUND",
4751
- RETURN_ALREADY_REQUESTED: "RETURN_ALREADY_REQUESTED",
4752
- RETURN_NOT_ALLOWED: "RETURN_NOT_ALLOWED",
4753
- RETURN_ALREADY_DECIDED: "RETURN_ALREADY_DECIDED",
4754
- STORE_HAS_NO_SUPPORT_EMAIL: "STORE_HAS_NO_SUPPORT_EMAIL",
4755
- TOO_MANY_ADDRESSES: "TOO_MANY_ADDRESSES",
4756
- STORE_NOT_LINKED: "STORE_NOT_LINKED",
4757
- STORED_METHOD_NOT_FOUND: "STORED_METHOD_NOT_FOUND"
4758
- };
4759
-
4760
- // shopper/email.ts
4761
- function normalizeShopperEmail(email) {
4762
- if (typeof email !== "string") return null;
4763
- const value = email.trim().toLowerCase();
4764
- return /^[^\s@]+@[^\s@]+$/.test(value) ? value : null;
4765
- }
4766
-
4767
- // shopper/card.ts
4768
- function cardFromProcessorData(processorData) {
4769
- if (typeof processorData !== "string" || !processorData) return {};
4770
- let data;
4771
- try {
4772
- data = JSON.parse(processorData);
4773
- } catch {
4774
- return {};
4775
- }
4776
- if (!data || typeof data !== "object") return {};
4777
- const fields = new Map(Object.entries(data));
4778
- const text = (...keys) => keys.map((key) => fields.get(key)).find((value) => typeof value === "string" && !!value.trim());
4779
- const brand = text("Brand", "brand")?.trim();
4780
- const digits = text("Card Number", "card", "card_number")?.replace(/\D/g, "");
4781
- const issuer = text("Issuer", "issuer")?.trim();
4782
- return {
4783
- ...brand ? { cardBrand: brand.charAt(0).toUpperCase() + brand.slice(1) } : {},
4784
- ...digits && digits.length >= 4 ? { cardLastFour: digits.slice(-4) } : {},
4785
- ...issuer ? { cardIssuer: issuer } : {}
4786
- };
4787
- }
4788
-
4789
- // shopper/payments.ts
4790
- var CARD_TYPES = /* @__PURE__ */ new Set(["card", "terminal", "taptopay", "moto", "cloud", "bluetooth"]);
4791
- function kindOf(paymentType) {
4792
- if (paymentType === "cash") return "cash";
4793
- if (paymentType === "redeem") return "gift_card";
4794
- if (paymentType === "pay_later") return "pay_later";
4795
- if (CARD_TYPES.has(paymentType)) return "card";
4796
- return "other";
4797
- }
4798
- function shopperPaymentsOf(legs) {
4799
- return (legs ?? []).map((leg) => {
4800
- const type = (leg.paymentType ?? "").trim();
4801
- const kind = kindOf(type.toLowerCase());
4802
- const card = kind === "card" ? cardFromProcessorData(leg.emv) : {};
4803
- return {
4804
- kind,
4805
- // Cards: the issuer's name, else the brand. Other tenders the store named itself keep that name.
4806
- name: kind === "card" ? card.cardIssuer ?? card.cardBrand ?? null : kind === "other" ? type || null : null,
4807
- lastFour: card.cardLastFour ?? null,
4808
- amount: (leg.amount ?? 0) + (leg.tip?.amount ?? 0)
4809
- };
4810
- });
4811
- }
4812
-
4813
4431
  // constants/adyen.constants.ts
4814
4432
  var ADYEN_ROLLOUT_COUNTRY_CODES = /* @__PURE__ */ new Set(["CA"]);
4815
4433
  function isAdyenRolloutCountry(alpha2) {
@@ -4926,8 +4544,6 @@ var EXPENSE_DEFAULT_CATEGORIES = [
4926
4544
  CONDITION_OPERATORS,
4927
4545
  COUNTRY_CURRENCIES,
4928
4546
  CURRENCY_CONFIG,
4929
- CUSTOMER_CONTACT_VERIFIED,
4930
- CUSTOMER_EMAIL_TAKEN,
4931
4547
  CompanyType,
4932
4548
  CurrencyCode,
4933
4549
  CustomTableAvailability,
@@ -4937,7 +4553,6 @@ var EXPENSE_DEFAULT_CATEGORIES = [
4937
4553
  DEFAULT_DISPLAY_STATE_MAP,
4938
4554
  DEFAULT_HOLD_MINUTES,
4939
4555
  DEFAULT_RESOLVED_CONFIG,
4940
- DEFAULT_SHELL_SETTINGS,
4941
4556
  DEFAULT_UNIT_ID,
4942
4557
  DualWriteStrategy,
4943
4558
  EUFixedRates,
@@ -4966,7 +4581,6 @@ var EXPENSE_DEFAULT_CATEGORIES = [
4966
4581
  ORDER_STATE_TOPIC,
4967
4582
  OrderPlatform,
4968
4583
  OtherFixedRates,
4969
- OutOfProvinceTaxes,
4970
4584
  OwnerType,
4971
4585
  PATH_MODES,
4972
4586
  PAYMENT_CHANNELS,
@@ -4994,18 +4608,7 @@ var EXPENSE_DEFAULT_CATEGORIES = [
4994
4608
  ResidualPaymentMethod,
4995
4609
  ResidualStatus,
4996
4610
  ResourceAvailabilityState,
4997
- SHELL_FLOW_SETTINGS_PREFIX,
4998
- SHELL_FLOW_TIPS_KEY,
4999
- SHELL_TIP_LABEL_MAX_LENGTH,
5000
- SHELL_TIP_PERCENT_MAX,
5001
- SHELL_TIP_PERCENT_MIN,
5002
4611
  SHIPPING_COUNTRIES,
5003
- SHOPPER_CONSENT_SOURCES,
5004
- SHOPPER_ERROR_CODES,
5005
- SHOPPER_RETURN_DECLINE_REASON_MAX,
5006
- SHOPPER_RETURN_METHODS,
5007
- SHOPPER_RETURN_STATUSES,
5008
- STANDARD_TAX_TYPE,
5009
4612
  STATE_SCHEMA,
5010
4613
  STRIPE_SUPPORTED_COUNTRIES,
5011
4614
  SYSTEM_FAMILIES,
@@ -5023,11 +4626,6 @@ var EXPENSE_DEFAULT_CATEGORIES = [
5023
4626
  StationStatus,
5024
4627
  StripeCurrencyCode,
5025
4628
  StripeStatus,
5026
- TAX_EXCEPTION_REASON_MAX,
5027
- TaxExceptionSource,
5028
- TaxRegistrationKind,
5029
- TaxSource,
5030
- TaxWarningCode,
5031
4629
  TimePeriod,
5032
4630
  TopMetericsSort,
5033
4631
  UserTypes,
@@ -5042,13 +4640,14 @@ var EXPENSE_DEFAULT_CATEGORIES = [
5042
4640
  ancestorChain,
5043
4641
  applyAssignment,
5044
4642
  assertUnitSane,
5045
- automaticTaxTableVersion,
4643
+ attachResolvedUnits,
5046
4644
  availableIn,
4645
+ bankersRoundDiv,
5047
4646
  baseFor,
5048
4647
  baseFulfillmentDefinitions,
5049
4648
  baseOf,
5050
4649
  basePaymentDefinitions,
5051
- buildAutomaticTaxTable,
4650
+ bookCostPerUnit,
5052
4651
  buildAvailability,
5053
4652
  buildGrid,
5054
4653
  buildOrderContext,
@@ -5056,9 +4655,11 @@ var EXPENSE_DEFAULT_CATEGORIES = [
5056
4655
  buildResolvedConfig,
5057
4656
  calculatePercentage,
5058
4657
  canTransition,
5059
- cardFromProcessorData,
5060
4658
  cheapestCompositeItem,
5061
4659
  cheapestCompositePrice,
4660
+ componentUnitsPerLine,
4661
+ compositeCostOfKnown,
4662
+ compositeCostRange,
5062
4663
  compositeItemCost,
5063
4664
  compositeItemUnavailable,
5064
4665
  compositeMakeable,
@@ -5067,6 +4668,7 @@ var EXPENSE_DEFAULT_CATEGORIES = [
5067
4668
  compositeVariantInStock,
5068
4669
  conditionSummary,
5069
4670
  convertFixedFeeToLocalCurrency,
4671
+ costPriceChangeStamp,
5070
4672
  createAmount,
5071
4673
  crossAxisRuleApplies,
5072
4674
  currentAssignees,
@@ -5075,17 +4677,14 @@ var EXPENSE_DEFAULT_CATEGORIES = [
5075
4677
  deriveUnitId,
5076
4678
  displayRuleMatchesPair,
5077
4679
  divideAmount,
5078
- emailKey,
5079
4680
  evaluateCondition,
5080
4681
  evaluateConditionSet,
5081
4682
  extendPrice,
5082
4683
  extendPriceFor,
5083
- flowSettingsFromShellSettings,
5084
4684
  formatCurrency,
5085
4685
  formatInUnit,
5086
4686
  formatMinorUnitsToString,
5087
4687
  formatQuantity,
5088
- formatShippingDuration,
5089
4688
  fromBase,
5090
4689
  fromMinorUnits,
5091
4690
  generateMongoID,
@@ -5107,6 +4706,7 @@ var EXPENSE_DEFAULT_CATEGORIES = [
5107
4706
  hasSellableChoice,
5108
4707
  holdExpiresAt,
5109
4708
  inferStatesFromLegacyStatus,
4709
+ innerCompositeOption,
5110
4710
  isAdyenRolloutCountry,
5111
4711
  isAffirmCountry,
5112
4712
  isAffirmPricePlan,
@@ -5114,17 +4714,19 @@ var EXPENSE_DEFAULT_CATEGORIES = [
5114
4714
  isConditionOperator,
5115
4715
  isFulfillmentState,
5116
4716
  isInCart,
4717
+ isInnerComposite,
5117
4718
  isPaymentState,
5118
- isShellTipPercent,
5119
4719
  isSupportedCurrency,
5120
4720
  isSystemFamilyCode,
5121
4721
  isValidQuantity,
5122
4722
  isWhole,
4723
+ landedCostPerUnit,
5123
4724
  lineStockMoves,
5124
4725
  listCountries,
5125
4726
  listProvinces,
5126
4727
  listShippingCountries,
5127
4728
  mapToLegacyStatus,
4729
+ marginPercentOf,
5128
4730
  maxPrecisionFor,
5129
4731
  mergeFragment,
5130
4732
  modifiersSellable,
@@ -5135,13 +4737,11 @@ var EXPENSE_DEFAULT_CATEGORIES = [
5135
4737
  normalizeMongoIdString,
5136
4738
  normalizePostCode,
5137
4739
  normalizeProvince,
5138
- normalizeShopperEmail,
5139
4740
  occupancyIn,
5140
4741
  orderAssignments,
5141
4742
  parseAmountToMinorUnits,
5142
4743
  parseCurrencyCode,
5143
4744
  parseStripeCurrencyCode,
5144
- phoneKey,
5145
4745
  placeKey,
5146
4746
  planWindow,
5147
4747
  poolDemand,
@@ -5152,29 +4752,19 @@ var EXPENSE_DEFAULT_CATEGORIES = [
5152
4752
  presentAt,
5153
4753
  priceForTotal,
5154
4754
  provincesForPostCode,
5155
- readShellTipSettings,
5156
- registrationPlacesByKind,
5157
4755
  removeFragment,
5158
4756
  resolveFamily,
5159
4757
  resolveModifiersForProduct,
5160
- resolveShellSettings,
5161
- resolveShellSettingsWithSources,
5162
4758
  resolveShipping,
5163
4759
  resolveTemplate,
5164
4760
  resolveUnit,
5165
4761
  roundToPrecision,
5166
4762
  sameFamily,
5167
4763
  setOrderState,
5168
- sha1Hex,
5169
- shellSettingsFromCompanyTips,
5170
- shellSettingsFromFlowSettings,
5171
- shellSettingsProblems,
5172
- shellTipSettingsProblems,
5173
- shippingDuration,
4764
+ shelfComponents,
5174
4765
  shipsToCountry,
5175
4766
  shopDayKey,
5176
4767
  shopDayRange,
5177
- shopperPaymentsOf,
5178
4768
  signReportForDisplay,
5179
4769
  slotsForWindow,
5180
4770
  stringifyMinorUnits,
@@ -5185,7 +4775,9 @@ var EXPENSE_DEFAULT_CATEGORIES = [
5185
4775
  validateFragmentCompatibility,
5186
4776
  validateOrderStatuses,
5187
4777
  validateShippingZone,
5188
- verifiedContactChange,
4778
+ variantCostAtSale,
4779
+ variantDisplayName,
4780
+ variantLabel,
5189
4781
  violatesFinancialInvariant,
5190
4782
  windowEndsAt,
5191
4783
  withinPresence