@managesome/eposmatic-toolkit 0.2.717 → 0.2.718

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.
@@ -144,27 +144,6 @@ function isRequiredModifierGroup(modifier) {
144
144
  return ((modifier.min_num_options != null && modifier.min_num_options > 0) ||
145
145
  (modifier.min_aggregate_options_quantity != null && modifier.min_aggregate_options_quantity > 0));
146
146
  }
147
- /**
148
- * Total divided base price of a segment item = item price + prices of all
149
- * required (price-defining) modifier options at any nesting depth. Used by
150
- * `choose_expensive_segment_price` so the comparison also covers items whose
151
- * price lives inside a required modifier group (e.g. "Pizza Size").
152
- */
153
- function getSegmentItemTotalPrice(item, platform) {
154
- let total = (0, platform_catalog_1.getPriceEnum)(item.price, platform);
155
- const addRequiredPrices = (modifiers) => {
156
- (modifiers ?? []).forEach((modifier) => {
157
- if (!isRequiredModifierGroup(modifier))
158
- return;
159
- (modifier.options ?? []).forEach((option) => {
160
- total += (0, platform_catalog_1.getPriceEnum)(option.price, platform);
161
- addRequiredPrices(option.modifiers);
162
- });
163
- });
164
- };
165
- addRequiredPrices(item.modifiers);
166
- return total;
167
- }
168
147
  function convertHalfHalfSetupToWorkableHalfHalfSetup(halfhalfSetups, itemsMap, platform, tenant_id) {
169
148
  if (!platform || !tenant_id)
170
149
  return [];
@@ -200,8 +179,11 @@ function convertHalfHalfSetupToWorkableHalfHalfSetup(halfhalfSetups, itemsMap, p
200
179
  // from the selectable list (same semantics as specials' excluded_refs).
201
180
  .filter((setupItem) => !halfhalfSetup.excluded_refs.includes(setupItem.item_id))
202
181
  .sort((a, b) => a.sort_id - b.sort_id);
203
- // Workable segment entries: divided base price, with the optional
204
- // expensive-segment normalization + own upsells applied here (modern view).
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`).
205
187
  const entries = [];
206
188
  for (let j = 0; j < halfhalfItems.length; j++) {
207
189
  const item = halfhalfItems[j];
@@ -224,76 +206,11 @@ function convertHalfHalfSetupToWorkableHalfHalfSetup(halfhalfSetups, itemsMap, p
224
206
  entries.push({
225
207
  workableItem: segmentItem,
226
208
  itemUpsell: item.upsell_price,
227
- segmentTotal: getSegmentItemTotalPrice(segmentItem, platform),
228
209
  });
229
210
  }
230
- // choose_expensive_segment_price: normalize every segment's TOTAL base
231
- // price (item price + required/price-defining modifier prices, already
232
- // divided) to the most expensive one; the difference is added at item
233
- // level so a $5 half and a $6 half both charge $6.
234
- let expensiveMaxTotal = 0;
235
- if (halfhalfSetup.choose_expensive_segment_price && entries.length > 0) {
236
- expensiveMaxTotal = entries.reduce((max, entry) => Math.max(max, entry.segmentTotal), 0);
237
- }
238
211
  const items = [];
239
- const raisePriceBy = (price, delta) => {
240
- // Raise BOTH the active platform's key AND the base by `delta` so the
241
- // effective price (`getPriceEnum` reads `price[platform] ?? BASE_PRICE`)
242
- // is normalized even for items priced per-platform (e.g. POS_DINE_IN /
243
- // WEB_DELIVERY keys on the same IPrice object).
244
- const deltaObj = { BASE_PRICE: delta };
245
- deltaObj[platform] = delta;
246
- return (0, platform_num_1.mergePriceObjs)(price, deltaObj);
247
- };
248
- // RULE (same as the engine's `findRaiseTarget`): the raise is applied to
249
- // the FIRST PRICED element along the segment's price chain —
250
- // 1. the item's own price when non-zero, else
251
- // 2. the priced required leaf: the single option of a single-option
252
- // required group (its price is fixed), or the selected/default
253
- // option of a multi-option group (never an unselected sibling), else
254
- // 3. fall back to the item price.
255
- const findRaiseTargetOption = (modifiers) => {
256
- for (const modifier of modifiers ?? []) {
257
- const isRequired = (modifier.min_num_options != null && modifier.min_num_options > 0) ||
258
- (modifier.min_aggregate_options_quantity != null && modifier.min_aggregate_options_quantity > 0);
259
- if (!isRequired)
260
- continue;
261
- const options = modifier.options ?? [];
262
- if (options.length === 1)
263
- return options[0];
264
- const selectedOption = options.find((option) => option.default);
265
- if (selectedOption != null)
266
- return selectedOption;
267
- }
268
- return null;
269
- };
270
212
  for (const entry of entries) {
271
- const { workableItem, itemUpsell, segmentTotal } = entry;
272
- if (halfhalfSetup.choose_expensive_segment_price && segmentTotal < expensiveMaxTotal) {
273
- const delta = expensiveMaxTotal - segmentTotal;
274
- if ((0, platform_catalog_1.getPriceEnum)(workableItem.price, platform) > 0) {
275
- // Rule 1: the item itself carries the price.
276
- workableItem.price = raisePriceBy(workableItem.price, delta);
277
- }
278
- else {
279
- // Rule 2: the price lives on a required leaf — raise it there
280
- // (e.g. "ROMA -> Pizza Size -> Large 13\"").
281
- const targetOption = findRaiseTargetOption(workableItem.modifiers);
282
- const currentModifiers = workableItem.modifiers ?? [];
283
- if (targetOption != null && currentModifiers.length > 0) {
284
- workableItem.modifiers = currentModifiers.map((modifier) => ({
285
- ...modifier,
286
- options: modifier.options.map((option) => option._id === targetOption._id
287
- ? { ...option, price: raisePriceBy(option.price ?? null, delta) }
288
- : option),
289
- }));
290
- }
291
- else {
292
- // Rule 3: fall back to the item price.
293
- workableItem.price = raisePriceBy(workableItem.price, delta);
294
- }
295
- }
296
- }
213
+ const { workableItem, itemUpsell } = entry;
297
214
  // Each half keeps its own item-level upsell, added ON TOP of the divided
298
215
  // price. The half-half upsell is a ONE-TIME addition on the order item,
299
216
  // not merged per segment.
@@ -6,39 +6,49 @@ export declare function hasMissedRequiredItemModifier(currentModifiers: IModifie
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
+ }
9
19
  /**
10
20
  * Applies `choose_expensive_segment_price` to an order engine item converted
11
21
  * from a half-half setup (top-level modifier groups = segments, single-select
12
22
  * each, only 2 or 4 segments).
13
23
  *
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. It is invoked automatically by
17
- * `setCheckFieldInOrderEngineItem` whenever the engine item's `item_type` is
18
- * `HALF_HALF` and the caller passed the flag.
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.
19
32
  *
20
33
  * Rule: `price = base + upsell` — the item (option) level upsell is already
21
- * baked into the option price at conversion. choose_expensive compares
22
- * EVERY segment option (option price + required/price-defining modifier
34
+ * baked into the option price at conversion. choose_expensive compares every
35
+ * SELECTED segment option (option price + required/price-defining modifier
23
36
  * prices — e.g. a "Pizza Size" group whose Small/Large/X-Large options are
24
- * part of the item's price) and raises the SELECTED ones so their final
25
- * segment price matches the setup's most expensive option — no matter which
26
- * halves the user picks (same semantics as the modern workable converter).
27
- * The raise is applied to the FIRST PRICED element along the segment's price
28
- * chain: the segment option's own price when non-zero (like the modern flow),
29
- * else the first priced required leaf ("First Half -> ROMA -> Pizza Size ->
30
- * Large 13\"") — see `findRaiseTarget`. Optional/upsell modifier groups are
31
- * excluded: they add on top and must not influence the comparison. The
32
- * IHalfHalfSetup level upsell is NOT part of this rule: it is the converted
33
- * item's own price and is added once on top of the combined subtotal.
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.
34
46
  *
35
- * All prices here are plain numbers (engine-priced). Idempotent — it only
36
- * ever raises, never lowers — so it can safely be re-applied (e.g. on
37
- * submit).
47
+ * All prices here are plain numbers (engine-priced).
38
48
  *
39
- * Returns the item unchanged when no segment option is selected.
49
+ * Returns the item unchanged when nothing changes.
40
50
  */
41
- export declare function applyChooseExpensiveSegmentPrice(orderEngineItem: IOrderEngineItem): IOrderEngineItem;
51
+ export declare function applyChooseExpensiveSegmentPrice(orderEngineItem: IOrderEngineItem, options?: IChooseExpensiveSegmentPriceOptions): IOrderEngineItem;
42
52
  /**
43
53
  * True when the item has a top-level modifier group option that is a nested
44
54
  * half-half (ref_type HALF_HALF) with its setup's choose_expensive flag.
@@ -49,9 +59,23 @@ export declare function hasFlaggedHalfHalfOption(orderEngineItem: IOrderEngineIt
49
59
  * the option's own top-level modifiers are its segment groups, so they get the
50
60
  * same raise-to-most-expensive treatment as a standalone half-half item.
51
61
  * ITEM options are terminal (their nested modifiers can never contain
52
- * ITEM/HALF_HALF); normal options pass untouched. Idempotent (only raises).
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
+ export declare function getOptionPriceMapFromItem(item: IItem | ISimplifiedCatalogItem, platform: PLATFORMS_ENUM | null | undefined): Record<string, number>;
73
+ /**
74
+ * Restores every engine option price from the pristine `basePrices` map (by
75
+ * option `_id`). Called when the drawer builds the engine item so state
76
+ * (sidebar prices, edit baselines) never carries a previous normalization.
53
77
  */
54
- export declare function applyNestedChooseExpensiveSegmentPrice(orderEngineItem: IOrderEngineItem): IOrderEngineItem;
78
+ export declare function resetOrderEngineItemPrices(orderEngineItem: IOrderEngineItem, basePrices: Record<string, number>): IOrderEngineItem;
55
79
  export type IOrderEngineItemRewardClaim = {
56
80
  type: 'offer';
57
81
  offerId: string;
@@ -10,6 +10,8 @@ exports.makeSpaceForFreeOptions = makeSpaceForFreeOptions;
10
10
  exports.applyChooseExpensiveSegmentPrice = applyChooseExpensiveSegmentPrice;
11
11
  exports.hasFlaggedHalfHalfOption = hasFlaggedHalfHalfOption;
12
12
  exports.applyNestedChooseExpensiveSegmentPrice = applyNestedChooseExpensiveSegmentPrice;
13
+ exports.getOptionPriceMapFromItem = getOptionPriceMapFromItem;
14
+ exports.resetOrderEngineItemPrices = resetOrderEngineItemPrices;
13
15
  exports.convertOrderEngineItemToOrderItem = convertOrderEngineItemToOrderItem;
14
16
  exports.convertItemDiscountToOrderItemDiscount = convertItemDiscountToOrderItemDiscount;
15
17
  exports.convertCatalogItemToOrderEngineItem = convertCatalogItemToOrderEngineItem;
@@ -285,44 +287,60 @@ function makeSpaceForFreeOptions(options, num_free_options) {
285
287
  }
286
288
  return [...defaultPriceOptions, ...nonDefaultOptions].sort((a, b) => a.sort_id - b.sort_id);
287
289
  }
288
- // ====================================>>><<<======================================
290
+ /** Restores engine option prices from a pristine `_id -> price` map. */
291
+ const resetEngineOptionPrices = (modifiers, basePrices) => {
292
+ if (basePrices == null)
293
+ return modifiers;
294
+ const resetOption = (option) => ({
295
+ ...option,
296
+ price: basePrices[option._id] ?? option.price,
297
+ modifiers: (option.modifiers ?? []).map((modifier) => ({
298
+ ...modifier,
299
+ options: (modifier.options ?? []).map(resetOption),
300
+ })),
301
+ });
302
+ return modifiers.map((modifier) => ({
303
+ ...modifier,
304
+ options: (modifier.options ?? []).map(resetOption),
305
+ }));
306
+ };
289
307
  /**
290
308
  * Applies `choose_expensive_segment_price` to an order engine item converted
291
309
  * from a half-half setup (top-level modifier groups = segments, single-select
292
310
  * each, only 2 or 4 segments).
293
311
  *
294
- * The expensive rule depends on which halves the user actually picked, so it
295
- * cannot run during `IHalfHalfSetup -> IItem` conversion — it must run after
296
- * selection. It is invoked automatically by
297
- * `setCheckFieldInOrderEngineItem` whenever the engine item's `item_type` is
298
- * `HALF_HALF` and the caller passed the flag.
312
+ * The rule is a pure function of the CURRENT selection: the most expensive
313
+ * half the user actually picked sets the charged price for every picked half
314
+ * (cheaper halves are raised to it; picking a cheaper combination later
315
+ * lowers them again). It cannot run during `IHalfHalfSetup -> IItem`
316
+ * conversion — it runs at display/submit time on a copy of the engine item,
317
+ * optionally with `basePrices` (see `IChooseExpensiveSegmentPriceOptions`) so
318
+ * the result is recomputed from pristine prices instead of accumulating
319
+ * raises in state.
299
320
  *
300
321
  * Rule: `price = base + upsell` — the item (option) level upsell is already
301
- * baked into the option price at conversion. choose_expensive compares
302
- * EVERY segment option (option price + required/price-defining modifier
322
+ * baked into the option price at conversion. choose_expensive compares every
323
+ * SELECTED segment option (option price + required/price-defining modifier
303
324
  * prices — e.g. a "Pizza Size" group whose Small/Large/X-Large options are
304
- * part of the item's price) and raises the SELECTED ones so their final
305
- * segment price matches the setup's most expensive option — no matter which
306
- * halves the user picks (same semantics as the modern workable converter).
307
- * The raise is applied to the FIRST PRICED element along the segment's price
308
- * chain: the segment option's own price when non-zero (like the modern flow),
309
- * else the first priced required leaf ("First Half -> ROMA -> Pizza Size ->
310
- * Large 13\"") — see `findRaiseTarget`. Optional/upsell modifier groups are
311
- * excluded: they add on top and must not influence the comparison. The
312
- * IHalfHalfSetup level upsell is NOT part of this rule: it is the converted
313
- * item's own price and is added once on top of the combined subtotal.
325
+ * part of the item's price) and raises the cheaper ones so their final
326
+ * segment price matches the most expensive selected half. The raise is
327
+ * applied to the FIRST PRICED element along the segment's price chain: the
328
+ * segment option's own price when non-zero, else the first priced required
329
+ * leaf ("First Half -> ROMA -> Pizza Size -> Large 13\"") — see
330
+ * `findRaiseTarget`. Optional/upsell modifier groups are excluded: they add
331
+ * on top and must not influence the comparison. The IHalfHalfSetup level
332
+ * upsell is NOT part of this rule: it is the converted item's own price and
333
+ * is added once on top of the combined subtotal.
314
334
  *
315
- * All prices here are plain numbers (engine-priced). Idempotent — it only
316
- * ever raises, never lowers — so it can safely be re-applied (e.g. on
317
- * submit).
335
+ * All prices here are plain numbers (engine-priced).
318
336
  *
319
- * Returns the item unchanged when no segment option is selected.
337
+ * Returns the item unchanged when nothing changes.
320
338
  */
321
- function applyChooseExpensiveSegmentPrice(orderEngineItem) {
339
+ function applyChooseExpensiveSegmentPrice(orderEngineItem, options) {
322
340
  const segmentGroups = (orderEngineItem.modifiers ?? []).filter((modifier) => modifier.depth === 0);
323
341
  if (segmentGroups.length < 2)
324
342
  return orderEngineItem;
325
- const raised = applyChooseExpensiveSegmentPriceToModifiers(segmentGroups);
343
+ const raised = applyChooseExpensiveSegmentPriceToModifiers(segmentGroups, options);
326
344
  if (raised == null)
327
345
  return orderEngineItem;
328
346
  let segmentGroupIndex = 0;
@@ -338,7 +356,9 @@ function applyChooseExpensiveSegmentPrice(orderEngineItem) {
338
356
  * Returns null when nothing needs to change (no selected option / no priced
339
357
  * segment), otherwise the raised segment groups.
340
358
  */
341
- function applyChooseExpensiveSegmentPriceToModifiers(segmentGroups) {
359
+ function applyChooseExpensiveSegmentPriceToModifiers(segmentGroups, options) {
360
+ const hasBasePrices = options?.basePrices != null;
361
+ const groups = resetEngineOptionPrices(segmentGroups, options?.basePrices);
342
362
  // Prices of ALL options of required (price-defining) modifier groups, at
343
363
  // any depth — e.g. "Pizza Size" -> "Large 13"" is part of the item's price
344
364
  // whichever size is picked (mirrors `getSegmentItemTotalPrice` used by the
@@ -361,28 +381,10 @@ function applyChooseExpensiveSegmentPriceToModifiers(segmentGroups) {
361
381
  // Segment price = option price (base + item/option level upsell, already
362
382
  // merged at conversion) + required (price-defining) modifier prices.
363
383
  const getSegmentTotal = (option) => (option.price ?? 0) + getRequiredOptionPrices(option.modifiers);
364
- // Max over ALL segment options (the setup's most expensive segment), not
365
- // just the selected ones — otherwise the charged price would depend on
366
- // which halves the user picks. Free options never drive the comparison.
367
- let maxSegmentValue = 0;
368
- for (let g = 0; g < segmentGroups.length; g++) {
369
- const options = segmentGroups[g].options ?? [];
370
- for (let o = 0; o < options.length; o++) {
371
- const option = options[o];
372
- if (option.is_free)
373
- continue;
374
- const segmentValue = getSegmentTotal(option);
375
- if (segmentValue > maxSegmentValue) {
376
- maxSegmentValue = segmentValue;
377
- }
378
- }
379
- }
380
- if (maxSegmentValue <= 0)
381
- return null;
382
384
  // One selected option per segment group (segments are single-select).
383
385
  const selections = [];
384
- for (let g = 0; g < segmentGroups.length; g++) {
385
- const options = segmentGroups[g].options ?? [];
386
+ for (let g = 0; g < groups.length; g++) {
387
+ const options = groups[g].options ?? [];
386
388
  for (let o = 0; o < options.length; o++) {
387
389
  const option = options[o];
388
390
  if (!option.default || option.is_free)
@@ -392,7 +394,21 @@ function applyChooseExpensiveSegmentPriceToModifiers(segmentGroups) {
392
394
  }
393
395
  }
394
396
  if (selections.length === 0)
395
- return null;
397
+ return hasBasePrices ? groups : null;
398
+ // Max over the SELECTED halves only — the "expensive segment" is the most
399
+ // expensive half the user actually picked, not the most expensive option in
400
+ // the setup (otherwise picking A+B would charge as if C+D were chosen).
401
+ // Free halves never drive the comparison and are never raised.
402
+ let maxSegmentValue = 0;
403
+ for (const selection of selections) {
404
+ const option = groups[selection.groupIndex].options[selection.optionIndex];
405
+ const segmentValue = getSegmentTotal(option);
406
+ if (segmentValue > maxSegmentValue) {
407
+ maxSegmentValue = segmentValue;
408
+ }
409
+ }
410
+ if (maxSegmentValue <= 0)
411
+ return hasBasePrices ? groups : null;
396
412
  // RULE for where the raise lands: on the FIRST PRICED element along the
397
413
  // segment's price chain —
398
414
  // 1. the segment option's own price (the item base) when it is non-zero
@@ -432,7 +448,7 @@ function applyChooseExpensiveSegmentPriceToModifiers(segmentGroups) {
432
448
  })),
433
449
  };
434
450
  };
435
- return segmentGroups.map((modifier, g) => {
451
+ return groups.map((modifier, g) => {
436
452
  const options = (modifier.options ?? []).map((option, o) => {
437
453
  const selection = selections.find((s) => s.groupIndex === g && s.optionIndex === o);
438
454
  if (selection == null)
@@ -462,9 +478,10 @@ function hasFlaggedHalfHalfOption(orderEngineItem) {
462
478
  * the option's own top-level modifiers are its segment groups, so they get the
463
479
  * same raise-to-most-expensive treatment as a standalone half-half item.
464
480
  * ITEM options are terminal (their nested modifiers can never contain
465
- * ITEM/HALF_HALF); normal options pass untouched. Idempotent (only raises).
481
+ * ITEM/HALF_HALF); normal options pass untouched. Runs on a copy with pristine
482
+ * `basePrices` when provided (see `IChooseExpensiveSegmentPriceOptions`).
466
483
  */
467
- function applyNestedChooseExpensiveSegmentPrice(orderEngineItem) {
484
+ function applyNestedChooseExpensiveSegmentPrice(orderEngineItem, options) {
468
485
  const modifiers = (orderEngineItem.modifiers ?? []).map((modifier) => ({
469
486
  ...modifier,
470
487
  options: (modifier.options ?? []).map((option) => {
@@ -472,7 +489,7 @@ function applyNestedChooseExpensiveSegmentPrice(orderEngineItem) {
472
489
  option.choose_expensive_segment_price !== true) {
473
490
  return option;
474
491
  }
475
- const raised = applyChooseExpensiveSegmentPriceToModifiers(option.modifiers ?? []);
492
+ const raised = applyChooseExpensiveSegmentPriceToModifiers(option.modifiers ?? [], options);
476
493
  if (raised == null)
477
494
  return option;
478
495
  return { ...option, modifiers: raised };
@@ -480,6 +497,34 @@ function applyNestedChooseExpensiveSegmentPrice(orderEngineItem) {
480
497
  }));
481
498
  return syncOrderEngineItem({ ...orderEngineItem, modifiers });
482
499
  }
500
+ /**
501
+ * Builds a pristine `_id -> price` map of every option in a converted catalog
502
+ * item (`modifiers -> options -> nested modifiers -> options ...`). Used as
503
+ * the baseline for `choose_expensive_segment_price` so applying the rule never
504
+ * depends on previously raised prices.
505
+ */
506
+ function getOptionPriceMapFromItem(item, platform) {
507
+ const priceMap = {};
508
+ const walk = (modifiers) => {
509
+ (modifiers ?? []).forEach((modifier) => {
510
+ (modifier.options ?? []).forEach((option) => {
511
+ priceMap[option._id] = (0, platform_catalog_1.getPriceEnum)(option.price, platform);
512
+ walk(option.modifiers);
513
+ });
514
+ });
515
+ };
516
+ walk(item.modifiers);
517
+ return priceMap;
518
+ }
519
+ /**
520
+ * Restores every engine option price from the pristine `basePrices` map (by
521
+ * option `_id`). Called when the drawer builds the engine item so state
522
+ * (sidebar prices, edit baselines) never carries a previous normalization.
523
+ */
524
+ function resetOrderEngineItemPrices(orderEngineItem, basePrices) {
525
+ const modifiers = resetEngineOptionPrices(orderEngineItem.modifiers ?? [], basePrices);
526
+ return syncOrderEngineItem({ ...orderEngineItem, modifiers });
527
+ }
483
528
  function convertCatalogItemModifierToOrderEngineItemModifier({ modifiers, orderItemModifiers, platform, tenantId, excludeRefs, zeroPriceRefs, loyaltyRefs, voucherRefs, keepOptionalModifiersAtBottom, soldoutModifiers, depth = 0, }) {
484
529
  function getSortedModifiers(modifiers = []) {
485
530
  const sortedModifiers = modifiers.sort((a, b) => a.sort_id - b.sort_id);
@@ -1027,21 +1072,14 @@ function setCheckFieldInOrderEngineItem(orderEngineItem, identifier, shouldCheck
1027
1072
  const allIds = identifier.split('_').filter((id) => id.trim() !== '');
1028
1073
  const modifiers = setUpdateModifiers(orderEngineItem.modifiers, allIds, 0);
1029
1074
  const updatedOrderEngineItem = syncOrderEngineItem({ ...orderEngineItem, modifiers });
1030
- // Half-half classic view: `choose_expensive_segment_price` depends on which
1031
- // halves the user actually picked, so it cannot run during
1032
- // `IHalfHalfSetup -> IItem` conversion — it is applied right here, after
1033
- // every selection, whenever the caller passes the setup flag. It compares
1034
- // EVERY segment option (option base + item upsell + required/price-defining
1035
- // modifiers) and raises the selected ones to the setup's most expensive
1036
- // segment. Idempotent: it never lowers a price, so re-running is safe.
1037
- if (orderEngineItem.item_type === constants_1.ORDER_ITEM_TYPE_ENUM.HALF_HALF && chooseExpensiveSegmentPrice === true) {
1038
- return applyChooseExpensiveSegmentPrice(updatedOrderEngineItem);
1039
- }
1040
- // Half-half option nested in a special: normalize its own segment groups
1041
- // (the option's top-level modifiers) whenever it carries the setup flag.
1042
- if (orderEngineItem.item_type === constants_1.ORDER_ITEM_TYPE_ENUM.SPECIAL && hasFlaggedHalfHalfOption(updatedOrderEngineItem)) {
1043
- return applyNestedChooseExpensiveSegmentPrice(updatedOrderEngineItem);
1044
- }
1075
+ // NOTE: `choose_expensive_segment_price` is intentionally NOT applied here.
1076
+ // The rule depends on the current selection and must be able to LOWER prices
1077
+ // again when a cheaper combination is picked, so normalization runs at
1078
+ // display/submit time on a copy of the engine item with pristine
1079
+ // `basePrices` (see `applyChooseExpensiveSegmentPrice` /
1080
+ // `applyNestedChooseExpensiveSegmentPrice`). The parameter is kept for
1081
+ // backwards compatibility.
1082
+ void chooseExpensiveSegmentPrice;
1045
1083
  return updatedOrderEngineItem;
1046
1084
  }
1047
1085
  function setIncrementOrderEngineItemQuantity(orderEngineItem, increment) {
@@ -222,3 +222,81 @@ describe('applyChooseExpensiveSegmentPrice (standalone regression)', () => {
222
222
  expect(segB.options.find((o) => o._id === 'torent2').price).toBe(600);
223
223
  });
224
224
  });
225
+ describe('applyNestedChooseExpensiveSegmentPrice — selected-halves max', () => {
226
+ /** Nested half-half hub: one flagged HALF_HALF option holding the segments. */
227
+ function makeHub(segmentGroups) {
228
+ return makeEngineItem({
229
+ modifiers: [
230
+ makeEngineModifier({
231
+ _id: 'first-pizza',
232
+ name: 'First Pizza',
233
+ depth: 0,
234
+ options: [
235
+ makeEngineOption({
236
+ _id: 'halfhalf-1',
237
+ ref: 'halfhalf-1',
238
+ ref_type: constants_1.MODIFIER_OPTION_REF_TYPE_ENUM.HALF_HALF,
239
+ choose_expensive_segment_price: true,
240
+ default: true,
241
+ price: 0,
242
+ modifiers: segmentGroups,
243
+ }),
244
+ ],
245
+ }),
246
+ ],
247
+ });
248
+ }
249
+ /** Marks exactly one option per segment as selected. */
250
+ function withSelections(item, selections) {
251
+ return {
252
+ ...item,
253
+ modifiers: item.modifiers.map((modifier) => ({
254
+ ...modifier,
255
+ options: modifier.options.map((option) => option.ref_type === constants_1.MODIFIER_OPTION_REF_TYPE_ENUM.HALF_HALF
256
+ ? {
257
+ ...option,
258
+ modifiers: option.modifiers.map((segment) => ({
259
+ ...segment,
260
+ options: segment.options.map((o) => ({
261
+ ...o,
262
+ default: o._id === selections[segment._id],
263
+ })),
264
+ })),
265
+ }
266
+ : option),
267
+ })),
268
+ };
269
+ }
270
+ function halfHalfOption(item) {
271
+ return item.modifiers[0].options[0];
272
+ }
273
+ function segmentPrice(item, segmentId, optionId) {
274
+ const option = halfHalfOption(item).modifiers.find((m) => m._id === segmentId);
275
+ return option.options.find((o) => o._id === optionId).price;
276
+ }
277
+ it('a cheap selected pair is NOT raised (max of the SELECTED halves only)', () => {
278
+ // seg-1: milan(500) selected, torent(600) not; seg-2: milan2(500) selected,
279
+ // torent2(600) not.
280
+ const item = withSelections(makeHub(makeSegmentGroups()), {
281
+ 'seg-1': 'milan',
282
+ 'seg-2': 'milan2',
283
+ });
284
+ const result = (0, order_engine_1.applyNestedChooseExpensiveSegmentPrice)(item);
285
+ expect(segmentPrice(result, 'seg-1', 'milan')).toBe(500);
286
+ expect(segmentPrice(result, 'seg-2', 'milan2')).toBe(500);
287
+ // Unselected expensive options keep their own prices.
288
+ expect(segmentPrice(result, 'seg-1', 'torent')).toBe(600);
289
+ });
290
+ it('LOWERS with basePrices when switching from an expensive to a cheap pair', () => {
291
+ const basePrices = { milan: 500, torent: 600, milan2: 500, torent2: 600 };
292
+ // Selected: milan (500) + torent2 (600) -> milan is raised to 600.
293
+ const normalized = (0, order_engine_1.applyNestedChooseExpensiveSegmentPrice)(withSelections(makeHub(makeSegmentGroups()), { 'seg-1': 'milan', 'seg-2': 'torent2' }));
294
+ expect(segmentPrice(normalized, 'seg-1', 'milan')).toBe(600);
295
+ // User switches seg-2 to milan2 (cheap pair: 500+500). Re-applying with
296
+ // pristine basePrices brings the previously raised milan back to 500.
297
+ const switched = withSelections(normalized, { 'seg-1': 'milan', 'seg-2': 'milan2' });
298
+ const lowered = (0, order_engine_1.applyNestedChooseExpensiveSegmentPrice)(switched, { basePrices });
299
+ expect(segmentPrice(lowered, 'seg-1', 'milan')).toBe(500);
300
+ expect(segmentPrice(lowered, 'seg-2', 'milan2')).toBe(500);
301
+ });
302
+ });
@@ -867,11 +867,12 @@ describe('choose_expensive_segment_price end-to-end (specials with half-half)',
867
867
  let engine = buildEngine();
868
868
  // Real UI flow: selection happens through the special's engine item, so
869
869
  // the identifier is the FULL path (group -> half-half option -> segment
870
- // -> option) and setCheckField auto-normalizes via its SPECIAL branch.
871
- engine = (0, order_engine_1.setCheckFieldInOrderEngineItem)(engine, 'mod-pizza_halfhalf-1_seg-1_milan', true, false);
872
- expect(segmentOptions(engine)[0].find((o) => o.id === 'milan').price).toBe(100);
873
- engine = (0, order_engine_1.setCheckFieldInOrderEngineItem)(engine, 'mod-pizza_halfhalf-1_seg-2_torent', true, false);
874
- const after = segmentOptions(engine);
870
+ // -> option). setCheckField keeps prices PRISTINE — normalization is a
871
+ // derived pass applied at display/submit time.
872
+ engine = (0, order_engine_1.setCheckFieldInOrderEngineItem)(engine, 'mod-pizza_halfhalf-1_seg-1_milan', true);
873
+ expect(segmentOptions(engine)[0].find((o) => o.id === 'milan').price).toBe(0);
874
+ engine = (0, order_engine_1.setCheckFieldInOrderEngineItem)(engine, 'mod-pizza_halfhalf-1_seg-2_torent', true);
875
+ const after = segmentOptions((0, order_engine_1.applyNestedChooseExpensiveSegmentPrice)(engine));
875
876
  // seg-1 selected MILAN raised 0 -> 100; seg-2 selected TORENT stays 100.
876
877
  // Unselected options untouched; NO 575 from Pizza Size anywhere.
877
878
  expect(after[0].find((o) => o.id === 'milan').price).toBe(100);
@@ -881,10 +882,10 @@ describe('choose_expensive_segment_price end-to-end (specials with half-half)',
881
882
  });
882
883
  it('is idempotent (re-applying never lowers or changes prices)', () => {
883
884
  let engine = buildEngine();
884
- engine = (0, order_engine_1.setCheckFieldInOrderEngineItem)(engine, 'mod-pizza_halfhalf-1_seg-1_milan', true, false);
885
- engine = (0, order_engine_1.setCheckFieldInOrderEngineItem)(engine, 'mod-pizza_halfhalf-1_seg-2_torent', true, false);
886
- const once = segmentOptions(engine);
887
- const twice = segmentOptions((0, order_engine_1.applyNestedChooseExpensiveSegmentPrice)(engine));
885
+ engine = (0, order_engine_1.setCheckFieldInOrderEngineItem)(engine, 'mod-pizza_halfhalf-1_seg-1_milan', true);
886
+ engine = (0, order_engine_1.setCheckFieldInOrderEngineItem)(engine, 'mod-pizza_halfhalf-1_seg-2_torent', true);
887
+ const once = segmentOptions((0, order_engine_1.applyNestedChooseExpensiveSegmentPrice)(engine));
888
+ const twice = segmentOptions((0, order_engine_1.applyNestedChooseExpensiveSegmentPrice)((0, order_engine_1.applyNestedChooseExpensiveSegmentPrice)(engine)));
888
889
  expect(twice).toEqual(once);
889
890
  });
890
891
  it('does nothing when the half-half flag is off', () => {
@@ -946,12 +947,103 @@ describe('choose_expensive_segment_price end-to-end (specials with half-half)',
946
947
  defaultMenuId: null,
947
948
  soldoutModifiers: [],
948
949
  });
949
- engine = (0, order_engine_1.setCheckFieldInOrderEngineItem)(engine, 'mod-pizza_hh-flag_seg-1_milan', true, false);
950
- engine = (0, order_engine_1.setCheckFieldInOrderEngineItem)(engine, 'mod-pizza_hh-no-flag_seg-1_milan', true, false);
951
- const hhFlag = engine.modifiers[0].options.find((o) => o._id === 'hh-flag');
952
- const hhNoFlag = engine.modifiers[0].options.find((o) => o._id === 'hh-no-flag');
953
- // Flagged: basic half raised to +100; un-flagged: stays free.
950
+ engine = (0, order_engine_1.setCheckFieldInOrderEngineItem)(engine, 'mod-pizza_hh-flag_seg-1_milan', true);
951
+ engine = (0, order_engine_1.setCheckFieldInOrderEngineItem)(engine, 'mod-pizza_hh-flag_seg-2_torent', true);
952
+ engine = (0, order_engine_1.setCheckFieldInOrderEngineItem)(engine, 'mod-pizza_hh-no-flag_seg-1_milan', true);
953
+ engine = (0, order_engine_1.setCheckFieldInOrderEngineItem)(engine, 'mod-pizza_hh-no-flag_seg-2_torent', true);
954
+ const normalized = (0, order_engine_1.applyNestedChooseExpensiveSegmentPrice)(engine);
955
+ const hhFlag = normalized.modifiers[0].options.find((o) => o._id === 'hh-flag');
956
+ const hhNoFlag = normalized.modifiers[0].options.find((o) => o._id === 'hh-no-flag');
957
+ // Flagged: selected free milan raised to the selected expensive half (+100);
958
+ // un-flagged: stays free.
954
959
  expect(hhFlag.modifiers[0].options.find((o) => o._id === 'milan').price).toBe(100);
955
960
  expect(hhNoFlag.modifiers[0].options.find((o) => o._id === 'milan').price).toBe(0);
956
961
  });
957
962
  });
963
+ // ============================================================================
964
+ // 5) Engine — choose_expensive_segment_price uses the MAX OF THE SELECTED halves
965
+ // ============================================================================
966
+ describe('choose_expensive_segment_price: selected-halves max (new semantics)', () => {
967
+ // A(500) B(500) C(600) D(600) halves — user example: the expensive half is
968
+ // at most the most expensive SELECTED one, not the setup's global max.
969
+ const itemsMap4 = {
970
+ a: makeItem('a', { price: { BASE_PRICE: 1000 } }),
971
+ b: makeItem('b', { price: { BASE_PRICE: 1000 } }),
972
+ c: makeItem('c', { price: { BASE_PRICE: 1200 } }),
973
+ d: makeItem('d', { price: { BASE_PRICE: 1200 } }),
974
+ };
975
+ const setup4 = () => makeHalfHalfSetup({
976
+ upsell_price: null,
977
+ items: [
978
+ { item_id: 'a', sort_id: 1, upsell_price: null },
979
+ { item_id: 'b', sort_id: 2, upsell_price: null },
980
+ { item_id: 'c', sort_id: 3, upsell_price: null },
981
+ { item_id: 'd', sort_id: 4, upsell_price: null },
982
+ ],
983
+ });
984
+ const converted = (0, halfhalf_setup_helpers_1.convertHalfHalfToItem)(setup4(), itemsMap4);
985
+ const basePrices = (0, order_engine_1.getOptionPriceMapFromItem)(converted, PLATFORM);
986
+ function selectEngine(picks) {
987
+ let engine = (0, order_engine_1.convertCatalogItemToOrderEngineItem)({
988
+ item: converted,
989
+ orderItem: undefined,
990
+ platform: PLATFORM,
991
+ tenantId: TENANT_ID,
992
+ orderItemType: constants_1.ORDER_ITEM_TYPE_ENUM.HALF_HALF,
993
+ defaultMenuId: null,
994
+ soldoutModifiers: [],
995
+ });
996
+ engine = (0, order_engine_1.setCheckFieldInOrderEngineItem)(engine, `seg-1_${picks[0]}`, true);
997
+ engine = (0, order_engine_1.setCheckFieldInOrderEngineItem)(engine, `seg-2_${picks[1]}`, true);
998
+ return engine;
999
+ }
1000
+ function selectedPrices(engine) {
1001
+ return engine.modifiers.map((m) => m.options.find((o) => o.default).price);
1002
+ }
1003
+ it('A+B stays 5+5 (global max must NOT leak)', () => {
1004
+ const result = (0, order_engine_1.applyChooseExpensiveSegmentPrice)(selectEngine(['a', 'b']));
1005
+ expect(selectedPrices(result)).toEqual([500, 500]);
1006
+ });
1007
+ it('B+C raises B to C (6+6)', () => {
1008
+ const result = (0, order_engine_1.applyChooseExpensiveSegmentPrice)(selectEngine(['b', 'c']));
1009
+ expect(selectedPrices(result)).toEqual([600, 600]);
1010
+ });
1011
+ it('C+B is order independent (6+6)', () => {
1012
+ const result = (0, order_engine_1.applyChooseExpensiveSegmentPrice)(selectEngine(['c', 'b']));
1013
+ expect(selectedPrices(result)).toEqual([600, 600]);
1014
+ });
1015
+ it('C+D needs no raise (6+6)', () => {
1016
+ const result = (0, order_engine_1.applyChooseExpensiveSegmentPrice)(selectEngine(['c', 'd']));
1017
+ expect(selectedPrices(result)).toEqual([600, 600]);
1018
+ });
1019
+ it('A+D raises A to D (6+6)', () => {
1020
+ const result = (0, order_engine_1.applyChooseExpensiveSegmentPrice)(selectEngine(['a', 'd']));
1021
+ expect(selectedPrices(result)).toEqual([600, 600]);
1022
+ });
1023
+ it('unselected options keep their own prices; item-level upsell untouched', () => {
1024
+ const result = (0, order_engine_1.applyChooseExpensiveSegmentPrice)(selectEngine(['a', 'b']));
1025
+ const seg1 = result.modifiers.find((m) => m._id === 'seg-1');
1026
+ expect(seg1.options.find((o) => o._id === 'c').price).toBe(600);
1027
+ expect(seg1.options.find((o) => o._id === 'd').price).toBe(600);
1028
+ // Setup upsell is null -> engine item price 0 (added once, never normalized).
1029
+ expect(result.price).toBe(0);
1030
+ });
1031
+ it('LOWERS again when switching from an expensive pair to a cheap pair (basePrices reset)', () => {
1032
+ // B+C -> B is raised to 600...
1033
+ const expensive = (0, order_engine_1.applyChooseExpensiveSegmentPrice)(selectEngine(['b', 'c']));
1034
+ expect(selectedPrices(expensive)).toEqual([600, 600]);
1035
+ // ...then the user switches BOTH halves to the cheap pair A+B. Re-applying
1036
+ // with pristine basePrices must bring B back down to 500.
1037
+ let engine = (0, order_engine_1.setCheckFieldInOrderEngineItem)(expensive, 'seg-1_b', false);
1038
+ engine = (0, order_engine_1.setCheckFieldInOrderEngineItem)(engine, 'seg-1_a', true);
1039
+ engine = (0, order_engine_1.setCheckFieldInOrderEngineItem)(engine, 'seg-2_c', false);
1040
+ engine = (0, order_engine_1.setCheckFieldInOrderEngineItem)(engine, 'seg-2_b', true);
1041
+ const lowered = (0, order_engine_1.applyChooseExpensiveSegmentPrice)(engine, { basePrices });
1042
+ expect(selectedPrices(lowered)).toEqual([500, 500]);
1043
+ });
1044
+ it('workable conversion no longer bakes the global max into option prices', () => {
1045
+ const workable = (0, halfhalf_setup_helpers_1.convertHalfHalfSetupToWorkableHalfHalfSetup)([setup4()], itemsMap4, PLATFORM, TENANT_ID);
1046
+ // a/b stay 500, c/d stay 600 — NOT all raised to 600 at conversion.
1047
+ expect(workable[0].items.map((i) => priceOf(i.price))).toEqual([500, 500, 600, 600]);
1048
+ });
1049
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@managesome/eposmatic-toolkit",
3
- "version": "0.2.717",
3
+ "version": "0.2.718",
4
4
  "description": "A Toolkit Library for Eposmatic",
5
5
  "main": "lib/index.js",
6
6
  "types": "lib/index.d.ts",