@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.
@@ -8,10 +8,9 @@ exports.syncOrderEngineItem = syncOrderEngineItem;
8
8
  exports.checkIfModifiersExist = checkIfModifiersExist;
9
9
  exports.makeSpaceForFreeOptions = makeSpaceForFreeOptions;
10
10
  exports.applyChooseExpensiveSegmentPrice = applyChooseExpensiveSegmentPrice;
11
+ exports.getOrderEnginePriceReferences = getOrderEnginePriceReferences;
11
12
  exports.hasFlaggedHalfHalfOption = hasFlaggedHalfHalfOption;
12
13
  exports.applyNestedChooseExpensiveSegmentPrice = applyNestedChooseExpensiveSegmentPrice;
13
- exports.getOptionPriceMapFromItem = getOptionPriceMapFromItem;
14
- exports.resetOrderEngineItemPrices = resetOrderEngineItemPrices;
15
14
  exports.convertOrderEngineItemToOrderItem = convertOrderEngineItemToOrderItem;
16
15
  exports.convertItemDiscountToOrderItemDiscount = convertItemDiscountToOrderItemDiscount;
17
16
  exports.convertCatalogItemToOrderEngineItem = convertCatalogItemToOrderEngineItem;
@@ -287,65 +286,127 @@ function makeSpaceForFreeOptions(options, num_free_options) {
287
286
  }
288
287
  return [...defaultPriceOptions, ...nonDefaultOptions].sort((a, b) => a.sort_id - b.sort_id);
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
291
  * Applies `choose_expensive_segment_price` to an order engine item converted
309
292
  * from a half-half setup (top-level modifier groups = segments, single-select
310
293
  * each, only 2 or 4 segments).
311
294
  *
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.
295
+ * The expensive rule depends on which halves the user actually picked, so it
296
+ * cannot run during `IHalfHalfSetup -> IItem` conversion — it must run after
297
+ * selection, on the WORKING data. When `originalPriceReferences` is provided,
298
+ * every option price is first re-based from that immutable reference, which
299
+ * makes the rule fully reversible: picking a cheaper pair afterwards restores
300
+ * the previous (raised) prices instead of accumulating them.
320
301
  *
321
302
  * Rule: `price = base + upsell` — the item (option) level upsell is already
322
303
  * baked into the option price at conversion. choose_expensive compares every
323
- * SELECTED segment option (option price + required/price-defining modifier
324
- * prices — e.g. a "Pizza Size" group whose Small/Large/X-Large options are
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.
304
+ * segment option (option price + required/price-defining modifier prices —
305
+ * e.g. a "Pizza Size" group whose Small/Large/X-Large options are part of the
306
+ * item's price) and levels the cheaper ones to the most expensive SELECTED
307
+ * half — `A($5)+B($5)` charges 5+5, `B($5)+C($6)` charges 6+6, and switching
308
+ * `C+D -> A+B` lowers them again. Unselected options are levelled too, so the
309
+ * drawer can SHOW what an option would cost before it is picked (they never
310
+ * contribute to totals while unselected). The raise is applied to the FIRST
311
+ * PRICED element along the segment's price chain: the segment option's own
312
+ * price when non-zero, else the first priced required leaf ("First Half ->
313
+ * ROMA -> Pizza Size -> Large 13"") — see `findRaiseTarget`. Optional/upsell
314
+ * modifier groups are excluded: they add on top and must not influence the
315
+ * comparison. The IHalfHalfSetup level upsell is NOT part of this rule: it is
316
+ * the converted item's own price and is added once on top of the combined
317
+ * subtotal. Free (`is_free`) options never drive the comparison and are never
318
+ * raised.
334
319
  *
335
320
  * All prices here are plain numbers (engine-priced).
336
321
  *
337
- * Returns the item unchanged when nothing changes.
322
+ * Returns the item unchanged when no segment option is selected (only
323
+ * re-based when references were provided).
338
324
  */
339
325
  function applyChooseExpensiveSegmentPrice(orderEngineItem, options) {
340
- const segmentGroups = (orderEngineItem.modifiers ?? []).filter((modifier) => modifier.depth === 0);
326
+ const references = options?.originalPriceReferences;
327
+ const rebased = references
328
+ ? {
329
+ ...orderEngineItem,
330
+ modifiers: rebaseEngineOptionPrices(orderEngineItem.modifiers ?? [], references, '', 'all', true),
331
+ }
332
+ : orderEngineItem;
333
+ const segmentGroups = (rebased.modifiers ?? []).filter((modifier) => modifier.depth === 0);
341
334
  if (segmentGroups.length < 2)
342
- return orderEngineItem;
343
- const raised = applyChooseExpensiveSegmentPriceToModifiers(segmentGroups, options);
335
+ return references ? syncOrderEngineItem(rebased) : rebased;
336
+ const raised = applyChooseExpensiveSegmentPriceToModifiers(segmentGroups);
344
337
  if (raised == null)
345
- return orderEngineItem;
338
+ return references ? syncOrderEngineItem(rebased) : rebased;
346
339
  let segmentGroupIndex = 0;
347
- const modifiers = (orderEngineItem.modifiers ?? []).map((modifier) => modifier.depth !== 0 ? modifier : raised[segmentGroupIndex++]);
348
- return syncOrderEngineItem({ ...orderEngineItem, modifiers });
340
+ const modifiers = (rebased.modifiers ?? []).map((modifier) => modifier.depth !== 0 ? modifier : raised[segmentGroupIndex++]);
341
+ return syncOrderEngineItem({ ...rebased, modifiers });
342
+ }
343
+ /**
344
+ * Path key of an option inside its modifier chain — `_`-joined ids from the
345
+ * root, identical to the identifiers used by `setCheckFieldInOrderEngineItem`
346
+ * (ids are BSON ObjectIds so `_` is unambiguous).
347
+ */
348
+ const buildOptionPath = (modifierPath, optionId) => `${modifierPath}_${optionId}`;
349
+ /**
350
+ * Records the ORIGINAL price of every option in the engine tree, keyed by its
351
+ * option path (see `TOrderEnginePriceReferences`). One walk, no copies — the
352
+ * map is the engine's memory for reversible price normalization.
353
+ */
354
+ function getOrderEnginePriceReferences(orderEngineItem) {
355
+ const references = {};
356
+ const walk = (modifiers, parentPath) => {
357
+ modifiers.forEach((modifier) => {
358
+ const modifierPath = parentPath ? `${parentPath}_${modifier._id}` : modifier._id;
359
+ (modifier.options ?? []).forEach((option) => {
360
+ const optionPath = buildOptionPath(modifierPath, option._id);
361
+ references[optionPath] = option.price ?? 0;
362
+ walk(option.modifiers ?? [], optionPath);
363
+ });
364
+ });
365
+ };
366
+ walk(orderEngineItem.modifiers ?? [], '');
367
+ return references;
368
+ }
369
+ /**
370
+ * Re-bases engine option prices from `references` (option path -> original
371
+ * price). The scope decides WHICH options are re-based:
372
+ * - `'all'` — every option (standalone half-half: segments and
373
+ * the required leaves that carry their price),
374
+ * - `'flaggedHalfHalf'` — only options inside a HALF_HALF option carrying
375
+ * the setup flag (a half-half nested in a special;
376
+ * the special's own option prices keep whatever the
377
+ * conversion produced).
378
+ * Returns the SAME tree object when no price changed (no needless copies).
379
+ */
380
+ function rebaseEngineOptionPrices(modifiers, references, parentPath, scope, insideScope) {
381
+ let treeChanged = false;
382
+ const nextModifiers = modifiers.map((modifier) => {
383
+ const modifierPath = parentPath ? `${parentPath}_${modifier._id}` : modifier._id;
384
+ let modifierChanged = false;
385
+ const nextOptions = (modifier.options ?? []).map((option) => {
386
+ let nextOption = option;
387
+ const optionPath = buildOptionPath(modifierPath, option._id);
388
+ if (insideScope) {
389
+ const originalPrice = references[optionPath];
390
+ if (originalPrice != null && originalPrice !== option.price) {
391
+ nextOption = { ...nextOption, price: originalPrice };
392
+ modifierChanged = true;
393
+ }
394
+ }
395
+ const isFlaggedHalfHalf = option.ref_type === constants_1.MODIFIER_OPTION_REF_TYPE_ENUM.HALF_HALF && option.choose_expensive_segment_price === true;
396
+ const childInsideScope = insideScope || (scope === 'flaggedHalfHalf' && isFlaggedHalfHalf);
397
+ const nextChildModifiers = rebaseEngineOptionPrices(nextOption.modifiers ?? [], references, optionPath, scope, childInsideScope);
398
+ if (nextChildModifiers !== nextOption.modifiers) {
399
+ nextOption = { ...nextOption, modifiers: nextChildModifiers };
400
+ modifierChanged = true;
401
+ }
402
+ return nextOption;
403
+ });
404
+ if (!modifierChanged)
405
+ return modifier;
406
+ treeChanged = true;
407
+ return { ...modifier, options: nextOptions };
408
+ });
409
+ return treeChanged ? nextModifiers : modifiers;
349
410
  }
350
411
  /**
351
412
  * Core `choose_expensive_segment_price` normalization over a list of segment
@@ -356,9 +417,7 @@ function applyChooseExpensiveSegmentPrice(orderEngineItem, options) {
356
417
  * Returns null when nothing needs to change (no selected option / no priced
357
418
  * segment), otherwise the raised segment groups.
358
419
  */
359
- function applyChooseExpensiveSegmentPriceToModifiers(segmentGroups, options) {
360
- const hasBasePrices = options?.basePrices != null;
361
- const groups = resetEngineOptionPrices(segmentGroups, options?.basePrices);
420
+ function applyChooseExpensiveSegmentPriceToModifiers(segmentGroups) {
362
421
  // Prices of ALL options of required (price-defining) modifier groups, at
363
422
  // any depth — e.g. "Pizza Size" -> "Large 13"" is part of the item's price
364
423
  // whichever size is picked (mirrors `getSegmentItemTotalPrice` used by the
@@ -383,8 +442,8 @@ function applyChooseExpensiveSegmentPriceToModifiers(segmentGroups, options) {
383
442
  const getSegmentTotal = (option) => (option.price ?? 0) + getRequiredOptionPrices(option.modifiers);
384
443
  // One selected option per segment group (segments are single-select).
385
444
  const selections = [];
386
- for (let g = 0; g < groups.length; g++) {
387
- const options = groups[g].options ?? [];
445
+ for (let g = 0; g < segmentGroups.length; g++) {
446
+ const options = segmentGroups[g].options ?? [];
388
447
  for (let o = 0; o < options.length; o++) {
389
448
  const option = options[o];
390
449
  if (!option.default || option.is_free)
@@ -394,21 +453,23 @@ function applyChooseExpensiveSegmentPriceToModifiers(segmentGroups, options) {
394
453
  }
395
454
  }
396
455
  if (selections.length === 0)
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.
456
+ return null;
457
+ // Max over the SELECTED segment options only — the expensive half is the
458
+ // most expensive one the user actually PICKED, not the setup's global max:
459
+ // picking A($5)+B($5) must charge 5+5 even though C($6)/D($6) exist.
460
+ // Free options never drive the comparison.
402
461
  let maxSegmentValue = 0;
403
462
  for (const selection of selections) {
404
- const option = groups[selection.groupIndex].options[selection.optionIndex];
463
+ const option = segmentGroups[selection.groupIndex].options[selection.optionIndex];
464
+ if (option.is_free)
465
+ continue;
405
466
  const segmentValue = getSegmentTotal(option);
406
467
  if (segmentValue > maxSegmentValue) {
407
468
  maxSegmentValue = segmentValue;
408
469
  }
409
470
  }
410
471
  if (maxSegmentValue <= 0)
411
- return hasBasePrices ? groups : null;
472
+ return null;
412
473
  // RULE for where the raise lands: on the FIRST PRICED element along the
413
474
  // segment's price chain —
414
475
  // 1. the segment option's own price (the item base) when it is non-zero
@@ -448,23 +509,26 @@ function applyChooseExpensiveSegmentPriceToModifiers(segmentGroups, options) {
448
509
  })),
449
510
  };
450
511
  };
451
- return groups.map((modifier, g) => {
452
- const options = (modifier.options ?? []).map((option, o) => {
453
- const selection = selections.find((s) => s.groupIndex === g && s.optionIndex === o);
454
- if (selection == null)
512
+ // Every option whose segment price is below that max is levelled to it:
513
+ // selected halves are CHARGED that way, unselected ones SHOW what they would
514
+ // cost if picked (they never contribute to totals while unselected), and
515
+ // free options are never raised.
516
+ return segmentGroups.map((modifier) => ({
517
+ ...modifier,
518
+ options: (modifier.options ?? []).map((option) => {
519
+ if (option.is_free)
455
520
  return option;
456
521
  const segmentValue = getSegmentTotal(option);
457
- // Already at (or above) the most expensive segment price: keep as is.
522
+ // Already at (or above) the most expensive selected segment: keep as is.
458
523
  if (segmentValue >= maxSegmentValue)
459
524
  return option;
460
- // Raise by the difference so the segment's final price (base + upsell +
461
- // required modifiers) equals the expensive one — applied to the priced
462
- // leaf when available (see `raiseSegmentOption`). The IHalfHalfSetup
463
- // upsell (item price) is untouched.
525
+ // Level by the difference so the segment's final price (base + upsell +
526
+ // required modifiers) equals the expensive selected half — applied to
527
+ // the priced leaf when available (see `raiseSegmentOption`). The
528
+ // IHalfHalfSetup upsell (item price) is untouched.
464
529
  return raiseSegmentOption(option, maxSegmentValue - segmentValue);
465
- });
466
- return { ...modifier, options };
467
- });
530
+ }),
531
+ }));
468
532
  }
469
533
  /**
470
534
  * True when the item has a top-level modifier group option that is a nested
@@ -476,95 +540,38 @@ function hasFlaggedHalfHalfOption(orderEngineItem) {
476
540
  /**
477
541
  * `choose_expensive_segment_price` for a half-half option nested in a special:
478
542
  * the option's own top-level modifiers are its segment groups, so they get the
479
- * same raise-to-most-expensive treatment as a standalone half-half item.
480
- * ITEM options are terminal (their nested modifiers can never contain
481
- * ITEM/HALF_HALF); normal options pass untouched. Runs on a copy with pristine
482
- * `basePrices` when provided (see `IChooseExpensiveSegmentPriceOptions`).
543
+ * same level-to-the-most-expensive-SELECTED-half treatment as a standalone
544
+ * half-half item. ITEM options are terminal (their nested modifiers can never
545
+ * contain ITEM/HALF_HALF); normal options pass untouched.
546
+ *
547
+ * When `originalPriceReferences` is provided, prices are re-based first — but
548
+ * ONLY inside the flagged half-half subtrees, so the special's own option
549
+ * prices keep whatever the conversion produced.
483
550
  */
484
551
  function applyNestedChooseExpensiveSegmentPrice(orderEngineItem, options) {
485
- const modifiers = (orderEngineItem.modifiers ?? []).map((modifier) => ({
552
+ const references = options?.originalPriceReferences;
553
+ const rebased = references
554
+ ? {
555
+ ...orderEngineItem,
556
+ modifiers: rebaseEngineOptionPrices(orderEngineItem.modifiers ?? [], references, '', 'flaggedHalfHalf', false),
557
+ }
558
+ : orderEngineItem;
559
+ const modifiers = (rebased.modifiers ?? []).map((modifier) => ({
486
560
  ...modifier,
487
561
  options: (modifier.options ?? []).map((option) => {
488
562
  if (option.ref_type !== constants_1.MODIFIER_OPTION_REF_TYPE_ENUM.HALF_HALF ||
489
563
  option.choose_expensive_segment_price !== true) {
490
564
  return option;
491
565
  }
492
- const raised = applyChooseExpensiveSegmentPriceToModifiers(option.modifiers ?? [], options);
566
+ const raised = applyChooseExpensiveSegmentPriceToModifiers(option.modifiers ?? []);
493
567
  if (raised == null)
494
568
  return option;
495
569
  return { ...option, modifiers: raised };
496
570
  }),
497
571
  }));
498
- return syncOrderEngineItem({ ...orderEngineItem, modifiers });
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
- * The flat `_id -> price` shape can only represent ONE value per option
507
- * `_id`, so callers MUST keep the map to a single price scope. A half-half
508
- * nested in a special is exactly the case where that fails: its segment
509
- * options are built FROM the special's items, so they reuse the SAME `_id`s
510
- * as the special's top-level options while their prices differ (top-level =
511
- * full upsell, segment = per-segment share). `nestedHalfHalfSegmentsOnly`
512
- * keeps the map to the subtrees of HALF_HALF options (the segment trees plus
513
- * their nested modifiers), excluding top-level option prices — the special
514
- * drawer feeds this map to `resetOrderEngineItemPrices` / the nested
515
- * normalization, so the walk order of the item can never leak a top-level
516
- * price into a segment (or the other way around). Standalone half-half items
517
- * are a single scope: every segment shares its option `_id`s with the SAME
518
- * price, so the unscoped map is safe there.
519
- */
520
- function getOptionPriceMapFromItem(item, platform, options) {
521
- const priceMap = {};
522
- const nestedHalfHalfSegmentsOnly = options?.nestedHalfHalfSegmentsOnly === true;
523
- const walk = (modifiers, insideHalfHalf) => {
524
- (modifiers ?? []).forEach((modifier) => {
525
- (modifier.options ?? []).forEach((option) => {
526
- const isHalfHalf = option.ref_type === constants_1.MODIFIER_OPTION_REF_TYPE_ENUM.HALF_HALF;
527
- // Inside a half-half subtree every option belongs to the segment
528
- // scope; at the top level only record when not scoped (or record
529
- // nothing because the option is the half-half hub itself, whose price
530
- // is NOT part of the segment scope).
531
- if (insideHalfHalf || !nestedHalfHalfSegmentsOnly) {
532
- priceMap[option._id] = (0, platform_catalog_1.getPriceEnum)(option.price, platform);
533
- }
534
- walk(option.modifiers, insideHalfHalf || isHalfHalf);
535
- });
536
- });
537
- };
538
- walk(item.modifiers, false);
539
- return priceMap;
572
+ return syncOrderEngineItem({ ...rebased, modifiers });
540
573
  }
541
- /**
542
- * Restores every engine option price from the pristine `basePrices` map (by
543
- * option `_id`). Called when the drawer builds the engine item so state
544
- * (sidebar prices, edit baselines) never carries a previous normalization.
545
- *
546
- * `options.nestedHalfHalfOnly` restricts the reset to the subtrees of
547
- * HALF_HALF options — the exact scope `getOptionPriceMapFromItem` builds when
548
- * called with `nestedHalfHalfSegmentsOnly`. A special's top-level options
549
- * reuse their `_id`s at different prices (full upsell vs per-segment share),
550
- * so a blanket reset with the scoped map would push the segment share onto
551
- * the top-level option. ALWAYS pass the SAME scope to the map builder and to
552
- * this reset.
553
- */
554
- function resetOrderEngineItemPrices(orderEngineItem, basePrices, options) {
555
- if (options?.nestedHalfHalfOnly === true) {
556
- const modifiers = (orderEngineItem.modifiers ?? []).map((modifier) => ({
557
- ...modifier,
558
- options: (modifier.options ?? []).map((option) => option.ref_type !== constants_1.MODIFIER_OPTION_REF_TYPE_ENUM.HALF_HALF
559
- ? option
560
- : { ...option, modifiers: resetEngineOptionPrices(option.modifiers ?? [], basePrices) }),
561
- }));
562
- return syncOrderEngineItem({ ...orderEngineItem, modifiers });
563
- }
564
- const modifiers = resetEngineOptionPrices(orderEngineItem.modifiers ?? [], basePrices);
565
- return syncOrderEngineItem({ ...orderEngineItem, modifiers });
566
- }
567
- function convertCatalogItemModifierToOrderEngineItemModifier({ modifiers, orderItemModifiers, platform, tenantId, excludeRefs, zeroPriceRefs, loyaltyRefs, voucherRefs, keepOptionalModifiersAtBottom, soldoutModifiers, depth = 0, }) {
574
+ function convertCatalogItemModifierToOrderEngineItemModifier({ modifiers, orderItemModifiers, platform, tenantId, excludeRefs, zeroPriceRefs, loyaltyRefs, voucherRefs, keepOptionalModifiersAtBottom, soldoutModifiers, depth = 0, priceReferences, parentPath, }) {
568
575
  function getSortedModifiers(modifiers = []) {
569
576
  const sortedModifiers = modifiers.sort((a, b) => a.sort_id - b.sort_id);
570
577
  return sortedModifiers;
@@ -600,6 +607,7 @@ function convertCatalogItemModifierToOrderEngineItemModifier({ modifiers, orderI
600
607
  // If excludeRefs is present then we exclude those modifiers
601
608
  if (excludeRefs != null && excludeRefs.includes(modifier.ref))
602
609
  continue;
610
+ const modifierPath = parentPath ? `${parentPath}_${modifier._id}` : modifier._id;
603
611
  const orderItemModifier = orderItemModifiers?.find((orderModifier) => orderModifier._id === modifier._id);
604
612
  const hasOrderItemSelectedOptions = orderItemModifier != null && orderItemModifier.options.length > 0;
605
613
  const maxDefaultSelections = modifier.max_aggregate_options_quantity ?? modifier.max_num_options ?? modifier.options.length;
@@ -648,11 +656,17 @@ function convertCatalogItemModifierToOrderEngineItemModifier({ modifiers, orderI
648
656
  keepOptionalModifiersAtBottom,
649
657
  soldoutModifiers,
650
658
  depth: depth + 1,
659
+ priceReferences,
660
+ parentPath: `${modifierPath}_${option._id}`,
651
661
  });
652
662
  // If zeroPriceRefs is present then we set the price to 0
653
- const optionPrice = zeroPriceRefs != null && (zeroPriceRefs.includes(option.ref) || zeroPriceRefs.includes(modifier.ref))
654
- ? 0
655
- : price;
663
+ const isZeroPriced = zeroPriceRefs != null && (zeroPriceRefs.includes(option.ref) || zeroPriceRefs.includes(modifier.ref));
664
+ const optionPrice = isZeroPriced ? 0 : price;
665
+ // ORIGINAL (definition) price of the option — deliberately NOT the
666
+ // persisted order price used above: it is the immutable reference the
667
+ // choose_expensive rule re-bases from (so edit flows can never treat an
668
+ // already-normalized price as the original).
669
+ priceReferences[`${modifierPath}_${option._id}`] = isZeroPriced ? 0 : (0, platform_catalog_1.getPriceEnum)(option.price, platform);
656
670
  const orderEngineSingleOption = {
657
671
  ...option,
658
672
  default: isDefaultOption,
@@ -846,6 +860,9 @@ function convertCatalogItemToOrderEngineItem({ item, orderItem, platform, tenant
846
860
  // Default values will be used in case of new order
847
861
  // we need to find the applicable schedule for the item
848
862
  const applicableSchedule = (0, platform_catalog_1.findApplicableSchedule)(item.item_special_hours, platform);
863
+ // Definition prices of every option, keyed by option path — the immutable
864
+ // baseline the UI re-bases from before every price normalization.
865
+ const originalPriceReferences = {};
849
866
  const orderEngineModifiers = convertCatalogItemModifierToOrderEngineItemModifier({
850
867
  modifiers: item.modifiers,
851
868
  orderItemModifiers: orderItem?.modifiers,
@@ -857,6 +874,8 @@ function convertCatalogItemToOrderEngineItem({ item, orderItem, platform, tenant
857
874
  voucherRefs: applyVoucher?.refs,
858
875
  keepOptionalModifiersAtBottom,
859
876
  soldoutModifiers,
877
+ priceReferences: originalPriceReferences,
878
+ parentPath: '',
860
879
  });
861
880
  let itemPrice = item.price;
862
881
  let discount_amount = item.discount_amount;
@@ -937,7 +956,7 @@ function convertCatalogItemToOrderEngineItem({ item, orderItem, platform, tenant
937
956
  item_discount_details: mergedItemDiscountDetails,
938
957
  modifiers: orderEngineModifiers,
939
958
  });
940
- return orderEngineItem;
959
+ return { originalPriceReferences, workingData: orderEngineItem };
941
960
  }
942
961
  function hasRequiredModifier(currentModifiers) {
943
962
  if (!currentModifiers)
@@ -1111,14 +1130,21 @@ function setCheckFieldInOrderEngineItem(orderEngineItem, identifier, shouldCheck
1111
1130
  const allIds = identifier.split('_').filter((id) => id.trim() !== '');
1112
1131
  const modifiers = setUpdateModifiers(orderEngineItem.modifiers, allIds, 0);
1113
1132
  const updatedOrderEngineItem = syncOrderEngineItem({ ...orderEngineItem, modifiers });
1114
- // NOTE: `choose_expensive_segment_price` is intentionally NOT applied here.
1115
- // The rule depends on the current selection and must be able to LOWER prices
1116
- // again when a cheaper combination is picked, so normalization runs at
1117
- // display/submit time on a copy of the engine item with pristine
1118
- // `basePrices` (see `applyChooseExpensiveSegmentPrice` /
1119
- // `applyNestedChooseExpensiveSegmentPrice`). The parameter is kept for
1120
- // backwards compatibility.
1121
- void chooseExpensiveSegmentPrice;
1133
+ // Half-half classic view: `choose_expensive_segment_price` depends on which
1134
+ // halves the user actually picked, so it cannot run during
1135
+ // `IHalfHalfSetup -> IItem` conversion — it is applied right here, after
1136
+ // every selection, whenever the caller passes the setup flag. It compares
1137
+ // EVERY segment option (option base + item upsell + required/price-defining
1138
+ // modifiers) and raises the selected ones to the setup's most expensive
1139
+ // segment. Idempotent: it never lowers a price, so re-running is safe.
1140
+ if (orderEngineItem.item_type === constants_1.ORDER_ITEM_TYPE_ENUM.HALF_HALF && chooseExpensiveSegmentPrice === true) {
1141
+ return applyChooseExpensiveSegmentPrice(updatedOrderEngineItem);
1142
+ }
1143
+ // Half-half option nested in a special: normalize its own segment groups
1144
+ // (the option's top-level modifiers) whenever it carries the setup flag.
1145
+ if (orderEngineItem.item_type === constants_1.ORDER_ITEM_TYPE_ENUM.SPECIAL && hasFlaggedHalfHalfOption(updatedOrderEngineItem)) {
1146
+ return applyNestedChooseExpensiveSegmentPrice(updatedOrderEngineItem);
1147
+ }
1122
1148
  return updatedOrderEngineItem;
1123
1149
  }
1124
1150
  function setIncrementOrderEngineItemQuantity(orderEngineItem, increment) {