@managesome/eposmatic-toolkit 0.2.721 → 0.2.733

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,966 @@
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 TENANT_ID = 'tenant-1';
7
+ const PLATFORM = constants_1.PLATFORMS_ENUM.POS_WALK_IN;
8
+ // ============================================================================
9
+ // Engine-item fixtures
10
+ // ============================================================================
11
+ function makeEngineOption(overrides = {}) {
12
+ return {
13
+ _id: 'opt-1',
14
+ ref: 'opt-1',
15
+ name: 'Option',
16
+ active: true,
17
+ sold_out: [],
18
+ sort_id: 1,
19
+ excluded_platforms: [],
20
+ default: false,
21
+ price: 0,
22
+ quantity: 1,
23
+ modifiers: [],
24
+ is_free: false,
25
+ loyalty_applied: false,
26
+ voucher_applied: false,
27
+ ...overrides,
28
+ };
29
+ }
30
+ function makeEngineModifier(overrides = {}) {
31
+ return {
32
+ _id: 'mod-1',
33
+ ref: 'mod-1',
34
+ name: 'Modifier',
35
+ description: '',
36
+ active: true,
37
+ sold_out: [],
38
+ sort_id: 1,
39
+ min_num_options: 1,
40
+ max_num_options: 1,
41
+ depth: 0,
42
+ default: false,
43
+ options: [],
44
+ ...overrides,
45
+ };
46
+ }
47
+ function makeEngineItem(overrides = {}) {
48
+ return {
49
+ _id: 'item-1',
50
+ category_id: 'cat-1',
51
+ item_id: 'item-ref-1',
52
+ menu_id: 'menu-1',
53
+ item_type: constants_1.ORDER_ITEM_TYPE_ENUM.HALF_HALF,
54
+ name: 'Item',
55
+ description: '',
56
+ loyalty_applied: false,
57
+ voucher_applied: false,
58
+ price: 0,
59
+ gross_total: 0,
60
+ subtotal: 0,
61
+ tax_rate: 0,
62
+ quantity: 1,
63
+ image_url: '',
64
+ special_instructions: '',
65
+ item_discount_details: null,
66
+ modifiers: [],
67
+ ...overrides,
68
+ };
69
+ }
70
+ // ============================================================================
71
+ // Classic flow — selection matrix (A/B = 500, C/D = 600 per segment)
72
+ // ============================================================================
73
+ const SEGMENT_VALUES = { a: 500, b: 500, c: 600, d: 600 };
74
+ const MATRIX_REFS = {
75
+ 'seg-1_a': 500,
76
+ 'seg-1_b': 500,
77
+ 'seg-1_c': 600,
78
+ 'seg-1_d': 600,
79
+ 'seg-2_a': 500,
80
+ 'seg-2_b': 500,
81
+ 'seg-2_c': 600,
82
+ 'seg-2_d': 600,
83
+ };
84
+ function makeMatrixSegment(segmentId, selection) {
85
+ return makeEngineModifier({
86
+ _id: segmentId,
87
+ name: segmentId,
88
+ depth: 0,
89
+ default: selection != null,
90
+ options: ['a', 'b', 'c', 'd'].map((optionId) => makeEngineOption({
91
+ _id: optionId,
92
+ ref: optionId,
93
+ price: SEGMENT_VALUES[optionId],
94
+ default: selection === optionId,
95
+ })),
96
+ });
97
+ }
98
+ function makeMatrixItem(seg1, seg2) {
99
+ return makeEngineItem({
100
+ modifiers: [makeMatrixSegment('seg-1', seg1), makeMatrixSegment('seg-2', seg2)],
101
+ });
102
+ }
103
+ const priceOf = (engine, segmentId, optionId) => engine.modifiers.find((m) => m._id === segmentId).options.find((o) => o._id === optionId).price;
104
+ describe('choose_expensive_segment_price — selection matrix (25 combinations)', () => {
105
+ it('every non-free option ends at max(own value, the OTHER segment’s selected value) — the level its own pick would charge; charged = level x selected count', () => {
106
+ const choices = [null, 'a', 'b', 'c', 'd'];
107
+ const mismatches = [];
108
+ choices.forEach((seg1) => {
109
+ choices.forEach((seg2) => {
110
+ const result = (0, order_engine_1.applyChooseExpensiveSegmentPrice)(makeMatrixItem(seg1, seg2), {
111
+ originalPriceReferences: MATRIX_REFS,
112
+ });
113
+ const selected = [seg1, seg2].filter((id) => id != null);
114
+ const maxSelected = selected.length > 0 ? Math.max(...selected.map((id) => SEGMENT_VALUES[id])) : 0;
115
+ // Every option is displayed at the level its OWN pick would charge:
116
+ // max(own value, the OTHER segment's selected value). A segment that
117
+ // holds a pick never inflates its own siblings — choosing a sibling
118
+ // REPLACES the current pick, re-evaluating the level without it.
119
+ const selectedBySegment = { 'seg-1': seg1, 'seg-2': seg2 };
120
+ result.modifiers.forEach((segment) => {
121
+ const otherSegmentsMax = Math.max(...Object.entries(selectedBySegment)
122
+ .filter(([id]) => id !== segment._id)
123
+ .map(([, id]) => (id != null ? SEGMENT_VALUES[id] : 0)), 0);
124
+ segment.options.forEach((option) => {
125
+ const own = SEGMENT_VALUES[option._id];
126
+ const expected = Math.max(own, otherSegmentsMax);
127
+ if (option.price !== expected) {
128
+ mismatches.push(`${seg1}+${seg2} ${segment._id}_${option._id}: got ${option.price}, expected ${expected}`);
129
+ }
130
+ });
131
+ });
132
+ const expectedSubtotal = maxSelected * selected.length;
133
+ if (result.subtotal !== expectedSubtotal) {
134
+ mismatches.push(`${seg1}+${seg2} subtotal: got ${result.subtotal}, expected ${expectedSubtotal}`);
135
+ }
136
+ });
137
+ });
138
+ expect(mismatches).toEqual([]);
139
+ });
140
+ });
141
+ describe('choose_expensive_segment_price — classic edge cases', () => {
142
+ it('with no selection: re-bases to definition prices, no levelling, no throw', () => {
143
+ const base = makeMatrixItem(null, null);
144
+ // Simulate a previously levelled item whose selections were cleared.
145
+ const levelled = {
146
+ ...base,
147
+ modifiers: base.modifiers.map((modifier) => ({
148
+ ...modifier,
149
+ default: false,
150
+ options: modifier.options.map((option) => ({ ...option, price: 600 })),
151
+ })),
152
+ };
153
+ const result = (0, order_engine_1.applyChooseExpensiveSegmentPrice)(levelled, { originalPriceReferences: MATRIX_REFS });
154
+ expect(result.modifiers[0].options.map((o) => o.price)).toEqual([500, 500, 600, 600]);
155
+ expect(result.modifiers[1].options.map((o) => o.price)).toEqual([500, 500, 600, 600]);
156
+ });
157
+ it('a single selected segment levels the OTHER segment to it', () => {
158
+ const result = (0, order_engine_1.applyChooseExpensiveSegmentPrice)(makeMatrixItem('c', null), {
159
+ originalPriceReferences: MATRIX_REFS,
160
+ });
161
+ expect(result.modifiers[1].options.every((o) => o.price === 600)).toBe(true);
162
+ });
163
+ it('is_free options never drive the max and are never raised', () => {
164
+ const item = makeEngineItem({
165
+ modifiers: [
166
+ makeEngineModifier({
167
+ _id: 'seg-1',
168
+ depth: 0,
169
+ default: true,
170
+ options: [
171
+ makeEngineOption({ _id: 'free', price: 900, is_free: true, default: true }),
172
+ makeEngineOption({ _id: 'cheap', price: 100 }),
173
+ ],
174
+ }),
175
+ makeEngineModifier({
176
+ _id: 'seg-2',
177
+ depth: 0,
178
+ default: true,
179
+ options: [makeEngineOption({ _id: 'x', price: 300, default: true })],
180
+ }),
181
+ ],
182
+ });
183
+ const result = (0, order_engine_1.applyChooseExpensiveSegmentPrice)(item, {
184
+ originalPriceReferences: { 'seg-1_free': 900, 'seg-1_cheap': 100, 'seg-2_x': 300 },
185
+ });
186
+ // The expensive free option must not inflate the level...
187
+ expect(priceOf(result, 'seg-2', 'x')).toBe(300);
188
+ expect(priceOf(result, 'seg-1', 'cheap')).toBe(300);
189
+ // ...and the free option keeps its own price (never raised).
190
+ expect(priceOf(result, 'seg-1', 'free')).toBe(900);
191
+ });
192
+ it('a zero-priced (exclusive_refs) half is levelled like any other option — only is_free options are excluded', () => {
193
+ // As produced by conversion for `zeroPriceRefs` / `exclusive_refs` options:
194
+ // the PRICE is mutated to 0 and NO `is_free` is set — the "Free" tag
195
+ // belongs exclusively to `num_free_options` options. The rule then treats
196
+ // the half like any other option (exclusive refs never alter the rule).
197
+ const item = makeEngineItem({
198
+ modifiers: [
199
+ makeEngineModifier({
200
+ _id: 'seg-1',
201
+ depth: 0,
202
+ default: true,
203
+ options: [
204
+ makeEngineOption({ _id: 'free-item', price: 0, default: true }),
205
+ makeEngineOption({ _id: 'paid-item', price: 500 }),
206
+ ],
207
+ }),
208
+ makeEngineModifier({
209
+ _id: 'seg-2',
210
+ depth: 0,
211
+ default: true,
212
+ options: [makeEngineOption({ _id: 'x', price: 600, default: true })],
213
+ }),
214
+ ],
215
+ });
216
+ const result = (0, order_engine_1.applyChooseExpensiveSegmentPrice)(item, {
217
+ originalPriceReferences: { 'seg-1_free-item': 0, 'seg-1_paid-item': 500, 'seg-2_x': 600 },
218
+ });
219
+ // The zero-priced half is the cheaper selected one: it is levelled to the
220
+ // max like any other option.
221
+ expect(priceOf(result, 'seg-1', 'free-item')).toBe(600);
222
+ expect(priceOf(result, 'seg-2', 'x')).toBe(600);
223
+ expect(priceOf(result, 'seg-1', 'paid-item')).toBe(600);
224
+ });
225
+ it('optional modifier groups do not influence the level and keep their prices', () => {
226
+ const roma = makeEngineOption({
227
+ _id: 'roma',
228
+ ref: 'roma',
229
+ default: true,
230
+ price: 0,
231
+ modifiers: [
232
+ makeEngineModifier({
233
+ _id: 'size-roma',
234
+ options: [makeEngineOption({ _id: 'l13-roma', price: 575, default: true })],
235
+ }),
236
+ makeEngineModifier({
237
+ _id: 'extra-roma',
238
+ min_num_options: 0,
239
+ max_num_options: 1,
240
+ options: [makeEngineOption({ _id: 'cheese', price: 50, default: true })],
241
+ }),
242
+ ],
243
+ });
244
+ const milano = makeEngineOption({
245
+ _id: 'milano',
246
+ ref: 'milano',
247
+ default: true,
248
+ price: 0,
249
+ modifiers: [
250
+ makeEngineModifier({
251
+ _id: 'size-milano',
252
+ options: [makeEngineOption({ _id: 'l13-milano', price: 500, default: true })],
253
+ }),
254
+ ],
255
+ });
256
+ const item = makeEngineItem({
257
+ modifiers: [
258
+ makeEngineModifier({ _id: 'seg-1', depth: 0, default: true, options: [roma] }),
259
+ makeEngineModifier({ _id: 'seg-2', depth: 0, default: true, options: [milano] }),
260
+ ],
261
+ });
262
+ const result = (0, order_engine_1.applyChooseExpensiveSegmentPrice)(item, {
263
+ originalPriceReferences: {
264
+ 'seg-1_roma': 0,
265
+ 'seg-1_roma_size-roma_l13-roma': 575,
266
+ 'seg-1_roma_extra-roma_cheese': 50,
267
+ 'seg-2_milano': 0,
268
+ 'seg-2_milano_size-milano_l13-milano': 500,
269
+ },
270
+ });
271
+ // Milano is levelled to ROMA's REQUIRED value (575), not to 575+50.
272
+ expect(priceOf(result, 'seg-2', 'milano')).toBe(0);
273
+ expect(result.modifiers[1].options[0].modifiers[0].options[0].price).toBe(575);
274
+ // The optional extra is untouched (adds on top of the charge).
275
+ expect(result.modifiers[0].options[0].modifiers[1].options[0].price).toBe(50);
276
+ });
277
+ it('user example: 575 half + optional topping 100 vs 500 half -> the 500 half becomes 575, topping untouched', () => {
278
+ const tikka = makeEngineOption({
279
+ _id: 'tikka',
280
+ ref: 'tikka',
281
+ default: true,
282
+ price: 575,
283
+ modifiers: [
284
+ makeEngineModifier({
285
+ _id: 'toppings',
286
+ min_num_options: 0,
287
+ max_num_options: 3,
288
+ default: true,
289
+ options: [makeEngineOption({ _id: 'extra-topping', price: 100, default: true })],
290
+ }),
291
+ ],
292
+ });
293
+ const other = makeEngineOption({ _id: 'other', ref: 'other', default: true, price: 500 });
294
+ const item = makeEngineItem({
295
+ modifiers: [
296
+ makeEngineModifier({ _id: 'seg-1', depth: 0, default: true, options: [tikka] }),
297
+ makeEngineModifier({ _id: 'seg-2', depth: 0, default: true, options: [other] }),
298
+ ],
299
+ });
300
+ const result = (0, order_engine_1.applyChooseExpensiveSegmentPrice)(item, {
301
+ originalPriceReferences: {
302
+ 'seg-1_tikka': 575,
303
+ 'seg-1_tikka_toppings_extra-topping': 100,
304
+ 'seg-2_other': 500,
305
+ },
306
+ });
307
+ // The second half becomes 575 — the topping price is NOT added on top of it.
308
+ expect(priceOf(result, 'seg-2', 'other')).toBe(575);
309
+ // The first half keeps its own price + its topping (charged separately).
310
+ expect(priceOf(result, 'seg-1', 'tikka')).toBe(575);
311
+ expect(result.modifiers[0].options[0].modifiers[0].options[0].price).toBe(100);
312
+ // Charged: (575 + 100 topping) + 575
313
+ expect(result.subtotal).toBe(1250);
314
+ });
315
+ it('a multi-option required group contributes ONLY the selected option (unselected siblings excluded)', () => {
316
+ const roma = makeEngineOption({
317
+ _id: 'roma',
318
+ default: true,
319
+ price: 0,
320
+ modifiers: [
321
+ makeEngineModifier({
322
+ _id: 'size',
323
+ options: [
324
+ makeEngineOption({
325
+ _id: 'sm',
326
+ price: 300,
327
+ default: true,
328
+ modifiers: [
329
+ makeEngineModifier({
330
+ _id: 'crust',
331
+ options: [makeEngineOption({ _id: 'thin', price: 100, default: true })],
332
+ }),
333
+ ],
334
+ }),
335
+ makeEngineOption({
336
+ _id: 'lg',
337
+ price: 1150,
338
+ modifiers: [
339
+ makeEngineModifier({
340
+ _id: 'crust-lg',
341
+ options: [makeEngineOption({ _id: 'pan', price: 999, default: true })],
342
+ }),
343
+ ],
344
+ }),
345
+ ],
346
+ }),
347
+ ],
348
+ });
349
+ // Selected small (300) + its selected required crust (100); the unselected
350
+ // large sibling (1150) and its nested crust (999) never count.
351
+ expect((0, order_engine_1.getOrderEngineOptionSegmentValue)(roma)).toBe(400);
352
+ });
353
+ it('never mutates the caller-provided price references', () => {
354
+ const references = { ...MATRIX_REFS };
355
+ const snapshot = JSON.stringify(references);
356
+ (0, order_engine_1.applyChooseExpensiveSegmentPrice)(makeMatrixItem('b', 'c'), { originalPriceReferences: references });
357
+ expect(JSON.stringify(references)).toBe(snapshot);
358
+ });
359
+ it('a missing reference key leaves that option at its current price (documented contract)', () => {
360
+ const references = { ...MATRIX_REFS };
361
+ delete references['seg-1_b'];
362
+ const base = makeMatrixItem('b', 'c');
363
+ // Persisted, previously levelled price for B — its reference is missing.
364
+ const persisted = {
365
+ ...base,
366
+ modifiers: base.modifiers.map((modifier) => ({
367
+ ...modifier,
368
+ options: modifier.options.map((option) => (option._id === 'b' ? { ...option, price: 900 } : option)),
369
+ })),
370
+ };
371
+ const result = (0, order_engine_1.applyChooseExpensiveSegmentPrice)(persisted, { originalPriceReferences: references });
372
+ // Without a reference the current price is the baseline: 900 becomes the
373
+ // level instead of the definition 500.
374
+ expect(priceOf(result, 'seg-1', 'b')).toBe(900);
375
+ expect(priceOf(result, 'seg-2', 'c')).toBe(900);
376
+ // Seg-1's sibling switches to the OTHER segment's level (C = 600): the
377
+ // bogus 900 pick never inflates its own segment's alternatives.
378
+ expect(priceOf(result, 'seg-1', 'a')).toBe(600);
379
+ });
380
+ it('item quantity scales the charged subtotal, not the unit prices', () => {
381
+ const item = makeMatrixItem('a', 'b');
382
+ const result = (0, order_engine_1.applyChooseExpensiveSegmentPrice)({ ...item, quantity: 2 }, { originalPriceReferences: MATRIX_REFS });
383
+ expect(priceOf(result, 'seg-1', 'a')).toBe(500);
384
+ expect(priceOf(result, 'seg-2', 'b')).toBe(500);
385
+ // (0 item price + 500 + 500) x 2
386
+ expect(result.subtotal).toBe(2000);
387
+ });
388
+ it('with fewer than 2 segment groups the prices are only re-based (no levelling)', () => {
389
+ const single = makeEngineItem({
390
+ modifiers: [
391
+ makeEngineModifier({
392
+ _id: 'seg-1',
393
+ depth: 0,
394
+ default: true,
395
+ options: [makeEngineOption({ _id: 'a', price: 700, default: true })],
396
+ }),
397
+ ],
398
+ });
399
+ const result = (0, order_engine_1.applyChooseExpensiveSegmentPrice)(single, {
400
+ originalPriceReferences: { 'seg-1_a': 500 },
401
+ });
402
+ expect(priceOf(result, 'seg-1', 'a')).toBe(500);
403
+ });
404
+ it('the engine subtotal skips free options (is_free means not charged — parity with the cart math)', () => {
405
+ const item = makeEngineItem({
406
+ modifiers: [
407
+ makeEngineModifier({
408
+ _id: 'mod',
409
+ depth: 0,
410
+ default: true,
411
+ options: [
412
+ makeEngineOption({ _id: 'free', price: 200, is_free: true, default: true }),
413
+ makeEngineOption({ _id: 'paid', price: 300, default: true }),
414
+ ],
415
+ }),
416
+ ],
417
+ });
418
+ // Only the paid option is charged — the engine preview now matches the cart
419
+ // math (`calculateItemModifiersPrice` skips is_free). Free options keep
420
+ // their price for reference but never count. Note: the CART already
421
+ // recomputes discounts from its own base, so this was display-only.
422
+ expect((0, order_engine_1.syncOrderEngineItem)(item).subtotal).toBe(300);
423
+ });
424
+ it('classic conversion: zeroPriceRefs (exclusive_refs) mutate price + reference to 0; is_free stays false', () => {
425
+ const itemsMap = {
426
+ a: makeCatalogItem('a', { price: { BASE_PRICE: 1000 } }),
427
+ b: makeCatalogItem('b', { price: { BASE_PRICE: 1000 } }),
428
+ c: makeCatalogItem('c', { price: { BASE_PRICE: 1200 } }),
429
+ d: makeCatalogItem('d', { price: { BASE_PRICE: 1200 } }),
430
+ };
431
+ const setup = {
432
+ _id: 'halfhalf-1',
433
+ brand_id: 'brand-1',
434
+ tenants: [TENANT_ID],
435
+ category_id: 'pizza-cat',
436
+ included_platforms: [PLATFORM],
437
+ name: 'Half/Half Pizza',
438
+ description: '',
439
+ active: true,
440
+ sold_out: [],
441
+ image_url: '',
442
+ upsell_price: null,
443
+ discount_amount: null,
444
+ is_discount_percentage: false,
445
+ choose_expensive_segment_price: true,
446
+ segments: [
447
+ { _id: 'seg-1', name: 'First Half', sort_id: 1 },
448
+ { _id: 'seg-2', name: 'Second Half', sort_id: 2 },
449
+ ],
450
+ items: [
451
+ { item_id: 'a', sort_id: 1, upsell_price: null },
452
+ { item_id: 'b', sort_id: 2, upsell_price: null },
453
+ { item_id: 'c', sort_id: 3, upsell_price: null },
454
+ { item_id: 'd', sort_id: 4, upsell_price: null },
455
+ ],
456
+ exclusive_refs: ['c'],
457
+ excluded_refs: [],
458
+ item_special_hours: null,
459
+ createdAt: new Date('2024-01-01'),
460
+ updatedAt: new Date('2024-01-02'),
461
+ };
462
+ const item = (0, halfhalf_setup_helpers_1.convertHalfHalfToItem)(setup, itemsMap);
463
+ const state = (0, order_engine_1.convertCatalogItemToOrderEngineItem)({
464
+ item,
465
+ orderItem: undefined,
466
+ platform: PLATFORM,
467
+ tenantId: TENANT_ID,
468
+ orderItemType: constants_1.ORDER_ITEM_TYPE_ENUM.HALF_HALF,
469
+ defaultMenuId: null,
470
+ soldoutModifiers: [],
471
+ zeroPriceRefs: setup.exclusive_refs,
472
+ });
473
+ // The exclusive half only has its PRICE (and its price reference) mutated
474
+ // to 0 — never `is_free` (the "Free" tag is produced only by
475
+ // `num_free_options`).
476
+ const exclusive = state.workingData.modifiers[0].options.find((o) => o._id === 'c');
477
+ expect(exclusive.price).toBe(0);
478
+ expect(exclusive.is_free).toBeFalsy();
479
+ expect(state.originalPriceReferences['seg-1_c']).toBe(0);
480
+ let engine = state.workingData;
481
+ engine = (0, order_engine_1.setCheckFieldInOrderEngineItem)(engine, 'seg-1_b', true);
482
+ engine = (0, order_engine_1.setCheckFieldInOrderEngineItem)(engine, 'seg-2_c', true);
483
+ const result = (0, order_engine_1.applyChooseExpensiveSegmentPrice)(engine, {
484
+ originalPriceReferences: state.originalPriceReferences,
485
+ });
486
+ // The rule treats the zero-priced half like any other option: as the
487
+ // cheaper selected half it is levelled to B's price; B keeps its own.
488
+ expect(priceOf(result, 'seg-2', 'c')).toBe(500);
489
+ expect(priceOf(result, 'seg-1', 'b')).toBe(500);
490
+ // Charged: B (500) + C (levelled to 500).
491
+ expect(result.subtotal).toBe(1000);
492
+ });
493
+ });
494
+ // ============================================================================
495
+ // Nested half-half inside a special — edge cases
496
+ // ============================================================================
497
+ describe('applyNestedChooseExpensiveSegmentPrice — edge cases', () => {
498
+ function makeSpecialItem(hhSelections) {
499
+ const halfHalfOption = makeEngineOption({
500
+ _id: 'hh',
501
+ ref: 'hh',
502
+ ref_type: constants_1.MODIFIER_OPTION_REF_TYPE_ENUM.HALF_HALF,
503
+ choose_expensive_segment_price: true,
504
+ default: true,
505
+ price: 0,
506
+ modifiers: [makeMatrixSegment('seg-1', hhSelections.seg1), makeMatrixSegment('seg-2', hhSelections.seg2)],
507
+ });
508
+ return makeEngineItem({
509
+ item_type: constants_1.ORDER_ITEM_TYPE_ENUM.SPECIAL,
510
+ modifiers: [
511
+ makeEngineModifier({
512
+ _id: 'mod-pizza',
513
+ depth: 0,
514
+ default: true,
515
+ options: [makeEngineOption({ _id: 'plain', price: 999 }), halfHalfOption],
516
+ }),
517
+ ],
518
+ });
519
+ }
520
+ const nestedRefs = () => ({
521
+ 'mod-pizza_plain': 111,
522
+ 'mod-pizza_hh_seg-1_a': 500,
523
+ 'mod-pizza_hh_seg-1_b': 500,
524
+ 'mod-pizza_hh_seg-1_c': 600,
525
+ 'mod-pizza_hh_seg-1_d': 600,
526
+ 'mod-pizza_hh_seg-2_a': 500,
527
+ 'mod-pizza_hh_seg-2_b': 500,
528
+ 'mod-pizza_hh_seg-2_c': 600,
529
+ 'mod-pizza_hh_seg-2_d': 600,
530
+ });
531
+ const hhPrice = (engine, segmentId, optionId) => {
532
+ const hh = engine.modifiers[0].options.find((o) => o._id === 'hh');
533
+ return hh.modifiers.find((m) => m._id === segmentId).options.find((o) => o._id === optionId).price;
534
+ };
535
+ it('with no selection: the flagged subtree is re-based, prices outside it are never touched', () => {
536
+ const base = makeSpecialItem({ seg1: null, seg2: null });
537
+ // Previously levelled subtree + a plain option price that differs from its reference.
538
+ const persisted = {
539
+ ...base,
540
+ modifiers: base.modifiers.map((modifier) => ({
541
+ ...modifier,
542
+ options: modifier.options.map((option) => option._id === 'hh'
543
+ ? {
544
+ ...option,
545
+ modifiers: option.modifiers.map((segment) => ({
546
+ ...segment,
547
+ options: segment.options.map((o) => ({ ...o, price: 600 })),
548
+ })),
549
+ }
550
+ : { ...option, price: 999 }),
551
+ })),
552
+ };
553
+ const result = (0, order_engine_1.applyNestedChooseExpensiveSegmentPrice)(persisted, {
554
+ originalPriceReferences: nestedRefs(),
555
+ });
556
+ // Outside the flagged subtree: NOT re-based (999 stays, not 111).
557
+ expect(result.modifiers[0].options.find((o) => o._id === 'plain').price).toBe(999);
558
+ // Inside: back to definition prices (no selection -> no levelling).
559
+ ['a', 'b', 'c', 'd'].forEach((optionId) => {
560
+ expect(hhPrice(result, 'seg-1', optionId)).toBe(MATRIX_REFS[`seg-1_${optionId}`]);
561
+ expect(hhPrice(result, 'seg-2', optionId)).toBe(MATRIX_REFS[`seg-2_${optionId}`]);
562
+ });
563
+ });
564
+ it('two flagged half-half options normalize independently', () => {
565
+ const base = makeSpecialItem({ seg1: null, seg2: null });
566
+ const options = base.modifiers[0].options;
567
+ const plain = options.find((o) => o._id === 'plain');
568
+ const hh = options.find((o) => o._id === 'hh');
569
+ const item = makeEngineItem({
570
+ item_type: constants_1.ORDER_ITEM_TYPE_ENUM.SPECIAL,
571
+ modifiers: [
572
+ makeEngineModifier({
573
+ _id: 'mod-pizza',
574
+ depth: 0,
575
+ default: true,
576
+ options: [
577
+ plain,
578
+ hh,
579
+ makeEngineOption({
580
+ ...hh,
581
+ _id: 'hh2',
582
+ ref: 'hh2',
583
+ modifiers: [makeMatrixSegment('seg-1', 'a'), makeMatrixSegment('seg-2', 'b')],
584
+ }),
585
+ ],
586
+ }),
587
+ ],
588
+ });
589
+ const result = (0, order_engine_1.applyNestedChooseExpensiveSegmentPrice)(item, {
590
+ originalPriceReferences: {
591
+ ...nestedRefs(),
592
+ 'mod-pizza_hh2_seg-1_a': 500,
593
+ 'mod-pizza_hh2_seg-1_b': 500,
594
+ 'mod-pizza_hh2_seg-1_c': 600,
595
+ 'mod-pizza_hh2_seg-1_d': 600,
596
+ 'mod-pizza_hh2_seg-2_a': 500,
597
+ 'mod-pizza_hh2_seg-2_b': 500,
598
+ 'mod-pizza_hh2_seg-2_c': 600,
599
+ 'mod-pizza_hh2_seg-2_d': 600,
600
+ },
601
+ });
602
+ const hh2 = result.modifiers[0].options.find((o) => o._id === 'hh2');
603
+ const hh2Price = (segmentId, optionId) => hh2.modifiers.find((m) => m._id === segmentId).options.find((o) => o._id === optionId).price;
604
+ // hh has no selection -> stays at definition prices, no levelling.
605
+ expect(hhPrice(result, 'seg-1', 'a')).toBe(500);
606
+ // hh2 (selected a+b, cheap pair) -> 500s, expensive options untouched.
607
+ expect(hh2Price('seg-1', 'a')).toBe(500);
608
+ expect(hh2Price('seg-2', 'b')).toBe(500);
609
+ expect(hh2Price('seg-1', 'c')).toBe(600);
610
+ });
611
+ it('missing nested references keep the current subtree prices (no crash)', () => {
612
+ const base = makeSpecialItem({ seg1: 'a', seg2: 'b' });
613
+ const withBogus = {
614
+ ...base,
615
+ modifiers: base.modifiers.map((modifier) => ({
616
+ ...modifier,
617
+ options: modifier.options.map((option) => option._id === 'hh'
618
+ ? {
619
+ ...option,
620
+ modifiers: option.modifiers.map((segment) => ({
621
+ ...segment,
622
+ options: segment.options.map((o) => (o._id === 'a' ? { ...o, price: 700 } : o)),
623
+ })),
624
+ }
625
+ : option),
626
+ })),
627
+ };
628
+ const references = nestedRefs();
629
+ delete references['mod-pizza_hh_seg-1_a'];
630
+ delete references['mod-pizza_hh_seg-2_a'];
631
+ const result = (0, order_engine_1.applyNestedChooseExpensiveSegmentPrice)(withBogus, { originalPriceReferences: references });
632
+ // 'a' keeps the (bogus) current price -> the CHARGED picks follow it.
633
+ expect(hhPrice(result, 'seg-1', 'a')).toBe(700);
634
+ expect(hhPrice(result, 'seg-2', 'b')).toBe(700);
635
+ // Seg-1's sibling switches to max(own 500, the other segment's 500) — the
636
+ // bogus 700 pick never inflates its own segment's alternatives.
637
+ expect(hhPrice(result, 'seg-1', 'b')).toBe(500);
638
+ });
639
+ });
640
+ // ============================================================================
641
+ // applySegmentPriceFloor — edge cases
642
+ // ============================================================================
643
+ describe('applySegmentPriceFloor — edge cases', () => {
644
+ const makeSizeAndExtraItem = () => makeEngineItem({
645
+ modifiers: [
646
+ makeEngineModifier({
647
+ _id: 'size',
648
+ default: true,
649
+ options: [makeEngineOption({ _id: 'l13', price: 400, default: true })],
650
+ }),
651
+ makeEngineModifier({
652
+ _id: 'extra',
653
+ min_num_options: 0,
654
+ max_num_options: 1,
655
+ default: true,
656
+ options: [makeEngineOption({ _id: 'cheese', price: 100, default: true })],
657
+ }),
658
+ ],
659
+ });
660
+ it('raises only the required part — optional selections stay and add on top', () => {
661
+ const levelled = (0, order_engine_1.applySegmentPriceFloor)(makeSizeAndExtraItem(), 575);
662
+ expect(levelled.modifiers[0].options[0].price).toBe(575);
663
+ expect(levelled.modifiers[1].options[0].price).toBe(100);
664
+ // required 575 + optional 100
665
+ expect(levelled.subtotal).toBe(675);
666
+ });
667
+ it('scales the subtotal with the item quantity, unit prices stay levelled', () => {
668
+ const levelled = (0, order_engine_1.applySegmentPriceFloor)({ ...makeSizeAndExtraItem(), quantity: 2 }, 575);
669
+ expect(levelled.modifiers[0].options[0].price).toBe(575);
670
+ expect(levelled.subtotal).toBe(1350);
671
+ });
672
+ it('raises the item price when it carries a price, leaving required leaves alone', () => {
673
+ const item = makeEngineItem({
674
+ price: 400,
675
+ modifiers: [
676
+ makeEngineModifier({
677
+ _id: 'size',
678
+ default: true,
679
+ options: [makeEngineOption({ _id: 'leaf', price: 100, default: true })],
680
+ }),
681
+ ],
682
+ });
683
+ const levelled = (0, order_engine_1.applySegmentPriceFloor)(item, 575);
684
+ // value 400 + 100 = 500 -> delta 75 goes on the item price (first priced element)
685
+ expect(levelled.price).toBe(475);
686
+ expect(levelled.modifiers[0].options[0].price).toBe(100);
687
+ expect(levelled.subtotal).toBe(575);
688
+ });
689
+ });
690
+ // ============================================================================
691
+ // Modern flow converter — documented behaviour (extras vs the classic rule)
692
+ // ============================================================================
693
+ function makeCatalogOption(id, overrides = {}) {
694
+ return {
695
+ _id: id,
696
+ ref: id,
697
+ name: `Option ${id}`,
698
+ active: true,
699
+ sold_out: [],
700
+ sort_id: 1,
701
+ excluded_platforms: [],
702
+ price: null,
703
+ modifiers: null,
704
+ ...overrides,
705
+ };
706
+ }
707
+ function makeCatalogModifier(id, options, overrides = {}) {
708
+ return {
709
+ _id: id,
710
+ ref: id,
711
+ name: `Modifier ${id}`,
712
+ description: '',
713
+ active: true,
714
+ sold_out: [],
715
+ sort_id: 1,
716
+ options,
717
+ ...overrides,
718
+ };
719
+ }
720
+ function makeCatalogItem(id, overrides = {}) {
721
+ return {
722
+ _id: id,
723
+ brand_id: 'brand-1',
724
+ tenants: [TENANT_ID],
725
+ category_id: 'pizza-cat',
726
+ included_platforms: [PLATFORM],
727
+ name: `Item ${id}`,
728
+ hide_name: false,
729
+ description: '',
730
+ active: true,
731
+ sold_out: [],
732
+ sort_id: 1,
733
+ price: { BASE_PRICE: 0 },
734
+ discount_amount: null,
735
+ is_discount_percentage: false,
736
+ tax_rate: null,
737
+ keywords: [],
738
+ caveats: [],
739
+ dietary_preferences: [],
740
+ image_url: '',
741
+ ingredients: null,
742
+ item_special_hours: null,
743
+ display_price: null,
744
+ show_starting_from: false,
745
+ use_source_ingredients: false,
746
+ is_featured: false,
747
+ featured_sort_id: 0,
748
+ createdAt: new Date('2024-01-01'),
749
+ updatedAt: new Date('2024-01-02'),
750
+ modifiers: null,
751
+ ...overrides,
752
+ };
753
+ }
754
+ function makeWorkableHalfHalf() {
755
+ const setup = {
756
+ _id: 'halfhalf-1',
757
+ brand_id: 'brand-1',
758
+ tenants: [TENANT_ID],
759
+ category_id: 'pizza-cat',
760
+ included_platforms: [PLATFORM],
761
+ name: 'Half/Half Pizza',
762
+ description: '',
763
+ active: true,
764
+ sold_out: [],
765
+ image_url: '',
766
+ upsell_price: null,
767
+ discount_amount: null,
768
+ is_discount_percentage: false,
769
+ choose_expensive_segment_price: true,
770
+ segments: [
771
+ { _id: 'seg-1', name: 'First Half', sort_id: 1 },
772
+ { _id: 'seg-2', name: 'Second Half', sort_id: 2 },
773
+ ],
774
+ items: [
775
+ { item_id: 'roma', sort_id: 1, upsell_price: null },
776
+ { item_id: 'milano', sort_id: 2, upsell_price: null },
777
+ ],
778
+ exclusive_refs: [],
779
+ excluded_refs: [],
780
+ item_special_hours: null,
781
+ createdAt: new Date('2024-01-01'),
782
+ updatedAt: new Date('2024-01-02'),
783
+ };
784
+ // ROMA: price on a required size leaf + an OPTIONAL extra selected by default.
785
+ const roma = makeCatalogItem('roma', {
786
+ modifiers: [
787
+ makeCatalogModifier('size-roma', [makeCatalogOption('l13-roma', { price: { BASE_PRICE: 1150 }, default: true })], {
788
+ min_num_options: 1,
789
+ max_num_options: 1,
790
+ }),
791
+ makeCatalogModifier('extra-roma', [makeCatalogOption('cheese', { price: { BASE_PRICE: 200 }, default: true })], {
792
+ max_num_options: 1,
793
+ }),
794
+ ],
795
+ });
796
+ const milano = makeCatalogItem('milano', {
797
+ modifiers: [
798
+ makeCatalogModifier('size-milano', [makeCatalogOption('l13-milano', { price: { BASE_PRICE: 1000 }, default: true })], { min_num_options: 1, max_num_options: 1 }),
799
+ ],
800
+ });
801
+ const [workable] = (0, halfhalf_setup_helpers_1.convertHalfHalfSetupToWorkableHalfHalfSetup)([setup], { roma, milano }, PLATFORM, TENANT_ID);
802
+ return workable;
803
+ }
804
+ describe('modern flow converter — references + nested required flags', () => {
805
+ it('collects definition prices keyed by segment/nested option paths', () => {
806
+ const workable = makeWorkableHalfHalf();
807
+ const roma = workable.items.find((item) => item._id === 'roma');
808
+ const milano = workable.items.find((item) => item._id === 'milano');
809
+ const engine = (0, halfhalf_setup_helpers_1.convertHalfHalfToOrderEngineItem)({
810
+ halfHalfItem: workable,
811
+ selectedHalfHalfItems: [
812
+ (0, order_engine_1.convertItemToOrderItem)(roma, null, PLATFORM, TENANT_ID),
813
+ (0, order_engine_1.convertItemToOrderItem)(milano, null, PLATFORM, TENANT_ID),
814
+ ],
815
+ quantity: 1,
816
+ platform: PLATFORM,
817
+ chooseExpensiveSegmentPrice: false,
818
+ });
819
+ const romaOption = engine.modifiers[0].options[0];
820
+ // Segment value: size leaf divided by segments (1150/2 = 575); the optional
821
+ // extra (200) is excluded — add-ons never drive the comparison.
822
+ expect((0, order_engine_1.getOrderEngineOptionSegmentValue)(romaOption)).toBe(575);
823
+ });
824
+ it('nested groups use the CATALOG definition flags (optional extras stay optional)', () => {
825
+ const workable = makeWorkableHalfHalf();
826
+ const roma = workable.items.find((item) => item._id === 'roma');
827
+ const milano = workable.items.find((item) => item._id === 'milano');
828
+ const engine = (0, halfhalf_setup_helpers_1.convertHalfHalfToOrderEngineItem)({
829
+ halfHalfItem: workable,
830
+ selectedHalfHalfItems: [
831
+ (0, order_engine_1.convertItemToOrderItem)(roma, null, PLATFORM, TENANT_ID),
832
+ (0, order_engine_1.convertItemToOrderItem)(milano, null, PLATFORM, TENANT_ID),
833
+ ],
834
+ quantity: 1,
835
+ platform: PLATFORM,
836
+ chooseExpensiveSegmentPrice: false,
837
+ });
838
+ const romaOption = engine.modifiers[0].options[0];
839
+ const sizeGroup = romaOption.modifiers.find((m) => m._id === 'size-roma');
840
+ const extraGroup = romaOption.modifiers.find((m) => m._id === 'extra-roma');
841
+ // Flags come from the catalog definitions: the size group is required...
842
+ expect(sizeGroup.min_num_options).toBe(1);
843
+ // ...and the extras group stays optional (no min flags at all), so it never
844
+ // inflates the value.
845
+ expect(extraGroup.min_num_options == null).toBe(true);
846
+ expect((0, order_engine_1.getOrderEngineOptionSegmentValue)(romaOption)).toBe(575);
847
+ });
848
+ it('with the rule on, the other half is levelled to the REQUIRED value only (extras stay on top)', () => {
849
+ const workable = makeWorkableHalfHalf();
850
+ const roma = workable.items.find((item) => item._id === 'roma');
851
+ const milano = workable.items.find((item) => item._id === 'milano');
852
+ const engine = (0, halfhalf_setup_helpers_1.convertHalfHalfToOrderEngineItem)({
853
+ halfHalfItem: workable,
854
+ selectedHalfHalfItems: [
855
+ (0, order_engine_1.convertItemToOrderItem)(roma, null, PLATFORM, TENANT_ID),
856
+ (0, order_engine_1.convertItemToOrderItem)(milano, null, PLATFORM, TENANT_ID),
857
+ ],
858
+ quantity: 1,
859
+ platform: PLATFORM,
860
+ chooseExpensiveSegmentPrice: true,
861
+ });
862
+ const milanoOption = engine.modifiers[1].options[0];
863
+ const milanoLeaf = milanoOption.modifiers[0].options[0];
864
+ const romaExtras = engine.modifiers[0].options[0].modifiers.find((m) => m._id === 'extra-roma');
865
+ // Milano (500) is levelled to ROMA's REQUIRED value only (575) — the 200
866
+ // extra does not raise it; it stays charged on ROMA alone.
867
+ expect(milanoLeaf.price).toBe(575);
868
+ expect(romaExtras.options[0].price).toBe(200);
869
+ });
870
+ });
871
+ // ============================================================================
872
+ // Classic vs modern parity — same setup + same halves must charge the same
873
+ // ============================================================================
874
+ describe('classic vs modern parity (same setup + same halves -> same charge)', () => {
875
+ const makeItems = () => ({
876
+ roma: makeCatalogItem('roma', {
877
+ modifiers: [
878
+ makeCatalogModifier('size-roma', [makeCatalogOption('l13-roma', { price: { BASE_PRICE: 1150 }, default: true })], { min_num_options: 1, max_num_options: 1 }),
879
+ makeCatalogModifier('extra-roma', [makeCatalogOption('cheese', { price: { BASE_PRICE: 200 }, default: true })], {
880
+ max_num_options: 1,
881
+ }),
882
+ ],
883
+ }),
884
+ milano: makeCatalogItem('milano', {
885
+ modifiers: [
886
+ makeCatalogModifier('size-milano', [makeCatalogOption('l13-milano', { price: { BASE_PRICE: 1000 }, default: true })], { min_num_options: 1, max_num_options: 1 }),
887
+ ],
888
+ }),
889
+ });
890
+ const makeSetup = () => ({
891
+ _id: 'halfhalf-1',
892
+ brand_id: 'brand-1',
893
+ tenants: [TENANT_ID],
894
+ category_id: 'pizza-cat',
895
+ included_platforms: [PLATFORM],
896
+ name: 'Half/Half Pizza',
897
+ description: '',
898
+ active: true,
899
+ sold_out: [],
900
+ image_url: '',
901
+ upsell_price: null,
902
+ discount_amount: null,
903
+ is_discount_percentage: false,
904
+ choose_expensive_segment_price: true,
905
+ segments: [
906
+ { _id: 'seg-1', name: 'First Half', sort_id: 1 },
907
+ { _id: 'seg-2', name: 'Second Half', sort_id: 2 },
908
+ ],
909
+ items: [
910
+ { item_id: 'roma', sort_id: 1, upsell_price: null },
911
+ { item_id: 'milano', sort_id: 2, upsell_price: null },
912
+ ],
913
+ exclusive_refs: [],
914
+ excluded_refs: [],
915
+ item_special_hours: null,
916
+ createdAt: new Date('2024-01-01'),
917
+ updatedAt: new Date('2024-01-02'),
918
+ });
919
+ it('charges the same halves and the same subtotal in the classic and the modern flow', () => {
920
+ const itemsMap = makeItems();
921
+ // ---- CLASSIC: half-half ITEM -> engine -> select -> normalize ----
922
+ const classicItem = (0, halfhalf_setup_helpers_1.convertHalfHalfToItem)(makeSetup(), itemsMap);
923
+ const classicState = (0, order_engine_1.convertCatalogItemToOrderEngineItem)({
924
+ item: classicItem,
925
+ orderItem: undefined,
926
+ platform: PLATFORM,
927
+ tenantId: TENANT_ID,
928
+ orderItemType: constants_1.ORDER_ITEM_TYPE_ENUM.HALF_HALF,
929
+ defaultMenuId: null,
930
+ soldoutModifiers: [],
931
+ });
932
+ let classicEngine = classicState.workingData;
933
+ classicEngine = (0, order_engine_1.setCheckFieldInOrderEngineItem)(classicEngine, 'seg-1_roma', true);
934
+ classicEngine = (0, order_engine_1.setCheckFieldInOrderEngineItem)(classicEngine, 'seg-2_milano', true);
935
+ const classic = (0, order_engine_1.applyChooseExpensiveSegmentPrice)(classicEngine, {
936
+ originalPriceReferences: classicState.originalPriceReferences,
937
+ });
938
+ // ---- MODERN: workable -> stored selections -> engine with the rule ----
939
+ const [workable] = (0, halfhalf_setup_helpers_1.convertHalfHalfSetupToWorkableHalfHalfSetup)([makeSetup()], itemsMap, PLATFORM, TENANT_ID);
940
+ const romaSelection = (0, order_engine_1.convertItemToOrderItem)(workable.items.find((item) => item._id === 'roma'), null, PLATFORM, TENANT_ID);
941
+ const milanoSelection = (0, order_engine_1.convertItemToOrderItem)(workable.items.find((item) => item._id === 'milano'), null, PLATFORM, TENANT_ID);
942
+ const modern = (0, halfhalf_setup_helpers_1.convertHalfHalfToOrderEngineItem)({
943
+ halfHalfItem: workable,
944
+ selectedHalfHalfItems: [romaSelection, milanoSelection],
945
+ quantity: 1,
946
+ platform: PLATFORM,
947
+ chooseExpensiveSegmentPrice: true,
948
+ });
949
+ const classicSeg = (segmentId, optionId) => classic.modifiers
950
+ .find((modifier) => modifier._id === segmentId)
951
+ .options.find((option) => option._id === optionId);
952
+ const modernSeg = (index) => modern.modifiers[index].options[0];
953
+ // First half: 575 required (size) — the topping is not part of the level.
954
+ expect((0, order_engine_1.getOrderEngineOptionSegmentValue)(classicSeg('seg-1', 'roma'))).toBe(575);
955
+ expect((0, order_engine_1.getOrderEngineOptionSegmentValue)(modernSeg(0))).toBe(575);
956
+ // Second half: levelled to 575 in BOTH flows (500 -> 575).
957
+ expect((0, order_engine_1.getOrderEngineOptionSegmentValue)(classicSeg('seg-2', 'milano'))).toBe(575);
958
+ expect((0, order_engine_1.getOrderEngineOptionSegmentValue)(modernSeg(1))).toBe(575);
959
+ // The optional topping is charged identically (ROMA only, own price).
960
+ expect(classicSeg('seg-1', 'roma').modifiers.find((m) => m._id === 'extra-roma').options[0].price).toBe(200);
961
+ expect(modernSeg(0).modifiers.find((m) => m._id === 'extra-roma').options[0].price).toBe(200);
962
+ // End to end: classic total == modern total (575 + 200 + 575).
963
+ expect(classic.subtotal).toBe(1350);
964
+ expect(modern.subtotal).toBe(1350);
965
+ });
966
+ });