@managesome/eposmatic-toolkit 0.2.768 → 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.
@@ -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;
@@ -639,6 +639,59 @@ function convertSpecialToItem(special, itemsMap, halfhalfSetups) {
639
639
  // (cannot be completed) — the whole conversion fails.
640
640
  if (options.length === 0)
641
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
+ };
642
695
  modifiers.push({
643
696
  // `_id` is the real modifier-special `_id` (like a catalog modifier id);
644
697
  // `ref` points to the same source modifier-special.
@@ -649,8 +702,7 @@ function convertSpecialToItem(special, itemsMap, halfhalfSetups) {
649
702
  active: true,
650
703
  sold_out: [],
651
704
  sort_id: modifierSpecial.sort_id,
652
- min_num_options: modifierSpecial.quantity,
653
- max_num_options: modifierSpecial.quantity,
705
+ ...selectionShape,
654
706
  num_free_options: modifierSpecial.num_free_items > 0 ? modifierSpecial.num_free_items : null,
655
707
  options,
656
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)', () => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@managesome/eposmatic-toolkit",
3
- "version": "0.2.768",
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",