@managesome/eposmatic-toolkit 0.2.695 → 0.2.696

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.
@@ -13,6 +13,7 @@ export interface ISimplifiedHalfHalfSetup {
13
13
  is_discount_percentage?: boolean;
14
14
  discount_amount?: IMinifiedPrice;
15
15
  item_special_hours?: IMinifiedItemSpecialHour[];
16
+ choose_expensive_segment_price?: boolean;
16
17
  _id: string;
17
18
  category_id: string;
18
19
  name: string;
@@ -36,6 +36,7 @@ export interface ICatalogItemOptionsDrawerProps<I extends ISimplifiedCatalogItem
36
36
  applyVoucher?: IApplyVoucher;
37
37
  rewardClaim?: IRewardClaim;
38
38
  isRewardItem?: boolean;
39
+ chooseExpensiveSegmentPrice?: boolean;
39
40
  onSelect?: (item: IOrderItem) => void;
40
41
  }
41
42
  interface IGetEditItemProps<I extends ISimplifiedCatalogItem | IItem> {
@@ -1,5 +1,5 @@
1
1
  import { PLATFORMS_ENUM } from '../../constants';
2
- import { IHalfHalfSetup, IItem, IOrderItem } from '../../schemas';
2
+ import { IHalfHalfSetup, IItem, IModifier, IOrderItem, IPrice } from '../../schemas';
3
3
  import { ISimplifiedCatalogItem } from '../types';
4
4
  export declare function getHalfHalfPostedData(data: IHalfHalfSetup[], payload: IHalfHalfSetup): IHalfHalfSetup[];
5
5
  export declare function renderBulkHalfHalfUpdate(data: IHalfHalfSetup[], payload: Partial<IHalfHalfSetup>[]): IHalfHalfSetup[];
@@ -22,24 +22,49 @@ export type IWorkableHalfHalfSetup<T extends IItem | ISimplifiedCatalogItem> = {
22
22
  is_discount_percentage: IHalfHalfSetup['is_discount_percentage'];
23
23
  items: T[];
24
24
  };
25
+ /**
26
+ * Divides a half-half segment item's price structure by the number of
27
+ * segments (2 halves / 4 quarters):
28
+ *
29
+ * - the item-level `price` is divided by `segments`,
30
+ * - **required** modifier groups (`min_num_options > 0` or
31
+ * `min_aggregate_options_quantity > 0`) get their option prices divided too
32
+ * (recursively) because they define the item's price (e.g. "Pizza Size" →
33
+ * "Large 13\""),
34
+ * - **optional** modifier groups/options (upsells like "Drinks") keep full
35
+ * prices so they add on top of the halved/quartered price,
36
+ * - upsell prices are never touched here; callers merge them on top.
37
+ *
38
+ * Returns the item unchanged when `segments` is missing/<= 1.
39
+ */
40
+ export declare function divideItemPriceBySegments<T extends {
41
+ price: IPrice | null;
42
+ modifiers?: IModifier[] | null | undefined;
43
+ }>(item: T, segments: number | undefined | null): T;
25
44
  export declare function convertHalfHalfSetupToWorkableHalfHalfSetup<T extends IItem | ISimplifiedCatalogItem>(halfhalfSetups: IHalfHalfSetup[], itemsMap: Record<string, T>, platform: PLATFORMS_ENUM | undefined, tenant_id: string | undefined): IWorkableHalfHalfSetup<T>[];
26
45
  /**
27
46
  * Converts an IHalfHalfSetup into an IItem so it can flow through the standard
28
47
  * catalog → drawer → cart pipeline just like a regular catalog item.
29
48
  *
30
49
  * Each segment becomes a single-select IModifier (one option per available
31
- * item, priced as `(item price + upsells) / segments`), so duplicates across
32
- * segments are allowed and each segment must be filled exactly once.
50
+ * item, priced as `(item price / segments) + own upsell`), so duplicates
51
+ * across segments are allowed and each segment must be filled exactly once.
52
+ * Required (price-defining) modifier option prices are divided with the base
53
+ * (e.g. Pizza Size 1150 -> 575); optional upsell modifier prices stay full.
33
54
  *
34
55
  * PURE CONVERSION ONLY — no availability filtering (active / tenants /
35
- * included_platforms) and no special-hours / platform-based price
36
- * resolution happens here. Setup fields are copied through as-is:
56
+ * included_platforms), no special-hours / platform-based price resolution,
57
+ * and NO `choose_expensive_segment_price` handling: that rule depends on
58
+ * which halves the user picks, so it is applied later at selection time
59
+ * (see `applyChooseExpensiveSegmentPrice`). Setup fields are copied through
60
+ * as-is:
61
+ * - item `price` stays the half-half upsell price (each platform resolves it
62
+ * via `getPriceEnum`),
63
+ * - item `discount_amount` stays the half-half discount,
37
64
  * - `item_special_hours` is preserved on the output item,
38
65
  * - each option's `excluded_platforms` is derived (complement) from its
39
66
  * source item's `included_platforms`, so platform availability can be
40
- * applied by the filter layer downstream,
41
- * - `choose_expensive_segment_price` compares segment prices by `BASE_PRICE`
42
- * (platform-neutral) and copies the actual IPrice object through.
67
+ * applied by the filter layer downstream.
43
68
  *
44
69
  * Returns null only when no option can be resolved from the items map.
45
70
  */
@@ -8,6 +8,7 @@ exports.renderBulkHalfHalfUpdate = renderBulkHalfHalfUpdate;
8
8
  exports.getHalfHalfUpdatedData = getHalfHalfUpdatedData;
9
9
  exports.getHalfHalfDeletedData = getHalfHalfDeletedData;
10
10
  exports.getHalfhalfSetupWithPrice = getHalfhalfSetupWithPrice;
11
+ exports.divideItemPriceBySegments = divideItemPriceBySegments;
11
12
  exports.convertHalfHalfSetupToWorkableHalfHalfSetup = convertHalfHalfSetupToWorkableHalfHalfSetup;
12
13
  exports.convertHalfHalfToItem = convertHalfHalfToItem;
13
14
  exports.convertHalfHalfToOrderItem = convertHalfHalfToOrderItem;
@@ -17,9 +18,9 @@ const constants_1 = require("../../constants");
17
18
  const store_1 = require("../store");
18
19
  const order_engine_1 = require("./order-engine");
19
20
  const platform_catalog_1 = require("./platform-catalog");
20
- const specials_helpers_1 = require("./specials-helpers");
21
21
  const platform_num_1 = require("./platform-num");
22
22
  const selection_model_1 = require("./selection-model");
23
+ const specials_helpers_1 = require("./specials-helpers");
23
24
  function getHalfHalfPostedData(data, payload) {
24
25
  return data.some((half) => half._id === payload._id)
25
26
  ? data
@@ -71,6 +72,75 @@ function getHalfhalfSetupWithPrice(halfhalfSetup, writeable) {
71
72
  : {}),
72
73
  };
73
74
  }
75
+ /**
76
+ * Divides a half-half segment item's price structure by the number of
77
+ * segments (2 halves / 4 quarters):
78
+ *
79
+ * - the item-level `price` is divided by `segments`,
80
+ * - **required** modifier groups (`min_num_options > 0` or
81
+ * `min_aggregate_options_quantity > 0`) get their option prices divided too
82
+ * (recursively) because they define the item's price (e.g. "Pizza Size" →
83
+ * "Large 13\""),
84
+ * - **optional** modifier groups/options (upsells like "Drinks") keep full
85
+ * prices so they add on top of the halved/quartered price,
86
+ * - upsell prices are never touched here; callers merge them on top.
87
+ *
88
+ * Returns the item unchanged when `segments` is missing/<= 1.
89
+ */
90
+ function divideItemPriceBySegments(item, segments) {
91
+ const divisor = segments ?? 1;
92
+ if (divisor <= 1)
93
+ return item;
94
+ const divideRequiredModifierPrices = (modifiers) => {
95
+ if (modifiers == null || modifiers.length === 0)
96
+ return modifiers;
97
+ return modifiers.map((modifier) => {
98
+ const isRequired = (modifier.min_num_options != null && modifier.min_num_options > 0) ||
99
+ (modifier.min_aggregate_options_quantity != null && modifier.min_aggregate_options_quantity > 0);
100
+ if (!isRequired)
101
+ return modifier;
102
+ return {
103
+ ...modifier,
104
+ options: (modifier.options ?? []).map((option) => ({
105
+ ...option,
106
+ price: (0, platform_num_1.convertPriceObjToSegmentPrice)(option.price ?? null, divisor),
107
+ modifiers: divideRequiredModifierPrices(option.modifiers),
108
+ })),
109
+ };
110
+ });
111
+ };
112
+ const result = {
113
+ ...item,
114
+ price: (0, platform_num_1.convertPriceObjToSegmentPrice)(item.price, divisor),
115
+ modifiers: divideRequiredModifierPrices(item.modifiers),
116
+ };
117
+ return result;
118
+ }
119
+ function isRequiredModifierGroup(modifier) {
120
+ return ((modifier.min_num_options != null && modifier.min_num_options > 0) ||
121
+ (modifier.min_aggregate_options_quantity != null && modifier.min_aggregate_options_quantity > 0));
122
+ }
123
+ /**
124
+ * Total divided base price of a segment item = item price + prices of all
125
+ * required (price-defining) modifier options at any nesting depth. Used by
126
+ * `choose_expensive_segment_price` so the comparison also covers items whose
127
+ * price lives inside a required modifier group (e.g. "Pizza Size").
128
+ */
129
+ function getSegmentItemTotalPrice(item, platform) {
130
+ let total = (0, platform_catalog_1.getPriceEnum)(item.price, platform);
131
+ const addRequiredPrices = (modifiers) => {
132
+ (modifiers ?? []).forEach((modifier) => {
133
+ if (!isRequiredModifierGroup(modifier))
134
+ return;
135
+ (modifier.options ?? []).forEach((option) => {
136
+ total += (0, platform_catalog_1.getPriceEnum)(option.price, platform);
137
+ addRequiredPrices(option.modifiers);
138
+ });
139
+ });
140
+ };
141
+ addRequiredPrices(item.modifiers);
142
+ return total;
143
+ }
74
144
  function convertHalfHalfSetupToWorkableHalfHalfSetup(halfhalfSetups, itemsMap, platform, tenant_id) {
75
145
  if (!platform || !tenant_id)
76
146
  return [];
@@ -106,8 +176,8 @@ function convertHalfHalfSetupToWorkableHalfHalfSetup(halfhalfSetups, itemsMap, p
106
176
  // from the selectable list (same semantics as specials' excluded_refs).
107
177
  .filter((setupItem) => !halfhalfSetup.excluded_refs.includes(setupItem.item_id))
108
178
  .sort((a, b) => a.sort_id - b.sort_id);
109
- // Workable segment entries: base price first, own upsells applied after
110
- // the optional expensive-segment normalization.
179
+ // Workable segment entries: divided base price, with the optional
180
+ // expensive-segment normalization + own upsells applied here (modern view).
111
181
  const entries = [];
112
182
  for (let j = 0; j < halfhalfItems.length; j++) {
113
183
  const item = halfhalfItems[j];
@@ -123,31 +193,41 @@ function convertHalfHalfSetupToWorkableHalfHalfSetup(halfhalfSetups, itemsMap, p
123
193
  // Apply the half-half reference rules to the item's own modifiers:
124
194
  // excluded_refs removes modifiers/options, exclusive_refs removes their price.
125
195
  workableItem.modifiers = (0, specials_helpers_1.applyModifierSpecialRefRules)(workableItem.modifiers, halfhalfSetup.exclusive_refs, halfhalfSetup.excluded_refs);
126
- entries.push({ workableItem, itemUpsell: item.upsell_price });
196
+ // Each half/quarter costs the item's price divided by the number of
197
+ // segments; required (price-defining) modifier options are divided with
198
+ // it (e.g. Pizza Size 1150 -> 575), optional upsell modifiers stay full.
199
+ const segmentItem = divideItemPriceBySegments(workableItem, halfhalfSetup.segments.length);
200
+ entries.push({
201
+ workableItem: segmentItem,
202
+ itemUpsell: item.upsell_price,
203
+ segmentTotal: getSegmentItemTotalPrice(segmentItem, platform),
204
+ });
127
205
  }
128
- // choose_expensive_segment_price: copy the most expensive segment's BASE
129
- // price into every segment's base price (each half still keeps its own
130
- // item-level upsell).
131
- let expensiveBasePrice = null;
206
+ // choose_expensive_segment_price: normalize every segment's TOTAL base
207
+ // price (item price + required/price-defining modifier prices, already
208
+ // divided) to the most expensive one; the difference is added at item
209
+ // level so a $5 half and a $6 half both charge $6.
210
+ let expensiveMaxTotal = 0;
132
211
  if (halfhalfSetup.choose_expensive_segment_price && entries.length > 0) {
133
- expensiveBasePrice = entries[0].workableItem.price;
134
- let maxValue = (0, platform_catalog_1.getPriceEnum)(expensiveBasePrice, platform);
135
- for (const entry of entries) {
136
- const value = (0, platform_catalog_1.getPriceEnum)(entry.workableItem.price, platform);
137
- if (value > maxValue) {
138
- maxValue = value;
139
- expensiveBasePrice = entry.workableItem.price;
140
- }
141
- }
212
+ expensiveMaxTotal = entries.reduce((max, entry) => Math.max(max, entry.segmentTotal), 0);
142
213
  }
143
214
  const items = [];
144
215
  for (const entry of entries) {
145
- const { workableItem, itemUpsell } = entry;
146
- if (expensiveBasePrice != null) {
147
- workableItem.price = expensiveBasePrice;
216
+ const { workableItem, itemUpsell, segmentTotal } = entry;
217
+ if (halfhalfSetup.choose_expensive_segment_price && segmentTotal < expensiveMaxTotal) {
218
+ const delta = expensiveMaxTotal - segmentTotal;
219
+ // Raise BOTH the active platform's key AND the base by `delta` so the
220
+ // effective price (`getPriceEnum` reads `price[platform] ??
221
+ // BASE_PRICE`) is normalized even for items priced per-platform (e.g.
222
+ // POS_DINE_IN / WEB_DELIVERY keys on the same IPrice object).
223
+ workableItem.price = (0, platform_num_1.mergePriceObjs)(workableItem.price, {
224
+ BASE_PRICE: delta,
225
+ [platform]: delta,
226
+ });
148
227
  }
149
- // Each half keeps its own item-level upsell. The half-half upsell is a
150
- // ONE-TIME addition on the order item, not merged per segment.
228
+ // Each half keeps its own item-level upsell, added ON TOP of the divided
229
+ // price. The half-half upsell is a ONE-TIME addition on the order item,
230
+ // not merged per segment.
151
231
  if (itemUpsell != null) {
152
232
  workableItem.price = (0, platform_num_1.mergePriceObjs)(workableItem.price, itemUpsell);
153
233
  }
@@ -184,18 +264,24 @@ function convertHalfHalfSetupToWorkableHalfHalfSetup(halfhalfSetups, itemsMap, p
184
264
  * catalog → drawer → cart pipeline just like a regular catalog item.
185
265
  *
186
266
  * Each segment becomes a single-select IModifier (one option per available
187
- * item, priced as `(item price + upsells) / segments`), so duplicates across
188
- * segments are allowed and each segment must be filled exactly once.
267
+ * item, priced as `(item price / segments) + own upsell`), so duplicates
268
+ * across segments are allowed and each segment must be filled exactly once.
269
+ * Required (price-defining) modifier option prices are divided with the base
270
+ * (e.g. Pizza Size 1150 -> 575); optional upsell modifier prices stay full.
189
271
  *
190
272
  * PURE CONVERSION ONLY — no availability filtering (active / tenants /
191
- * included_platforms) and no special-hours / platform-based price
192
- * resolution happens here. Setup fields are copied through as-is:
273
+ * included_platforms), no special-hours / platform-based price resolution,
274
+ * and NO `choose_expensive_segment_price` handling: that rule depends on
275
+ * which halves the user picks, so it is applied later at selection time
276
+ * (see `applyChooseExpensiveSegmentPrice`). Setup fields are copied through
277
+ * as-is:
278
+ * - item `price` stays the half-half upsell price (each platform resolves it
279
+ * via `getPriceEnum`),
280
+ * - item `discount_amount` stays the half-half discount,
193
281
  * - `item_special_hours` is preserved on the output item,
194
282
  * - each option's `excluded_platforms` is derived (complement) from its
195
283
  * source item's `included_platforms`, so platform availability can be
196
- * applied by the filter layer downstream,
197
- * - `choose_expensive_segment_price` compares segment prices by `BASE_PRICE`
198
- * (platform-neutral) and copies the actual IPrice object through.
284
+ * applied by the filter layer downstream.
199
285
  *
200
286
  * Returns null only when no option can be resolved from the items map.
201
287
  */
@@ -224,34 +310,27 @@ function convertHalfHalfToItem(halfhalfSetup, itemsMap) {
224
310
  allKeywords.push(...(catalogItem.keywords ?? []));
225
311
  allCaveats.push(...(catalogItem.caveats ?? []));
226
312
  allDietaryPreferences.push(...(catalogItem.dietary_preferences ?? []));
313
+ // Ref rules first (excluded/exclusive), then divide the price structure
314
+ // by the number of segments (required/price-defining modifier prices are
315
+ // divided; optional upsell modifier prices stay full).
316
+ const segmentItem = divideItemPriceBySegments({
317
+ ...catalogItem,
318
+ modifiers: (0, specials_helpers_1.applyModifierSpecialRefRules)(catalogItem.modifiers, halfhalfSetup.exclusive_refs, halfhalfSetup.excluded_refs),
319
+ }, halfhalfSetup.segments.length);
227
320
  optionEntries.push({
228
321
  catalogItem,
322
+ segmentItem,
229
323
  itemUpsell: halfHalfItem.upsell_price,
230
324
  sortId: halfHalfItem.sort_id,
231
325
  });
232
326
  }
233
- // choose_expensive_segment_price: copy the most expensive segment's BASE
234
- // price into every segment's base price (each half still keeps its own
235
- // item-level upsell). Comparison uses BASE_PRICE (platform-neutral); the
236
- // actual IPrice object is copied through unresolved.
237
- let expensiveBasePrice = null;
238
- if (halfhalfSetup.choose_expensive_segment_price && optionEntries.length > 0) {
239
- expensiveBasePrice = optionEntries[0].catalogItem.price;
240
- let maxValue = expensiveBasePrice?.BASE_PRICE ?? 0;
241
- for (const entry of optionEntries) {
242
- const value = entry.catalogItem.price?.BASE_PRICE ?? 0;
243
- if (value > maxValue) {
244
- maxValue = value;
245
- expensiveBasePrice = entry.catalogItem.price;
246
- }
247
- }
248
- }
249
327
  const baseOptions = [];
250
328
  for (const entry of optionEntries) {
251
- const { catalogItem, itemUpsell, sortId } = entry;
252
- let optionPrice = expensiveBasePrice != null ? expensiveBasePrice : catalogItem.price;
253
- // Each half keeps its own item-level upsell. The half-half upsell is a
254
- // ONE-TIME addition on the item price, not merged per segment.
329
+ const { catalogItem, segmentItem, itemUpsell, sortId } = entry;
330
+ // Option price = (item's original price / segments) + this item's own
331
+ // upsell (added on top). The half-half upsell is a ONE-TIME addition on
332
+ // the item price, not merged per segment.
333
+ let optionPrice = segmentItem.price;
255
334
  if (itemUpsell != null) {
256
335
  optionPrice = (0, platform_num_1.mergePriceObjs)(optionPrice, itemUpsell);
257
336
  }
@@ -275,7 +354,7 @@ function convertHalfHalfToItem(halfhalfSetup, itemsMap) {
275
354
  // schedule availability (pure mapping, no resolution here).
276
355
  item_modifier_option_special_hours: catalogItem.item_special_hours,
277
356
  price: optionPrice,
278
- modifiers: (0, specials_helpers_1.applyModifierSpecialRefRules)(catalogItem.modifiers, halfhalfSetup.exclusive_refs, halfhalfSetup.excluded_refs),
357
+ modifiers: segmentItem.modifiers,
279
358
  });
280
359
  }
281
360
  if (baseOptions.length === 0)
@@ -6,6 +6,34 @@ export declare function hasMissedRequiredItemModifier(currentModifiers: IModifie
6
6
  export declare function syncOrderEngineItem(orderEngineItem: IOrderEngineItem): IOrderEngineItem;
7
7
  export declare function checkIfModifiersExist(modifiers: IModifier[] | null, platform: PLATFORMS_ENUM | undefined): boolean;
8
8
  export declare function makeSpaceForFreeOptions(options: IOrderEngineOption[], num_free_options: number | null | undefined): IOrderEngineOption[];
9
+ /**
10
+ * Applies `choose_expensive_segment_price` to an order engine item converted
11
+ * from a half-half setup (top-level modifier groups = segments, single-select
12
+ * each, only 2 or 4 segments).
13
+ *
14
+ * The expensive rule depends on which halves the user actually picked, so it
15
+ * cannot run during `IHalfHalfSetup -> IItem` conversion — it must run after
16
+ * selection. It is invoked automatically by
17
+ * `setCheckFieldInOrderEngineItem` whenever the engine item's `item_type` is
18
+ * `HALF_HALF` and the caller passed the flag.
19
+ *
20
+ * Rule: `price = base + upsell` — the item (option) level upsell is already
21
+ * baked into the option price at conversion. choose_expensive compares the
22
+ * FINAL segment price (option price + required/price-defining modifier
23
+ * prices — e.g. a "Pizza Size" group whose Small/Large/X-Large options are
24
+ * part of the item's price) and raises every cheaper selected segment to the
25
+ * most expensive one. Optional/upsell modifier groups are excluded: they add
26
+ * on top and must not influence the comparison. The IHalfHalfSetup level
27
+ * upsell is NOT part of this rule: it is the converted item's own price and
28
+ * is added once on top of the combined subtotal.
29
+ *
30
+ * All prices here are plain numbers (engine-priced). Idempotent — it only
31
+ * ever raises, never lowers — so it can safely be re-applied (e.g. on
32
+ * submit).
33
+ *
34
+ * Returns the item unchanged when fewer than two segments are selected.
35
+ */
36
+ export declare function applyChooseExpensiveSegmentPrice(orderEngineItem: IOrderEngineItem): IOrderEngineItem;
9
37
  export type IOrderEngineItemRewardClaim = {
10
38
  type: 'offer';
11
39
  offerId: string;
@@ -55,7 +83,7 @@ interface IConvertCatalogItemToOrderEngineItemParams {
55
83
  export declare function convertCatalogItemToOrderEngineItem({ item, orderItem, platform, tenantId, excludeRefs, excludedDiscountRefs, zeroPriceRefs, orderItemType, applyLoyalty, applyVoucher, keepOptionalModifiersAtBottom, defaultMenuId, soldoutModifiers, }: IConvertCatalogItemToOrderEngineItemParams): IOrderEngineItem;
56
84
  export declare function hasRequiredModifier<T extends IModifier | IOrderEngineModifier>(currentModifiers: T[] | null): boolean;
57
85
  export declare function convertItemToOrderItem(item: IItem | ISimplifiedCatalogItem, menu_id: string | null, platform: PLATFORMS_ENUM | undefined, tenantId: string, orderItemType?: ORDER_ITEM_TYPE_ENUM): IOrderItem;
58
- export declare function setCheckFieldInOrderEngineItem(orderEngineItem: IOrderEngineItem, identifier: string, shouldCheck: boolean): IOrderEngineItem;
86
+ export declare function setCheckFieldInOrderEngineItem(orderEngineItem: IOrderEngineItem, identifier: string, shouldCheck: boolean, chooseExpensiveSegmentPrice?: boolean): IOrderEngineItem;
59
87
  export declare function setIncrementOrderEngineItemQuantity(orderEngineItem: IOrderEngineItem, increment: number): IOrderEngineItem;
60
88
  export declare function setUpdateSelectedOrderEngineOptionQuantity(orderEngineItem: IOrderEngineItem, identifier: string, newQuantity: number, isIncrement?: boolean): IOrderEngineItem;
61
89
  export declare function getFlattenedOrderEngineItemModifiers(modifiers: IOrderEngineModifier[], keepOptionalModifiersAtBottom?: boolean): IOrderEngineModifier[];
@@ -7,6 +7,7 @@ exports.hasMissedRequiredItemModifier = hasMissedRequiredItemModifier;
7
7
  exports.syncOrderEngineItem = syncOrderEngineItem;
8
8
  exports.checkIfModifiersExist = checkIfModifiersExist;
9
9
  exports.makeSpaceForFreeOptions = makeSpaceForFreeOptions;
10
+ exports.applyChooseExpensiveSegmentPrice = applyChooseExpensiveSegmentPrice;
10
11
  exports.convertOrderEngineItemToOrderItem = convertOrderEngineItemToOrderItem;
11
12
  exports.convertItemDiscountToOrderItemDiscount = convertItemDiscountToOrderItemDiscount;
12
13
  exports.convertCatalogItemToOrderEngineItem = convertCatalogItemToOrderEngineItem;
@@ -282,6 +283,100 @@ function makeSpaceForFreeOptions(options, num_free_options) {
282
283
  }
283
284
  return [...defaultPriceOptions, ...nonDefaultOptions].sort((a, b) => a.sort_id - b.sort_id);
284
285
  }
286
+ // ====================================>>><<<======================================
287
+ /**
288
+ * Applies `choose_expensive_segment_price` to an order engine item converted
289
+ * from a half-half setup (top-level modifier groups = segments, single-select
290
+ * each, only 2 or 4 segments).
291
+ *
292
+ * The expensive rule depends on which halves the user actually picked, so it
293
+ * cannot run during `IHalfHalfSetup -> IItem` conversion — it must run after
294
+ * selection. It is invoked automatically by
295
+ * `setCheckFieldInOrderEngineItem` whenever the engine item's `item_type` is
296
+ * `HALF_HALF` and the caller passed the flag.
297
+ *
298
+ * Rule: `price = base + upsell` — the item (option) level upsell is already
299
+ * baked into the option price at conversion. choose_expensive compares the
300
+ * FINAL segment price (option price + required/price-defining modifier
301
+ * prices — e.g. a "Pizza Size" group whose Small/Large/X-Large options are
302
+ * part of the item's price) and raises every cheaper selected segment to the
303
+ * most expensive one. Optional/upsell modifier groups are excluded: they add
304
+ * on top and must not influence the comparison. The IHalfHalfSetup level
305
+ * upsell is NOT part of this rule: it is the converted item's own price and
306
+ * is added once on top of the combined subtotal.
307
+ *
308
+ * All prices here are plain numbers (engine-priced). Idempotent — it only
309
+ * ever raises, never lowers — so it can safely be re-applied (e.g. on
310
+ * submit).
311
+ *
312
+ * Returns the item unchanged when fewer than two segments are selected.
313
+ */
314
+ function applyChooseExpensiveSegmentPrice(orderEngineItem) {
315
+ const segmentGroups = (orderEngineItem.modifiers ?? []).filter((modifier) => modifier.depth === 0);
316
+ if (segmentGroups.length < 2)
317
+ return orderEngineItem;
318
+ // Prices of all SELECTED options of required (price-defining) modifier
319
+ // groups, at any depth — e.g. "Pizza Size" -> "Large 13"" carried under a
320
+ // segment option. Optional/upsell modifier groups are excluded: they add on
321
+ // top and must not influence the comparison.
322
+ const getRequiredOptionPrices = (modifiers) => {
323
+ let total = 0;
324
+ (modifiers ?? []).forEach((modifier) => {
325
+ const isRequired = (modifier.min_num_options != null && modifier.min_num_options > 0) ||
326
+ (modifier.min_aggregate_options_quantity != null && modifier.min_aggregate_options_quantity > 0);
327
+ if (!isRequired)
328
+ return;
329
+ (modifier.options ?? []).forEach((option) => {
330
+ if (!option.default)
331
+ return;
332
+ total += (option.price ?? 0) * (option.quantity || 1);
333
+ total += getRequiredOptionPrices(option.modifiers);
334
+ });
335
+ });
336
+ return total;
337
+ };
338
+ // FINAL segment price = option price (base + item/option level upsell,
339
+ // already merged at conversion) + required (price-defining) modifier prices.
340
+ const getSegmentTotal = (option) => (option.price ?? 0) + getRequiredOptionPrices(option.modifiers);
341
+ // One selected option per segment group (segments are single-select).
342
+ const selections = [];
343
+ let maxSegmentValue = 0;
344
+ for (let g = 0; g < segmentGroups.length; g++) {
345
+ const options = segmentGroups[g].options ?? [];
346
+ for (let o = 0; o < options.length; o++) {
347
+ const option = options[o];
348
+ if (!option.default || option.is_free)
349
+ continue;
350
+ selections.push({ groupIndex: g, optionIndex: o });
351
+ const segmentValue = getSegmentTotal(option);
352
+ if (segmentValue > maxSegmentValue) {
353
+ maxSegmentValue = segmentValue;
354
+ }
355
+ break; // single-select: at most one selected option
356
+ }
357
+ }
358
+ if (selections.length < 2 || maxSegmentValue <= 0)
359
+ return orderEngineItem;
360
+ const modifiers = (orderEngineItem.modifiers ?? []).map((modifier, g) => {
361
+ if (modifier.depth !== 0)
362
+ return modifier;
363
+ const options = (modifier.options ?? []).map((option, o) => {
364
+ const selection = selections.find((s) => s.groupIndex === g && s.optionIndex === o);
365
+ if (selection == null)
366
+ return option;
367
+ const segmentValue = getSegmentTotal(option);
368
+ // Already at (or above) the most expensive final price: keep as is.
369
+ if (segmentValue >= maxSegmentValue)
370
+ return option;
371
+ // Raise the option's own price by the difference so the segment's final
372
+ // price (base + upsell + required modifiers) equals the expensive one.
373
+ // The IHalfHalfSetup upsell (item price) is untouched.
374
+ return { ...option, price: (option.price ?? 0) + (maxSegmentValue - segmentValue) };
375
+ });
376
+ return { ...modifier, options };
377
+ });
378
+ return syncOrderEngineItem({ ...orderEngineItem, modifiers });
379
+ }
285
380
  function convertCatalogItemModifierToOrderEngineItemModifier({ modifiers, orderItemModifiers, platform, tenantId, excludeRefs, zeroPriceRefs, loyaltyRefs, voucherRefs, keepOptionalModifiersAtBottom, soldoutModifiers, depth = 0, }) {
286
381
  function getSortedModifiers(modifiers = []) {
287
382
  const sortedModifiers = modifiers.sort((a, b) => a.sort_id - b.sort_id);
@@ -728,7 +823,7 @@ function convertItemToOrderItem(item, menu_id, platform, tenantId, orderItemType
728
823
  /*
729
824
 
730
825
  */
731
- function setCheckFieldInOrderEngineItem(orderEngineItem, identifier, shouldCheck) {
826
+ function setCheckFieldInOrderEngineItem(orderEngineItem, identifier, shouldCheck, chooseExpensiveSegmentPrice) {
732
827
  const setUpdateOptions = (modifier, ids, level) => {
733
828
  const optionId = ids[level];
734
829
  if (!optionId)
@@ -808,6 +903,17 @@ function setCheckFieldInOrderEngineItem(orderEngineItem, identifier, shouldCheck
808
903
  const allIds = identifier.split('_').filter((id) => id.trim() !== '');
809
904
  const modifiers = setUpdateModifiers(orderEngineItem.modifiers, allIds, 0);
810
905
  const updatedOrderEngineItem = syncOrderEngineItem({ ...orderEngineItem, modifiers });
906
+ // Half-half classic view: `choose_expensive_segment_price` depends on which
907
+ // halves the user actually picked, so it cannot run during
908
+ // `IHalfHalfSetup -> IItem` conversion — it is applied right here, after
909
+ // every selection, whenever the caller passes the setup flag. It compares
910
+ // the FINAL segment prices (option base + item upsell + required/price-
911
+ // defining modifiers — all baked at conversion) and raises the cheaper ones
912
+ // to the most expensive. Idempotent: it never lowers a price, so re-running
913
+ // is safe.
914
+ if (orderEngineItem.item_type === constants_1.ORDER_ITEM_TYPE_ENUM.HALF_HALF && chooseExpensiveSegmentPrice === true) {
915
+ return applyChooseExpensiveSegmentPrice(updatedOrderEngineItem);
916
+ }
811
917
  return updatedOrderEngineItem;
812
918
  }
813
919
  function setIncrementOrderEngineItemQuantity(orderEngineItem, increment) {
@@ -9,6 +9,8 @@ function convertHalfHalfSetupToSimplifiedHalfHalfSetup(halfhalfSetup, tenantId)
9
9
  is_discount_percentage: halfhalfSetup.is_discount_percentage || undefined,
10
10
  discount_amount: (0, minified_catalog_1.convertOriginalPlatformNumToMinifiedPlatformNum)(halfhalfSetup.discount_amount),
11
11
  item_special_hours: (0, minified_catalog_1.convertOriginalSpecialHoursToMinifiedSpecialHours)(halfhalfSetup.item_special_hours),
12
+ // Only sent when true (keeps the minified payload lean, same as above).
13
+ choose_expensive_segment_price: halfhalfSetup.choose_expensive_segment_price || undefined,
12
14
  _id: halfhalfSetup._id,
13
15
  category_id: halfhalfSetup.category_id,
14
16
  name: halfhalfSetup.name,
@@ -92,10 +92,16 @@ function applyModifierSpecialRefRules(modifiers, exclusiveRefs, excludedRefs) {
92
92
  let result = modifiers.map((modifier) => {
93
93
  const isModifierExclusive = exclusiveRefs.includes(modifier.ref);
94
94
  const options = modifier.options.map((option) => {
95
+ // Recurse: modifiers -> options -> modifiers -> options ...
96
+ // (option-level modifiers carry their own nested modifier/option tree
97
+ // that must honor the same ref rules — e.g. half-half: segment -> item
98
+ // -> "Pizza Size" -> "Large 13" -> "Drinks".)
99
+ const nestedModifiers = applyModifierSpecialRefRules(option.modifiers, exclusiveRefs, excludedRefs);
100
+ const updatedOption = { ...option, modifiers: nestedModifiers };
95
101
  if (isModifierExclusive || exclusiveRefs.includes(option.ref)) {
96
- return { ...option, price: null };
102
+ return { ...updatedOption, price: null };
97
103
  }
98
- return option;
104
+ return updatedOption;
99
105
  });
100
106
  return { ...modifier, options };
101
107
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@managesome/eposmatic-toolkit",
3
- "version": "0.2.695",
3
+ "version": "0.2.696",
4
4
  "description": "A Toolkit Library for Eposmatic",
5
5
  "main": "lib/index.js",
6
6
  "types": "lib/index.d.ts",