@managesome/eposmatic-toolkit 0.2.720 → 0.2.732

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,12 @@ exports.syncOrderEngineItem = syncOrderEngineItem;
8
8
  exports.checkIfModifiersExist = checkIfModifiersExist;
9
9
  exports.makeSpaceForFreeOptions = makeSpaceForFreeOptions;
10
10
  exports.applyChooseExpensiveSegmentPrice = applyChooseExpensiveSegmentPrice;
11
+ exports.getOrderEngineOptionSegmentValue = getOrderEngineOptionSegmentValue;
11
12
  exports.hasFlaggedHalfHalfOption = hasFlaggedHalfHalfOption;
13
+ exports.getBlockedHalfHalfOptionPaths = getBlockedHalfHalfOptionPaths;
14
+ exports.getHalfHalfBlockedItemIds = getHalfHalfBlockedItemIds;
12
15
  exports.applyNestedChooseExpensiveSegmentPrice = applyNestedChooseExpensiveSegmentPrice;
13
- exports.getOptionPriceMapFromItem = getOptionPriceMapFromItem;
14
- exports.resetOrderEngineItemPrices = resetOrderEngineItemPrices;
16
+ exports.applySegmentPriceFloor = applySegmentPriceFloor;
15
17
  exports.convertOrderEngineItemToOrderItem = convertOrderEngineItemToOrderItem;
16
18
  exports.convertItemDiscountToOrderItemDiscount = convertItemDiscountToOrderItemDiscount;
17
19
  exports.convertCatalogItemToOrderEngineItem = convertCatalogItemToOrderEngineItem;
@@ -164,6 +166,11 @@ function syncOrderEngineItem(orderEngineItem) {
164
166
  const option = modifier.options[j];
165
167
  if (!option.default)
166
168
  continue;
169
+ // `is_free` means NOT charged (the cart math —
170
+ // `calculateItemModifiersPrice` — skips them too): free options keep
171
+ // their price for reference but must never add to the totals.
172
+ if (option.is_free)
173
+ continue;
167
174
  const quantity = option.quantity || 1;
168
175
  // Add option price to total
169
176
  total += (option.price || 0) * quantity;
@@ -287,88 +294,179 @@ function makeSpaceForFreeOptions(options, num_free_options) {
287
294
  }
288
295
  return [...defaultPriceOptions, ...nonDefaultOptions].sort((a, b) => a.sort_id - b.sort_id);
289
296
  }
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
- };
297
+ // ====================================>>><<<======================================
329
298
  /**
330
299
  * Applies `choose_expensive_segment_price` to an order engine item converted
331
300
  * from a half-half setup (top-level modifier groups = segments, single-select
332
301
  * each, only 2 or 4 segments).
333
302
  *
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`).
303
+ * The expensive rule depends on which halves the user actually picked, so it
304
+ * cannot run during `IHalfHalfSetup -> IItem` conversion — it must run after
305
+ * selection, on the WORKING data. When `originalPriceReferences` is provided,
306
+ * every option price is first re-based from that immutable reference, which
307
+ * makes the rule fully reversible: picking a cheaper pair afterwards restores
308
+ * the previous (raised) prices instead of accumulating them.
343
309
  *
344
310
  * Rule: `price = base + upsell` — the item (option) level upsell is already
345
311
  * 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.
312
+ * segment option (option price + required/price-defining modifier prices —
313
+ * e.g. a "Pizza Size" group whose Small/Large/X-Large options are part of the
314
+ * item's price) and levels the cheaper PICK to the most expensive SELECTED
315
+ * half — `A($5)+B($5)` charges 5+5, `B($5)+C($6)` charges 6+6, and switching
316
+ * `C+D -> A+B` lowers them again. Every option is levelled to `max(own value,
317
+ * the max of the OTHER segments' selected values)` — the level its OWN pick
318
+ * would produce: choosing an unselected sibling REPLACES its segment's
319
+ * current pick, so that pick never inflates its own siblings' prices (a
320
+ * segment holding the expensive half keeps its other options at their own
321
+ * prices — you can only pick the next half from the NEXT segment), while a
322
+ * segment with no pick yet previews the full level. Unselected options never
323
+ * contribute to totals. The raise is applied to the FIRST
324
+ * PRICED element along the segment's price chain: the segment option's own
325
+ * price when non-zero, else the first priced required leaf ("First Half ->
326
+ * ROMA -> Pizza Size -> Large 13"") — see `findRaiseTarget`. Optional/upsell
327
+ * modifier groups are excluded: they add on top and must not influence the
328
+ * comparison. The IHalfHalfSetup level upsell is NOT part of this rule: it is
329
+ * the converted item's own price and is added once on top of the combined
330
+ * subtotal. Free (`is_free`) options never drive the comparison and are never
331
+ * raised.
357
332
  *
358
333
  * All prices here are plain numbers (engine-priced).
359
334
  *
360
- * Returns the item unchanged when nothing changes.
335
+ * Returns the item unchanged when no segment option is selected (only
336
+ * re-based when references were provided).
361
337
  */
362
338
  function applyChooseExpensiveSegmentPrice(orderEngineItem, options) {
363
- const segmentGroups = (orderEngineItem.modifiers ?? []).filter((modifier) => modifier.depth === 0);
339
+ const references = options?.originalPriceReferences;
340
+ const rebased = references
341
+ ? {
342
+ ...orderEngineItem,
343
+ modifiers: rebaseEngineOptionPrices(orderEngineItem.modifiers ?? [], references, '', 'all', true),
344
+ }
345
+ : orderEngineItem;
346
+ const segmentGroups = (rebased.modifiers ?? []).filter((modifier) => modifier.depth === 0);
364
347
  if (segmentGroups.length < 2)
365
- return orderEngineItem;
366
- const raised = applyChooseExpensiveSegmentPriceToModifiers(segmentGroups, options);
348
+ return references ? syncOrderEngineItem(rebased) : rebased;
349
+ const raised = applyChooseExpensiveSegmentPriceToModifiers(segmentGroups);
367
350
  if (raised == null)
368
- return orderEngineItem;
351
+ return references ? syncOrderEngineItem(rebased) : rebased;
369
352
  let segmentGroupIndex = 0;
370
- const modifiers = (orderEngineItem.modifiers ?? []).map((modifier) => modifier.depth !== 0 ? modifier : raised[segmentGroupIndex++]);
371
- return syncOrderEngineItem({ ...orderEngineItem, modifiers });
353
+ const modifiers = (rebased.modifiers ?? []).map((modifier) => modifier.depth !== 0 ? modifier : raised[segmentGroupIndex++]);
354
+ return syncOrderEngineItem({ ...rebased, modifiers });
355
+ }
356
+ /**
357
+ * Path key of an option inside its modifier chain — `_`-joined ids from the
358
+ * root, identical to the identifiers used by `setCheckFieldInOrderEngineItem`
359
+ * (ids are BSON ObjectIds so `_` is unambiguous).
360
+ */
361
+ const buildOptionPath = (modifierPath, optionId) => `${modifierPath}_${optionId}`;
362
+ /**
363
+ * Re-bases engine option prices from `references` (option path -> original
364
+ * price). The scope decides WHICH options are re-based:
365
+ * - `'all'` — every option (standalone half-half: segments and
366
+ * the required leaves that carry their price),
367
+ * - `'flaggedHalfHalf'` — only options inside a HALF_HALF option carrying
368
+ * the setup flag (a half-half nested in a special;
369
+ * the special's own option prices keep whatever the
370
+ * conversion produced).
371
+ * Returns the SAME tree object when no price changed (no needless copies).
372
+ */
373
+ function rebaseEngineOptionPrices(modifiers, references, parentPath, scope, insideScope) {
374
+ let treeChanged = false;
375
+ const nextModifiers = modifiers.map((modifier) => {
376
+ const modifierPath = parentPath ? `${parentPath}_${modifier._id}` : modifier._id;
377
+ let modifierChanged = false;
378
+ const nextOptions = (modifier.options ?? []).map((option) => {
379
+ let nextOption = option;
380
+ const optionPath = buildOptionPath(modifierPath, option._id);
381
+ if (insideScope) {
382
+ const originalPrice = references[optionPath];
383
+ if (originalPrice != null && originalPrice !== option.price) {
384
+ nextOption = { ...nextOption, price: originalPrice };
385
+ modifierChanged = true;
386
+ }
387
+ }
388
+ const isFlaggedHalfHalf = option.ref_type === constants_1.MODIFIER_OPTION_REF_TYPE_ENUM.HALF_HALF && option.choose_expensive_segment_price === true;
389
+ const childInsideScope = insideScope || (scope === 'flaggedHalfHalf' && isFlaggedHalfHalf);
390
+ const nextChildModifiers = rebaseEngineOptionPrices(nextOption.modifiers ?? [], references, optionPath, scope, childInsideScope);
391
+ if (nextChildModifiers !== nextOption.modifiers) {
392
+ nextOption = { ...nextOption, modifiers: nextChildModifiers };
393
+ modifierChanged = true;
394
+ }
395
+ return nextOption;
396
+ });
397
+ if (!modifierChanged)
398
+ return modifier;
399
+ treeChanged = true;
400
+ return { ...modifier, options: nextOptions };
401
+ });
402
+ return treeChanged ? nextModifiers : modifiers;
403
+ }
404
+ /**
405
+ * The option a required (price-defining) group contributes to the segment
406
+ * value: the SELECTED (default) one for a multi-option group, or the only
407
+ * option of a single-option group — never an unselected sibling.
408
+ */
409
+ function getSelectedRequiredOption(modifier) {
410
+ const options = modifier.options ?? [];
411
+ return options.find((option) => option.default) ?? (options.length === 1 ? options[0] : null);
412
+ }
413
+ /** Required (price-defining) group: at least one selection is mandatory. */
414
+ function isRequiredModifierGroup(modifier) {
415
+ return ((modifier.min_num_options != null && modifier.min_num_options > 0) ||
416
+ (modifier.min_aggregate_options_quantity != null && modifier.min_aggregate_options_quantity > 0));
417
+ }
418
+ /**
419
+ * Value of the SELECTED option of every required (price-defining) modifier
420
+ * group, at any depth — e.g. "Pizza Size" -> "Large 13"" is part of the
421
+ * item's price whichever size is picked, and only the picked size is charged.
422
+ * Optional/upsell groups, unselected siblings and the add-ons chosen on top of
423
+ * the item are excluded: they must not influence the comparison.
424
+ */
425
+ function getRequiredOptionPrices(modifiers) {
426
+ let total = 0;
427
+ (modifiers ?? []).forEach((modifier) => {
428
+ if (!isRequiredModifierGroup(modifier))
429
+ return;
430
+ const selected = getSelectedRequiredOption(modifier);
431
+ if (selected == null)
432
+ return;
433
+ total += (selected.price ?? 0) * (selected.quantity || 1);
434
+ total += getRequiredOptionPrices(selected.modifiers);
435
+ });
436
+ return total;
437
+ }
438
+ /**
439
+ * Value `choose_expensive_segment_price` compares and levels: the option price
440
+ * (base + item/option level upsell, merged at conversion) + the prices of its
441
+ * SELECTED required (price-defining) options. Exposed so callers that show a
442
+ * price for a single segment (e.g. the segment customization drawer) use the
443
+ * SAME math.
444
+ */
445
+ function getOrderEngineOptionSegmentValue(option) {
446
+ return (option.price ?? 0) + getRequiredOptionPrices(option.modifiers);
447
+ }
448
+ /**
449
+ * First priced required leaf reachable from `modifiers` (direct children):
450
+ * the single option of a single-option required group (its price is fixed —
451
+ * e.g. "ROMA -> Pizza Size -> Large 13""), or the selected/default option
452
+ * of a multi-option required group (never an unselected sibling).
453
+ */
454
+ function findPricedRequiredLeaf(modifiers) {
455
+ for (const modifier of modifiers ?? []) {
456
+ if (!isRequiredModifierGroup(modifier))
457
+ continue;
458
+ const candidate = getSelectedRequiredOption(modifier);
459
+ if (candidate != null && (candidate.price ?? 0) > 0)
460
+ return candidate;
461
+ }
462
+ return null;
463
+ }
464
+ /** Raises the option `targetId` inside its (direct) modifier group by `delta`. */
465
+ function raiseOptionPriceInModifiers(modifiers, targetId, delta) {
466
+ return modifiers.map((modifier) => ({
467
+ ...modifier,
468
+ options: modifier.options.map((option) => option._id === targetId ? { ...option, price: (option.price ?? 0) + delta } : option),
469
+ }));
372
470
  }
373
471
  /**
374
472
  * Core `choose_expensive_segment_price` normalization over a list of segment
@@ -379,61 +477,16 @@ function applyChooseExpensiveSegmentPrice(orderEngineItem, options) {
379
477
  * Returns null when nothing needs to change (no selected option / no priced
380
478
  * segment), otherwise the raised segment groups.
381
479
  */
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);
387
- // Prices of ALL options of required (price-defining) modifier groups, at
388
- // any depth — e.g. "Pizza Size" -> "Large 13"" is part of the item's price
389
- // whichever size is picked (mirrors `getSegmentItemTotalPrice` used by the
390
- // modern workable converter). Optional/upsell modifier groups are excluded:
391
- // they add on top and must not influence the comparison.
392
- const getRequiredOptionPrices = (modifiers) => {
393
- let total = 0;
394
- (modifiers ?? []).forEach((modifier) => {
395
- const isRequired = (modifier.min_num_options != null && modifier.min_num_options > 0) ||
396
- (modifier.min_aggregate_options_quantity != null && modifier.min_aggregate_options_quantity > 0);
397
- if (!isRequired)
398
- return;
399
- (modifier.options ?? []).forEach((option) => {
400
- total += (option.price ?? 0) * (option.quantity || 1);
401
- total += getRequiredOptionPrices(option.modifiers);
402
- });
403
- });
404
- return total;
405
- };
406
- // Segment price = option price (base + item/option level upsell, already
407
- // merged at conversion) + required (price-defining) modifier prices.
408
- const getSegmentTotal = (option) => (option.price ?? 0) + getRequiredOptionPrices(option.modifiers);
480
+ function applyChooseExpensiveSegmentPriceToModifiers(segmentGroups) {
409
481
  // One selected option per segment group (segments are single-select).
410
- const selections = [];
411
- for (let g = 0; g < groups.length; g++) {
412
- const options = groups[g].options ?? [];
413
- for (let o = 0; o < options.length; o++) {
414
- const option = options[o];
415
- if (!option.default || option.is_free)
416
- continue;
417
- selections.push({ groupIndex: g, optionIndex: o });
418
- break; // single-select: at most one selected option
419
- }
420
- }
421
- 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.
427
- let maxSegmentValue = 0;
428
- for (const selection of selections) {
429
- const option = groups[selection.groupIndex].options[selection.optionIndex];
430
- const segmentValue = getSegmentTotal(option);
431
- if (segmentValue > maxSegmentValue) {
432
- maxSegmentValue = segmentValue;
433
- }
434
- }
435
- if (maxSegmentValue <= 0)
436
- return haveSameOptionPrices(groups, segmentGroups) ? null : groups;
482
+ const selections = segmentGroups.map((group) => (group.options ?? []).find((option) => option.default && !option.is_free) ?? null);
483
+ if (selections.every((selection) => selection == null))
484
+ return null;
485
+ // Value of every segment's SELECTED option — only picks are charged, and
486
+ // only picks drive the level.
487
+ const selectedValues = selections.map((selection) => selection == null ? 0 : getOrderEngineOptionSegmentValue(selection));
488
+ if (Math.max(...selectedValues, 0) <= 0)
489
+ return null;
437
490
  // RULE for where the raise lands: on the FIRST PRICED element along the
438
491
  // segment's price chain —
439
492
  // 1. the segment option's own price (the item base) when it is non-zero
@@ -445,54 +498,43 @@ function applyChooseExpensiveSegmentPriceToModifiers(segmentGroups, options) {
445
498
  // 3. otherwise, the segment option's own price (even when 0).
446
499
  // This keeps the raise where the price actually lives and never invents a
447
500
  // price on an empty slot or an unselected option.
448
- const findRaiseTarget = (option) => {
449
- if ((option.price ?? 0) > 0)
450
- return option;
451
- for (const modifier of option.modifiers ?? []) {
452
- const isRequired = (modifier.min_num_options != null && modifier.min_num_options > 0) ||
453
- (modifier.min_aggregate_options_quantity != null && modifier.min_aggregate_options_quantity > 0);
454
- if (!isRequired)
455
- continue;
456
- const options = modifier.options ?? [];
457
- const candidate = options.length === 1 ? options[0] : (options.find((opt) => opt.default) ?? null);
458
- if (candidate != null && (candidate.price ?? 0) > 0)
459
- return candidate;
460
- }
461
- return null;
462
- };
501
+ const findRaiseTarget = (option) => (option.price ?? 0) > 0 ? option : findPricedRequiredLeaf(option.modifiers);
463
502
  const raiseSegmentOption = (option, delta) => {
464
503
  const target = findRaiseTarget(option);
465
504
  if (target == null || target._id === option._id) {
466
505
  return { ...option, price: (option.price ?? 0) + delta };
467
506
  }
507
+ return { ...option, modifiers: raiseOptionPriceInModifiers(option.modifiers, target._id, delta) };
508
+ };
509
+ // Every option is levelled to `max(own value, the max of the OTHER
510
+ // segments' selected values)` — the level its OWN pick would produce:
511
+ // - the selected option of a segment is CHARGED that way (the most
512
+ // expensive selected half drives every pick),
513
+ // - an unselected SIBLING replaces its segment's current pick when
514
+ // chosen, so that pick must not inflate the sibling's price (the
515
+ // expensive half's own list keeps its other options at their prices),
516
+ // - every option of a segment with no pick yet previews the full level
517
+ // (what picking it right now would cost).
518
+ // Free (`is_free`) options never drive the comparison and are never raised.
519
+ return segmentGroups.map((modifier, groupIndex) => {
520
+ const otherSegmentsMax = Math.max(...selectedValues.filter((_, index) => index !== groupIndex), 0);
468
521
  return {
469
- ...option,
470
- modifiers: option.modifiers.map((modifier) => ({
471
- ...modifier,
472
- options: modifier.options.map((opt) => opt._id === target._id ? { ...opt, price: (opt.price ?? 0) + delta } : opt),
473
- })),
522
+ ...modifier,
523
+ options: (modifier.options ?? []).map((option) => {
524
+ if (option.is_free)
525
+ return option;
526
+ const segmentValue = getOrderEngineOptionSegmentValue(option);
527
+ const target = Math.max(segmentValue, otherSegmentsMax);
528
+ if (target <= segmentValue)
529
+ return option;
530
+ // Level by the difference so the option's final segment value
531
+ // (base + upsell + required modifiers) equals the target — applied
532
+ // to the priced leaf when available (see `raiseSegmentOption`). The
533
+ // IHalfHalfSetup upsell (item price) is untouched.
534
+ return raiseSegmentOption(option, target - segmentValue);
535
+ }),
474
536
  };
475
- };
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)
480
- return option;
481
- const segmentValue = getSegmentTotal(option);
482
- // Already at (or above) the most expensive segment price: keep as is.
483
- if (segmentValue >= maxSegmentValue)
484
- 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.
489
- return raiseSegmentOption(option, maxSegmentValue - segmentValue);
490
- });
491
- return { ...modifier, options };
492
537
  });
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;
496
538
  }
497
539
  /**
498
540
  * True when the item has a top-level modifier group option that is a nested
@@ -501,100 +543,150 @@ function applyChooseExpensiveSegmentPriceToModifiers(segmentGroups, options) {
501
543
  function hasFlaggedHalfHalfOption(orderEngineItem) {
502
544
  return (orderEngineItem.modifiers ?? []).some((modifier) => (modifier.options ?? []).some((option) => option.ref_type === constants_1.MODIFIER_OPTION_REF_TYPE_ENUM.HALF_HALF && option.choose_expensive_segment_price === true));
503
545
  }
546
+ /**
547
+ * Half-half selection rule: an item may fill at most `segments - 1` halves —
548
+ * it may never make ALL sides of the half-half (otherwise it is not a half-half
549
+ * anymore). Returns the option PATHS that would complete "all sides" when
550
+ * selected, formatted exactly like `setCheckFieldInOrderEngineItem`
551
+ * identifiers (`seg-2_roma`, `mod-pizza_halfhalf-1_seg-2_milan`), so callers
552
+ * can block, guard and label them.
553
+ *
554
+ * Handles both shapes:
555
+ * - a HALF_HALF item (its top-level groups are the segments — pass
556
+ * `isHalfHalfSegmentItem: false`),
557
+ * - a flagged half-half option nested in a SPECIAL (its own modifier groups
558
+ * are the segments).
559
+ * A drawer opened for a single half-half SEGMENT passes
560
+ * `isHalfHalfSegmentItem: true` so the item's own option groups are never
561
+ * treated as segments.
562
+ */
563
+ function getBlockedHalfHalfOptionPaths(orderEngineItem, isHalfHalfSegmentItem = false) {
564
+ const blocked = new Set();
565
+ const blockSegments = (segments, segmentsPath) => {
566
+ const total = segments.length;
567
+ if (total < 2)
568
+ return;
569
+ const selectedBySegment = segments.map((segment) => segment.options.find((option) => option.default) ?? null);
570
+ segments.forEach((segment, index) => {
571
+ const segmentPath = segmentsPath ? `${segmentsPath}_${segment._id}` : segment._id;
572
+ segment.options.forEach((option) => {
573
+ const others = selectedBySegment.filter((selected, otherIndex) => otherIndex !== index && selected != null && selected._id === option._id).length;
574
+ if (others >= total - 1) {
575
+ blocked.add(`${segmentPath}_${option._id}`);
576
+ }
577
+ });
578
+ });
579
+ };
580
+ const walkNestedHalfHalf = (modifiers, parentPath) => {
581
+ modifiers.forEach((modifier) => {
582
+ const modifierPath = parentPath ? `${parentPath}_${modifier._id}` : modifier._id;
583
+ modifier.options.forEach((option) => {
584
+ const optionPath = `${modifierPath}_${option._id}`;
585
+ if (option.ref_type === constants_1.MODIFIER_OPTION_REF_TYPE_ENUM.HALF_HALF &&
586
+ option.choose_expensive_segment_price === true) {
587
+ blockSegments(option.modifiers ?? [], optionPath);
588
+ }
589
+ walkNestedHalfHalf(option.modifiers ?? [], optionPath);
590
+ });
591
+ });
592
+ };
593
+ if (orderEngineItem.item_type === constants_1.ORDER_ITEM_TYPE_ENUM.HALF_HALF && !isHalfHalfSegmentItem) {
594
+ blockSegments((orderEngineItem.modifiers ?? []).filter((modifier) => modifier.depth === 0), '');
595
+ }
596
+ walkNestedHalfHalf(orderEngineItem.modifiers ?? [], '');
597
+ return blocked;
598
+ }
599
+ /**
600
+ * Same half-half selection rule for the MODERN selection list (no engine tree
601
+ * yet): the item ids that cannot be picked for `segmentIndex` because doing so
602
+ * would make them occupy every segment. `segmentIndex` is the segment being
603
+ * picked/edited (its own current item does not count against itself).
604
+ */
605
+ function getHalfHalfBlockedItemIds(orderItems, segmentIndex) {
606
+ if (segmentIndex == null)
607
+ return [];
608
+ const totalSegments = orderItems.length;
609
+ if (totalSegments < 2)
610
+ return [];
611
+ const blocked = [];
612
+ const checked = new Set();
613
+ orderItems.forEach((orderItem) => {
614
+ if (orderItem == null || checked.has(orderItem.item_id))
615
+ return;
616
+ checked.add(orderItem.item_id);
617
+ const others = orderItems.filter((other, index) => index !== segmentIndex && other != null && other.item_id === orderItem.item_id).length;
618
+ if (others >= totalSegments - 1) {
619
+ blocked.push(orderItem.item_id);
620
+ }
621
+ });
622
+ return blocked;
623
+ }
504
624
  /**
505
625
  * `choose_expensive_segment_price` for a half-half option nested in a special:
506
626
  * 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`).
627
+ * same level-to-the-most-expensive-SELECTED-half treatment as a standalone
628
+ * half-half item. ITEM options are terminal (their nested modifiers can never
629
+ * contain ITEM/HALF_HALF); normal options pass untouched.
630
+ *
631
+ * When `originalPriceReferences` is provided, prices are re-based first — but
632
+ * ONLY inside the flagged half-half subtrees, so the special's own option
633
+ * prices keep whatever the conversion produced.
511
634
  */
512
635
  function applyNestedChooseExpensiveSegmentPrice(orderEngineItem, options) {
513
- const modifiers = (orderEngineItem.modifiers ?? []).map((modifier) => ({
636
+ const references = options?.originalPriceReferences;
637
+ const rebased = references
638
+ ? {
639
+ ...orderEngineItem,
640
+ modifiers: rebaseEngineOptionPrices(orderEngineItem.modifiers ?? [], references, '', 'flaggedHalfHalf', false),
641
+ }
642
+ : orderEngineItem;
643
+ const modifiers = (rebased.modifiers ?? []).map((modifier) => ({
514
644
  ...modifier,
515
645
  options: (modifier.options ?? []).map((option) => {
516
646
  if (option.ref_type !== constants_1.MODIFIER_OPTION_REF_TYPE_ENUM.HALF_HALF ||
517
647
  option.choose_expensive_segment_price !== true) {
518
648
  return option;
519
649
  }
520
- const raised = applyChooseExpensiveSegmentPriceToModifiers(option.modifiers ?? [], options);
650
+ const raised = applyChooseExpensiveSegmentPriceToModifiers(option.modifiers ?? []);
521
651
  if (raised == null)
522
652
  return option;
523
653
  return { ...option, modifiers: raised };
524
654
  }),
525
655
  }));
526
- return syncOrderEngineItem({ ...orderEngineItem, modifiers });
656
+ return syncOrderEngineItem({ ...rebased, modifiers });
527
657
  }
528
658
  /**
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.
659
+ * Levels the item's segment VALUE (item price + required option prices — the
660
+ * value `getOrderEngineOptionSegmentValue` / `applyChooseExpensiveSegmentPrice`
661
+ * compare) UP to `floorPrice`, using the same raise mechanics as the rule: the
662
+ * raise lands on the FIRST PRICED element — the item price when non-zero,
663
+ * otherwise the first priced required leaf, otherwise the item price.
533
664
  *
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.
665
+ * Used by the drawer that edits a SINGLE half-half segment: the half-half
666
+ * screen passes the max value of the OTHER selected halves as the floor, so
667
+ * the drawer shows the amount this segment is actually charged once the
668
+ * choose_expensive rule levels it. It never lowers.
547
669
  */
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 });
670
+ function applySegmentPriceFloor(orderEngineItem, floorPrice) {
671
+ if (!(floorPrice > 0))
672
+ return orderEngineItem;
673
+ const currentValue = (orderEngineItem.price ?? 0) + getRequiredOptionPrices(orderEngineItem.modifiers);
674
+ const delta = floorPrice - currentValue;
675
+ if (delta <= 0)
676
+ return orderEngineItem;
677
+ if ((orderEngineItem.price ?? 0) > 0) {
678
+ return syncOrderEngineItem({ ...orderEngineItem, price: orderEngineItem.price + delta });
593
679
  }
594
- const modifiers = resetEngineOptionPrices(orderEngineItem.modifiers ?? [], basePrices);
595
- return syncOrderEngineItem({ ...orderEngineItem, modifiers });
680
+ const target = findPricedRequiredLeaf(orderEngineItem.modifiers);
681
+ if (target == null) {
682
+ return syncOrderEngineItem({ ...orderEngineItem, price: (orderEngineItem.price ?? 0) + delta });
683
+ }
684
+ return syncOrderEngineItem({
685
+ ...orderEngineItem,
686
+ modifiers: raiseOptionPriceInModifiers(orderEngineItem.modifiers, target._id, delta),
687
+ });
596
688
  }
597
- function convertCatalogItemModifierToOrderEngineItemModifier({ modifiers, orderItemModifiers, platform, tenantId, excludeRefs, zeroPriceRefs, loyaltyRefs, voucherRefs, keepOptionalModifiersAtBottom, soldoutModifiers, depth = 0, }) {
689
+ function convertCatalogItemModifierToOrderEngineItemModifier({ modifiers, orderItemModifiers, platform, tenantId, excludeRefs, zeroPriceRefs, loyaltyRefs, voucherRefs, keepOptionalModifiersAtBottom, soldoutModifiers, depth = 0, priceReferences, parentPath, }) {
598
690
  function getSortedModifiers(modifiers = []) {
599
691
  const sortedModifiers = modifiers.sort((a, b) => a.sort_id - b.sort_id);
600
692
  return sortedModifiers;
@@ -630,6 +722,7 @@ function convertCatalogItemModifierToOrderEngineItemModifier({ modifiers, orderI
630
722
  // If excludeRefs is present then we exclude those modifiers
631
723
  if (excludeRefs != null && excludeRefs.includes(modifier.ref))
632
724
  continue;
725
+ const modifierPath = parentPath ? `${parentPath}_${modifier._id}` : modifier._id;
633
726
  const orderItemModifier = orderItemModifiers?.find((orderModifier) => orderModifier._id === modifier._id);
634
727
  const hasOrderItemSelectedOptions = orderItemModifier != null && orderItemModifier.options.length > 0;
635
728
  const maxDefaultSelections = modifier.max_aggregate_options_quantity ?? modifier.max_num_options ?? modifier.options.length;
@@ -678,21 +771,27 @@ function convertCatalogItemModifierToOrderEngineItemModifier({ modifiers, orderI
678
771
  keepOptionalModifiersAtBottom,
679
772
  soldoutModifiers,
680
773
  depth: depth + 1,
774
+ priceReferences,
775
+ parentPath: `${modifierPath}_${option._id}`,
681
776
  });
682
777
  // 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);
778
+ const isZeroPriced = zeroPriceRefs != null && (zeroPriceRefs.includes(option.ref) || zeroPriceRefs.includes(modifier.ref));
779
+ const optionPrice = isZeroPriced ? 0 : price;
780
+ // ORIGINAL (definition) price of the option — deliberately NOT the
781
+ // persisted order price used above: it is the immutable reference the
782
+ // choose_expensive rule re-bases from (so edit flows can never treat an
783
+ // already-normalized price as the original).
784
+ priceReferences[`${modifierPath}_${option._id}`] = isZeroPriced ? 0 : (0, platform_catalog_1.getPriceEnum)(option.price, platform);
689
785
  const orderEngineSingleOption = {
690
786
  ...option,
691
787
  default: isDefaultOption,
692
788
  price: optionPrice,
693
- base_price: basePrice,
694
789
  quantity: qty,
695
790
  modifiers: newModifiers,
791
+ // `zeroPriceRefs` (half-half `exclusive_refs`) mutate the PRICE only
792
+ // (`optionPrice` above) — they must never set `is_free`: the "Free"
793
+ // tag belongs exclusively to `num_free_options` options
794
+ // (`makeSpaceForFreeOptions`).
696
795
  is_free,
697
796
  loyalty_applied: false,
698
797
  voucher_applied: false,
@@ -880,6 +979,9 @@ function convertCatalogItemToOrderEngineItem({ item, orderItem, platform, tenant
880
979
  // Default values will be used in case of new order
881
980
  // we need to find the applicable schedule for the item
882
981
  const applicableSchedule = (0, platform_catalog_1.findApplicableSchedule)(item.item_special_hours, platform);
982
+ // Definition prices of every option, keyed by option path — the immutable
983
+ // baseline the UI re-bases from before every price normalization.
984
+ const originalPriceReferences = {};
883
985
  const orderEngineModifiers = convertCatalogItemModifierToOrderEngineItemModifier({
884
986
  modifiers: item.modifiers,
885
987
  orderItemModifiers: orderItem?.modifiers,
@@ -891,6 +993,8 @@ function convertCatalogItemToOrderEngineItem({ item, orderItem, platform, tenant
891
993
  voucherRefs: applyVoucher?.refs,
892
994
  keepOptionalModifiersAtBottom,
893
995
  soldoutModifiers,
996
+ priceReferences: originalPriceReferences,
997
+ parentPath: '',
894
998
  });
895
999
  let itemPrice = item.price;
896
1000
  let discount_amount = item.discount_amount;
@@ -971,7 +1075,7 @@ function convertCatalogItemToOrderEngineItem({ item, orderItem, platform, tenant
971
1075
  item_discount_details: mergedItemDiscountDetails,
972
1076
  modifiers: orderEngineModifiers,
973
1077
  });
974
- return orderEngineItem;
1078
+ return { originalPriceReferences, workingData: orderEngineItem };
975
1079
  }
976
1080
  function hasRequiredModifier(currentModifiers) {
977
1081
  if (!currentModifiers)
@@ -1145,13 +1249,11 @@ function setCheckFieldInOrderEngineItem(orderEngineItem, identifier, shouldCheck
1145
1249
  const allIds = identifier.split('_').filter((id) => id.trim() !== '');
1146
1250
  const modifiers = setUpdateModifiers(orderEngineItem.modifiers, allIds, 0);
1147
1251
  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.
1252
+ // `choose_expensive_segment_price` is NOT applied here: price normalization
1253
+ // has a single entry point (`applyChooseExpensiveSegmentPrice` /
1254
+ // `applyNestedChooseExpensiveSegmentPrice`, called with the original price
1255
+ // references by the drawer after this mutation). The flag parameter is kept
1256
+ // for API compatibility and ignored.
1155
1257
  void chooseExpensiveSegmentPrice;
1156
1258
  return updatedOrderEngineItem;
1157
1259
  }