@managesome/eposmatic-toolkit 0.2.674 → 0.2.688

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.
@@ -1886,6 +1886,7 @@ function getAddItemToCartData(data, payload, courses, listnerSettings, appliedCu
1886
1886
  }),
1887
1887
  tax_rate: item.tax_rate,
1888
1888
  special_instructions: item.special_instructions,
1889
+ is_ready: item.is_ready,
1889
1890
  modifiers: item.modifiers,
1890
1891
  };
1891
1892
  };
@@ -17,6 +17,9 @@ export type IWorkableHalfHalfSetup<T extends IItem | ISimplifiedCatalogItem> = {
17
17
  category_id: IHalfHalfSetup['category_id'];
18
18
  excluded_refs: IHalfHalfSetup['excluded_refs'];
19
19
  exclusive_refs: IHalfHalfSetup['exclusive_refs'];
20
+ upsell_price: IHalfHalfSetup['upsell_price'];
21
+ discount_amount: IHalfHalfSetup['discount_amount'];
22
+ is_discount_percentage: IHalfHalfSetup['is_discount_percentage'];
20
23
  items: T[];
21
24
  };
22
25
  export declare function convertHalfHalfSetupToWorkableHalfHalfSetup<T extends IItem | ISimplifiedCatalogItem>(halfhalfSetups: IHalfHalfSetup[], itemsMap: Record<string, T>, platform: PLATFORMS_ENUM | undefined, tenant_id: string | undefined): IWorkableHalfHalfSetup<T>[];
@@ -48,7 +51,7 @@ interface IConvertHalfHalfToOrderItem {
48
51
  * same every time this half-half is punched. Each option's `ref` is the
49
52
  * chosen item's `_id`, allowing the item to be de-structured back on edit.
50
53
  */
51
- export declare function convertHalfHalfToOrderItem({ halfHalfItem, selectedHalfHalfItems, quantity, platform: _platform, existingOrderItem, orderItemId, }: IConvertHalfHalfToOrderItem): IOrderItem;
54
+ export declare function convertHalfHalfToOrderItem({ halfHalfItem, selectedHalfHalfItems, quantity, platform, existingOrderItem, orderItemId, }: IConvertHalfHalfToOrderItem): IOrderItem;
52
55
  /**
53
56
  * De-structures a HALF_HALF IOrderItem back into the legacy per-segment
54
57
  * selection format used by the HalfHalfScreen selection flow.
@@ -15,8 +15,10 @@ exports.deStructureHalfHalfOrderItem = deStructureHalfHalfOrderItem;
15
15
  const bson_objectid_1 = __importDefault(require("bson-objectid"));
16
16
  const constants_1 = require("../../constants");
17
17
  const store_1 = require("../store");
18
+ const order_engine_1 = require("./order-engine");
18
19
  const platform_catalog_1 = require("./platform-catalog");
19
20
  const platform_num_1 = require("./platform-num");
21
+ const selection_model_1 = require("./selection-model");
20
22
  function getHalfHalfPostedData(data, payload) {
21
23
  return data.some((half) => half._id === payload._id)
22
24
  ? data
@@ -91,13 +93,18 @@ function convertHalfHalfSetupToWorkableHalfHalfSetup(halfhalfSetups, itemsMap, p
91
93
  }
92
94
  // we get the discount_amount of the halfhalfSetup
93
95
  let discount_amount = halfhalfSetup.discount_amount;
96
+ let is_discount_percentage = halfhalfSetup.is_discount_percentage;
94
97
  if (applicableSchedule !== true && applicableSchedule.discount_amount) {
95
- // if there is an applicable schedule, we use the discount_amount from the schedule
98
+ // schedule discount takes preference over the half-half's own discount
99
+ // and the schedule also carries the percentage flag (same as IItem)
96
100
  discount_amount = applicableSchedule.discount_amount;
101
+ is_discount_percentage = applicableSchedule.is_discount_percentage;
97
102
  }
98
103
  const halfhalfItems = [...halfhalfSetup.items];
99
104
  halfhalfItems.sort((a, b) => a.sort_id - b.sort_id);
100
- const items = [];
105
+ // Workable segment entries: base price first, own upsells applied after
106
+ // the optional expensive-segment normalization.
107
+ const entries = [];
101
108
  for (let j = 0; j < halfhalfItems.length; j++) {
102
109
  const item = halfhalfItems[j];
103
110
  const catalogItem = itemsMap[item.item_id];
@@ -106,19 +113,37 @@ function convertHalfHalfSetupToWorkableHalfHalfSetup(halfhalfSetups, itemsMap, p
106
113
  const workableItem = (0, platform_catalog_1.convertItemToWorkableItem)(catalogItem, platform, tenant_id);
107
114
  if (!workableItem)
108
115
  continue;
109
- if (upsell_price != null) {
110
- workableItem.price = (0, platform_num_1.mergePriceObjs)(workableItem.price, upsell_price);
111
- }
112
116
  if (discount_amount != null) {
113
117
  workableItem.discount_amount = null;
114
118
  }
115
- if (item.upsell_price != null) {
116
- workableItem.price = (0, platform_num_1.mergePriceObjs)(workableItem.price, item.upsell_price);
119
+ entries.push({ workableItem, itemUpsell: item.upsell_price });
120
+ }
121
+ // choose_expensive_segment_price: copy the most expensive segment's BASE
122
+ // price into every segment's base price (each half still keeps its own
123
+ // item-level upsell).
124
+ let expensiveBasePrice = null;
125
+ if (halfhalfSetup.choose_expensive_segment_price && entries.length > 0) {
126
+ expensiveBasePrice = entries[0].workableItem.price;
127
+ let maxValue = (0, platform_catalog_1.getPriceEnum)(expensiveBasePrice, platform);
128
+ for (const entry of entries) {
129
+ const value = (0, platform_catalog_1.getPriceEnum)(entry.workableItem.price, platform);
130
+ if (value > maxValue) {
131
+ maxValue = value;
132
+ expensiveBasePrice = entry.workableItem.price;
133
+ }
134
+ }
135
+ }
136
+ const items = [];
137
+ for (const entry of entries) {
138
+ const { workableItem, itemUpsell } = entry;
139
+ if (expensiveBasePrice != null) {
140
+ workableItem.price = expensiveBasePrice;
141
+ }
142
+ // Each half keeps its own item-level upsell. The half-half upsell is a
143
+ // ONE-TIME addition on the order item, not merged per segment.
144
+ if (itemUpsell != null) {
145
+ workableItem.price = (0, platform_num_1.mergePriceObjs)(workableItem.price, itemUpsell);
117
146
  }
118
- // we divide the price by the number of segments
119
- workableItem.price = (0, platform_num_1.convertPriceObjToSegmentPrice)(workableItem.price, halfhalfSetup.segments.length);
120
- // we divide the discount_amount by the number of segments
121
- workableItem.discount_amount = (0, platform_num_1.convertPriceObjToSegmentPrice)(workableItem.discount_amount, halfhalfSetup.segments.length);
122
147
  items.push(workableItem);
123
148
  }
124
149
  if (items.length === 0)
@@ -134,6 +159,9 @@ function convertHalfHalfSetupToWorkableHalfHalfSetup(halfhalfSetups, itemsMap, p
134
159
  category_id: halfhalfSetup.category_id,
135
160
  excluded_refs: halfhalfSetup.excluded_refs,
136
161
  exclusive_refs: halfhalfSetup.exclusive_refs,
162
+ discount_amount,
163
+ is_discount_percentage,
164
+ upsell_price,
137
165
  items,
138
166
  });
139
167
  }
@@ -164,11 +192,14 @@ function convertHalfHalfToItem(halfhalfSetup, itemsMap, platform, tenant_id) {
164
192
  return null;
165
193
  let upsell_price = halfhalfSetup.upsell_price;
166
194
  let discount_amount = halfhalfSetup.discount_amount;
195
+ let is_discount_percentage = halfhalfSetup.is_discount_percentage;
167
196
  if (applicableSchedule !== true) {
168
197
  if (applicableSchedule.price != null)
169
198
  upsell_price = applicableSchedule.price;
170
199
  if (applicableSchedule.discount_amount != null) {
171
200
  discount_amount = applicableSchedule.discount_amount;
201
+ // the schedule also carries the percentage flag (same as IItem)
202
+ is_discount_percentage = applicableSchedule.is_discount_percentage;
172
203
  }
173
204
  }
174
205
  // ── Build shared option list (segment-neutral ids) ─────────────
@@ -178,7 +209,7 @@ function convertHalfHalfToItem(halfhalfSetup, itemsMap, platform, tenant_id) {
178
209
  const allKeywords = [];
179
210
  const allCaveats = [];
180
211
  const allDietaryPreferences = [];
181
- const baseOptions = [];
212
+ const optionEntries = [];
182
213
  for (let i = 0; i < halfHalfItems.length; i++) {
183
214
  const halfHalfItem = halfHalfItems[i];
184
215
  const catalogItem = itemsMap[halfHalfItem.item_id];
@@ -190,22 +221,46 @@ function convertHalfHalfToItem(halfhalfSetup, itemsMap, platform, tenant_id) {
190
221
  allKeywords.push(...(workableItem.keywords ?? []));
191
222
  allCaveats.push(...(workableItem.caveats ?? []));
192
223
  allDietaryPreferences.push(...(workableItem.dietary_preferences ?? []));
193
- let optionPrice = workableItem.price;
194
- if (upsell_price != null)
195
- optionPrice = (0, platform_num_1.mergePriceObjs)(optionPrice, upsell_price);
196
- if (halfHalfItem.upsell_price != null) {
197
- optionPrice = (0, platform_num_1.mergePriceObjs)(optionPrice, halfHalfItem.upsell_price);
224
+ optionEntries.push({
225
+ workableItem,
226
+ itemUpsell: halfHalfItem.upsell_price,
227
+ catalogItem,
228
+ sortId: halfHalfItem.sort_id,
229
+ });
230
+ }
231
+ // choose_expensive_segment_price: copy the most expensive segment's BASE
232
+ // price into every segment's base price (each half still keeps its own
233
+ // item-level upsell).
234
+ let expensiveBasePrice = null;
235
+ if (halfhalfSetup.choose_expensive_segment_price && optionEntries.length > 0) {
236
+ expensiveBasePrice = optionEntries[0].workableItem.price;
237
+ let maxValue = (0, platform_catalog_1.getPriceEnum)(expensiveBasePrice, platform);
238
+ for (const entry of optionEntries) {
239
+ const value = (0, platform_catalog_1.getPriceEnum)(entry.workableItem.price, platform);
240
+ if (value > maxValue) {
241
+ maxValue = value;
242
+ expensiveBasePrice = entry.workableItem.price;
243
+ }
244
+ }
245
+ }
246
+ const baseOptions = [];
247
+ for (const entry of optionEntries) {
248
+ const { workableItem, itemUpsell, catalogItem, sortId } = entry;
249
+ let optionPrice = expensiveBasePrice != null ? expensiveBasePrice : workableItem.price;
250
+ // Each half keeps its own item-level upsell. The half-half upsell is a
251
+ // ONE-TIME addition on the item price, not merged per segment.
252
+ if (itemUpsell != null) {
253
+ optionPrice = (0, platform_num_1.mergePriceObjs)(optionPrice, itemUpsell);
198
254
  }
199
- optionPrice = (0, platform_num_1.convertPriceObjToSegmentPrice)(optionPrice, halfhalfSetup.segments.length);
200
255
  baseOptions.push({
201
- // `_id` is a generated BSON ObjectId (unique); `ref` is the actual
202
- // item `_id` (deterministic, used for reporting).
203
- _id: (0, bson_objectid_1.default)().toHexString(),
256
+ // `_id` is the real item `_id` (like a catalog option id); each segment
257
+ // creates its own occurrence below. `ref` points to the same item.
258
+ _id: catalogItem._id,
204
259
  ref: catalogItem._id,
205
260
  name: catalogItem.name,
206
261
  active: catalogItem.active,
207
262
  sold_out: catalogItem.sold_out,
208
- sort_id: halfHalfItem.sort_id,
263
+ sort_id: sortId,
209
264
  excluded_platforms: [],
210
265
  price: optionPrice,
211
266
  modifiers: workableItem.modifiers,
@@ -218,10 +273,9 @@ function convertHalfHalfToItem(halfhalfSetup, itemsMap, platform, tenant_id) {
218
273
  for (let s = 0; s < halfhalfSetup.segments.length; s++) {
219
274
  const segment = halfhalfSetup.segments[s];
220
275
  modifiers.push({
221
- // `_id` is a generated BSON ObjectId (unique per creation); `ref` is the
222
- // segment's real `_id` — deterministic, unique per portion and the same
223
- // every time this half-half is punched.
224
- _id: (0, bson_objectid_1.default)().toHexString(),
276
+ // `_id` is the real segment `_id` (like a catalog modifier id); `ref`
277
+ // points to the same segment.
278
+ _id: segment._id,
225
279
  ref: segment._id,
226
280
  name: segment.name || `Segment ${s + 1}`,
227
281
  description: '',
@@ -233,9 +287,9 @@ function convertHalfHalfToItem(halfhalfSetup, itemsMap, platform, tenant_id) {
233
287
  num_free_options: null,
234
288
  options: baseOptions.map((option) => ({
235
289
  ...option,
236
- // `_id` is a generated BSON ObjectId (unique); `ref` stays the item
237
- // `_id` (deterministic, used for reporting).
238
- _id: (0, bson_objectid_1.default)().toHexString(),
290
+ // `_id` is the real item `_id` — same choice always yields the same
291
+ // id; `ref` stays the item `_id`.
292
+ _id: option.ref,
239
293
  })),
240
294
  });
241
295
  }
@@ -252,9 +306,11 @@ function convertHalfHalfToItem(halfhalfSetup, itemsMap, platform, tenant_id) {
252
306
  active: halfhalfSetup.active,
253
307
  sold_out: halfhalfSetup.sold_out,
254
308
  sort_id: 0,
255
- price: null,
309
+ // half-half-level upsell is added ONCE at item level; segment options
310
+ // carry the per-segment base (+ own item upsell) prices.
311
+ price: upsell_price,
256
312
  discount_amount,
257
- is_discount_percentage: halfhalfSetup.is_discount_percentage,
313
+ is_discount_percentage,
258
314
  caveats: Array.from(new Set(allCaveats)),
259
315
  dietary_preferences: Array.from(new Set(allDietaryPreferences)),
260
316
  tax_rate: null,
@@ -281,8 +337,8 @@ function convertHalfHalfToItem(halfhalfSetup, itemsMap, platform, tenant_id) {
281
337
  * same every time this half-half is punched. Each option's `ref` is the
282
338
  * chosen item's `_id`, allowing the item to be de-structured back on edit.
283
339
  */
284
- function convertHalfHalfToOrderItem({ halfHalfItem, selectedHalfHalfItems, quantity, platform: _platform, existingOrderItem, orderItemId, }) {
285
- const modifiers = [];
340
+ function convertHalfHalfToOrderItem({ halfHalfItem, selectedHalfHalfItems, quantity, platform, existingOrderItem, orderItemId, }) {
341
+ const groups = [];
286
342
  let menu_id;
287
343
  for (let s = 0; s < selectedHalfHalfItems.length; s++) {
288
344
  const selectedItem = selectedHalfHalfItems[s];
@@ -294,29 +350,41 @@ function convertHalfHalfToOrderItem({ halfHalfItem, selectedHalfHalfItems, quant
294
350
  if (selectedItem.menu_id != null && menu_id == null) {
295
351
  menu_id = selectedItem.menu_id;
296
352
  }
297
- modifiers.push({
298
- // `_id` must be a BSON ObjectId — generated on create, same as regular
299
- // order items (convertItemToOrderItem).
300
- _id: (0, bson_objectid_1.default)().toHexString(),
353
+ const segment = halfHalfItem.segments[s];
354
+ groups.push({
301
355
  // Deterministic ref = the segment's real `_id` — unique per portion and
302
- // the same every time this half-half is punched.
303
- ref: halfHalfItem.segments[s]?._id ?? halfHalfItem._id,
304
- name: halfHalfItem.segments[s]?.name || `Segment ${s + 1}`,
356
+ // the same every time this half-half is punched. Occurrence `_id` is
357
+ // fresh on create (selection model generates below); preserved on edit
358
+ // when the stored order item is threaded through.
359
+ ref: segment?._id ?? halfHalfItem._id,
360
+ _id: '',
361
+ name: segment?.name || `Segment ${s + 1}`,
362
+ min: 1,
363
+ max: 1,
364
+ freeN: 0,
305
365
  options: [
306
366
  {
307
- _id: selectedItem._id,
367
+ // `_id` is the real catalog item `_id` (like an IItem option), so
368
+ // raw modifiers comparison works for merge and edits stay
369
+ // deterministic.
308
370
  ref: selectedItem.item_id,
371
+ _id: selectedItem.item_id,
309
372
  name: selectedItem.name,
310
373
  price: selectedItem.price,
311
374
  quantity: selectedItem.quantity,
312
- modifiers: selectedItem.modifiers,
313
375
  is_free: false,
376
+ modifiers: selectedItem.modifiers ?? null,
314
377
  },
315
378
  ],
316
379
  });
317
380
  }
381
+ // Save direction of the selection model: `_id`s preserved when carried from
382
+ // the stored order item, fresh ObjectIds otherwise.
383
+ const modifiers = (0, selection_model_1.buildStoredFromSelection)(groups);
318
384
  const orderItem = {
319
- item_discount_details: null,
385
+ // Half-half setup discount (schedule-resolved) is a special_discount on the
386
+ // order item — same as specials.
387
+ item_discount_details: (0, order_engine_1.convertItemDiscountToOrderItemDiscount)(halfHalfItem.discount_amount, halfHalfItem.is_discount_percentage, platform, halfHalfItem._id),
320
388
  special_instructions: '',
321
389
  _net_amount: 0,
322
390
  _gross_amount: 0,
@@ -333,7 +401,9 @@ function convertHalfHalfToOrderItem({ halfHalfItem, selectedHalfHalfItems, quant
333
401
  menu_id,
334
402
  item_type: constants_1.ORDER_ITEM_TYPE_ENUM.HALF_HALF,
335
403
  name: halfHalfItem.name,
336
- price: 0,
404
+ // half-half-level upsell is added ONCE here (segment options carry only
405
+ // their own base + item upsell prices).
406
+ price: (0, platform_catalog_1.getPriceEnum)(halfHalfItem.upsell_price, platform),
337
407
  subtotal: 0,
338
408
  tax_rate: 0,
339
409
  quantity,
@@ -358,24 +428,60 @@ function deStructureHalfHalfOrderItem(orderItem, halfHalfItem) {
358
428
  return null;
359
429
  const selectedHalfHalfItems = new Array(halfHalfItem.segments.length).fill(null);
360
430
  const orderModifiers = orderItem.modifiers ?? [];
361
- for (let i = 0; i < orderModifiers.length; i++) {
362
- const orderModifier = orderModifiers[i];
363
- // Segment identity: the modifier ref = the segment's real `_id`; position
364
- // and first-empty-slot are fallbacks for edge cases.
365
- const modifierRef = orderModifier.ref ?? orderModifier._id ?? '';
366
- let segmentIndex = halfHalfItem.segments.findIndex((segment) => segment._id === modifierRef);
367
- if (segmentIndex === -1)
368
- segmentIndex = i;
369
- if (segmentIndex < 0 || segmentIndex >= selectedHalfHalfItems.length) {
370
- // Fallback: assign to the first empty slot
371
- segmentIndex = selectedHalfHalfItems.findIndex((item) => item === null);
372
- if (segmentIndex === -1)
373
- continue;
431
+ // Ref-keyed FIFO queues: one stored modifier per segment (consumed once,
432
+ // duplicate-safe). Segment identity = modifier ref = the segment's real `_id`;
433
+ // exactId also covers legacy orders that stored `_id` = ref.
434
+ const orderModifierQueues = (0, selection_model_1.buildSelectionRefQueues)(orderModifiers);
435
+ const consumedModifierIds = new Set();
436
+ for (let i = 0; i < halfHalfItem.segments.length; i++) {
437
+ const segment = halfHalfItem.segments[i];
438
+ if (segment == null)
439
+ continue;
440
+ let orderModifier = (0, selection_model_1.consumeSelectionMatch)(orderModifierQueues, segment._id, segment._id);
441
+ if (orderModifier == null) {
442
+ // Legacy pre-punched lines: stored modifier may carry only `_id` = the
443
+ // segment `_id` (no ref) — match by exact `_id` as a fallback.
444
+ orderModifier = orderModifiers.find((storedModifier) => !consumedModifierIds.has(storedModifier._id) && storedModifier._id === segment._id);
374
445
  }
446
+ if (orderModifier != null)
447
+ consumedModifierIds.add(orderModifier._id);
448
+ const option = orderModifier?.options[0];
449
+ if (option == null)
450
+ continue;
451
+ selectedHalfHalfItems[i] = {
452
+ _id: option._id,
453
+ item_id: option.ref,
454
+ menu_id: orderItem.menu_id ?? null,
455
+ item_type: constants_1.ORDER_ITEM_TYPE_ENUM.HALF_HALF,
456
+ name: option.name,
457
+ price: option.price,
458
+ subtotal: option.price,
459
+ tax_rate: 0,
460
+ quantity: option.quantity,
461
+ special_instructions: '',
462
+ item_discount_details: null,
463
+ modifiers: option.modifiers ?? null,
464
+ // These values will be auto calculated
465
+ _discount_amount: 0,
466
+ _gross_amount: 0,
467
+ _gst_amount: 0,
468
+ _net_amount: 0,
469
+ };
470
+ }
471
+ // Fallback: leftover stored modifiers (segments renamed/removed, or legacy
472
+ // lines without refs) go to the first empty slot, oldest first — keeps the
473
+ // selection visible. Iterates the RAW stored modifiers so empty-ref legacy
474
+ // entries (skipped by the ref queues) are still recovered.
475
+ for (const orderModifier of orderModifiers) {
476
+ if (consumedModifierIds.has(orderModifier._id))
477
+ continue;
478
+ const slotIndex = selectedHalfHalfItems.findIndex((item) => item === null);
479
+ if (slotIndex === -1)
480
+ break;
375
481
  const option = orderModifier.options[0];
376
482
  if (option == null)
377
483
  continue;
378
- selectedHalfHalfItems[segmentIndex] = {
484
+ selectedHalfHalfItems[slotIndex] = {
379
485
  _id: option._id,
380
486
  item_id: option.ref,
381
487
  menu_id: orderItem.menu_id ?? null,
@@ -459,8 +459,59 @@ function getReceiptBody({ orderItems, currency_symbol, show_modifiers, display_m
459
459
  return items;
460
460
  }
461
461
  // =========================><=========================
462
+ /**
463
+ * For a SPECIAL / HALF_HALF order item (a deal or half-half pizza), the
464
+ * top-level modifiers hold the real constituent items as options: each
465
+ * `option.ref` is an item `_id` that may live in any category.
466
+ *
467
+ * In partial printing these composite products must not be printed blindly:
468
+ * - an option whose item is not selected in ANY included category is dropped;
469
+ * - a modifier left with no options is dropped;
470
+ * - if every modifier is dropped the whole item is dropped as well.
471
+ *
472
+ * Returns a shallow-cloned item with the trimmed modifiers, or null when
473
+ * nothing survives the filter.
474
+ */
475
+ function getPartiallyIncludedCompositeItem(item, includedItemIds) {
476
+ const trimmedModifiers = [];
477
+ const itemModifiers = item.modifiers ?? [];
478
+ for (let i = 0; i < itemModifiers.length; i++) {
479
+ const modifier = itemModifiers[i];
480
+ // option.ref acts as a real item _id; keep the option only when that item
481
+ // is part of the partial menu in any of its categories.
482
+ const keptOptions = modifier.options.filter((option) => includedItemIds.has(option.ref));
483
+ if (keptOptions.length === 0)
484
+ continue;
485
+ trimmedModifiers.push({
486
+ ...modifier,
487
+ options: keptOptions,
488
+ });
489
+ }
490
+ if (trimmedModifiers.length === 0)
491
+ return null;
492
+ return {
493
+ ...item,
494
+ modifiers: trimmedModifiers,
495
+ };
496
+ }
462
497
  const getPartialItems = (categories = [], included_categories_map, filterEmpty) => {
463
498
  const partialCategories = [];
499
+ // Union of every included item id across all categories. Built lazily and
500
+ // only when a composite item (deal / half-half) actually needs it, so plain
501
+ // orders don't pay for it.
502
+ let allIncludedItemIds = null;
503
+ const getAllIncludedItemIds = () => {
504
+ if (allIncludedItemIds == null) {
505
+ allIncludedItemIds = new Set();
506
+ for (const categoryId in included_categories_map) {
507
+ const includedItems = included_categories_map[categoryId].includedItemsMap;
508
+ for (const itemId in includedItems) {
509
+ allIncludedItemIds.add(itemId);
510
+ }
511
+ }
512
+ }
513
+ return allIncludedItemIds;
514
+ };
464
515
  for (let i = 0; i < categories.length; i++) {
465
516
  const category = categories[i];
466
517
  const includedCategory = included_categories_map[category.category_id];
@@ -470,8 +521,20 @@ const getPartialItems = (categories = [], included_categories_map, filterEmpty)
470
521
  for (let j = 0; j < category.items.length; j++) {
471
522
  const item = category.items[j];
472
523
  const includedItem = includedCategory.includedItemsMap[item.item_id];
524
+ // A composite item (deal / half-half) is still gated by its own item_id
525
+ // exactly like any other item; only once included do we trim its parts.
473
526
  if (!includedItem)
474
527
  continue;
528
+ if ([constants_1.ORDER_ITEM_TYPE_ENUM.SPECIAL, constants_1.ORDER_ITEM_TYPE_ENUM.HALF_HALF].includes(item.item_type)) {
529
+ const partialItem = getPartiallyIncludedCompositeItem(item, getAllIncludedItemIds());
530
+ if (partialItem == null)
531
+ continue;
532
+ partialItems.push({
533
+ sortId: includedItem.sortId,
534
+ item: partialItem,
535
+ });
536
+ continue;
537
+ }
475
538
  partialItems.push({
476
539
  sortId: includedItem.sortId,
477
540
  item,
@@ -0,0 +1,52 @@
1
+ import { IOrderModifier } from '../../schemas';
2
+ export interface ISelectionOption {
3
+ /** Deterministic semantic identity — the catalog item `_id`. */
4
+ ref: string;
5
+ /** Occurrence-local identity — preserved on edit, random on create. */
6
+ _id: string;
7
+ name: string;
8
+ price: number;
9
+ quantity: number;
10
+ is_free: boolean;
11
+ modifiers: IOrderModifier[] | null;
12
+ }
13
+ export interface ISelectionGroup {
14
+ /** Deterministic semantic identity — modifierSpecial._id or segment._id. */
15
+ ref: string;
16
+ /** Occurrence-local identity of the stored IOrderModifier — preserved on edit. */
17
+ _id: string;
18
+ name: string;
19
+ /** Required number of selections (0 or 1 for segments; quantity for specials). */
20
+ min: number;
21
+ /** Maximum number of selections. */
22
+ max: number;
23
+ /** Number of cheapest options that are free (num_free_items). */
24
+ freeN: number;
25
+ options: ISelectionOption[];
26
+ }
27
+ /**
28
+ * Builds IOrderModifier[] from selection groups (save direction).
29
+ * Occurrence `_id`s are the real deterministic entity ids: groups use
30
+ * `group.ref` (modifierSpecial/segment `_id`), options use `option.ref`
31
+ * (catalog item `_id`) — same as `ref`, like catalog IItem ids. Stored
32
+ * `_id`s are kept when present (legacy lines).
33
+ */
34
+ export declare function buildStoredFromSelection(groups: ISelectionGroup[]): IOrderModifier[];
35
+ /**
36
+ * Builds FIFO queues of stored order modifiers/options keyed by their
37
+ * deterministic `ref`, preserving stored order. Empty refs are skipped so
38
+ * they can never alias.
39
+ */
40
+ export declare function buildSelectionRefQueues<T extends {
41
+ ref: string;
42
+ }>(items: T[]): Map<string, T[]>;
43
+ /**
44
+ * Consumes one stored occurrence for a catalog entity (duplicate-safe):
45
+ * prefers an exact `_id` hit (same converted instance, e.g. legacy data where
46
+ * `_id` equals the source ref), otherwise takes the oldest stored occurrence
47
+ * with the ref (FIFO, deterministic). Returns undefined when nothing is left.
48
+ */
49
+ export declare function consumeSelectionMatch<T extends {
50
+ ref: string;
51
+ _id: string;
52
+ }>(queues: Map<string, T[]> | null | undefined, ref: string, exactId: string): T | undefined;
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildStoredFromSelection = buildStoredFromSelection;
4
+ exports.buildSelectionRefQueues = buildSelectionRefQueues;
5
+ exports.consumeSelectionMatch = consumeSelectionMatch;
6
+ /**
7
+ * Builds IOrderModifier[] from selection groups (save direction).
8
+ * Occurrence `_id`s are the real deterministic entity ids: groups use
9
+ * `group.ref` (modifierSpecial/segment `_id`), options use `option.ref`
10
+ * (catalog item `_id`) — same as `ref`, like catalog IItem ids. Stored
11
+ * `_id`s are kept when present (legacy lines).
12
+ */
13
+ function buildStoredFromSelection(groups) {
14
+ const modifiers = [];
15
+ for (let i = 0; i < groups.length; i++) {
16
+ const group = groups[i];
17
+ if (group.options.length === 0)
18
+ continue;
19
+ const options = group.options.map((option) => ({
20
+ _id: option._id.length > 0 ? option._id : option.ref,
21
+ ref: option.ref,
22
+ name: option.name,
23
+ price: option.price,
24
+ quantity: option.quantity,
25
+ is_free: option.is_free,
26
+ modifiers: option.modifiers ?? null,
27
+ }));
28
+ modifiers.push({
29
+ _id: group._id.length > 0 ? group._id : group.ref,
30
+ ref: group.ref,
31
+ name: group.name,
32
+ options,
33
+ });
34
+ }
35
+ return modifiers;
36
+ }
37
+ /**
38
+ * Builds FIFO queues of stored order modifiers/options keyed by their
39
+ * deterministic `ref`, preserving stored order. Empty refs are skipped so
40
+ * they can never alias.
41
+ */
42
+ function buildSelectionRefQueues(items) {
43
+ const queues = new Map();
44
+ for (let i = 0; i < items.length; i++) {
45
+ const item = items[i];
46
+ if (item.ref.length === 0)
47
+ continue;
48
+ const queue = queues.get(item.ref);
49
+ if (queue == null) {
50
+ queues.set(item.ref, [item]);
51
+ }
52
+ else {
53
+ queue.push(item);
54
+ }
55
+ }
56
+ return queues;
57
+ }
58
+ /**
59
+ * Consumes one stored occurrence for a catalog entity (duplicate-safe):
60
+ * prefers an exact `_id` hit (same converted instance, e.g. legacy data where
61
+ * `_id` equals the source ref), otherwise takes the oldest stored occurrence
62
+ * with the ref (FIFO, deterministic). Returns undefined when nothing is left.
63
+ */
64
+ function consumeSelectionMatch(queues, ref, exactId) {
65
+ if (queues == null || ref.length === 0)
66
+ return undefined;
67
+ const queue = queues.get(ref);
68
+ if (queue == null || queue.length === 0)
69
+ return undefined;
70
+ const exactIndex = exactId.length > 0 ? queue.findIndex((item) => item._id === exactId) : -1;
71
+ return exactIndex !== -1 ? queue.splice(exactIndex, 1)[0] : queue.shift();
72
+ }
@@ -40,7 +40,7 @@ export type IWorkableSpecialMenu<T extends IItem | ISimplifiedCatalogItem> = {
40
40
  */
41
41
  export declare function applyModifierSpecialRefRules(modifiers: IModifier[] | null | undefined, exclusiveRefs: string[], excludedRefs: string[]): IModifier[] | null;
42
42
  export declare function convertSpecialsToWorkableSpecials<T extends IItem | ISimplifiedCatalogItem>(specials: ISpecial[], itemsMap: Record<string, T>, platform: PLATFORMS_ENUM | undefined, tenant_id: string | undefined): IWorkableSpecialMenu<T>[];
43
- interface IModifierSpecials {
43
+ export interface IModifierSpecials {
44
44
  _id: string;
45
45
  selectedItems: (IOrderItem | null)[];
46
46
  }
@@ -20,6 +20,7 @@ const order_engine_1 = require("./order-engine");
20
20
  const platform_catalog_1 = require("./platform-catalog");
21
21
  const platform_num_1 = require("./platform-num");
22
22
  const price_conversion_1 = require("./price-conversion");
23
+ const selection_model_1 = require("./selection-model");
23
24
  function getSpecialsPostedData(data, payload) {
24
25
  return data.some((special) => special._id === payload._id)
25
26
  ? data
@@ -133,9 +134,12 @@ function convertSpecialsToWorkableSpecials(specials, itemsMap, platform, tenant_
133
134
  }
134
135
  // we get the discount_amount of the special
135
136
  let discount_amount = special.discount_amount;
137
+ let is_discount_percentage = special.is_discount_percentage;
136
138
  if (applicableSchedule !== true && applicableSchedule.discount_amount) {
137
139
  // if there is an applicable schedule, we use the discount_amount from the schedule
138
140
  discount_amount = applicableSchedule.discount_amount;
141
+ // the schedule also carries the percentage flag (same as IItem)
142
+ is_discount_percentage = applicableSchedule.is_discount_percentage;
139
143
  }
140
144
  const modifierSpecials = [];
141
145
  for (let j = 0; j < special.modifier_specials.length; j++) {
@@ -185,7 +189,7 @@ function convertSpecialsToWorkableSpecials(specials, itemsMap, platform, tenant_
185
189
  category_id: special.category_id,
186
190
  price,
187
191
  discount_amount,
188
- is_discount_percentage: special.is_discount_percentage,
192
+ is_discount_percentage,
189
193
  display_price: special.display_price,
190
194
  show_starting_from: special.show_starting_from,
191
195
  modifier_specials: modifierSpecials,
@@ -195,7 +199,7 @@ function convertSpecialsToWorkableSpecials(specials, itemsMap, platform, tenant_
195
199
  return specialsMenu;
196
200
  }
197
201
  function convertSpecialItemToOrderItem({ specialItem, modifierSpecials, quantity, platform, existingOrderItem, orderItemId, }) {
198
- const modifiers = [];
202
+ const groups = [];
199
203
  let menu_id;
200
204
  for (let i = 0; i < modifierSpecials.length; i++) {
201
205
  const modifierSpecial = modifierSpecials[i];
@@ -213,11 +217,10 @@ function convertSpecialItemToOrderItem({ specialItem, modifierSpecials, quantity
213
217
  if (selectedItem.menu_id != null && menu_id == null) {
214
218
  menu_id = selectedItem.menu_id;
215
219
  }
216
- // `_id` must be a BSON ObjectId (backend rejects plain strings). The
217
- // selection item already carries a valid ObjectId — random on create and
218
- // stable across edit round-trips. Determinism lives in `ref`.
220
+ // `_id` is the real catalog item `_id` (like an IItem option), so raw
221
+ // modifiers comparison works for merge and edits stay deterministic.
219
222
  options.push({
220
- _id: selectedItem._id,
223
+ _id: selectedItem.item_id,
221
224
  ref: selectedItem.item_id,
222
225
  name: selectedItem.name,
223
226
  price: selectedItem.price,
@@ -241,16 +244,28 @@ function convertSpecialItemToOrderItem({ specialItem, modifierSpecials, quantity
241
244
  }
242
245
  });
243
246
  }
244
- // Modifier `_id` must be a BSON ObjectId — generated on create (same as the
245
- // order engine). Edit matching uses the deterministic `ref`.
246
- const modifier = {
247
- _id: (0, bson_objectid_1.default)().toHexString(),
247
+ // Group id = the modifier-special `_id` (same as ref — deterministic).
248
+ groups.push({
248
249
  ref: originalModifierSpecial._id,
250
+ _id: '',
249
251
  name: originalModifierSpecial.name,
250
- options,
251
- };
252
- modifiers.push(modifier);
252
+ min: 0,
253
+ max: 0,
254
+ freeN: numFreeItems,
255
+ options: options.map((option) => ({
256
+ ref: option.ref,
257
+ _id: option._id,
258
+ name: option.name,
259
+ price: option.price,
260
+ quantity: option.quantity,
261
+ is_free: option.is_free,
262
+ modifiers: option.modifiers ?? null,
263
+ })),
264
+ });
253
265
  }
266
+ // Save direction of the selection model: `_id`s preserved when carried from
267
+ // the stored order item, fresh ObjectIds otherwise.
268
+ const modifiers = (0, selection_model_1.buildStoredFromSelection)(groups);
254
269
  const orderItem = {
255
270
  item_discount_details: (0, order_engine_1.convertItemDiscountToOrderItemDiscount)(specialItem.discount_amount, specialItem.is_discount_percentage, platform, specialItem._id),
256
271
  special_instructions: '',
@@ -302,9 +317,21 @@ function deStructureSpecialOrderItem(orderItem, specialItem) {
302
317
  return null;
303
318
  const orderModifiers = orderItem.modifiers ?? [];
304
319
  const modifierSpecials = [];
320
+ // Ref-keyed FIFO queues: stored modifiers are consumed one-at-a-time so a
321
+ // modifier special that appears multiple times maps to distinct occurrences.
322
+ const orderModifierQueues = (0, selection_model_1.buildSelectionRefQueues)(orderModifiers);
323
+ const consumedModifierIds = new Set();
305
324
  for (let i = 0; i < specialItem.modifier_specials.length; i++) {
306
325
  const modifierSpecial = specialItem.modifier_specials[i];
307
- const orderModifier = orderModifiers.find((modifier) => modifier.ref === modifierSpecial._id || modifier._id === modifierSpecial._id);
326
+ // exactId = the modifier-special `_id` (legacy orders stored `_id` = ref).
327
+ let orderModifier = (0, selection_model_1.consumeSelectionMatch)(orderModifierQueues, modifierSpecial._id, modifierSpecial._id);
328
+ if (orderModifier == null) {
329
+ // Legacy pre-punched lines: stored modifier may carry only `_id` = the
330
+ // modifier-special `_id` (no ref) — match by exact `_id` as a fallback.
331
+ orderModifier = orderModifiers.find((storedModifier) => !consumedModifierIds.has(storedModifier._id) && storedModifier._id === modifierSpecial._id);
332
+ }
333
+ if (orderModifier != null)
334
+ consumedModifierIds.add(orderModifier._id);
308
335
  const selectedItems = new Array(modifierSpecial.quantity).fill(null);
309
336
  if (orderModifier != null) {
310
337
  for (let j = 0; j < orderModifier.options.length; j++) {
@@ -368,8 +395,11 @@ function convertSpecialToItem(special, itemsMap, platform, tenant_id) {
368
395
  price = applicableSchedule.price;
369
396
  }
370
397
  let discount_amount = special.discount_amount;
398
+ let is_discount_percentage = special.is_discount_percentage;
371
399
  if (applicableSchedule !== true && applicableSchedule.discount_amount) {
372
400
  discount_amount = applicableSchedule.discount_amount;
401
+ // the schedule also carries the percentage flag (same as IItem)
402
+ is_discount_percentage = applicableSchedule.is_discount_percentage;
373
403
  }
374
404
  // ── Build modifiers from modifier_specials ─────────────────────
375
405
  const modifiers = [];
@@ -406,9 +436,10 @@ function convertSpecialToItem(special, itemsMap, platform, tenant_id) {
406
436
  // excluded_refs removes modifiers/options, exclusive_refs removes their price.
407
437
  const itemModifiers = applyModifierSpecialRefRules(workableItem.modifiers, modifierSpecial.exclusive_refs, modifierSpecial.excluded_refs);
408
438
  options.push({
409
- // `_id` is a generated BSON ObjectId (unique); `ref` is the actual
410
- // item `_id` (deterministic, used for reporting).
411
- _id: (0, bson_objectid_1.default)().toHexString(),
439
+ // `_id` is the real item `_id` (like a catalog option id —
440
+ // deterministic, identical across lines of the same selection);
441
+ // `ref` points to the same actual item.
442
+ _id: catalogItem._id,
412
443
  ref: catalogItem._id,
413
444
  name: catalogItem.name,
414
445
  active: catalogItem.active,
@@ -422,10 +453,9 @@ function convertSpecialToItem(special, itemsMap, platform, tenant_id) {
422
453
  if (options.length === 0)
423
454
  continue;
424
455
  modifiers.push({
425
- // `_id` is a generated BSON ObjectId — unique identifier of this
426
- // modifier instance; `ref` is the source modifier-special `_id`
427
- // (deterministic, used for matching/reporting).
428
- _id: (0, bson_objectid_1.default)().toHexString(),
456
+ // `_id` is the real modifier-special `_id` (like a catalog modifier id);
457
+ // `ref` points to the same source modifier-special.
458
+ _id: modifierSpecial._id,
429
459
  ref: modifierSpecial._id,
430
460
  name: modifierSpecial.name,
431
461
  description: '',
@@ -453,7 +483,7 @@ function convertSpecialToItem(special, itemsMap, platform, tenant_id) {
453
483
  sort_id: special.sort_id,
454
484
  price,
455
485
  discount_amount,
456
- is_discount_percentage: special.is_discount_percentage,
486
+ is_discount_percentage,
457
487
  caveats: Array.from(new Set(allCaveats)),
458
488
  dietary_preferences: Array.from(new Set(allDietaryPreferences)),
459
489
  tax_rate: null,
@@ -1,6 +1,5 @@
1
1
  import { PLATFORMS_ENUM } from '../../constants';
2
2
  import { IItemSpecialHour, IPrice } from './common';
3
- import { IOrderItem } from './orders';
4
3
  export interface ISpecialItem {
5
4
  item_id: string;
6
5
  sort_id: number;
@@ -39,7 +38,3 @@ export interface ISpecial {
39
38
  createdAt: Date;
40
39
  updatedAt: Date;
41
40
  }
42
- export interface IModifierSpecials {
43
- _id: string;
44
- selectedItems: (IOrderItem | null)[];
45
- }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@managesome/eposmatic-toolkit",
3
- "version": "0.2.674",
3
+ "version": "0.2.688",
4
4
  "description": "A Toolkit Library for Eposmatic",
5
5
  "main": "lib/index.js",
6
6
  "types": "lib/index.d.ts",