@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.
@@ -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,88 +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
- /**
291
- * Restores engine option prices from the pristine baseline: the per-option
292
- * `base_price` the engine stamped when the item was built, overridden by the
293
- * optional external `_id -> price` map (see
294
- * `IChooseExpensiveSegmentPriceOptions`). This is the engine's own memory —
295
- * re-basing never depends on callers keeping a pristine copy of the item.
296
- */
297
- const resetEngineOptionPrices = (modifiers, basePrices) => {
298
- const resetOption = (option) => ({
299
- ...option,
300
- price: basePrices?.[option._id] ?? option.base_price ?? option.price,
301
- modifiers: (option.modifiers ?? []).map((modifier) => ({
302
- ...modifier,
303
- options: (modifier.options ?? []).map(resetOption),
304
- })),
305
- });
306
- return modifiers.map((modifier) => ({
307
- ...modifier,
308
- options: (modifier.options ?? []).map(resetOption),
309
- }));
310
- };
311
- /** True when two modifier trees carry the same option prices at the same positions. */
312
- const haveSameOptionPrices = (a, b) => {
313
- if (a.length !== b.length)
314
- return false;
315
- for (let i = 0; i < a.length; i++) {
316
- const optionsA = a[i].options ?? [];
317
- const optionsB = b[i].options ?? [];
318
- if (optionsA.length !== optionsB.length)
319
- return false;
320
- for (let j = 0; j < optionsA.length; j++) {
321
- if ((optionsA[j].price ?? 0) !== (optionsB[j].price ?? 0))
322
- return false;
323
- if (!haveSameOptionPrices(optionsA[j].modifiers ?? [], optionsB[j].modifiers ?? []))
324
- return false;
325
- }
326
- }
327
- return true;
328
- };
289
+ // ====================================>>><<<======================================
329
290
  /**
330
291
  * Applies `choose_expensive_segment_price` to an order engine item converted
331
292
  * from a half-half setup (top-level modifier groups = segments, single-select
332
293
  * each, only 2 or 4 segments).
333
294
  *
334
- * The rule is a pure function of the CURRENT selection: the most expensive
335
- * half the user actually picked sets the charged price for every picked half
336
- * (cheaper halves are raised to it; picking a cheaper combination later
337
- * lowers them again). It cannot run during `IHalfHalfSetup -> IItem`
338
- * conversion — it runs at display/submit time on the engine item, re-basing
339
- * every price from the engine's own memory (the `base_price` stamped at
340
- * conversion) so the result NEVER accumulates raises, even when the item is
341
- * mutated in place across selection changes. `basePrices` can override that
342
- * baseline (see `IChooseExpensiveSegmentPriceOptions`).
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.
343
301
  *
344
302
  * Rule: `price = base + upsell` — the item (option) level upsell is already
345
303
  * baked into the option price at conversion. choose_expensive compares every
346
- * SELECTED segment option (option price + required/price-defining modifier
347
- * prices — e.g. a "Pizza Size" group whose Small/Large/X-Large options are
348
- * part of the item's price) and raises the cheaper ones so their final
349
- * segment price matches the most expensive selected half. The raise is
350
- * applied to the FIRST PRICED element along the segment's price chain: the
351
- * segment option's own price when non-zero, else the first priced required
352
- * leaf ("First Half -> ROMA -> Pizza Size -> Large 13\"") — see
353
- * `findRaiseTarget`. Optional/upsell modifier groups are excluded: they add
354
- * on top and must not influence the comparison. The IHalfHalfSetup level
355
- * upsell is NOT part of this rule: it is the converted item's own price and
356
- * 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.
357
319
  *
358
320
  * All prices here are plain numbers (engine-priced).
359
321
  *
360
- * 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).
361
324
  */
362
325
  function applyChooseExpensiveSegmentPrice(orderEngineItem, options) {
363
- 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);
364
334
  if (segmentGroups.length < 2)
365
- return orderEngineItem;
366
- const raised = applyChooseExpensiveSegmentPriceToModifiers(segmentGroups, options);
335
+ return references ? syncOrderEngineItem(rebased) : rebased;
336
+ const raised = applyChooseExpensiveSegmentPriceToModifiers(segmentGroups);
367
337
  if (raised == null)
368
- return orderEngineItem;
338
+ return references ? syncOrderEngineItem(rebased) : rebased;
369
339
  let segmentGroupIndex = 0;
370
- const modifiers = (orderEngineItem.modifiers ?? []).map((modifier) => modifier.depth !== 0 ? modifier : raised[segmentGroupIndex++]);
371
- 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;
372
410
  }
373
411
  /**
374
412
  * Core `choose_expensive_segment_price` normalization over a list of segment
@@ -379,11 +417,7 @@ function applyChooseExpensiveSegmentPrice(orderEngineItem, options) {
379
417
  * Returns null when nothing needs to change (no selected option / no priced
380
418
  * segment), otherwise the raised segment groups.
381
419
  */
382
- function applyChooseExpensiveSegmentPriceToModifiers(segmentGroups, options) {
383
- // Re-base from the engine's own memory (or the caller's override) so the
384
- // rule is always a pure function of the CURRENT selection: switching to a
385
- // cheaper combination lowers the previously raised halves again.
386
- const groups = resetEngineOptionPrices(segmentGroups, options?.basePrices);
420
+ function applyChooseExpensiveSegmentPriceToModifiers(segmentGroups) {
387
421
  // Prices of ALL options of required (price-defining) modifier groups, at
388
422
  // any depth — e.g. "Pizza Size" -> "Large 13"" is part of the item's price
389
423
  // whichever size is picked (mirrors `getSegmentItemTotalPrice` used by the
@@ -408,8 +442,8 @@ function applyChooseExpensiveSegmentPriceToModifiers(segmentGroups, options) {
408
442
  const getSegmentTotal = (option) => (option.price ?? 0) + getRequiredOptionPrices(option.modifiers);
409
443
  // One selected option per segment group (segments are single-select).
410
444
  const selections = [];
411
- for (let g = 0; g < groups.length; g++) {
412
- const options = groups[g].options ?? [];
445
+ for (let g = 0; g < segmentGroups.length; g++) {
446
+ const options = segmentGroups[g].options ?? [];
413
447
  for (let o = 0; o < options.length; o++) {
414
448
  const option = options[o];
415
449
  if (!option.default || option.is_free)
@@ -419,21 +453,23 @@ function applyChooseExpensiveSegmentPriceToModifiers(segmentGroups, options) {
419
453
  }
420
454
  }
421
455
  if (selections.length === 0)
422
- return haveSameOptionPrices(groups, segmentGroups) ? null : groups;
423
- // Max over the SELECTED halves only — the "expensive segment" is the most
424
- // expensive half the user actually picked, not the most expensive option in
425
- // the setup (otherwise picking A+B would charge as if C+D were chosen).
426
- // 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.
427
461
  let maxSegmentValue = 0;
428
462
  for (const selection of selections) {
429
- const option = groups[selection.groupIndex].options[selection.optionIndex];
463
+ const option = segmentGroups[selection.groupIndex].options[selection.optionIndex];
464
+ if (option.is_free)
465
+ continue;
430
466
  const segmentValue = getSegmentTotal(option);
431
467
  if (segmentValue > maxSegmentValue) {
432
468
  maxSegmentValue = segmentValue;
433
469
  }
434
470
  }
435
471
  if (maxSegmentValue <= 0)
436
- return haveSameOptionPrices(groups, segmentGroups) ? null : groups;
472
+ return null;
437
473
  // RULE for where the raise lands: on the FIRST PRICED element along the
438
474
  // segment's price chain —
439
475
  // 1. the segment option's own price (the item base) when it is non-zero
@@ -473,26 +509,26 @@ function applyChooseExpensiveSegmentPriceToModifiers(segmentGroups, options) {
473
509
  })),
474
510
  };
475
511
  };
476
- const raised = groups.map((modifier, g) => {
477
- const options = (modifier.options ?? []).map((option, o) => {
478
- const selection = selections.find((s) => s.groupIndex === g && s.optionIndex === o);
479
- 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)
480
520
  return option;
481
521
  const segmentValue = getSegmentTotal(option);
482
- // 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.
483
523
  if (segmentValue >= maxSegmentValue)
484
524
  return option;
485
- // Raise by the difference so the segment's final price (base + upsell +
486
- // required modifiers) equals the expensive one — applied to the priced
487
- // leaf when available (see `raiseSegmentOption`). The IHalfHalfSetup
488
- // 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.
489
529
  return raiseSegmentOption(option, maxSegmentValue - segmentValue);
490
- });
491
- return { ...modifier, options };
492
- });
493
- // Nothing to change (pristine prices for the current selection): report
494
- // "no change" so callers keep the original engine item object.
495
- return haveSameOptionPrices(raised, segmentGroups) ? null : raised;
530
+ }),
531
+ }));
496
532
  }
497
533
  /**
498
534
  * True when the item has a top-level modifier group option that is a nested
@@ -504,97 +540,38 @@ function hasFlaggedHalfHalfOption(orderEngineItem) {
504
540
  /**
505
541
  * `choose_expensive_segment_price` for a half-half option nested in a special:
506
542
  * the option's own top-level modifiers are its segment groups, so they get the
507
- * same raise-to-most-expensive treatment as a standalone half-half item.
508
- * ITEM options are terminal (their nested modifiers can never contain
509
- * ITEM/HALF_HALF); normal options pass untouched. Runs on a copy with pristine
510
- * `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.
511
550
  */
512
551
  function applyNestedChooseExpensiveSegmentPrice(orderEngineItem, options) {
513
- 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) => ({
514
560
  ...modifier,
515
561
  options: (modifier.options ?? []).map((option) => {
516
562
  if (option.ref_type !== constants_1.MODIFIER_OPTION_REF_TYPE_ENUM.HALF_HALF ||
517
563
  option.choose_expensive_segment_price !== true) {
518
564
  return option;
519
565
  }
520
- const raised = applyChooseExpensiveSegmentPriceToModifiers(option.modifiers ?? [], options);
566
+ const raised = applyChooseExpensiveSegmentPriceToModifiers(option.modifiers ?? []);
521
567
  if (raised == null)
522
568
  return option;
523
569
  return { ...option, modifiers: raised };
524
570
  }),
525
571
  }));
526
- return syncOrderEngineItem({ ...orderEngineItem, modifiers });
572
+ return syncOrderEngineItem({ ...rebased, modifiers });
527
573
  }
528
- /**
529
- * Builds a pristine `_id -> price` map of every option in a converted catalog
530
- * item (`modifiers -> options -> nested modifiers -> options ...`). Used as
531
- * the baseline for `choose_expensive_segment_price` so applying the rule never
532
- * depends on previously raised prices.
533
- *
534
- * The flat `_id -> price` shape can only represent ONE value per option
535
- * `_id`, so callers MUST keep the map to a single price scope. A half-half
536
- * nested in a special is exactly the case where that fails: its segment
537
- * options are built FROM the special's items, so they reuse the SAME `_id`s
538
- * as the special's top-level options while their prices differ (top-level =
539
- * full upsell, segment = per-segment share). `nestedHalfHalfSegmentsOnly`
540
- * keeps the map to the subtrees of HALF_HALF options (the segment trees plus
541
- * their nested modifiers), excluding top-level option prices — the special
542
- * drawer feeds this map to `resetOrderEngineItemPrices` / the nested
543
- * normalization, so the walk order of the item can never leak a top-level
544
- * price into a segment (or the other way around). Standalone half-half items
545
- * are a single scope: every segment shares its option `_id`s with the SAME
546
- * price, so the unscoped map is safe there.
547
- */
548
- function getOptionPriceMapFromItem(item, platform, options) {
549
- const priceMap = {};
550
- const nestedHalfHalfSegmentsOnly = options?.nestedHalfHalfSegmentsOnly === true;
551
- const walk = (modifiers, insideHalfHalf) => {
552
- (modifiers ?? []).forEach((modifier) => {
553
- (modifier.options ?? []).forEach((option) => {
554
- const isHalfHalf = option.ref_type === constants_1.MODIFIER_OPTION_REF_TYPE_ENUM.HALF_HALF;
555
- // Inside a half-half subtree every option belongs to the segment
556
- // scope; at the top level only record when not scoped (or record
557
- // nothing because the option is the half-half hub itself, whose price
558
- // is NOT part of the segment scope).
559
- if (insideHalfHalf || !nestedHalfHalfSegmentsOnly) {
560
- priceMap[option._id] = (0, platform_catalog_1.getPriceEnum)(option.price, platform);
561
- }
562
- walk(option.modifiers, insideHalfHalf || isHalfHalf);
563
- });
564
- });
565
- };
566
- walk(item.modifiers, false);
567
- return priceMap;
568
- }
569
- /**
570
- * Re-bases every engine option price from the engine's own memory (the
571
- * `base_price` stamped at conversion), optionally overridden by an explicit
572
- * `basePrices` map. Called when a drawer builds the engine item so state
573
- * (sidebar prices, edit baselines) never carries a previous normalization.
574
- *
575
- * `options.nestedHalfHalfOnly` restricts the reset to the subtrees of
576
- * HALF_HALF options — the exact scope `getOptionPriceMapFromItem` builds when
577
- * called with `nestedHalfHalfSegmentsOnly`. Only needed when an external
578
- * `basePrices` map is passed (a special's top-level options reuse their `_id`s
579
- * at different prices, so a blanket reset with the scoped map would push the
580
- * segment share onto the top-level option). With the engine's own stamps the
581
- * scope is inherent — pass the SAME scope to the map builder and to this
582
- * reset when you do pass a map.
583
- */
584
- function resetOrderEngineItemPrices(orderEngineItem, basePrices, options) {
585
- if (options?.nestedHalfHalfOnly === true) {
586
- const modifiers = (orderEngineItem.modifiers ?? []).map((modifier) => ({
587
- ...modifier,
588
- options: (modifier.options ?? []).map((option) => option.ref_type !== constants_1.MODIFIER_OPTION_REF_TYPE_ENUM.HALF_HALF
589
- ? option
590
- : { ...option, modifiers: resetEngineOptionPrices(option.modifiers ?? [], basePrices) }),
591
- }));
592
- return syncOrderEngineItem({ ...orderEngineItem, modifiers });
593
- }
594
- const modifiers = resetEngineOptionPrices(orderEngineItem.modifiers ?? [], basePrices);
595
- return syncOrderEngineItem({ ...orderEngineItem, modifiers });
596
- }
597
- 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, }) {
598
575
  function getSortedModifiers(modifiers = []) {
599
576
  const sortedModifiers = modifiers.sort((a, b) => a.sort_id - b.sort_id);
600
577
  return sortedModifiers;
@@ -630,6 +607,7 @@ function convertCatalogItemModifierToOrderEngineItemModifier({ modifiers, orderI
630
607
  // If excludeRefs is present then we exclude those modifiers
631
608
  if (excludeRefs != null && excludeRefs.includes(modifier.ref))
632
609
  continue;
610
+ const modifierPath = parentPath ? `${parentPath}_${modifier._id}` : modifier._id;
633
611
  const orderItemModifier = orderItemModifiers?.find((orderModifier) => orderModifier._id === modifier._id);
634
612
  const hasOrderItemSelectedOptions = orderItemModifier != null && orderItemModifier.options.length > 0;
635
613
  const maxDefaultSelections = modifier.max_aggregate_options_quantity ?? modifier.max_num_options ?? modifier.options.length;
@@ -678,19 +656,21 @@ function convertCatalogItemModifierToOrderEngineItemModifier({ modifiers, orderI
678
656
  keepOptionalModifiersAtBottom,
679
657
  soldoutModifiers,
680
658
  depth: depth + 1,
659
+ priceReferences,
660
+ parentPath: `${modifierPath}_${option._id}`,
681
661
  });
682
662
  // If zeroPriceRefs is present then we set the price to 0
683
- const isZeroPricedOption = zeroPriceRefs != null && (zeroPriceRefs.includes(option.ref) || zeroPriceRefs.includes(modifier.ref));
684
- const optionPrice = isZeroPricedOption ? 0 : price;
685
- // The engine's own memory records the CATALOG value (`price` above may
686
- // come from the persisted order item in edit flows) so re-basing never
687
- // inherits a previously normalized (raised) price.
688
- const basePrice = isZeroPricedOption ? 0 : (0, platform_catalog_1.getPriceEnum)(option.price, platform);
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);
689
670
  const orderEngineSingleOption = {
690
671
  ...option,
691
672
  default: isDefaultOption,
692
673
  price: optionPrice,
693
- base_price: basePrice,
694
674
  quantity: qty,
695
675
  modifiers: newModifiers,
696
676
  is_free,
@@ -880,6 +860,9 @@ function convertCatalogItemToOrderEngineItem({ item, orderItem, platform, tenant
880
860
  // Default values will be used in case of new order
881
861
  // we need to find the applicable schedule for the item
882
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 = {};
883
866
  const orderEngineModifiers = convertCatalogItemModifierToOrderEngineItemModifier({
884
867
  modifiers: item.modifiers,
885
868
  orderItemModifiers: orderItem?.modifiers,
@@ -891,6 +874,8 @@ function convertCatalogItemToOrderEngineItem({ item, orderItem, platform, tenant
891
874
  voucherRefs: applyVoucher?.refs,
892
875
  keepOptionalModifiersAtBottom,
893
876
  soldoutModifiers,
877
+ priceReferences: originalPriceReferences,
878
+ parentPath: '',
894
879
  });
895
880
  let itemPrice = item.price;
896
881
  let discount_amount = item.discount_amount;
@@ -971,7 +956,7 @@ function convertCatalogItemToOrderEngineItem({ item, orderItem, platform, tenant
971
956
  item_discount_details: mergedItemDiscountDetails,
972
957
  modifiers: orderEngineModifiers,
973
958
  });
974
- return orderEngineItem;
959
+ return { originalPriceReferences, workingData: orderEngineItem };
975
960
  }
976
961
  function hasRequiredModifier(currentModifiers) {
977
962
  if (!currentModifiers)
@@ -1145,14 +1130,21 @@ function setCheckFieldInOrderEngineItem(orderEngineItem, identifier, shouldCheck
1145
1130
  const allIds = identifier.split('_').filter((id) => id.trim() !== '');
1146
1131
  const modifiers = setUpdateModifiers(orderEngineItem.modifiers, allIds, 0);
1147
1132
  const updatedOrderEngineItem = syncOrderEngineItem({ ...orderEngineItem, modifiers });
1148
- // NOTE: `choose_expensive_segment_price` is intentionally NOT applied here.
1149
- // The rule depends on the current selection and must be able to LOWER prices
1150
- // again when a cheaper combination is picked, so normalization runs at
1151
- // display/submit time on a copy of the engine item with pristine
1152
- // `basePrices` (see `applyChooseExpensiveSegmentPrice` /
1153
- // `applyNestedChooseExpensiveSegmentPrice`). The parameter is kept for
1154
- // backwards compatibility.
1155
- 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
+ }
1156
1148
  return updatedOrderEngineItem;
1157
1149
  }
1158
1150
  function setIncrementOrderEngineItemQuantity(orderEngineItem, increment) {