@managesome/eposmatic-toolkit 0.2.720 → 0.2.721

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.
@@ -5,18 +5,6 @@ export interface IOrderEngineOption extends Omit<IModifierOption, 'modifiers' |
5
5
  loyalty_applied: boolean;
6
6
  voucher_applied: boolean;
7
7
  price: number;
8
- /**
9
- * The price the engine assigned to this option when the item was built
10
- * (the catalog/definition value — NOT a persisted order value). It is the
11
- * engine's own memory for reversible price normalization such as
12
- * `choose_expensive_segment_price`: normalizing re-bases each option from
13
- * here first, so the rule can raise AND lower across selection changes
14
- * without any caller having to keep a pristine copy of the item.
15
- *
16
- * Optionally absent (e.g. hand-built engine items): callers that normalize
17
- * prices should then pass an explicit `basePrices` map instead.
18
- */
19
- base_price?: number;
20
8
  quantity: number;
21
9
  modifiers: IOrderEngineModifier[];
22
10
  }
@@ -25,6 +13,31 @@ export interface IOrderEngineModifier extends Omit<IModifier, 'options'> {
25
13
  default: boolean;
26
14
  options: IOrderEngineOption[];
27
15
  }
16
+ /**
17
+ * Original (definition) price of every engine option, keyed by its OPTION
18
+ * PATH: the `_`-joined chain of modifier/option ids from the root — the same
19
+ * identifier format used by `setCheckFieldInOrderEngineItem` and the
20
+ * flattened modifiers (all ids are BSON ObjectIds, so `_` cannot appear
21
+ * inside one). Examples:
22
+ * - standalone half-half segment option: `seg-1_milan`
23
+ * - option of a half-half nested in a special: `mod-pizza_halfhalf-1_seg-1_milan`
24
+ * - option inside a required modifier group: `mod-roma_size-mod_large-13`
25
+ *
26
+ * Engine price normalization (`choose_expensive_segment_price`) only ever
27
+ * mutates `price`, so this map is a COMPLETE reference of the original state:
28
+ * re-basing from it before every re-apply keeps the rule reversible (raise
29
+ * AND lower) while selections stay untouched.
30
+ */
31
+ export type TOrderEnginePriceReferences = Record<string, number>;
32
+ /**
33
+ * Return of `convertCatalogItemToOrderEngineItem`: the immutable original
34
+ * price references plus the item the UI edits (working data). The references
35
+ * are never mutated; every normalization reads them to restore prices first.
36
+ */
37
+ export interface IOrderEngineItemState {
38
+ originalPriceReferences: TOrderEnginePriceReferences;
39
+ workingData: IOrderEngineItem;
40
+ }
28
41
  export interface IOrderEngineItem {
29
42
  _id: string;
30
43
  category_id: string;
@@ -179,11 +179,11 @@ function convertHalfHalfSetupToWorkableHalfHalfSetup(halfhalfSetups, itemsMap, p
179
179
  // from the selectable list (same semantics as specials' excluded_refs).
180
180
  .filter((setupItem) => !halfhalfSetup.excluded_refs.includes(setupItem.item_id))
181
181
  .sort((a, b) => a.sort_id - b.sort_id);
182
- // Workable segment entries: divided base price + own upsell applied below.
183
- // `choose_expensive_segment_price` is NOT applied here: it depends on which
184
- // halves the user picks and must be able to lower prices again, so it runs
185
- // at selection/display/submit time on the engine item with pristine
186
- // `basePrices` (see `applyChooseExpensiveSegmentPrice`).
182
+ // Workable segment entries: divided base price + own upsell. The
183
+ // expensive-segment rule is NOT baked in here: it depends on the current
184
+ // selection, so it runs on the engine working data (classic drawer and
185
+ // `convertHalfHalfToOrderEngineItem`) against the definition prices as
186
+ // the original references.
187
187
  const entries = [];
188
188
  for (let j = 0; j < halfhalfItems.length; j++) {
189
189
  const item = halfhalfItems[j];
@@ -539,29 +539,30 @@ function convertHalfHalfToOrderItem({ halfHalfItem, selectedHalfHalfItems, quant
539
539
  */
540
540
  function convertHalfHalfToOrderEngineItem({ halfHalfItem, selectedHalfHalfItems, quantity, platform, existingOrderItem, orderItemId, chooseExpensiveSegmentPrice, }) {
541
541
  let menu_id;
542
- /**
543
- * Definition prices of the SEGMENT ITEM (its own price + nested modifier
544
- * option prices). The selected per-segment order items can carry prices
545
- * raised by a previous `choose_expensive_segment_price` normalization (edit
546
- * flow, de-structured line), so the engine stamps THIS baseline as its own
547
- * memory `base_price` — re-apply can then raise AND lower.
548
- */
549
- const getSegmentItemBasePrices = (itemId) => {
550
- const workableItem = halfHalfItem.items.find((item) => item._id === itemId);
551
- return workableItem == null ? {} : (0, order_engine_1.getOptionPriceMapFromItem)(workableItem, platform);
552
- };
553
- const getWorkableItemPrice = (itemId) => {
554
- const workableItem = halfHalfItem.items.find((item) => item._id === itemId);
555
- return workableItem == null ? undefined : (0, platform_catalog_1.getPriceEnum)(workableItem.price, platform);
542
+ // Original (definition) prices for the assembled engine tree, keyed by the
543
+ // same option path the engine uses (`seg-1_milan`,
544
+ // `seg-1_milan_size-mod_large-13`). The selected per-segment items can carry
545
+ // prices raised by an earlier normalization (an edit de-structures them from
546
+ // the persisted line), so the baseline MUST come from the workable
547
+ // definition instead of the selected item price.
548
+ const originalPriceReferences = {};
549
+ const addDefinitionReferences = (modifiers, parentPath) => {
550
+ (modifiers ?? []).forEach((modifier) => {
551
+ const modifierPath = parentPath ? `${parentPath}_${modifier._id}` : modifier._id;
552
+ (modifier.options ?? []).forEach((option) => {
553
+ const optionPath = `${modifierPath}_${option._id}`;
554
+ originalPriceReferences[optionPath] = (0, platform_catalog_1.getPriceEnum)(option.price, platform);
555
+ addDefinitionReferences(option.modifiers, optionPath);
556
+ });
557
+ });
556
558
  };
557
- const toEngineModifiers = (modifiers, depth, basePrices) => (modifiers ?? []).map((modifier) => {
559
+ const toEngineModifiers = (modifiers, depth) => (modifiers ?? []).map((modifier) => {
558
560
  const options = modifier.options ?? [];
559
561
  const engineOptions = options.map((option) => ({
560
562
  _id: option._id,
561
563
  ref: option.ref,
562
564
  name: option.name,
563
565
  price: option.price,
564
- base_price: basePrices[option._id] ?? option.price,
565
566
  quantity: option.quantity || 1,
566
567
  is_free: option.is_free ?? false,
567
568
  default: true,
@@ -571,7 +572,7 @@ function convertHalfHalfToOrderEngineItem({ halfHalfItem, selectedHalfHalfItems,
571
572
  sold_out: [],
572
573
  sort_id: 0,
573
574
  excluded_platforms: [],
574
- modifiers: toEngineModifiers(option.modifiers, depth + 1, basePrices),
575
+ modifiers: toEngineModifiers(option.modifiers, depth + 1),
575
576
  }));
576
577
  return {
577
578
  _id: modifier._id,
@@ -597,16 +598,18 @@ function convertHalfHalfToOrderEngineItem({ halfHalfItem, selectedHalfHalfItems,
597
598
  menu_id = selectedItem.menu_id;
598
599
  }
599
600
  const segment = halfHalfItem.segments[s];
600
- const segmentBasePrices = getSegmentItemBasePrices(selectedItem.item_id);
601
+ const definitionItem = halfHalfItem.items.find((item) => item._id === selectedItem.item_id);
602
+ const segmentPath = `${segment?._id ?? halfHalfItem._id}_${selectedItem.item_id}`;
603
+ if (definitionItem != null) {
604
+ originalPriceReferences[segmentPath] = (0, platform_catalog_1.getPriceEnum)(definitionItem.price, platform);
605
+ addDefinitionReferences(definitionItem.modifiers, segmentPath);
606
+ }
601
607
  const segmentOptions = [
602
608
  {
603
609
  _id: selectedItem.item_id,
604
610
  ref: selectedItem.item_id,
605
611
  name: selectedItem.name,
606
612
  price: selectedItem.price,
607
- // Definition price, not the (possibly previously raised) selected
608
- // order item price — see `getSegmentItemBasePrices`.
609
- base_price: getWorkableItemPrice(selectedItem.item_id) ?? selectedItem.price,
610
613
  quantity: selectedItem.quantity || 1,
611
614
  is_free: false,
612
615
  default: true,
@@ -616,7 +619,7 @@ function convertHalfHalfToOrderEngineItem({ halfHalfItem, selectedHalfHalfItems,
616
619
  sold_out: [],
617
620
  sort_id: 0,
618
621
  excluded_platforms: [],
619
- modifiers: toEngineModifiers(selectedItem.modifiers, 1, segmentBasePrices),
622
+ modifiers: toEngineModifiers(selectedItem.modifiers, 1),
620
623
  },
621
624
  ];
622
625
  const segmentModifier = {
@@ -667,7 +670,7 @@ function convertHalfHalfToOrderEngineItem({ halfHalfItem, selectedHalfHalfItems,
667
670
  };
668
671
  const syncedOrderEngineItem = (0, order_engine_1.syncOrderEngineItem)(orderEngineItem);
669
672
  if (chooseExpensiveSegmentPrice === true) {
670
- return (0, order_engine_1.applyChooseExpensiveSegmentPrice)(syncedOrderEngineItem);
673
+ return (0, order_engine_1.applyChooseExpensiveSegmentPrice)(syncedOrderEngineItem, { originalPriceReferences });
671
674
  }
672
675
  return syncedOrderEngineItem;
673
676
  }
@@ -1,59 +1,55 @@
1
1
  import { ORDER_ITEM_TYPE_ENUM, PLATFORMS_ENUM } from '../../constants';
2
2
  import { IDiscountDetails, IGiftCard, IItem, IModifier, IOffer, IOrderItem, IPrice } from '../../schemas';
3
3
  import { ISimplifiedCatalogItem } from '../types';
4
- import { IOrderEngineItem, IOrderEngineModifier, IOrderEngineOption } from '../types/order-engine';
4
+ import { IOrderEngineItem, IOrderEngineItemState, IOrderEngineModifier, IOrderEngineOption, TOrderEnginePriceReferences } from '../types/order-engine';
5
5
  export declare function hasMissedRequiredItemModifier(currentModifiers: IModifier[] | null, platform: PLATFORMS_ENUM | undefined): boolean;
6
6
  export declare function syncOrderEngineItem(orderEngineItem: IOrderEngineItem): IOrderEngineItem;
7
7
  export declare function checkIfModifiersExist(modifiers: IModifier[] | null, platform: PLATFORMS_ENUM | undefined): boolean;
8
8
  export declare function makeSpaceForFreeOptions(options: IOrderEngineOption[], num_free_options: number | null | undefined): IOrderEngineOption[];
9
- /**
10
- * OPTIONAL override of the pristine-price baseline for
11
- * `choose_expensive_segment_price`.
12
- *
13
- * The engine normally re-bases itself from the `base_price` stamped on every
14
- * option when the item was built (its own memory — see `IOrderEngineOption`),
15
- * so re-applying the rule after a selection change can LOWER prices again and
16
- * callers never have to keep a pristine copy of the item. Pass `basePrices`
17
- * only when the baseline must come from somewhere else (e.g. a pre-computed
18
- * `_id -> price` map); it takes precedence over the stamps.
19
- */
20
- export interface IChooseExpensiveSegmentPriceOptions {
21
- basePrices?: Record<string, number>;
22
- }
23
9
  /**
24
10
  * Applies `choose_expensive_segment_price` to an order engine item converted
25
11
  * from a half-half setup (top-level modifier groups = segments, single-select
26
12
  * each, only 2 or 4 segments).
27
13
  *
28
- * The rule is a pure function of the CURRENT selection: the most expensive
29
- * half the user actually picked sets the charged price for every picked half
30
- * (cheaper halves are raised to it; picking a cheaper combination later
31
- * lowers them again). It cannot run during `IHalfHalfSetup -> IItem`
32
- * conversion — it runs at display/submit time on the engine item, re-basing
33
- * every price from the engine's own memory (the `base_price` stamped at
34
- * conversion) so the result NEVER accumulates raises, even when the item is
35
- * mutated in place across selection changes. `basePrices` can override that
36
- * baseline (see `IChooseExpensiveSegmentPriceOptions`).
14
+ * The expensive rule depends on which halves the user actually picked, so it
15
+ * cannot run during `IHalfHalfSetup -> IItem` conversion — it must run after
16
+ * selection, on the WORKING data. When `originalPriceReferences` is provided,
17
+ * every option price is first re-based from that immutable reference, which
18
+ * makes the rule fully reversible: picking a cheaper pair afterwards restores
19
+ * the previous (raised) prices instead of accumulating them.
37
20
  *
38
21
  * Rule: `price = base + upsell` — the item (option) level upsell is already
39
22
  * baked into the option price at conversion. choose_expensive compares every
40
- * SELECTED segment option (option price + required/price-defining modifier
41
- * prices — e.g. a "Pizza Size" group whose Small/Large/X-Large options are
42
- * part of the item's price) and raises the cheaper ones so their final
43
- * segment price matches the most expensive selected half. The raise is
44
- * applied to the FIRST PRICED element along the segment's price chain: the
45
- * segment option's own price when non-zero, else the first priced required
46
- * leaf ("First Half -> ROMA -> Pizza Size -> Large 13\"") — see
47
- * `findRaiseTarget`. Optional/upsell modifier groups are excluded: they add
48
- * on top and must not influence the comparison. The IHalfHalfSetup level
49
- * upsell is NOT part of this rule: it is the converted item's own price and
50
- * is added once on top of the combined subtotal.
23
+ * segment option (option price + required/price-defining modifier prices —
24
+ * e.g. a "Pizza Size" group whose Small/Large/X-Large options are part of the
25
+ * item's price) and levels the cheaper ones to the most expensive SELECTED
26
+ * half — `A($5)+B($5)` charges 5+5, `B($5)+C($6)` charges 6+6, and switching
27
+ * `C+D -> A+B` lowers them again. Unselected options are levelled too, so the
28
+ * drawer can SHOW what an option would cost before it is picked (they never
29
+ * contribute to totals while unselected). The raise is applied to the FIRST
30
+ * PRICED element along the segment's price chain: the segment option's own
31
+ * price when non-zero, else the first priced required leaf ("First Half ->
32
+ * ROMA -> Pizza Size -> Large 13"") — see `findRaiseTarget`. Optional/upsell
33
+ * modifier groups are excluded: they add on top and must not influence the
34
+ * comparison. The IHalfHalfSetup level upsell is NOT part of this rule: it is
35
+ * the converted item's own price and is added once on top of the combined
36
+ * subtotal. Free (`is_free`) options never drive the comparison and are never
37
+ * raised.
51
38
  *
52
39
  * All prices here are plain numbers (engine-priced).
53
40
  *
54
- * Returns the item unchanged when nothing changes.
41
+ * Returns the item unchanged when no segment option is selected (only
42
+ * re-based when references were provided).
43
+ */
44
+ export declare function applyChooseExpensiveSegmentPrice(orderEngineItem: IOrderEngineItem, options?: {
45
+ originalPriceReferences?: TOrderEnginePriceReferences;
46
+ }): IOrderEngineItem;
47
+ /**
48
+ * Records the ORIGINAL price of every option in the engine tree, keyed by its
49
+ * option path (see `TOrderEnginePriceReferences`). One walk, no copies — the
50
+ * map is the engine's memory for reversible price normalization.
55
51
  */
56
- export declare function applyChooseExpensiveSegmentPrice(orderEngineItem: IOrderEngineItem, options?: IChooseExpensiveSegmentPriceOptions): IOrderEngineItem;
52
+ export declare function getOrderEnginePriceReferences(orderEngineItem: IOrderEngineItem): TOrderEnginePriceReferences;
57
53
  /**
58
54
  * True when the item has a top-level modifier group option that is a nested
59
55
  * half-half (ref_type HALF_HALF) with its setup's choose_expensive flag.
@@ -62,52 +58,16 @@ export declare function hasFlaggedHalfHalfOption(orderEngineItem: IOrderEngineIt
62
58
  /**
63
59
  * `choose_expensive_segment_price` for a half-half option nested in a special:
64
60
  * the option's own top-level modifiers are its segment groups, so they get the
65
- * same raise-to-most-expensive treatment as a standalone half-half item.
66
- * ITEM options are terminal (their nested modifiers can never contain
67
- * ITEM/HALF_HALF); normal options pass untouched. Runs on a copy with pristine
68
- * `basePrices` when provided (see `IChooseExpensiveSegmentPriceOptions`).
69
- */
70
- export declare function applyNestedChooseExpensiveSegmentPrice(orderEngineItem: IOrderEngineItem, options?: IChooseExpensiveSegmentPriceOptions): IOrderEngineItem;
71
- /**
72
- * Builds a pristine `_id -> price` map of every option in a converted catalog
73
- * item (`modifiers -> options -> nested modifiers -> options ...`). Used as
74
- * the baseline for `choose_expensive_segment_price` so applying the rule never
75
- * depends on previously raised prices.
76
- *
77
- * The flat `_id -> price` shape can only represent ONE value per option
78
- * `_id`, so callers MUST keep the map to a single price scope. A half-half
79
- * nested in a special is exactly the case where that fails: its segment
80
- * options are built FROM the special's items, so they reuse the SAME `_id`s
81
- * as the special's top-level options while their prices differ (top-level =
82
- * full upsell, segment = per-segment share). `nestedHalfHalfSegmentsOnly`
83
- * keeps the map to the subtrees of HALF_HALF options (the segment trees plus
84
- * their nested modifiers), excluding top-level option prices — the special
85
- * drawer feeds this map to `resetOrderEngineItemPrices` / the nested
86
- * normalization, so the walk order of the item can never leak a top-level
87
- * price into a segment (or the other way around). Standalone half-half items
88
- * are a single scope: every segment shares its option `_id`s with the SAME
89
- * price, so the unscoped map is safe there.
90
- */
91
- export declare function getOptionPriceMapFromItem(item: IItem | ISimplifiedCatalogItem, platform: PLATFORMS_ENUM | null | undefined, options?: {
92
- nestedHalfHalfSegmentsOnly?: boolean;
93
- }): Record<string, number>;
94
- /**
95
- * Re-bases every engine option price from the engine's own memory (the
96
- * `base_price` stamped at conversion), optionally overridden by an explicit
97
- * `basePrices` map. Called when a drawer builds the engine item so state
98
- * (sidebar prices, edit baselines) never carries a previous normalization.
61
+ * same level-to-the-most-expensive-SELECTED-half treatment as a standalone
62
+ * half-half item. ITEM options are terminal (their nested modifiers can never
63
+ * contain ITEM/HALF_HALF); normal options pass untouched.
99
64
  *
100
- * `options.nestedHalfHalfOnly` restricts the reset to the subtrees of
101
- * HALF_HALF options — the exact scope `getOptionPriceMapFromItem` builds when
102
- * called with `nestedHalfHalfSegmentsOnly`. Only needed when an external
103
- * `basePrices` map is passed (a special's top-level options reuse their `_id`s
104
- * at different prices, so a blanket reset with the scoped map would push the
105
- * segment share onto the top-level option). With the engine's own stamps the
106
- * scope is inherent — pass the SAME scope to the map builder and to this
107
- * reset when you do pass a map.
65
+ * When `originalPriceReferences` is provided, prices are re-based first — but
66
+ * ONLY inside the flagged half-half subtrees, so the special's own option
67
+ * prices keep whatever the conversion produced.
108
68
  */
109
- export declare function resetOrderEngineItemPrices(orderEngineItem: IOrderEngineItem, basePrices?: Record<string, number>, options?: {
110
- nestedHalfHalfOnly?: boolean;
69
+ export declare function applyNestedChooseExpensiveSegmentPrice(orderEngineItem: IOrderEngineItem, options?: {
70
+ originalPriceReferences?: TOrderEnginePriceReferences;
111
71
  }): IOrderEngineItem;
112
72
  export type IOrderEngineItemRewardClaim = {
113
73
  type: 'offer';
@@ -155,7 +115,7 @@ interface IConvertCatalogItemToOrderEngineItemParams {
155
115
  defaultMenuId: string | null;
156
116
  soldoutModifiers: string[];
157
117
  }
158
- export declare function convertCatalogItemToOrderEngineItem({ item, orderItem, platform, tenantId, excludeRefs, excludedDiscountRefs, zeroPriceRefs, orderItemType, applyLoyalty, applyVoucher, keepOptionalModifiersAtBottom, defaultMenuId, soldoutModifiers, }: IConvertCatalogItemToOrderEngineItemParams): IOrderEngineItem;
118
+ export declare function convertCatalogItemToOrderEngineItem({ item, orderItem, platform, tenantId, excludeRefs, excludedDiscountRefs, zeroPriceRefs, orderItemType, applyLoyalty, applyVoucher, keepOptionalModifiersAtBottom, defaultMenuId, soldoutModifiers, }: IConvertCatalogItemToOrderEngineItemParams): IOrderEngineItemState;
159
119
  export declare function hasRequiredModifier<T extends IModifier | IOrderEngineModifier>(currentModifiers: T[] | null): boolean;
160
120
  export declare function convertItemToOrderItem(item: IItem | ISimplifiedCatalogItem, menu_id: string | null, platform: PLATFORMS_ENUM | undefined, tenantId: string, orderItemType?: ORDER_ITEM_TYPE_ENUM): IOrderItem;
161
121
  export declare function setCheckFieldInOrderEngineItem(orderEngineItem: IOrderEngineItem, identifier: string, shouldCheck: boolean, chooseExpensiveSegmentPrice?: boolean): IOrderEngineItem;