@managesome/eposmatic-toolkit 0.2.695 → 0.2.699

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,39 @@ 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
22
+ * EVERY segment option (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 the SELECTED ones so their final
25
+ * segment price matches the setup's most expensive option — no matter which
26
+ * halves the user picks (same semantics as the modern workable converter).
27
+ * The raise is applied to the FIRST PRICED element along the segment's price
28
+ * chain: the segment option's own price when non-zero (like the modern flow),
29
+ * else the first priced required leaf ("First Half -> ROMA -> Pizza Size ->
30
+ * Large 13\"") — see `findRaiseTarget`. Optional/upsell modifier groups are
31
+ * excluded: they add on top and must not influence the comparison. The
32
+ * IHalfHalfSetup level upsell is NOT part of this rule: it is the converted
33
+ * item's own price and is added once on top of the combined subtotal.
34
+ *
35
+ * All prices here are plain numbers (engine-priced). Idempotent — it only
36
+ * ever raises, never lowers — so it can safely be re-applied (e.g. on
37
+ * submit).
38
+ *
39
+ * Returns the item unchanged when no segment option is selected.
40
+ */
41
+ export declare function applyChooseExpensiveSegmentPrice(orderEngineItem: IOrderEngineItem): IOrderEngineItem;
9
42
  export type IOrderEngineItemRewardClaim = {
10
43
  type: 'offer';
11
44
  offerId: string;
@@ -55,7 +88,7 @@ interface IConvertCatalogItemToOrderEngineItemParams {
55
88
  export declare function convertCatalogItemToOrderEngineItem({ item, orderItem, platform, tenantId, excludeRefs, excludedDiscountRefs, zeroPriceRefs, orderItemType, applyLoyalty, applyVoucher, keepOptionalModifiersAtBottom, defaultMenuId, soldoutModifiers, }: IConvertCatalogItemToOrderEngineItemParams): IOrderEngineItem;
56
89
  export declare function hasRequiredModifier<T extends IModifier | IOrderEngineModifier>(currentModifiers: T[] | null): boolean;
57
90
  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;
91
+ export declare function setCheckFieldInOrderEngineItem(orderEngineItem: IOrderEngineItem, identifier: string, shouldCheck: boolean, chooseExpensiveSegmentPrice?: boolean): IOrderEngineItem;
59
92
  export declare function setIncrementOrderEngineItemQuantity(orderEngineItem: IOrderEngineItem, increment: number): IOrderEngineItem;
60
93
  export declare function setUpdateSelectedOrderEngineOptionQuantity(orderEngineItem: IOrderEngineItem, identifier: string, newQuantity: number, isIncrement?: boolean): IOrderEngineItem;
61
94
  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,157 @@ 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
300
+ * EVERY segment option (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 the SELECTED ones so their final
303
+ * segment price matches the setup's most expensive option — no matter which
304
+ * halves the user picks (same semantics as the modern workable converter).
305
+ * The raise is applied to the FIRST PRICED element along the segment's price
306
+ * chain: the segment option's own price when non-zero (like the modern flow),
307
+ * else the first priced required leaf ("First Half -> ROMA -> Pizza Size ->
308
+ * Large 13\"") — see `findRaiseTarget`. Optional/upsell modifier groups are
309
+ * excluded: they add on top and must not influence the comparison. The
310
+ * IHalfHalfSetup level upsell is NOT part of this rule: it is the converted
311
+ * item's own price and is added once on top of the combined subtotal.
312
+ *
313
+ * All prices here are plain numbers (engine-priced). Idempotent — it only
314
+ * ever raises, never lowers — so it can safely be re-applied (e.g. on
315
+ * submit).
316
+ *
317
+ * Returns the item unchanged when no segment option is selected.
318
+ */
319
+ function applyChooseExpensiveSegmentPrice(orderEngineItem) {
320
+ const segmentGroups = (orderEngineItem.modifiers ?? []).filter((modifier) => modifier.depth === 0);
321
+ if (segmentGroups.length < 2)
322
+ return orderEngineItem;
323
+ // Prices of ALL options of required (price-defining) modifier groups, at
324
+ // any depth — e.g. "Pizza Size" -> "Large 13"" is part of the item's price
325
+ // whichever size is picked (mirrors `getSegmentItemTotalPrice` used by the
326
+ // modern workable converter). Optional/upsell modifier groups are excluded:
327
+ // they add on top and must not influence the comparison.
328
+ const getRequiredOptionPrices = (modifiers) => {
329
+ let total = 0;
330
+ (modifiers ?? []).forEach((modifier) => {
331
+ const isRequired = (modifier.min_num_options != null && modifier.min_num_options > 0) ||
332
+ (modifier.min_aggregate_options_quantity != null && modifier.min_aggregate_options_quantity > 0);
333
+ if (!isRequired)
334
+ return;
335
+ (modifier.options ?? []).forEach((option) => {
336
+ total += (option.price ?? 0) * (option.quantity || 1);
337
+ total += getRequiredOptionPrices(option.modifiers);
338
+ });
339
+ });
340
+ return total;
341
+ };
342
+ // Segment price = option price (base + item/option level upsell, already
343
+ // merged at conversion) + required (price-defining) modifier prices.
344
+ const getSegmentTotal = (option) => (option.price ?? 0) + getRequiredOptionPrices(option.modifiers);
345
+ // Max over ALL segment options (the setup's most expensive segment), not
346
+ // just the selected ones — otherwise the charged price would depend on
347
+ // which halves the user picks. Free options never drive the comparison.
348
+ let maxSegmentValue = 0;
349
+ for (let g = 0; g < segmentGroups.length; g++) {
350
+ const options = segmentGroups[g].options ?? [];
351
+ for (let o = 0; o < options.length; o++) {
352
+ const option = options[o];
353
+ if (option.is_free)
354
+ continue;
355
+ const segmentValue = getSegmentTotal(option);
356
+ if (segmentValue > maxSegmentValue) {
357
+ maxSegmentValue = segmentValue;
358
+ }
359
+ }
360
+ }
361
+ if (maxSegmentValue <= 0)
362
+ return orderEngineItem;
363
+ // One selected option per segment group (segments are single-select).
364
+ const selections = [];
365
+ for (let g = 0; g < segmentGroups.length; g++) {
366
+ const options = segmentGroups[g].options ?? [];
367
+ for (let o = 0; o < options.length; o++) {
368
+ const option = options[o];
369
+ if (!option.default || option.is_free)
370
+ continue;
371
+ selections.push({ groupIndex: g, optionIndex: o });
372
+ break; // single-select: at most one selected option
373
+ }
374
+ }
375
+ if (selections.length === 0)
376
+ return orderEngineItem;
377
+ // RULE for where the raise lands: on the FIRST PRICED element along the
378
+ // segment's price chain —
379
+ // 1. the segment option's own price (the item base) when it is non-zero
380
+ // (same as the modern flow, which raises the item price), or
381
+ // 2. otherwise, the first priced required leaf down the chain: the single
382
+ // option of a single-option required group (its price is fixed — e.g.
383
+ // "ROMA -> Pizza Size -> Large 13\""), or the currently selected
384
+ // option of a multi-option required group,
385
+ // 3. otherwise, the segment option's own price (even when 0).
386
+ // This keeps the raise where the price actually lives and never invents a
387
+ // price on an empty slot or an unselected option.
388
+ const findRaiseTarget = (option) => {
389
+ if ((option.price ?? 0) > 0)
390
+ return option;
391
+ for (const modifier of option.modifiers ?? []) {
392
+ const isRequired = (modifier.min_num_options != null && modifier.min_num_options > 0) ||
393
+ (modifier.min_aggregate_options_quantity != null && modifier.min_aggregate_options_quantity > 0);
394
+ if (!isRequired)
395
+ continue;
396
+ const options = modifier.options ?? [];
397
+ const candidate = options.length === 1 ? options[0] : (options.find((opt) => opt.default) ?? null);
398
+ if (candidate != null && (candidate.price ?? 0) > 0)
399
+ return candidate;
400
+ }
401
+ return null;
402
+ };
403
+ const raiseSegmentOption = (option, delta) => {
404
+ const target = findRaiseTarget(option);
405
+ if (target == null || target._id === option._id) {
406
+ return { ...option, price: (option.price ?? 0) + delta };
407
+ }
408
+ return {
409
+ ...option,
410
+ modifiers: option.modifiers.map((modifier) => ({
411
+ ...modifier,
412
+ options: modifier.options.map((opt) => opt._id === target._id ? { ...opt, price: (opt.price ?? 0) + delta } : opt),
413
+ })),
414
+ };
415
+ };
416
+ const modifiers = (orderEngineItem.modifiers ?? []).map((modifier, g) => {
417
+ if (modifier.depth !== 0)
418
+ return modifier;
419
+ const options = (modifier.options ?? []).map((option, o) => {
420
+ const selection = selections.find((s) => s.groupIndex === g && s.optionIndex === o);
421
+ if (selection == null)
422
+ return option;
423
+ const segmentValue = getSegmentTotal(option);
424
+ // Already at (or above) the most expensive segment price: keep as is.
425
+ if (segmentValue >= maxSegmentValue)
426
+ return option;
427
+ // Raise by the difference so the segment's final price (base + upsell +
428
+ // required modifiers) equals the expensive one — applied to the priced
429
+ // leaf when available (see `raiseSegmentOption`). The IHalfHalfSetup
430
+ // upsell (item price) is untouched.
431
+ return raiseSegmentOption(option, maxSegmentValue - segmentValue);
432
+ });
433
+ return { ...modifier, options };
434
+ });
435
+ return syncOrderEngineItem({ ...orderEngineItem, modifiers });
436
+ }
285
437
  function convertCatalogItemModifierToOrderEngineItemModifier({ modifiers, orderItemModifiers, platform, tenantId, excludeRefs, zeroPriceRefs, loyaltyRefs, voucherRefs, keepOptionalModifiersAtBottom, soldoutModifiers, depth = 0, }) {
286
438
  function getSortedModifiers(modifiers = []) {
287
439
  const sortedModifiers = modifiers.sort((a, b) => a.sort_id - b.sort_id);
@@ -395,6 +547,24 @@ function convertCatalogItemModifierToOrderEngineItemModifier({ modifiers, orderI
395
547
  const options = makeSpaceForFreeOptions(orderEngineSingleModifier.options, modifier.num_free_options);
396
548
  orderEngineSingleModifier.options = options;
397
549
  }
550
+ // A required modifier with exactly ONE selectable option left has no real
551
+ // choice — auto-select it so the user doesn't have to pick the only
552
+ // option (e.g. "Half/Half Pizza -> Pizza Size -> Large 13\""). Applied
553
+ // recursively: nested required groups under an option get the same
554
+ // treatment; they only reveal once their parent option is selected.
555
+ const isRequiredModifier = (modifier.min_num_options != null && modifier.min_num_options > 0) ||
556
+ (modifier.min_aggregate_options_quantity != null && modifier.min_aggregate_options_quantity > 0);
557
+ if (isRequiredModifier && orderEngineSingleModifier.options.length === 1) {
558
+ const singleOption = orderEngineSingleModifier.options[0];
559
+ if (!singleOption.default) {
560
+ orderEngineSingleModifier.options[0] = {
561
+ ...singleOption,
562
+ default: true,
563
+ quantity: modifier.min_option_choice_quantity || 1,
564
+ };
565
+ totalDefaultOptions = 1;
566
+ }
567
+ }
398
568
  orderEngineSingleModifier.default = totalDefaultOptions > 0;
399
569
  orderEngineModifiers.push(orderEngineSingleModifier);
400
570
  }
@@ -728,7 +898,7 @@ function convertItemToOrderItem(item, menu_id, platform, tenantId, orderItemType
728
898
  /*
729
899
 
730
900
  */
731
- function setCheckFieldInOrderEngineItem(orderEngineItem, identifier, shouldCheck) {
901
+ function setCheckFieldInOrderEngineItem(orderEngineItem, identifier, shouldCheck, chooseExpensiveSegmentPrice) {
732
902
  const setUpdateOptions = (modifier, ids, level) => {
733
903
  const optionId = ids[level];
734
904
  if (!optionId)
@@ -808,6 +978,16 @@ function setCheckFieldInOrderEngineItem(orderEngineItem, identifier, shouldCheck
808
978
  const allIds = identifier.split('_').filter((id) => id.trim() !== '');
809
979
  const modifiers = setUpdateModifiers(orderEngineItem.modifiers, allIds, 0);
810
980
  const updatedOrderEngineItem = syncOrderEngineItem({ ...orderEngineItem, modifiers });
981
+ // Half-half classic view: `choose_expensive_segment_price` depends on which
982
+ // halves the user actually picked, so it cannot run during
983
+ // `IHalfHalfSetup -> IItem` conversion — it is applied right here, after
984
+ // every selection, whenever the caller passes the setup flag. It compares
985
+ // EVERY segment option (option base + item upsell + required/price-defining
986
+ // modifiers) and raises the selected ones to the setup's most expensive
987
+ // segment. Idempotent: it never lowers a price, so re-running is safe.
988
+ if (orderEngineItem.item_type === constants_1.ORDER_ITEM_TYPE_ENUM.HALF_HALF && chooseExpensiveSegmentPrice === true) {
989
+ return applyChooseExpensiveSegmentPrice(updatedOrderEngineItem);
990
+ }
811
991
  return updatedOrderEngineItem;
812
992
  }
813
993
  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
  });
@@ -56,13 +56,18 @@ describe('convertHalfHalfSetupToSimplifiedHalfHalfSetup', () => {
56
56
  expect(simplified).not.toHaveProperty('items');
57
57
  expect(simplified).not.toHaveProperty('excluded_refs');
58
58
  expect(simplified).not.toHaveProperty('exclusive_refs');
59
- expect(simplified).not.toHaveProperty('choose_expensive_segment_price');
60
59
  expect(simplified).not.toHaveProperty('upsell_price');
61
60
  });
61
+ it('carries choose_expensive_segment_price through', () => {
62
+ const simplified = (0, simplified_halfhalf_1.convertHalfHalfSetupToSimplifiedHalfHalfSetup)(makeHalfHalfSetup({ choose_expensive_segment_price: true }), TENANT_ID);
63
+ expect(simplified.choose_expensive_segment_price).toBe(true);
64
+ });
65
+ it('omits choose_expensive_segment_price when not enabled', () => {
66
+ const simplified = (0, simplified_halfhalf_1.convertHalfHalfSetupToSimplifiedHalfHalfSetup)(makeHalfHalfSetup({ choose_expensive_segment_price: false }), TENANT_ID);
67
+ expect(simplified.choose_expensive_segment_price).toBeUndefined();
68
+ });
62
69
  it('minifies setup prices', () => {
63
- const simplified = (0, simplified_halfhalf_1.convertHalfHalfSetupToSimplifiedHalfHalfSetup)(makeHalfHalfSetup({
64
- discount_amount: { BASE_PRICE: 300 },
65
- }), TENANT_ID);
70
+ const simplified = (0, simplified_halfhalf_1.convertHalfHalfSetupToSimplifiedHalfHalfSetup)(makeHalfHalfSetup({ discount_amount: { BASE_PRICE: 300 } }), TENANT_ID);
66
71
  expect(simplified.discount_amount).toBe(300);
67
72
  });
68
73
  it('handles a halfhalf sold out for the tenant', () => {
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.699",
4
4
  "description": "A Toolkit Library for Eposmatic",
5
5
  "main": "lib/index.js",
6
6
  "types": "lib/index.d.ts",