@final-commerce/common 2.12.2-staging2.1 → 2.13.0-staging2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1019,6 +1019,16 @@ function resolveUnit(unitId, companyUnits = []) {
1019
1019
  if (!unit2) throw new Error(`Unknown measurement unit: ${unitId}`);
1020
1020
  return unit2;
1021
1021
  }
1022
+ function attachResolvedUnits(variants, companyUnits, logLabel = "attachUnits") {
1023
+ for (const variant of variants)
1024
+ if (variant.unitId)
1025
+ try {
1026
+ variant.unit = resolveUnit(variant.unitId, companyUnits);
1027
+ } catch (error) {
1028
+ console.error(`[${logLabel}] unit ${variant.unitId} does not resolve. ${error.message}`);
1029
+ }
1030
+ return variants;
1031
+ }
1022
1032
  function resolveFamily(familyId, companyFamilies = []) {
1023
1033
  const family = SYSTEM_FAMILIES.find((f) => f.familyId === familyId) ?? companyFamilies.find((f) => f.familyId === familyId);
1024
1034
  if (!family) throw new Error(`Unknown measurement unit family: ${familyId}`);
@@ -1559,6 +1569,66 @@ function hasSellableChoice(modifier, outletId) {
1559
1569
  }
1560
1570
  var modifiersSellable = (modifiers, outletId) => modifiers.every((modifier) => !modifier.required || hasSellableChoice(modifier, outletId));
1561
1571
 
1572
+ // utils/line-stock-moves.util.ts
1573
+ function lineStockMoves(item, quantity, reservations = []) {
1574
+ const sign = Math.sign(quantity);
1575
+ const pool = (stockVariantId) => stockVariantId ? { stockVariantId: stockVariantId.toString() } : {};
1576
+ if (!item.components?.length)
1577
+ return [
1578
+ {
1579
+ productId: item.productId.toString(),
1580
+ variantId: item.variantId.toString(),
1581
+ fields: {
1582
+ quantity,
1583
+ ...item.stockQuantity != null ? { stockQuantity: sign * item.stockQuantity, unitId: item.unitId?.toString() } : {},
1584
+ ...pool(item.stockVariantId)
1585
+ }
1586
+ }
1587
+ ];
1588
+ const booked = new Set(
1589
+ reservations.filter((reservation) => reservation.lineItemInternalId && reservation.lineItemInternalId === item.internalId).map((reservation) => reservation.componentIndex)
1590
+ );
1591
+ return shelfComponents(item.components).flatMap(({ component, componentIndex, parentUnits }) => {
1592
+ if (booked.has(componentIndex)) return [];
1593
+ if (component.unitId && component.stockQuantity == null)
1594
+ throw new Error(
1595
+ `Composite ${item.productId?.toString()} component ${component.variantId.toString()} is sold in ${component.unitId.toString()} but carries no stockQuantity`
1596
+ );
1597
+ return [
1598
+ {
1599
+ productId: component.productId.toString(),
1600
+ variantId: component.variantId.toString(),
1601
+ componentIndex,
1602
+ fields: {
1603
+ quantity: component.quantity * parentUnits * quantity,
1604
+ ...component.stockQuantity != null ? { stockQuantity: component.stockQuantity * parentUnits * quantity, unitId: component.unitId?.toString() } : {},
1605
+ ...pool(component.stockVariantId),
1606
+ ...item.productId ? { compositeProductId: item.productId.toString() } : {},
1607
+ ...item.name ? { compositeName: item.name } : {}
1608
+ }
1609
+ }
1610
+ ];
1611
+ });
1612
+ }
1613
+ function componentUnitsPerLine(components, index) {
1614
+ const component = components[index];
1615
+ if (!component) throw new Error(`No component ${index} on the line`);
1616
+ if (component.parentIndex == null) return component.quantity;
1617
+ if (component.parentIndex >= index)
1618
+ throw new Error(`Component ${index} points to parent ${component.parentIndex}, which is not before it`);
1619
+ return component.quantity * componentUnitsPerLine(components, component.parentIndex);
1620
+ }
1621
+ var isInnerComposite = (components, index) => components.some((child) => child.parentIndex === index);
1622
+ var shelfComponents = (components) => components.flatMap(
1623
+ (component, componentIndex) => isInnerComposite(components, componentIndex) ? [] : [
1624
+ {
1625
+ component,
1626
+ componentIndex,
1627
+ parentUnits: component.parentIndex == null ? 1 : componentUnitsPerLine(components, component.parentIndex)
1628
+ }
1629
+ ]
1630
+ );
1631
+
1562
1632
  // utils/composite-availability.util.ts
1563
1633
  function poolStockAt(rows, outletId) {
1564
1634
  if (!rows.some((row) => row.manageStock === true)) return null;
@@ -1599,13 +1669,14 @@ function compositeItemUnavailable(item, rows) {
1599
1669
  }
1600
1670
  return compositeVariantInStock(variantId, item.quantity, outlet) ? null : "out_of_stock";
1601
1671
  }
1602
- function compositeMakeable(parts, rows) {
1672
+ function compositeMakeable(parts, rows, inner = /* @__PURE__ */ new Map()) {
1603
1673
  const { outlet } = rows;
1604
1674
  if (!outlet) throw new Error("compositeMakeable counts at one outlet: rows.outlet is required");
1605
- const required = parts.map((part, partIndex) => ({ ...part, partIndex })).filter((part) => part.min > 0);
1675
+ const own = parts.map((part, partIndex) => ({ ...part, partIndex })).filter((part) => part.min > 0);
1606
1676
  const isBookable = (variantId) => rows.bookableProductIds.has(rows.variantProducts.get(String(variantId)) ?? "");
1607
- if (required.some((part) => part.items.some((item) => item.variantId && isBookable(item.variantId))))
1677
+ if (own.some((part) => part.items.some((item) => item.variantId && isBookable(item.variantId))))
1608
1678
  return { byDate: true };
1679
+ const required = own.flatMap((part) => withInnerParts(part, inner, rows, /* @__PURE__ */ new Set()));
1609
1680
  const optionsOf = (item) => (item.categoryId ? rows.categoryVariants.get(String(item.categoryId)) ?? [] : [String(item.variantId)]).flatMap(
1610
1681
  (variantId) => {
1611
1682
  const reason = compositeItemUnavailable({ variantId, quantity: item.quantity }, rows);
@@ -1614,7 +1685,7 @@ function compositeMakeable(parts, rows) {
1614
1685
  const stock = outlet.poolStock.get(shelf.pool);
1615
1686
  const onHand = shelf.unresolved || stock === void 0 ? 0 : stock === null || shelf.backorder ? null : stock;
1616
1687
  const perPick = shelf.unit ? toBase(item.quantity, shelf.unit) : item.quantity;
1617
- return [{ itemId: item.id, pool: shelf.pool, perPick, onHand }];
1688
+ return [{ itemId: item.id, variantId, pool: shelf.pool, perPick, onHand }];
1618
1689
  }
1619
1690
  );
1620
1691
  const counted = required.map((part) => ({ ...part, options: part.items.flatMap(optionsOf) }));
@@ -1632,28 +1703,31 @@ function compositeMakeable(parts, rows) {
1632
1703
  reserved.set(option.pool, (reserved.get(option.pool) ?? 0) + taken * option.perPick);
1633
1704
  wanted -= taken;
1634
1705
  }
1635
- if (wanted > 0) return part.partIndex;
1706
+ if (wanted > 0) return part;
1636
1707
  }
1637
1708
  return void 0;
1638
1709
  };
1639
1710
  const whyRows = [];
1640
1711
  const rowPools = /* @__PURE__ */ new Map();
1712
+ const rowOf = /* @__PURE__ */ new Map();
1641
1713
  const makes = (has, uses) => has === null ? null : Math.floor(has / uses);
1642
1714
  for (const part of counted) {
1643
1715
  const [option] = part.options;
1644
1716
  if (part.options.length === 1) {
1645
1717
  const uses = option.perPick * part.min;
1646
- const row = whyRows.find((candidate) => rowPools.get(candidate) === option.pool);
1647
- if (!row) {
1718
+ const row2 = whyRows.find((candidate) => rowPools.get(candidate) === option.pool);
1719
+ if (!row2) {
1648
1720
  const created = { itemIds: [option.itemId], uses, has: option.onHand, makes: makes(option.onHand, uses) };
1649
1721
  rowPools.set(created, option.pool);
1722
+ rowOf.set(part, created);
1650
1723
  whyRows.push(created);
1651
1724
  continue;
1652
1725
  }
1653
- row.itemIds.push(option.itemId);
1654
- row.uses += uses;
1655
- if (option.onHand === null) row.has = null;
1656
- row.makes = makes(row.has, row.uses);
1726
+ rowOf.set(part, row2);
1727
+ if (!row2.itemIds.includes(option.itemId)) row2.itemIds.push(option.itemId);
1728
+ row2.uses += uses;
1729
+ if (option.onHand === null) row2.has = null;
1730
+ row2.makes = makes(row2.has, row2.uses);
1657
1731
  continue;
1658
1732
  }
1659
1733
  const perPool = /* @__PURE__ */ new Map();
@@ -1661,13 +1735,19 @@ function compositeMakeable(parts, rows) {
1661
1735
  perPool.set(candidate.pool, Math.max(perPool.get(candidate.pool) ?? 0, picksLeft(candidate, /* @__PURE__ */ new Map())));
1662
1736
  const total = [...perPool.values()].reduce((sum, picks) => sum + picks, 0);
1663
1737
  const has = total === Infinity ? null : total;
1664
- whyRows.push({
1665
- itemIds: part.items.map((item) => item.id),
1738
+ const row = {
1739
+ itemIds: [...new Set(part.items.map((item) => item.id))],
1666
1740
  partIndex: part.partIndex,
1667
1741
  uses: part.min,
1668
1742
  has,
1669
1743
  makes: makes(has, part.min)
1670
- });
1744
+ };
1745
+ rowOf.set(part, row);
1746
+ whyRows.push(row);
1747
+ }
1748
+ for (const row of new Set(counted.filter((part) => part.inner).map((part) => rowOf.get(part)))) {
1749
+ const rowParts = counted.filter((part) => rowOf.get(part) === row);
1750
+ row.variantIds = [...new Set(rowParts.flatMap((part) => part.options.map((option) => option.variantId)))];
1671
1751
  }
1672
1752
  if (counted.every((part) => part.options.some((option) => option.onHand === null)))
1673
1753
  return { count: null, rows: whyRows };
@@ -1683,12 +1763,29 @@ function compositeMakeable(parts, rows) {
1683
1763
  else high = mid - 1;
1684
1764
  }
1685
1765
  const short = shortAt(low + 1);
1686
- const shortPart = counted.find((part) => part.partIndex === short);
1687
- const limitedBy = whyRows.findIndex(
1688
- (row) => shortPart?.options.length === 1 ? row.partIndex === void 0 && row.itemIds.includes(shortPart.options[0].itemId) : row.partIndex === short
1689
- );
1766
+ const limitedBy = short ? whyRows.indexOf(rowOf.get(short)) : -1;
1690
1767
  return { count: low, rows: whyRows, ...limitedBy >= 0 ? { limitedBy } : {} };
1691
1768
  }
1769
+ function withInnerParts(part, inner, rows, seen) {
1770
+ const [item] = part.items;
1771
+ const variantId = String(item?.variantId);
1772
+ const innerParts = part.items.length === 1 && item.variantId ? inner.get(variantId) : void 0;
1773
+ const reason = innerParts && compositeItemUnavailable({ variantId, quantity: item.quantity }, rows);
1774
+ if (!innerParts || seen.has(variantId) || reason && reason !== "out_of_stock") return [part];
1775
+ return innerParts.filter((innerPart) => innerPart.min > 0).flatMap(
1776
+ (innerPart) => withInnerParts(
1777
+ {
1778
+ ...part,
1779
+ inner: true,
1780
+ min: part.min * item.quantity * innerPart.min,
1781
+ items: innerPart.items.map((innerItem) => ({ ...innerItem, id: item.id }))
1782
+ },
1783
+ inner,
1784
+ rows,
1785
+ new Set(seen).add(variantId)
1786
+ )
1787
+ );
1788
+ }
1692
1789
  var poolOf = (line) => line.stockVariantId || line.variantId;
1693
1790
  function poolDemand(lines) {
1694
1791
  const demand = /* @__PURE__ */ new Map();
@@ -1697,7 +1794,9 @@ function poolDemand(lines) {
1697
1794
  (demand.get(poolOf(line)) ?? 0) + (line.unit ? toBase(line.quantity * times, line.unit) : line.quantity * times)
1698
1795
  );
1699
1796
  for (const line of lines) {
1700
- if (line.components) for (const component of line.components) add(component, line.quantity);
1797
+ if (line.components)
1798
+ for (const { component, parentUnits } of shelfComponents(line.components))
1799
+ add(component, line.quantity * parentUnits);
1701
1800
  else add(line, 1);
1702
1801
  }
1703
1802
  return demand;
@@ -1739,47 +1838,76 @@ function compositeReservationMismatches(order) {
1739
1838
  });
1740
1839
  }
1741
1840
 
1742
- // utils/line-stock-moves.util.ts
1743
- function lineStockMoves(item, quantity, reservations = []) {
1744
- const sign = Math.sign(quantity);
1745
- const pool = (stockVariantId) => stockVariantId ? { stockVariantId: stockVariantId.toString() } : {};
1746
- if (!item.components?.length)
1747
- return [
1748
- {
1749
- productId: item.productId.toString(),
1750
- variantId: item.variantId.toString(),
1751
- fields: {
1752
- quantity,
1753
- ...item.stockQuantity != null ? { stockQuantity: sign * item.stockQuantity, unitId: item.unitId?.toString() } : {},
1754
- ...pool(item.stockVariantId)
1755
- }
1756
- }
1757
- ];
1758
- const booked = new Set(
1759
- reservations.filter((reservation) => reservation.lineItemInternalId && reservation.lineItemInternalId === item.internalId).map((reservation) => reservation.componentIndex)
1760
- );
1761
- return item.components.flatMap((component, componentIndex) => {
1762
- if (booked.has(componentIndex)) return [];
1763
- if (component.unitId && component.stockQuantity == null)
1764
- throw new Error(
1765
- `Composite ${item.productId?.toString()} component ${component.variantId.toString()} is sold in ${component.unitId.toString()} but carries no stockQuantity`
1766
- );
1767
- return [
1768
- {
1769
- productId: component.productId.toString(),
1770
- variantId: component.variantId.toString(),
1771
- componentIndex,
1772
- fields: {
1773
- quantity: component.quantity * quantity,
1774
- ...component.stockQuantity != null ? { stockQuantity: component.stockQuantity * quantity, unitId: component.unitId?.toString() } : {},
1775
- ...pool(component.stockVariantId),
1776
- ...item.productId ? { compositeProductId: item.productId.toString() } : {},
1777
- ...item.name ? { compositeName: item.name } : {}
1778
- }
1779
- }
1780
- ];
1841
+ // utils/variant-cost.util.ts
1842
+ function variantCostAtSale({
1843
+ costPrice,
1844
+ costPriceUpdatedAt,
1845
+ landedCost,
1846
+ lastReceivedAt
1847
+ }) {
1848
+ if (landedCost == null) return costPrice ?? null;
1849
+ if (costPrice == null) return landedCost;
1850
+ if (!costPriceUpdatedAt || !lastReceivedAt) return costPrice;
1851
+ return new Date(lastReceivedAt).getTime() > new Date(costPriceUpdatedAt).getTime() ? landedCost : costPrice;
1852
+ }
1853
+ function compositeCostOfKnown(items) {
1854
+ const known = items.filter((item) => item.cost !== null);
1855
+ if (!known.length) return null;
1856
+ return known.reduce((sum, { cost, quantity }) => sum + extendPrice(cost, quantity), 0);
1857
+ }
1858
+ function compositeCostRange(parts) {
1859
+ const missing = new Set(parts.flatMap((part) => part.options.flatMap((option) => option.missing)));
1860
+ const [low, high] = [pickedEnd(parts, "low"), pickedEnd(parts, "high")];
1861
+ const [lowCost, highCost] = [low.length ? compositeCostOfKnown(low) : 0, compositeCostOfKnown(high)];
1862
+ return { range: lowCost === null || highCost === null ? null : [lowCost, highCost], missing: [...missing] };
1863
+ }
1864
+ function innerCompositeOption(name, quantity, cost) {
1865
+ const [low, high] = cost.range ?? [null, null];
1866
+ return { name, quantity, low, high, missing: cost.range === null && !cost.missing.length ? [name] : cost.missing };
1867
+ }
1868
+ function variantLabel(variant, variantCount) {
1869
+ if (variantCount === 1) return "";
1870
+ const attributes = (variant.attributes ?? []).map((attribute) => attribute.value ?? attribute.values?.[0] ?? "");
1871
+ return attributes.filter(Boolean).join(" / ") || variant.name || variant.sku || "";
1872
+ }
1873
+ function variantDisplayName(productName, variant, variantCount) {
1874
+ const label = variantLabel(variant, variantCount);
1875
+ return label ? `${productName} \xB7 ${label}` : productName;
1876
+ }
1877
+ function pickedEnd(parts, end) {
1878
+ return parts.flatMap((part) => {
1879
+ if (!part.options.length) return [];
1880
+ 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));
1881
+ const pick = (end === "low" ? byCost[0] : byCost[byCost.length - 1]) ?? { cost: null, quantity: 1 };
1882
+ return Array(end === "low" ? part.minPicks : part.maxPicks).fill(pick);
1781
1883
  });
1782
1884
  }
1885
+ function costPriceChangeStamp(next, stored) {
1886
+ if (next === void 0 || next === (stored ?? null)) return {};
1887
+ return { costPriceUpdatedAt: /* @__PURE__ */ new Date() };
1888
+ }
1889
+ function bankersRoundDiv(numerator, denominator) {
1890
+ if (denominator === 0n) return 0n;
1891
+ const negative = numerator < 0n !== denominator < 0n;
1892
+ const n = numerator < 0n ? -numerator : numerator;
1893
+ const d = denominator < 0n ? -denominator : denominator;
1894
+ const quotient = n / d;
1895
+ const twiceRemainder = n % d * 2n;
1896
+ let result;
1897
+ if (twiceRemainder < d) {
1898
+ result = quotient;
1899
+ } else if (twiceRemainder > d) {
1900
+ result = quotient + 1n;
1901
+ } else {
1902
+ result = quotient % 2n === 0n ? quotient : quotient + 1n;
1903
+ }
1904
+ return negative ? -result : result;
1905
+ }
1906
+ function landedCostPerUnit(landedValue, baseQuantity, ratioToBase = 1) {
1907
+ return Number(bankersRoundDiv(BigInt(Math.round(landedValue * ratioToBase)), BigInt(baseQuantity)));
1908
+ }
1909
+ var bookCostPerUnit = (book, ratioToBase) => book && book.totalQuantity > 0 && ratioToBase ? landedCostPerUnit(book.totalLandedValue, book.totalQuantity, ratioToBase) : null;
1910
+ var marginPercentOf = (grossProfit, costedGross) => grossProfit === null || !costedGross ? null : grossProfit * 100 / costedGross;
1783
1911
 
1784
1912
  // units/family-code.ts
1785
1913
  var MAX_SLUG_LENGTH = 32;
@@ -4256,11 +4384,14 @@ export {
4256
4384
  ancestorChain,
4257
4385
  applyAssignment,
4258
4386
  assertUnitSane,
4387
+ attachResolvedUnits,
4259
4388
  availableIn,
4389
+ bankersRoundDiv,
4260
4390
  baseFor,
4261
4391
  baseFulfillmentDefinitions,
4262
4392
  baseOf,
4263
4393
  basePaymentDefinitions,
4394
+ bookCostPerUnit,
4264
4395
  buildAvailability,
4265
4396
  buildGrid,
4266
4397
  buildOrderContext,
@@ -4270,6 +4401,9 @@ export {
4270
4401
  canTransition,
4271
4402
  cheapestCompositeItem,
4272
4403
  cheapestCompositePrice,
4404
+ componentUnitsPerLine,
4405
+ compositeCostOfKnown,
4406
+ compositeCostRange,
4273
4407
  compositeItemCost,
4274
4408
  compositeItemUnavailable,
4275
4409
  compositeMakeable,
@@ -4278,6 +4412,7 @@ export {
4278
4412
  compositeVariantInStock,
4279
4413
  conditionSummary,
4280
4414
  convertFixedFeeToLocalCurrency,
4415
+ costPriceChangeStamp,
4281
4416
  createAmount,
4282
4417
  crossAxisRuleApplies,
4283
4418
  currentAssignees,
@@ -4315,6 +4450,7 @@ export {
4315
4450
  hasSellableChoice,
4316
4451
  holdExpiresAt,
4317
4452
  inferStatesFromLegacyStatus,
4453
+ innerCompositeOption,
4318
4454
  isAdyenRolloutCountry,
4319
4455
  isAffirmCountry,
4320
4456
  isAffirmPricePlan,
@@ -4322,16 +4458,19 @@ export {
4322
4458
  isConditionOperator,
4323
4459
  isFulfillmentState,
4324
4460
  isInCart,
4461
+ isInnerComposite,
4325
4462
  isPaymentState,
4326
4463
  isSupportedCurrency,
4327
4464
  isSystemFamilyCode,
4328
4465
  isValidQuantity,
4329
4466
  isWhole,
4467
+ landedCostPerUnit,
4330
4468
  lineStockMoves,
4331
4469
  listCountries,
4332
4470
  listProvinces,
4333
4471
  listShippingCountries,
4334
4472
  mapToLegacyStatus,
4473
+ marginPercentOf,
4335
4474
  maxPrecisionFor,
4336
4475
  mergeFragment,
4337
4476
  modifiersSellable,
@@ -4366,6 +4505,7 @@ export {
4366
4505
  roundToPrecision,
4367
4506
  sameFamily,
4368
4507
  setOrderState,
4508
+ shelfComponents,
4369
4509
  shipsToCountry,
4370
4510
  shopDayKey,
4371
4511
  shopDayRange,
@@ -4379,6 +4519,9 @@ export {
4379
4519
  validateFragmentCompatibility,
4380
4520
  validateOrderStatuses,
4381
4521
  validateShippingZone,
4522
+ variantCostAtSale,
4523
+ variantDisplayName,
4524
+ variantLabel,
4382
4525
  violatesFinancialInvariant,
4383
4526
  windowEndsAt,
4384
4527
  withinPresence