@final-commerce/common 2.11.1-online.1 → 2.11.1-online.10

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.mjs CHANGED
@@ -1805,6 +1805,32 @@ function lineStockMoves(item, quantity, reservations = []) {
1805
1805
  });
1806
1806
  }
1807
1807
 
1808
+ // utils/contact-keys.util.ts
1809
+ function emailKey(email) {
1810
+ const key = email?.trim().toLowerCase();
1811
+ return key && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(key) ? key : null;
1812
+ }
1813
+ function phoneKey(phone) {
1814
+ const raw = phone?.trim();
1815
+ if (!raw) return null;
1816
+ const digits = raw.replace(/\D/g, "");
1817
+ if (raw.startsWith("+")) return digits.length >= 8 && digits.length <= 15 ? `+${digits}` : null;
1818
+ if (digits.length === 10) return `+1${digits}`;
1819
+ if (digits.length === 11 && digits.startsWith("1")) return `+${digits}`;
1820
+ return null;
1821
+ }
1822
+ var CUSTOMER_CONTACT_VERIFIED = "CUSTOMER_CONTACT_VERIFIED";
1823
+ var CUSTOMER_EMAIL_TAKEN = "CUSTOMER_EMAIL_TAKEN";
1824
+ function sameContact(a, b, key) {
1825
+ return (key(a) ?? a?.trim().toLowerCase() ?? "") === (key(b) ?? b?.trim().toLowerCase() ?? "");
1826
+ }
1827
+ function verifiedContactChange(existing, change) {
1828
+ if (!existing.verifiedShopperAt) return null;
1829
+ if (change.email !== void 0 && !sameContact(existing.email, change.email, emailKey)) return "email";
1830
+ if (change.phone !== void 0 && !sameContact(existing.phone, change.phone, phoneKey)) return "phone";
1831
+ return null;
1832
+ }
1833
+
1808
1834
  // units/family-code.ts
1809
1835
  var MAX_SLUG_LENGTH = 32;
1810
1836
  var FALLBACK_SLUG = "family";
@@ -1847,6 +1873,7 @@ var FULFILLMENT_STATES = [
1847
1873
  "in_progress",
1848
1874
  "fulfilled",
1849
1875
  "partially_fulfilled",
1876
+ "return_pending",
1850
1877
  "returned",
1851
1878
  "partially_returned",
1852
1879
  "cancelled"
@@ -1872,10 +1899,7 @@ var CONDITION_OPERATORS = [
1872
1899
  function isConditionOperator(value) {
1873
1900
  return CONDITION_OPERATORS.includes(value);
1874
1901
  }
1875
- var PATH_MODES = [
1876
- "strict",
1877
- "permissive"
1878
- ];
1902
+ var PATH_MODES = ["strict", "permissive"];
1879
1903
 
1880
1904
  // order-state-machine/state-schema.ts
1881
1905
  var PAYMENT_DEFS = [
@@ -1896,6 +1920,9 @@ var FULFILLMENT_DEFS = [
1896
1920
  { id: "in_progress", label: "In Progress", terminal: false },
1897
1921
  { id: "fulfilled", label: "Fulfilled", terminal: true },
1898
1922
  { id: "partially_fulfilled", label: "Partially Fulfilled", terminal: false },
1923
+ // The store accepted the shopper's return request: the goods are on their way back, no money has moved yet.
1924
+ // The refund lands `partially_returned` / `returned` as it does from `fulfilled`.
1925
+ { id: "return_pending", label: "Return Accepted", terminal: false },
1899
1926
  { id: "returned", label: "Returned", terminal: true },
1900
1927
  { id: "partially_returned", label: "Partially Returned", terminal: false },
1901
1928
  { id: "cancelled", label: "Cancelled", terminal: true }
@@ -1925,6 +1952,8 @@ var STATE_SCHEMA = Object.freeze({
1925
1952
  var REFUND_ALLOWED_FULFILLMENT = /* @__PURE__ */ new Set(["fulfilled", "returned", "partially_returned", "cancelled"]);
1926
1953
  var PAYMENT_COLLECTION_ORDER = ["unpaid", "partially_paid", "paid"];
1927
1954
  var UNRETURNED_MONEY_STATES = /* @__PURE__ */ new Set(["partially_paid", "paid", "partially_refunded"]);
1955
+ var RETURN_FROM_FULFILLMENT = /* @__PURE__ */ new Set(["fulfilled", "partially_fulfilled", "partially_returned"]);
1956
+ var RETURN_PENDING_PAYMENTS = /* @__PURE__ */ new Set(["paid", "partially_refunded"]);
1928
1957
  var REFUNDED_FULFILLMENT_LANDINGS = /* @__PURE__ */ new Set(["returned", "cancelled"]);
1929
1958
  var FINANCIAL_INVARIANTS = [
1930
1959
  {
@@ -1972,6 +2001,11 @@ var FINANCIAL_INVARIANTS = [
1972
2001
  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",
1973
2002
  check: (from, to) => (from === null || from.payment === "voided") && to.payment === "voided" && to.fulfillment !== "cancelled"
1974
2003
  },
2004
+ {
2005
+ id: "return-pending-needs-goods-out",
2006
+ 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",
2007
+ check: (from, to) => to.fulfillment === "return_pending" && (!RETURN_PENDING_PAYMENTS.has(to.payment) || from?.fulfillment !== "return_pending" && !(from && RETURN_FROM_FULFILLMENT.has(from.fulfillment)))
2008
+ },
1975
2009
  {
1976
2010
  id: "no-reopen-refunded-fulfillment",
1977
2011
  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)",
@@ -2063,7 +2097,9 @@ var DISPLAY_LABEL_OVERRIDES = {
2063
2097
  "paid|on_hold": "Parked - Paid",
2064
2098
  "paid|fulfilled": "Completed",
2065
2099
  "partially_refunded|fulfilled": "Partially Refunded",
2066
- "partially_refunded|partially_returned": "Partially Refunded"
2100
+ "partially_refunded|partially_returned": "Partially Refunded",
2101
+ "paid|return_pending": "Return Accepted",
2102
+ "partially_refunded|return_pending": "Return Accepted"
2067
2103
  };
2068
2104
  var TERMINAL_LABEL_OVERRIDES = {
2069
2105
  voided: "Cancelled"
@@ -2205,6 +2241,7 @@ function buildOrderContext(order, extras) {
2205
2241
  }
2206
2242
 
2207
2243
  // order-state-machine/display-state.ts
2244
+ var ATOMS_ADDED_AFTER_SNAPSHOT = /* @__PURE__ */ new Set(["return_pending"]);
2208
2245
  function atomLabel(atom, defs) {
2209
2246
  return defs.find((d) => d.id === atom)?.label ?? atom;
2210
2247
  }
@@ -2218,6 +2255,10 @@ function deriveDisplayState(payment, fulfillment, config) {
2218
2255
  return { label: rule.label, color: rule.color, icon: rule.icon };
2219
2256
  }
2220
2257
  }
2258
+ if (ATOMS_ADDED_AFTER_SNAPSHOT.has(fulfillment)) {
2259
+ const fallback = DEFAULT_DISPLAY_STATE_MAP.find((rule) => displayRuleMatchesPair(rule, payment, fulfillment));
2260
+ if (fallback) return { label: fallback.label, color: fallback.color, icon: fallback.icon };
2261
+ }
2221
2262
  return {
2222
2263
  label: `${atomLabel(payment, STATE_SCHEMA.paymentStates)} / ${atomLabel(fulfillment, STATE_SCHEMA.fulfillmentStates)}`
2223
2264
  };
@@ -4005,6 +4046,8 @@ function quote(option, zoneId, itemsTotal) {
4005
4046
  amountToFree: freeOver != null && amount > 0 ? freeOver - itemsTotal : null,
4006
4047
  minDays: option.minDays ?? null,
4007
4048
  maxDays: option.maxDays ?? null,
4049
+ minMinutes: option.minMinutes ?? null,
4050
+ maxMinutes: option.maxMinutes ?? null,
4008
4051
  outletId: option.outletId ?? null
4009
4052
  };
4010
4053
  }
@@ -4019,6 +4062,21 @@ function countriesShippedTo(zones) {
4019
4062
  return [...countries].sort();
4020
4063
  }
4021
4064
 
4065
+ // shipping/time.ts
4066
+ function shippingDuration(minMinutes, maxMinutes) {
4067
+ const min = minMinutes ?? maxMinutes;
4068
+ const max = maxMinutes ?? minMinutes;
4069
+ if (min == null || max == null) return null;
4070
+ const wholeHours = max > 0 && min % 60 === 0 && max % 60 === 0;
4071
+ return wholeHours ? { unit: "hour", min: min / 60, max: max / 60 } : { unit: "minute", min, max };
4072
+ }
4073
+ function formatShippingDuration(minMinutes, maxMinutes, locale, display = "long") {
4074
+ const duration = shippingDuration(minMinutes, maxMinutes);
4075
+ if (!duration) return null;
4076
+ const unit2 = new Intl.NumberFormat(locale ?? "en", { style: "unit", unit: duration.unit, unitDisplay: display });
4077
+ return duration.min === duration.max ? unit2.format(duration.max) : `${duration.min}\u2013${unit2.format(duration.max)}`;
4078
+ }
4079
+
4022
4080
  // shipping/validate.ts
4023
4081
  function validateShippingZone(zone) {
4024
4082
  const problems = [...placeProblems(zone)];
@@ -4047,7 +4105,15 @@ function fitsKind(place, kind) {
4047
4105
  return false;
4048
4106
  }
4049
4107
  var isAmount = (value) => Number.isInteger(value) && value >= 0;
4050
- var isDays = (value) => value == null || isAmount(value);
4108
+ var isTime = (value) => value == null || isAmount(value);
4109
+ var inOrder = (min, max) => (min ?? 0) <= (max ?? Infinity);
4110
+ function timeIsValid(option) {
4111
+ const { minDays, maxDays, minMinutes, maxMinutes } = option;
4112
+ if (![minDays, maxDays, minMinutes, maxMinutes].every(isTime)) return false;
4113
+ const hasDays = minDays != null || maxDays != null;
4114
+ const hasMinutes = minMinutes != null || maxMinutes != null;
4115
+ return !(hasDays && hasMinutes) && inOrder(minDays, maxDays) && inOrder(minMinutes, maxMinutes);
4116
+ }
4051
4117
  function optionProblems(option) {
4052
4118
  const problems = [];
4053
4119
  const isPickup = option.type === "pickup" /* PICKUP */;
@@ -4055,9 +4121,7 @@ function optionProblems(option) {
4055
4121
  problems.push("INVALID_PRICE" /* INVALID_PRICE */);
4056
4122
  }
4057
4123
  if (!isPickup && !option.name?.trim()) problems.push("MISSING_NAME" /* MISSING_NAME */);
4058
- if (!isDays(option.minDays) || !isDays(option.maxDays) || (option.minDays ?? 0) > (option.maxDays ?? Infinity)) {
4059
- problems.push("INVALID_DAYS" /* INVALID_DAYS */);
4060
- }
4124
+ if (!timeIsValid(option)) problems.push("INVALID_DAYS" /* INVALID_DAYS */);
4061
4125
  if (!tiersAreValid(option)) problems.push("INVALID_TIERS" /* INVALID_TIERS */);
4062
4126
  if (option.channels.length === 0) problems.push("NO_CHANNEL" /* NO_CHANNEL */);
4063
4127
  if (isPickup && !option.outletId) problems.push("PICKUP_WITHOUT_STORE" /* PICKUP_WITHOUT_STORE */);
@@ -4210,6 +4274,83 @@ function registrationPlacesByKind(rates) {
4210
4274
  return places;
4211
4275
  }
4212
4276
 
4277
+ // tax/exceptions.ts
4278
+ var TaxExceptionSource = /* @__PURE__ */ ((TaxExceptionSource2) => {
4279
+ TaxExceptionSource2["PRODUCT"] = "product";
4280
+ TaxExceptionSource2["CATEGORY"] = "category";
4281
+ return TaxExceptionSource2;
4282
+ })(TaxExceptionSource || {});
4283
+ var TAX_EXCEPTION_REASON_MAX = 200;
4284
+
4285
+ // shopper/types.ts
4286
+ var SHOPPER_CONSENT_SOURCES = ["checkout", "my-account", "store-account"];
4287
+ var SHOPPER_RETURN_METHODS = ["mail", "in-store"];
4288
+ var SHOPPER_RETURN_STATUSES = ["requested", "accepted", "declined"];
4289
+ var SHOPPER_RETURN_DECLINE_REASON_MAX = 500;
4290
+ var SHOPPER_ERROR_CODES = {
4291
+ ORDER_NOT_FOUND: "ORDER_NOT_FOUND",
4292
+ RETURN_ALREADY_REQUESTED: "RETURN_ALREADY_REQUESTED",
4293
+ RETURN_NOT_ALLOWED: "RETURN_NOT_ALLOWED",
4294
+ RETURN_ALREADY_DECIDED: "RETURN_ALREADY_DECIDED",
4295
+ STORE_HAS_NO_SUPPORT_EMAIL: "STORE_HAS_NO_SUPPORT_EMAIL",
4296
+ TOO_MANY_ADDRESSES: "TOO_MANY_ADDRESSES",
4297
+ STORE_NOT_LINKED: "STORE_NOT_LINKED",
4298
+ STORED_METHOD_NOT_FOUND: "STORED_METHOD_NOT_FOUND"
4299
+ };
4300
+
4301
+ // shopper/email.ts
4302
+ function normalizeShopperEmail(email) {
4303
+ if (typeof email !== "string") return null;
4304
+ const value = email.trim().toLowerCase();
4305
+ return /^[^\s@]+@[^\s@]+$/.test(value) ? value : null;
4306
+ }
4307
+
4308
+ // shopper/card.ts
4309
+ function cardFromProcessorData(processorData) {
4310
+ if (typeof processorData !== "string" || !processorData) return {};
4311
+ let data;
4312
+ try {
4313
+ data = JSON.parse(processorData);
4314
+ } catch {
4315
+ return {};
4316
+ }
4317
+ if (!data || typeof data !== "object") return {};
4318
+ const fields = new Map(Object.entries(data));
4319
+ const text = (...keys) => keys.map((key) => fields.get(key)).find((value) => typeof value === "string" && !!value.trim());
4320
+ const brand = text("Brand", "brand")?.trim();
4321
+ const digits = text("Card Number", "card", "card_number")?.replace(/\D/g, "");
4322
+ const issuer = text("Issuer", "issuer")?.trim();
4323
+ return {
4324
+ ...brand ? { cardBrand: brand.charAt(0).toUpperCase() + brand.slice(1) } : {},
4325
+ ...digits && digits.length >= 4 ? { cardLastFour: digits.slice(-4) } : {},
4326
+ ...issuer ? { cardIssuer: issuer } : {}
4327
+ };
4328
+ }
4329
+
4330
+ // shopper/payments.ts
4331
+ var CARD_TYPES = /* @__PURE__ */ new Set(["card", "terminal", "taptopay", "moto", "cloud", "bluetooth"]);
4332
+ function kindOf(paymentType) {
4333
+ if (paymentType === "cash") return "cash";
4334
+ if (paymentType === "redeem") return "gift_card";
4335
+ if (paymentType === "pay_later") return "pay_later";
4336
+ if (CARD_TYPES.has(paymentType)) return "card";
4337
+ return "other";
4338
+ }
4339
+ function shopperPaymentsOf(legs) {
4340
+ return (legs ?? []).map((leg) => {
4341
+ const type = (leg.paymentType ?? "").trim();
4342
+ const kind = kindOf(type.toLowerCase());
4343
+ const card = kind === "card" ? cardFromProcessorData(leg.emv) : {};
4344
+ return {
4345
+ kind,
4346
+ // Cards: the issuer's name, else the brand. Other tenders the store named itself keep that name.
4347
+ name: kind === "card" ? card.cardIssuer ?? card.cardBrand ?? null : kind === "other" ? type || null : null,
4348
+ lastFour: card.cardLastFour ?? null,
4349
+ amount: (leg.amount ?? 0) + (leg.tip?.amount ?? 0)
4350
+ };
4351
+ });
4352
+ }
4353
+
4213
4354
  // constants/adyen.constants.ts
4214
4355
  var ADYEN_ROLLOUT_COUNTRY_CODES = /* @__PURE__ */ new Set(["CA"]);
4215
4356
  function isAdyenRolloutCountry(alpha2) {
@@ -4325,6 +4466,8 @@ export {
4325
4466
  CONDITION_OPERATORS,
4326
4467
  COUNTRY_CURRENCIES,
4327
4468
  CURRENCY_CONFIG,
4469
+ CUSTOMER_CONTACT_VERIFIED,
4470
+ CUSTOMER_EMAIL_TAKEN,
4328
4471
  CompanyType,
4329
4472
  CurrencyCode,
4330
4473
  CustomTableAvailability,
@@ -4391,6 +4534,11 @@ export {
4391
4534
  ResidualStatus,
4392
4535
  ResourceAvailabilityState,
4393
4536
  SHIPPING_COUNTRIES,
4537
+ SHOPPER_CONSENT_SOURCES,
4538
+ SHOPPER_ERROR_CODES,
4539
+ SHOPPER_RETURN_DECLINE_REASON_MAX,
4540
+ SHOPPER_RETURN_METHODS,
4541
+ SHOPPER_RETURN_STATUSES,
4394
4542
  STANDARD_TAX_TYPE,
4395
4543
  STATE_SCHEMA,
4396
4544
  STRIPE_SUPPORTED_COUNTRIES,
@@ -4409,6 +4557,8 @@ export {
4409
4557
  StationStatus,
4410
4558
  StripeCurrencyCode,
4411
4559
  StripeStatus,
4560
+ TAX_EXCEPTION_REASON_MAX,
4561
+ TaxExceptionSource,
4412
4562
  TaxRegistrationKind,
4413
4563
  TaxSource,
4414
4564
  TaxWarningCode,
@@ -4440,6 +4590,7 @@ export {
4440
4590
  buildResolvedConfig,
4441
4591
  calculatePercentage,
4442
4592
  canTransition,
4593
+ cardFromProcessorData,
4443
4594
  cheapestCompositeItem,
4444
4595
  cheapestCompositePrice,
4445
4596
  compositeItemCost,
@@ -4458,6 +4609,7 @@ export {
4458
4609
  deriveUnitId,
4459
4610
  displayRuleMatchesPair,
4460
4611
  divideAmount,
4612
+ emailKey,
4461
4613
  evaluateCondition,
4462
4614
  evaluateConditionSet,
4463
4615
  extendPrice,
@@ -4466,6 +4618,7 @@ export {
4466
4618
  formatInUnit,
4467
4619
  formatMinorUnitsToString,
4468
4620
  formatQuantity,
4621
+ formatShippingDuration,
4469
4622
  fromBase,
4470
4623
  fromMinorUnits,
4471
4624
  generateMongoID,
@@ -4514,11 +4667,13 @@ export {
4514
4667
  normalizeMongoIdString,
4515
4668
  normalizePostCode,
4516
4669
  normalizeProvince,
4670
+ normalizeShopperEmail,
4517
4671
  occupancyIn,
4518
4672
  orderAssignments,
4519
4673
  parseAmountToMinorUnits,
4520
4674
  parseCurrencyCode,
4521
4675
  parseStripeCurrencyCode,
4676
+ phoneKey,
4522
4677
  placeKey,
4523
4678
  planWindow,
4524
4679
  poolDemand,
@@ -4540,9 +4695,11 @@ export {
4540
4695
  sameFamily,
4541
4696
  setOrderState,
4542
4697
  sha1Hex,
4698
+ shippingDuration,
4543
4699
  shipsToCountry,
4544
4700
  shopDayKey,
4545
4701
  shopDayRange,
4702
+ shopperPaymentsOf,
4546
4703
  signReportForDisplay,
4547
4704
  slotsForWindow,
4548
4705
  stringifyMinorUnits,
@@ -4553,6 +4710,7 @@ export {
4553
4710
  validateFragmentCompatibility,
4554
4711
  validateOrderStatuses,
4555
4712
  validateShippingZone,
4713
+ verifiedContactChange,
4556
4714
  violatesFinancialInvariant,
4557
4715
  windowEndsAt,
4558
4716
  withinPresence