@managesome/eposmatic-toolkit 0.2.719 → 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.
@@ -13,6 +13,31 @@ export interface IOrderEngineModifier extends Omit<IModifier, 'options'> {
13
13
  default: boolean;
14
14
  options: IOrderEngineOption[];
15
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
+ }
16
41
  export interface IOrderEngineItem {
17
42
  _id: string;
18
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,6 +539,23 @@ function convertHalfHalfToOrderItem({ halfHalfItem, selectedHalfHalfItems, quant
539
539
  */
540
540
  function convertHalfHalfToOrderEngineItem({ halfHalfItem, selectedHalfHalfItems, quantity, platform, existingOrderItem, orderItemId, chooseExpensiveSegmentPrice, }) {
541
541
  let menu_id;
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
+ });
558
+ };
542
559
  const toEngineModifiers = (modifiers, depth) => (modifiers ?? []).map((modifier) => {
543
560
  const options = modifier.options ?? [];
544
561
  const engineOptions = options.map((option) => ({
@@ -581,6 +598,12 @@ function convertHalfHalfToOrderEngineItem({ halfHalfItem, selectedHalfHalfItems,
581
598
  menu_id = selectedItem.menu_id;
582
599
  }
583
600
  const segment = halfHalfItem.segments[s];
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
+ }
584
607
  const segmentOptions = [
585
608
  {
586
609
  _id: selectedItem.item_id,
@@ -647,7 +670,7 @@ function convertHalfHalfToOrderEngineItem({ halfHalfItem, selectedHalfHalfItems,
647
670
  };
648
671
  const syncedOrderEngineItem = (0, order_engine_1.syncOrderEngineItem)(orderEngineItem);
649
672
  if (chooseExpensiveSegmentPrice === true) {
650
- return (0, order_engine_1.applyChooseExpensiveSegmentPrice)(syncedOrderEngineItem);
673
+ return (0, order_engine_1.applyChooseExpensiveSegmentPrice)(syncedOrderEngineItem, { originalPriceReferences });
651
674
  }
652
675
  return syncedOrderEngineItem;
653
676
  }
@@ -1,54 +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 pristine-price baseline for `choose_expensive_segment_price`.
11
- * When provided, every option price is first restored from this map (keyed by
12
- * option `_id`) before the rule runs — so re-applying it after a selection
13
- * change can LOWER prices again (the rule is a pure function of the current
14
- * selection, not an accumulating raise).
15
- */
16
- export interface IChooseExpensiveSegmentPriceOptions {
17
- basePrices?: Record<string, number>;
18
- }
19
9
  /**
20
10
  * Applies `choose_expensive_segment_price` to an order engine item converted
21
11
  * from a half-half setup (top-level modifier groups = segments, single-select
22
12
  * each, only 2 or 4 segments).
23
13
  *
24
- * The rule is a pure function of the CURRENT selection: the most expensive
25
- * half the user actually picked sets the charged price for every picked half
26
- * (cheaper halves are raised to it; picking a cheaper combination later
27
- * lowers them again). It cannot run during `IHalfHalfSetup -> IItem`
28
- * conversion — it runs at display/submit time on a copy of the engine item,
29
- * optionally with `basePrices` (see `IChooseExpensiveSegmentPriceOptions`) so
30
- * the result is recomputed from pristine prices instead of accumulating
31
- * raises in state.
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.
32
20
  *
33
21
  * Rule: `price = base + upsell` — the item (option) level upsell is already
34
22
  * baked into the option price at conversion. choose_expensive compares every
35
- * SELECTED segment option (option price + required/price-defining modifier
36
- * prices — e.g. a "Pizza Size" group whose Small/Large/X-Large options are
37
- * part of the item's price) and raises the cheaper ones so their final
38
- * segment price matches the most expensive selected half. The raise is
39
- * applied to the FIRST PRICED element along the segment's price chain: the
40
- * segment option's own price when non-zero, else the first priced required
41
- * leaf ("First Half -> ROMA -> Pizza Size -> Large 13\"") — see
42
- * `findRaiseTarget`. Optional/upsell modifier groups are excluded: they add
43
- * on top and must not influence the comparison. The IHalfHalfSetup level
44
- * upsell is NOT part of this rule: it is the converted item's own price and
45
- * 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.
46
38
  *
47
39
  * All prices here are plain numbers (engine-priced).
48
40
  *
49
- * 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.
50
51
  */
51
- export declare function applyChooseExpensiveSegmentPrice(orderEngineItem: IOrderEngineItem, options?: IChooseExpensiveSegmentPriceOptions): IOrderEngineItem;
52
+ export declare function getOrderEnginePriceReferences(orderEngineItem: IOrderEngineItem): TOrderEnginePriceReferences;
52
53
  /**
53
54
  * True when the item has a top-level modifier group option that is a nested
54
55
  * half-half (ref_type HALF_HALF) with its setup's choose_expensive flag.
@@ -57,50 +58,16 @@ export declare function hasFlaggedHalfHalfOption(orderEngineItem: IOrderEngineIt
57
58
  /**
58
59
  * `choose_expensive_segment_price` for a half-half option nested in a special:
59
60
  * the option's own top-level modifiers are its segment groups, so they get the
60
- * same raise-to-most-expensive treatment as a standalone half-half item.
61
- * ITEM options are terminal (their nested modifiers can never contain
62
- * ITEM/HALF_HALF); normal options pass untouched. Runs on a copy with pristine
63
- * `basePrices` when provided (see `IChooseExpensiveSegmentPriceOptions`).
64
- */
65
- export declare function applyNestedChooseExpensiveSegmentPrice(orderEngineItem: IOrderEngineItem, options?: IChooseExpensiveSegmentPriceOptions): IOrderEngineItem;
66
- /**
67
- * Builds a pristine `_id -> price` map of every option in a converted catalog
68
- * item (`modifiers -> options -> nested modifiers -> options ...`). Used as
69
- * the baseline for `choose_expensive_segment_price` so applying the rule never
70
- * depends on previously raised prices.
71
- *
72
- * The flat `_id -> price` shape can only represent ONE value per option
73
- * `_id`, so callers MUST keep the map to a single price scope. A half-half
74
- * nested in a special is exactly the case where that fails: its segment
75
- * options are built FROM the special's items, so they reuse the SAME `_id`s
76
- * as the special's top-level options while their prices differ (top-level =
77
- * full upsell, segment = per-segment share). `nestedHalfHalfSegmentsOnly`
78
- * keeps the map to the subtrees of HALF_HALF options (the segment trees plus
79
- * their nested modifiers), excluding top-level option prices — the special
80
- * drawer feeds this map to `resetOrderEngineItemPrices` / the nested
81
- * normalization, so the walk order of the item can never leak a top-level
82
- * price into a segment (or the other way around). Standalone half-half items
83
- * are a single scope: every segment shares its option `_id`s with the SAME
84
- * price, so the unscoped map is safe there.
85
- */
86
- export declare function getOptionPriceMapFromItem(item: IItem | ISimplifiedCatalogItem, platform: PLATFORMS_ENUM | null | undefined, options?: {
87
- nestedHalfHalfSegmentsOnly?: boolean;
88
- }): Record<string, number>;
89
- /**
90
- * Restores every engine option price from the pristine `basePrices` map (by
91
- * option `_id`). Called when the drawer builds the engine item so state
92
- * (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.
93
64
  *
94
- * `options.nestedHalfHalfOnly` restricts the reset to the subtrees of
95
- * HALF_HALF options — the exact scope `getOptionPriceMapFromItem` builds when
96
- * called with `nestedHalfHalfSegmentsOnly`. A special's top-level options
97
- * reuse their `_id`s at different prices (full upsell vs per-segment share),
98
- * so a blanket reset with the scoped map would push the segment share onto
99
- * the top-level option. ALWAYS pass the SAME scope to the map builder and to
100
- * this reset.
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.
101
68
  */
102
- export declare function resetOrderEngineItemPrices(orderEngineItem: IOrderEngineItem, basePrices: Record<string, number>, options?: {
103
- nestedHalfHalfOnly?: boolean;
69
+ export declare function applyNestedChooseExpensiveSegmentPrice(orderEngineItem: IOrderEngineItem, options?: {
70
+ originalPriceReferences?: TOrderEnginePriceReferences;
104
71
  }): IOrderEngineItem;
105
72
  export type IOrderEngineItemRewardClaim = {
106
73
  type: 'offer';
@@ -148,7 +115,7 @@ interface IConvertCatalogItemToOrderEngineItemParams {
148
115
  defaultMenuId: string | null;
149
116
  soldoutModifiers: string[];
150
117
  }
151
- 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;
152
119
  export declare function hasRequiredModifier<T extends IModifier | IOrderEngineModifier>(currentModifiers: T[] | null): boolean;
153
120
  export declare function convertItemToOrderItem(item: IItem | ISimplifiedCatalogItem, menu_id: string | null, platform: PLATFORMS_ENUM | undefined, tenantId: string, orderItemType?: ORDER_ITEM_TYPE_ENUM): IOrderItem;
154
121
  export declare function setCheckFieldInOrderEngineItem(orderEngineItem: IOrderEngineItem, identifier: string, shouldCheck: boolean, chooseExpensiveSegmentPrice?: boolean): IOrderEngineItem;