@managesome/eposmatic-toolkit 0.2.767 → 0.2.769

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.
@@ -1,5 +1,5 @@
1
1
  import { DISCOUNT_APPLICABILITY_ENUM, GIFT_CARD_REWARD_TYPE_ENUM, ORDER_STATUS_ENUM, PLATFORMS_ENUM, SORT_TYPE_ENUM } from '../../constants';
2
- import { ICourse, IDiscountDetails, IGeneralItem, IItem, IModifier, IOffer, IOrder, IOrderCategory, IOrderCourse, IOrderDeliveryDetails, IOrderItem, IOrderIteration, IPrice } from '../../schemas';
2
+ import { ICourse, IDiscountDetails, IGeneralItem, IItem, IModifier, IOffer, IOrder, IOrderCategory, IOrderCourse, IOrderDeliveryDetails, IOrderItem, IOrderIteration, IOrderModifier, IPrice } from '../../schemas';
3
3
  import { ICartListnerSettings } from '../types';
4
4
  import { ICartItemsObj } from '../types/cart-actions';
5
5
  interface IGetItemQuantityChangeResultsParams {
@@ -74,6 +74,28 @@ export interface ISetAddItemToCartActionPayload {
74
74
  rewardClaim?: IRewardClaim;
75
75
  }
76
76
  export declare const getOrderItemComaparableData: (item: IOrderItem) => Partial<IOrderItem>;
77
+ /**
78
+ * Merge-comparable projection of an order item: everything that makes two
79
+ * items "the same" for quantity merging (item, modifiers, per-unit terms),
80
+ * with the quantity-dependent amounts normalized to a single unit.
81
+ *
82
+ * Two items whose projections are deeply equal merge into ONE with a summed
83
+ * quantity — the cart-line merge (`getAddItemToCartData`) and the specials
84
+ * slot merge (`convertSpecialItemToOrderItem`, e.g. the same pizza picked in
85
+ * several slots of a deal) both key on this projection.
86
+ */
87
+ export declare function getComparableOrderItem(item: IOrderItem): {
88
+ item_id: string;
89
+ menu_id: string | null | undefined;
90
+ item_type: import("../../constants").ORDER_ITEM_TYPE_ENUM;
91
+ name: string;
92
+ price: number;
93
+ item_discount_details: IDiscountDetails | null;
94
+ tax_rate: number;
95
+ special_instructions: string;
96
+ is_ready: boolean;
97
+ modifiers: IOrderModifier[] | null;
98
+ };
77
99
  export declare function getAddItemToCartData(data: Partial<IOrder>, payload: ISetAddItemToCartActionPayload, courses: ICourse[], listnerSettings: ICartListnerSettings, appliedCustomDiscounts?: IAppliedCustomDiscount[]): Partial<IOrder>;
78
100
  interface IGetSplitCartItemToTwo {
79
101
  data: Partial<IOrder>;
@@ -15,6 +15,7 @@ exports.getSurchargeAmount = getSurchargeAmount;
15
15
  exports.calculateGstForItem = calculateGstForItem;
16
16
  exports.getCashierAppliedDiscountAmount = getCashierAppliedDiscountAmount;
17
17
  exports.calculateCartOrderInfoAndSyncData = calculateCartOrderInfoAndSyncData;
18
+ exports.getComparableOrderItem = getComparableOrderItem;
18
19
  exports.getAddItemToCartData = getAddItemToCartData;
19
20
  exports.getSplitCartItemToTwo = getSplitCartItemToTwo;
20
21
  exports.getAddItemsToCartData = getAddItemsToCartData;
@@ -1947,25 +1948,35 @@ const getOrderItemComaparableData = (item) => ({
1947
1948
  quantity: item.quantity,
1948
1949
  });
1949
1950
  exports.getOrderItemComaparableData = getOrderItemComaparableData;
1950
- function getAddItemToCartData(data, payload, courses, listnerSettings, appliedCustomDiscounts) {
1951
- const getComparableItem = (item) => {
1952
- return {
1953
- item_id: item.item_id,
1954
- menu_id: item.menu_id,
1955
- item_type: item.item_type,
1956
- name: item.name,
1957
- price: item.price,
1958
- item_discount_details: getItemQuantityChangeResults({
1959
- prevQuantity: item.quantity,
1960
- newQuantity: 1,
1961
- prevItemDiscountDetails: item.item_discount_details,
1962
- }),
1963
- tax_rate: item.tax_rate,
1964
- special_instructions: item.special_instructions,
1965
- is_ready: item.is_ready ?? false,
1966
- modifiers: item.modifiers,
1967
- };
1951
+ /**
1952
+ * Merge-comparable projection of an order item: everything that makes two
1953
+ * items "the same" for quantity merging (item, modifiers, per-unit terms),
1954
+ * with the quantity-dependent amounts normalized to a single unit.
1955
+ *
1956
+ * Two items whose projections are deeply equal merge into ONE with a summed
1957
+ * quantity — the cart-line merge (`getAddItemToCartData`) and the specials
1958
+ * slot merge (`convertSpecialItemToOrderItem`, e.g. the same pizza picked in
1959
+ * several slots of a deal) both key on this projection.
1960
+ */
1961
+ function getComparableOrderItem(item) {
1962
+ return {
1963
+ item_id: item.item_id,
1964
+ menu_id: item.menu_id,
1965
+ item_type: item.item_type,
1966
+ name: item.name,
1967
+ price: item.price,
1968
+ item_discount_details: getItemQuantityChangeResults({
1969
+ prevQuantity: item.quantity,
1970
+ newQuantity: 1,
1971
+ prevItemDiscountDetails: item.item_discount_details,
1972
+ }),
1973
+ tax_rate: item.tax_rate,
1974
+ special_instructions: item.special_instructions,
1975
+ is_ready: item.is_ready ?? false,
1976
+ modifiers: item.modifiers,
1968
1977
  };
1978
+ }
1979
+ function getAddItemToCartData(data, payload, courses, listnerSettings, appliedCustomDiscounts) {
1969
1980
  const { category_id, name, item, chosen_course_id, replace_id, rewardClaim } = payload;
1970
1981
  const normalizedRewardClaim = getNormalizedRewardClaim(rewardClaim);
1971
1982
  const validatedRewardItemAddContext = getValidatedRewardItemAddContext({
@@ -1974,7 +1985,7 @@ function getAddItemToCartData(data, payload, courses, listnerSettings, appliedCu
1974
1985
  });
1975
1986
  const itemWithValidatedRewardClaim = validatedRewardItemAddContext.item;
1976
1987
  const validatedRewardClaim = validatedRewardItemAddContext.rewardClaim;
1977
- const comparableItem = getComparableItem(itemWithValidatedRewardClaim);
1988
+ const comparableItem = getComparableOrderItem(itemWithValidatedRewardClaim);
1978
1989
  let mainItemId = itemWithValidatedRewardClaim._id;
1979
1990
  const orderData = { ...data };
1980
1991
  // =====================><=====================
@@ -2008,7 +2019,7 @@ function getAddItemToCartData(data, payload, courses, listnerSettings, appliedCu
2008
2019
  // We make sure that the item does not have loyalty_discount_id and voucher_discount_id
2009
2020
  itm.item_discount_details?.loyalty_discount_id == null &&
2010
2021
  itm.item_discount_details?.voucher_discount_id == null &&
2011
- (0, lodash_1.isEqual)(getComparableItem(itm), comparableItem)) {
2022
+ (0, lodash_1.isEqual)(getComparableOrderItem(itm), comparableItem)) {
2012
2023
  mainItemId = replace_id ?? itm._id;
2013
2024
  const newQuantity = itemWithValidatedRewardClaim.quantity + itm.quantity;
2014
2025
  allItems[j] = {
@@ -686,7 +686,7 @@ function applySegmentPriceFloor(orderEngineItem, floorPrice) {
686
686
  modifiers: raiseOptionPriceInModifiers(orderEngineItem.modifiers, target._id, delta),
687
687
  });
688
688
  }
689
- function convertCatalogItemModifierToOrderEngineItemModifier({ modifiers, orderItemModifiers, platform, tenantId, excludeRefs, zeroPriceRefs, loyaltyRefs, voucherRefs, keepOptionalModifiersAtBottom, soldoutModifiers, depth = 0, priceReferences, parentPath, }) {
689
+ function convertCatalogItemModifierToOrderEngineItemModifier({ modifiers, orderItemModifiers, platform, tenantId, excludeRefs, zeroPriceRefs, loyaltyRefs, voucherRefs, keepOptionalModifiersAtBottom, soldoutModifiers, depth = 0, priceReferences, parentPath, isSetupSelection = false, }) {
690
690
  function getSortedModifiers(modifiers = []) {
691
691
  const sortedModifiers = modifiers.sort((a, b) => a.sort_id - b.sort_id);
692
692
  return sortedModifiers;
@@ -739,8 +739,30 @@ function convertCatalogItemModifierToOrderEngineItemModifier({ modifiers, orderI
739
739
  const option = sortedOptions[j];
740
740
  if (excludeRefs != null && excludeRefs.includes(option.ref))
741
741
  continue;
742
- // Default values would be used in case of new order
743
- const { modifiers: orderItemOptionModifiers, is_free = false, price = (0, platform_catalog_1.getPriceEnum)(option.price, platform), quantity = modifier.min_option_choice_quantity || 1, _id, } = orderItemModifier?.options.find((orderOption) => orderOption._id === option._id) ?? {};
742
+ // Default values would be used in case of new order. SETUP order items
743
+ // (specials / half-half) may hold the SAME option several times — a
744
+ // repeated pick merged into a quantity, the free/paid split of a
745
+ // partially free special group, or legacy per-slot options — so their
746
+ // occurrences AGGREGATE into the single engine option: the classic
747
+ // edit must not lose units nor flag a "missing selection" for repeated
748
+ // picks (a mixed free/paid set cannot be represented by one option, so
749
+ // any paid occurrence keeps it paid). Regular ITEM conversions keep the
750
+ // original single-match lookup (`find` + destructuring defaults).
751
+ const matchedOptions = isSetupSelection && orderItemModifier != null
752
+ ? orderItemModifier.options.filter((orderOption) => orderOption._id === option._id)
753
+ : [];
754
+ const matchedOption = isSetupSelection
755
+ ? matchedOptions[0]
756
+ : orderItemModifier?.options.find((orderOption) => orderOption._id === option._id);
757
+ const { modifiers: orderItemOptionModifiers, is_free: matchedIsFree = false, price = (0, platform_catalog_1.getPriceEnum)(option.price, platform), quantity: matchedQuantity = modifier.min_option_choice_quantity || 1, _id, } = matchedOption ?? {};
758
+ const quantity = isSetupSelection
759
+ ? matchedOptions.reduce((total, orderOption) => total + (orderOption.quantity || 1), 0) ||
760
+ modifier.min_option_choice_quantity ||
761
+ 1
762
+ : matchedQuantity;
763
+ const is_free = isSetupSelection
764
+ ? matchedOptions.length > 0 && matchedOptions.every((orderOption) => orderOption.is_free)
765
+ : matchedIsFree;
744
766
  let qty = quantity;
745
767
  const isSoldout = option.sold_out.includes(tenantId) || soldoutModifiers?.includes(option.ref);
746
768
  let isDefaultOption = false;
@@ -773,6 +795,7 @@ function convertCatalogItemModifierToOrderEngineItemModifier({ modifiers, orderI
773
795
  depth: depth + 1,
774
796
  priceReferences,
775
797
  parentPath: `${modifierPath}_${option._id}`,
798
+ isSetupSelection,
776
799
  });
777
800
  // If zeroPriceRefs is present then we set the price to 0
778
801
  const isZeroPriced = zeroPriceRefs != null && (zeroPriceRefs.includes(option.ref) || zeroPriceRefs.includes(modifier.ref));
@@ -806,7 +829,9 @@ function convertCatalogItemModifierToOrderEngineItemModifier({ modifiers, orderI
806
829
  }
807
830
  orderEngineSingleModifier.options.push(orderEngineSingleOption);
808
831
  }
809
- if (!orderItemModifier) {
832
+ if (!isSetupSelection && !orderItemModifier) {
833
+ // Regular items: ORIGINAL position — free marking runs BEFORE the
834
+ // lone-option auto-select (pre-existing behavior, untouched).
810
835
  const options = makeSpaceForFreeOptions(orderEngineSingleModifier.options, modifier.num_free_options);
811
836
  orderEngineSingleModifier.options = options;
812
837
  }
@@ -828,6 +853,15 @@ function convertCatalogItemModifierToOrderEngineItemModifier({ modifiers, orderI
828
853
  totalDefaultOptions = 1;
829
854
  }
830
855
  }
856
+ if (isSetupSelection && !orderItemModifier) {
857
+ // SETUP order items: free marking runs AFTER the lone-option
858
+ // auto-select so the auto-selected option takes part in
859
+ // `num_free_options` too — otherwise a special whose single option
860
+ // covers the free budget would charge for it when submitted without
861
+ // any further interaction.
862
+ const options = makeSpaceForFreeOptions(orderEngineSingleModifier.options, modifier.num_free_options);
863
+ orderEngineSingleModifier.options = options;
864
+ }
831
865
  orderEngineSingleModifier.default = totalDefaultOptions > 0;
832
866
  orderEngineModifiers.push(orderEngineSingleModifier);
833
867
  }
@@ -983,6 +1017,10 @@ function convertCatalogItemToOrderEngineItem({ item, orderItem, platform, tenant
983
1017
  // Definition prices of every option, keyed by option path — the immutable
984
1018
  // baseline the UI re-bases from before every price normalization.
985
1019
  const originalPriceReferences = {};
1020
+ // Setup (specials / half-half) order items slide the setup-only engine
1021
+ // rules (duplicate-occurrence aggregation + free-after-auto-select);
1022
+ // regular ITEM conversions keep the original path.
1023
+ const isSetupSelection = orderItemType === constants_1.ORDER_ITEM_TYPE_ENUM.SPECIAL || orderItemType === constants_1.ORDER_ITEM_TYPE_ENUM.HALF_HALF;
986
1024
  const orderEngineModifiers = convertCatalogItemModifierToOrderEngineItemModifier({
987
1025
  modifiers: item.modifiers,
988
1026
  orderItemModifiers: orderItem?.modifiers,
@@ -996,6 +1034,7 @@ function convertCatalogItemToOrderEngineItem({ item, orderItem, platform, tenant
996
1034
  soldoutModifiers,
997
1035
  priceReferences: originalPriceReferences,
998
1036
  parentPath: '',
1037
+ isSetupSelection,
999
1038
  });
1000
1039
  let itemPrice = item.price;
1001
1040
  let discount_amount = item.discount_amount;
@@ -58,8 +58,12 @@ export declare function convertSpecialItemToOrderItem({ specialItem, modifierSpe
58
58
  * used by the SpecialsScreen selection flow (edit without classic preview).
59
59
  *
60
60
  * Each modifier on the order item maps back to its `IModifierSpecial` group
61
- * (matched by ref or _id), and each selected option becomes a selection
62
- * order item placed into the next free slot (up to modifier_special.quantity).
61
+ * (matched by ref or _id). Options MERGE identical slot selections into one
62
+ * option with a summed `quantity` (see `convertSpecialItemToOrderItem`), so
63
+ * the reverse fill EXPANDS a quantity into that many slots (one unit per
64
+ * slot, up to modifier_special.quantity, at least one slot reserved per
65
+ * remaining option) — the modern view is refilled with the same number of
66
+ * filled slots the cashier originally picked.
63
67
  *
64
68
  * Returns null if the order item doesn't belong to the provided special.
65
69
  */
@@ -14,6 +14,7 @@ exports.convertSpecialItemToOrderItem = convertSpecialItemToOrderItem;
14
14
  exports.deStructureSpecialOrderItem = deStructureSpecialOrderItem;
15
15
  exports.convertSpecialToItem = convertSpecialToItem;
16
16
  const bson_objectid_1 = __importDefault(require("bson-objectid"));
17
+ const lodash_1 = require("lodash");
17
18
  const constants_1 = require("../../constants");
18
19
  const store_1 = require("../store");
19
20
  const halfhalf_setup_helpers_1 = require("./halfhalf-setup-helpers");
@@ -257,7 +258,10 @@ function convertSpecialItemToOrderItem({ specialItem, modifierSpecials, quantity
257
258
  const originalModifierSpecial = specialItem.modifier_specials.find((ms) => ms._id === modifierSpecial._id);
258
259
  if (!originalModifierSpecial)
259
260
  continue;
260
- const options = [];
261
+ // One entry per filled slot; `comparable` is the SAME "is this the same
262
+ // selection?" projection the cart-line merge uses (`getAddItemToCartData`
263
+ // -> `getComparableOrderItem`) — computed once per slot item.
264
+ const entries = [];
261
265
  for (let j = 0; j < modifierSpecial.selectedItems.length; j++) {
262
266
  const selectedItem = modifierSpecial.selectedItems[j];
263
267
  if (!selectedItem)
@@ -270,35 +274,58 @@ function convertSpecialItemToOrderItem({ specialItem, modifierSpecials, quantity
270
274
  }
271
275
  // `_id` is the real catalog item `_id` (like an IItem option), so raw
272
276
  // modifiers comparison works for merge and edits stay deterministic.
273
- options.push({
274
- _id: selectedItem.item_id,
275
- ref: selectedItem.item_id,
276
- name: selectedItem.name,
277
- price: selectedItem.price,
278
- quantity: selectedItem.quantity,
279
- modifiers: selectedItem.modifiers,
280
- is_free: false,
281
- // The option IS an item or a half-half — carry its kind.
282
- ref_type: selectedItem.item_type === constants_1.ORDER_ITEM_TYPE_ENUM.HALF_HALF
283
- ? constants_1.MODIFIER_OPTION_REF_TYPE_ENUM.HALF_HALF
284
- : constants_1.MODIFIER_OPTION_REF_TYPE_ENUM.ITEM,
277
+ entries.push({
278
+ option: {
279
+ _id: selectedItem.item_id,
280
+ ref: selectedItem.item_id,
281
+ name: selectedItem.name,
282
+ price: selectedItem.price,
283
+ quantity: selectedItem.quantity,
284
+ modifiers: selectedItem.modifiers,
285
+ is_free: false,
286
+ // The option IS an item or a half-half — carry its kind.
287
+ ref_type: selectedItem.item_type === constants_1.ORDER_ITEM_TYPE_ENUM.HALF_HALF
288
+ ? constants_1.MODIFIER_OPTION_REF_TYPE_ENUM.HALF_HALF
289
+ : constants_1.MODIFIER_OPTION_REF_TYPE_ENUM.ITEM,
290
+ },
291
+ comparable: (0, store_1.getComparableOrderItem)(selectedItem),
285
292
  });
286
293
  }
287
294
  // Mark the cheapest N selected items as free (num_free_items), same as the
288
295
  // classic drawer flow (makeSpaceForFreeOptions semantics). Slot order kept.
289
296
  const numFreeItems = originalModifierSpecial.num_free_items || 0;
290
- if (numFreeItems > 0 && options.length > 0) {
291
- const freeIndexes = new Set(options
292
- .map((option, index) => ({ index, value: (option.price || 0) * (option.quantity || 1) }))
297
+ if (numFreeItems > 0 && entries.length > 0) {
298
+ const freeIndexes = new Set(entries
299
+ .map((entry, index) => ({
300
+ index,
301
+ value: (entry.option.price || 0) * (entry.option.quantity || 1),
302
+ }))
293
303
  .sort((a, b) => a.value - b.value)
294
304
  .slice(0, numFreeItems)
295
305
  .map((entry) => entry.index));
296
- options.forEach((option, index) => {
306
+ entries.forEach((entry, index) => {
297
307
  if (freeIndexes.has(index)) {
298
- option.is_free = true;
308
+ entry.option.is_free = true;
299
309
  }
300
310
  });
301
311
  }
312
+ // MERGE identical selections: choosing the same item with the same
313
+ // modifiers in several slots means N units of that option, not N options —
314
+ // the stored line carries ONE option whose `quantity` is the unit sum
315
+ // (mirrors the cart merging two identical lines into one with a summed
316
+ // quantity). Free marking ran per slot BEFORE this and `is_free` is part
317
+ // of the merge key, so free units keep the exact count they had per slot
318
+ // (a mixed group stays as a free option + a paid option).
319
+ const mergedEntries = [];
320
+ for (const entry of entries) {
321
+ const existing = mergedEntries.find((candidate) => candidate.option.is_free === entry.option.is_free && (0, lodash_1.isEqual)(candidate.comparable, entry.comparable));
322
+ if (existing != null) {
323
+ existing.option.quantity = (existing.option.quantity || 1) + (entry.option.quantity || 1);
324
+ continue;
325
+ }
326
+ mergedEntries.push(entry);
327
+ }
328
+ const options = mergedEntries.map((entry) => entry.option);
302
329
  // Group id = the modifier-special `_id` (same as ref — deterministic).
303
330
  groups.push({
304
331
  ref: originalModifierSpecial._id,
@@ -363,8 +390,12 @@ function convertSpecialItemToOrderItem({ specialItem, modifierSpecials, quantity
363
390
  * used by the SpecialsScreen selection flow (edit without classic preview).
364
391
  *
365
392
  * Each modifier on the order item maps back to its `IModifierSpecial` group
366
- * (matched by ref or _id), and each selected option becomes a selection
367
- * order item placed into the next free slot (up to modifier_special.quantity).
393
+ * (matched by ref or _id). Options MERGE identical slot selections into one
394
+ * option with a summed `quantity` (see `convertSpecialItemToOrderItem`), so
395
+ * the reverse fill EXPANDS a quantity into that many slots (one unit per
396
+ * slot, up to modifier_special.quantity, at least one slot reserved per
397
+ * remaining option) — the modern view is refilled with the same number of
398
+ * filled slots the cashier originally picked.
368
399
  *
369
400
  * Returns null if the order item doesn't belong to the provided special.
370
401
  */
@@ -390,30 +421,49 @@ function deStructureSpecialOrderItem(orderItem, specialItem) {
390
421
  consumedModifierIds.add(orderModifier._id);
391
422
  const selectedItems = new Array(modifierSpecial.quantity).fill(null);
392
423
  if (orderModifier != null) {
393
- for (let j = 0; j < orderModifier.options.length; j++) {
394
- const option = orderModifier.options[j];
395
- const slotIndex = selectedItems.findIndex((item) => item === null);
396
- if (slotIndex === -1)
424
+ const buildSlotItem = (option, quantity) => ({
425
+ _id: option._id,
426
+ item_id: option.ref,
427
+ menu_id: orderItem.menu_id ?? null,
428
+ item_type: constants_1.ORDER_ITEM_TYPE_ENUM.SPECIAL,
429
+ name: option.name,
430
+ price: option.price,
431
+ subtotal: option.price,
432
+ tax_rate: 0,
433
+ quantity,
434
+ special_instructions: '',
435
+ item_discount_details: null,
436
+ modifiers: option.modifiers ?? null,
437
+ // These values will be auto calculated
438
+ _discount_amount: 0,
439
+ _gross_amount: 0,
440
+ _gst_amount: 0,
441
+ _net_amount: 0,
442
+ });
443
+ // Reverse fill (see the docblock): a merged option with quantity N is
444
+ // refilled as N slot selections (one unit per slot) where the slot
445
+ // budget allows. Every remaining option keeps at least one slot
446
+ // reserved so a merged quantity can never starve the others; when the
447
+ // slots run out the leftover units stay on a single slot (a
448
+ // drawer-stepped quantity keeps its legacy one-slot shape).
449
+ let freeSlots = selectedItems.filter((item) => item === null).length;
450
+ const storedOptions = orderModifier.options;
451
+ for (let j = 0; j < storedOptions.length; j++) {
452
+ if (freeSlots <= 0)
397
453
  break;
398
- selectedItems[slotIndex] = {
399
- _id: option._id,
400
- item_id: option.ref,
401
- menu_id: orderItem.menu_id ?? null,
402
- item_type: constants_1.ORDER_ITEM_TYPE_ENUM.SPECIAL,
403
- name: option.name,
404
- price: option.price,
405
- subtotal: option.price,
406
- tax_rate: 0,
407
- quantity: option.quantity,
408
- special_instructions: '',
409
- item_discount_details: null,
410
- modifiers: option.modifiers ?? null,
411
- // These values will be auto calculated
412
- _discount_amount: 0,
413
- _gross_amount: 0,
414
- _gst_amount: 0,
415
- _net_amount: 0,
416
- };
454
+ const option = storedOptions[j];
455
+ const units = option.quantity > 0 ? option.quantity : 1;
456
+ const remainingOptions = storedOptions.length - j - 1;
457
+ const slotsForOption = Math.min(units, Math.max(1, freeSlots - remainingOptions));
458
+ const unitsPerSlot = Math.floor(units / slotsForOption);
459
+ const slotsWithExtraUnit = units % slotsForOption;
460
+ for (let k = 0; k < slotsForOption; k++) {
461
+ const slotIndex = selectedItems.findIndex((item) => item === null);
462
+ if (slotIndex === -1)
463
+ break;
464
+ selectedItems[slotIndex] = buildSlotItem(option, unitsPerSlot + (k < slotsWithExtraUnit ? 1 : 0));
465
+ freeSlots -= 1;
466
+ }
417
467
  }
418
468
  }
419
469
  modifierSpecials.push({ _id: modifierSpecial._id, selectedItems });
@@ -589,6 +639,59 @@ function convertSpecialToItem(special, itemsMap, halfhalfSetups) {
589
639
  // (cannot be completed) — the whole conversion fails.
590
640
  if (options.length === 0)
591
641
  return null;
642
+ // ── Selection shape — DERIVED from how the drawer + engine consume
643
+ // these fields, not set generically ─────────────────────────────────
644
+ //
645
+ // Engine/UI switches on the fields (order-engine + drawer components):
646
+ // - `max_num_options === 1` → RADIO rows (tick one, no steppers)
647
+ // - `*_option_choice_quantity` set → stepper rows; a click seeds the
648
+ // row at `min_option_choice_quantity`; stepping below it deselects;
649
+ // a lone required option is AUTO-SELECTED on open at that quantity
650
+ // - `min/max_aggregate_options_quantity` → the UNIT total validation,
651
+ // click bounce and drawer caps enforce against (sum of option
652
+ // quantities — repeats included)
653
+ //
654
+ // A modifier special is "pick any mix of this group's items totalling
655
+ // `quantity` units". That leaves exactly two shapes:
656
+ // - quantity 1 → a single pick, no units involved: the engine-native
657
+ // RADIO shape (same config half-half segments use) — ticking a row
658
+ // selects it, ticking another switches, and the required flag keeps
659
+ // the pick from being deselected.
660
+ // - quantity > 1 → ticks cannot express units nor repeats, so the group
661
+ // must render as stepper rows with the AGGREGATES pinning the exact
662
+ // total (min = max = quantity): under-selection errors, exceeding
663
+ // bounces, and each row can repeat the same item. `min_num_options`
664
+ // stays 1 (never null) so the group is declared REQUIRED for every
665
+ // consumer that reads it directly (`min_num_options ?? ... ?? 0`) —
666
+ // the AGGREGATES remain the enforcement, and `max_num_options` stays
667
+ // null so the radio switch (`max_num_options === 1`) never trips on a
668
+ // multi-unit group. The click quantity differs by necessity:
669
+ // · multi-item group → a click adds ONE unit (the cashier
670
+ // distributes the rest with the steppers),
671
+ // · single-item group → there is no choice to make, so a click
672
+ // selects the FULL quantity in one go, and the engine's
673
+ // lone-required-option auto-select seeds it with the same amount
674
+ // the moment the drawer opens — identical outcome to the modern
675
+ // flow's slot auto-fill.
676
+ const groupQuantity = Math.max(1, modifierSpecial.quantity || 1);
677
+ const isSingleOptionGroup = options.length === 1;
678
+ const selectionShape = groupQuantity === 1
679
+ ? {
680
+ min_num_options: 1,
681
+ max_num_options: 1,
682
+ min_option_choice_quantity: null,
683
+ max_option_choice_quantity: null,
684
+ min_aggregate_options_quantity: null,
685
+ max_aggregate_options_quantity: null,
686
+ }
687
+ : {
688
+ min_num_options: 1,
689
+ max_num_options: null,
690
+ min_option_choice_quantity: isSingleOptionGroup ? groupQuantity : 1,
691
+ max_option_choice_quantity: groupQuantity,
692
+ min_aggregate_options_quantity: groupQuantity,
693
+ max_aggregate_options_quantity: groupQuantity,
694
+ };
592
695
  modifiers.push({
593
696
  // `_id` is the real modifier-special `_id` (like a catalog modifier id);
594
697
  // `ref` points to the same source modifier-special.
@@ -599,8 +702,7 @@ function convertSpecialToItem(special, itemsMap, halfhalfSetups) {
599
702
  active: true,
600
703
  sold_out: [],
601
704
  sort_id: modifierSpecial.sort_id,
602
- min_num_options: modifierSpecial.quantity,
603
- max_num_options: modifierSpecial.quantity,
705
+ ...selectionShape,
604
706
  num_free_options: modifierSpecial.num_free_items > 0 ? modifierSpecial.num_free_items : null,
605
707
  options,
606
708
  });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,319 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const constants_1 = require("../constants");
4
+ const order_engine_1 = require("../helpers/utils/order-engine");
5
+ const specials_helpers_1 = require("../helpers/utils/specials-helpers");
6
+ // ============================================================================
7
+ // Classic preview (`pos_enable_classic_specials_preview`) quantity parity.
8
+ //
9
+ // The modern flow lets a cashier pick the same item several times in a group
10
+ // (merged into one option with a summed quantity). The classic drawer must
11
+ // support the same selection semantics:
12
+ // - a group's exact total is enforced by the AGGREGATES (repeats allowed),
13
+ // - the drawer renders quantity rows (choice quantities),
14
+ // - a single-item group is selected in ONE click at the full quantity,
15
+ // - stored lines with repeated options (merged quantity, free/paid split)
16
+ // EDIT losslessly — occurrences aggregate into the one engine option.
17
+ // ============================================================================
18
+ const TENANT_ID = 'tenant-1';
19
+ const PLATFORM = constants_1.PLATFORMS_ENUM.POS_WALK_IN;
20
+ function makeItem(id, price, overrides = {}) {
21
+ return {
22
+ _id: id,
23
+ brand_id: 'brand-1',
24
+ tenants: [TENANT_ID],
25
+ category_id: 'pizza-cat',
26
+ included_platforms: [PLATFORM],
27
+ name: `Item ${id}`,
28
+ active: true,
29
+ sold_out: [],
30
+ sort_id: 1,
31
+ image_url: '',
32
+ price: { BASE_PRICE: price },
33
+ discount_amount: null,
34
+ is_discount_percentage: false,
35
+ tax_rate: null,
36
+ keywords: [],
37
+ caveats: [],
38
+ dietary_preferences: [],
39
+ hide_name: false,
40
+ description: '',
41
+ ingredients: null,
42
+ is_featured: false,
43
+ featured_sort_id: 0,
44
+ item_special_hours: null,
45
+ display_price: null,
46
+ show_starting_from: false,
47
+ createdAt: new Date('2024-01-01'),
48
+ updatedAt: new Date('2024-01-02'),
49
+ modifiers: null,
50
+ ...overrides,
51
+ };
52
+ }
53
+ const itemsMap = {
54
+ donut: makeItem('donut', 300),
55
+ pizzaA: makeItem('pizzaA', 400),
56
+ pizzaB: makeItem('pizzaB', 450),
57
+ };
58
+ function makeGroup({ quantity = 2, num_free_items = 0, items = ['donut'], } = {}) {
59
+ return {
60
+ _id: 'mod-donut',
61
+ name: 'Donuts',
62
+ sort_id: 1,
63
+ quantity,
64
+ num_free_items,
65
+ excluded_refs: [],
66
+ exclusive_refs: [],
67
+ omit_items_schedule: false,
68
+ items: items.map((item_id, index) => ({ item_id, sort_id: index + 1, upsell_price: null })),
69
+ };
70
+ }
71
+ function makeSpecial(overrides = {}) {
72
+ return {
73
+ _id: 'special-1',
74
+ brand_id: 'brand-1',
75
+ tenants: [TENANT_ID],
76
+ category_id: 'combo-cat',
77
+ included_platforms: [PLATFORM],
78
+ name: '2 Donut Deal',
79
+ description: '',
80
+ active: true,
81
+ sold_out: [],
82
+ sort_id: 1,
83
+ image_url: '',
84
+ price: { BASE_PRICE: 500 },
85
+ discount_amount: null,
86
+ is_discount_percentage: false,
87
+ display_price: null,
88
+ show_starting_from: false,
89
+ item_special_hours: null,
90
+ modifier_specials: [makeGroup()],
91
+ createdAt: new Date('2024-01-01'),
92
+ updatedAt: new Date('2024-01-02'),
93
+ ...overrides,
94
+ };
95
+ }
96
+ function makeWorkableSpecial(group) {
97
+ return {
98
+ _id: 'special-1',
99
+ name: '2 Donut Deal',
100
+ description: '',
101
+ sold_out: [],
102
+ image_url: '',
103
+ category_id: 'combo-cat',
104
+ price: { BASE_PRICE: 500 },
105
+ discount_amount: null,
106
+ is_discount_percentage: false,
107
+ display_price: null,
108
+ show_starting_from: false,
109
+ modifier_specials: [
110
+ {
111
+ _id: group._id,
112
+ name: group.name,
113
+ quantity: group.quantity,
114
+ num_free_items: group.num_free_items,
115
+ items: [],
116
+ exclusive_refs: [],
117
+ excluded_refs: [],
118
+ },
119
+ ],
120
+ };
121
+ }
122
+ function makeSlotItem(item_id, price) {
123
+ return {
124
+ _id: `slot-${item_id}`,
125
+ item_id,
126
+ menu_id: 'menu-1',
127
+ item_type: constants_1.ORDER_ITEM_TYPE_ENUM.SPECIAL,
128
+ name: `Item ${item_id}`,
129
+ price,
130
+ subtotal: price,
131
+ quantity: 1,
132
+ special_instructions: '',
133
+ item_discount_details: null,
134
+ tax_rate: 0,
135
+ modifiers: null,
136
+ _discount_amount: 0,
137
+ _gross_amount: 0,
138
+ _gst_amount: 0,
139
+ _net_amount: 0,
140
+ };
141
+ }
142
+ function buildModernLine(group, slotIds, price = 300) {
143
+ return (0, specials_helpers_1.convertSpecialItemToOrderItem)({
144
+ specialItem: makeWorkableSpecial(group),
145
+ modifierSpecials: [{ _id: group._id, selectedItems: slotIds.map((id) => makeSlotItem(id, price)) }],
146
+ quantity: 1,
147
+ platform: PLATFORM,
148
+ });
149
+ }
150
+ function classicEngineState(converted, orderItem) {
151
+ return (0, order_engine_1.convertCatalogItemToOrderEngineItem)({
152
+ item: converted,
153
+ orderItem,
154
+ platform: PLATFORM,
155
+ tenantId: TENANT_ID,
156
+ orderItemType: constants_1.ORDER_ITEM_TYPE_ENUM.SPECIAL,
157
+ defaultMenuId: null,
158
+ soldoutModifiers: [],
159
+ }).workingData;
160
+ }
161
+ function optionClickId(engineItem, optionIndex = 0) {
162
+ const group = engineItem.modifiers[0];
163
+ return `${group._id}_${group.options[optionIndex]._id}`;
164
+ }
165
+ describe('convertSpecialToItem: quantity-capable classic groups', () => {
166
+ it('configures a single-item group to be selected in one click at the full quantity', () => {
167
+ const converted = (0, specials_helpers_1.convertSpecialToItem)(makeSpecial(), itemsMap, {});
168
+ const group = converted.modifiers[0];
169
+ // Required flag stays >= 1 (`min_num_options ?? min_aggregate ?? 0`
170
+ // consumers mark the group REQUIRED); the exact total is enforced by the
171
+ // aggregates, and max stays null so the radio switch never trips.
172
+ expect(group.min_num_options).toBe(1);
173
+ expect(group.max_num_options).toBeNull();
174
+ expect(group.min_aggregate_options_quantity).toBe(2);
175
+ expect(group.max_aggregate_options_quantity).toBe(2);
176
+ // Single item: the click quantity IS the required total (no choice).
177
+ expect(group.min_option_choice_quantity).toBe(2);
178
+ expect(group.max_option_choice_quantity).toBe(2);
179
+ });
180
+ it('keeps the per-option minimum at 1 for a mix of items', () => {
181
+ const converted = (0, specials_helpers_1.convertSpecialToItem)(makeSpecial({ modifier_specials: [makeGroup({ items: ['pizzaA', 'pizzaB'] })] }), itemsMap, {});
182
+ const group = converted.modifiers[0];
183
+ expect(group.min_num_options).toBe(1);
184
+ expect(group.min_option_choice_quantity).toBe(1);
185
+ expect(group.max_option_choice_quantity).toBe(2);
186
+ expect(group.min_aggregate_options_quantity).toBe(2);
187
+ });
188
+ it('keeps a single-unit group as the engine-native RADIO shape (no steppers)', () => {
189
+ const converted = (0, specials_helpers_1.convertSpecialToItem)(makeSpecial({ modifier_specials: [makeGroup({ quantity: 1, items: ['pizzaA', 'pizzaB'] })] }), itemsMap, {});
190
+ const group = converted.modifiers[0];
191
+ // One pick, no quantities involved: `max_num_options === 1` IS the switch
192
+ // the drawer reads for radio rows, and leaving the choice/aggregate fields
193
+ // null keeps the steppers (and their caps) out of a single-pick group.
194
+ expect(group.min_num_options).toBe(1);
195
+ expect(group.max_num_options).toBe(1);
196
+ expect(group.min_option_choice_quantity).toBeNull();
197
+ expect(group.max_option_choice_quantity).toBeNull();
198
+ expect(group.min_aggregate_options_quantity).toBeNull();
199
+ expect(group.max_aggregate_options_quantity).toBeNull();
200
+ });
201
+ });
202
+ describe('classic add: single choice with quantity > 1', () => {
203
+ it('auto-selects the lone option at the full quantity when the drawer opens', () => {
204
+ const converted = (0, specials_helpers_1.convertSpecialToItem)(makeSpecial(), itemsMap, {});
205
+ // The engine seeds a lone required option with `min_option_choice_quantity`
206
+ // — for a single-item group that IS the required total, so the drawer opens
207
+ // complete (same outcome as the modern flow's slot auto-fill).
208
+ const fresh = classicEngineState(converted);
209
+ expect(fresh.error_id).toBeUndefined();
210
+ expect(fresh.modifiers[0].options[0]).toEqual(expect.objectContaining({ default: true, quantity: 2 }));
211
+ });
212
+ it('auto-selects AND free-marks the lone option of a fully-free group on open', () => {
213
+ const converted = (0, specials_helpers_1.convertSpecialToItem)(makeSpecial({ modifier_specials: [makeGroup({ num_free_items: 2 })] }), itemsMap, {});
214
+ // Free marking must run AFTER the auto-select, otherwise submitting
215
+ // without any interaction would charge for the auto-selected units.
216
+ const fresh = classicEngineState(converted);
217
+ expect(fresh.modifiers[0].options[0]).toEqual(expect.objectContaining({ default: true, quantity: 2, is_free: true }));
218
+ });
219
+ it('satisfies the required total with one click and stores the summed quantity', () => {
220
+ const converted = (0, specials_helpers_1.convertSpecialToItem)(makeSpecial(), itemsMap, {});
221
+ const fresh = classicEngineState(converted);
222
+ const clicked = (0, order_engine_1.setCheckFieldInOrderEngineItem)(fresh, optionClickId(fresh), true);
223
+ // Previously the group demanded two DISTINCT picks: clicking the only
224
+ // option left `error_id` set and the quantity stuck at 1.
225
+ expect(clicked.error_id).toBeUndefined();
226
+ expect(clicked.modifiers[0].options[0].quantity).toBe(2);
227
+ const orderItem = (0, order_engine_1.convertOrderEngineItemToOrderItem)(clicked, TENANT_ID);
228
+ expect(orderItem.modifiers[0].options).toEqual([expect.objectContaining({ ref: 'donut', quantity: 2 })]);
229
+ });
230
+ it('deselecting the only item restores the required error', () => {
231
+ const converted = (0, specials_helpers_1.convertSpecialToItem)(makeSpecial(), itemsMap, {});
232
+ const fresh = classicEngineState(converted);
233
+ const clicked = (0, order_engine_1.setCheckFieldInOrderEngineItem)(fresh, optionClickId(fresh), true);
234
+ const unclicked = (0, order_engine_1.setCheckFieldInOrderEngineItem)(clicked, optionClickId(clicked), false);
235
+ expect(unclicked.error_id).toBe('mod-donut');
236
+ });
237
+ it('allows picking the same item twice in a multi-item group', () => {
238
+ const converted = (0, specials_helpers_1.convertSpecialToItem)(makeSpecial({ modifier_specials: [makeGroup({ items: ['pizzaA', 'pizzaB'] })] }), itemsMap, {});
239
+ let engine = classicEngineState(converted);
240
+ const identifier = optionClickId(engine);
241
+ // Pick pizza A once, then STEP it up to 2 — the old tick-only group could
242
+ // only ever select two DISTINCT items.
243
+ engine = (0, order_engine_1.setCheckFieldInOrderEngineItem)(engine, identifier, true);
244
+ expect(engine.modifiers[0].options.find((o) => o._id === 'pizzaA').quantity).toBe(1);
245
+ engine = (0, order_engine_1.setUpdateSelectedOrderEngineOptionQuantity)(engine, identifier, 1, true);
246
+ expect(engine.modifiers[0].options.find((o) => o._id === 'pizzaA').quantity).toBe(2);
247
+ expect(engine.error_id).toBeUndefined();
248
+ });
249
+ it('marks both units free for a "2 Free Donuts" group', () => {
250
+ const converted = (0, specials_helpers_1.convertSpecialToItem)(makeSpecial({ modifier_specials: [makeGroup({ num_free_items: 2 })] }), itemsMap, {});
251
+ const fresh = classicEngineState(converted);
252
+ const clicked = (0, order_engine_1.setCheckFieldInOrderEngineItem)(fresh, optionClickId(fresh), true);
253
+ expect(clicked.modifiers[0].options[0]).toEqual(expect.objectContaining({ quantity: 2, is_free: true }));
254
+ });
255
+ });
256
+ describe('classic add: single-unit groups behave like a radio modifier', () => {
257
+ const unitSpecial = (items, num_free_items = 0) => makeSpecial({ modifier_specials: [makeGroup({ quantity: 1, items, num_free_items })] });
258
+ it('selects one pick and switches between options (radio semantics)', () => {
259
+ const converted = (0, specials_helpers_1.convertSpecialToItem)(unitSpecial(['pizzaA', 'pizzaB']), itemsMap, {});
260
+ const fresh = classicEngineState(converted);
261
+ const pickA = (0, order_engine_1.setCheckFieldInOrderEngineItem)(fresh, optionClickId(fresh, 0), true);
262
+ expect(pickA.error_id).toBeUndefined();
263
+ expect(pickA.modifiers[0].options.map((option) => option.default)).toEqual([true, false]);
264
+ // Ticking the other item REPLACES the pick (radio), it does not add a unit.
265
+ const pickB = (0, order_engine_1.setCheckFieldInOrderEngineItem)(pickA, optionClickId(pickA, 1), true);
266
+ expect(pickB.modifiers[0].options.map((option) => option.default)).toEqual([false, true]);
267
+ expect(pickB.modifiers[0].options[1].quantity).toBe(1);
268
+ expect(pickB.error_id).toBeUndefined();
269
+ });
270
+ it('auto-selects the only option and the required pick cannot be cleared', () => {
271
+ const converted = (0, specials_helpers_1.convertSpecialToItem)(unitSpecial(['donut']), itemsMap, {});
272
+ const fresh = classicEngineState(converted);
273
+ expect(fresh.modifiers[0].options[0].default).toBe(true);
274
+ expect(fresh.error_id).toBeUndefined();
275
+ // The radio screen always sends `shouldCheck: true` for the row it renders
276
+ // as selected — the pick stays selected (required radio).
277
+ const reclicked = (0, order_engine_1.setCheckFieldInOrderEngineItem)(fresh, optionClickId(fresh), true);
278
+ expect(reclicked.modifiers[0].options[0].default).toBe(true);
279
+ expect(reclicked.error_id).toBeUndefined();
280
+ });
281
+ it('free-marks the single pick when num_free_items covers it', () => {
282
+ const converted = (0, specials_helpers_1.convertSpecialToItem)(unitSpecial(['pizzaA', 'pizzaB'], 1), itemsMap, {});
283
+ const fresh = classicEngineState(converted);
284
+ const picked = (0, order_engine_1.setCheckFieldInOrderEngineItem)(fresh, optionClickId(fresh, 0), true);
285
+ expect(picked.modifiers[0].options[0]).toEqual(expect.objectContaining({ quantity: 1, is_free: true }));
286
+ });
287
+ });
288
+ describe('classic edit: repeated stored options aggregate into one engine option', () => {
289
+ it('maps a merged [qty 2] line without losing units or flagging an error', () => {
290
+ const converted = (0, specials_helpers_1.convertSpecialToItem)(makeSpecial(), itemsMap, {});
291
+ const modern = buildModernLine(makeGroup(), ['donut', 'donut']);
292
+ const engine = classicEngineState(converted, modern);
293
+ expect(engine.error_id).toBeUndefined();
294
+ expect(engine.modifiers[0].options[0]).toEqual(expect.objectContaining({ default: true, quantity: 2, is_free: false }));
295
+ const resaved = (0, order_engine_1.convertOrderEngineItemToOrderItem)(engine, TENANT_ID);
296
+ expect(resaved.modifiers[0].options).toEqual([
297
+ expect.objectContaining({ ref: 'donut', quantity: 2, is_free: false }),
298
+ ]);
299
+ });
300
+ it('maps a free/paid split line (previously blocked) keeping it PAID', () => {
301
+ const group = makeGroup({ num_free_items: 1 });
302
+ const converted = (0, specials_helpers_1.convertSpecialToItem)(makeSpecial({ modifier_specials: [group] }), itemsMap, {});
303
+ const modern = buildModernLine(group, ['donut', 'donut']);
304
+ // Modern free marking split the two units: one free, one paid.
305
+ expect(modern.modifiers[0].options.map((o) => o.is_free)).toEqual([true, false]);
306
+ const engine = classicEngineState(converted, modern);
307
+ expect(engine.error_id).toBeUndefined();
308
+ // One engine option cannot be half free: any paid occurrence keeps it paid.
309
+ expect(engine.modifiers[0].options[0]).toEqual(expect.objectContaining({ quantity: 2, is_free: false }));
310
+ });
311
+ it('keeps an all-free repeated line free', () => {
312
+ const group = makeGroup({ num_free_items: 2 });
313
+ const converted = (0, specials_helpers_1.convertSpecialToItem)(makeSpecial({ modifier_specials: [group] }), itemsMap, {});
314
+ const modern = buildModernLine(group, ['donut', 'donut']);
315
+ const engine = classicEngineState(converted, modern);
316
+ expect(engine.error_id).toBeUndefined();
317
+ expect(engine.modifiers[0].options[0]).toEqual(expect.objectContaining({ quantity: 2, is_free: true }));
318
+ });
319
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,193 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const constants_1 = require("../constants");
4
+ const order_engine_1 = require("../helpers/utils/order-engine");
5
+ // ============================================================================
6
+ // SCOPE GUARD — the two setup-only engine rules must never leak into the
7
+ // regular item selection path:
8
+ //
9
+ // 1. duplicate stored occurrences of one option are AGGREGATED for
10
+ // SPECIAL / HALF_HALF order items (merged repeats, free/paid splits,
11
+ // legacy per-slot options). Regular ITEM conversions keep the original
12
+ // single-match (`find`) lookup.
13
+ // 2. free marking (`num_free_options`) runs AFTER the lone-option
14
+ // auto-select for setups (auto-selected option takes part in it).
15
+ // Regular ITEM conversions keep the original position (free marking
16
+ // before the auto-select).
17
+ //
18
+ // If these tests fail, a specials/half-half change has altered the item
19
+ // process — that is not allowed.
20
+ // ============================================================================
21
+ const TENANT_ID = 'tenant-1';
22
+ const PLATFORM = constants_1.PLATFORMS_ENUM.POS_WALK_IN;
23
+ function makeItem(overrides = {}) {
24
+ return {
25
+ _id: 'item-1',
26
+ brand_id: 'brand-1',
27
+ tenants: [TENANT_ID],
28
+ category_id: 'cat-1',
29
+ included_platforms: [PLATFORM],
30
+ name: 'Item',
31
+ hide_name: false,
32
+ description: '',
33
+ active: true,
34
+ sold_out: [],
35
+ sort_id: 1,
36
+ price: { BASE_PRICE: 500 },
37
+ discount_amount: null,
38
+ is_discount_percentage: false,
39
+ tax_rate: null,
40
+ keywords: [],
41
+ caveats: [],
42
+ dietary_preferences: [],
43
+ image_url: '',
44
+ ingredients: null,
45
+ item_special_hours: null,
46
+ modifiers: null,
47
+ is_featured: false,
48
+ featured_sort_id: 0,
49
+ display_price: null,
50
+ show_starting_from: false,
51
+ createdAt: new Date('2024-01-01'),
52
+ updatedAt: new Date('2024-01-02'),
53
+ ...overrides,
54
+ };
55
+ }
56
+ function makeStoredOption(quantity, is_free) {
57
+ return {
58
+ _id: 'opt-a',
59
+ ref: 'opt-a',
60
+ name: 'A',
61
+ price: 300,
62
+ quantity,
63
+ is_free,
64
+ modifiers: [],
65
+ };
66
+ }
67
+ function makeStoredModifier(options) {
68
+ return { _id: 'mod-1', ref: 'mod-1', name: 'Sauce', options };
69
+ }
70
+ function makeOrderItem(modifiers, itemType) {
71
+ return {
72
+ _id: 'order-item-1',
73
+ item_id: 'item-1',
74
+ menu_id: null,
75
+ item_type: itemType,
76
+ name: 'Item',
77
+ price: 500,
78
+ subtotal: 0,
79
+ quantity: 1,
80
+ special_instructions: '',
81
+ item_discount_details: null,
82
+ tax_rate: 0,
83
+ modifiers,
84
+ _discount_amount: 0,
85
+ _gross_amount: 0,
86
+ _gst_amount: 0,
87
+ _net_amount: 0,
88
+ };
89
+ }
90
+ /** One modifier with the single option `opt-a` the fixtures reference. */
91
+ const itemWithOneOption = makeItem({
92
+ modifiers: [
93
+ {
94
+ _id: 'mod-1',
95
+ ref: 'mod-1',
96
+ name: 'Sauce',
97
+ description: '',
98
+ active: true,
99
+ sold_out: [],
100
+ sort_id: 1,
101
+ options: [
102
+ {
103
+ _id: 'opt-a',
104
+ ref: 'opt-a',
105
+ name: 'A',
106
+ active: true,
107
+ sold_out: [],
108
+ sort_id: 1,
109
+ excluded_platforms: [],
110
+ price: { BASE_PRICE: 300 },
111
+ modifiers: null,
112
+ },
113
+ ],
114
+ },
115
+ ],
116
+ });
117
+ function convert(item, orderItem, orderItemType) {
118
+ return (0, order_engine_1.convertCatalogItemToOrderEngineItem)({
119
+ item,
120
+ orderItem,
121
+ platform: PLATFORM,
122
+ tenantId: TENANT_ID,
123
+ orderItemType,
124
+ defaultMenuId: null,
125
+ soldoutModifiers: [],
126
+ }).workingData;
127
+ }
128
+ describe('engine scope guard: duplicate occurrences (setup-only aggregation)', () => {
129
+ it('KEEPS the original single-match lookup for ITEM conversions', () => {
130
+ const orderItem = makeOrderItem([makeStoredModifier([makeStoredOption(2, false), makeStoredOption(1, true)])], constants_1.ORDER_ITEM_TYPE_ENUM.ITEM);
131
+ const engine = convert(itemWithOneOption, orderItem, constants_1.ORDER_ITEM_TYPE_ENUM.ITEM);
132
+ const option = engine.modifiers[0].options[0];
133
+ // Original behavior: FIRST occurrence wins (quantity 2, is_free false —
134
+ // the second occurrence is ignored), exactly as before the setup work.
135
+ expect(option).toEqual(expect.objectContaining({ default: true, quantity: 2, is_free: false }));
136
+ });
137
+ it('AGGREGATES occurrences for SPECIAL conversions (merged repeats / free split)', () => {
138
+ const orderItem = makeOrderItem([makeStoredModifier([makeStoredOption(2, false), makeStoredOption(1, true)])], constants_1.ORDER_ITEM_TYPE_ENUM.SPECIAL);
139
+ const engine = convert(itemWithOneOption, orderItem, constants_1.ORDER_ITEM_TYPE_ENUM.SPECIAL);
140
+ const option = engine.modifiers[0].options[0];
141
+ // Quantity summed (2 + 1); a paid occurrence keeps the row paid.
142
+ expect(option).toEqual(expect.objectContaining({ default: true, quantity: 3, is_free: false }));
143
+ expect(engine.error_id).toBeUndefined();
144
+ });
145
+ it('AGGREGATES all-free occurrences to a free quantity row (SPECIAL)', () => {
146
+ const orderItem = makeOrderItem([makeStoredModifier([makeStoredOption(2, true), makeStoredOption(1, true)])], constants_1.ORDER_ITEM_TYPE_ENUM.SPECIAL);
147
+ const engine = convert(itemWithOneOption, orderItem, constants_1.ORDER_ITEM_TYPE_ENUM.SPECIAL);
148
+ expect(engine.modifiers[0].options[0]).toEqual(expect.objectContaining({ default: true, quantity: 3, is_free: true }));
149
+ });
150
+ });
151
+ describe('engine scope guard: free marking position (setup-only reorder)', () => {
152
+ // A required modifier with ONE option and a free budget covering it — the
153
+ // exact shape the reorder targets.
154
+ const freshItem = makeItem({
155
+ modifiers: [
156
+ {
157
+ _id: 'mod-1',
158
+ ref: 'mod-1',
159
+ name: 'Sauce',
160
+ description: '',
161
+ active: true,
162
+ sold_out: [],
163
+ sort_id: 1,
164
+ min_num_options: 1,
165
+ max_num_options: 1,
166
+ num_free_options: 1,
167
+ options: [
168
+ {
169
+ _id: 'opt-a',
170
+ ref: 'opt-a',
171
+ name: 'A',
172
+ active: true,
173
+ sold_out: [],
174
+ sort_id: 1,
175
+ excluded_platforms: [],
176
+ price: { BASE_PRICE: 300 },
177
+ modifiers: null,
178
+ },
179
+ ],
180
+ },
181
+ ],
182
+ });
183
+ it('KEEPS the original position for ITEM conversions (auto-selected, not free)', () => {
184
+ const engine = convert(freshItem, undefined, constants_1.ORDER_ITEM_TYPE_ENUM.ITEM);
185
+ // Original behavior: free marking ran BEFORE the auto-select, so the
186
+ // auto-selected option is not free until the user interacts.
187
+ expect(engine.modifiers[0].options[0]).toEqual(expect.objectContaining({ default: true, quantity: 1, is_free: false }));
188
+ });
189
+ it('free-marks the auto-selected option for SPECIAL conversions', () => {
190
+ const engine = convert(freshItem, undefined, constants_1.ORDER_ITEM_TYPE_ENUM.SPECIAL);
191
+ expect(engine.modifiers[0].options[0]).toEqual(expect.objectContaining({ default: true, quantity: 1, is_free: true }));
192
+ });
193
+ });
@@ -328,8 +328,16 @@ describe('Specials alone — convertSpecialToItem pricing', () => {
328
328
  ],
329
329
  }), itemsMap, {});
330
330
  const group = item.modifiers[0];
331
- expect(group.min_num_options).toBe(2);
332
- expect(group.max_num_options).toBe(2);
331
+ // Quantity-capable group (classic parity with the modern slot flow): the
332
+ // exact total is enforced by the AGGREGATES (any mix, repeats allowed),
333
+ // the drawer renders quantity rows, min_num_options stays 1 (required
334
+ // flag), and num_free_options still mirrors num_free_items.
335
+ expect(group.min_num_options).toBe(1);
336
+ expect(group.max_num_options).toBeNull();
337
+ expect(group.min_aggregate_options_quantity).toBe(2);
338
+ expect(group.max_aggregate_options_quantity).toBe(2);
339
+ expect(group.min_option_choice_quantity).toBe(1); // a real mix of items
340
+ expect(group.max_option_choice_quantity).toBe(2);
333
341
  expect(group.num_free_options).toBe(1);
334
342
  });
335
343
  it('exclusive_refs zero nested item modifier prices; excluded_refs REMOVE them (recursive)', () => {
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,198 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const constants_1 = require("../constants");
4
+ const store_1 = require("../helpers/store");
5
+ const specials_helpers_1 = require("../helpers/utils/specials-helpers");
6
+ // ============================================================================
7
+ // Specials: identical slot selections merge into ONE option with a summed
8
+ // quantity — picking the same pizza (same modifiers, same instructions) in
9
+ // two slots must produce `quantity: 2` on a single option, exactly like the
10
+ // cart merges two identical lines (getComparableItem + deep equality).
11
+ // The reverse (deStructure) must refill the modern view with the same number
12
+ // of slots the cashier picked.
13
+ // ============================================================================
14
+ const PLATFORM = constants_1.PLATFORMS_ENUM.POS_WALK_IN;
15
+ function makeModifierSpecial(overrides = {}) {
16
+ return {
17
+ _id: 'mod-pizza',
18
+ name: 'Pizza',
19
+ quantity: 3,
20
+ num_free_items: 0,
21
+ items: [],
22
+ exclusive_refs: [],
23
+ excluded_refs: [],
24
+ ...overrides,
25
+ };
26
+ }
27
+ function makeWorkableSpecial(overrides = {}) {
28
+ return {
29
+ _id: 'special-1',
30
+ name: 'Student Deal',
31
+ description: 'Deal',
32
+ sold_out: [],
33
+ image_url: 'https://example.com/special.jpg',
34
+ category_id: 'combo-cat',
35
+ price: { BASE_PRICE: 1000 },
36
+ discount_amount: null,
37
+ is_discount_percentage: false,
38
+ display_price: null,
39
+ show_starting_from: false,
40
+ modifier_specials: [makeModifierSpecial()],
41
+ ...overrides,
42
+ };
43
+ }
44
+ function makeOrderModifier(id, optionName = 'Small') {
45
+ return {
46
+ _id: id,
47
+ ref: id,
48
+ name: 'Size',
49
+ options: [
50
+ {
51
+ _id: `${id}-opt`,
52
+ ref: `${id}-opt`,
53
+ name: optionName,
54
+ price: 0,
55
+ quantity: 1,
56
+ is_free: false,
57
+ modifiers: [],
58
+ },
59
+ ],
60
+ };
61
+ }
62
+ function makeSlotItem(overrides = {}) {
63
+ return {
64
+ _id: 'slot-1',
65
+ item_id: 'pizza-a',
66
+ menu_id: 'menu-1',
67
+ item_type: constants_1.ORDER_ITEM_TYPE_ENUM.ITEM,
68
+ name: 'Pizza A',
69
+ price: 500,
70
+ subtotal: 500,
71
+ quantity: 1,
72
+ special_instructions: '',
73
+ item_discount_details: null,
74
+ tax_rate: 0,
75
+ modifiers: null,
76
+ _discount_amount: 0,
77
+ _gross_amount: 0,
78
+ _gst_amount: 0,
79
+ _net_amount: 0,
80
+ ...overrides,
81
+ };
82
+ }
83
+ function convert(selectedItems, specialItem = makeWorkableSpecial()) {
84
+ return (0, specials_helpers_1.convertSpecialItemToOrderItem)({
85
+ specialItem,
86
+ modifierSpecials: [{ _id: 'mod-pizza', selectedItems }],
87
+ quantity: 1,
88
+ platform: PLATFORM,
89
+ });
90
+ }
91
+ describe('convertSpecialItemToOrderItem: identical selections merge into one option', () => {
92
+ it('sets the summed quantity on a single option instead of N options', () => {
93
+ const converted = convert([makeSlotItem(), makeSlotItem()]);
94
+ const group = converted.modifiers[0];
95
+ expect(group.options).toHaveLength(1);
96
+ expect(group.options[0]._id).toBe('pizza-a');
97
+ expect(group.options[0].quantity).toBe(2);
98
+ });
99
+ it('keeps the totals identical to the per-slot math', () => {
100
+ // 1000 (special price) + 2 × 500 (the two pizzas) — the merge must not
101
+ // change what the cashier pays.
102
+ const merged = convert([makeSlotItem(), makeSlotItem()]);
103
+ expect(merged.subtotal).toBe(2000);
104
+ const mixed = convert([makeSlotItem(), makeSlotItem({ quantity: 2 })]);
105
+ expect(mixed.modifiers[0].options[0].quantity).toBe(3);
106
+ expect(mixed.subtotal).toBe(2500); // 1000 + 3 × 500
107
+ });
108
+ it('keeps selections with different modifiers apart', () => {
109
+ const converted = convert([makeSlotItem(), makeSlotItem({ modifiers: [makeOrderModifier('size-large')] })]);
110
+ expect(converted.modifiers[0].options).toHaveLength(2);
111
+ });
112
+ it('keeps selections with different instructions apart', () => {
113
+ const converted = convert([makeSlotItem(), makeSlotItem({ special_instructions: 'no onions' })]);
114
+ expect(converted.modifiers[0].options).toHaveLength(2);
115
+ });
116
+ it('merges identical half-half selections the same way', () => {
117
+ const halfHalfSlot = {
118
+ item_id: 'halfhalf-1',
119
+ item_type: constants_1.ORDER_ITEM_TYPE_ENUM.HALF_HALF,
120
+ name: 'Half/Half Pizza Large',
121
+ price: 300,
122
+ modifiers: [makeOrderModifier('seg-1', 'First Half')],
123
+ };
124
+ const converted = convert([makeSlotItem(halfHalfSlot), makeSlotItem(halfHalfSlot)]);
125
+ const group = converted.modifiers[0];
126
+ expect(group.options).toHaveLength(1);
127
+ expect(group.options[0].quantity).toBe(2);
128
+ expect(group.options[0].ref_type).toBe(constants_1.MODIFIER_OPTION_REF_TYPE_ENUM.HALF_HALF);
129
+ });
130
+ it('keeps the per-slot free semantics for mixed free/paid identical units', () => {
131
+ // num_free_items = 1 with 2 identical: the cheapest slot (the first) is
132
+ // free — one FREE unit + one PAID unit, never "2 free".
133
+ const special = makeWorkableSpecial({
134
+ modifier_specials: [makeModifierSpecial({ num_free_items: 1 })],
135
+ });
136
+ const converted = convert([makeSlotItem(), makeSlotItem()], special);
137
+ const options = converted.modifiers[0].options;
138
+ expect(options).toHaveLength(2);
139
+ const freeOption = options.find((option) => option.is_free);
140
+ const paidOption = options.find((option) => !option.is_free);
141
+ expect(freeOption?.quantity).toBe(1);
142
+ expect(paidOption?.quantity).toBe(1);
143
+ });
144
+ it('merges the free units together when all of them are free', () => {
145
+ const special = makeWorkableSpecial({
146
+ modifier_specials: [makeModifierSpecial({ num_free_items: 2 })],
147
+ });
148
+ const converted = convert([makeSlotItem(), makeSlotItem(), makeSlotItem()], special);
149
+ const options = converted.modifiers[0].options;
150
+ expect(options).toHaveLength(2);
151
+ expect(options.find((option) => option.is_free)?.quantity).toBe(2);
152
+ expect(options.find((option) => !option.is_free)?.quantity).toBe(1);
153
+ });
154
+ });
155
+ describe('deStructureSpecialOrderItem: reverse fill the modern view', () => {
156
+ it('expands a merged quantity into the same number of slots', () => {
157
+ const converted = convert([makeSlotItem(), makeSlotItem()]);
158
+ const reversed = (0, specials_helpers_1.deStructureSpecialOrderItem)(converted, makeWorkableSpecial());
159
+ const slots = reversed.modifierSpecials[0].selectedItems;
160
+ expect(slots).toHaveLength(3);
161
+ expect(slots.map((item) => item?.item_id ?? null)).toEqual(['pizza-a', 'pizza-a', null]);
162
+ expect(slots.map((item) => item?.quantity ?? null)).toEqual([1, 1, null]);
163
+ });
164
+ it('reserves a slot for every remaining option when expanding', () => {
165
+ const converted = convert([makeSlotItem(), makeSlotItem(), makeSlotItem({ item_id: 'pizza-b', name: 'Pizza B' })]);
166
+ const reversed = (0, specials_helpers_1.deStructureSpecialOrderItem)(converted, makeWorkableSpecial());
167
+ const slots = reversed.modifierSpecials[0].selectedItems;
168
+ expect(slots.map((item) => item?.item_id ?? null)).toEqual(['pizza-a', 'pizza-a', 'pizza-b']);
169
+ expect(slots.map((item) => item?.quantity ?? null)).toEqual([1, 1, 1]);
170
+ });
171
+ it('keeps a legacy one-slot quantity shape when the group has no room', () => {
172
+ const converted = convert([makeSlotItem(), makeSlotItem()]);
173
+ const singleSlotSpecial = makeWorkableSpecial({
174
+ modifier_specials: [makeModifierSpecial({ quantity: 1 })],
175
+ });
176
+ const reversed = (0, specials_helpers_1.deStructureSpecialOrderItem)(converted, singleSlotSpecial);
177
+ const slots = reversed.modifierSpecials[0].selectedItems;
178
+ expect(slots).toHaveLength(1);
179
+ expect(slots[0]?.quantity).toBe(2);
180
+ });
181
+ it('round-trips: slots -> merged order item -> slots -> the SAME order item', () => {
182
+ const slots = [makeSlotItem(), makeSlotItem(), makeSlotItem({ item_id: 'pizza-b', name: 'Pizza B' })];
183
+ const first = convert(slots);
184
+ const reversed = (0, specials_helpers_1.deStructureSpecialOrderItem)(first, makeWorkableSpecial());
185
+ const second = convert(reversed.modifierSpecials[0].selectedItems);
186
+ expect(second.modifiers[0].options).toEqual(first.modifiers[0].options);
187
+ expect(second.subtotal).toBe(first.subtotal);
188
+ });
189
+ });
190
+ describe('getComparableOrderItem', () => {
191
+ it('ignores quantity (and _id) so summed units stay comparable', () => {
192
+ expect((0, store_1.getComparableOrderItem)(makeSlotItem())).toEqual((0, store_1.getComparableOrderItem)(makeSlotItem({ quantity: 5 })));
193
+ });
194
+ it('separates items with different instructions or modifiers', () => {
195
+ expect((0, store_1.getComparableOrderItem)(makeSlotItem())).not.toEqual((0, store_1.getComparableOrderItem)(makeSlotItem({ special_instructions: 'no onions' })));
196
+ expect((0, store_1.getComparableOrderItem)(makeSlotItem())).not.toEqual((0, store_1.getComparableOrderItem)(makeSlotItem({ modifiers: [makeOrderModifier('size-large')] })));
197
+ });
198
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@managesome/eposmatic-toolkit",
3
- "version": "0.2.767",
3
+ "version": "0.2.769",
4
4
  "description": "A Toolkit Library for Eposmatic",
5
5
  "main": "lib/index.js",
6
6
  "types": "lib/index.d.ts",