@managesome/eposmatic-toolkit 0.2.721 → 0.2.732

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,702 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const constants_1 = require("../constants");
4
+ const halfhalf_setup_helpers_1 = require("../helpers/utils/halfhalf-setup-helpers");
5
+ const order_engine_1 = require("../helpers/utils/order-engine");
6
+ const specials_helpers_1 = require("../helpers/utils/specials-helpers");
7
+ // ============================================================================
8
+ // choose_expensive_segment_price — cross-flow verification.
9
+ //
10
+ // Verifies the rule end-to-end in the three real contexts:
11
+ // 1. STANDALONE half-half — classic flow (IHalfHalfSetup -> IItem -> engine
12
+ // -> drawer rule with references) vs modern flow
13
+ // (convertHalfHalfSetupToWorkableHalfHalfSetup -> stored selections ->
14
+ // convertHalfHalfToOrderEngineItem with the flag).
15
+ // 2. SPECIAL (whole item) — the nested rule over a flagged HALF_HALF
16
+ // option (applyNestedChooseExpensiveSegmentPrice).
17
+ // 3. SPECIAL (pick flow) — the drawer-style conversion of the half-half
18
+ // OPTION with specialItems + zeroPriceRefs, top-level rule — must agree
19
+ // with (2) for the same halves.
20
+ //
21
+ // Expected numbers (fixture below):
22
+ // roma : price 1000, required size large-13 (1150, default) -> per half
23
+ // 500 + 575 = 1075
24
+ // milano : price 1200, required size l13-milano (1000, default) -> per half
25
+ // 600 + 500 = 1100
26
+ // torent : price 800, no modifiers -> 400 per half
27
+ // half-half level upsell: null (item price 0)
28
+ // ============================================================================
29
+ const TENANT_ID = 'tenant-1';
30
+ const PLATFORM = constants_1.PLATFORMS_ENUM.POS_WALK_IN;
31
+ // ---------------------------------------------------------------------------
32
+ // Fixtures (standalone)
33
+ // ---------------------------------------------------------------------------
34
+ function makeItem(id, overrides = {}) {
35
+ return {
36
+ _id: id,
37
+ brand_id: 'brand-1',
38
+ tenants: ['tenant-1'],
39
+ category_id: 'pizza-cat',
40
+ included_platforms: [PLATFORM],
41
+ name: `Item ${id}`,
42
+ hide_name: false,
43
+ description: '',
44
+ active: true,
45
+ sold_out: [],
46
+ sort_id: 1,
47
+ price: { BASE_PRICE: 1000 },
48
+ discount_amount: null,
49
+ is_discount_percentage: false,
50
+ tax_rate: null,
51
+ keywords: [],
52
+ caveats: [],
53
+ dietary_preferences: [],
54
+ image_url: '',
55
+ ingredients: null,
56
+ item_special_hours: null,
57
+ display_price: null,
58
+ show_starting_from: false,
59
+ use_source_ingredients: false,
60
+ is_featured: false,
61
+ featured_sort_id: 0,
62
+ createdAt: new Date('2024-01-01'),
63
+ updatedAt: new Date('2024-01-02'),
64
+ modifiers: null,
65
+ ...overrides,
66
+ };
67
+ }
68
+ function makeOption(id, overrides = {}) {
69
+ return {
70
+ _id: id,
71
+ ref: id,
72
+ name: `Option ${id}`,
73
+ active: true,
74
+ sold_out: [],
75
+ sort_id: 1,
76
+ excluded_platforms: [],
77
+ price: null,
78
+ modifiers: null,
79
+ ...overrides,
80
+ };
81
+ }
82
+ function makeModifier(id, options, overrides = {}) {
83
+ return {
84
+ _id: id,
85
+ ref: id,
86
+ name: `Modifier ${id}`,
87
+ description: '',
88
+ active: true,
89
+ sold_out: [],
90
+ sort_id: 1,
91
+ options,
92
+ ...overrides,
93
+ };
94
+ }
95
+ /** "Pizza Size" (required: large default 1150, small 500) + optional "Extras" (cheese 200). */
96
+ function makePizzaSizeAndExtra(cheeseDefault = false) {
97
+ return [
98
+ makeModifier('size-mod', [
99
+ makeOption('large-13', { name: 'Large 13"', price: { BASE_PRICE: 1150 }, default: true }),
100
+ makeOption('small-11', { name: 'Small 11"', price: { BASE_PRICE: 500 } }),
101
+ ], { name: 'Pizza Size', min_num_options: 1, max_num_options: 1 }),
102
+ makeModifier('extra-mod', [makeOption('cheese', { name: 'Extra Cheese', price: { BASE_PRICE: 200 }, default: cheeseDefault })], {
103
+ name: 'Extras',
104
+ max_num_options: 1,
105
+ }),
106
+ ];
107
+ }
108
+ function makeStandaloneItems(cheeseDefault = false) {
109
+ return {
110
+ roma: makeItem('roma', { price: { BASE_PRICE: 1000 }, modifiers: makePizzaSizeAndExtra(cheeseDefault) }),
111
+ milano: makeItem('milano', {
112
+ price: { BASE_PRICE: 1200 },
113
+ modifiers: [
114
+ makeModifier('size-milano', [makeOption('l13-milano', { name: 'Large 13"', price: { BASE_PRICE: 1000 }, default: true })], { name: 'Pizza Size', min_num_options: 1, max_num_options: 1 }),
115
+ ],
116
+ }),
117
+ torent: makeItem('torent', { price: { BASE_PRICE: 800 } }),
118
+ napoli: makeItem('napoli', { price: { BASE_PRICE: 900 } }),
119
+ };
120
+ }
121
+ function makeSetup(overrides = {}) {
122
+ return {
123
+ _id: 'halfhalf-1',
124
+ brand_id: 'brand-1',
125
+ tenants: ['tenant-1'],
126
+ category_id: 'pizza-cat',
127
+ included_platforms: [PLATFORM],
128
+ name: 'Half/Half Pizza',
129
+ description: '',
130
+ active: true,
131
+ sold_out: [],
132
+ image_url: '',
133
+ upsell_price: null,
134
+ discount_amount: null,
135
+ is_discount_percentage: false,
136
+ choose_expensive_segment_price: true,
137
+ segments: [
138
+ { _id: 'seg-1', name: 'First Half', sort_id: 1 },
139
+ { _id: 'seg-2', name: 'Second Half', sort_id: 2 },
140
+ ],
141
+ items: [
142
+ { item_id: 'roma', sort_id: 1, upsell_price: null },
143
+ { item_id: 'milano', sort_id: 2, upsell_price: null },
144
+ { item_id: 'torent', sort_id: 3, upsell_price: null },
145
+ { item_id: 'napoli', sort_id: 4, upsell_price: null },
146
+ ],
147
+ exclusive_refs: [],
148
+ excluded_refs: [],
149
+ item_special_hours: null,
150
+ createdAt: new Date('2024-01-01'),
151
+ updatedAt: new Date('2024-01-02'),
152
+ ...overrides,
153
+ };
154
+ }
155
+ // ---------------------------------------------------------------------------
156
+ // Flow runners
157
+ // ---------------------------------------------------------------------------
158
+ /** Classic: setup -> half-half ITEM -> engine (with refs) -> selections. */
159
+ function classicFlow(overrides = {}, cheeseDefault = false) {
160
+ const setup = makeSetup(overrides);
161
+ const item = (0, halfhalf_setup_helpers_1.convertHalfHalfToItem)(setup, makeStandaloneItems(cheeseDefault));
162
+ const state = (0, order_engine_1.convertCatalogItemToOrderEngineItem)({
163
+ item,
164
+ orderItem: undefined,
165
+ platform: PLATFORM,
166
+ tenantId: TENANT_ID,
167
+ orderItemType: constants_1.ORDER_ITEM_TYPE_ENUM.HALF_HALF,
168
+ defaultMenuId: null,
169
+ soldoutModifiers: [],
170
+ // Same props the drawer receives.
171
+ zeroPriceRefs: setup.exclusive_refs,
172
+ });
173
+ return { setup, state };
174
+ }
175
+ /** Modern: workable setup -> stored selections -> engine (rule applied inside). */
176
+ function modernFlow(overrides = {}, selectedItemIds, chooseExpensive = true, cheeseDefault = false) {
177
+ const setup = makeSetup(overrides);
178
+ const [workable] = (0, halfhalf_setup_helpers_1.convertHalfHalfSetupToWorkableHalfHalfSetup)([setup], makeStandaloneItems(cheeseDefault), PLATFORM, TENANT_ID);
179
+ const selections = selectedItemIds.map((id) => id == null
180
+ ? null
181
+ : (0, order_engine_1.convertItemToOrderItem)(workable.items.find((item) => item._id === id), null, PLATFORM, TENANT_ID));
182
+ const engine = (0, halfhalf_setup_helpers_1.convertHalfHalfToOrderEngineItem)({
183
+ halfHalfItem: workable,
184
+ selectedHalfHalfItems: selections,
185
+ quantity: 1,
186
+ platform: PLATFORM,
187
+ chooseExpensiveSegmentPrice: chooseExpensive,
188
+ });
189
+ return { setup, engine };
190
+ }
191
+ const select = (engine, identifier) => (0, order_engine_1.setCheckFieldInOrderEngineItem)(engine, identifier, true);
192
+ const classicOption = (engine, segId, optionId) => engine.modifiers.find((m) => m._id === segId).options.find((o) => o._id === optionId);
193
+ const classicValue = (engine, segId, optionId) => (0, order_engine_1.getOrderEngineOptionSegmentValue)(classicOption(engine, segId, optionId));
194
+ const modernValue = (engine, segmentIndex) => (0, order_engine_1.getOrderEngineOptionSegmentValue)(engine.modifiers[segmentIndex].options[0]);
195
+ const priceOf = (price) => price?.BASE_PRICE ?? null;
196
+ /**
197
+ * Persisted-style selection for a stored half whose option was changed: the
198
+ * order item's modifiers carry ONLY the selected options (same as
199
+ * `convertOrderEngineItemToOrderItem` writes them).
200
+ */
201
+ function withOnlyOption(orderItem, modifierId, optionId) {
202
+ return {
203
+ ...orderItem,
204
+ modifiers: (orderItem.modifiers ?? []).map((modifier) => modifier._id === modifierId
205
+ ? { ...modifier, options: modifier.options.filter((option) => option._id === optionId) }
206
+ : modifier),
207
+ };
208
+ }
209
+ // ============================================================================
210
+ // 1) STANDALONE — classic vs modern
211
+ // ============================================================================
212
+ describe('standalone half-half — classic vs modern parity', () => {
213
+ it('both flows level the cheaper half to the pricier selected one (raise lands on the priced option)', () => {
214
+ // ---- classic ----
215
+ const { state } = classicFlow();
216
+ let engine = select(state.workingData, 'seg-1_roma');
217
+ engine = select(engine, 'seg-2_milano');
218
+ const classic = (0, order_engine_1.applyChooseExpensiveSegmentPrice)(engine, {
219
+ originalPriceReferences: state.originalPriceReferences,
220
+ });
221
+ expect(classicValue(classic, 'seg-1', 'roma')).toBe(1100); // 500 + 575 raised by 25
222
+ expect(classicValue(classic, 'seg-2', 'milano')).toBe(1100); // 600 + 500 (max)
223
+ expect(classicOption(classic, 'seg-1', 'roma').price).toBe(525); // raise on the option price
224
+ expect(classicOption(classic, 'seg-1', 'roma')
225
+ .modifiers.find((m) => m._id === 'size-mod')
226
+ .options.find((o) => o._id === 'large-13').price).toBe(575); // leaf untouched
227
+ expect(classic.subtotal).toBe(2200);
228
+ // ---- modern ----
229
+ const { engine: modern } = modernFlow({}, ['roma', 'milano']);
230
+ expect(modernValue(modern, 0)).toBe(1100);
231
+ expect(modernValue(modern, 1)).toBe(1100);
232
+ expect(modern.subtotal).toBe(classic.subtotal);
233
+ expect(modern.modifiers[0].options[0].is_free).toBe(false);
234
+ expect(modern.modifiers[1].options[0].is_free).toBe(false);
235
+ });
236
+ it('optional toppings never influence the level and are charged on their own half (both flows)', () => {
237
+ const { state } = classicFlow({}, true);
238
+ let engine = select(state.workingData, 'seg-1_roma');
239
+ engine = select(engine, 'seg-2_milano');
240
+ const classic = (0, order_engine_1.applyChooseExpensiveSegmentPrice)(engine, {
241
+ originalPriceReferences: state.originalPriceReferences,
242
+ });
243
+ expect(classicValue(classic, 'seg-1', 'roma')).toBe(1100);
244
+ expect(classicOption(classic, 'seg-1', 'roma').modifiers.find((m) => m._id === 'extra-mod').options[0].price).toBe(200);
245
+ expect(classic.subtotal).toBe(2400); // 1100 + 200 + 1100
246
+ const { engine: modern } = modernFlow({}, ['roma', 'milano'], true, true);
247
+ expect(modernValue(modern, 0)).toBe(1100);
248
+ expect(modernValue(modern, 1)).toBe(1100);
249
+ expect(modern.modifiers[0].options[0].modifiers.find((m) => m._id === 'extra-mod').options[0].price).toBe(200);
250
+ expect(modern.subtotal).toBe(classic.subtotal);
251
+ });
252
+ it('a single selected half: nothing is charged twice, unselected halves only preview the level (classic)', () => {
253
+ const { state } = classicFlow();
254
+ const engine = select(state.workingData, 'seg-1_roma');
255
+ const classic = (0, order_engine_1.applyChooseExpensiveSegmentPrice)(engine, {
256
+ originalPriceReferences: state.originalPriceReferences,
257
+ });
258
+ expect(classicValue(classic, 'seg-1', 'roma')).toBe(1075);
259
+ // Unselected previews in the EMPTY segment level to it (display only).
260
+ expect(classicValue(classic, 'seg-2', 'torent')).toBe(1075);
261
+ expect(classicValue(classic, 'seg-2', 'milano')).toBe(1100); // already above the level
262
+ expect(classic.subtotal).toBe(1075);
263
+ const { engine: modern } = modernFlow({}, ['roma', null]);
264
+ expect(modernValue(modern, 0)).toBe(1075);
265
+ expect(modern.subtotal).toBe(classic.subtotal);
266
+ });
267
+ it('switching to a cheaper pair re-bases the raised half DOWN (classic) and matches modern', () => {
268
+ const { state } = classicFlow();
269
+ let engine = select(state.workingData, 'seg-1_roma');
270
+ engine = select(engine, 'seg-2_milano');
271
+ engine = (0, order_engine_1.applyChooseExpensiveSegmentPrice)(engine, {
272
+ originalPriceReferences: state.originalPriceReferences,
273
+ });
274
+ expect(classicValue(engine, 'seg-1', 'roma')).toBe(1100);
275
+ // Now switch the second half to the cheap TORENT: ROMA returns to 1075.
276
+ engine = select(engine, 'seg-2_torent');
277
+ const switched = (0, order_engine_1.applyChooseExpensiveSegmentPrice)(engine, {
278
+ originalPriceReferences: state.originalPriceReferences,
279
+ });
280
+ expect(classicValue(switched, 'seg-1', 'roma')).toBe(1075); // re-based down (reversible)
281
+ expect(classicValue(switched, 'seg-2', 'torent')).toBe(1075); // 400 -> 1075
282
+ expect(switched.subtotal).toBe(2150);
283
+ const { engine: modern } = modernFlow({}, ['roma', 'torent']);
284
+ expect(modernValue(modern, 0)).toBe(1075);
285
+ expect(modernValue(modern, 1)).toBe(1075);
286
+ expect(modern.subtotal).toBe(switched.subtotal);
287
+ });
288
+ it('exclusive_refs half: price + reference are 0, is_free stays false, and both flows agree after the rule', () => {
289
+ const overrides = { exclusive_refs: ['milano'] };
290
+ // ---- classic ----
291
+ const { state } = classicFlow(overrides);
292
+ const milano = classicOption(state.workingData, 'seg-2', 'milano');
293
+ expect(milano.price).toBe(0); // price mutated
294
+ expect(state.originalPriceReferences['seg-2_milano']).toBe(0); // reference mutated
295
+ expect(milano.is_free).toBe(false); // never is_free ("Free" tag is num_free_options only)
296
+ let engine = select(state.workingData, 'seg-1_roma');
297
+ engine = select(engine, 'seg-2_milano');
298
+ const classic = (0, order_engine_1.applyChooseExpensiveSegmentPrice)(engine, {
299
+ originalPriceReferences: state.originalPriceReferences,
300
+ });
301
+ // Milano's value is its required leaf (500); the rule levels it to 1075.
302
+ expect(classicValue(classic, 'seg-1', 'roma')).toBe(1075);
303
+ expect(classicValue(classic, 'seg-2', 'milano')).toBe(1075);
304
+ expect(classicOption(classic, 'seg-2', 'milano').price).toBe(0); // option stays 0; raise landed on the leaf
305
+ expect(classic.subtotal).toBe(2150);
306
+ // ---- modern ----
307
+ const { engine: modern } = modernFlow(overrides, ['roma', 'milano']);
308
+ expect(modernValue(modern, 0)).toBe(1075);
309
+ expect(modernValue(modern, 1)).toBe(1075);
310
+ expect(modern.modifiers[1].options[0].is_free).toBe(false);
311
+ expect(modern.subtotal).toBe(classic.subtotal);
312
+ });
313
+ it('a segment holding the expensive pick keeps its siblings at their own prices; the other segment previews the level', () => {
314
+ // Reported from the specials classic drawer: with an expensive First Half
315
+ // picked, the OTHER First Half options showed the incremented price even
316
+ // though they can only REPLACE the pick (you choose the next half from
317
+ // the next segment) — switching re-evaluates the level without it.
318
+ const { state } = classicFlow();
319
+ const engine = select(state.workingData, 'seg-1_roma'); // 1075 (the pick)
320
+ const classic = (0, order_engine_1.applyChooseExpensiveSegmentPrice)(engine, {
321
+ originalPriceReferences: state.originalPriceReferences,
322
+ });
323
+ // First Half (holds the pick): alternatives keep their OWN prices.
324
+ expect(classicValue(classic, 'seg-1', 'torent')).toBe(400);
325
+ expect(classicValue(classic, 'seg-1', 'milano')).toBe(1100); // own (higher)
326
+ // Second Half (empty): previews the level — picking anything there charges
327
+ // the expensive First Half's price (this behavior was confirmed as fine).
328
+ expect(classicValue(classic, 'seg-2', 'torent')).toBe(1075);
329
+ // Charged: only the picks (single pick here).
330
+ expect(classic.subtotal).toBe(1075);
331
+ });
332
+ it('flag off: the modern converter does not level and the classic conversion stays untouched', () => {
333
+ const { state } = classicFlow({ choose_expensive_segment_price: false });
334
+ let engine = select(state.workingData, 'seg-1_roma');
335
+ engine = select(engine, 'seg-2_milano');
336
+ // The drawer would NOT call the rule (flag off) — conversion values stand.
337
+ expect(classicValue(engine, 'seg-1', 'roma')).toBe(1075);
338
+ expect(classicValue(engine, 'seg-2', 'milano')).toBe(1100);
339
+ const { engine: modern } = modernFlow({ choose_expensive_segment_price: false }, ['roma', 'milano'], false);
340
+ expect(modernValue(modern, 0)).toBe(1075);
341
+ expect(modernValue(modern, 1)).toBe(1100);
342
+ expect(modern.subtotal).toBe(2175);
343
+ });
344
+ it('four segments (quarters): all quarters level to the most expensive selected one (both flows)', () => {
345
+ const overrides = {
346
+ segments: [
347
+ { _id: 'q-1', name: 'Quarter 1', sort_id: 1 },
348
+ { _id: 'q-2', name: 'Quarter 2', sort_id: 2 },
349
+ { _id: 'q-3', name: 'Quarter 3', sort_id: 3 },
350
+ { _id: 'q-4', name: 'Quarter 4', sort_id: 4 },
351
+ ],
352
+ };
353
+ const { state } = classicFlow(overrides);
354
+ let engine = select(state.workingData, 'q-1_roma');
355
+ engine = select(engine, 'q-2_milano');
356
+ engine = select(engine, 'q-3_torent');
357
+ engine = select(engine, 'q-4_torent');
358
+ const classic = (0, order_engine_1.applyChooseExpensiveSegmentPrice)(engine, {
359
+ originalPriceReferences: state.originalPriceReferences,
360
+ });
361
+ // quarters: roma 250+287.5, milano 300+250, torent 200 — max 550.
362
+ expect(classicValue(classic, 'q-1', 'roma')).toBe(550);
363
+ expect(classicValue(classic, 'q-2', 'milano')).toBe(550);
364
+ expect(classicValue(classic, 'q-3', 'torent')).toBe(550);
365
+ expect(classicValue(classic, 'q-4', 'torent')).toBe(550);
366
+ expect(classic.subtotal).toBe(2200);
367
+ const { engine: modern } = modernFlow(overrides, ['roma', 'milano', 'torent', 'torent']);
368
+ expect(modernValue(modern, 0)).toBe(550);
369
+ expect(modernValue(modern, 1)).toBe(550);
370
+ expect(modernValue(modern, 2)).toBe(550);
371
+ expect(modernValue(modern, 3)).toBe(550);
372
+ expect(modern.subtotal).toBe(classic.subtotal);
373
+ });
374
+ });
375
+ // ============================================================================
376
+ // 2) USE CASES — change choice / change options / edit round-trips
377
+ // ============================================================================
378
+ describe('use cases — every user action stays aligned with the rule', () => {
379
+ it('changing the pair between cheap and expensive re-raises AND drops the level (classic)', () => {
380
+ const { state } = classicFlow();
381
+ let engine = select(state.workingData, 'seg-1_torent'); // 400
382
+ engine = select(engine, 'seg-2_napoli'); // 450
383
+ engine = (0, order_engine_1.applyChooseExpensiveSegmentPrice)(engine, { originalPriceReferences: state.originalPriceReferences });
384
+ expect(classicValue(engine, 'seg-1', 'torent')).toBe(450);
385
+ expect(classicValue(engine, 'seg-2', 'napoli')).toBe(450);
386
+ expect(engine.subtotal).toBe(900);
387
+ // Upgrade the first half: the level follows the new max (MILANO 1100).
388
+ engine = select(engine, 'seg-1_milano');
389
+ engine = (0, order_engine_1.applyChooseExpensiveSegmentPrice)(engine, { originalPriceReferences: state.originalPriceReferences });
390
+ expect(classicValue(engine, 'seg-1', 'milano')).toBe(1100);
391
+ expect(classicValue(engine, 'seg-2', 'napoli')).toBe(1100);
392
+ expect(engine.subtotal).toBe(2200);
393
+ // Downgrading again drops every re-based price back to the cheap level.
394
+ engine = select(engine, 'seg-1_torent');
395
+ engine = (0, order_engine_1.applyChooseExpensiveSegmentPrice)(engine, { originalPriceReferences: state.originalPriceReferences });
396
+ expect(classicValue(engine, 'seg-1', 'torent')).toBe(450); // 400 re-raised to NAPOLI's 450
397
+ expect(classicValue(engine, 'seg-2', 'napoli')).toBe(450);
398
+ expect(engine.subtotal).toBe(900);
399
+ });
400
+ it('classic: changing the required SIZE of a picked half re-evaluates the level (raise re-lands on the option)', () => {
401
+ const { state } = classicFlow();
402
+ let engine = select(state.workingData, 'seg-1_roma');
403
+ engine = select(engine, 'seg-2_milano');
404
+ engine = (0, order_engine_1.applyChooseExpensiveSegmentPrice)(engine, { originalPriceReferences: state.originalPriceReferences });
405
+ expect(classicValue(engine, 'seg-1', 'roma')).toBe(1100);
406
+ // Change ROMA to Small 11" (500/2 = 250): 500 + 250 = 750 -> MILANO's 1100.
407
+ engine = select(engine, 'seg-1_roma_size-mod_small-11');
408
+ const resized = (0, order_engine_1.applyChooseExpensiveSegmentPrice)(engine, {
409
+ originalPriceReferences: state.originalPriceReferences,
410
+ });
411
+ expect(classicValue(resized, 'seg-1', 'roma')).toBe(1100);
412
+ expect(classicOption(resized, 'seg-1', 'roma').price).toBe(850); // 500 re-based + 350 raise
413
+ expect(classicOption(resized, 'seg-1', 'roma')
414
+ .modifiers.find((m) => m._id === 'size-mod')
415
+ .options.find((o) => o._id === 'large-13').price).toBe(575); // re-based to its definition, not left raised
416
+ expect(resized.subtotal).toBe(2200);
417
+ });
418
+ it('modern: changing the required size of a stored half behaves identically', () => {
419
+ const [workable] = (0, halfhalf_setup_helpers_1.convertHalfHalfSetupToWorkableHalfHalfSetup)([makeSetup()], makeStandaloneItems(), PLATFORM, TENANT_ID);
420
+ const romaSelection = withOnlyOption((0, order_engine_1.convertItemToOrderItem)(workable.items.find((item) => item._id === 'roma'), null, PLATFORM, TENANT_ID), 'size-mod', 'small-11');
421
+ const milanoSelection = (0, order_engine_1.convertItemToOrderItem)(workable.items.find((item) => item._id === 'milano'), null, PLATFORM, TENANT_ID);
422
+ const modern = (0, halfhalf_setup_helpers_1.convertHalfHalfToOrderEngineItem)({
423
+ halfHalfItem: workable,
424
+ selectedHalfHalfItems: [romaSelection, milanoSelection],
425
+ quantity: 1,
426
+ platform: PLATFORM,
427
+ chooseExpensiveSegmentPrice: true,
428
+ });
429
+ expect(modernValue(modern, 0)).toBe(1100);
430
+ expect(modernValue(modern, 1)).toBe(1100);
431
+ expect(modern.subtotal).toBe(2200);
432
+ });
433
+ it('classic cart edit: a persisted, already-leveled line is re-based and produces the same charge (no drift)', () => {
434
+ const { state } = classicFlow();
435
+ let engine = select(state.workingData, 'seg-1_roma');
436
+ engine = select(engine, 'seg-2_milano');
437
+ const first = (0, order_engine_1.applyChooseExpensiveSegmentPrice)(engine, { originalPriceReferences: state.originalPriceReferences });
438
+ // Persist like the cart does (selected options only, leveled prices)...
439
+ const persisted = (0, order_engine_1.convertOrderEngineItemToOrderItem)(first, TENANT_ID);
440
+ // ...and reopen the line for editing.
441
+ const item = (0, halfhalf_setup_helpers_1.convertHalfHalfToItem)(makeSetup(), makeStandaloneItems());
442
+ const editState = (0, order_engine_1.convertCatalogItemToOrderEngineItem)({
443
+ item,
444
+ orderItem: persisted,
445
+ platform: PLATFORM,
446
+ tenantId: TENANT_ID,
447
+ orderItemType: constants_1.ORDER_ITEM_TYPE_ENUM.HALF_HALF,
448
+ defaultMenuId: null,
449
+ soldoutModifiers: [],
450
+ });
451
+ const edited = (0, order_engine_1.applyChooseExpensiveSegmentPrice)(editState.workingData, {
452
+ originalPriceReferences: editState.originalPriceReferences,
453
+ });
454
+ expect(classicValue(edited, 'seg-1', 'roma')).toBe(1100);
455
+ expect(classicValue(edited, 'seg-2', 'milano')).toBe(1100);
456
+ expect(edited.subtotal).toBe(first.subtotal);
457
+ });
458
+ it('modern edit: stored halves carrying already-leveled prices are re-based from the definitions (no drift)', () => {
459
+ const [workable] = (0, halfhalf_setup_helpers_1.convertHalfHalfSetupToWorkableHalfHalfSetup)([makeSetup()], makeStandaloneItems(), PLATFORM, TENANT_ID);
460
+ const romaSelection = (0, order_engine_1.convertItemToOrderItem)(workable.items.find((item) => item._id === 'roma'), null, PLATFORM, TENANT_ID);
461
+ const milanoSelection = (0, order_engine_1.convertItemToOrderItem)(workable.items.find((item) => item._id === 'milano'), null, PLATFORM, TENANT_ID);
462
+ // The stored ROMA half carries a price raised by an earlier normalization
463
+ // (500 -> 525); MILANO is untouched.
464
+ const raisedRoma = { ...romaSelection, price: 525 };
465
+ const modern = (0, halfhalf_setup_helpers_1.convertHalfHalfToOrderEngineItem)({
466
+ halfHalfItem: workable,
467
+ selectedHalfHalfItems: [raisedRoma, milanoSelection],
468
+ quantity: 1,
469
+ platform: PLATFORM,
470
+ chooseExpensiveSegmentPrice: true,
471
+ });
472
+ expect(modernValue(modern, 0)).toBe(1100); // 525 re-based to 500, then levelled
473
+ expect(modernValue(modern, 1)).toBe(1100);
474
+ expect(modern.subtotal).toBe(2200);
475
+ });
476
+ it('segment drawer floor equals what the rule will actually charge for that segment', () => {
477
+ const [workable] = (0, halfhalf_setup_helpers_1.convertHalfHalfSetupToWorkableHalfHalfSetup)([makeSetup()], makeStandaloneItems(), PLATFORM, TENANT_ID);
478
+ const romaSelection = (0, order_engine_1.convertItemToOrderItem)(workable.items.find((item) => item._id === 'roma'), null, PLATFORM, TENANT_ID);
479
+ const torentSelection = (0, order_engine_1.convertItemToOrderItem)(workable.items.find((item) => item._id === 'torent'), null, PLATFORM, TENANT_ID);
480
+ // POS `getOtherSegmentsFloor`: the rule applied with the edited segment
481
+ // EXCLUDED — the max value of the remaining picked halves.
482
+ const othersEngine = (0, halfhalf_setup_helpers_1.convertHalfHalfToOrderEngineItem)({
483
+ halfHalfItem: workable,
484
+ selectedHalfHalfItems: [romaSelection, null],
485
+ quantity: 1,
486
+ platform: PLATFORM,
487
+ chooseExpensiveSegmentPrice: true,
488
+ });
489
+ const floor = (0, order_engine_1.getOrderEngineOptionSegmentValue)(othersEngine.modifiers[0].options[0]);
490
+ expect(floor).toBe(1075);
491
+ // Picking TORENT for the second half charges exactly that floor.
492
+ const fullEngine = (0, halfhalf_setup_helpers_1.convertHalfHalfToOrderEngineItem)({
493
+ halfHalfItem: workable,
494
+ selectedHalfHalfItems: [romaSelection, torentSelection],
495
+ quantity: 1,
496
+ platform: PLATFORM,
497
+ chooseExpensiveSegmentPrice: true,
498
+ });
499
+ expect(modernValue(fullEngine, 1)).toBe(floor);
500
+ });
501
+ });
502
+ // ============================================================================
503
+ // 3) SPECIALS — nested rule (whole special) vs pick-flow drawer rule
504
+ // ============================================================================
505
+ describe('half-half inside a special — nested rule vs pick-flow drawer rule', () => {
506
+ const specialItems = (milanUpsell, torentUpsell) => [
507
+ { item_id: 'milan', sort_id: 1, upsell_price: milanUpsell },
508
+ { item_id: 'torent', sort_id: 2, upsell_price: torentUpsell },
509
+ { item_id: 'halfhalf-1', sort_id: 3, upsell_price: { BASE_PRICE: 100 } },
510
+ ];
511
+ function makeSpecial(milanUpsell, torentUpsell, groupExclusiveRefs) {
512
+ return {
513
+ _id: 'special-1',
514
+ brand_id: 'brand-1',
515
+ tenants: ['tenant-1'],
516
+ category_id: 'combo-cat',
517
+ included_platforms: [PLATFORM],
518
+ name: 'Deal',
519
+ description: '',
520
+ active: true,
521
+ sold_out: [],
522
+ sort_id: 1,
523
+ image_url: '',
524
+ price: { BASE_PRICE: 1500 },
525
+ discount_amount: null,
526
+ is_discount_percentage: false,
527
+ display_price: null,
528
+ show_starting_from: false,
529
+ item_special_hours: null,
530
+ modifier_specials: [
531
+ {
532
+ _id: 'mod-pizza',
533
+ name: 'First Pizza',
534
+ sort_id: 1,
535
+ quantity: 1,
536
+ num_free_items: 0,
537
+ excluded_refs: [],
538
+ exclusive_refs: groupExclusiveRefs,
539
+ omit_items_schedule: false,
540
+ items: specialItems(milanUpsell, torentUpsell),
541
+ },
542
+ ],
543
+ createdAt: new Date('2024-01-01'),
544
+ updatedAt: new Date('2024-01-02'),
545
+ };
546
+ }
547
+ const makeSetupB = (overrides = {}) => makeSetup({
548
+ items: [
549
+ { item_id: 'milan', sort_id: 1, upsell_price: null },
550
+ { item_id: 'torent', sort_id: 2, upsell_price: null },
551
+ ],
552
+ ...overrides,
553
+ });
554
+ const specialItemsMap = () => ({
555
+ milan: makeItem('milan', { modifiers: makePizzaSizeAndExtra() }),
556
+ torent: makeItem('torent', { price: { BASE_PRICE: 1200 } }),
557
+ });
558
+ /** Whole special item -> engine -> select the half-half halves -> nested rule. */
559
+ function nestedFlow(opts = {}) {
560
+ const { milanUpsell = null, torentUpsell = { BASE_PRICE: 200 }, exclusive = [], flag = true } = opts;
561
+ const item = (0, specials_helpers_1.convertSpecialToItem)(makeSpecial(milanUpsell, torentUpsell, exclusive), specialItemsMap(), {
562
+ 'halfhalf-1': makeSetupB({ choose_expensive_segment_price: flag }),
563
+ });
564
+ const state = (0, order_engine_1.convertCatalogItemToOrderEngineItem)({
565
+ item,
566
+ orderItem: undefined,
567
+ platform: PLATFORM,
568
+ tenantId: TENANT_ID,
569
+ orderItemType: constants_1.ORDER_ITEM_TYPE_ENUM.SPECIAL,
570
+ defaultMenuId: null,
571
+ soldoutModifiers: [],
572
+ });
573
+ let engine = select(state.workingData, 'mod-pizza_halfhalf-1_seg-1_milan');
574
+ engine = select(engine, 'mod-pizza_halfhalf-1_seg-2_torent');
575
+ return { state, engine };
576
+ }
577
+ /** Pick flow: half-half OPTION built for the special -> drawer engine -> top-level rule. */
578
+ function pickFlow(opts = {}) {
579
+ const { milanUpsell = null, torentUpsell = { BASE_PRICE: 200 }, exclusive = [], flag = true } = opts;
580
+ const converted = (0, halfhalf_setup_helpers_1.convertHalfHalfToItem)(makeSetupB({ choose_expensive_segment_price: flag }), specialItemsMap(), {
581
+ specialItems: [
582
+ { item_id: 'milan', sort_id: 1, upsell_price: milanUpsell },
583
+ { item_id: 'torent', sort_id: 2, upsell_price: torentUpsell },
584
+ ],
585
+ specialHalfHalfUpsell: { BASE_PRICE: 100 },
586
+ });
587
+ const state = (0, order_engine_1.convertCatalogItemToOrderEngineItem)({
588
+ item: converted,
589
+ orderItem: undefined,
590
+ platform: PLATFORM,
591
+ tenantId: TENANT_ID,
592
+ orderItemType: constants_1.ORDER_ITEM_TYPE_ENUM.HALF_HALF,
593
+ defaultMenuId: null,
594
+ soldoutModifiers: [],
595
+ zeroPriceRefs: exclusive,
596
+ });
597
+ let engine = select(state.workingData, 'seg-1_milan');
598
+ engine = select(engine, 'seg-2_torent');
599
+ return { state, engine };
600
+ }
601
+ const nestedHH = (engine) => engine.modifiers.find((m) => m._id === 'mod-pizza').options.find((o) => o._id === 'halfhalf-1');
602
+ const nestedValue = (engine, segId, optionId) => (0, order_engine_1.getOrderEngineOptionSegmentValue)(nestedHH(engine)
603
+ .modifiers.find((m) => m._id === segId)
604
+ .options.find((o) => o._id === optionId));
605
+ it('both entry points level to the most expensive selected half (0/100 -> 100/100) and keep the special prices untouched', () => {
606
+ // ---- nested rule on the whole special ----
607
+ const { state: nestedState, engine: nestedConverted } = nestedFlow();
608
+ expect((0, order_engine_1.hasFlaggedHalfHalfOption)(nestedConverted)).toBe(true);
609
+ const nested = (0, order_engine_1.applyNestedChooseExpensiveSegmentPrice)(nestedConverted, {
610
+ originalPriceReferences: nestedState.originalPriceReferences,
611
+ });
612
+ expect(nestedValue(nested, 'seg-1', 'milan')).toBe(100);
613
+ expect(nestedValue(nested, 'seg-2', 'torent')).toBe(100);
614
+ // The special's own option prices are never re-based by the nested rule.
615
+ const group = nested.modifiers.find((m) => m._id === 'mod-pizza');
616
+ expect(group.options.find((o) => o._id === 'milan').price).toBe(0);
617
+ expect(group.options.find((o) => o._id === 'torent').price).toBe(200);
618
+ expect(group.options.find((o) => o._id === 'halfhalf-1').price).toBe(100);
619
+ // ---- pick flow (drawer on the half-half option) ----
620
+ const { state: pickState, engine: pickConverted } = pickFlow();
621
+ const pick = (0, order_engine_1.applyChooseExpensiveSegmentPrice)(pickConverted, {
622
+ originalPriceReferences: pickState.originalPriceReferences,
623
+ });
624
+ expect(classicValue(pick, 'seg-1', 'milan')).toBe(100);
625
+ expect(classicValue(pick, 'seg-2', 'torent')).toBe(100);
626
+ expect(pick.price).toBe(100); // the half-half option price (special upsell) stays
627
+ // No Free tag data anywhere: is_free belongs to num_free_options only.
628
+ nestedHH(nested).modifiers.forEach((seg) => seg.options.forEach((o) => expect(o.is_free).toBe(false)));
629
+ pick.modifiers.forEach((seg) => seg.options.forEach((o) => expect(o.is_free).toBe(false)));
630
+ });
631
+ it('flag off: neither entry point levels (nested option is not flagged; the drawer skips)', () => {
632
+ const { state, engine } = nestedFlow({ flag: false });
633
+ expect((0, order_engine_1.hasFlaggedHalfHalfOption)(engine)).toBe(false);
634
+ const nested = (0, order_engine_1.applyNestedChooseExpensiveSegmentPrice)(engine, {
635
+ originalPriceReferences: state.originalPriceReferences,
636
+ });
637
+ expect(nestedValue(nested, 'seg-1', 'milan')).toBe(0);
638
+ expect(nestedValue(nested, 'seg-2', 'torent')).toBe(100);
639
+ const { engine: pickConverted } = pickFlow({ flag: false });
640
+ // The drawer would not run the rule with the flag off; conversion values stand.
641
+ expect(classicValue(pickConverted, 'seg-1', 'milan')).toBe(0);
642
+ expect(classicValue(pickConverted, 'seg-2', 'torent')).toBe(100);
643
+ });
644
+ it('special exclusive_refs zero a segment price (price + reference, never is_free) and both entry points agree', () => {
645
+ const opts = {
646
+ milanUpsell: { BASE_PRICE: 200 },
647
+ torentUpsell: { BASE_PRICE: 200 },
648
+ exclusive: ['torent'],
649
+ };
650
+ // ---- nested: the special's ref rules null TORENT's segment price at conversion ----
651
+ const { state: nestedState, engine: nestedConverted } = nestedFlow(opts);
652
+ expect(nestedState.originalPriceReferences['mod-pizza_halfhalf-1_seg-2_torent']).toBe(0);
653
+ const nested = (0, order_engine_1.applyNestedChooseExpensiveSegmentPrice)(nestedConverted, {
654
+ originalPriceReferences: nestedState.originalPriceReferences,
655
+ });
656
+ expect(nestedValue(nested, 'seg-1', 'milan')).toBe(100);
657
+ expect(nestedValue(nested, 'seg-2', 'torent')).toBe(100); // 0 -> levelled to MILAN's 100
658
+ // ---- pick: the drawer's zeroPriceRefs zero TORENT as well ----
659
+ const { state: pickState, engine: pickConverted } = pickFlow(opts);
660
+ expect(pickState.originalPriceReferences['seg-2_torent']).toBe(0);
661
+ expect(classicValue(pickConverted, 'seg-2', 'torent')).toBe(0); // zeroed at conversion
662
+ const pick = (0, order_engine_1.applyChooseExpensiveSegmentPrice)(pickConverted, {
663
+ originalPriceReferences: pickState.originalPriceReferences,
664
+ });
665
+ expect(classicValue(pick, 'seg-1', 'milan')).toBe(100);
666
+ expect(classicValue(pick, 'seg-2', 'torent')).toBe(100);
667
+ expect(classicOption(pick, 'seg-2', 'torent').is_free).toBe(false);
668
+ });
669
+ it('classic special edit round-trip: reopening the whole special from the cart re-bases and charges the same', () => {
670
+ // The drawer-based classic EDIT: CartItem rebuilds the converted special
671
+ // and reopens it with the persisted line; the nested rule re-bases the
672
+ // flagged half-half subtree from the definition references, so persisted
673
+ // (already-leveled) segment prices can never leak into the display/charge.
674
+ const { state, engine: selected } = nestedFlow();
675
+ const first = (0, order_engine_1.applyNestedChooseExpensiveSegmentPrice)(selected, {
676
+ originalPriceReferences: state.originalPriceReferences,
677
+ });
678
+ // Persist like the cart does (selected options only, leveled segments).
679
+ const persisted = (0, order_engine_1.convertOrderEngineItemToOrderItem)(first, TENANT_ID);
680
+ const item = (0, specials_helpers_1.convertSpecialToItem)(makeSpecial(null, { BASE_PRICE: 200 }, []), specialItemsMap(), {
681
+ 'halfhalf-1': makeSetupB(),
682
+ });
683
+ const editState = (0, order_engine_1.convertCatalogItemToOrderEngineItem)({
684
+ item,
685
+ orderItem: persisted,
686
+ platform: PLATFORM,
687
+ tenantId: TENANT_ID,
688
+ orderItemType: constants_1.ORDER_ITEM_TYPE_ENUM.SPECIAL,
689
+ defaultMenuId: null,
690
+ soldoutModifiers: [],
691
+ });
692
+ const edited = (0, order_engine_1.applyNestedChooseExpensiveSegmentPrice)(editState.workingData, {
693
+ originalPriceReferences: editState.originalPriceReferences,
694
+ });
695
+ expect(nestedValue(edited, 'seg-1', 'milan')).toBe(100);
696
+ expect(nestedValue(edited, 'seg-2', 'torent')).toBe(100);
697
+ expect(edited.subtotal).toBe(first.subtotal);
698
+ // The special's own option prices stay wherever the conversion put them.
699
+ const group = edited.modifiers.find((m) => m._id === 'mod-pizza');
700
+ expect(group.options.find((o) => o._id === 'torent').price).toBe(200);
701
+ });
702
+ });