@managesome/eposmatic-toolkit 0.3.7 → 0.3.9

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.
Files changed (439) hide show
  1. package/esm/constants/ANALYTICS.js +146 -0
  2. package/esm/constants/API_ERRORS.js +6 -0
  3. package/esm/constants/COMMON.js +369 -0
  4. package/esm/constants/DELIVERY.js +45 -0
  5. package/esm/constants/DIALER_ENUMS.js +11 -0
  6. package/esm/constants/ENUMS.js +1988 -0
  7. package/esm/constants/FBR_ENUMS.js +18 -0
  8. package/esm/constants/HUBRISE_ENUMS.js +179 -0
  9. package/esm/constants/INTERNAL_ENUMS.js +49 -0
  10. package/esm/constants/NOTIFICATIONS.js +6 -0
  11. package/esm/constants/ORDER.js +251 -0
  12. package/esm/constants/PRA_ENUMS.js +18 -0
  13. package/esm/constants/REPORT_WEBVIEW.js +28 -0
  14. package/esm/constants/RFQ_GO.js +83 -0
  15. package/esm/constants/SMARTPAY_ENUMS.js +55 -0
  16. package/esm/constants/SOCKET.js +149 -0
  17. package/esm/constants/SRB_ENUMS.js +13 -0
  18. package/esm/constants/SWITCHPAY.js +28 -0
  19. package/esm/constants/TENANT_ENUMS.js +90 -0
  20. package/esm/constants/TENANT_PURCHASE_ORDER.js +91 -0
  21. package/esm/constants/WALLET.js +51 -0
  22. package/esm/constants/WAREHOUSE_ANALYTICS.js +28 -0
  23. package/esm/constants/WAREHOUSE_ENUMS.js +420 -0
  24. package/esm/constants/WAREHOUSE_PURCHASE_ORDER.js +97 -0
  25. package/esm/constants/WEBVIEW.js +43 -0
  26. package/esm/constants/WORKER_ENDPOINTS.js +79 -0
  27. package/esm/constants/index.js +27 -0
  28. package/esm/constants/types.js +2 -0
  29. package/esm/helpers/fbr/generate-invoice.js +94 -0
  30. package/esm/helpers/fbr/index.js +1 -0
  31. package/esm/helpers/hubrise/hubrise-catalog.js +304 -0
  32. package/esm/helpers/hubrise/index.js +1 -0
  33. package/esm/helpers/index.js +9 -0
  34. package/esm/helpers/kpra/generate-invoice.js +26 -0
  35. package/esm/helpers/kpra/index.js +1 -0
  36. package/esm/helpers/order/generate-order.js +508 -0
  37. package/esm/helpers/order/generate-warehouse-internal-movement.js +71 -0
  38. package/esm/helpers/order/generate-warehouse-purchase-order-rfq.js +176 -0
  39. package/esm/helpers/order/generate-warehouse-purchase-order.js +187 -0
  40. package/esm/helpers/order/generate-warehouse-sale-order-rfq.js +176 -0
  41. package/esm/helpers/order/generate-warehouse-sale-order.js +149 -0
  42. package/esm/helpers/order/index.js +6 -0
  43. package/esm/helpers/pra/generate-invoice.js +94 -0
  44. package/esm/helpers/pra/index.js +1 -0
  45. package/esm/helpers/srb/generate-invoice.js +68 -0
  46. package/esm/helpers/srb/index.js +1 -0
  47. package/esm/helpers/store/all-orders-actions.js +17 -0
  48. package/esm/helpers/store/all-tenant-purchase-orders-actions.js +45 -0
  49. package/esm/helpers/store/all-warehouse-purchase-order-rfqs-actions.js +66 -0
  50. package/esm/helpers/store/all-warehouse-purchase-order-vendor-return-actions.js +50 -0
  51. package/esm/helpers/store/all-warehouse-purchase-orders-actions.js +49 -0
  52. package/esm/helpers/store/all-warehouse-sale-order-invoices-actions.js +132 -0
  53. package/esm/helpers/store/all-warehouse-sale-order-rfqs-actions.js +66 -0
  54. package/esm/helpers/store/all-warehouse-sale-orders-actions.js +72 -0
  55. package/esm/helpers/store/cart-actions.js +3563 -0
  56. package/esm/helpers/store/catalog-actions.js +379 -0
  57. package/esm/helpers/store/common-order-actions.js +937 -0
  58. package/esm/helpers/store/common-tenant-purchase-order-actions.js +440 -0
  59. package/esm/helpers/store/common-warehouse-internal-movement-actions.js +95 -0
  60. package/esm/helpers/store/common-warehouse-purchase-order-actions.js +530 -0
  61. package/esm/helpers/store/common-warehouse-purchase-order-receipt-actions.js +33 -0
  62. package/esm/helpers/store/common-warehouse-purchase-order-rfq-actions.js +523 -0
  63. package/esm/helpers/store/common-warehouse-purchase-order-vendor-return-actions.js +25 -0
  64. package/esm/helpers/store/common-warehouse-sale-order-actions.js +483 -0
  65. package/esm/helpers/store/common-warehouse-sale-order-invoice-actions.js +54 -0
  66. package/esm/helpers/store/common-warehouse-sale-order-rfq-actions.js +523 -0
  67. package/esm/helpers/store/index.js +26 -0
  68. package/esm/helpers/store/offline-ordering.js +251 -0
  69. package/esm/helpers/store/tenant-purchase-orders-cart-actions.js +379 -0
  70. package/esm/helpers/store/warehouse-purchase-order-rfq-cart-actions.js +360 -0
  71. package/esm/helpers/store/warehouse-purchase-orders-cart-actions.js +470 -0
  72. package/esm/helpers/store/warehouse-sale-order-rfq-cart-actions.js +359 -0
  73. package/esm/helpers/store/warehouse-sale-orders-cart-actions.js +456 -0
  74. package/esm/helpers/types/api-types.js +1 -0
  75. package/esm/helpers/types/cart-actions.js +1 -0
  76. package/esm/helpers/types/cart-helpers.js +1 -0
  77. package/esm/helpers/types/catalog.js +1 -0
  78. package/esm/helpers/types/common.js +1 -0
  79. package/esm/helpers/types/deliverect_menu.js +1 -0
  80. package/esm/helpers/types/email-templates.js +1 -0
  81. package/esm/helpers/types/fbr-generate-invoice.js +1 -0
  82. package/esm/helpers/types/halfhalf.js +1 -0
  83. package/esm/helpers/types/hubrise_catalog.js +1 -0
  84. package/esm/helpers/types/hubrise_customers.js +1 -0
  85. package/esm/helpers/types/hubrise_deliveries.js +1 -0
  86. package/esm/helpers/types/hubrise_location.js +1 -0
  87. package/esm/helpers/types/hubrise_orders.js +1 -0
  88. package/esm/helpers/types/index.js +33 -0
  89. package/esm/helpers/types/internal-leads.js +1 -0
  90. package/esm/helpers/types/inventory-catalog.js +1 -0
  91. package/esm/helpers/types/kpra-generate-invoice.js +1 -0
  92. package/esm/helpers/types/marketing.js +1 -0
  93. package/esm/helpers/types/order-engine.js +1 -0
  94. package/esm/helpers/types/pra-generate-invoice.js +1 -0
  95. package/esm/helpers/types/report-webview.js +1 -0
  96. package/esm/helpers/types/reports.js +1 -0
  97. package/esm/helpers/types/smartpay-apis.js +2 -0
  98. package/esm/helpers/types/specials.js +1 -0
  99. package/esm/helpers/types/split_bill.js +1 -0
  100. package/esm/helpers/types/srb-generate-invoice.js +1 -0
  101. package/esm/helpers/types/switchpay.js +1 -0
  102. package/esm/helpers/types/tenant-purchase-order-cart-actions.js +1 -0
  103. package/esm/helpers/types/warehouse-catalog.js +1 -0
  104. package/esm/helpers/types/warehouse-purchase-order-cart-actions.js +1 -0
  105. package/esm/helpers/types/warehouse-purchase-order-rfq-cart-actions.js +1 -0
  106. package/esm/helpers/types/warehouse-sale-order-cart-actions.js +1 -0
  107. package/esm/helpers/types/warehouse-sale-order-rfq-cart-actions.js +1 -0
  108. package/esm/helpers/types/workers.js +1 -0
  109. package/esm/helpers/utils/asaanbill-identifier-helpers.js +31 -0
  110. package/esm/helpers/utils/business-day-helpers.js +201 -0
  111. package/esm/helpers/utils/cart-helpers.js +156 -0
  112. package/esm/helpers/utils/catalog-conversion.js +129 -0
  113. package/esm/helpers/utils/code-redemption-helpers.js +452 -0
  114. package/esm/helpers/utils/color-helpers.js +31 -0
  115. package/esm/helpers/utils/common.js +368 -0
  116. package/esm/helpers/utils/crypt.js +40 -0
  117. package/esm/helpers/utils/customers-helpers.js +15 -0
  118. package/esm/helpers/utils/delivery-area-helpers.js +42 -0
  119. package/esm/helpers/utils/delivery-helpers.js +87 -0
  120. package/esm/helpers/utils/denominations-helpers.js +53 -0
  121. package/esm/helpers/utils/dinein.js +39 -0
  122. package/esm/helpers/utils/discount-helpers.js +55 -0
  123. package/esm/helpers/utils/email-helpers.js +111 -0
  124. package/esm/helpers/utils/error-helpers.js +14 -0
  125. package/esm/helpers/utils/expense.js +26 -0
  126. package/esm/helpers/utils/getFormFieldsDiff.js +15 -0
  127. package/esm/helpers/utils/gift-card-helpers.js +258 -0
  128. package/esm/helpers/utils/halfhalf-setup-helpers.js +779 -0
  129. package/esm/helpers/utils/hourly-comparison-report-helpers.js +851 -0
  130. package/esm/helpers/utils/hr-helpers.js +62 -0
  131. package/esm/helpers/utils/hubrise-utils.js +32 -0
  132. package/esm/helpers/utils/image-helpers.js +95 -0
  133. package/esm/helpers/utils/image-url-helpers.js +96 -0
  134. package/esm/helpers/utils/index.js +96 -0
  135. package/esm/helpers/utils/ingredients.js +26 -0
  136. package/esm/helpers/utils/internal-amount-helpers.js +49 -0
  137. package/esm/helpers/utils/inventory.js +123 -0
  138. package/esm/helpers/utils/inventory_entries.js +91 -0
  139. package/esm/helpers/utils/inventory_transactions.js +91 -0
  140. package/esm/helpers/utils/item-report-helpers.js +2603 -0
  141. package/esm/helpers/utils/items-comparison-report-helpers.js +1057 -0
  142. package/esm/helpers/utils/kds-helpers.js +43 -0
  143. package/esm/helpers/utils/location-helpers.js +13 -0
  144. package/esm/helpers/utils/menu-helpers.js +44 -0
  145. package/esm/helpers/utils/minified-catalog.js +428 -0
  146. package/esm/helpers/utils/offer-apply-helpers.js +613 -0
  147. package/esm/helpers/utils/offers-helpers.js +3351 -0
  148. package/esm/helpers/utils/operational-roles-helpers.js +33 -0
  149. package/esm/helpers/utils/order-engine.js +1409 -0
  150. package/esm/helpers/utils/order-history.js +208 -0
  151. package/esm/helpers/utils/payment-comparison-report-helpers.js +873 -0
  152. package/esm/helpers/utils/payment-helpers.js +302 -0
  153. package/esm/helpers/utils/pdf-generator.js +110 -0
  154. package/esm/helpers/utils/platform-catalog.js +306 -0
  155. package/esm/helpers/utils/platform-num.js +188 -0
  156. package/esm/helpers/utils/platform-specific-tenant-shifts.js +19 -0
  157. package/esm/helpers/utils/price-conversion.js +24 -0
  158. package/esm/helpers/utils/printer-helpers.js +319 -0
  159. package/esm/helpers/utils/public-holidays-helpers.js +8 -0
  160. package/esm/helpers/utils/ratings-comparison-report-helpers.js +1187 -0
  161. package/esm/helpers/utils/receipt-engine.js +1050 -0
  162. package/esm/helpers/utils/review-helpers.js +391 -0
  163. package/esm/helpers/utils/rider-tracking.js +12 -0
  164. package/esm/helpers/utils/riders-report-helpers.js +1590 -0
  165. package/esm/helpers/utils/sales-comparison-report-helpers.js +1259 -0
  166. package/esm/helpers/utils/sales-comparitive-report-helpers.js +939 -0
  167. package/esm/helpers/utils/sales-overview-report-helpers.js +1046 -0
  168. package/esm/helpers/utils/sales-summary-report-helpers.js +877 -0
  169. package/esm/helpers/utils/scan-code-helpers.js +31 -0
  170. package/esm/helpers/utils/selection-model.js +68 -0
  171. package/esm/helpers/utils/shift-window-helpers.js +148 -0
  172. package/esm/helpers/utils/simplified-catalog.js +107 -0
  173. package/esm/helpers/utils/simplified-halfhalf.js +101 -0
  174. package/esm/helpers/utils/simplified-specials.js +107 -0
  175. package/esm/helpers/utils/simplified-tenant.js +411 -0
  176. package/esm/helpers/utils/specials-helpers.js +727 -0
  177. package/esm/helpers/utils/tenant-calendar-helpers.js +67 -0
  178. package/esm/helpers/utils/tenant-cash-drawer-sessions-helpers.js +248 -0
  179. package/esm/helpers/utils/tenant-cash-drawers-helpers.js +31 -0
  180. package/esm/helpers/utils/tenant-cash-in-out-helpers.js +47 -0
  181. package/esm/helpers/utils/tenant-day-sessions-helpers.js +167 -0
  182. package/esm/helpers/utils/tenant-instore-shift-sessions-helpers.js +227 -0
  183. package/esm/helpers/utils/tenant-staff-helpers.js +19 -0
  184. package/esm/helpers/utils/tenant_cash_in_hand_transactions.js +31 -0
  185. package/esm/helpers/utils/time-helpers.js +142 -0
  186. package/esm/helpers/utils/void-items-report-helpers.js +529 -0
  187. package/esm/helpers/utils/void-order-items-helpers.js +32 -0
  188. package/esm/helpers/utils/voidations-summary-report-helpers.js +800 -0
  189. package/esm/helpers/utils/wallet-helpers.js +22 -0
  190. package/esm/helpers/utils/wallet-redemption-helpers.js +46 -0
  191. package/esm/helpers/utils/warehouse-catalog-conversion.js +117 -0
  192. package/esm/helpers/utils/warehouse-inventory.js +59 -0
  193. package/esm/helpers/utils/warehouse-purchase-order-engine.js +27 -0
  194. package/esm/helpers/utils/warehouse-purchase-order-receipt-engine.js +205 -0
  195. package/esm/helpers/utils/warehouse-purchase-order-x-report-helpers.js +1432 -0
  196. package/esm/helpers/utils/warehouse-sale-order-engine.js +27 -0
  197. package/esm/helpers/utils/warehouse-sale-order-receipt-engine.js +207 -0
  198. package/esm/helpers/utils/warehouse-sale-order-x-report-helpers.js +1 -0
  199. package/esm/helpers/utils/warehouse-sale-x-report-helpers.js +1434 -0
  200. package/esm/helpers/utils/warehouse-settings-helpers.js +37 -0
  201. package/esm/helpers/utils/warehouse-void-purchase-order-items-helpers.js +34 -0
  202. package/esm/helpers/utils/warehouse-void-purchase-order-items-report-helpers.js +18 -0
  203. package/esm/helpers/utils/warehouse-void-sale-order-items-helpers.js +34 -0
  204. package/esm/helpers/utils/warehouse-void-sale-order-items-report-helpers.js +18 -0
  205. package/esm/helpers/utils/warehouse_inventory_transactions.js +91 -0
  206. package/esm/helpers/utils/x-report-helpers.js +1850 -0
  207. package/esm/index.js +3 -0
  208. package/esm/schemas/index.js +2 -0
  209. package/esm/schemas/models/app_configs.js +36 -0
  210. package/esm/schemas/models/applied_order_discounts.js +103 -0
  211. package/esm/schemas/models/brands.js +56 -0
  212. package/esm/schemas/models/categories.js +74 -0
  213. package/esm/schemas/models/close_dates.js +63 -0
  214. package/esm/schemas/models/common-models.js +449 -0
  215. package/esm/schemas/models/courses.js +62 -0
  216. package/esm/schemas/models/customer_redemptions.js +82 -0
  217. package/esm/schemas/models/customers.js +269 -0
  218. package/esm/schemas/models/deliveries.js +137 -0
  219. package/esm/schemas/models/delivery_areas.js +97 -0
  220. package/esm/schemas/models/dinein_floors.js +55 -0
  221. package/esm/schemas/models/dinein_tables.js +97 -0
  222. package/esm/schemas/models/dinein_tables_fingerprints.js +96 -0
  223. package/esm/schemas/models/discounts.js +87 -0
  224. package/esm/schemas/models/expense_categories.js +61 -0
  225. package/esm/schemas/models/expense_details.js +130 -0
  226. package/esm/schemas/models/gift_cards.js +342 -0
  227. package/esm/schemas/models/halfhalf_setup.js +142 -0
  228. package/esm/schemas/models/index.js +111 -0
  229. package/esm/schemas/models/internal_customers.js +139 -0
  230. package/esm/schemas/models/internal_invoices.js +119 -0
  231. package/esm/schemas/models/internal_leads.js +78 -0
  232. package/esm/schemas/models/internal_operational_roles.js +85 -0
  233. package/esm/schemas/models/internal_staffs.js +65 -0
  234. package/esm/schemas/models/inventories.js +103 -0
  235. package/esm/schemas/models/inventory_categories.js +52 -0
  236. package/esm/schemas/models/inventory_transactions.js +143 -0
  237. package/esm/schemas/models/item_transactions.js +117 -0
  238. package/esm/schemas/models/items.js +341 -0
  239. package/esm/schemas/models/marketing_fingerprints.js +92 -0
  240. package/esm/schemas/models/menus.js +66 -0
  241. package/esm/schemas/models/messaging_devices.js +99 -0
  242. package/esm/schemas/models/modifier_extras.js +120 -0
  243. package/esm/schemas/models/offers.js +470 -0
  244. package/esm/schemas/models/offers_fingerprints.js +61 -0
  245. package/esm/schemas/models/operational_roles.js +155 -0
  246. package/esm/schemas/models/orders.js +1051 -0
  247. package/esm/schemas/models/printer_settings.js +245 -0
  248. package/esm/schemas/models/public_holidays.js +58 -0
  249. package/esm/schemas/models/reservations.js +127 -0
  250. package/esm/schemas/models/reviews.js +145 -0
  251. package/esm/schemas/models/rewards_usage.js +61 -0
  252. package/esm/schemas/models/riders.js +75 -0
  253. package/esm/schemas/models/specials.js +169 -0
  254. package/esm/schemas/models/staff_shifts.js +66 -0
  255. package/esm/schemas/models/tenant-activity-logs.js +126 -0
  256. package/esm/schemas/models/tenant_active_jobs.js +77 -0
  257. package/esm/schemas/models/tenant_calendar.js +89 -0
  258. package/esm/schemas/models/tenant_cash_drawer_sessions.js +208 -0
  259. package/esm/schemas/models/tenant_cash_drawers.js +60 -0
  260. package/esm/schemas/models/tenant_cash_in_hand_transactions.js +69 -0
  261. package/esm/schemas/models/tenant_cash_in_out.js +104 -0
  262. package/esm/schemas/models/tenant_clients.js +66 -0
  263. package/esm/schemas/models/tenant_day_sessions.js +166 -0
  264. package/esm/schemas/models/tenant_hr_attendance_records.js +87 -0
  265. package/esm/schemas/models/tenant_hr_biometric_enrollments.js +69 -0
  266. package/esm/schemas/models/tenant_hr_departments.js +42 -0
  267. package/esm/schemas/models/tenant_hr_documents.js +71 -0
  268. package/esm/schemas/models/tenant_hr_employees.js +172 -0
  269. package/esm/schemas/models/tenant_hr_leave_requests.js +80 -0
  270. package/esm/schemas/models/tenant_hr_payrolls.js +131 -0
  271. package/esm/schemas/models/tenant_hr_performance_reviews.js +58 -0
  272. package/esm/schemas/models/tenant_hr_policies.js +57 -0
  273. package/esm/schemas/models/tenant_hr_positions.js +48 -0
  274. package/esm/schemas/models/tenant_hr_shift_schedules.js +84 -0
  275. package/esm/schemas/models/tenant_hr_shifts.js +64 -0
  276. package/esm/schemas/models/tenant_instore_shift_sessions.js +204 -0
  277. package/esm/schemas/models/tenant_instore_shifts.js +63 -0
  278. package/esm/schemas/models/tenant_inventory_department_transactions.js +116 -0
  279. package/esm/schemas/models/tenant_inventory_department_utilities.js +85 -0
  280. package/esm/schemas/models/tenant_inventory_departments.js +55 -0
  281. package/esm/schemas/models/tenant_inventory_entries.js +131 -0
  282. package/esm/schemas/models/tenant_metadata.js +88 -0
  283. package/esm/schemas/models/tenant_order_item_instructions.js +66 -0
  284. package/esm/schemas/models/tenant_purchase_order_vendor_returns.js +80 -0
  285. package/esm/schemas/models/tenant_purchase_orders.js +158 -0
  286. package/esm/schemas/models/tenant_shifts.js +57 -0
  287. package/esm/schemas/models/tenant_staffs.js +129 -0
  288. package/esm/schemas/models/tenant_vendors.js +99 -0
  289. package/esm/schemas/models/tenants.js +811 -0
  290. package/esm/schemas/models/terminal_devices.js +63 -0
  291. package/esm/schemas/models/tokens.js +73 -0
  292. package/esm/schemas/models/track_order_numbers.js +42 -0
  293. package/esm/schemas/models/void_order_items.js +210 -0
  294. package/esm/schemas/models/vouchers.js +101 -0
  295. package/esm/schemas/models/wallet_transactions.js +128 -0
  296. package/esm/schemas/models/wallets.js +44 -0
  297. package/esm/schemas/models/warehouse-activity-logs.js +144 -0
  298. package/esm/schemas/models/warehouse_categories.js +83 -0
  299. package/esm/schemas/models/warehouse_clients.js +81 -0
  300. package/esm/schemas/models/warehouse_communications.js +226 -0
  301. package/esm/schemas/models/warehouse_internal_movements.js +463 -0
  302. package/esm/schemas/models/warehouse_inventory_entries.js +125 -0
  303. package/esm/schemas/models/warehouse_inventory_lot_serial_numbers.js +188 -0
  304. package/esm/schemas/models/warehouse_inventory_transactions.js +133 -0
  305. package/esm/schemas/models/warehouse_item_transactions.js +97 -0
  306. package/esm/schemas/models/warehouse_items.js +173 -0
  307. package/esm/schemas/models/warehouse_operational_roles.js +87 -0
  308. package/esm/schemas/models/warehouse_purchase_order_receipts.js +163 -0
  309. package/esm/schemas/models/warehouse_purchase_order_rfqs.js +339 -0
  310. package/esm/schemas/models/warehouse_purchase_order_vendor_returns.js +199 -0
  311. package/esm/schemas/models/warehouse_purchase_orders.js +334 -0
  312. package/esm/schemas/models/warehouse_sale_deliveries.js +155 -0
  313. package/esm/schemas/models/warehouse_sale_invoices.js +229 -0
  314. package/esm/schemas/models/warehouse_sale_order_rfqs.js +340 -0
  315. package/esm/schemas/models/warehouse_sale_orders.js +322 -0
  316. package/esm/schemas/models/warehouse_staffs.js +104 -0
  317. package/esm/schemas/models/warehouse_track_order_numbers.js +73 -0
  318. package/esm/schemas/models/warehouse_vendors.js +99 -0
  319. package/esm/schemas/models/warehouse_void_purchase_order_items.js +174 -0
  320. package/esm/schemas/models/warehouse_void_sale_order_items.js +174 -0
  321. package/esm/schemas/models/warehouses.js +253 -0
  322. package/esm/schemas/types/app_configs.js +1 -0
  323. package/esm/schemas/types/applied_order_discounts.js +1 -0
  324. package/esm/schemas/types/brands.js +1 -0
  325. package/esm/schemas/types/categories.js +1 -0
  326. package/esm/schemas/types/close_dates.js +1 -0
  327. package/esm/schemas/types/common.js +1 -0
  328. package/esm/schemas/types/courses.js +1 -0
  329. package/esm/schemas/types/customer_redemptions.js +1 -0
  330. package/esm/schemas/types/customers.js +1 -0
  331. package/esm/schemas/types/deliveries.js +1 -0
  332. package/esm/schemas/types/delivery_areas.js +1 -0
  333. package/esm/schemas/types/dinein_floors.js +1 -0
  334. package/esm/schemas/types/dinein_tables.js +1 -0
  335. package/esm/schemas/types/dinein_tables_fingerprints.js +1 -0
  336. package/esm/schemas/types/discounts.js +1 -0
  337. package/esm/schemas/types/expense_categories.js +1 -0
  338. package/esm/schemas/types/expense_details.js +1 -0
  339. package/esm/schemas/types/gift_cards.js +1 -0
  340. package/esm/schemas/types/halfhalf_setup.js +1 -0
  341. package/esm/schemas/types/index.js +113 -0
  342. package/esm/schemas/types/internal_customers.js +1 -0
  343. package/esm/schemas/types/internal_invoices.js +1 -0
  344. package/esm/schemas/types/internal_leads.js +1 -0
  345. package/esm/schemas/types/internal_operational_roles.js +16 -0
  346. package/esm/schemas/types/internal_staffs.js +1 -0
  347. package/esm/schemas/types/inventories.js +1 -0
  348. package/esm/schemas/types/inventory_categories.js +1 -0
  349. package/esm/schemas/types/inventory_department_transactions.js +1 -0
  350. package/esm/schemas/types/inventory_department_utilities.js +1 -0
  351. package/esm/schemas/types/inventory_departments.js +1 -0
  352. package/esm/schemas/types/inventory_transactions.js +1 -0
  353. package/esm/schemas/types/item_transactions.js +1 -0
  354. package/esm/schemas/types/items.js +1 -0
  355. package/esm/schemas/types/marketing_fingerprints.js +1 -0
  356. package/esm/schemas/types/menus.js +1 -0
  357. package/esm/schemas/types/messaging_devices.js +1 -0
  358. package/esm/schemas/types/modifier_extras.js +1 -0
  359. package/esm/schemas/types/multi_tenants.js +1 -0
  360. package/esm/schemas/types/offers.js +1 -0
  361. package/esm/schemas/types/offers_fingerprints.js +1 -0
  362. package/esm/schemas/types/operational_roles.js +15 -0
  363. package/esm/schemas/types/orders.js +1 -0
  364. package/esm/schemas/types/printer_settings.js +1 -0
  365. package/esm/schemas/types/public_holidays.js +1 -0
  366. package/esm/schemas/types/reservations.js +1 -0
  367. package/esm/schemas/types/reviews.js +1 -0
  368. package/esm/schemas/types/rewards_usage.js +1 -0
  369. package/esm/schemas/types/riders.js +1 -0
  370. package/esm/schemas/types/specials.js +1 -0
  371. package/esm/schemas/types/staff_shifts.js +1 -0
  372. package/esm/schemas/types/tenant-activity-logs.js +1 -0
  373. package/esm/schemas/types/tenant_active_jobs.js +1 -0
  374. package/esm/schemas/types/tenant_calendar.js +1 -0
  375. package/esm/schemas/types/tenant_cash_drawer_sessions.js +1 -0
  376. package/esm/schemas/types/tenant_cash_drawers.js +1 -0
  377. package/esm/schemas/types/tenant_cash_in_hand_transactions.js +1 -0
  378. package/esm/schemas/types/tenant_cash_in_out.js +1 -0
  379. package/esm/schemas/types/tenant_clients.js +1 -0
  380. package/esm/schemas/types/tenant_day_sessions.js +1 -0
  381. package/esm/schemas/types/tenant_hr_attendance_records.js +1 -0
  382. package/esm/schemas/types/tenant_hr_biometric_enrollments.js +1 -0
  383. package/esm/schemas/types/tenant_hr_departments.js +1 -0
  384. package/esm/schemas/types/tenant_hr_documents.js +1 -0
  385. package/esm/schemas/types/tenant_hr_employees.js +1 -0
  386. package/esm/schemas/types/tenant_hr_leave_requests.js +1 -0
  387. package/esm/schemas/types/tenant_hr_payrolls.js +1 -0
  388. package/esm/schemas/types/tenant_hr_performance_reviews.js +1 -0
  389. package/esm/schemas/types/tenant_hr_policies.js +1 -0
  390. package/esm/schemas/types/tenant_hr_positions.js +1 -0
  391. package/esm/schemas/types/tenant_hr_shift_schedules.js +1 -0
  392. package/esm/schemas/types/tenant_hr_shifts.js +1 -0
  393. package/esm/schemas/types/tenant_instore_shift_sessions.js +1 -0
  394. package/esm/schemas/types/tenant_instore_shifts.js +1 -0
  395. package/esm/schemas/types/tenant_inventory_entries.js +1 -0
  396. package/esm/schemas/types/tenant_metadata.js +1 -0
  397. package/esm/schemas/types/tenant_order_item_instructions.js +1 -0
  398. package/esm/schemas/types/tenant_purchase_order_vendor_returns.js +1 -0
  399. package/esm/schemas/types/tenant_purchase_orders.js +1 -0
  400. package/esm/schemas/types/tenant_shifts.js +1 -0
  401. package/esm/schemas/types/tenant_staffs.js +1 -0
  402. package/esm/schemas/types/tenant_vendors.js +1 -0
  403. package/esm/schemas/types/tenants.js +1 -0
  404. package/esm/schemas/types/terminal_devices.js +1 -0
  405. package/esm/schemas/types/tokens.js +1 -0
  406. package/esm/schemas/types/track_order_numbers.js +1 -0
  407. package/esm/schemas/types/void_order_items.js +1 -0
  408. package/esm/schemas/types/vouchers.js +1 -0
  409. package/esm/schemas/types/wallet_transactions.js +1 -0
  410. package/esm/schemas/types/wallets.js +1 -0
  411. package/esm/schemas/types/warehouse-activity-logs.js +1 -0
  412. package/esm/schemas/types/warehouse_categories.js +1 -0
  413. package/esm/schemas/types/warehouse_clients.js +1 -0
  414. package/esm/schemas/types/warehouse_communications.js +1 -0
  415. package/esm/schemas/types/warehouse_internal_movements.js +1 -0
  416. package/esm/schemas/types/warehouse_inventory_entries.js +1 -0
  417. package/esm/schemas/types/warehouse_inventory_lot_serial_numbers.js +1 -0
  418. package/esm/schemas/types/warehouse_inventory_transactions.js +1 -0
  419. package/esm/schemas/types/warehouse_item_transactions.js +1 -0
  420. package/esm/schemas/types/warehouse_items.js +1 -0
  421. package/esm/schemas/types/warehouse_operational_roles.js +15 -0
  422. package/esm/schemas/types/warehouse_purchase_order_receipts.js +18 -0
  423. package/esm/schemas/types/warehouse_purchase_order_rfqs.js +1 -0
  424. package/esm/schemas/types/warehouse_purchase_order_vendor_returns.js +1 -0
  425. package/esm/schemas/types/warehouse_purchase_orders.js +1 -0
  426. package/esm/schemas/types/warehouse_sale_deliveries.js +1 -0
  427. package/esm/schemas/types/warehouse_sale_invoices.js +1 -0
  428. package/esm/schemas/types/warehouse_sale_order_rfqs.js +1 -0
  429. package/esm/schemas/types/warehouse_sale_orders.js +1 -0
  430. package/esm/schemas/types/warehouse_staffs.js +1 -0
  431. package/esm/schemas/types/warehouse_track_order_numbers.js +1 -0
  432. package/esm/schemas/types/warehouse_vendors.js +1 -0
  433. package/esm/schemas/types/warehouse_void_purchase_order_items.js +1 -0
  434. package/esm/schemas/types/warehouse_void_sale_order_items.js +1 -0
  435. package/esm/schemas/types/warehouses.js +1 -0
  436. package/lib/helpers/utils/order-engine.js +6 -1
  437. package/lib/tests/soldout-option-default-guard.test.d.ts +1 -0
  438. package/lib/tests/soldout-option-default-guard.test.js +126 -0
  439. package/package.json +6 -3
@@ -0,0 +1,1409 @@
1
+ import ObjectID from 'bson-objectid';
2
+ import { MODIFIER_OPTION_REF_TYPE_ENUM, ORDER_ITEM_TYPE_ENUM } from '../../constants';
3
+ import { getDiscountDetails, getItemQuantityChangeResults } from '../store';
4
+ import { getPercentageAmount, parseNum } from './common';
5
+ import { findApplicableSchedule, getPlatformModifiers, getPriceEnum } from './platform-catalog';
6
+ /* ==========================================================><==================================================== */
7
+ export function hasMissedRequiredItemModifier(currentModifiers, platform) {
8
+ let missedModifier = null;
9
+ if (!currentModifiers)
10
+ return false;
11
+ const findMissedRequiredModifiers = (modifiers) => {
12
+ for (let i = 0; i < modifiers.length; i++) {
13
+ if (missedModifier)
14
+ break;
15
+ const modifier = modifiers[i];
16
+ let totalDefaultOptions = 0;
17
+ const options = modifier.options.filter((option) => option.active && !option.excluded_platforms.includes(platform));
18
+ if (options.length === 0) {
19
+ continue;
20
+ }
21
+ const defaultOptionsWithModifiers = [];
22
+ for (let j = 0; j < options.length; j++) {
23
+ const option = options[j];
24
+ if (!option.default)
25
+ continue;
26
+ totalDefaultOptions += modifier.min_option_choice_quantity || 1;
27
+ if (option.modifiers != null && option.modifiers.length > 0) {
28
+ defaultOptionsWithModifiers.push(option);
29
+ }
30
+ }
31
+ const totalRequiredOptions = modifier.min_aggregate_options_quantity ?? modifier.min_num_options ?? 0;
32
+ if (!missedModifier && totalRequiredOptions && totalRequiredOptions > totalDefaultOptions) {
33
+ missedModifier = modifier;
34
+ break;
35
+ }
36
+ for (let j = 0; j < defaultOptionsWithModifiers.length; j++) {
37
+ const option = defaultOptionsWithModifiers[j];
38
+ const optionModifiers = option.modifiers;
39
+ findMissedRequiredModifiers(optionModifiers ?? []);
40
+ }
41
+ }
42
+ };
43
+ findMissedRequiredModifiers(currentModifiers);
44
+ return missedModifier !== null;
45
+ }
46
+ /* ==========================================================><==================================================== */
47
+ function getSelectedModifiersPriceSplit(modifiers, excludedRefSet, inheritedExcluded = false) {
48
+ let eligible = 0;
49
+ let excluded = 0;
50
+ for (let i = 0; i < modifiers.length; i++) {
51
+ const modifier = modifiers[i];
52
+ if (!modifier.default || !modifier.active)
53
+ continue;
54
+ const modifierExcluded = inheritedExcluded || excludedRefSet.has(modifier.ref);
55
+ for (let j = 0; j < modifier.options.length; j++) {
56
+ const option = modifier.options[j];
57
+ if (!option.default || !option.active)
58
+ continue;
59
+ const optionExcluded = modifierExcluded || excludedRefSet.has(option.ref);
60
+ const optionTotal = (option.price ?? 0) * (option.quantity ?? 1);
61
+ if (optionExcluded) {
62
+ excluded += optionTotal;
63
+ }
64
+ else {
65
+ eligible += optionTotal;
66
+ }
67
+ if (option.modifiers?.length > 0) {
68
+ const nested = getSelectedModifiersPriceSplit(option.modifiers, excludedRefSet, optionExcluded);
69
+ eligible += nested.eligible;
70
+ excluded += nested.excluded;
71
+ }
72
+ }
73
+ }
74
+ return {
75
+ eligible: parseNum(eligible),
76
+ excluded: parseNum(excluded),
77
+ };
78
+ }
79
+ function getEligibleDiscountBaseForItem(item, fullTotal) {
80
+ const excludedDiscountRefs = item.excluded_discount_refs ?? [];
81
+ if (excludedDiscountRefs.length === 0)
82
+ return fullTotal;
83
+ const excludedRefSet = new Set(excludedDiscountRefs);
84
+ const itemExcluded = excludedRefSet.has(item.item_id);
85
+ const { eligible: eligibleModifiersTotal, excluded: excludedModifiersTotal } = getSelectedModifiersPriceSplit(item.modifiers, excludedRefSet);
86
+ if (!itemExcluded && excludedModifiersTotal === 0)
87
+ return fullTotal;
88
+ const eligibleItemBase = itemExcluded ? 0 : item.price;
89
+ return parseNum((eligibleItemBase + eligibleModifiersTotal) * item.quantity);
90
+ }
91
+ /**
92
+ * Resolve percentage discounts to fixed amounts for excluded-ref items.
93
+ * Used when converting to IOrderItem so cart-actions (which doesn't know about
94
+ * excluded refs) can recalculate correctly.
95
+ */
96
+ function resolveDiscountDetailsForExcludedRefs(orderItem) {
97
+ const details = orderItem.item_discount_details;
98
+ if (!details)
99
+ return null;
100
+ if (!orderItem.excluded_discount_refs?.length)
101
+ return details;
102
+ const excludedRefSet = new Set(orderItem.excluded_discount_refs);
103
+ const itemExcluded = excludedRefSet.has(orderItem.item_id);
104
+ const { eligible: eligibleModifiersTotal, excluded: excludedModifiersTotal } = getSelectedModifiersPriceSplit(orderItem.modifiers, excludedRefSet);
105
+ if (!itemExcluded && excludedModifiersTotal === 0)
106
+ return details;
107
+ const eligibleItemBase = itemExcluded ? 0 : orderItem.price;
108
+ const eligibleSubtotal = parseNum((eligibleItemBase + eligibleModifiersTotal) * orderItem.quantity);
109
+ const resolved = { ...details };
110
+ if (resolved.loyalty_discount_id != null && resolved.loyalty_discount != null) {
111
+ if (resolved.is_loyalty_discount_percentage) {
112
+ resolved.loyalty_discount =
113
+ eligibleSubtotal > 0 ? parseNum(getPercentageAmount(eligibleSubtotal, resolved.loyalty_discount)) : 0;
114
+ resolved.is_loyalty_discount_percentage = false;
115
+ }
116
+ else {
117
+ resolved.loyalty_discount = parseNum(Math.min(resolved.loyalty_discount, eligibleSubtotal));
118
+ }
119
+ }
120
+ if (resolved.voucher_discount_id != null && resolved.voucher_discount != null) {
121
+ if (resolved.is_voucher_discount_percentage) {
122
+ resolved.voucher_discount =
123
+ eligibleSubtotal > 0 ? parseNum(getPercentageAmount(eligibleSubtotal, resolved.voucher_discount)) : 0;
124
+ resolved.is_voucher_discount_percentage = false;
125
+ }
126
+ else {
127
+ resolved.voucher_discount = parseNum(Math.min(resolved.voucher_discount, eligibleSubtotal));
128
+ }
129
+ }
130
+ return resolved;
131
+ }
132
+ export function syncOrderEngineItem(orderEngineItem) {
133
+ // Calculate modifiers total and find errors
134
+ let error = null;
135
+ function calcModifiersTotal(modifiers) {
136
+ let total = 0;
137
+ for (let i = 0; i < modifiers.length; i++) {
138
+ const modifier = modifiers[i];
139
+ if (modifier.default) {
140
+ for (let j = 0; j < modifier.options.length; j++) {
141
+ const option = modifier.options[j];
142
+ if (!option.default)
143
+ continue;
144
+ // `is_free` means NOT charged (the cart math —
145
+ // `calculateItemModifiersPrice` — skips them too): free options keep
146
+ // their price for reference but must never add to the totals.
147
+ if (option.is_free)
148
+ continue;
149
+ const quantity = option.quantity || 1;
150
+ // Add option price to total
151
+ total += (option.price || 0) * quantity;
152
+ // Recursively process nested modifiers
153
+ if (option.modifiers?.length > 0) {
154
+ total += calcModifiersTotal(option.modifiers);
155
+ }
156
+ }
157
+ }
158
+ }
159
+ return total;
160
+ }
161
+ function findFirstError(modifiers, parentPath = '', parentOptionName = '') {
162
+ if (error)
163
+ return; // Early exit if error already found
164
+ for (let i = 0; i < modifiers.length; i++) {
165
+ const modifier = modifiers[i];
166
+ const currentPath = parentPath ? `${parentPath}_${modifier._id}` : modifier._id;
167
+ let totalDefaults = 0;
168
+ if (modifier.default) {
169
+ for (let j = 0; j < modifier.options.length; j++) {
170
+ const option = modifier.options[j];
171
+ if (!option.default)
172
+ continue;
173
+ const quantity = option.quantity || 1;
174
+ totalDefaults += quantity;
175
+ }
176
+ }
177
+ // Check if current modifier meets minimum/maximum requirements
178
+ const minRequired = modifier.min_aggregate_options_quantity ?? modifier.min_num_options ?? 0;
179
+ const maxRequired = modifier.max_aggregate_options_quantity ?? modifier.max_num_options ?? Infinity;
180
+ if (minRequired > 0 && totalDefaults < minRequired) {
181
+ const modifierName = parentOptionName ? `${parentOptionName} > ${modifier.name}` : modifier.name;
182
+ error = {
183
+ error_id: currentPath,
184
+ error_message: `Select ${minRequired > 1 ? `${minRequired} options` : 'an option'} for ${modifierName}`,
185
+ };
186
+ return; // Stop immediately when error found
187
+ }
188
+ else if (totalDefaults > maxRequired) {
189
+ const modifierName = parentOptionName ? `${parentOptionName} › ${modifier.name}` : modifier.name;
190
+ error = {
191
+ error_id: currentPath,
192
+ error_message: `Max ${maxRequired > 1 ? `${maxRequired} options` : 'option'} Selectable for ${modifierName}`,
193
+ };
194
+ return; // Stop immediately when error found
195
+ }
196
+ // Process nested modifiers depth-first
197
+ if (modifier.default) {
198
+ for (let j = 0; j < modifier.options.length; j++) {
199
+ const option = modifier.options[j];
200
+ if (!option.default)
201
+ continue;
202
+ // Recursively check nested modifiers
203
+ if (option.modifiers?.length > 0) {
204
+ const optionPath = `${currentPath}_${option._id}`;
205
+ findFirstError(option.modifiers, optionPath, option.name);
206
+ if (error)
207
+ return; // Stop if error found in nested modifiers
208
+ }
209
+ }
210
+ }
211
+ }
212
+ }
213
+ const modifiersTotal = calcModifiersTotal(orderEngineItem.modifiers);
214
+ findFirstError(orderEngineItem.modifiers);
215
+ // Item total without tax amount and without discount amount
216
+ // total is 20
217
+ const itemTotalWithoutTaxAndWithoutDiscount = (orderEngineItem.price + modifiersTotal) * orderEngineItem.quantity;
218
+ // Item discount details
219
+ // discount is 50%
220
+ // 50% of 20 is 10
221
+ // When excluded_discount_refs exist, discount is computed against the eligible subtotal only.
222
+ // Original percentage flags are preserved so re-syncs (option toggles, qty changes) stay correct.
223
+ const discountBase = getEligibleDiscountBaseForItem(orderEngineItem, itemTotalWithoutTaxAndWithoutDiscount);
224
+ const item_discount_details = getDiscountDetails(orderEngineItem.item_discount_details, discountBase);
225
+ // Item total without tax amount and with discount amount
226
+ // 20 - 10 = 10
227
+ // 10 is the item total without tax amount and with discount amount
228
+ const itemTotalWithoutTaxAndWithDiscount = itemTotalWithoutTaxAndWithoutDiscount - (item_discount_details?.total_discount ?? 0);
229
+ // Item tax amount with discount amount
230
+ // tax is 50%
231
+ // tax amount of 50% of 10 is 5
232
+ const itemTaxAmount = getPercentageAmount(itemTotalWithoutTaxAndWithDiscount, orderEngineItem.tax_rate);
233
+ const itemTotal = parseNum(itemTotalWithoutTaxAndWithoutDiscount + itemTaxAmount);
234
+ const itemSubtotal = parseNum(itemTotalWithoutTaxAndWithDiscount + itemTaxAmount);
235
+ const updatedOrderEngineItem = {
236
+ ...orderEngineItem,
237
+ gross_total: itemTotal,
238
+ subtotal: itemSubtotal,
239
+ item_discount_details,
240
+ error_id: error?.error_id,
241
+ error_message: error?.error_message,
242
+ };
243
+ return updatedOrderEngineItem;
244
+ }
245
+ // ==========================================================><====================================================
246
+ export function checkIfModifiersExist(modifiers, platform) {
247
+ if (!modifiers || !platform)
248
+ return false;
249
+ return modifiers.some((modifier) => modifier.active &&
250
+ modifier.options.some((option) => option.active &&
251
+ !option.excluded_platforms.includes(platform) &&
252
+ findApplicableSchedule(option.item_modifier_option_special_hours, platform) !== false));
253
+ }
254
+ /* =========================>POS Actions<============================ */
255
+ export function makeSpaceForFreeOptions(options, num_free_options) {
256
+ // Login for implementing free items
257
+ if (!num_free_options)
258
+ return options;
259
+ const defaultPriceOptions = options
260
+ .filter((option) => option.default)
261
+ .sort((a, b) => a.price * a.quantity - b.price * b.quantity)
262
+ .map((option, index) => index + 1 > num_free_options ? { ...option, is_free: false } : { ...option, is_free: true });
263
+ const nonDefaultOptions = [];
264
+ for (let i = 0; i < options.length; i++) {
265
+ const option = options[i];
266
+ if (!option.default) {
267
+ nonDefaultOptions.push({ ...option, is_free: false });
268
+ }
269
+ }
270
+ return [...defaultPriceOptions, ...nonDefaultOptions].sort((a, b) => a.sort_id - b.sort_id);
271
+ }
272
+ // ====================================>>><<<======================================
273
+ /**
274
+ * Applies `choose_expensive_segment_price` to an order engine item converted
275
+ * from a half-half setup (top-level modifier groups = segments, single-select
276
+ * each, only 2 or 4 segments).
277
+ *
278
+ * The expensive rule depends on which halves the user actually picked, so it
279
+ * cannot run during `IHalfHalfSetup -> IItem` conversion — it must run after
280
+ * selection, on the WORKING data. When `originalPriceReferences` is provided,
281
+ * every option price is first re-based from that immutable reference, which
282
+ * makes the rule fully reversible: picking a cheaper pair afterwards restores
283
+ * the previous (raised) prices instead of accumulating them.
284
+ *
285
+ * Rule: `price = base + upsell` — the item (option) level upsell is already
286
+ * baked into the option price at conversion. choose_expensive compares every
287
+ * segment option (option price + required/price-defining modifier prices —
288
+ * e.g. a "Pizza Size" group whose Small/Large/X-Large options are part of the
289
+ * item's price) and levels the cheaper PICK to the most expensive SELECTED
290
+ * half — `A($5)+B($5)` charges 5+5, `B($5)+C($6)` charges 6+6, and switching
291
+ * `C+D -> A+B` lowers them again. Every option is levelled to `max(own value,
292
+ * the max of the OTHER segments' selected values)` — the level its OWN pick
293
+ * would produce: choosing an unselected sibling REPLACES its segment's
294
+ * current pick, so that pick never inflates its own siblings' prices (a
295
+ * segment holding the expensive half keeps its other options at their own
296
+ * prices — you can only pick the next half from the NEXT segment), while a
297
+ * segment with no pick yet previews the full level. Unselected options never
298
+ * contribute to totals. The raise is applied to the FIRST
299
+ * PRICED element along the segment's price chain: the segment option's own
300
+ * price when non-zero, else the first priced required leaf ("First Half ->
301
+ * ROMA -> Pizza Size -> Large 13"") — see `findRaiseTarget`. Optional/upsell
302
+ * modifier groups are excluded: they add on top and must not influence the
303
+ * comparison. The IHalfHalfSetup level upsell is NOT part of this rule: it is
304
+ * the converted item's own price and is added once on top of the combined
305
+ * subtotal. Free (`is_free`) options never drive the comparison and are never
306
+ * raised.
307
+ *
308
+ * All prices here are plain numbers (engine-priced).
309
+ *
310
+ * Returns the item unchanged when no segment option is selected (only
311
+ * re-based when references were provided).
312
+ */
313
+ export function applyChooseExpensiveSegmentPrice(orderEngineItem, options) {
314
+ const references = options?.originalPriceReferences;
315
+ const rebased = references
316
+ ? {
317
+ ...orderEngineItem,
318
+ modifiers: rebaseEngineOptionPrices(orderEngineItem.modifiers ?? [], references, '', 'all', true),
319
+ }
320
+ : orderEngineItem;
321
+ const segmentGroups = (rebased.modifiers ?? []).filter((modifier) => modifier.depth === 0);
322
+ if (segmentGroups.length < 2)
323
+ return references ? syncOrderEngineItem(rebased) : rebased;
324
+ const raised = applyChooseExpensiveSegmentPriceToModifiers(segmentGroups);
325
+ if (raised == null)
326
+ return references ? syncOrderEngineItem(rebased) : rebased;
327
+ let segmentGroupIndex = 0;
328
+ const modifiers = (rebased.modifiers ?? []).map((modifier) => modifier.depth !== 0 ? modifier : raised[segmentGroupIndex++]);
329
+ return syncOrderEngineItem({ ...rebased, modifiers });
330
+ }
331
+ /**
332
+ * Path key of an option inside its modifier chain — `_`-joined ids from the
333
+ * root, identical to the identifiers used by `setCheckFieldInOrderEngineItem`
334
+ * (ids are BSON ObjectIds so `_` is unambiguous).
335
+ */
336
+ const buildOptionPath = (modifierPath, optionId) => `${modifierPath}_${optionId}`;
337
+ /**
338
+ * Re-bases engine option prices from `references` (option path -> original
339
+ * price). The scope decides WHICH options are re-based:
340
+ * - `'all'` — every option (standalone half-half: segments and
341
+ * the required leaves that carry their price),
342
+ * - `'flaggedHalfHalf'` — only options inside a HALF_HALF option carrying
343
+ * the setup flag (a half-half nested in a special;
344
+ * the special's own option prices keep whatever the
345
+ * conversion produced).
346
+ * Returns the SAME tree object when no price changed (no needless copies).
347
+ */
348
+ function rebaseEngineOptionPrices(modifiers, references, parentPath, scope, insideScope) {
349
+ let treeChanged = false;
350
+ const nextModifiers = modifiers.map((modifier) => {
351
+ const modifierPath = parentPath ? `${parentPath}_${modifier._id}` : modifier._id;
352
+ let modifierChanged = false;
353
+ const nextOptions = (modifier.options ?? []).map((option) => {
354
+ let nextOption = option;
355
+ const optionPath = buildOptionPath(modifierPath, option._id);
356
+ if (insideScope) {
357
+ const originalPrice = references[optionPath];
358
+ if (originalPrice != null && originalPrice !== option.price) {
359
+ nextOption = { ...nextOption, price: originalPrice };
360
+ modifierChanged = true;
361
+ }
362
+ }
363
+ const isFlaggedHalfHalf = option.ref_type === MODIFIER_OPTION_REF_TYPE_ENUM.HALF_HALF && option.choose_expensive_segment_price === true;
364
+ const childInsideScope = insideScope || (scope === 'flaggedHalfHalf' && isFlaggedHalfHalf);
365
+ const nextChildModifiers = rebaseEngineOptionPrices(nextOption.modifiers ?? [], references, optionPath, scope, childInsideScope);
366
+ if (nextChildModifiers !== nextOption.modifiers) {
367
+ nextOption = { ...nextOption, modifiers: nextChildModifiers };
368
+ modifierChanged = true;
369
+ }
370
+ return nextOption;
371
+ });
372
+ if (!modifierChanged)
373
+ return modifier;
374
+ treeChanged = true;
375
+ return { ...modifier, options: nextOptions };
376
+ });
377
+ return treeChanged ? nextModifiers : modifiers;
378
+ }
379
+ /**
380
+ * The option a required (price-defining) group contributes to the segment
381
+ * value: the SELECTED (default) one for a multi-option group, or the only
382
+ * option of a single-option group — never an unselected sibling.
383
+ */
384
+ function getSelectedRequiredOption(modifier) {
385
+ const options = modifier.options ?? [];
386
+ return options.find((option) => option.default) ?? (options.length === 1 ? options[0] : null);
387
+ }
388
+ /** Required (price-defining) group: at least one selection is mandatory. */
389
+ function isRequiredModifierGroup(modifier) {
390
+ return ((modifier.min_num_options != null && modifier.min_num_options > 0) ||
391
+ (modifier.min_aggregate_options_quantity != null && modifier.min_aggregate_options_quantity > 0));
392
+ }
393
+ /**
394
+ * Value of the SELECTED option of every required (price-defining) modifier
395
+ * group, at any depth — e.g. "Pizza Size" -> "Large 13"" is part of the
396
+ * item's price whichever size is picked, and only the picked size is charged.
397
+ * Optional/upsell groups, unselected siblings and the add-ons chosen on top of
398
+ * the item are excluded: they must not influence the comparison.
399
+ */
400
+ function getRequiredOptionPrices(modifiers) {
401
+ let total = 0;
402
+ (modifiers ?? []).forEach((modifier) => {
403
+ if (!isRequiredModifierGroup(modifier))
404
+ return;
405
+ const selected = getSelectedRequiredOption(modifier);
406
+ if (selected == null)
407
+ return;
408
+ total += (selected.price ?? 0) * (selected.quantity || 1);
409
+ total += getRequiredOptionPrices(selected.modifiers);
410
+ });
411
+ return total;
412
+ }
413
+ /**
414
+ * Value `choose_expensive_segment_price` compares and levels: the option price
415
+ * (base + item/option level upsell, merged at conversion) + the prices of its
416
+ * SELECTED required (price-defining) options. Exposed so callers that show a
417
+ * price for a single segment (e.g. the segment customization drawer) use the
418
+ * SAME math.
419
+ */
420
+ export function getOrderEngineOptionSegmentValue(option) {
421
+ return (option.price ?? 0) + getRequiredOptionPrices(option.modifiers);
422
+ }
423
+ /**
424
+ * First priced required leaf reachable from `modifiers` (direct children):
425
+ * the single option of a single-option required group (its price is fixed —
426
+ * e.g. "ROMA -> Pizza Size -> Large 13""), or the selected/default option
427
+ * of a multi-option required group (never an unselected sibling).
428
+ */
429
+ function findPricedRequiredLeaf(modifiers) {
430
+ for (const modifier of modifiers ?? []) {
431
+ if (!isRequiredModifierGroup(modifier))
432
+ continue;
433
+ const candidate = getSelectedRequiredOption(modifier);
434
+ if (candidate != null && (candidate.price ?? 0) > 0)
435
+ return candidate;
436
+ }
437
+ return null;
438
+ }
439
+ /** Raises the option `targetId` inside its (direct) modifier group by `delta`. */
440
+ function raiseOptionPriceInModifiers(modifiers, targetId, delta) {
441
+ return modifiers.map((modifier) => ({
442
+ ...modifier,
443
+ options: modifier.options.map((option) => option._id === targetId ? { ...option, price: (option.price ?? 0) + delta } : option),
444
+ }));
445
+ }
446
+ /**
447
+ * Core `choose_expensive_segment_price` normalization over a list of segment
448
+ * groups (single-select: one option per group). Used for standalone HALF_HALF
449
+ * items (top-level segments) and for a HALF_HALF option nested in a special
450
+ * (the option's own modifiers).
451
+ *
452
+ * Returns null when nothing needs to change (no selected option / no priced
453
+ * segment), otherwise the raised segment groups.
454
+ */
455
+ function applyChooseExpensiveSegmentPriceToModifiers(segmentGroups) {
456
+ // One selected option per segment group (segments are single-select).
457
+ const selections = segmentGroups.map((group) => (group.options ?? []).find((option) => option.default && !option.is_free) ?? null);
458
+ if (selections.every((selection) => selection == null))
459
+ return null;
460
+ // Value of every segment's SELECTED option — only picks are charged, and
461
+ // only picks drive the level.
462
+ const selectedValues = selections.map((selection) => selection == null ? 0 : getOrderEngineOptionSegmentValue(selection));
463
+ if (Math.max(...selectedValues, 0) <= 0)
464
+ return null;
465
+ // RULE for where the raise lands: on the FIRST PRICED element along the
466
+ // segment's price chain —
467
+ // 1. the segment option's own price (the item base) when it is non-zero
468
+ // (same as the modern flow, which raises the item price), or
469
+ // 2. otherwise, the first priced required leaf down the chain: the single
470
+ // option of a single-option required group (its price is fixed — e.g.
471
+ // "ROMA -> Pizza Size -> Large 13\""), or the currently selected
472
+ // option of a multi-option required group,
473
+ // 3. otherwise, the segment option's own price (even when 0).
474
+ // This keeps the raise where the price actually lives and never invents a
475
+ // price on an empty slot or an unselected option.
476
+ const findRaiseTarget = (option) => (option.price ?? 0) > 0 ? option : findPricedRequiredLeaf(option.modifiers);
477
+ const raiseSegmentOption = (option, delta) => {
478
+ const target = findRaiseTarget(option);
479
+ if (target == null || target._id === option._id) {
480
+ return { ...option, price: (option.price ?? 0) + delta };
481
+ }
482
+ return { ...option, modifiers: raiseOptionPriceInModifiers(option.modifiers, target._id, delta) };
483
+ };
484
+ // Every option is levelled to `max(own value, the max of the OTHER
485
+ // segments' selected values)` — the level its OWN pick would produce:
486
+ // - the selected option of a segment is CHARGED that way (the most
487
+ // expensive selected half drives every pick),
488
+ // - an unselected SIBLING replaces its segment's current pick when
489
+ // chosen, so that pick must not inflate the sibling's price (the
490
+ // expensive half's own list keeps its other options at their prices),
491
+ // - every option of a segment with no pick yet previews the full level
492
+ // (what picking it right now would cost).
493
+ // Free (`is_free`) options never drive the comparison and are never raised.
494
+ return segmentGroups.map((modifier, groupIndex) => {
495
+ const otherSegmentsMax = Math.max(...selectedValues.filter((_, index) => index !== groupIndex), 0);
496
+ return {
497
+ ...modifier,
498
+ options: (modifier.options ?? []).map((option) => {
499
+ if (option.is_free)
500
+ return option;
501
+ const segmentValue = getOrderEngineOptionSegmentValue(option);
502
+ const target = Math.max(segmentValue, otherSegmentsMax);
503
+ if (target <= segmentValue)
504
+ return option;
505
+ // Level by the difference so the option's final segment value
506
+ // (base + upsell + required modifiers) equals the target — applied
507
+ // to the priced leaf when available (see `raiseSegmentOption`). The
508
+ // IHalfHalfSetup upsell (item price) is untouched.
509
+ return raiseSegmentOption(option, target - segmentValue);
510
+ }),
511
+ };
512
+ });
513
+ }
514
+ /**
515
+ * True when the item has a top-level modifier group option that is a nested
516
+ * half-half (ref_type HALF_HALF) with its setup's choose_expensive flag.
517
+ */
518
+ export function hasFlaggedHalfHalfOption(orderEngineItem) {
519
+ return (orderEngineItem.modifiers ?? []).some((modifier) => (modifier.options ?? []).some((option) => option.ref_type === MODIFIER_OPTION_REF_TYPE_ENUM.HALF_HALF && option.choose_expensive_segment_price === true));
520
+ }
521
+ /**
522
+ * Half-half selection rule: an item may fill at most `segments - 1` halves —
523
+ * it may never make ALL sides of the half-half (otherwise it is not a half-half
524
+ * anymore). Returns the option PATHS that would complete "all sides" when
525
+ * selected, formatted exactly like `setCheckFieldInOrderEngineItem`
526
+ * identifiers (`seg-2_roma`, `mod-pizza_halfhalf-1_seg-2_milan`), so callers
527
+ * can block, guard and label them.
528
+ *
529
+ * Handles both shapes:
530
+ * - a HALF_HALF item (its top-level groups are the segments — pass
531
+ * `isHalfHalfSegmentItem: false`),
532
+ * - a flagged half-half option nested in a SPECIAL (its own modifier groups
533
+ * are the segments).
534
+ * A drawer opened for a single half-half SEGMENT passes
535
+ * `isHalfHalfSegmentItem: true` so the item's own option groups are never
536
+ * treated as segments.
537
+ */
538
+ export function getBlockedHalfHalfOptionPaths(orderEngineItem, isHalfHalfSegmentItem = false) {
539
+ const blocked = new Set();
540
+ const blockSegments = (segments, segmentsPath) => {
541
+ const total = segments.length;
542
+ if (total < 2)
543
+ return;
544
+ const selectedBySegment = segments.map((segment) => segment.options.find((option) => option.default) ?? null);
545
+ segments.forEach((segment, index) => {
546
+ const segmentPath = segmentsPath ? `${segmentsPath}_${segment._id}` : segment._id;
547
+ segment.options.forEach((option) => {
548
+ const others = selectedBySegment.filter((selected, otherIndex) => otherIndex !== index && selected != null && selected._id === option._id).length;
549
+ if (others >= total - 1) {
550
+ blocked.add(`${segmentPath}_${option._id}`);
551
+ }
552
+ });
553
+ });
554
+ };
555
+ const walkNestedHalfHalf = (modifiers, parentPath) => {
556
+ modifiers.forEach((modifier) => {
557
+ const modifierPath = parentPath ? `${parentPath}_${modifier._id}` : modifier._id;
558
+ modifier.options.forEach((option) => {
559
+ const optionPath = `${modifierPath}_${option._id}`;
560
+ if (option.ref_type === MODIFIER_OPTION_REF_TYPE_ENUM.HALF_HALF &&
561
+ option.choose_expensive_segment_price === true) {
562
+ blockSegments(option.modifiers ?? [], optionPath);
563
+ }
564
+ walkNestedHalfHalf(option.modifiers ?? [], optionPath);
565
+ });
566
+ });
567
+ };
568
+ if (orderEngineItem.item_type === ORDER_ITEM_TYPE_ENUM.HALF_HALF && !isHalfHalfSegmentItem) {
569
+ blockSegments((orderEngineItem.modifiers ?? []).filter((modifier) => modifier.depth === 0), '');
570
+ }
571
+ walkNestedHalfHalf(orderEngineItem.modifiers ?? [], '');
572
+ return blocked;
573
+ }
574
+ /**
575
+ * Same half-half selection rule for the MODERN selection list (no engine tree
576
+ * yet): the item ids that cannot be picked for `segmentIndex` because doing so
577
+ * would make them occupy every segment. `segmentIndex` is the segment being
578
+ * picked/edited (its own current item does not count against itself).
579
+ */
580
+ export function getHalfHalfBlockedItemIds(orderItems, segmentIndex) {
581
+ if (segmentIndex == null)
582
+ return [];
583
+ const totalSegments = orderItems.length;
584
+ if (totalSegments < 2)
585
+ return [];
586
+ const blocked = [];
587
+ const checked = new Set();
588
+ orderItems.forEach((orderItem) => {
589
+ if (orderItem == null || checked.has(orderItem.item_id))
590
+ return;
591
+ checked.add(orderItem.item_id);
592
+ const others = orderItems.filter((other, index) => index !== segmentIndex && other != null && other.item_id === orderItem.item_id).length;
593
+ if (others >= totalSegments - 1) {
594
+ blocked.push(orderItem.item_id);
595
+ }
596
+ });
597
+ return blocked;
598
+ }
599
+ /**
600
+ * `choose_expensive_segment_price` for a half-half option nested in a special:
601
+ * the option's own top-level modifiers are its segment groups, so they get the
602
+ * same level-to-the-most-expensive-SELECTED-half treatment as a standalone
603
+ * half-half item. ITEM options are terminal (their nested modifiers can never
604
+ * contain ITEM/HALF_HALF); normal options pass untouched.
605
+ *
606
+ * When `originalPriceReferences` is provided, prices are re-based first — but
607
+ * ONLY inside the flagged half-half subtrees, so the special's own option
608
+ * prices keep whatever the conversion produced.
609
+ */
610
+ export function applyNestedChooseExpensiveSegmentPrice(orderEngineItem, options) {
611
+ const references = options?.originalPriceReferences;
612
+ const rebased = references
613
+ ? {
614
+ ...orderEngineItem,
615
+ modifiers: rebaseEngineOptionPrices(orderEngineItem.modifiers ?? [], references, '', 'flaggedHalfHalf', false),
616
+ }
617
+ : orderEngineItem;
618
+ const modifiers = (rebased.modifiers ?? []).map((modifier) => ({
619
+ ...modifier,
620
+ options: (modifier.options ?? []).map((option) => {
621
+ if (option.ref_type !== MODIFIER_OPTION_REF_TYPE_ENUM.HALF_HALF ||
622
+ option.choose_expensive_segment_price !== true) {
623
+ return option;
624
+ }
625
+ const raised = applyChooseExpensiveSegmentPriceToModifiers(option.modifiers ?? []);
626
+ if (raised == null)
627
+ return option;
628
+ return { ...option, modifiers: raised };
629
+ }),
630
+ }));
631
+ return syncOrderEngineItem({ ...rebased, modifiers });
632
+ }
633
+ /**
634
+ * Levels the item's segment VALUE (item price + required option prices — the
635
+ * value `getOrderEngineOptionSegmentValue` / `applyChooseExpensiveSegmentPrice`
636
+ * compare) UP to `floorPrice`, using the same raise mechanics as the rule: the
637
+ * raise lands on the FIRST PRICED element — the item price when non-zero,
638
+ * otherwise the first priced required leaf, otherwise the item price.
639
+ *
640
+ * Used by the drawer that edits a SINGLE half-half segment: the half-half
641
+ * screen passes the max value of the OTHER selected halves as the floor, so
642
+ * the drawer shows the amount this segment is actually charged once the
643
+ * choose_expensive rule levels it. It never lowers.
644
+ */
645
+ export function applySegmentPriceFloor(orderEngineItem, floorPrice) {
646
+ if (!(floorPrice > 0))
647
+ return orderEngineItem;
648
+ const currentValue = (orderEngineItem.price ?? 0) + getRequiredOptionPrices(orderEngineItem.modifiers);
649
+ const delta = floorPrice - currentValue;
650
+ if (delta <= 0)
651
+ return orderEngineItem;
652
+ if ((orderEngineItem.price ?? 0) > 0) {
653
+ return syncOrderEngineItem({ ...orderEngineItem, price: orderEngineItem.price + delta });
654
+ }
655
+ const target = findPricedRequiredLeaf(orderEngineItem.modifiers);
656
+ if (target == null) {
657
+ return syncOrderEngineItem({ ...orderEngineItem, price: (orderEngineItem.price ?? 0) + delta });
658
+ }
659
+ return syncOrderEngineItem({
660
+ ...orderEngineItem,
661
+ modifiers: raiseOptionPriceInModifiers(orderEngineItem.modifiers, target._id, delta),
662
+ });
663
+ }
664
+ function convertCatalogItemModifierToOrderEngineItemModifier({ modifiers, orderItemModifiers, platform, tenantId, excludeRefs, zeroPriceRefs, loyaltyRefs, voucherRefs, keepOptionalModifiersAtBottom, soldoutModifiers, depth = 0, priceReferences, parentPath, isSetupSelection = false, }) {
665
+ function getSortedModifiers(modifiers = []) {
666
+ const sortedModifiers = modifiers.sort((a, b) => a.sort_id - b.sort_id);
667
+ return sortedModifiers;
668
+ }
669
+ function getSortedOptions(options = []) {
670
+ return options.sort((a, b) => a.sort_id - b.sort_id);
671
+ }
672
+ const filteredModifiers = getPlatformModifiers(modifiers, platform);
673
+ const orderEngineModifiers = [];
674
+ if (!platform || !filteredModifiers || filteredModifiers.length === 0)
675
+ return [];
676
+ let sortedModifiers = getSortedModifiers(filteredModifiers);
677
+ if (keepOptionalModifiersAtBottom) {
678
+ const requiredModifiers = [];
679
+ const optionalModifiers = [];
680
+ sortedModifiers.forEach((modifier) => {
681
+ const isRequired = (modifier.min_num_options != null && modifier.min_num_options > 0) ||
682
+ (modifier.min_aggregate_options_quantity != null && modifier.min_aggregate_options_quantity > 0);
683
+ if (isRequired) {
684
+ requiredModifiers.push(modifier);
685
+ }
686
+ else {
687
+ optionalModifiers.push(modifier);
688
+ }
689
+ });
690
+ sortedModifiers = [...requiredModifiers, ...optionalModifiers];
691
+ }
692
+ const sortedModifiersLength = sortedModifiers.length;
693
+ for (let i = 0; i < sortedModifiersLength; i++) {
694
+ const modifier = sortedModifiers[i];
695
+ if (modifier.options.length === 0)
696
+ continue;
697
+ // If excludeRefs is present then we exclude those modifiers
698
+ if (excludeRefs != null && excludeRefs.includes(modifier.ref))
699
+ continue;
700
+ const modifierPath = parentPath ? `${parentPath}_${modifier._id}` : modifier._id;
701
+ const orderItemModifier = orderItemModifiers?.find((orderModifier) => orderModifier._id === modifier._id);
702
+ const hasOrderItemSelectedOptions = orderItemModifier != null && orderItemModifier.options.length > 0;
703
+ const maxDefaultSelections = modifier.max_aggregate_options_quantity ?? modifier.max_num_options ?? modifier.options.length;
704
+ const orderEngineSingleModifier = {
705
+ ...modifier,
706
+ depth,
707
+ default: false,
708
+ options: [],
709
+ };
710
+ const sortedOptions = getSortedOptions(modifier.options);
711
+ const sortedOptionsLength = sortedOptions.length;
712
+ let totalDefaultOptions = 0;
713
+ for (let j = 0; j < sortedOptionsLength; j++) {
714
+ const option = sortedOptions[j];
715
+ if (excludeRefs != null && excludeRefs.includes(option.ref))
716
+ continue;
717
+ // Default values would be used in case of new order. SETUP order items
718
+ // (specials / half-half) may hold the SAME option several times — a
719
+ // repeated pick merged into a quantity, the free/paid split of a
720
+ // partially free special group, or legacy per-slot options — so their
721
+ // occurrences AGGREGATE into the single engine option: the classic
722
+ // edit must not lose units nor flag a "missing selection" for repeated
723
+ // picks (a mixed free/paid set cannot be represented by one option, so
724
+ // any paid occurrence keeps it paid). Regular ITEM conversions keep the
725
+ // original single-match lookup (`find` + destructuring defaults).
726
+ const matchedOptions = isSetupSelection && orderItemModifier != null
727
+ ? orderItemModifier.options.filter((orderOption) => orderOption._id === option._id)
728
+ : [];
729
+ const matchedOption = isSetupSelection
730
+ ? matchedOptions[0]
731
+ : orderItemModifier?.options.find((orderOption) => orderOption._id === option._id);
732
+ const { modifiers: orderItemOptionModifiers, is_free: matchedIsFree = false, price = getPriceEnum(option.price, platform), quantity: matchedQuantity = modifier.min_option_choice_quantity || 1, _id, } = matchedOption ?? {};
733
+ const quantity = isSetupSelection
734
+ ? matchedOptions.reduce((total, orderOption) => total + (orderOption.quantity || 1), 0) ||
735
+ modifier.min_option_choice_quantity ||
736
+ 1
737
+ : matchedQuantity;
738
+ const is_free = isSetupSelection
739
+ ? matchedOptions.length > 0 && matchedOptions.every((orderOption) => orderOption.is_free)
740
+ : matchedIsFree;
741
+ let qty = quantity;
742
+ const isSoldout = option.sold_out.includes(tenantId) || soldoutModifiers?.includes(option.ref);
743
+ let isDefaultOption = false;
744
+ if (!isSoldout && option.active) {
745
+ // In edit flow, use persisted selections as the source of truth.
746
+ if (hasOrderItemSelectedOptions) {
747
+ isDefaultOption = _id != null;
748
+ }
749
+ else {
750
+ isDefaultOption = Boolean(option.default) && totalDefaultOptions < maxDefaultSelections;
751
+ }
752
+ }
753
+ if (isDefaultOption) {
754
+ totalDefaultOptions++;
755
+ }
756
+ else {
757
+ qty = 1;
758
+ }
759
+ const newModifiers = convertCatalogItemModifierToOrderEngineItemModifier({
760
+ modifiers: option.modifiers,
761
+ orderItemModifiers: orderItemOptionModifiers,
762
+ platform,
763
+ tenantId,
764
+ excludeRefs,
765
+ zeroPriceRefs,
766
+ loyaltyRefs,
767
+ voucherRefs,
768
+ keepOptionalModifiersAtBottom,
769
+ soldoutModifiers,
770
+ depth: depth + 1,
771
+ priceReferences,
772
+ parentPath: `${modifierPath}_${option._id}`,
773
+ isSetupSelection,
774
+ });
775
+ // If zeroPriceRefs is present then we set the price to 0
776
+ const isZeroPriced = zeroPriceRefs != null && (zeroPriceRefs.includes(option.ref) || zeroPriceRefs.includes(modifier.ref));
777
+ const optionPrice = isZeroPriced ? 0 : price;
778
+ // ORIGINAL (definition) price of the option — deliberately NOT the
779
+ // persisted order price used above: it is the immutable reference the
780
+ // choose_expensive rule re-bases from (so edit flows can never treat an
781
+ // already-normalized price as the original).
782
+ priceReferences[`${modifierPath}_${option._id}`] = isZeroPriced ? 0 : getPriceEnum(option.price, platform);
783
+ const orderEngineSingleOption = {
784
+ ...option,
785
+ default: isDefaultOption,
786
+ price: optionPrice,
787
+ quantity: qty,
788
+ modifiers: newModifiers,
789
+ // `zeroPriceRefs` (half-half `exclusive_refs`) mutate the PRICE only
790
+ // (`optionPrice` above) — they must never set `is_free`: the "Free"
791
+ // tag belongs exclusively to `num_free_options` options
792
+ // (`makeSpaceForFreeOptions`).
793
+ is_free,
794
+ loyalty_applied: false,
795
+ voucher_applied: false,
796
+ };
797
+ if (loyaltyRefs != null &&
798
+ (loyaltyRefs.includes(orderEngineSingleOption.ref) || loyaltyRefs.includes(modifier.ref))) {
799
+ orderEngineSingleOption.loyalty_applied = true;
800
+ }
801
+ if (voucherRefs != null &&
802
+ (voucherRefs.includes(orderEngineSingleOption.ref) || voucherRefs.includes(modifier.ref))) {
803
+ orderEngineSingleOption.voucher_applied = true;
804
+ }
805
+ orderEngineSingleModifier.options.push(orderEngineSingleOption);
806
+ }
807
+ if (!isSetupSelection && !orderItemModifier) {
808
+ // Regular items: ORIGINAL position — free marking runs BEFORE the
809
+ // lone-option auto-select (pre-existing behavior, untouched).
810
+ const options = makeSpaceForFreeOptions(orderEngineSingleModifier.options, modifier.num_free_options);
811
+ orderEngineSingleModifier.options = options;
812
+ }
813
+ // A required modifier with exactly ONE selectable option left has no real
814
+ // choice — auto-select it so the user doesn't have to pick the only
815
+ // option (e.g. "Half/Half Pizza -> Pizza Size -> Large 13\""). Applied
816
+ // recursively: nested required groups under an option get the same
817
+ // treatment; they only reveal once their parent option is selected.
818
+ // SOLD-OUT lone options are NOT selectable: they stay visible in the
819
+ // drawer (struck through, selection blocked), but are never defaulted —
820
+ // the required group then reports its usual "select an option" error
821
+ // instead of silently charging a sold-out option.
822
+ const isRequiredModifier = (modifier.min_num_options != null && modifier.min_num_options > 0) ||
823
+ (modifier.min_aggregate_options_quantity != null && modifier.min_aggregate_options_quantity > 0);
824
+ if (isRequiredModifier && orderEngineSingleModifier.options.length === 1) {
825
+ const singleOption = orderEngineSingleModifier.options[0];
826
+ const isSingleSoldout = singleOption.sold_out.includes(tenantId) || soldoutModifiers?.includes(singleOption.ref);
827
+ if (!singleOption.default && !isSingleSoldout) {
828
+ orderEngineSingleModifier.options[0] = {
829
+ ...singleOption,
830
+ default: true,
831
+ quantity: modifier.min_option_choice_quantity || 1,
832
+ };
833
+ totalDefaultOptions = 1;
834
+ }
835
+ }
836
+ if (isSetupSelection && !orderItemModifier) {
837
+ // SETUP order items: free marking runs AFTER the lone-option
838
+ // auto-select so the auto-selected option takes part in
839
+ // `num_free_options` too — otherwise a special whose single option
840
+ // covers the free budget would charge for it when submitted without
841
+ // any further interaction.
842
+ const options = makeSpaceForFreeOptions(orderEngineSingleModifier.options, modifier.num_free_options);
843
+ orderEngineSingleModifier.options = options;
844
+ }
845
+ orderEngineSingleModifier.default = totalDefaultOptions > 0;
846
+ orderEngineModifiers.push(orderEngineSingleModifier);
847
+ }
848
+ return orderEngineModifiers;
849
+ }
850
+ /* ==========================================================><==================================================== */
851
+ function convertOrderEngineOptionsToOrderItemOptions(options, tenantId) {
852
+ const newOptions = [];
853
+ for (let i = 0; i < options.length; i++) {
854
+ const option = options[i];
855
+ if (!option.default || !option.active)
856
+ continue;
857
+ newOptions.push({
858
+ _id: option._id,
859
+ ref: option.ref,
860
+ name: option.name,
861
+ price: option.price,
862
+ quantity: option.quantity,
863
+ is_free: option.is_free,
864
+ // Item / half-half options carry their ref_type; normal modifier
865
+ // options omit it.
866
+ ...(option.ref_type != null ? { ref_type: option.ref_type } : {}),
867
+ modifiers: convertOrderEngineModifiersToOrderItemModifiers(option.modifiers, tenantId),
868
+ });
869
+ }
870
+ return newOptions;
871
+ }
872
+ function convertOrderEngineModifiersToOrderItemModifiers(modifiers, tenantId) {
873
+ const newModifiers = [];
874
+ for (let i = 0; i < modifiers.length; i++) {
875
+ const modifier = modifiers[i];
876
+ if (!modifier.default || !modifier.active)
877
+ continue;
878
+ const options = convertOrderEngineOptionsToOrderItemOptions(modifier.options, tenantId);
879
+ if (options.length === 0)
880
+ continue;
881
+ newModifiers.push({
882
+ _id: modifier._id,
883
+ ref: modifier.ref,
884
+ name: modifier.name,
885
+ options,
886
+ });
887
+ }
888
+ return newModifiers;
889
+ }
890
+ function getNormalizedDiscountId(discountId) {
891
+ if (discountId == null)
892
+ return null;
893
+ const normalizedId = discountId.toString().trim();
894
+ return normalizedId.length > 0 ? normalizedId : null;
895
+ }
896
+ function getRewardClaimFromOrderItemDiscountDetails({ itemDiscountDetails, offers, giftCards, }) {
897
+ const loyaltyDiscountId = getNormalizedDiscountId(itemDiscountDetails?.loyalty_discount_id);
898
+ const voucherDiscountId = getNormalizedDiscountId(itemDiscountDetails?.voucher_discount_id);
899
+ if (loyaltyDiscountId == null && voucherDiscountId == null) {
900
+ return undefined;
901
+ }
902
+ const matchedGiftCard = loyaltyDiscountId != null
903
+ ? ((giftCards ?? []).find((giftCard) => giftCard._id === loyaltyDiscountId) ?? null)
904
+ : null;
905
+ if (matchedGiftCard != null) {
906
+ return {
907
+ type: 'gift-card',
908
+ giftCardId: matchedGiftCard._id,
909
+ ...(matchedGiftCard.reward_type != null
910
+ ? {
911
+ mysteryGiftType: matchedGiftCard.reward_type,
912
+ }
913
+ : {}),
914
+ };
915
+ }
916
+ const matchedOfferId = voucherDiscountId != null
917
+ ? ((offers ?? []).find((offer) => offer._id === voucherDiscountId)?._id ?? null)
918
+ : loyaltyDiscountId != null
919
+ ? ((offers ?? []).find((offer) => offer._id === loyaltyDiscountId)?._id ?? null)
920
+ : null;
921
+ if (matchedOfferId == null) {
922
+ return undefined;
923
+ }
924
+ return {
925
+ type: 'offer',
926
+ offerId: matchedOfferId,
927
+ };
928
+ }
929
+ export function convertOrderEngineItemToOrderItem(orderItem, tenantId, offers, giftCards) {
930
+ // When excluded_discount_refs exist, resolve percentage discounts to fixed amounts
931
+ // so that cart-actions (which doesn't know about exclusions) recalculates correctly.
932
+ const item_discount_details = resolveDiscountDetailsForExcludedRefs(orderItem);
933
+ const convertedOrderItem = {
934
+ _id: orderItem._id,
935
+ item_id: orderItem.item_id,
936
+ menu_id: orderItem.menu_id,
937
+ item_type: orderItem.item_type,
938
+ is_ready: orderItem.is_ready,
939
+ is_split: orderItem.is_split,
940
+ moved_to_order_id: orderItem.moved_to_order_id,
941
+ moved_from_order_id: orderItem.moved_from_order_id,
942
+ ready_minutes: orderItem.ready_minutes,
943
+ prep_started_at: orderItem.prep_started_at,
944
+ name: orderItem.name,
945
+ price: orderItem.price,
946
+ subtotal: orderItem.price,
947
+ item_discount_details,
948
+ quantity: orderItem.quantity,
949
+ tax_rate: orderItem.tax_rate,
950
+ special_instructions: orderItem.special_instructions,
951
+ modifiers: convertOrderEngineModifiersToOrderItemModifiers(orderItem.modifiers, tenantId),
952
+ // These values will be auto calculated
953
+ _discount_amount: 0,
954
+ _gross_amount: 0,
955
+ _gst_amount: 0,
956
+ _net_amount: 0,
957
+ };
958
+ const rewardClaim = getRewardClaimFromOrderItemDiscountDetails({
959
+ itemDiscountDetails: convertedOrderItem.item_discount_details,
960
+ offers,
961
+ giftCards,
962
+ });
963
+ return {
964
+ ...convertedOrderItem,
965
+ ...(rewardClaim != null
966
+ ? {
967
+ rewardClaim,
968
+ }
969
+ : {}),
970
+ };
971
+ }
972
+ // ==========================================================><====================================================
973
+ export function convertItemDiscountToOrderItemDiscount(discount_amount, is_special_discount_percentage, platform, discountId) {
974
+ // apply discount to item if its present
975
+ let defaultItemDiscountDetails = null;
976
+ // If it's a new item and there is a discount on the item
977
+ if (discount_amount) {
978
+ const discountAmount = getPriceEnum(discount_amount, platform);
979
+ const discountName = 'Special Discount';
980
+ // apply discount to item
981
+ defaultItemDiscountDetails = {
982
+ ...(defaultItemDiscountDetails ?? {}),
983
+ special_discount: discountAmount,
984
+ special_discount_id: discountId,
985
+ special_discount_name: discountName,
986
+ is_special_discount_percentage,
987
+ // This will be auto calculated
988
+ total_discount: 0,
989
+ };
990
+ }
991
+ return defaultItemDiscountDetails;
992
+ }
993
+ export function convertCatalogItemToOrderEngineItem({ item, orderItem, platform, tenantId, excludeRefs, excludedDiscountRefs, zeroPriceRefs, orderItemType, applyLoyalty, applyVoucher, keepOptionalModifiersAtBottom, defaultMenuId, soldoutModifiers, }) {
994
+ // Default values will be used in case of new order
995
+ // we need to find the applicable schedule for the item
996
+ const applicableSchedule = findApplicableSchedule(item.item_special_hours, platform);
997
+ // Definition prices of every option, keyed by option path — the immutable
998
+ // baseline the UI re-bases from before every price normalization.
999
+ const originalPriceReferences = {};
1000
+ // Setup (specials / half-half) order items slide the setup-only engine
1001
+ // rules (duplicate-occurrence aggregation + free-after-auto-select);
1002
+ // regular ITEM conversions keep the original path.
1003
+ const isSetupSelection = orderItemType === ORDER_ITEM_TYPE_ENUM.SPECIAL || orderItemType === ORDER_ITEM_TYPE_ENUM.HALF_HALF;
1004
+ const orderEngineModifiers = convertCatalogItemModifierToOrderEngineItemModifier({
1005
+ modifiers: item.modifiers,
1006
+ orderItemModifiers: orderItem?.modifiers,
1007
+ platform,
1008
+ tenantId,
1009
+ excludeRefs,
1010
+ zeroPriceRefs,
1011
+ loyaltyRefs: applyLoyalty?.refs,
1012
+ voucherRefs: applyVoucher?.refs,
1013
+ keepOptionalModifiersAtBottom,
1014
+ soldoutModifiers,
1015
+ priceReferences: originalPriceReferences,
1016
+ parentPath: '',
1017
+ isSetupSelection,
1018
+ });
1019
+ let itemPrice = item.price;
1020
+ let discount_amount = item.discount_amount;
1021
+ let is_special_discount_percentage = item.is_discount_percentage;
1022
+ const defaultItemPrice = zeroPriceRefs != null && zeroPriceRefs.includes(item._id) ? 0 : getPriceEnum(itemPrice, platform);
1023
+ // if applicable schedule is an object then we need to check its price and discount
1024
+ if (typeof applicableSchedule !== 'boolean') {
1025
+ // apply price to item if its present
1026
+ if (applicableSchedule.price != null) {
1027
+ itemPrice = applicableSchedule.price;
1028
+ }
1029
+ // apply discount to item if its present
1030
+ if (applicableSchedule.discount_amount != null) {
1031
+ discount_amount = applicableSchedule.discount_amount;
1032
+ is_special_discount_percentage = applicableSchedule.is_discount_percentage;
1033
+ }
1034
+ }
1035
+ const { _id = ObjectID().toHexString(), menu_id = defaultMenuId,
1036
+ // For New Item, If zeroPriceRefs is present then we set the price to 0
1037
+ price = defaultItemPrice, tax_rate = getPriceEnum(item.tax_rate, platform), quantity = 1, subtotal = 0, special_instructions = '', item_discount_details = convertItemDiscountToOrderItemDiscount(discount_amount, is_special_discount_percentage, platform, item._id), item_type = orderItemType, is_ready, is_split, moved_to_order_id, moved_from_order_id, ready_minutes, prep_started_at, } = orderItem ?? {};
1038
+ const loyaltyApplied = applyLoyalty != null && applyLoyalty.refs.includes(item._id);
1039
+ const voucherApplied = applyVoucher != null && applyVoucher.refs.includes(item._id);
1040
+ let mergedItemDiscountDetails = item_discount_details;
1041
+ if (loyaltyApplied && applyLoyalty != null) {
1042
+ const loyaltyDiscountDetails = applyLoyalty.discount_details ?? {
1043
+ discount_value: 100,
1044
+ is_discount_percentage: true,
1045
+ };
1046
+ const loyaltyDiscountReason = applyLoyalty.name?.trim() || undefined;
1047
+ mergedItemDiscountDetails = {
1048
+ ...(mergedItemDiscountDetails ?? { total_discount: 0 }),
1049
+ loyalty_discount_id: applyLoyalty.loyalty_id,
1050
+ loyalty_discount_name: applyLoyalty.name,
1051
+ loyalty_discount: loyaltyDiscountDetails.discount_value,
1052
+ is_loyalty_discount_percentage: loyaltyDiscountDetails.is_discount_percentage,
1053
+ loyalty_discount_reason: loyaltyDiscountReason,
1054
+ };
1055
+ }
1056
+ if (voucherApplied && applyVoucher != null) {
1057
+ const voucherDiscountDetails = applyVoucher.discount_details ?? {
1058
+ discount_value: 100,
1059
+ is_discount_percentage: true,
1060
+ };
1061
+ const voucherDiscountReason = applyVoucher.name?.trim() || undefined;
1062
+ mergedItemDiscountDetails = {
1063
+ ...(mergedItemDiscountDetails ?? { total_discount: 0 }),
1064
+ voucher_discount_id: applyVoucher.voucher_id,
1065
+ voucher_discount_name: applyVoucher.name,
1066
+ voucher_discount: voucherDiscountDetails.discount_value,
1067
+ is_voucher_discount_percentage: voucherDiscountDetails.is_discount_percentage,
1068
+ voucher_discount_reason: voucherDiscountReason,
1069
+ };
1070
+ }
1071
+ const orderEngineItem = syncOrderEngineItem({
1072
+ _id,
1073
+ category_id: item.category_id,
1074
+ item_id: item._id,
1075
+ name: item.name,
1076
+ description: item.description,
1077
+ image_url: item.image_url,
1078
+ // For Edit Case
1079
+ menu_id,
1080
+ item_type,
1081
+ is_ready,
1082
+ is_split,
1083
+ moved_to_order_id,
1084
+ moved_from_order_id,
1085
+ ready_minutes,
1086
+ prep_started_at,
1087
+ price,
1088
+ tax_rate,
1089
+ quantity,
1090
+ subtotal,
1091
+ gross_total: 0,
1092
+ loyalty_applied: loyaltyApplied,
1093
+ voucher_applied: voucherApplied,
1094
+ special_instructions,
1095
+ excluded_discount_refs: excludedDiscountRefs,
1096
+ item_discount_details: mergedItemDiscountDetails,
1097
+ modifiers: orderEngineModifiers,
1098
+ });
1099
+ return { originalPriceReferences, workingData: orderEngineItem };
1100
+ }
1101
+ export function hasRequiredModifier(currentModifiers) {
1102
+ if (!currentModifiers)
1103
+ return false;
1104
+ return currentModifiers.some((modifier) => modifier.active && Boolean(modifier.min_num_options || modifier.min_aggregate_options_quantity));
1105
+ }
1106
+ /* ==========================================================><==================================================== */
1107
+ function convertOptionsToOrderItemOptions(options, min_option_choice_quantity, platform, is_free = false, tenantId) {
1108
+ if (!platform)
1109
+ return [];
1110
+ const newOptions = [];
1111
+ for (let i = 0; i < options.length; i++) {
1112
+ const option = options[i];
1113
+ if (!option.default || !option.active || option.excluded_platforms.includes(platform))
1114
+ continue;
1115
+ const price = getPriceEnum(option.price, platform);
1116
+ newOptions.push({
1117
+ _id: option._id,
1118
+ ref: option.ref,
1119
+ name: option.name,
1120
+ price,
1121
+ quantity: min_option_choice_quantity || 1,
1122
+ is_free,
1123
+ modifiers: convertItemModifiersToOrderItemModifiers(option.modifiers, platform, tenantId),
1124
+ });
1125
+ }
1126
+ return newOptions;
1127
+ }
1128
+ function convertItemModifiersToOrderItemModifiers(modifiers, platform, tenantId) {
1129
+ if (!modifiers || !platform)
1130
+ return [];
1131
+ const newModifiers = [];
1132
+ for (let i = 0; i < modifiers.length; i++) {
1133
+ const modifier = modifiers[i];
1134
+ if (!modifier.active)
1135
+ continue;
1136
+ const options = convertOptionsToOrderItemOptions(modifier.options, modifier.min_option_choice_quantity, platform, false, tenantId);
1137
+ if (options.length === 0)
1138
+ continue;
1139
+ newModifiers.push({
1140
+ _id: modifier._id,
1141
+ ref: modifier.ref,
1142
+ name: modifier.name,
1143
+ options,
1144
+ });
1145
+ }
1146
+ return newModifiers;
1147
+ }
1148
+ export function convertItemToOrderItem(item, menu_id, platform, tenantId, orderItemType = ORDER_ITEM_TYPE_ENUM.ITEM) {
1149
+ const _id = ObjectID().toHexString();
1150
+ const price = getPriceEnum(item.price, platform);
1151
+ const tax_rate = getPriceEnum(item.tax_rate, platform);
1152
+ // apply discount to item if its present
1153
+ let defaultItemDiscountDetails = null;
1154
+ // If it's a new item and there is a discount on the item
1155
+ if (item.discount_amount != null) {
1156
+ const discountAmount = getPriceEnum(item.discount_amount, platform);
1157
+ const discountId = item._id;
1158
+ const discountName = 'Special Discount';
1159
+ // apply discount to item
1160
+ defaultItemDiscountDetails = {
1161
+ ...(defaultItemDiscountDetails ?? {}),
1162
+ special_discount: discountAmount,
1163
+ special_discount_id: discountId,
1164
+ special_discount_name: discountName,
1165
+ is_special_discount_percentage: item.is_discount_percentage,
1166
+ // This will be auto calculated
1167
+ total_discount: 0,
1168
+ };
1169
+ }
1170
+ return {
1171
+ _id,
1172
+ item_id: item._id,
1173
+ menu_id,
1174
+ item_type: orderItemType,
1175
+ name: item.name,
1176
+ price,
1177
+ subtotal: price,
1178
+ quantity: 1,
1179
+ special_instructions: '',
1180
+ item_discount_details: defaultItemDiscountDetails,
1181
+ tax_rate,
1182
+ modifiers: convertItemModifiersToOrderItemModifiers(item.modifiers, platform, tenantId),
1183
+ // These values will be auto calculated
1184
+ _discount_amount: 0,
1185
+ _gross_amount: 0,
1186
+ _gst_amount: 0,
1187
+ _net_amount: 0,
1188
+ };
1189
+ }
1190
+ /*
1191
+
1192
+ */
1193
+ export function setCheckFieldInOrderEngineItem(orderEngineItem, identifier, shouldCheck, chooseExpensiveSegmentPrice) {
1194
+ const setUpdateOptions = (modifier, ids, level) => {
1195
+ const optionId = ids[level];
1196
+ if (!optionId)
1197
+ return modifier.options;
1198
+ const isLastLevel = level === ids.length - 1 || level === ids.length - 2;
1199
+ const isRadioType = modifier.max_num_options === 1;
1200
+ const isChoiceType = modifier.min_option_choice_quantity != null || modifier.max_option_choice_quantity != null;
1201
+ const maxNumOptions = modifier.max_num_options ?? 0;
1202
+ const maxAggregate = (modifier.max_aggregate_options_quantity != null && modifier.max_aggregate_options_quantity > maxNumOptions
1203
+ ? modifier.max_aggregate_options_quantity
1204
+ : maxNumOptions) || modifier.options.length;
1205
+ let newOptions = [];
1206
+ let totalDefaults = 0;
1207
+ for (let i = 0; i < modifier.options.length; i++) {
1208
+ let option = modifier.options[i];
1209
+ let isDefault = option.default;
1210
+ let modifiers = option.modifiers;
1211
+ let quantity = option.quantity || 1;
1212
+ if (option._id === optionId) {
1213
+ if (isLastLevel) {
1214
+ isDefault = shouldCheck;
1215
+ }
1216
+ else {
1217
+ isDefault = true;
1218
+ modifiers = setUpdateModifiers(option.modifiers, ids, level + 1);
1219
+ }
1220
+ }
1221
+ if (isChoiceType) {
1222
+ if (isDefault) {
1223
+ if (isLastLevel && option._id === optionId) {
1224
+ quantity = modifier.min_option_choice_quantity || 1;
1225
+ }
1226
+ totalDefaults += quantity;
1227
+ }
1228
+ else {
1229
+ quantity = 1;
1230
+ }
1231
+ }
1232
+ else if (isRadioType) {
1233
+ if (option._id !== optionId && shouldCheck) {
1234
+ isDefault = false;
1235
+ }
1236
+ quantity = 1;
1237
+ }
1238
+ else {
1239
+ quantity = 1;
1240
+ if (isDefault) {
1241
+ totalDefaults += quantity;
1242
+ }
1243
+ }
1244
+ option = { ...option, default: isDefault, modifiers, quantity };
1245
+ newOptions.push(option);
1246
+ }
1247
+ if (isLastLevel) {
1248
+ if (totalDefaults > maxAggregate) {
1249
+ newOptions = newOptions.map((option) => (option._id === optionId ? { ...option, default: false } : option));
1250
+ }
1251
+ newOptions = makeSpaceForFreeOptions(newOptions, modifier.num_free_options);
1252
+ }
1253
+ return newOptions;
1254
+ };
1255
+ const setUpdateModifiers = (currentModifiers, ids, level) => {
1256
+ const modifierId = ids[level];
1257
+ if (!modifierId)
1258
+ return currentModifiers;
1259
+ const newModifiers = [];
1260
+ for (let i = 0; i < currentModifiers.length; i++) {
1261
+ let modifier = currentModifiers[i];
1262
+ if (modifier._id === modifierId) {
1263
+ const options = setUpdateOptions(modifier, ids, level + 1);
1264
+ modifier = { ...modifier, default: true, options };
1265
+ }
1266
+ newModifiers.push(modifier);
1267
+ }
1268
+ return newModifiers;
1269
+ };
1270
+ const allIds = identifier.split('_').filter((id) => id.trim() !== '');
1271
+ const modifiers = setUpdateModifiers(orderEngineItem.modifiers, allIds, 0);
1272
+ const updatedOrderEngineItem = syncOrderEngineItem({ ...orderEngineItem, modifiers });
1273
+ // `choose_expensive_segment_price` is NOT applied here: price normalization
1274
+ // has a single entry point (`applyChooseExpensiveSegmentPrice` /
1275
+ // `applyNestedChooseExpensiveSegmentPrice`, called with the original price
1276
+ // references by the drawer after this mutation). The flag parameter is kept
1277
+ // for API compatibility and ignored.
1278
+ void chooseExpensiveSegmentPrice;
1279
+ return updatedOrderEngineItem;
1280
+ }
1281
+ export function setIncrementOrderEngineItemQuantity(orderEngineItem, increment, isAbs) {
1282
+ const newQuantity = isAbs ? Math.abs(increment) || 1 : increment + orderEngineItem.quantity;
1283
+ const item_discount_details = getItemQuantityChangeResults({
1284
+ newQuantity,
1285
+ prevQuantity: orderEngineItem.quantity,
1286
+ prevItemDiscountDetails: orderEngineItem.item_discount_details,
1287
+ });
1288
+ const updatedOrderEngineItem = syncOrderEngineItem({
1289
+ ...orderEngineItem,
1290
+ quantity: newQuantity,
1291
+ item_discount_details,
1292
+ });
1293
+ return updatedOrderEngineItem;
1294
+ }
1295
+ export function setUpdateSelectedOrderEngineOptionQuantity(orderEngineItem, identifier, newQuantity, isIncrement) {
1296
+ const setUpdateOptions = (modifier, ids, level) => {
1297
+ const optionId = ids[level];
1298
+ if (!optionId)
1299
+ return modifier.options;
1300
+ const isLastLevel = level === ids.length - 1 || level === ids.length - 2;
1301
+ const minChoiceQty = modifier.min_option_choice_quantity || 1;
1302
+ const maxNumOptions = modifier.max_num_options ?? 0;
1303
+ const maxAggregate = (modifier.max_aggregate_options_quantity != null && modifier.max_aggregate_options_quantity > maxNumOptions
1304
+ ? modifier.max_aggregate_options_quantity
1305
+ : maxNumOptions) || modifier.options.length;
1306
+ let newOptions = [];
1307
+ let totalDefaults = 0;
1308
+ let prevOptionQuantity = 1;
1309
+ for (let i = 0; i < modifier.options.length; i++) {
1310
+ let option = modifier.options[i];
1311
+ let quantity = option.quantity || 1;
1312
+ let modifiers = option.modifiers;
1313
+ let isDefault = option.default;
1314
+ if (option._id === optionId) {
1315
+ if (isLastLevel) {
1316
+ prevOptionQuantity = quantity;
1317
+ quantity = isIncrement ? quantity + newQuantity : newQuantity;
1318
+ // If quantity is less than the threshold, unselect the option and set quantity to 1
1319
+ if (quantity < minChoiceQty) {
1320
+ isDefault = false;
1321
+ quantity = 1;
1322
+ }
1323
+ }
1324
+ else {
1325
+ modifiers = setUpdateModifiers(option.modifiers, ids, level + 1);
1326
+ }
1327
+ }
1328
+ if (isDefault) {
1329
+ totalDefaults += quantity;
1330
+ }
1331
+ option = { ...option, default: isDefault, quantity, modifiers };
1332
+ newOptions.push(option);
1333
+ }
1334
+ if (isLastLevel) {
1335
+ if (totalDefaults > maxAggregate) {
1336
+ newOptions = newOptions.map((option) => option._id === optionId ? { ...option, quantity: prevOptionQuantity || 1 } : option);
1337
+ }
1338
+ newOptions = makeSpaceForFreeOptions(newOptions, modifier.num_free_options);
1339
+ }
1340
+ return newOptions;
1341
+ };
1342
+ const setUpdateModifiers = (currentModifiers, ids, level) => {
1343
+ const modifierId = ids[level];
1344
+ if (!modifierId)
1345
+ return currentModifiers;
1346
+ const newModifiers = [];
1347
+ for (let i = 0; i < currentModifiers.length; i++) {
1348
+ let modifier = currentModifiers[i];
1349
+ if (modifier._id === modifierId) {
1350
+ const options = setUpdateOptions(modifier, ids, level + 1);
1351
+ modifier = { ...modifier, options };
1352
+ }
1353
+ newModifiers.push(modifier);
1354
+ }
1355
+ return newModifiers;
1356
+ };
1357
+ const allIds = identifier.split('_').filter((id) => id.trim() !== '');
1358
+ const modifiers = setUpdateModifiers(orderEngineItem.modifiers, allIds, 0);
1359
+ const updatedOrderEngineItem = syncOrderEngineItem({ ...orderEngineItem, modifiers });
1360
+ return updatedOrderEngineItem;
1361
+ }
1362
+ export function getFlattenedOrderEngineItemModifiers(modifiers, keepOptionalModifiersAtBottom) {
1363
+ let result = [];
1364
+ const flatten = (modifiers, parentId = '') => {
1365
+ modifiers.forEach((modifier) => {
1366
+ let newParentId = `${parentId}_${modifier._id}`;
1367
+ if (parentId.length === 0) {
1368
+ newParentId = modifier._id;
1369
+ }
1370
+ const updatedOptions = [...modifier.options];
1371
+ const subModifiers = [];
1372
+ modifier.options?.forEach((option, index) => {
1373
+ if (option.default && option.modifiers.length > 0) {
1374
+ updatedOptions[index] = {
1375
+ ...option,
1376
+ modifiers: [],
1377
+ };
1378
+ option.modifiers.forEach((subModifier) => {
1379
+ const updatedSubModifier = {
1380
+ ...subModifier,
1381
+ _id: `${option._id}_${subModifier._id}`,
1382
+ name: `${option.name} › ${subModifier.name}`,
1383
+ };
1384
+ subModifiers.push(updatedSubModifier);
1385
+ });
1386
+ }
1387
+ });
1388
+ result.push({ ...modifier, _id: newParentId, options: updatedOptions });
1389
+ flatten(subModifiers, newParentId);
1390
+ });
1391
+ };
1392
+ flatten(modifiers);
1393
+ if (keepOptionalModifiersAtBottom) {
1394
+ const required = [];
1395
+ const optional = [];
1396
+ result.forEach((modifier) => {
1397
+ const isRequired = (modifier.min_num_options != null && modifier.min_num_options > 0) ||
1398
+ (modifier.min_aggregate_options_quantity != null && modifier.min_aggregate_options_quantity > 0);
1399
+ if (isRequired) {
1400
+ required.push(modifier);
1401
+ }
1402
+ else {
1403
+ optional.push(modifier);
1404
+ }
1405
+ });
1406
+ result = [...required, ...optional];
1407
+ }
1408
+ return result;
1409
+ }