@managesome/eposmatic-toolkit 0.3.8 → 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 (436) 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/package.json +6 -3
@@ -0,0 +1,3351 @@
1
+ import { CUSTOMER_REDEMPTION_TYPE_ENUM, OFFER_REWARD_TYPE_ENUM, PATHWAY_TO_UNLOCK_TYPE_ENUM, PATHWAY_TO_UNLOCK_TYPE_ORDERS_SCOPE_ENUM, PLATFORMS_BY_ORDER_FROM, WALLET_CASHBACK_LOYALTY_DISCOUNT_ID, } from '../../constants';
2
+ import { calculateEligibleOfferDiscountDetails, parseNum } from './common';
3
+ import { findApplicableSchedule } from './platform-catalog';
4
+ import { convertSpecialHoursFromCents, convertSpecialHoursToCents } from './platform-num';
5
+ import { convertPriceFromCents, convertPriceToCents } from './price-conversion';
6
+ import { getWalletGiftCardRedemptionClaims } from './wallet-redemption-helpers';
7
+ export function getOfferWithPrice(offer, writeable) {
8
+ // const convertToPrice = writeable ? convertPriceObjToCents : convertPriceObjFromCents;
9
+ const convertItemSpecialHours = writeable ? convertSpecialHoursToCents : convertSpecialHoursFromCents;
10
+ const convertToNum = writeable ? convertPriceToCents : convertPriceFromCents;
11
+ const newOffer = {
12
+ ...offer,
13
+ };
14
+ if (writeable) {
15
+ if (newOffer.offer_special_hours != null && newOffer.offer_special_hours.length === 0) {
16
+ newOffer.offer_special_hours = null;
17
+ }
18
+ // Always remove non-selected pathway payloads based on selector.
19
+ if (newOffer.pathway_to_unlock_type === PATHWAY_TO_UNLOCK_TYPE_ENUM.ITEMS) {
20
+ delete newOffer.pathway_to_unlock_type_orders;
21
+ delete newOffer.pathway_to_unlock_type_points;
22
+ delete newOffer.pathway_to_unlock_type_vouchers;
23
+ }
24
+ else if (newOffer.pathway_to_unlock_type === PATHWAY_TO_UNLOCK_TYPE_ENUM.ORDERS) {
25
+ delete newOffer.pathway_to_unlock_type_items;
26
+ delete newOffer.pathway_to_unlock_type_points;
27
+ delete newOffer.pathway_to_unlock_type_vouchers;
28
+ }
29
+ else if (newOffer.pathway_to_unlock_type === PATHWAY_TO_UNLOCK_TYPE_ENUM.POINTS) {
30
+ delete newOffer.pathway_to_unlock_type_items;
31
+ delete newOffer.pathway_to_unlock_type_orders;
32
+ delete newOffer.pathway_to_unlock_type_vouchers;
33
+ }
34
+ else if (newOffer.pathway_to_unlock_type === PATHWAY_TO_UNLOCK_TYPE_ENUM.VOUCHER) {
35
+ delete newOffer.pathway_to_unlock_type_items;
36
+ delete newOffer.pathway_to_unlock_type_orders;
37
+ delete newOffer.pathway_to_unlock_type_points;
38
+ }
39
+ // Always remove non-selected reward payloads based on selector.
40
+ if (newOffer.reward_type === OFFER_REWARD_TYPE_ENUM.ITEMS) {
41
+ delete newOffer.reward_discount;
42
+ delete newOffer.reward_discount_items;
43
+ delete newOffer.reward_points;
44
+ delete newOffer.reward_cashback;
45
+ delete newOffer.reward_gift_cards;
46
+ delete newOffer.reward_voucher;
47
+ }
48
+ else if (newOffer.reward_type === OFFER_REWARD_TYPE_ENUM.DISCOUNT) {
49
+ delete newOffer.reward_items;
50
+ delete newOffer.reward_discount_items;
51
+ delete newOffer.reward_points;
52
+ delete newOffer.reward_cashback;
53
+ delete newOffer.reward_gift_cards;
54
+ delete newOffer.reward_voucher;
55
+ }
56
+ else if (newOffer.reward_type === OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS) {
57
+ delete newOffer.reward_items;
58
+ delete newOffer.reward_points;
59
+ delete newOffer.reward_discount;
60
+ delete newOffer.reward_cashback;
61
+ delete newOffer.reward_gift_cards;
62
+ delete newOffer.reward_voucher;
63
+ }
64
+ else if (newOffer.reward_type === OFFER_REWARD_TYPE_ENUM.POINTS) {
65
+ delete newOffer.reward_items;
66
+ delete newOffer.reward_discount;
67
+ delete newOffer.reward_discount_items;
68
+ delete newOffer.reward_cashback;
69
+ delete newOffer.reward_gift_cards;
70
+ delete newOffer.reward_voucher;
71
+ }
72
+ else if (newOffer.reward_type === OFFER_REWARD_TYPE_ENUM.CASHBACK) {
73
+ delete newOffer.reward_items;
74
+ delete newOffer.reward_discount;
75
+ delete newOffer.reward_discount_items;
76
+ delete newOffer.reward_points;
77
+ delete newOffer.reward_gift_cards;
78
+ delete newOffer.reward_voucher;
79
+ }
80
+ else if (newOffer.reward_type === OFFER_REWARD_TYPE_ENUM.GIFT_CARDS) {
81
+ delete newOffer.reward_items;
82
+ delete newOffer.reward_discount;
83
+ delete newOffer.reward_discount_items;
84
+ delete newOffer.reward_points;
85
+ delete newOffer.reward_cashback;
86
+ delete newOffer.reward_voucher;
87
+ }
88
+ else if (newOffer.reward_type === OFFER_REWARD_TYPE_ENUM.VOUCHER) {
89
+ delete newOffer.reward_items;
90
+ delete newOffer.reward_discount;
91
+ delete newOffer.reward_discount_items;
92
+ delete newOffer.reward_points;
93
+ delete newOffer.reward_cashback;
94
+ delete newOffer.reward_gift_cards;
95
+ }
96
+ if (newOffer.reward_type === OFFER_REWARD_TYPE_ENUM.DISCOUNT && newOffer.reward_discount != null) {
97
+ if (newOffer.reward_discount.is_discount_percentage) {
98
+ newOffer.reward_discount.max_discount_percentage = null;
99
+ }
100
+ else {
101
+ newOffer.reward_discount.max_discount_amount = null;
102
+ }
103
+ }
104
+ }
105
+ return {
106
+ ...newOffer,
107
+ ...(newOffer.offer_special_hours != null
108
+ ? {
109
+ offer_special_hours: convertItemSpecialHours(newOffer.offer_special_hours),
110
+ }
111
+ : {}),
112
+ ...(newOffer.pathway_to_unlock_type_orders != null
113
+ ? {
114
+ pathway_to_unlock_type_orders: {
115
+ ...newOffer.pathway_to_unlock_type_orders,
116
+ total_amount: convertToNum(newOffer.pathway_to_unlock_type_orders.total_amount),
117
+ max_amount: newOffer.pathway_to_unlock_type_orders.max_amount != null
118
+ ? convertToNum(newOffer.pathway_to_unlock_type_orders.max_amount)
119
+ : null,
120
+ },
121
+ }
122
+ : {}),
123
+ ...(newOffer.pathway_to_unlock_type_items != null
124
+ ? {
125
+ pathway_to_unlock_type_items: {
126
+ ...newOffer.pathway_to_unlock_type_items,
127
+ total_amount: convertToNum(newOffer.pathway_to_unlock_type_items.total_amount),
128
+ },
129
+ }
130
+ : {}),
131
+ ...(newOffer.pathway_to_unlock_type_points != null
132
+ ? {
133
+ pathway_to_unlock_type_points: {
134
+ ...newOffer.pathway_to_unlock_type_points,
135
+ total_amount: convertToNum(newOffer.pathway_to_unlock_type_points.total_amount),
136
+ },
137
+ }
138
+ : {}),
139
+ ...(newOffer.pathway_to_unlock_type_vouchers != null
140
+ ? {
141
+ pathway_to_unlock_type_vouchers: {
142
+ ...newOffer.pathway_to_unlock_type_vouchers,
143
+ total_amount: convertToNum(newOffer.pathway_to_unlock_type_vouchers.total_amount),
144
+ max_amount: newOffer.pathway_to_unlock_type_vouchers.max_amount != null
145
+ ? convertToNum(newOffer.pathway_to_unlock_type_vouchers.max_amount)
146
+ : null,
147
+ },
148
+ }
149
+ : {}),
150
+ ...(newOffer.reward_discount != null
151
+ ? {
152
+ reward_discount: {
153
+ ...newOffer.reward_discount,
154
+ discount_value: convertToNum(newOffer.reward_discount.discount_value),
155
+ max_discount_amount: newOffer.reward_discount.max_discount_amount != null
156
+ ? convertToNum(newOffer.reward_discount.max_discount_amount)
157
+ : null,
158
+ max_discount_percentage: newOffer.reward_discount.max_discount_percentage != null
159
+ ? convertToNum(newOffer.reward_discount.max_discount_percentage)
160
+ : null,
161
+ },
162
+ }
163
+ : {}),
164
+ ...(newOffer.reward_discount_items != null
165
+ ? {
166
+ reward_discount_items: {
167
+ ...newOffer.reward_discount_items,
168
+ discount_value: convertToNum(newOffer.reward_discount_items.discount_value),
169
+ },
170
+ }
171
+ : {}),
172
+ ...(newOffer.reward_cashback != null
173
+ ? {
174
+ reward_cashback: {
175
+ ...newOffer.reward_cashback,
176
+ cashback_value: convertToNum(newOffer.reward_cashback.cashback_value),
177
+ max_cashback_amount: newOffer.reward_cashback.max_cashback_amount != null
178
+ ? convertToNum(newOffer.reward_cashback.max_cashback_amount)
179
+ : null,
180
+ },
181
+ }
182
+ : {}),
183
+ ...(newOffer.reward_gift_cards != null
184
+ ? {
185
+ reward_gift_cards: {
186
+ ...newOffer.reward_gift_cards,
187
+ },
188
+ }
189
+ : {}),
190
+ };
191
+ }
192
+ // ====================================================================================================================
193
+ export function convertOffersToWorkableOffers(offers, platform) {
194
+ const filteredOffers = [];
195
+ for (let i = 0; i < offers.length; i++) {
196
+ const offer = offers[i];
197
+ if (!offer.active || !offer.included_platforms.includes(platform)) {
198
+ continue;
199
+ }
200
+ // we try to find a schedule that is applicable to the current date and time
201
+ const applicableSchedule = findApplicableSchedule(offer.offer_special_hours, platform);
202
+ // if there is no applicable schedule, we skip the item
203
+ if (applicableSchedule === false)
204
+ continue;
205
+ filteredOffers.push(offer);
206
+ }
207
+ filteredOffers.sort((a, b) => a.sort_id - b.sort_id);
208
+ return filteredOffers;
209
+ }
210
+ // ====================================================================================================================
211
+ function calculatePointsRedeemedForOffer(redeemedOffer, totalOrderPrice, categories, claimedTimes) {
212
+ if (redeemedOffer.reward_type !== OFFER_REWARD_TYPE_ENUM.POINTS || redeemedOffer.reward_points == null) {
213
+ return 0;
214
+ }
215
+ let times = 1;
216
+ if (!redeemedOffer.reward_points.once_per_order) {
217
+ const getUnlockTimesByOrderAmount = (orderValue, totalAmount) => {
218
+ const safeRequiredAmount = Math.max(1, totalAmount || 1);
219
+ return Math.max(1, Math.floor(orderValue / safeRequiredAmount));
220
+ };
221
+ // This means that we need to see if the condition to unlock the redeemedOffer is met multiple times
222
+ // i.e. if the customer has ordered 2 pizzas, and the redeemedOffer is applicable for 1 pizza
223
+ // then we need to calculate the points redeemed for 2 pizzas
224
+ if (redeemedOffer.pathway_to_unlock_type === PATHWAY_TO_UNLOCK_TYPE_ENUM.ITEMS) {
225
+ if (redeemedOffer.pathway_to_unlock_type_items != null) {
226
+ const { num_of_items, max_claims, min_same_item_quantity, max_same_item_quantity, total_amount, excluded_refs, exclusive_refs, item_ids, category_ids, } = redeemedOffer.pathway_to_unlock_type_items;
227
+ // A Bachelor Item is an item that meets the criteria of the redeemedOffer and doesn't have any redeemedOffer applied to it
228
+ const bachelorItems = getCartItemsApplicableToOfferItemsQuantity({
229
+ categories,
230
+ excluded_refs,
231
+ exclusive_refs,
232
+ item_ids,
233
+ category_ids,
234
+ min_same_item_quantity,
235
+ max_same_item_quantity,
236
+ });
237
+ if (bachelorItems >= num_of_items) {
238
+ if (totalOrderPrice >= total_amount) {
239
+ const timesForItems = Math.floor(bachelorItems / (num_of_items || 1));
240
+ const timesForAmount = Math.floor(totalOrderPrice / (total_amount || 1));
241
+ // we need to find the minimum of the two
242
+ const minTimes = Math.min(timesForItems, timesForAmount);
243
+ const maxClaims = max_claims == null ? Infinity : Math.max(1, max_claims);
244
+ const cappedTimes = Math.min(minTimes, maxClaims);
245
+ if (cappedTimes > 1) {
246
+ times = cappedTimes;
247
+ }
248
+ }
249
+ }
250
+ }
251
+ }
252
+ else if (redeemedOffer.pathway_to_unlock_type === PATHWAY_TO_UNLOCK_TYPE_ENUM.ORDERS) {
253
+ if (redeemedOffer.pathway_to_unlock_type_orders != null) {
254
+ const { total_amount, max_amount, max_claims } = redeemedOffer.pathway_to_unlock_type_orders;
255
+ if (totalOrderPrice >= total_amount && (max_amount == null || totalOrderPrice <= max_amount)) {
256
+ const timesForAmount = getUnlockTimesByOrderAmount(totalOrderPrice, total_amount);
257
+ const maxClaims = max_claims == null ? Infinity : Math.max(1, max_claims);
258
+ times = Math.min(timesForAmount, maxClaims);
259
+ }
260
+ }
261
+ }
262
+ else if (redeemedOffer.pathway_to_unlock_type === PATHWAY_TO_UNLOCK_TYPE_ENUM.VOUCHER) {
263
+ if (redeemedOffer.pathway_to_unlock_type_vouchers != null) {
264
+ const { total_amount, max_amount, max_claims } = redeemedOffer.pathway_to_unlock_type_vouchers;
265
+ if (totalOrderPrice >= total_amount && (max_amount == null || totalOrderPrice <= max_amount)) {
266
+ const timesForAmount = getUnlockTimesByOrderAmount(totalOrderPrice, total_amount);
267
+ const maxClaims = max_claims == null ? Infinity : Math.max(1, max_claims);
268
+ times = Math.min(timesForAmount, maxClaims);
269
+ }
270
+ }
271
+ }
272
+ // 💡 NOTE: We don't need to check for pathway_to_unlock_type_points because it is not possible to have
273
+ // pathway_to_unlock_type_points and reward_points at the same time
274
+ }
275
+ if (claimedTimes != null && Number.isFinite(claimedTimes) && claimedTimes > 0) {
276
+ times = Math.min(times, Math.floor(claimedTimes));
277
+ }
278
+ let pointsRedeemed = redeemedOffer.reward_points.num_of_points ?? 0;
279
+ pointsRedeemed *= times;
280
+ return pointsRedeemed;
281
+ }
282
+ function normalizeVoucherCode(voucherCode) {
283
+ const normalizedCode = voucherCode?.trim().toUpperCase();
284
+ return normalizedCode != null && normalizedCode.length > 0 ? normalizedCode : null;
285
+ }
286
+ function normalizeGiftCardCode(giftCardCode) {
287
+ const normalizedCode = giftCardCode?.trim().toUpperCase();
288
+ return normalizedCode != null && normalizedCode.length > 0 ? normalizedCode : null;
289
+ }
290
+ function getOfferRedeemedClaims(redeemedOffers, offerId) {
291
+ const redeemedTimes = Number(redeemedOffers?.[offerId]);
292
+ if (Number.isFinite(redeemedTimes) && redeemedTimes > 0) {
293
+ return Math.floor(redeemedTimes);
294
+ }
295
+ return 0;
296
+ }
297
+ export function getVoucherPathwayCartContext({ offers, vouchers, redeemedOffers, orderDiscountDetails, }) {
298
+ const consumedVoucherCodes = new Set();
299
+ const consumedVoucherIds = new Set();
300
+ const redeemedOfferIds = new Set();
301
+ const voucherCodeById = new Map();
302
+ const referencedVoucherCode = normalizeVoucherCode(orderDiscountDetails?.voucher_reference_number);
303
+ if (vouchers != null) {
304
+ for (let i = 0; i < vouchers.length; i++) {
305
+ const voucher = vouchers[i];
306
+ const normalizedVoucherCode = normalizeVoucherCode(voucher.code);
307
+ if (normalizedVoucherCode == null)
308
+ continue;
309
+ voucherCodeById.set(voucher._id, normalizedVoucherCode);
310
+ }
311
+ }
312
+ for (let i = 0; i < offers.length; i++) {
313
+ const offer = offers[i];
314
+ if (offer.pathway_to_unlock_type !== PATHWAY_TO_UNLOCK_TYPE_ENUM.VOUCHER) {
315
+ continue;
316
+ }
317
+ const redeemedTimes = getOfferRedeemedClaims(redeemedOffers, offer._id);
318
+ if (redeemedTimes <= 0) {
319
+ continue;
320
+ }
321
+ const pathwayVouchers = offer.pathway_to_unlock_type_vouchers;
322
+ if (pathwayVouchers == null || pathwayVouchers.voucher_ids.length === 0) {
323
+ continue;
324
+ }
325
+ redeemedOfferIds.add(offer._id);
326
+ const linkedVoucherCodes = new Set();
327
+ for (let j = 0; j < pathwayVouchers.voucher_ids.length; j++) {
328
+ const voucherId = pathwayVouchers.voucher_ids[j];
329
+ consumedVoucherIds.add(voucherId);
330
+ const linkedVoucherCode = voucherCodeById.get(voucherId);
331
+ if (linkedVoucherCode == null)
332
+ continue;
333
+ linkedVoucherCodes.add(linkedVoucherCode);
334
+ }
335
+ if (referencedVoucherCode != null && linkedVoucherCodes.has(referencedVoucherCode)) {
336
+ consumedVoucherCodes.add(referencedVoucherCode);
337
+ continue;
338
+ }
339
+ for (const linkedVoucherCode of linkedVoucherCodes) {
340
+ consumedVoucherCodes.add(linkedVoucherCode);
341
+ }
342
+ }
343
+ const inferredVoucherCode = referencedVoucherCode ?? (consumedVoucherCodes.size === 1 ? consumedVoucherCodes.values().next().value : null);
344
+ return {
345
+ activeVoucherCode: inferredVoucherCode ?? null,
346
+ consumedVoucherCodes,
347
+ consumedVoucherIds,
348
+ redeemedOfferIds,
349
+ };
350
+ }
351
+ export function isVoucherPathwayOfferBlockedByCartContext({ offer, cartContext, }) {
352
+ if (offer.pathway_to_unlock_type !== PATHWAY_TO_UNLOCK_TYPE_ENUM.VOUCHER) {
353
+ return false;
354
+ }
355
+ if (cartContext.redeemedOfferIds.size === 0) {
356
+ return false;
357
+ }
358
+ return !cartContext.redeemedOfferIds.has(offer._id);
359
+ }
360
+ // ================================><================================= //
361
+ // === isExhaustedVoucherOffer === //
362
+ // ================================><================================= //
363
+ /**
364
+ * Determines whether a voucher-type offer should show "already claimed"
365
+ * instead of the toolkit's generic "not eligible" message.
366
+ *
367
+ * Returns `true` when the offer itself has been redeemed AND the offer's
368
+ * per-customer usage count has been reached.
369
+ */
370
+ export function isExhaustedVoucherOffer({ offer, customerOfferRedemptionCounts, redeemedOffers, isRedeemed, }) {
371
+ if (offer == null ||
372
+ offer.pathway_to_unlock_type !== PATHWAY_TO_UNLOCK_TYPE_ENUM.VOUCHER ||
373
+ offer.pathway_to_unlock_type_vouchers == null ||
374
+ customerOfferRedemptionCounts == null) {
375
+ return false;
376
+ }
377
+ const isThisOfferRedeemed = isRedeemed || (redeemedOffers != null && Number(redeemedOffers[offer._id]) > 0);
378
+ if (!isThisOfferRedeemed)
379
+ return false;
380
+ const pathwayMaxUsesPerCustomer = offer.pathway_to_unlock_type_vouchers.max_uses_per_customer;
381
+ return (pathwayMaxUsesPerCustomer != null &&
382
+ getCustomerUsedRedemptionCount(customerOfferRedemptionCounts, offer._id) >= pathwayMaxUsesPerCustomer);
383
+ }
384
+ // ================================><================================= //
385
+ // === findLinkedVoucherOffers === //
386
+ // ================================><================================= //
387
+ /**
388
+ * Find all offers linked to a given voucher code.
389
+ * Works with raw IOffer[] — no stats needed.
390
+ */
391
+ export function findLinkedVoucherOffers({ voucherCode, offers, vouchers, }) {
392
+ const normalizedCode = voucherCode.trim().toUpperCase();
393
+ if (!normalizedCode)
394
+ return { matchedVoucher: null, linkedOffers: [] };
395
+ const matchedVoucher = vouchers.find((v) => v.code.trim().toUpperCase() === normalizedCode) ?? null;
396
+ if (!matchedVoucher)
397
+ return { matchedVoucher: null, linkedOffers: [] };
398
+ const linkedOffers = offers.filter((offer) => offer.pathway_to_unlock_type === PATHWAY_TO_UNLOCK_TYPE_ENUM.VOUCHER &&
399
+ offer.pathway_to_unlock_type_vouchers?.voucher_ids.includes(matchedVoucher._id));
400
+ return { matchedVoucher, linkedOffers };
401
+ }
402
+ // ================================><================================= //
403
+ // === buildClearVoucherDiscountDetails === //
404
+ // ================================><================================= //
405
+ /**
406
+ * Returns a discount details object with all voucher-related fields cleared.
407
+ * Use when removing a voucher code from the cart (no offers claimed).
408
+ */
409
+ export function buildClearVoucherDiscountDetails(currentDetails) {
410
+ return {
411
+ ...(currentDetails ?? { total_discount: 0 }),
412
+ voucher_discount_id: undefined,
413
+ voucher_discount_name: undefined,
414
+ voucher_discount: undefined,
415
+ is_voucher_discount_percentage: undefined,
416
+ voucher_discount_reason: undefined,
417
+ voucher_reference_number: undefined,
418
+ total_discount: 0,
419
+ };
420
+ }
421
+ export function calculateCustomerSpendableVoucherCodes({ customerVoucherCodes, orderDiscountDetails, redeemedOffers, offers, vouchers, }) {
422
+ const voucherCodes = {};
423
+ if (customerVoucherCodes != null) {
424
+ const entries = Object.entries(customerVoucherCodes);
425
+ for (let i = 0; i < entries.length; i++) {
426
+ const [code, count] = entries[i];
427
+ const normalizedCode = normalizeVoucherCode(code);
428
+ if (normalizedCode == null)
429
+ continue;
430
+ const parsedCount = Number(count);
431
+ if (!Number.isFinite(parsedCount) || parsedCount <= 0)
432
+ continue;
433
+ voucherCodes[normalizedCode] = Math.floor(parsedCount);
434
+ }
435
+ }
436
+ const activeVoucherCode = normalizeVoucherCode(orderDiscountDetails?.voucher_reference_number);
437
+ if (vouchers == null || offers.length === 0 || redeemedOffers == null) {
438
+ return {
439
+ voucherCodes,
440
+ totalVouchers: Object.values(voucherCodes).reduce((acc, count) => acc + count, 0),
441
+ activeVoucherCode,
442
+ consumedVoucherClaims: 0,
443
+ };
444
+ }
445
+ const voucherCodeById = new Map();
446
+ for (let i = 0; i < vouchers.length; i++) {
447
+ const voucher = vouchers[i];
448
+ const normalizedVoucherCode = normalizeVoucherCode(voucher.code);
449
+ if (normalizedVoucherCode == null)
450
+ continue;
451
+ voucherCodeById.set(voucher._id, normalizedVoucherCode);
452
+ }
453
+ const consumedVoucherClaimsByCode = {};
454
+ for (let i = 0; i < offers.length; i++) {
455
+ const offer = offers[i];
456
+ if (offer.pathway_to_unlock_type !== PATHWAY_TO_UNLOCK_TYPE_ENUM.VOUCHER) {
457
+ continue;
458
+ }
459
+ const pathwayVouchers = offer.pathway_to_unlock_type_vouchers;
460
+ if (pathwayVouchers == null || pathwayVouchers.voucher_ids.length === 0) {
461
+ continue;
462
+ }
463
+ const redeemedTimes = getOfferRedeemedClaims(redeemedOffers, offer._id);
464
+ if (redeemedTimes <= 0) {
465
+ continue;
466
+ }
467
+ const linkedVoucherCodes = new Set();
468
+ for (let j = 0; j < pathwayVouchers.voucher_ids.length; j++) {
469
+ const linkedVoucherCode = voucherCodeById.get(pathwayVouchers.voucher_ids[j]);
470
+ if (linkedVoucherCode == null)
471
+ continue;
472
+ linkedVoucherCodes.add(linkedVoucherCode);
473
+ }
474
+ if (linkedVoucherCodes.size === 0) {
475
+ continue;
476
+ }
477
+ const [singleLinkedVoucherCode] = linkedVoucherCodes;
478
+ const targetVoucherCode = linkedVoucherCodes.size === 1
479
+ ? singleLinkedVoucherCode
480
+ : activeVoucherCode != null && linkedVoucherCodes.has(activeVoucherCode)
481
+ ? activeVoucherCode
482
+ : null;
483
+ if (targetVoucherCode == null) {
484
+ continue;
485
+ }
486
+ consumedVoucherClaimsByCode[targetVoucherCode] =
487
+ (consumedVoucherClaimsByCode[targetVoucherCode] ?? 0) + redeemedTimes;
488
+ }
489
+ const consumedVoucherCodes = Object.keys(consumedVoucherClaimsByCode);
490
+ for (let i = 0; i < consumedVoucherCodes.length; i++) {
491
+ const voucherCode = consumedVoucherCodes[i];
492
+ if (voucherCodes[voucherCode] == null) {
493
+ continue;
494
+ }
495
+ voucherCodes[voucherCode] = Math.max(0, voucherCodes[voucherCode] - consumedVoucherClaimsByCode[voucherCode]);
496
+ }
497
+ const consumedVoucherClaims = activeVoucherCode != null ? (consumedVoucherClaimsByCode[activeVoucherCode] ?? 0) : 0;
498
+ return {
499
+ voucherCodes,
500
+ totalVouchers: Object.values(voucherCodes).reduce((acc, count) => acc + count, 0),
501
+ activeVoucherCode,
502
+ consumedVoucherClaims,
503
+ };
504
+ }
505
+ export function calculateCustomerSpendableGiftCardCodes({ customerGiftCardCodes, loyaltyReferenceNumber, loyaltyDiscountId, walletGiftCardRedemptions, giftCards, }) {
506
+ const giftCardCodes = {};
507
+ const shouldFilterByGiftCardEntities = giftCards != null && giftCards.length > 0;
508
+ const activeGiftCardCodes = new Set();
509
+ const giftCardCodeById = new Map();
510
+ if (shouldFilterByGiftCardEntities) {
511
+ const now = Date.now();
512
+ for (let i = 0; i < giftCards.length; i++) {
513
+ const giftCard = giftCards[i];
514
+ const normalizedCode = normalizeGiftCardCode(giftCard.code);
515
+ if (normalizedCode == null)
516
+ continue;
517
+ if (!giftCard.active)
518
+ continue;
519
+ if (giftCard.expire_at != null) {
520
+ const expiryTime = new Date(giftCard.expire_at).getTime();
521
+ if (Number.isFinite(expiryTime) && expiryTime < now) {
522
+ continue;
523
+ }
524
+ }
525
+ activeGiftCardCodes.add(normalizedCode);
526
+ giftCardCodeById.set(giftCard._id, normalizedCode);
527
+ }
528
+ }
529
+ if (customerGiftCardCodes != null) {
530
+ const entries = Object.entries(customerGiftCardCodes);
531
+ for (let i = 0; i < entries.length; i++) {
532
+ const [code, count] = entries[i];
533
+ const normalizedCode = normalizeGiftCardCode(code);
534
+ if (normalizedCode == null)
535
+ continue;
536
+ if (shouldFilterByGiftCardEntities && !activeGiftCardCodes.has(normalizedCode)) {
537
+ continue;
538
+ }
539
+ const parsedCount = Number(count);
540
+ if (!Number.isFinite(parsedCount) || parsedCount <= 0)
541
+ continue;
542
+ giftCardCodes[normalizedCode] = Math.floor(parsedCount);
543
+ }
544
+ }
545
+ const appliedGiftCardClaimsByCode = {};
546
+ const normalizedWalletGiftCardRedemptions = getWalletGiftCardRedemptionClaims(walletGiftCardRedemptions);
547
+ for (let i = 0; i < normalizedWalletGiftCardRedemptions.length; i++) {
548
+ const walletGiftCardRedemption = normalizedWalletGiftCardRedemptions[i];
549
+ const normalizedWalletGiftCardCode = giftCardCodeById.get(walletGiftCardRedemption.gift_card_id);
550
+ if (normalizedWalletGiftCardCode == null || normalizedWalletGiftCardCode.length === 0) {
551
+ continue;
552
+ }
553
+ appliedGiftCardClaimsByCode[normalizedWalletGiftCardCode] =
554
+ (appliedGiftCardClaimsByCode[normalizedWalletGiftCardCode] ?? 0) + walletGiftCardRedemption.redeemed_times;
555
+ }
556
+ const appliedGiftCardCodes = Object.keys(appliedGiftCardClaimsByCode);
557
+ if (appliedGiftCardCodes.length > 0) {
558
+ for (let i = 0; i < appliedGiftCardCodes.length; i++) {
559
+ const appliedGiftCardCode = appliedGiftCardCodes[i];
560
+ if (giftCardCodes[appliedGiftCardCode] == null)
561
+ continue;
562
+ giftCardCodes[appliedGiftCardCode] = Math.max(0, giftCardCodes[appliedGiftCardCode] - appliedGiftCardClaimsByCode[appliedGiftCardCode]);
563
+ }
564
+ }
565
+ else {
566
+ const normalizedLoyaltyReference = normalizeGiftCardCode(loyaltyReferenceNumber);
567
+ const normalizedAppliedCode = loyaltyDiscountId != null &&
568
+ loyaltyDiscountId !== WALLET_CASHBACK_LOYALTY_DISCOUNT_ID &&
569
+ normalizedLoyaltyReference != null &&
570
+ normalizedLoyaltyReference.length > 0
571
+ ? normalizedLoyaltyReference
572
+ : null;
573
+ if (normalizedAppliedCode != null && giftCardCodes[normalizedAppliedCode] != null) {
574
+ giftCardCodes[normalizedAppliedCode] = Math.max(0, giftCardCodes[normalizedAppliedCode] - 1);
575
+ }
576
+ }
577
+ return {
578
+ giftCardCodes,
579
+ totalGiftCards: Object.values(giftCardCodes).reduce((total, count) => {
580
+ const safeCount = Number(count);
581
+ return total + (Number.isFinite(safeCount) && safeCount > 0 ? safeCount : 0);
582
+ }, 0),
583
+ };
584
+ }
585
+ // The purpose of this function is to calculate the total number of points that are applied/consumed by the cart items
586
+ export function calculateCustomerLoyaltyPoints({ customerLoyaltyPoints, orderDiscountDetails, redeemedOffers, currentItemsPrice, totalDiscountApplied, categories, offers, includePendingRewardPoints = false, }) {
587
+ const totalOrderPrice = (currentItemsPrice ?? 0) - (totalDiscountApplied ?? 0);
588
+ let loyaltyPoints = customerLoyaltyPoints ?? 0;
589
+ let addedLoyaltyPoints = loyaltyPoints;
590
+ let deductedLoyaltyPoints = loyaltyPoints;
591
+ const offersThatHavePointsMap = {};
592
+ const offerApplicableQuantity = {};
593
+ for (let i = 0; i < offers.length; i++) {
594
+ const offer = offers[i];
595
+ const isRewardPointsOffer = offer.reward_type === OFFER_REWARD_TYPE_ENUM.POINTS;
596
+ const isPointsPathwayOffer = offer.pathway_to_unlock_type === PATHWAY_TO_UNLOCK_TYPE_ENUM.POINTS;
597
+ if (!isRewardPointsOffer && !isPointsPathwayOffer) {
598
+ continue;
599
+ }
600
+ offersThatHavePointsMap[offer._id] = offer;
601
+ if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.ITEMS) {
602
+ offerApplicableQuantity[offer._id] = Math.max(1, offer.reward_items?.num_of_items ?? 1);
603
+ }
604
+ else if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS) {
605
+ offerApplicableQuantity[offer._id] = Math.max(1, offer.reward_discount_items?.num_of_items ?? 1);
606
+ }
607
+ else {
608
+ offerApplicableQuantity[offer._id] = 1;
609
+ }
610
+ }
611
+ const pointsRelevantOfferIds = Object.keys(offersThatHavePointsMap);
612
+ if (pointsRelevantOfferIds.length > 0) {
613
+ const claimedTimesByOfferId = {};
614
+ const markClaimedTimes = (offerId, claimsCount) => {
615
+ if (offerId == null) {
616
+ return;
617
+ }
618
+ const offer = offersThatHavePointsMap[offerId];
619
+ if (offer == null) {
620
+ return;
621
+ }
622
+ const parsedClaimsCount = Number(claimsCount);
623
+ if (!Number.isFinite(parsedClaimsCount) || parsedClaimsCount <= 0) {
624
+ return;
625
+ }
626
+ const safeClaimsCount = Math.max(1, Math.floor(parsedClaimsCount));
627
+ claimedTimesByOfferId[offerId] = Math.max(claimedTimesByOfferId[offerId] ?? 0, safeClaimsCount);
628
+ };
629
+ // Canonical claim source: redeemed_offers map.
630
+ if (redeemedOffers != null) {
631
+ const redeemedOfferIds = Object.keys(redeemedOffers);
632
+ for (let i = 0; i < redeemedOfferIds.length; i++) {
633
+ const offerId = redeemedOfferIds[i];
634
+ markClaimedTimes(offerId, redeemedOffers[offerId]);
635
+ }
636
+ }
637
+ // Fallback claim signals from order-level discount ids.
638
+ if (orderDiscountDetails != null) {
639
+ markClaimedTimes(orderDiscountDetails.loyalty_discount_id, 1);
640
+ markClaimedTimes(orderDiscountDetails.voucher_discount_id, 1);
641
+ }
642
+ // Secondary claim signal from selected reward items in cart.
643
+ if (categories != null && categories.length > 0) {
644
+ const selectedItemsCountByOfferId = {};
645
+ for (let i = 0; i < categories.length; i++) {
646
+ const category = categories[i];
647
+ for (let j = 0; j < category.items.length; j++) {
648
+ const item = category.items[j];
649
+ const itemDiscountDetails = item.item_discount_details;
650
+ if (itemDiscountDetails == null) {
651
+ continue;
652
+ }
653
+ const safeQuantity = Number(item.quantity);
654
+ if (!Number.isFinite(safeQuantity) || safeQuantity <= 0) {
655
+ continue;
656
+ }
657
+ const quantity = Math.floor(safeQuantity);
658
+ const loyaltyOffer = offersThatHavePointsMap[itemDiscountDetails.loyalty_discount_id ?? ''];
659
+ if (loyaltyOffer != null) {
660
+ selectedItemsCountByOfferId[loyaltyOffer._id] =
661
+ (selectedItemsCountByOfferId[loyaltyOffer._id] ?? 0) + quantity;
662
+ }
663
+ const voucherOffer = offersThatHavePointsMap[itemDiscountDetails.voucher_discount_id ?? ''];
664
+ if (voucherOffer != null) {
665
+ selectedItemsCountByOfferId[voucherOffer._id] =
666
+ (selectedItemsCountByOfferId[voucherOffer._id] ?? 0) + quantity;
667
+ }
668
+ }
669
+ }
670
+ const selectedItemOfferIds = Object.keys(selectedItemsCountByOfferId);
671
+ for (let i = 0; i < selectedItemOfferIds.length; i++) {
672
+ const offerId = selectedItemOfferIds[i];
673
+ const selectedItemsCount = selectedItemsCountByOfferId[offerId] ?? 0;
674
+ if (selectedItemsCount <= 0) {
675
+ continue;
676
+ }
677
+ const applicableQuantity = Math.max(1, offerApplicableQuantity[offerId] ?? 1);
678
+ const derivedClaimsCount = Math.ceil(selectedItemsCount / applicableQuantity);
679
+ markClaimedTimes(offerId, derivedClaimsCount);
680
+ }
681
+ }
682
+ const claimedOfferIds = Object.keys(claimedTimesByOfferId);
683
+ for (let i = 0; i < claimedOfferIds.length; i++) {
684
+ const offerId = claimedOfferIds[i];
685
+ const redeemedOffer = offersThatHavePointsMap[offerId];
686
+ const claimedTimes = claimedTimesByOfferId[offerId] ?? 0;
687
+ if (redeemedOffer == null || claimedTimes <= 0) {
688
+ continue;
689
+ }
690
+ if (redeemedOffer.reward_type === OFFER_REWARD_TYPE_ENUM.POINTS && includePendingRewardPoints) {
691
+ const points = calculatePointsRedeemedForOffer(redeemedOffer, totalOrderPrice, categories, claimedTimes);
692
+ loyaltyPoints += points;
693
+ addedLoyaltyPoints += points;
694
+ }
695
+ if (redeemedOffer.pathway_to_unlock_type === PATHWAY_TO_UNLOCK_TYPE_ENUM.POINTS) {
696
+ const points = (redeemedOffer.pathway_to_unlock_type_points?.num_of_points ?? 0) * claimedTimes;
697
+ loyaltyPoints -= points;
698
+ deductedLoyaltyPoints += points;
699
+ }
700
+ }
701
+ }
702
+ return {
703
+ loyaltyPoints,
704
+ addedLoyaltyPoints,
705
+ deductedLoyaltyPoints,
706
+ };
707
+ }
708
+ function getCartItemsApplicableToOfferItemsQuantity({ categories, excluded_refs, exclusive_refs, item_ids, category_ids, min_same_item_quantity, max_same_item_quantity, }) {
709
+ if (categories == null)
710
+ return 0;
711
+ const checkIfItemHasAnyRef = (item, refs_arr) => {
712
+ if (refs_arr.includes(item.item_id)) {
713
+ return true;
714
+ }
715
+ let hasRef = false;
716
+ if (item.modifiers != null) {
717
+ const recursiveCheck = (modifiers) => {
718
+ outer: for (let i = 0; i < modifiers.length; i++) {
719
+ if (hasRef)
720
+ break outer;
721
+ const modifier = modifiers[i];
722
+ if (refs_arr.includes(modifier.ref)) {
723
+ hasRef = true;
724
+ break outer;
725
+ }
726
+ for (let j = 0; j < modifier.options.length; j++) {
727
+ const option = modifier.options[j];
728
+ if (refs_arr.includes(option.ref)) {
729
+ hasRef = true;
730
+ break outer;
731
+ }
732
+ if (option.modifiers != null) {
733
+ recursiveCheck(option.modifiers);
734
+ }
735
+ }
736
+ }
737
+ };
738
+ recursiveCheck(item.modifiers);
739
+ }
740
+ return hasRef;
741
+ };
742
+ const applicableItems = categories.reduce((acc, category) => {
743
+ category.items.forEach((item) => {
744
+ const hasItemFilter = item_ids.length > 0;
745
+ const hasCategoryFilter = category_ids.length > 0;
746
+ const isItemMatched = item_ids.length > 0 && item_ids.includes(item.item_id);
747
+ const isCategoryMatched = category_ids.length > 0 && category_ids.includes(category.category_id);
748
+ const isItemCategoryScopeMatched = hasItemFilter && hasCategoryFilter
749
+ ? isItemMatched && isCategoryMatched
750
+ : hasItemFilter
751
+ ? isItemMatched
752
+ : hasCategoryFilter
753
+ ? isCategoryMatched
754
+ : false;
755
+ if (
756
+ // We only want to check for items that don't have any loyalty or voucher discounts
757
+ item.item_discount_details?.loyalty_discount_id == null &&
758
+ item.item_discount_details?.voucher_discount_id == null &&
759
+ // Matching precedence:
760
+ // 1) only item_ids => match item_ids,
761
+ // 2) only category_ids => match category_ids,
762
+ // 3) both => match item_ids within matched category_ids.
763
+ isItemCategoryScopeMatched &&
764
+ // We only want to check for items that don't have any modifiers/options that are excluded
765
+ (excluded_refs.length === 0 || (excluded_refs.length > 0 && !checkIfItemHasAnyRef(item, excluded_refs))) &&
766
+ // We only want to check for items that have at least one modifier/option that is inclusive
767
+ (exclusive_refs.length === 0 || (exclusive_refs.length > 0 && checkIfItemHasAnyRef(item, exclusive_refs)))) {
768
+ acc.push({
769
+ item_id: item.item_id,
770
+ quantity: item.quantity,
771
+ subtotal: item.subtotal,
772
+ });
773
+ }
774
+ });
775
+ return acc;
776
+ }, []) ?? [];
777
+ const minSameItemQuantity = min_same_item_quantity == null ? 1 : Math.max(1, min_same_item_quantity);
778
+ const maxSameItemQuantity = max_same_item_quantity == null ? Infinity : Math.max(minSameItemQuantity, max_same_item_quantity);
779
+ const quantityByItemId = applicableItems.reduce((acc, item) => {
780
+ acc[item.item_id] = (acc[item.item_id] ?? 0) + item.quantity;
781
+ return acc;
782
+ }, {});
783
+ const totalQuantity = Object.values(quantityByItemId).reduce((acc, quantity) => {
784
+ const boundedQuantity = Math.min(quantity, maxSameItemQuantity);
785
+ if (boundedQuantity < minSameItemQuantity) {
786
+ return acc;
787
+ }
788
+ acc += boundedQuantity;
789
+ return acc;
790
+ }, 0);
791
+ return totalQuantity;
792
+ }
793
+ // ====================================================================================================================
794
+ /**
795
+ * Check if there are any eligible items for a discount offer
796
+ * Returns true if at least one item in categories is NOT in excluded_refs
797
+ */
798
+ function hasEligibleItemsForDiscount(categories, excluded_refs) {
799
+ if (!categories?.length)
800
+ return false;
801
+ if (!excluded_refs?.length)
802
+ return true; // No exclusions means all items are eligible
803
+ for (const category of categories) {
804
+ // If category is excluded, skip it
805
+ if (excluded_refs.includes(category.category_id)) {
806
+ continue;
807
+ }
808
+ // Check if any item in this category is NOT excluded
809
+ for (const item of category.items ?? []) {
810
+ if (!excluded_refs.includes(item.item_id)) {
811
+ return true; // Found at least one eligible item
812
+ }
813
+ }
814
+ }
815
+ return false; // All items are excluded
816
+ }
817
+ // ====================================================================================================================
818
+ export const getTotalSelectedOfferItemsAgainstOffer = (categories, offer_id) => {
819
+ const totalOfferItems = categories?.reduce((acc, category) => {
820
+ let totalItems = 0;
821
+ category.items.forEach((item) => {
822
+ if (item.item_discount_details != null &&
823
+ (item.item_discount_details.loyalty_discount_id === offer_id ||
824
+ item.item_discount_details.voucher_discount_id === offer_id)) {
825
+ totalItems += item.quantity;
826
+ }
827
+ });
828
+ return acc + totalItems;
829
+ }, 0) ?? 0;
830
+ return totalOfferItems;
831
+ };
832
+ function normalizeOfferId(offerId) {
833
+ if (offerId == null)
834
+ return null;
835
+ const normalizedOfferId = offerId.toString().trim();
836
+ return normalizedOfferId.length > 0 ? normalizedOfferId : null;
837
+ }
838
+ function toPositiveInteger(value, fallback = 0) {
839
+ const parsedValue = Number(value);
840
+ if (!Number.isFinite(parsedValue) || parsedValue <= 0) {
841
+ return fallback;
842
+ }
843
+ return Math.floor(parsedValue);
844
+ }
845
+ function getCustomerRedemptionCount(customerOfferRedemptionCounts, type, id) {
846
+ const normalizedId = normalizeOfferId(id);
847
+ if (customerOfferRedemptionCounts == null || normalizedId == null) {
848
+ return 0;
849
+ }
850
+ const typedCount = customerOfferRedemptionCounts[type]?.[normalizedId];
851
+ if (typedCount != null) {
852
+ return toPositiveInteger(typedCount, 0);
853
+ }
854
+ const legacyFlatCounts = customerOfferRedemptionCounts;
855
+ return toPositiveInteger(legacyFlatCounts[normalizedId], 0);
856
+ }
857
+ function getRewardMaxAssignmentsPerCustomer(rewardResource) {
858
+ return rewardResource.max_assignments_per_customer ?? rewardResource.max_uses_per_customer ?? null;
859
+ }
860
+ function getCustomerUsedRedemptionCount(customerOfferRedemptionCounts, id) {
861
+ return getCustomerRedemptionCount(customerOfferRedemptionCounts, CUSTOMER_REDEMPTION_TYPE_ENUM.USED, id);
862
+ }
863
+ function getCustomerAssignedRedemptionCount(customerOfferRedemptionCounts, id) {
864
+ return getCustomerRedemptionCount(customerOfferRedemptionCounts, CUSTOMER_REDEMPTION_TYPE_ENUM.ASSIGNED, id);
865
+ }
866
+ function getOfferPathwayMaxUsesPerCustomer(offer) {
867
+ if (offer == null) {
868
+ return null;
869
+ }
870
+ if (offer.pathway_to_unlock_type === PATHWAY_TO_UNLOCK_TYPE_ENUM.ORDERS) {
871
+ return toPositiveInteger(offer.pathway_to_unlock_type_orders?.max_uses_per_customer, 0) || null;
872
+ }
873
+ if (offer.pathway_to_unlock_type === PATHWAY_TO_UNLOCK_TYPE_ENUM.ITEMS) {
874
+ return toPositiveInteger(offer.pathway_to_unlock_type_items?.max_uses_per_customer, 0) || null;
875
+ }
876
+ if (offer.pathway_to_unlock_type === PATHWAY_TO_UNLOCK_TYPE_ENUM.POINTS) {
877
+ return toPositiveInteger(offer.pathway_to_unlock_type_points?.max_uses_per_customer, 0) || null;
878
+ }
879
+ if (offer.pathway_to_unlock_type === PATHWAY_TO_UNLOCK_TYPE_ENUM.VOUCHER) {
880
+ return toPositiveInteger(offer.pathway_to_unlock_type_vouchers?.max_uses_per_customer, 0) || null;
881
+ }
882
+ return null;
883
+ }
884
+ export function getOfferUsageLimitMeta(offer) {
885
+ const maxUsesPerCustomer = getOfferPathwayMaxUsesPerCustomer(offer);
886
+ if (maxUsesPerCustomer == null) {
887
+ return null;
888
+ }
889
+ const usageKey = normalizeOfferId(offer?._id);
890
+ if (usageKey == null) {
891
+ return null;
892
+ }
893
+ return {
894
+ maxUsesPerCustomer,
895
+ usageKey,
896
+ };
897
+ }
898
+ export function getOfferConsumedUses({ offer, usageLimit, customerOfferRedemptionCounts, }) {
899
+ if (usageLimit == null || customerOfferRedemptionCounts == null) {
900
+ return null;
901
+ }
902
+ const usageKey = normalizeOfferId(offer?._id) ?? normalizeOfferId(usageLimit.usageKey);
903
+ if (usageKey == null) {
904
+ return null;
905
+ }
906
+ return getCustomerUsedRedemptionCount(customerOfferRedemptionCounts, usageKey);
907
+ }
908
+ export function isOfferFullyConsumedForCustomer({ offer, usageLimit, customerOfferRedemptionCounts, }) {
909
+ const consumedUses = getOfferConsumedUses({
910
+ offer,
911
+ usageLimit,
912
+ customerOfferRedemptionCounts,
913
+ });
914
+ return usageLimit != null && consumedUses != null && consumedUses >= usageLimit.maxUsesPerCustomer;
915
+ }
916
+ function getOfferRemainingClaimsFromStats(stats) {
917
+ const applicableQuantity = toPositiveInteger(stats?.applicable_quantity, 0);
918
+ const redeemedTimes = toPositiveInteger(stats?.redeemed_times, 0);
919
+ return Math.max(0, applicableQuantity - redeemedTimes);
920
+ }
921
+ export function getOfferClaimIncrementFromStats({ stats, fallbackClaims = 0, }) {
922
+ const remainingClaims = getOfferRemainingClaimsFromStats(stats);
923
+ if (remainingClaims > 0) {
924
+ return remainingClaims;
925
+ }
926
+ return toPositiveInteger(fallbackClaims, 0);
927
+ }
928
+ export function getOffersIdsHashKey(offerIds) {
929
+ return (offerIds ?? [])
930
+ .map((offerId) => normalizeOfferId(offerId))
931
+ .sort()
932
+ .join('|');
933
+ }
934
+ export function getSuppressedOfferIdsHashKey(suppressedOfferIds) {
935
+ return getOffersIdsHashKey(Object.keys(suppressedOfferIds ?? {}));
936
+ }
937
+ export function getAutoApplyOfferCandidates({ offersWithStats, suppressedOfferIds, }) {
938
+ if (offersWithStats == null || offersWithStats.length === 0) {
939
+ return [];
940
+ }
941
+ const autoApplyOfferCandidates = [];
942
+ for (let i = 0; i < offersWithStats.length; i++) {
943
+ const offerWithStats = offersWithStats[i];
944
+ const offer = offerWithStats.offer;
945
+ const stats = offerWithStats.stats;
946
+ const normalizedOfferId = normalizeOfferId(offer._id);
947
+ if (normalizedOfferId == null) {
948
+ continue;
949
+ }
950
+ const isAutoApplyAfterFirstPointsClaim = offer.reward_type === OFFER_REWARD_TYPE_ENUM.POINTS &&
951
+ offer.reward_points != null &&
952
+ !offer.reward_points.once_per_order &&
953
+ stats.redeemed_times > 0;
954
+ const shouldAutoApplyOffer = offer.auto_apply || isAutoApplyAfterFirstPointsClaim;
955
+ if (!stats.claimable || stats.invalid_offer || !shouldAutoApplyOffer) {
956
+ continue;
957
+ }
958
+ // ITEMS / DISCOUNT_ITEMS rewards are claimed manually through the reward
959
+ // drawers and their claimability tracks selected cart items rather than
960
+ // redeemed_offers. No app implements auto-apply for them, and applying via
961
+ // a redeemed_offers patch would leave them permanently claimable, causing
962
+ // the auto-apply effect to loop.
963
+ if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.ITEMS ||
964
+ offer.reward_type === OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS) {
965
+ continue;
966
+ }
967
+ if (suppressedOfferIds?.[normalizedOfferId]) {
968
+ continue;
969
+ }
970
+ // For repeatable POINTS and flat CASHBACK, claimsIncrement covers ALL
971
+ // remaining claims in a single patch so the next stats snapshot flips
972
+ // claimable to false. Callers MUST forward claimsIncrement into
973
+ // buildRedeemedOffersClaimPatch; otherwise redeemed_times advances by 1
974
+ // per cycle and the auto-apply effect loops until React throws
975
+ // "Maximum update depth exceeded".
976
+ const claimsIncrement = offer.reward_type === OFFER_REWARD_TYPE_ENUM.POINTS ||
977
+ (offer.reward_type === OFFER_REWARD_TYPE_ENUM.CASHBACK && offer.reward_cashback?.is_cashback_percentage !== true)
978
+ ? getOfferClaimIncrementFromStats({
979
+ stats,
980
+ })
981
+ : undefined;
982
+ if (claimsIncrement != null && claimsIncrement <= 0) {
983
+ continue;
984
+ }
985
+ autoApplyOfferCandidates.push({
986
+ offer,
987
+ ...(claimsIncrement != null ? { claimsIncrement } : {}),
988
+ });
989
+ }
990
+ return autoApplyOfferCandidates;
991
+ }
992
+ export function buildRedeemedOffersClaimPatch({ currentRedeemedOffers, offerId, claimsIncrement = 1, }) {
993
+ const normalizedOfferId = normalizeOfferId(offerId);
994
+ if (normalizedOfferId == null) {
995
+ return {};
996
+ }
997
+ const nextRedeemedOffers = {};
998
+ const redeemedOfferEntries = Object.entries(currentRedeemedOffers ?? {});
999
+ for (let i = 0; i < redeemedOfferEntries.length; i++) {
1000
+ const [offerKey, redeemedTimes] = redeemedOfferEntries[i];
1001
+ const normalizedOfferKey = normalizeOfferId(offerKey);
1002
+ if (normalizedOfferKey == null)
1003
+ continue;
1004
+ const safeRedeemedTimes = toPositiveInteger(redeemedTimes, 0);
1005
+ if (safeRedeemedTimes <= 0)
1006
+ continue;
1007
+ nextRedeemedOffers[normalizedOfferKey] = safeRedeemedTimes;
1008
+ }
1009
+ const safeClaimsIncrement = toPositiveInteger(claimsIncrement, 1);
1010
+ const currentRedeemedTimes = toPositiveInteger(nextRedeemedOffers[normalizedOfferId], 0);
1011
+ nextRedeemedOffers[normalizedOfferId] = currentRedeemedTimes + safeClaimsIncrement;
1012
+ return {
1013
+ redeemed_offers: Object.keys(nextRedeemedOffers).length > 0 ? nextRedeemedOffers : null,
1014
+ };
1015
+ }
1016
+ export function getNetItemsValueAfterItemDiscount({ itemsPrice, totalDiscountApplied, orderLevelDiscount, }) {
1017
+ const safeItemsPrice = Number.isFinite(itemsPrice) ? Math.max(0, Number(itemsPrice)) : 0;
1018
+ const safeTotalDiscountApplied = Number.isFinite(totalDiscountApplied)
1019
+ ? Math.max(0, Number(totalDiscountApplied))
1020
+ : 0;
1021
+ const safeOrderLevelDiscount = Number.isFinite(orderLevelDiscount) ? Math.max(0, Number(orderLevelDiscount)) : 0;
1022
+ const itemDiscount = parseNum(Math.max(0, safeTotalDiscountApplied - safeOrderLevelDiscount));
1023
+ return parseNum(Math.max(0, safeItemsPrice - itemDiscount));
1024
+ }
1025
+ function getPositiveAmount(value) {
1026
+ const parsedValue = Number(value);
1027
+ if (!Number.isFinite(parsedValue) || parsedValue <= 0) {
1028
+ return 0;
1029
+ }
1030
+ return parseNum(parsedValue);
1031
+ }
1032
+ function getOrderSubtotalFromCategoriesForOfferStats(categories) {
1033
+ if (categories == null)
1034
+ return null;
1035
+ let subtotal = 0;
1036
+ let itemsCount = 0;
1037
+ for (let i = 0; i < categories.length; i++) {
1038
+ const items = categories[i].items;
1039
+ for (let j = 0; j < items.length; j++) {
1040
+ subtotal += getPositiveAmount(items[j].subtotal);
1041
+ itemsCount += Math.max(0, Math.floor(items[j].quantity ?? 0));
1042
+ }
1043
+ }
1044
+ return { subtotal: parseNum(subtotal), itemsCount };
1045
+ }
1046
+ function getOrderLevelDiscountBaseAmountForOfferStats({ categories, itemsPrice, totalDiscountApplied, orderDiscountDetails, }) {
1047
+ const categoriesResult = getOrderSubtotalFromCategoriesForOfferStats(categories);
1048
+ if (categoriesResult != null) {
1049
+ return { baseAmount: categoriesResult.subtotal, itemsCount: categoriesResult.itemsCount };
1050
+ }
1051
+ return {
1052
+ baseAmount: getNetItemsValueAfterItemDiscount({
1053
+ itemsPrice,
1054
+ totalDiscountApplied,
1055
+ orderLevelDiscount: orderDiscountDetails?.total_discount,
1056
+ }),
1057
+ itemsCount: 0,
1058
+ };
1059
+ }
1060
+ function getOrderLevelDiscountAmountForOfferStats({ orderDiscountDetails, orderLevelDiscountBaseAmount, }) {
1061
+ return parseNum(Math.min(getPositiveAmount(orderDiscountDetails?.total_discount), getPositiveAmount(orderLevelDiscountBaseAmount)));
1062
+ }
1063
+ function getOrderLevelDiscountSlotAmount({ orderLevelDiscountBaseAmount, discountValue, isDiscountPercentage, }) {
1064
+ const safeDiscountValue = getPositiveAmount(discountValue);
1065
+ if (safeDiscountValue <= 0) {
1066
+ return 0;
1067
+ }
1068
+ if (isDiscountPercentage) {
1069
+ return parseNum((getPositiveAmount(orderLevelDiscountBaseAmount) * safeDiscountValue) / 100);
1070
+ }
1071
+ return safeDiscountValue;
1072
+ }
1073
+ function getOrderLevelDiscountSlotAmounts({ orderDiscountDetails, orderLevelDiscountBaseAmount, }) {
1074
+ const discountSlotAmounts = {
1075
+ special: 0,
1076
+ loyalty: 0,
1077
+ voucher: 0,
1078
+ };
1079
+ if (orderDiscountDetails == null) {
1080
+ return discountSlotAmounts;
1081
+ }
1082
+ const safeOrderLevelDiscountBaseAmount = getPositiveAmount(orderLevelDiscountBaseAmount);
1083
+ let remainingDiscountableAmount = safeOrderLevelDiscountBaseAmount;
1084
+ const applyDiscountSlot = ({ slot, discountId, discountValue, isDiscountPercentage, }) => {
1085
+ if (!discountId || !discountValue) {
1086
+ return;
1087
+ }
1088
+ const discountSlotAmount = getOrderLevelDiscountSlotAmount({
1089
+ orderLevelDiscountBaseAmount: safeOrderLevelDiscountBaseAmount,
1090
+ discountValue,
1091
+ isDiscountPercentage,
1092
+ });
1093
+ if (discountSlotAmount <= 0 || discountSlotAmount > remainingDiscountableAmount) {
1094
+ return;
1095
+ }
1096
+ discountSlotAmounts[slot] = discountSlotAmount;
1097
+ remainingDiscountableAmount = parseNum(Math.max(0, remainingDiscountableAmount - discountSlotAmount));
1098
+ };
1099
+ applyDiscountSlot({
1100
+ slot: 'special',
1101
+ discountId: orderDiscountDetails.special_discount_id,
1102
+ discountValue: orderDiscountDetails.special_discount,
1103
+ isDiscountPercentage: orderDiscountDetails.is_special_discount_percentage,
1104
+ });
1105
+ applyDiscountSlot({
1106
+ slot: 'loyalty',
1107
+ discountId: orderDiscountDetails.loyalty_discount_id,
1108
+ discountValue: orderDiscountDetails.loyalty_discount,
1109
+ isDiscountPercentage: orderDiscountDetails.is_loyalty_discount_percentage,
1110
+ });
1111
+ applyDiscountSlot({
1112
+ slot: 'voucher',
1113
+ discountId: orderDiscountDetails.voucher_discount_id,
1114
+ discountValue: orderDiscountDetails.voucher_discount,
1115
+ isDiscountPercentage: orderDiscountDetails.is_voucher_discount_percentage,
1116
+ });
1117
+ return discountSlotAmounts;
1118
+ }
1119
+ function getOfferOrderLevelDiscountSlot(offer) {
1120
+ return offer.pathway_to_unlock_type === PATHWAY_TO_UNLOCK_TYPE_ENUM.VOUCHER ? 'voucher' : 'loyalty';
1121
+ }
1122
+ function getOwnOfferOrderLevelDiscountAmount({ offer, orderDiscountDetails, orderLevelDiscountBaseAmount, orderLevelDiscountAmount, }) {
1123
+ if (orderDiscountDetails == null || orderLevelDiscountAmount <= 0) {
1124
+ return 0;
1125
+ }
1126
+ const discountSlot = getOfferOrderLevelDiscountSlot(offer);
1127
+ const appliedOfferId = discountSlot === 'voucher' ? orderDiscountDetails.voucher_discount_id : orderDiscountDetails.loyalty_discount_id;
1128
+ if (appliedOfferId !== offer._id) {
1129
+ return 0;
1130
+ }
1131
+ const discountSlotAmounts = getOrderLevelDiscountSlotAmounts({
1132
+ orderDiscountDetails,
1133
+ orderLevelDiscountBaseAmount,
1134
+ });
1135
+ return parseNum(Math.min(orderLevelDiscountAmount, discountSlotAmounts[discountSlot]));
1136
+ }
1137
+ /**
1138
+ * Discount-eligibility refs whose cart amounts must not count toward the
1139
+ * offer's spend qualification. Mirrors the refs used to compute the eligible
1140
+ * discount base (`calculateEligibleOfferDiscountDetails`) and to gate
1141
+ * "no eligible items" in the stats engine.
1142
+ */
1143
+ function getOfferOrderValueExcludedRefs(offer) {
1144
+ if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.DISCOUNT) {
1145
+ return offer.reward_discount?.excluded_refs ?? [];
1146
+ }
1147
+ if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS) {
1148
+ return offer.reward_discount_items?.excluded_refs ?? [];
1149
+ }
1150
+ if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.CASHBACK) {
1151
+ return offer.reward_cashback?.excluded_refs ?? [];
1152
+ }
1153
+ return [];
1154
+ }
1155
+ function getOfferQualifyingOrderValue({ offer, categories, orderLevelDiscountBaseAmount, orderLevelDiscountAmount, orderDiscountDetails, }) {
1156
+ // Spend thresholds measure only the eligible (non-excluded) portion of the
1157
+ // cart — excluded categories/items never count toward unlock amounts. When
1158
+ // the cart has no matching excluded refs, keep the original base untouched.
1159
+ const excludedRefs = getOfferOrderValueExcludedRefs(offer);
1160
+ const eligibleSubtotalResult = excludedRefs.length > 0 && categories != null
1161
+ ? calculateEligibleOfferDiscountDetails(categories, excludedRefs)
1162
+ : null;
1163
+ const effectiveBaseAmount = eligibleSubtotalResult?.hasExcludedRefs === true ? eligibleSubtotalResult.subtotal : orderLevelDiscountBaseAmount;
1164
+ const ownOrderLevelDiscountAmount = getOwnOfferOrderLevelDiscountAmount({
1165
+ offer,
1166
+ orderDiscountDetails,
1167
+ orderLevelDiscountBaseAmount: effectiveBaseAmount,
1168
+ orderLevelDiscountAmount,
1169
+ });
1170
+ return parseNum(Math.max(0, effectiveBaseAmount - orderLevelDiscountAmount + ownOrderLevelDiscountAmount));
1171
+ }
1172
+ export function getMaxApplicableWalletCashback({ cashbackBalance, itemsPrice, totalDiscountApplied, orderLevelDiscount, }) {
1173
+ const safeCashbackBalance = Number.isFinite(cashbackBalance) ? Math.max(0, Number(cashbackBalance)) : 0;
1174
+ const netItemsValue = getNetItemsValueAfterItemDiscount({
1175
+ itemsPrice,
1176
+ totalDiscountApplied,
1177
+ orderLevelDiscount,
1178
+ });
1179
+ return parseNum(Math.min(safeCashbackBalance, netItemsValue));
1180
+ }
1181
+ export const DEFAULT_WALLET_CASHBACK_PERCENTAGE_STEPS = [25, 50, 75, 100];
1182
+ export function getWalletCashbackRecommendedBreakpoints({ maxApplicableCashback, percentageSteps = DEFAULT_WALLET_CASHBACK_PERCENTAGE_STEPS, }) {
1183
+ const safeMaxApplicableCashback = Number.isFinite(maxApplicableCashback)
1184
+ ? Math.max(0, Number(maxApplicableCashback))
1185
+ : 0;
1186
+ if (safeMaxApplicableCashback <= 0) {
1187
+ return [];
1188
+ }
1189
+ const percentageByValue = new Map();
1190
+ for (let i = 0; i < percentageSteps.length; i++) {
1191
+ const percentageStep = Number(percentageSteps[i]);
1192
+ if (!Number.isFinite(percentageStep)) {
1193
+ continue;
1194
+ }
1195
+ const safePercentageStep = parseNum(Math.max(0, Math.min(100, percentageStep)));
1196
+ const computedValue = parseNum((safeMaxApplicableCashback * safePercentageStep) / 100);
1197
+ const normalizedValue = parseNum(Math.max(0, Math.min(computedValue, safeMaxApplicableCashback)));
1198
+ if (normalizedValue <= 0) {
1199
+ continue;
1200
+ }
1201
+ percentageByValue.set(normalizedValue, safePercentageStep);
1202
+ }
1203
+ return Array.from(percentageByValue.entries())
1204
+ .sort((a, b) => a[0] - b[0])
1205
+ .map(([value, percentage]) => ({ value, percentage }));
1206
+ }
1207
+ export function getWalletCashbackRecommendedValues({ maxApplicableCashback, percentageSteps = DEFAULT_WALLET_CASHBACK_PERCENTAGE_STEPS, }) {
1208
+ return getWalletCashbackRecommendedBreakpoints({
1209
+ maxApplicableCashback,
1210
+ percentageSteps,
1211
+ }).map((breakpoint) => breakpoint.value);
1212
+ }
1213
+ function normalizeGiftCardId(giftCardId) {
1214
+ if (giftCardId == null)
1215
+ return null;
1216
+ const normalizedGiftCardId = giftCardId.toString().trim();
1217
+ return normalizedGiftCardId.length > 0 ? normalizedGiftCardId : null;
1218
+ }
1219
+ function normalizeWalletRedemptions(walletRedemptions) {
1220
+ if (walletRedemptions == null) {
1221
+ return null;
1222
+ }
1223
+ const normalizedWalletRedemptions = {};
1224
+ const cashbackAmount = Number(walletRedemptions.cashback_amount);
1225
+ if (Number.isFinite(cashbackAmount) && cashbackAmount > 0) {
1226
+ normalizedWalletRedemptions.cashback_amount = parseNum(cashbackAmount);
1227
+ }
1228
+ const rawGiftCardRedemptions = walletRedemptions.gift_cards;
1229
+ const giftCardRedemptions = rawGiftCardRedemptions == null
1230
+ ? []
1231
+ : Array.isArray(rawGiftCardRedemptions)
1232
+ ? rawGiftCardRedemptions
1233
+ : [rawGiftCardRedemptions];
1234
+ if (giftCardRedemptions.length > 0) {
1235
+ const normalizedGiftCardRedemptionsMap = {};
1236
+ for (let i = 0; i < giftCardRedemptions.length; i++) {
1237
+ const giftCardRedemption = giftCardRedemptions[i];
1238
+ const giftCardId = normalizeGiftCardId(giftCardRedemption.gift_card_id);
1239
+ const legacyValueRedeemed = giftCardRedemption.value_redeemed;
1240
+ const redeemedTimes = toPositiveInteger(giftCardRedemption.redeemed_times ?? legacyValueRedeemed, 0);
1241
+ if (giftCardId == null || redeemedTimes <= 0) {
1242
+ continue;
1243
+ }
1244
+ const existingRedemption = normalizedGiftCardRedemptionsMap[giftCardId];
1245
+ normalizedGiftCardRedemptionsMap[giftCardId] = {
1246
+ gift_card_id: giftCardId,
1247
+ redeemed_times: (existingRedemption?.redeemed_times ?? 0) + redeemedTimes,
1248
+ ...(giftCardRedemption.mystery_gift_type != null
1249
+ ? { mystery_gift_type: giftCardRedemption.mystery_gift_type }
1250
+ : existingRedemption?.mystery_gift_type != null
1251
+ ? { mystery_gift_type: existingRedemption.mystery_gift_type }
1252
+ : {}),
1253
+ };
1254
+ }
1255
+ const normalizedGiftCardRedemptions = Object.values(normalizedGiftCardRedemptionsMap);
1256
+ if (normalizedGiftCardRedemptions.length > 0) {
1257
+ normalizedWalletRedemptions.gift_cards = normalizedGiftCardRedemptions;
1258
+ }
1259
+ }
1260
+ return Object.keys(normalizedWalletRedemptions).length > 0 ? normalizedWalletRedemptions : null;
1261
+ }
1262
+ export function buildWalletRedemptionsPatch({ walletRedemptions, }) {
1263
+ return {
1264
+ wallet_redemptions: normalizeWalletRedemptions(walletRedemptions),
1265
+ };
1266
+ }
1267
+ export function buildWalletRedemptionsMergePatch({ currentWalletRedemptions, walletRedemptionsPatch, }) {
1268
+ const normalizedCurrentWalletRedemptions = normalizeWalletRedemptions(currentWalletRedemptions);
1269
+ const mergedWalletRedemptions = {
1270
+ ...(normalizedCurrentWalletRedemptions ?? {}),
1271
+ ...(walletRedemptionsPatch ?? {}),
1272
+ };
1273
+ return {
1274
+ wallet_redemptions: normalizeWalletRedemptions(mergedWalletRedemptions),
1275
+ };
1276
+ }
1277
+ export function buildWalletCashbackRedemptionPatch({ currentWalletRedemptions, cashbackAmount, }) {
1278
+ return buildWalletRedemptionsMergePatch({
1279
+ currentWalletRedemptions,
1280
+ walletRedemptionsPatch: {
1281
+ cashback_amount: cashbackAmount,
1282
+ },
1283
+ });
1284
+ }
1285
+ export function buildWalletGiftCardRedemptionPatch({ currentWalletRedemptions, giftCardRedemption, }) {
1286
+ const giftCardRedemptionsPatch = giftCardRedemption == null
1287
+ ? undefined
1288
+ : Array.isArray(giftCardRedemption)
1289
+ ? giftCardRedemption
1290
+ : [giftCardRedemption];
1291
+ return buildWalletRedemptionsMergePatch({
1292
+ currentWalletRedemptions,
1293
+ walletRedemptionsPatch: {
1294
+ gift_cards: giftCardRedemptionsPatch,
1295
+ },
1296
+ });
1297
+ }
1298
+ export function buildWalletGiftCardRedemptionClaimPatch({ currentWalletRedemptions, giftCardId, claimsIncrement = 1, mysteryGiftType, }) {
1299
+ const normalizedGiftCardId = normalizeGiftCardId(giftCardId);
1300
+ if (normalizedGiftCardId == null) {
1301
+ return {};
1302
+ }
1303
+ const safeClaimsIncrement = toPositiveInteger(claimsIncrement, 1);
1304
+ const normalizedCurrentWalletRedemptions = normalizeWalletRedemptions(currentWalletRedemptions);
1305
+ const existingGiftCardRedemptions = normalizedCurrentWalletRedemptions?.gift_cards ?? [];
1306
+ let hasUpdatedGiftCardClaim = false;
1307
+ const nextGiftCardRedemptions = existingGiftCardRedemptions.map((existingGiftCardRedemption) => {
1308
+ if (existingGiftCardRedemption.gift_card_id !== normalizedGiftCardId) {
1309
+ return existingGiftCardRedemption;
1310
+ }
1311
+ hasUpdatedGiftCardClaim = true;
1312
+ return {
1313
+ ...existingGiftCardRedemption,
1314
+ redeemed_times: toPositiveInteger(existingGiftCardRedemption.redeemed_times, 0) + safeClaimsIncrement,
1315
+ ...(mysteryGiftType != null ? { mystery_gift_type: mysteryGiftType } : {}),
1316
+ };
1317
+ });
1318
+ if (!hasUpdatedGiftCardClaim) {
1319
+ nextGiftCardRedemptions.push({
1320
+ gift_card_id: normalizedGiftCardId,
1321
+ redeemed_times: safeClaimsIncrement,
1322
+ ...(mysteryGiftType != null ? { mystery_gift_type: mysteryGiftType } : {}),
1323
+ });
1324
+ }
1325
+ return buildWalletGiftCardRedemptionPatch({
1326
+ currentWalletRedemptions,
1327
+ giftCardRedemption: nextGiftCardRedemptions,
1328
+ });
1329
+ }
1330
+ export function buildClearWalletRedemptionsPatch({ currentWalletRedemptions, clearCashbackAmount = false, clearGiftCardRedemption = false, clearAll = false, }) {
1331
+ if (clearAll) {
1332
+ return {
1333
+ wallet_redemptions: null,
1334
+ };
1335
+ }
1336
+ if (!clearCashbackAmount && !clearGiftCardRedemption) {
1337
+ return {
1338
+ wallet_redemptions: normalizeWalletRedemptions(currentWalletRedemptions),
1339
+ };
1340
+ }
1341
+ const normalizedCurrentWalletRedemptions = normalizeWalletRedemptions(currentWalletRedemptions);
1342
+ if (normalizedCurrentWalletRedemptions == null) {
1343
+ return {
1344
+ wallet_redemptions: null,
1345
+ };
1346
+ }
1347
+ const nextWalletRedemptions = {
1348
+ ...normalizedCurrentWalletRedemptions,
1349
+ ...(clearCashbackAmount ? { cashback_amount: undefined } : {}),
1350
+ ...(clearGiftCardRedemption ? { gift_cards: undefined } : {}),
1351
+ };
1352
+ return {
1353
+ wallet_redemptions: normalizeWalletRedemptions(nextWalletRedemptions),
1354
+ };
1355
+ }
1356
+ function buildRewardPreview(offer) {
1357
+ switch (offer.reward_type) {
1358
+ case OFFER_REWARD_TYPE_ENUM.DISCOUNT: {
1359
+ if (offer.reward_discount == null)
1360
+ return null;
1361
+ const { discount_value, is_discount_percentage, max_discount_amount, max_discount_percentage } = offer.reward_discount;
1362
+ let label = is_discount_percentage ? `${discount_value}% off` : `${discount_value} off`;
1363
+ if (is_discount_percentage && max_discount_amount != null) {
1364
+ label += ` (max ${max_discount_amount})`;
1365
+ }
1366
+ if (!is_discount_percentage && max_discount_percentage != null) {
1367
+ label += ` (max ${max_discount_percentage}%)`;
1368
+ }
1369
+ return {
1370
+ type: OFFER_REWARD_TYPE_ENUM.DISCOUNT,
1371
+ label,
1372
+ discount_value,
1373
+ is_percentage: is_discount_percentage,
1374
+ max_discount_amount,
1375
+ max_discount_percentage,
1376
+ };
1377
+ }
1378
+ case OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS: {
1379
+ if (offer.reward_discount_items == null)
1380
+ return null;
1381
+ const { discount_value, is_discount_percentage, num_of_items } = offer.reward_discount_items;
1382
+ return {
1383
+ type: OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS,
1384
+ label: is_discount_percentage
1385
+ ? `${discount_value}% off on ${num_of_items} item(s)`
1386
+ : `${discount_value} off on ${num_of_items} item(s)`,
1387
+ discount_value,
1388
+ is_percentage: is_discount_percentage,
1389
+ free_items_count: num_of_items,
1390
+ };
1391
+ }
1392
+ case OFFER_REWARD_TYPE_ENUM.ITEMS: {
1393
+ if (offer.reward_items == null)
1394
+ return null;
1395
+ return {
1396
+ type: OFFER_REWARD_TYPE_ENUM.ITEMS,
1397
+ label: `Free ${offer.reward_items.num_of_items} item(s)`,
1398
+ free_items_count: offer.reward_items.num_of_items,
1399
+ };
1400
+ }
1401
+ case OFFER_REWARD_TYPE_ENUM.POINTS: {
1402
+ if (offer.reward_points == null)
1403
+ return null;
1404
+ return {
1405
+ type: OFFER_REWARD_TYPE_ENUM.POINTS,
1406
+ label: `${offer.reward_points.num_of_points} points`,
1407
+ points_value: offer.reward_points.num_of_points,
1408
+ };
1409
+ }
1410
+ case OFFER_REWARD_TYPE_ENUM.CASHBACK: {
1411
+ if (offer.reward_cashback == null)
1412
+ return null;
1413
+ const { cashback_value, is_cashback_percentage } = offer.reward_cashback;
1414
+ return {
1415
+ type: OFFER_REWARD_TYPE_ENUM.CASHBACK,
1416
+ label: is_cashback_percentage ? `${cashback_value}% cashback` : `${cashback_value} cashback`,
1417
+ cashback_value,
1418
+ is_percentage: is_cashback_percentage,
1419
+ };
1420
+ }
1421
+ case OFFER_REWARD_TYPE_ENUM.GIFT_CARDS: {
1422
+ if (offer.reward_gift_cards == null)
1423
+ return null;
1424
+ return {
1425
+ type: OFFER_REWARD_TYPE_ENUM.GIFT_CARDS,
1426
+ label: `Gift card reward`,
1427
+ };
1428
+ }
1429
+ case OFFER_REWARD_TYPE_ENUM.VOUCHER: {
1430
+ if (offer.reward_voucher == null)
1431
+ return null;
1432
+ return {
1433
+ type: OFFER_REWARD_TYPE_ENUM.VOUCHER,
1434
+ label: `Voucher code reward`,
1435
+ };
1436
+ }
1437
+ default:
1438
+ return null;
1439
+ }
1440
+ }
1441
+ function getEligibleItemIds(offer) {
1442
+ if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.ITEMS && offer.reward_items != null) {
1443
+ return offer.reward_items.item_ids ?? [];
1444
+ }
1445
+ if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS && offer.reward_discount_items != null) {
1446
+ return offer.reward_discount_items.item_ids ?? [];
1447
+ }
1448
+ return [];
1449
+ }
1450
+ function getEligibleCategoryIds(offer) {
1451
+ if (offer.pathway_to_unlock_type === PATHWAY_TO_UNLOCK_TYPE_ENUM.ITEMS &&
1452
+ offer.pathway_to_unlock_type_items != null) {
1453
+ return offer.pathway_to_unlock_type_items.category_ids ?? [];
1454
+ }
1455
+ return [];
1456
+ }
1457
+ function getActionHint(offer, claimable) {
1458
+ if (!claimable)
1459
+ return null;
1460
+ if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.ITEMS)
1461
+ return 'Select your free items';
1462
+ if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS)
1463
+ return 'Select items for discount';
1464
+ return 'Ready to apply';
1465
+ }
1466
+ function getProgressPercentage(currentValue, requiredValue) {
1467
+ if (requiredValue <= 0)
1468
+ return 100;
1469
+ const safeCurrentValue = Number.isFinite(currentValue) ? Math.max(0, currentValue) : 0;
1470
+ const safeRequiredValue = Number.isFinite(requiredValue) ? requiredValue : 0;
1471
+ if (safeRequiredValue <= 0)
1472
+ return 100;
1473
+ return Math.max(0, Math.min(100, Math.round((safeCurrentValue / safeRequiredValue) * 100)));
1474
+ }
1475
+ /**
1476
+ * Progress that stays below 100% while a pathway requirement is still unmet.
1477
+ *
1478
+ * A requirement that is absent, zero or negative counts as already satisfied
1479
+ * (`getProgressPercentage` returns 100 for it), so callers must pass the RAW
1480
+ * requirement. The old `requirement || 1` fallbacks turned a satisfied minimum
1481
+ * (e.g. `min_num_of_orders: 0`, `num_of_items: 0`, `num_of_points: 0`,
1482
+ * `total_amount: 0`) into 0%, which then zeroed the `Math.min(...)` combined
1483
+ * progress for the whole pre-unlock range. Unlocking is never decided by this
1484
+ * progress value — the pathway comparisons (`orderValue >= total_amount` etc.)
1485
+ * and the explicit `stats.progress = 100` branches decide it.
1486
+ */
1487
+ function getPreUnlockProgressPercentage(currentValue, requiredValue) {
1488
+ return Math.min(99, getProgressPercentage(currentValue, requiredValue ?? 0));
1489
+ }
1490
+ function getUnlockedOffersApplicableTimesHashKey(map, isEdit) {
1491
+ const keys = Object.keys(map).sort();
1492
+ const editPrefix = isEdit ? 'edit:v1:' : '';
1493
+ if (keys.length === 0)
1494
+ return `unlock:v1:${editPrefix}empty`;
1495
+ let result = `unlock:v1:${editPrefix}`;
1496
+ for (let i = 0; i < keys.length; i++) {
1497
+ const key = keys[i];
1498
+ result += `${key}:${map[key]};`;
1499
+ }
1500
+ return result;
1501
+ }
1502
+ function getRewardPreviewHashKey(rewardPreview) {
1503
+ if (rewardPreview == null)
1504
+ return '';
1505
+ return [
1506
+ rewardPreview.type,
1507
+ rewardPreview.label,
1508
+ rewardPreview.discount_value ?? '',
1509
+ rewardPreview.is_percentage ?? '',
1510
+ rewardPreview.max_discount_amount ?? '',
1511
+ rewardPreview.max_discount_percentage ?? '',
1512
+ rewardPreview.free_items_count ?? '',
1513
+ rewardPreview.points_value ?? '',
1514
+ rewardPreview.cashback_value ?? '',
1515
+ rewardPreview.gift_card_value ?? '',
1516
+ ].join('|');
1517
+ }
1518
+ // HASH KEY RULE: Every field on IOfferStats that can change must be included in the hash key below.
1519
+ // If you add or rename a field on IOfferStats, you MUST add it to the hash string concatenation.
1520
+ // Failing to do so will cause the frontend (OffersProvider) to miss state changes —
1521
+ // it compares hash key strings to decide whether to update React state / dispatch Redux actions.
1522
+ // The same rule applies to getUnlockedOffersApplicableTimesHashKey and getRewardPreviewHashKey.
1523
+ function getOffersWithStatsHashKey({ offersWithStats, totalClaimableOffers, isEdit, itemsCount, itemsPrice, }) {
1524
+ const editSegment = isEdit ? 'edit:' : '';
1525
+ const cartSegment = `c:${itemsCount ?? 0}:${parseNum(itemsPrice ?? 0)}`;
1526
+ if (offersWithStats.length === 0) {
1527
+ return `offers:v1:${editSegment}${cartSegment}:empty:${totalClaimableOffers.length}`;
1528
+ }
1529
+ const sortedOffers = [...offersWithStats].sort((a, b) => a.offer._id.localeCompare(b.offer._id));
1530
+ let result = `offers:v1:${editSegment}${cartSegment}:${totalClaimableOffers.length}|`;
1531
+ for (let i = 0; i < sortedOffers.length; i++) {
1532
+ const { offer, stats } = sortedOffers[i];
1533
+ const eligibleItemIds = [...stats.eligible_item_ids].sort().join(',');
1534
+ const eligibleCategoryIds = [...stats.eligible_category_ids].sort().join(',');
1535
+ const rewardPreviewKey = getRewardPreviewHashKey(stats.reward_preview);
1536
+ result += `${offer._id}:${stats.progress}:${stats.message}:${stats.invalid_offer ? 1 : 0}:${stats.redeemed_times}:${stats.claimable ? 1 : 0}:${stats.applicable_quantity}:${stats.action_hint ?? ''}:${stats.auto_apply ? 1 : 0}:${eligibleItemIds}:${eligibleCategoryIds}:${rewardPreviewKey};`;
1537
+ }
1538
+ return result;
1539
+ }
1540
+ export function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOfferRedemptionCounts, redeemed_offers, platform, currency_symbol, currentItemsPrice, totalDiscountApplied, categories, order_discount_details, isEdit, editedOrderRedeemedOffers, }) {
1541
+ const offersWithStats = [];
1542
+ const { baseAmount: orderLevelDiscountBaseAmount, itemsCount } = getOrderLevelDiscountBaseAmountForOfferStats({
1543
+ categories,
1544
+ itemsPrice: currentItemsPrice,
1545
+ totalDiscountApplied,
1546
+ orderDiscountDetails: order_discount_details,
1547
+ });
1548
+ const orderLevelDiscountAmount = getOrderLevelDiscountAmountForOfferStats({
1549
+ orderDiscountDetails: order_discount_details,
1550
+ orderLevelDiscountBaseAmount,
1551
+ });
1552
+ const unlockedOffersApplicableTimes = {};
1553
+ let totalClaimableOffers = [];
1554
+ let totalLoyaltyPointsOfCustomer = null;
1555
+ const nowTs = Date.now();
1556
+ const isVoucherUseResourceUnavailable = (voucher) => {
1557
+ if (voucher == null) {
1558
+ return true;
1559
+ }
1560
+ const voucherIsExpired = voucher.expire_at != null && new Date(voucher.expire_at).getTime() <= nowTs;
1561
+ const voucherUsesExhausted = voucher.max_uses != null && voucher.used_count >= voucher.max_uses;
1562
+ return !voucher.active || voucherIsExpired || voucherUsesExhausted;
1563
+ };
1564
+ const isVoucherRewardResourceUnavailable = (voucher) => {
1565
+ if (voucher == null) {
1566
+ return true;
1567
+ }
1568
+ const voucherIsExpired = voucher.expire_at != null && new Date(voucher.expire_at).getTime() <= nowTs;
1569
+ const voucherAssignmentsExhausted = voucher.max_assignments != null && voucher.assigned_count >= voucher.max_assignments;
1570
+ return !voucher.active || voucherIsExpired || voucherAssignmentsExhausted;
1571
+ };
1572
+ const isGiftCardRewardResourceUnavailable = (giftCard) => {
1573
+ if (giftCard == null) {
1574
+ return true;
1575
+ }
1576
+ const giftCardIsExpired = giftCard.expire_at != null && new Date(giftCard.expire_at).getTime() <= nowTs;
1577
+ const giftCardAssignmentsExhausted = giftCard.max_assignments != null && giftCard.assigned_count >= giftCard.max_assignments;
1578
+ return !giftCard.active || giftCardIsExpired || giftCardAssignmentsExhausted;
1579
+ };
1580
+ const { voucherCodes: spendableVoucherCodesByCode } = calculateCustomerSpendableVoucherCodes({
1581
+ customerVoucherCodes: customer?.voucher_codes,
1582
+ orderDiscountDetails: order_discount_details,
1583
+ redeemedOffers: redeemed_offers,
1584
+ offers,
1585
+ vouchers,
1586
+ });
1587
+ const voucherPathwayCartContext = getVoucherPathwayCartContext({
1588
+ offers,
1589
+ vouchers,
1590
+ redeemedOffers: redeemed_offers,
1591
+ orderDiscountDetails: order_discount_details,
1592
+ });
1593
+ const redeemedOffersById = redeemed_offers ?? null;
1594
+ // Frozen baseline of the edited order's own claims (captured when the edit
1595
+ // session started). Normalized once here so the per-offer evaluation below
1596
+ // can subtract them from the customer's lifetime USED counters without the
1597
+ // edited order counting itself out of `max_uses_per_customer`.
1598
+ const editedOrderBaselineClaims = new Map();
1599
+ if (isEdit && editedOrderRedeemedOffers != null) {
1600
+ const baselineOfferIds = Object.keys(editedOrderRedeemedOffers);
1601
+ for (let i = 0; i < baselineOfferIds.length; i++) {
1602
+ const baselineOfferId = baselineOfferIds[i];
1603
+ const normalizedBaselineOfferId = normalizeOfferId(baselineOfferId);
1604
+ const rawBaselineCount = Number(editedOrderRedeemedOffers[baselineOfferId]);
1605
+ if (normalizedBaselineOfferId == null || !Number.isFinite(rawBaselineCount) || rawBaselineCount <= 0) {
1606
+ continue;
1607
+ }
1608
+ editedOrderBaselineClaims.set(normalizedBaselineOfferId, Math.floor(rawBaselineCount));
1609
+ }
1610
+ }
1611
+ const getBaselineRedeemedClaimsForOffer = (offerId) => {
1612
+ const normalizedOfferId = normalizeOfferId(offerId);
1613
+ if (normalizedOfferId == null)
1614
+ return 0;
1615
+ return editedOrderBaselineClaims.get(normalizedOfferId) ?? 0;
1616
+ };
1617
+ const getEffectiveUsedRedemptionCount = (offerId) => Math.max(0, getCustomerUsedRedemptionCount(customerOfferRedemptionCounts, offerId) -
1618
+ getBaselineRedeemedClaimsForOffer(offerId));
1619
+ const vouchersById = new Map();
1620
+ const allVouchersById = new Map();
1621
+ if (vouchers != null) {
1622
+ for (let i = 0; i < vouchers.length; i++) {
1623
+ const voucher = vouchers[i];
1624
+ allVouchersById.set(voucher._id, voucher);
1625
+ if (isVoucherUseResourceUnavailable(voucher)) {
1626
+ continue;
1627
+ }
1628
+ vouchersById.set(voucher._id, voucher);
1629
+ }
1630
+ }
1631
+ const giftCardsById = new Map();
1632
+ const allGiftCardsById = new Map();
1633
+ if (giftCards != null) {
1634
+ for (let i = 0; i < giftCards.length; i++) {
1635
+ const giftCard = giftCards[i];
1636
+ allGiftCardsById.set(giftCard._id, giftCard);
1637
+ if (isGiftCardRewardResourceUnavailable(giftCard)) {
1638
+ continue;
1639
+ }
1640
+ giftCardsById.set(giftCard._id, giftCard);
1641
+ }
1642
+ }
1643
+ const getRewardVoucherAvailability = (voucherIds) => {
1644
+ let rewardVoucherUnavailable = false;
1645
+ let rewardVoucherLimitExhausted = false;
1646
+ for (let vIdx = 0; vIdx < voucherIds.length; vIdx++) {
1647
+ const rewardVoucher = allVouchersById.get(voucherIds[vIdx]);
1648
+ if (rewardVoucher == null || isVoucherRewardResourceUnavailable(rewardVoucher)) {
1649
+ rewardVoucherUnavailable = true;
1650
+ break;
1651
+ }
1652
+ const maxAssignmentsPerCustomer = getRewardMaxAssignmentsPerCustomer(rewardVoucher);
1653
+ if (maxAssignmentsPerCustomer != null &&
1654
+ (customerOfferRedemptionCounts == null ||
1655
+ getCustomerAssignedRedemptionCount(customerOfferRedemptionCounts, rewardVoucher._id) >=
1656
+ maxAssignmentsPerCustomer)) {
1657
+ rewardVoucherLimitExhausted = true;
1658
+ break;
1659
+ }
1660
+ }
1661
+ return {
1662
+ rewardVoucherUnavailable,
1663
+ rewardVoucherLimitExhausted,
1664
+ };
1665
+ };
1666
+ const getRewardGiftCardAvailability = (giftCardIds) => {
1667
+ let rewardGiftCardUnavailable = false;
1668
+ let rewardGiftCardLimitExhausted = false;
1669
+ for (let gcIdx = 0; gcIdx < giftCardIds.length; gcIdx++) {
1670
+ const rewardGiftCard = allGiftCardsById.get(giftCardIds[gcIdx]);
1671
+ if (rewardGiftCard == null || isGiftCardRewardResourceUnavailable(rewardGiftCard)) {
1672
+ rewardGiftCardUnavailable = true;
1673
+ break;
1674
+ }
1675
+ const maxAssignmentsPerCustomer = getRewardMaxAssignmentsPerCustomer(rewardGiftCard);
1676
+ if (maxAssignmentsPerCustomer != null &&
1677
+ (customerOfferRedemptionCounts == null ||
1678
+ getCustomerAssignedRedemptionCount(customerOfferRedemptionCounts, rewardGiftCard._id) >=
1679
+ maxAssignmentsPerCustomer)) {
1680
+ rewardGiftCardLimitExhausted = true;
1681
+ break;
1682
+ }
1683
+ }
1684
+ return {
1685
+ rewardGiftCardUnavailable,
1686
+ rewardGiftCardLimitExhausted,
1687
+ };
1688
+ };
1689
+ const clearBlockedRewardApplicableQuantity = (offerToCheck, statsToUpdate) => {
1690
+ if (statsToUpdate.claimable ||
1691
+ (offerToCheck.reward_type !== OFFER_REWARD_TYPE_ENUM.VOUCHER &&
1692
+ offerToCheck.reward_type !== OFFER_REWARD_TYPE_ENUM.GIFT_CARDS)) {
1693
+ return;
1694
+ }
1695
+ if (statsToUpdate.message !== '⛔️ This reward is no longer available ⛔️' &&
1696
+ statsToUpdate.message !== '⛔️ You have reached your personal limit for this reward ⛔️') {
1697
+ return;
1698
+ }
1699
+ statsToUpdate.applicable_quantity = 0;
1700
+ unlockedOffersApplicableTimes[offerToCheck._id] = 0;
1701
+ };
1702
+ const getOfferRedeemedTimes = (offerId) => {
1703
+ const redeemedTimes = Number(redeemedOffersById?.[offerId]);
1704
+ if (Number.isFinite(redeemedTimes) && redeemedTimes > 0) {
1705
+ return Math.floor(redeemedTimes);
1706
+ }
1707
+ return 0;
1708
+ };
1709
+ const getItemRewardRedeemedTimes = ({ totalOfferItemsSelected, applicableQuantity, }) => {
1710
+ const safeApplicableQuantity = Math.max(1, applicableQuantity || 1);
1711
+ // Item reward claimability should follow the current cart snapshot so
1712
+ // removing a claimed reward item re-opens one claim slot.
1713
+ return Math.floor(totalOfferItemsSelected / safeApplicableQuantity);
1714
+ };
1715
+ const getOrdersScopedStats = ({ scope, currentOrderValue, }) => {
1716
+ if (scope === PATHWAY_TO_UNLOCK_TYPE_ORDERS_SCOPE_ENUM.OVERALL) {
1717
+ const rawTotalOrders = customer?.total_orders ?? 0;
1718
+ const totalOrders = isEdit ? Math.max(0, rawTotalOrders - 1) : rawTotalOrders;
1719
+ return {
1720
+ valid: true,
1721
+ totalOrders,
1722
+ totalAmount: currentOrderValue,
1723
+ };
1724
+ }
1725
+ if (platform == null) {
1726
+ return {
1727
+ valid: false,
1728
+ totalOrders: 0,
1729
+ totalAmount: 0,
1730
+ };
1731
+ }
1732
+ const totalOrdersPerPlatform = customer?.total_orders_per_platform_type;
1733
+ if (scope === PATHWAY_TO_UNLOCK_TYPE_ORDERS_SCOPE_ENUM.PLATFORM) {
1734
+ const rawPlatformOrders = totalOrdersPerPlatform?.[platform] ?? 0;
1735
+ const totalOrders = isEdit ? Math.max(0, rawPlatformOrders - 1) : rawPlatformOrders;
1736
+ return {
1737
+ valid: true,
1738
+ totalOrders,
1739
+ totalAmount: currentOrderValue,
1740
+ };
1741
+ }
1742
+ const orderFrom = platform.split('_')[0];
1743
+ const platformsForOrderFrom = PLATFORMS_BY_ORDER_FROM[orderFrom];
1744
+ if (platformsForOrderFrom == null) {
1745
+ return {
1746
+ valid: false,
1747
+ totalOrders: 0,
1748
+ totalAmount: 0,
1749
+ };
1750
+ }
1751
+ let totalOrders = 0;
1752
+ for (let i = 0; i < platformsForOrderFrom.length; i++) {
1753
+ const groupedPlatform = platformsForOrderFrom[i];
1754
+ totalOrders += totalOrdersPerPlatform?.[groupedPlatform] ?? 0;
1755
+ }
1756
+ // When editing, the current order's platform bucket is inflated by 1.
1757
+ // Since ORDER_FROM aggregates across all platforms under the same
1758
+ // prefix and the current order contributed exactly 1 to its own
1759
+ // platform bucket, subtract 1 from the aggregate.
1760
+ if (isEdit) {
1761
+ totalOrders = Math.max(0, totalOrders - 1);
1762
+ }
1763
+ return {
1764
+ valid: true,
1765
+ totalOrders,
1766
+ totalAmount: currentOrderValue,
1767
+ };
1768
+ };
1769
+ const getOfferMaxUsesPerCustomer = (offerToCheck) => {
1770
+ if (offerToCheck.pathway_to_unlock_type === PATHWAY_TO_UNLOCK_TYPE_ENUM.ORDERS) {
1771
+ return offerToCheck.pathway_to_unlock_type_orders?.max_uses_per_customer ?? null;
1772
+ }
1773
+ if (offerToCheck.pathway_to_unlock_type === PATHWAY_TO_UNLOCK_TYPE_ENUM.ITEMS) {
1774
+ return offerToCheck.pathway_to_unlock_type_items?.max_uses_per_customer ?? null;
1775
+ }
1776
+ if (offerToCheck.pathway_to_unlock_type === PATHWAY_TO_UNLOCK_TYPE_ENUM.POINTS) {
1777
+ return offerToCheck.pathway_to_unlock_type_points?.max_uses_per_customer ?? null;
1778
+ }
1779
+ if (offerToCheck.pathway_to_unlock_type === PATHWAY_TO_UNLOCK_TYPE_ENUM.VOUCHER) {
1780
+ return offerToCheck.pathway_to_unlock_type_vouchers?.max_uses_per_customer ?? null;
1781
+ }
1782
+ return null;
1783
+ };
1784
+ const isOfferUsesPerCustomerExhausted = (offerToCheck) => {
1785
+ const maxUsesPerCustomer = getOfferMaxUsesPerCustomer(offerToCheck);
1786
+ if (maxUsesPerCustomer == null)
1787
+ return false;
1788
+ const baselineRedeemedClaims = getBaselineRedeemedClaimsForOffer(offerToCheck._id);
1789
+ // Unknown counts must never destroy claims the edited order verifiably
1790
+ // carried at load; for everything else keep the conservative
1791
+ // "counts unknown = exhausted" behavior so new claims stay blocked.
1792
+ if (customerOfferRedemptionCounts == null) {
1793
+ return baselineRedeemedClaims <= 0;
1794
+ }
1795
+ return getEffectiveUsedRedemptionCount(offerToCheck._id) >= maxUsesPerCustomer;
1796
+ };
1797
+ // Remaining lifetime budget for this offer expressed in CLAIMS:
1798
+ // max_uses_per_customer minus the customer's effective (baseline-adjusted)
1799
+ // settled usage. Null when the offer has no per-customer limit.
1800
+ const getRemainingClaimBudgetForOffer = (offerToCheck) => {
1801
+ const maxUsesPerCustomer = getOfferMaxUsesPerCustomer(offerToCheck);
1802
+ if (maxUsesPerCustomer == null)
1803
+ return null;
1804
+ // Unknown counts must not grant new claims: preserve only when the
1805
+ // edited order verifiably carried claims (mirrors
1806
+ // isOfferUsesPerCustomerExhausted). With a baseline the full limit stays
1807
+ // available because the customer's true used count is unknown.
1808
+ if (customerOfferRedemptionCounts == null) {
1809
+ return getBaselineRedeemedClaimsForOffer(offerToCheck._id) > 0 ? maxUsesPerCustomer : 0;
1810
+ }
1811
+ return Math.max(0, maxUsesPerCustomer - getEffectiveUsedRedemptionCount(offerToCheck._id));
1812
+ };
1813
+ // Per-order claim counts (value chunks / max_claims) must never exceed the
1814
+ // customer's remaining budget, otherwise a multi-claim reward could be
1815
+ // claimed more times in one order than max_uses_per_customer allows.
1816
+ const clampClaimsToRemainingClaimBudget = (offerToCheck, perOrderClaims) => {
1817
+ const remainingBudget = getRemainingClaimBudgetForOffer(offerToCheck);
1818
+ return remainingBudget == null ? perOrderClaims : Math.min(perOrderClaims, remainingBudget);
1819
+ };
1820
+ const getOrderValueClaimTimes = (orderValue, minAmount) => {
1821
+ const safeRequiredAmount = Math.max(1, minAmount || 1);
1822
+ return Math.max(1, Math.floor(orderValue / safeRequiredAmount));
1823
+ };
1824
+ const getOrdersBetweenUnlocksStats = ({ totalOrders, ordersBetweenUnlocks, }) => {
1825
+ const normalizedTotalOrders = Math.max(0, Math.floor(Number.isFinite(totalOrders) ? totalOrders : 0));
1826
+ const normalizedOrdersBetweenUnlocks = toPositiveInteger(ordersBetweenUnlocks, 0);
1827
+ if (normalizedOrdersBetweenUnlocks <= 0) {
1828
+ return {
1829
+ isUnlockOrder: true,
1830
+ ordersAwayFromNextUnlock: 0,
1831
+ progress: 100,
1832
+ };
1833
+ }
1834
+ const unlockInterval = normalizedOrdersBetweenUnlocks + 1;
1835
+ const remainder = normalizedTotalOrders % unlockInterval;
1836
+ const isUnlockOrder = normalizedTotalOrders > 0 && remainder === 0;
1837
+ const ordersAwayFromNextUnlock = isUnlockOrder ? 0 : remainder === 0 ? unlockInterval : unlockInterval - remainder;
1838
+ return {
1839
+ isUnlockOrder,
1840
+ ordersAwayFromNextUnlock,
1841
+ progress: getPreUnlockProgressPercentage(remainder, unlockInterval),
1842
+ };
1843
+ };
1844
+ const getPointsMaxRedeemableClaims = ({ offerToCheck, pathwayUnlockableClaims, }) => {
1845
+ if (offerToCheck.reward_type !== OFFER_REWARD_TYPE_ENUM.POINTS || offerToCheck.reward_points == null) {
1846
+ return 1;
1847
+ }
1848
+ if (offerToCheck.reward_points.once_per_order) {
1849
+ return 1;
1850
+ }
1851
+ const normalizedUnlockableClaims = Math.max(0, pathwayUnlockableClaims);
1852
+ if (normalizedUnlockableClaims === 0) {
1853
+ return 0;
1854
+ }
1855
+ // The incoming claim count is already clamped to the customer's
1856
+ // remaining lifetime budget (max_uses_per_customer − effectiveUsed, via
1857
+ // clampClaimsToRemainingClaimBudget at the call site); the reward's own
1858
+ // max_claims governs the ongoing session only.
1859
+ return normalizedUnlockableClaims;
1860
+ };
1861
+ const getPathwayMaxRedeemableClaims = (pathwayUnlockableClaims) => {
1862
+ const normalizedUnlockableClaims = Math.max(0, pathwayUnlockableClaims);
1863
+ if (normalizedUnlockableClaims === 0) {
1864
+ return 0;
1865
+ }
1866
+ // Same as getPointsMaxRedeemableClaims: the incoming claim count is
1867
+ // already clamped to the customer's remaining lifetime budget at the
1868
+ // call site.
1869
+ return normalizedUnlockableClaims;
1870
+ };
1871
+ const isDiscountSlotOccupiedForOffer = (offerToCheck) => {
1872
+ if (order_discount_details == null) {
1873
+ return false;
1874
+ }
1875
+ if (offerToCheck.pathway_to_unlock_type === PATHWAY_TO_UNLOCK_TYPE_ENUM.VOUCHER) {
1876
+ return Boolean(order_discount_details.voucher_discount_id);
1877
+ }
1878
+ return Boolean(order_discount_details.loyalty_discount_id);
1879
+ };
1880
+ const applyItemRewardClaimableFallback = ({ offerToCheck, stats }) => {
1881
+ const isItemRewardType = offerToCheck.reward_type === OFFER_REWARD_TYPE_ENUM.ITEMS ||
1882
+ offerToCheck.reward_type === OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS;
1883
+ if (!isItemRewardType)
1884
+ return;
1885
+ if (stats.invalid_offer || stats.claimable)
1886
+ return;
1887
+ if (stats.progress < 100 || stats.redeemed_times > 0)
1888
+ return;
1889
+ const normalizedMessage = (stats.message ?? '').toLowerCase();
1890
+ if (!normalizedMessage.includes('redeemed')) {
1891
+ return;
1892
+ }
1893
+ const fallbackApplicableQuantity = offerToCheck.reward_type === OFFER_REWARD_TYPE_ENUM.ITEMS
1894
+ ? Math.max(1, offerToCheck.reward_items?.num_of_items ?? 1)
1895
+ : Math.max(1, offerToCheck.reward_discount_items?.num_of_items ?? 1);
1896
+ stats.claimable = true;
1897
+ stats.applicable_quantity = Math.max(stats.applicable_quantity, fallbackApplicableQuantity);
1898
+ stats.message = `🎉 You have unlocked this offer 🎉`;
1899
+ unlockedOffersApplicableTimes[offerToCheck._id] = stats.applicable_quantity;
1900
+ if (!totalClaimableOffers.includes(offerToCheck._id)) {
1901
+ totalClaimableOffers.push(offerToCheck._id);
1902
+ }
1903
+ };
1904
+ const applyVoucherPathwayCartContextBlock = ({ offerToCheck, statsToUpdate, }) => {
1905
+ if (!isVoucherPathwayOfferBlockedByCartContext({
1906
+ offer: offerToCheck,
1907
+ cartContext: voucherPathwayCartContext,
1908
+ })) {
1909
+ return;
1910
+ }
1911
+ if (!statsToUpdate.claimable && statsToUpdate.applicable_quantity <= 0 && statsToUpdate.progress < 100) {
1912
+ return;
1913
+ }
1914
+ totalClaimableOffers = totalClaimableOffers.filter((id) => id !== offerToCheck._id);
1915
+ statsToUpdate.claimable = false;
1916
+ statsToUpdate.applicable_quantity = 0;
1917
+ unlockedOffersApplicableTimes[offerToCheck._id] = 0;
1918
+ statsToUpdate.message =
1919
+ voucherPathwayCartContext.activeVoucherCode != null
1920
+ ? `You already selected a reward for voucher ${voucherPathwayCartContext.activeVoucherCode}.`
1921
+ : 'You already selected a voucher reward for this order.';
1922
+ };
1923
+ for (let i = 0; i < offers.length; i++) {
1924
+ const offer = offers[i];
1925
+ const stats = {
1926
+ progress: 0,
1927
+ message: '',
1928
+ invalid_offer: false,
1929
+ redeemed_times: 0,
1930
+ claimable: false,
1931
+ applicable_quantity: 0,
1932
+ eligible_item_ids: getEligibleItemIds(offer),
1933
+ eligible_category_ids: getEligibleCategoryIds(offer),
1934
+ reward_preview: buildRewardPreview(offer),
1935
+ action_hint: null,
1936
+ auto_apply: offer.auto_apply ?? false,
1937
+ };
1938
+ if (offer.pathway_to_unlock_type === PATHWAY_TO_UNLOCK_TYPE_ENUM.ORDERS) {
1939
+ if (offer.pathway_to_unlock_type_orders == null) {
1940
+ stats.invalid_offer = true;
1941
+ stats.message = `Offer pathway to unlock type orders is empty`;
1942
+ offersWithStats.push({ offer, stats });
1943
+ continue;
1944
+ }
1945
+ const orderValue = getOfferQualifyingOrderValue({
1946
+ offer,
1947
+ categories,
1948
+ orderLevelDiscountBaseAmount,
1949
+ orderLevelDiscountAmount,
1950
+ orderDiscountDetails: order_discount_details,
1951
+ });
1952
+ // Need to check if offer is unlocked
1953
+ const { scope = PATHWAY_TO_UNLOCK_TYPE_ORDERS_SCOPE_ENUM.OVERALL, min_num_of_orders, max_num_of_orders, total_amount, max_amount, orders_between_unlocks, } = offer.pathway_to_unlock_type_orders;
1954
+ const scopedStats = getOrdersScopedStats({
1955
+ scope,
1956
+ currentOrderValue: orderValue,
1957
+ });
1958
+ if (!scopedStats.valid) {
1959
+ stats.progress = 0;
1960
+ stats.claimable = false;
1961
+ stats.invalid_offer = true;
1962
+ stats.message = `⛔️ This offer requires platform context ⛔️`;
1963
+ offersWithStats.push({
1964
+ offer,
1965
+ stats,
1966
+ });
1967
+ continue;
1968
+ }
1969
+ const { totalOrders, totalAmount } = scopedStats;
1970
+ // Raw requirements: a zero minimum is already satisfied, so it must not
1971
+ // drag `Math.min(ordersProgress, amountProgress)` down to 0%.
1972
+ const ordersProgress = getPreUnlockProgressPercentage(totalOrders, min_num_of_orders);
1973
+ const amountProgress = getPreUnlockProgressPercentage(totalAmount, total_amount);
1974
+ const combinedProgress = Math.min(ordersProgress, amountProgress);
1975
+ const ordersBetweenUnlocksStats = getOrdersBetweenUnlocksStats({
1976
+ totalOrders,
1977
+ ordersBetweenUnlocks: orders_between_unlocks,
1978
+ });
1979
+ if (totalOrders >= min_num_of_orders) {
1980
+ // Either the max_num_of_orders is infinity, or the customer has not reached the max_num_of_orders
1981
+ if ((max_num_of_orders == null || totalOrders <= max_num_of_orders) &&
1982
+ (max_amount == null || totalAmount <= max_amount)) {
1983
+ if (totalAmount >= total_amount) {
1984
+ if (ordersBetweenUnlocksStats.isUnlockOrder) {
1985
+ stats.progress = 100;
1986
+ stats.claimable = false;
1987
+ stats.message = `🎉 You have unlocked this offer 🎉`;
1988
+ stats.applicable_quantity = 1;
1989
+ }
1990
+ else {
1991
+ stats.progress = Math.min(combinedProgress, ordersBetweenUnlocksStats.progress);
1992
+ stats.message = `You are ${ordersBetweenUnlocksStats.ordersAwayFromNextUnlock} orders away from unlocking this offer`;
1993
+ }
1994
+ }
1995
+ else {
1996
+ // This means that the customer has not spent enough to unlock the offer
1997
+ // But they have enough orders to unlock the offer
1998
+ stats.progress = combinedProgress;
1999
+ stats.message = `Spend ${currency_symbol}${parseNum(total_amount - totalAmount)} more to unlock this offer 🔓`;
2000
+ }
2001
+ }
2002
+ else {
2003
+ // This means that the customer has reached the max_num_of_orders
2004
+ stats.progress = 0;
2005
+ stats.message = `⛔️ You are not eligible for this offer ⛔️`;
2006
+ }
2007
+ }
2008
+ else {
2009
+ stats.progress = combinedProgress;
2010
+ stats.message = `You are ${min_num_of_orders - totalOrders} orders away from unlocking this offer`;
2011
+ }
2012
+ if (stats.progress >= 100) {
2013
+ if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.DISCOUNT) {
2014
+ if (offer.reward_discount == null)
2015
+ continue;
2016
+ // Check if at least one item is eligible for the discount (not in excluded_refs)
2017
+ const excluded_refs = offer.reward_discount.excluded_refs ?? [];
2018
+ if (excluded_refs.length > 0 && !hasEligibleItemsForDiscount(categories, excluded_refs)) {
2019
+ // All items are excluded, offer cannot be unlocked
2020
+ stats.progress = 0;
2021
+ stats.claimable = false;
2022
+ stats.message = `⛔️ No eligible items for this offer ⛔️`;
2023
+ offersWithStats.push({ offer, stats });
2024
+ continue;
2025
+ }
2026
+ const redeemedTimes = getOfferRedeemedTimes(offer._id);
2027
+ const isRedeemed = redeemedTimes > 0;
2028
+ const discountSlotOccupied = isDiscountSlotOccupiedForOffer(offer);
2029
+ stats.claimable = !isRedeemed && !discountSlotOccupied;
2030
+ stats.applicable_quantity = 1;
2031
+ stats.redeemed_times = redeemedTimes;
2032
+ if (isRedeemed) {
2033
+ stats.message = 'This offer is redeemed ✅';
2034
+ }
2035
+ else if (discountSlotOccupied) {
2036
+ stats.message = 'You already have an offer applied to your order.';
2037
+ }
2038
+ else {
2039
+ totalClaimableOffers.push(offer._id);
2040
+ stats.message = `🎉 You have unlocked this offer 🎉`;
2041
+ }
2042
+ unlockedOffersApplicableTimes[offer._id] = stats.applicable_quantity;
2043
+ }
2044
+ else if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS) {
2045
+ if (offer.reward_discount_items == null)
2046
+ continue;
2047
+ // Check if at least one item is eligible for the discount (not in excluded_refs)
2048
+ const excluded_refs = offer.reward_discount_items.excluded_refs ?? [];
2049
+ if (excluded_refs.length > 0 && !hasEligibleItemsForDiscount(categories, excluded_refs)) {
2050
+ // All items are excluded, offer cannot be unlocked
2051
+ stats.progress = 0;
2052
+ stats.claimable = false;
2053
+ stats.message = `⛔️ No eligible items for this offer ⛔️`;
2054
+ offersWithStats.push({ offer, stats });
2055
+ continue;
2056
+ }
2057
+ const applicableQuantity = offer.reward_discount_items.num_of_items || 1;
2058
+ const totalOfferItemsSelected = getTotalSelectedOfferItemsAgainstOffer(categories, offer._id);
2059
+ const redeemedTimes = getItemRewardRedeemedTimes({
2060
+ totalOfferItemsSelected,
2061
+ applicableQuantity,
2062
+ });
2063
+ const maxClaimsPerOrder = offer.pathway_to_unlock_type_orders?.max_claims == null
2064
+ ? Infinity
2065
+ : Math.max(1, offer.pathway_to_unlock_type_orders.max_claims);
2066
+ const unlockTimesForAmount = getOrderValueClaimTimes(orderValue, offer.pathway_to_unlock_type_orders?.total_amount);
2067
+ const totalUnlockableClaims = clampClaimsToRemainingClaimBudget(offer, Math.min(unlockTimesForAmount, maxClaimsPerOrder));
2068
+ const discountSlotOccupied = isDiscountSlotOccupiedForOffer(offer);
2069
+ const isClaimable = redeemedTimes < totalUnlockableClaims && !discountSlotOccupied;
2070
+ stats.redeemed_times = redeemedTimes;
2071
+ stats.applicable_quantity = applicableQuantity * Math.max(1, totalUnlockableClaims);
2072
+ if (isClaimable) {
2073
+ totalClaimableOffers.push(offer._id);
2074
+ stats.claimable = true;
2075
+ stats.message = `🎉 You have unlocked this offer 🎉`;
2076
+ }
2077
+ else {
2078
+ stats.claimable = false;
2079
+ stats.message =
2080
+ redeemedTimes >= totalUnlockableClaims
2081
+ ? `This offer is redeemed ✅`
2082
+ : discountSlotOccupied
2083
+ ? 'You already have an offer applied to your order.'
2084
+ : `🎉 You have unlocked this offer 🎉`;
2085
+ }
2086
+ unlockedOffersApplicableTimes[offer._id] = stats.applicable_quantity;
2087
+ }
2088
+ else if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.POINTS) {
2089
+ if (offer.reward_points == null)
2090
+ continue;
2091
+ const redeemedTimes = getOfferRedeemedTimes(offer._id);
2092
+ const maxClaimsPerOrder = offer.pathway_to_unlock_type_orders?.max_claims == null
2093
+ ? Infinity
2094
+ : Math.max(1, offer.pathway_to_unlock_type_orders.max_claims);
2095
+ const unlockTimesForAmount = getOrderValueClaimTimes(orderValue, offer.pathway_to_unlock_type_orders?.total_amount);
2096
+ const totalUnlockableClaims = clampClaimsToRemainingClaimBudget(offer, Math.min(unlockTimesForAmount, maxClaimsPerOrder));
2097
+ const maxRedeemableClaims = getPointsMaxRedeemableClaims({
2098
+ offerToCheck: offer,
2099
+ pathwayUnlockableClaims: totalUnlockableClaims,
2100
+ });
2101
+ const isClaimable = redeemedTimes < maxRedeemableClaims;
2102
+ stats.redeemed_times = redeemedTimes;
2103
+ stats.applicable_quantity = maxRedeemableClaims;
2104
+ stats.claimable = isClaimable;
2105
+ if (!isClaimable) {
2106
+ stats.message = 'This offer is redeemed ✅';
2107
+ }
2108
+ else {
2109
+ stats.message = `🎉 You have unlocked this offer 🎉`;
2110
+ totalClaimableOffers.push(offer._id);
2111
+ }
2112
+ unlockedOffersApplicableTimes[offer._id] = stats.applicable_quantity;
2113
+ }
2114
+ else if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.VOUCHER) {
2115
+ if (offer.reward_voucher == null)
2116
+ continue;
2117
+ const { rewardVoucherUnavailable, rewardVoucherLimitExhausted } = getRewardVoucherAvailability(Object.keys(offer.reward_voucher.voucher_ids));
2118
+ const redeemedTimes = getOfferRedeemedTimes(offer._id);
2119
+ const isRedeemed = redeemedTimes > 0;
2120
+ stats.redeemed_times = redeemedTimes;
2121
+ stats.applicable_quantity = 1;
2122
+ if (rewardVoucherUnavailable) {
2123
+ stats.claimable = false;
2124
+ stats.message = '⛔️ This reward is no longer available ⛔️';
2125
+ }
2126
+ else if (rewardVoucherLimitExhausted) {
2127
+ stats.claimable = false;
2128
+ stats.message = '⛔️ You have reached your personal limit for this reward ⛔️';
2129
+ }
2130
+ else if (isRedeemed) {
2131
+ stats.claimable = false;
2132
+ stats.message = 'This offer is redeemed ✅';
2133
+ }
2134
+ else {
2135
+ stats.claimable = true;
2136
+ stats.message = `🎉 You have unlocked this offer 🎉`;
2137
+ totalClaimableOffers.push(offer._id);
2138
+ }
2139
+ unlockedOffersApplicableTimes[offer._id] = stats.applicable_quantity;
2140
+ }
2141
+ else if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.CASHBACK) {
2142
+ if (offer.reward_cashback == null)
2143
+ continue;
2144
+ const rewardExcludedRefs = offer.reward_cashback.excluded_refs ?? [];
2145
+ if (rewardExcludedRefs.length > 0 && !hasEligibleItemsForDiscount(categories, rewardExcludedRefs)) {
2146
+ stats.progress = 0;
2147
+ stats.claimable = false;
2148
+ stats.message = `⛔️ No eligible items for this offer ⛔️`;
2149
+ offersWithStats.push({ offer, stats });
2150
+ continue;
2151
+ }
2152
+ const redeemedTimes = getOfferRedeemedTimes(offer._id);
2153
+ if (offer.reward_cashback.is_cashback_percentage === true) {
2154
+ // Percentage cashback scales with the order total and is claimed
2155
+ // once per order; total_amount / max_claims do not apply.
2156
+ const isRedeemed = redeemedTimes > 0;
2157
+ stats.redeemed_times = redeemedTimes;
2158
+ stats.applicable_quantity = 1;
2159
+ stats.claimable = !isRedeemed;
2160
+ if (isRedeemed) {
2161
+ stats.message = 'This offer is redeemed ✅';
2162
+ }
2163
+ else {
2164
+ stats.message = `🎉 You have unlocked this offer 🎉`;
2165
+ totalClaimableOffers.push(offer._id);
2166
+ }
2167
+ }
2168
+ else {
2169
+ // Flat cashback repeats per qualifying spend chunk
2170
+ // (every total_amount unlocks one claim), capped by max_claims.
2171
+ const maxClaimsPerOrder = offer.pathway_to_unlock_type_orders?.max_claims == null
2172
+ ? Infinity
2173
+ : Math.max(1, offer.pathway_to_unlock_type_orders.max_claims);
2174
+ const unlockTimesForAmount = getOrderValueClaimTimes(orderValue, offer.pathway_to_unlock_type_orders?.total_amount);
2175
+ const totalUnlockableClaims = clampClaimsToRemainingClaimBudget(offer, Math.min(unlockTimesForAmount, maxClaimsPerOrder));
2176
+ const maxRedeemableClaims = getPathwayMaxRedeemableClaims(totalUnlockableClaims);
2177
+ const isClaimable = redeemedTimes < maxRedeemableClaims;
2178
+ stats.redeemed_times = redeemedTimes;
2179
+ stats.applicable_quantity = maxRedeemableClaims;
2180
+ stats.claimable = isClaimable;
2181
+ if (!isClaimable) {
2182
+ stats.message = 'This offer is redeemed ✅';
2183
+ }
2184
+ else {
2185
+ stats.message = `🎉 You have unlocked this offer 🎉`;
2186
+ totalClaimableOffers.push(offer._id);
2187
+ }
2188
+ }
2189
+ unlockedOffersApplicableTimes[offer._id] = stats.applicable_quantity;
2190
+ }
2191
+ else if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.GIFT_CARDS) {
2192
+ if (offer.reward_gift_cards == null)
2193
+ continue;
2194
+ const { rewardGiftCardUnavailable, rewardGiftCardLimitExhausted } = getRewardGiftCardAvailability(Object.keys(offer.reward_gift_cards.gift_card_ids));
2195
+ const redeemedTimes = getOfferRedeemedTimes(offer._id);
2196
+ const isRedeemed = redeemedTimes > 0;
2197
+ stats.redeemed_times = redeemedTimes;
2198
+ stats.applicable_quantity = 1;
2199
+ if (rewardGiftCardUnavailable) {
2200
+ stats.claimable = false;
2201
+ stats.message = '⛔️ This reward is no longer available ⛔️';
2202
+ }
2203
+ else if (rewardGiftCardLimitExhausted) {
2204
+ stats.claimable = false;
2205
+ stats.message = '⛔️ You have reached your personal limit for this reward ⛔️';
2206
+ }
2207
+ else if (isRedeemed) {
2208
+ stats.claimable = false;
2209
+ stats.message = 'This offer is redeemed ✅';
2210
+ }
2211
+ else {
2212
+ stats.claimable = true;
2213
+ stats.message = `🎉 You have unlocked this offer 🎉`;
2214
+ totalClaimableOffers.push(offer._id);
2215
+ }
2216
+ unlockedOffersApplicableTimes[offer._id] = stats.applicable_quantity;
2217
+ }
2218
+ else if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.ITEMS) {
2219
+ if (offer.reward_items == null)
2220
+ continue;
2221
+ const applicableQuantity = offer.reward_items.num_of_items || 1;
2222
+ const totalOfferItemsSelected = getTotalSelectedOfferItemsAgainstOffer(categories, offer._id);
2223
+ const redeemedTimes = getItemRewardRedeemedTimes({
2224
+ totalOfferItemsSelected,
2225
+ applicableQuantity,
2226
+ });
2227
+ const maxClaimsPerOrder = offer.pathway_to_unlock_type_orders?.max_claims == null
2228
+ ? Infinity
2229
+ : Math.max(1, offer.pathway_to_unlock_type_orders.max_claims);
2230
+ const unlockTimesForAmount = getOrderValueClaimTimes(orderValue, offer.pathway_to_unlock_type_orders?.total_amount);
2231
+ const totalUnlockableClaims = clampClaimsToRemainingClaimBudget(offer, Math.min(unlockTimesForAmount, maxClaimsPerOrder));
2232
+ const isClaimable = redeemedTimes < totalUnlockableClaims;
2233
+ stats.redeemed_times = redeemedTimes;
2234
+ stats.applicable_quantity = applicableQuantity * Math.max(1, totalUnlockableClaims);
2235
+ if (isClaimable) {
2236
+ totalClaimableOffers.push(offer._id);
2237
+ stats.claimable = true;
2238
+ stats.message = `🎉 You have unlocked this offer 🎉`;
2239
+ }
2240
+ else {
2241
+ stats.claimable = false;
2242
+ stats.message = `This offer is redeemed ✅`;
2243
+ }
2244
+ unlockedOffersApplicableTimes[offer._id] = stats.applicable_quantity;
2245
+ }
2246
+ }
2247
+ applyItemRewardClaimableFallback({
2248
+ offerToCheck: offer,
2249
+ stats,
2250
+ });
2251
+ if (stats.progress >= 100 && isOfferUsesPerCustomerExhausted(offer)) {
2252
+ if (stats.claimable) {
2253
+ totalClaimableOffers = totalClaimableOffers.filter((id) => id !== offer._id);
2254
+ }
2255
+ stats.applicable_quantity = 0;
2256
+ unlockedOffersApplicableTimes[offer._id] = 0;
2257
+ stats.claimable = false;
2258
+ stats.message = '⛔️ You have reached your personal limit for this offer ⛔️';
2259
+ }
2260
+ clearBlockedRewardApplicableQuantity(offer, stats);
2261
+ stats.action_hint = getActionHint(offer, stats.claimable);
2262
+ offersWithStats.push({
2263
+ offer,
2264
+ stats,
2265
+ });
2266
+ }
2267
+ else if (offer.pathway_to_unlock_type === PATHWAY_TO_UNLOCK_TYPE_ENUM.ITEMS) {
2268
+ if (offer.pathway_to_unlock_type_items == null) {
2269
+ stats.invalid_offer = true;
2270
+ stats.message = `Offer pathway to unlock type items is empty`;
2271
+ offersWithStats.push({ offer, stats });
2272
+ continue;
2273
+ }
2274
+ const orderValue = getOfferQualifyingOrderValue({
2275
+ offer,
2276
+ categories,
2277
+ orderLevelDiscountBaseAmount,
2278
+ orderLevelDiscountAmount,
2279
+ orderDiscountDetails: order_discount_details,
2280
+ });
2281
+ const { num_of_items, max_claims, min_same_item_quantity, max_same_item_quantity, total_amount, excluded_refs, exclusive_refs, item_ids, category_ids, } = offer.pathway_to_unlock_type_items;
2282
+ const bachelorItems = getCartItemsApplicableToOfferItemsQuantity({
2283
+ categories,
2284
+ excluded_refs,
2285
+ exclusive_refs,
2286
+ item_ids,
2287
+ category_ids,
2288
+ min_same_item_quantity,
2289
+ max_same_item_quantity,
2290
+ });
2291
+ const totalOfferItemsSelected = getTotalSelectedOfferItemsAgainstOffer(categories, offer._id);
2292
+ const totalItemsSelected = totalOfferItemsSelected + bachelorItems;
2293
+ const maxClaimsPerOrder = max_claims == null ? Infinity : Math.max(1, max_claims);
2294
+ const unlockTimesForItems = Math.floor(totalItemsSelected / (num_of_items || 1));
2295
+ const unlockTimesForAmount = total_amount != null && total_amount > 0 ? Math.floor(orderValue / total_amount) : unlockTimesForItems;
2296
+ const totalUnlockableClaims = clampClaimsToRemainingClaimBudget(offer, Math.min(unlockTimesForItems, unlockTimesForAmount, maxClaimsPerOrder));
2297
+ const itemsProgress = getPreUnlockProgressPercentage(bachelorItems, num_of_items);
2298
+ const amountProgress = getPreUnlockProgressPercentage(orderValue, total_amount);
2299
+ const combinedProgress = Math.min(itemsProgress, amountProgress);
2300
+ if (totalItemsSelected >= num_of_items) {
2301
+ if (orderValue >= total_amount) {
2302
+ if (bachelorItems >= num_of_items) {
2303
+ stats.progress = 100;
2304
+ stats.message = `🎉 You have unlocked this offer 🎉`;
2305
+ }
2306
+ else {
2307
+ stats.progress = combinedProgress;
2308
+ stats.message = `You are ${num_of_items - bachelorItems} items away from unlocking this offer`;
2309
+ }
2310
+ }
2311
+ else {
2312
+ stats.progress = combinedProgress;
2313
+ stats.message = `Spend ${currency_symbol}${parseNum(total_amount - orderValue)} more in this order to unlock this offer 🔓`;
2314
+ }
2315
+ }
2316
+ else {
2317
+ stats.progress = combinedProgress;
2318
+ stats.message = `You are ${num_of_items - bachelorItems} items away from unlocking this offer`;
2319
+ }
2320
+ if (stats.progress >= 100) {
2321
+ if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.DISCOUNT) {
2322
+ if (offer.reward_discount == null)
2323
+ continue;
2324
+ const rewardExcludedRefs = offer.reward_discount.excluded_refs ?? [];
2325
+ if (rewardExcludedRefs.length > 0 && !hasEligibleItemsForDiscount(categories, rewardExcludedRefs)) {
2326
+ stats.progress = 0;
2327
+ stats.claimable = false;
2328
+ stats.message = `⛔️ No eligible items for this offer ⛔️`;
2329
+ offersWithStats.push({ offer, stats });
2330
+ continue;
2331
+ }
2332
+ const redeemedTimes = getOfferRedeemedTimes(offer._id);
2333
+ const isRedeemed = redeemedTimes > 0;
2334
+ const discountSlotOccupied = isDiscountSlotOccupiedForOffer(offer);
2335
+ stats.redeemed_times = redeemedTimes;
2336
+ stats.applicable_quantity = 1;
2337
+ stats.claimable = !isRedeemed && !discountSlotOccupied;
2338
+ if (isRedeemed) {
2339
+ stats.message = 'This offer is redeemed ✅';
2340
+ }
2341
+ else if (discountSlotOccupied) {
2342
+ stats.message = 'You already have an offer applied to your order.';
2343
+ }
2344
+ else {
2345
+ totalClaimableOffers.push(offer._id);
2346
+ stats.message = `🎉 You have unlocked this offer 🎉`;
2347
+ }
2348
+ unlockedOffersApplicableTimes[offer._id] = stats.applicable_quantity;
2349
+ }
2350
+ else if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS) {
2351
+ if (offer.reward_discount_items == null)
2352
+ continue;
2353
+ const rewardExcludedRefs = offer.reward_discount_items.excluded_refs ?? [];
2354
+ if (rewardExcludedRefs.length > 0 && !hasEligibleItemsForDiscount(categories, rewardExcludedRefs)) {
2355
+ stats.progress = 0;
2356
+ stats.claimable = false;
2357
+ stats.message = `⛔️ No eligible items for this offer ⛔️`;
2358
+ offersWithStats.push({ offer, stats });
2359
+ continue;
2360
+ }
2361
+ const applicableQuantity = offer.reward_discount_items.num_of_items || 1;
2362
+ const redeemedTimes = getItemRewardRedeemedTimes({
2363
+ totalOfferItemsSelected,
2364
+ applicableQuantity,
2365
+ });
2366
+ const discountSlotOccupied = isDiscountSlotOccupiedForOffer(offer);
2367
+ const isClaimable = redeemedTimes < totalUnlockableClaims && !discountSlotOccupied;
2368
+ stats.redeemed_times = redeemedTimes;
2369
+ stats.applicable_quantity = applicableQuantity * Math.max(1, totalUnlockableClaims);
2370
+ stats.claimable = isClaimable;
2371
+ if (isClaimable) {
2372
+ totalClaimableOffers.push(offer._id);
2373
+ stats.message = `🎉 You have unlocked this offer 🎉`;
2374
+ }
2375
+ else {
2376
+ stats.message =
2377
+ redeemedTimes >= totalUnlockableClaims
2378
+ ? `This offer is redeemed ✅`
2379
+ : discountSlotOccupied
2380
+ ? 'You already have an offer applied to your order.'
2381
+ : `🎉 You have unlocked this offer 🎉`;
2382
+ }
2383
+ unlockedOffersApplicableTimes[offer._id] = stats.applicable_quantity;
2384
+ }
2385
+ else if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.POINTS) {
2386
+ if (offer.reward_points == null)
2387
+ continue;
2388
+ const redeemedTimes = getOfferRedeemedTimes(offer._id);
2389
+ const maxRedeemableClaims = getPointsMaxRedeemableClaims({
2390
+ offerToCheck: offer,
2391
+ pathwayUnlockableClaims: totalUnlockableClaims,
2392
+ });
2393
+ const isClaimable = redeemedTimes < maxRedeemableClaims;
2394
+ stats.redeemed_times = redeemedTimes;
2395
+ stats.applicable_quantity = maxRedeemableClaims;
2396
+ stats.claimable = isClaimable;
2397
+ if (!isClaimable) {
2398
+ stats.message = 'This offer is redeemed ✅';
2399
+ }
2400
+ else {
2401
+ totalClaimableOffers.push(offer._id);
2402
+ stats.message = `🎉 You have unlocked this offer 🎉`;
2403
+ }
2404
+ unlockedOffersApplicableTimes[offer._id] = stats.applicable_quantity;
2405
+ }
2406
+ else if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.VOUCHER) {
2407
+ if (offer.reward_voucher == null)
2408
+ continue;
2409
+ const { rewardVoucherUnavailable, rewardVoucherLimitExhausted } = getRewardVoucherAvailability(Object.keys(offer.reward_voucher.voucher_ids));
2410
+ const redeemedTimes = getOfferRedeemedTimes(offer._id);
2411
+ const isRedeemed = redeemedTimes > 0;
2412
+ stats.redeemed_times = redeemedTimes;
2413
+ stats.applicable_quantity = 1;
2414
+ stats.claimable = !isRedeemed && !rewardVoucherUnavailable && !rewardVoucherLimitExhausted;
2415
+ if (rewardVoucherUnavailable) {
2416
+ stats.message = '⛔️ This reward is no longer available ⛔️';
2417
+ }
2418
+ else if (rewardVoucherLimitExhausted) {
2419
+ stats.message = '⛔️ You have reached your personal limit for this reward ⛔️';
2420
+ }
2421
+ else if (isRedeemed) {
2422
+ stats.message = 'This offer is redeemed ✅';
2423
+ }
2424
+ else {
2425
+ totalClaimableOffers.push(offer._id);
2426
+ stats.message = `🎉 You have unlocked this offer 🎉`;
2427
+ }
2428
+ unlockedOffersApplicableTimes[offer._id] = stats.applicable_quantity;
2429
+ }
2430
+ else if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.CASHBACK) {
2431
+ if (offer.reward_cashback == null)
2432
+ continue;
2433
+ const rewardExcludedRefs = offer.reward_cashback.excluded_refs ?? [];
2434
+ if (rewardExcludedRefs.length > 0 && !hasEligibleItemsForDiscount(categories, rewardExcludedRefs)) {
2435
+ stats.progress = 0;
2436
+ stats.claimable = false;
2437
+ stats.message = `⛔️ No eligible items for this offer ⛔️`;
2438
+ offersWithStats.push({ offer, stats });
2439
+ continue;
2440
+ }
2441
+ const redeemedTimes = getOfferRedeemedTimes(offer._id);
2442
+ if (offer.reward_cashback.is_cashback_percentage === true) {
2443
+ // Percentage cashback scales with the order total and is claimed
2444
+ // once per order; total_amount / max_claims do not apply.
2445
+ const isRedeemed = redeemedTimes > 0;
2446
+ stats.redeemed_times = redeemedTimes;
2447
+ stats.applicable_quantity = 1;
2448
+ stats.claimable = !isRedeemed;
2449
+ if (isRedeemed) {
2450
+ stats.message = 'This offer is redeemed ✅';
2451
+ }
2452
+ else {
2453
+ totalClaimableOffers.push(offer._id);
2454
+ stats.message = `🎉 You have unlocked this offer 🎉`;
2455
+ }
2456
+ }
2457
+ else {
2458
+ // Flat cashback repeats per qualifying spend chunk
2459
+ // (every total_amount unlocks one claim), capped by max_claims.
2460
+ const maxRedeemableClaims = getPathwayMaxRedeemableClaims(totalUnlockableClaims);
2461
+ const isClaimable = redeemedTimes < maxRedeemableClaims;
2462
+ stats.redeemed_times = redeemedTimes;
2463
+ stats.applicable_quantity = maxRedeemableClaims;
2464
+ stats.claimable = isClaimable;
2465
+ if (!isClaimable) {
2466
+ stats.message = 'This offer is redeemed ✅';
2467
+ }
2468
+ else {
2469
+ totalClaimableOffers.push(offer._id);
2470
+ stats.message = `🎉 You have unlocked this offer 🎉`;
2471
+ }
2472
+ }
2473
+ unlockedOffersApplicableTimes[offer._id] = stats.applicable_quantity;
2474
+ }
2475
+ else if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.GIFT_CARDS) {
2476
+ if (offer.reward_gift_cards == null)
2477
+ continue;
2478
+ const { rewardGiftCardUnavailable, rewardGiftCardLimitExhausted } = getRewardGiftCardAvailability(Object.keys(offer.reward_gift_cards.gift_card_ids));
2479
+ const redeemedTimes = getOfferRedeemedTimes(offer._id);
2480
+ const isRedeemed = redeemedTimes > 0;
2481
+ stats.redeemed_times = redeemedTimes;
2482
+ stats.applicable_quantity = 1;
2483
+ stats.claimable = !isRedeemed && !rewardGiftCardUnavailable && !rewardGiftCardLimitExhausted;
2484
+ if (rewardGiftCardUnavailable) {
2485
+ stats.message = '⛔️ This reward is no longer available ⛔️';
2486
+ }
2487
+ else if (rewardGiftCardLimitExhausted) {
2488
+ stats.message = '⛔️ You have reached your personal limit for this reward ⛔️';
2489
+ }
2490
+ else if (isRedeemed) {
2491
+ stats.message = 'This offer is redeemed ✅';
2492
+ }
2493
+ else {
2494
+ totalClaimableOffers.push(offer._id);
2495
+ stats.message = `🎉 You have unlocked this offer 🎉`;
2496
+ }
2497
+ unlockedOffersApplicableTimes[offer._id] = stats.applicable_quantity;
2498
+ }
2499
+ else if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.ITEMS) {
2500
+ if (offer.reward_items == null)
2501
+ continue;
2502
+ const applicableQuantity = offer.reward_items.num_of_items || 1;
2503
+ const redeemedTimes = getItemRewardRedeemedTimes({
2504
+ totalOfferItemsSelected,
2505
+ applicableQuantity,
2506
+ });
2507
+ const isClaimable = redeemedTimes < totalUnlockableClaims;
2508
+ stats.redeemed_times = redeemedTimes;
2509
+ stats.applicable_quantity = applicableQuantity * Math.max(1, totalUnlockableClaims);
2510
+ stats.claimable = isClaimable;
2511
+ if (isClaimable) {
2512
+ totalClaimableOffers.push(offer._id);
2513
+ stats.message = `🎉 You have unlocked this offer 🎉`;
2514
+ }
2515
+ else {
2516
+ stats.message = `This offer is redeemed ✅`;
2517
+ }
2518
+ unlockedOffersApplicableTimes[offer._id] = stats.applicable_quantity;
2519
+ }
2520
+ }
2521
+ applyItemRewardClaimableFallback({
2522
+ offerToCheck: offer,
2523
+ stats,
2524
+ });
2525
+ if (stats.progress >= 100 && isOfferUsesPerCustomerExhausted(offer)) {
2526
+ if (stats.claimable) {
2527
+ totalClaimableOffers = totalClaimableOffers.filter((id) => id !== offer._id);
2528
+ }
2529
+ stats.applicable_quantity = 0;
2530
+ unlockedOffersApplicableTimes[offer._id] = 0;
2531
+ stats.claimable = false;
2532
+ stats.message = '⛔️ You have reached your personal limit for this offer ⛔️';
2533
+ }
2534
+ clearBlockedRewardApplicableQuantity(offer, stats);
2535
+ stats.action_hint = getActionHint(offer, stats.claimable);
2536
+ offersWithStats.push({
2537
+ offer,
2538
+ stats,
2539
+ });
2540
+ }
2541
+ else if (offer.pathway_to_unlock_type === PATHWAY_TO_UNLOCK_TYPE_ENUM.POINTS) {
2542
+ if (offer.pathway_to_unlock_type_points == null) {
2543
+ stats.invalid_offer = true;
2544
+ stats.message = `Offer pathway to unlock type points is empty`;
2545
+ offersWithStats.push({ offer, stats });
2546
+ continue;
2547
+ }
2548
+ const orderValue = getOfferQualifyingOrderValue({
2549
+ offer,
2550
+ categories,
2551
+ orderLevelDiscountBaseAmount,
2552
+ orderLevelDiscountAmount,
2553
+ orderDiscountDetails: order_discount_details,
2554
+ });
2555
+ const { num_of_points, total_amount, max_claims } = offer.pathway_to_unlock_type_points;
2556
+ const maxClaimsPerOrder = max_claims == null ? Infinity : Math.max(1, max_claims);
2557
+ if (totalLoyaltyPointsOfCustomer == null) {
2558
+ const { loyaltyPoints } = calculateCustomerLoyaltyPoints({
2559
+ customerLoyaltyPoints: customer?.loyalty_points,
2560
+ orderDiscountDetails: order_discount_details,
2561
+ redeemedOffers: redeemed_offers,
2562
+ currentItemsPrice,
2563
+ categories,
2564
+ totalDiscountApplied,
2565
+ offers,
2566
+ includePendingRewardPoints: false,
2567
+ });
2568
+ totalLoyaltyPointsOfCustomer = loyaltyPoints;
2569
+ }
2570
+ const orderLevelClaimSignal = order_discount_details?.loyalty_discount_id === offer._id ? 1 : 0;
2571
+ const redeemedTimesForCurrentOffer = Math.max(getOfferRedeemedTimes(offer._id), orderLevelClaimSignal);
2572
+ const effectiveLoyaltyPointsForCurrentOffer = (totalLoyaltyPointsOfCustomer ?? 0) + redeemedTimesForCurrentOffer * (num_of_points ?? 0);
2573
+ const pointsProgress = getPreUnlockProgressPercentage(effectiveLoyaltyPointsForCurrentOffer, num_of_points);
2574
+ const amountProgress = getPreUnlockProgressPercentage(orderValue, total_amount);
2575
+ const combinedProgress = Math.min(pointsProgress, amountProgress);
2576
+ if (effectiveLoyaltyPointsForCurrentOffer >= num_of_points) {
2577
+ if (orderValue >= total_amount) {
2578
+ if (effectiveLoyaltyPointsForCurrentOffer >= num_of_points) {
2579
+ stats.progress = 100;
2580
+ stats.message = `🎉 You have unlocked this offer 🎉`;
2581
+ }
2582
+ else {
2583
+ stats.progress = combinedProgress;
2584
+ stats.message = `You are ${(num_of_points - effectiveLoyaltyPointsForCurrentOffer).toFixed(0)} points away from unlocking this offer`;
2585
+ }
2586
+ }
2587
+ else {
2588
+ stats.progress = combinedProgress;
2589
+ stats.message = `Spend ${currency_symbol}${parseNum(parseNum(total_amount - orderValue))} more in this order to unlock this offer 🔓`;
2590
+ }
2591
+ }
2592
+ else {
2593
+ stats.progress = combinedProgress;
2594
+ stats.message = `You are ${(num_of_points - effectiveLoyaltyPointsForCurrentOffer).toFixed(0)} points away from unlocking this offer`;
2595
+ }
2596
+ if (stats.progress >= 100) {
2597
+ const pointBurnTimes = Math.floor(effectiveLoyaltyPointsForCurrentOffer / (num_of_points || 1));
2598
+ const amountTimes = total_amount != null && total_amount > 0 ? Math.floor(orderValue / total_amount) : pointBurnTimes;
2599
+ const totalUnlockableClaims = clampClaimsToRemainingClaimBudget(offer, Math.min(pointBurnTimes, amountTimes, maxClaimsPerOrder));
2600
+ if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.DISCOUNT) {
2601
+ if (offer.reward_discount == null)
2602
+ continue;
2603
+ const rewardExcludedRefs = offer.reward_discount.excluded_refs ?? [];
2604
+ if (rewardExcludedRefs.length > 0 && !hasEligibleItemsForDiscount(categories, rewardExcludedRefs)) {
2605
+ stats.progress = 0;
2606
+ stats.claimable = false;
2607
+ stats.message = `⛔️ No eligible items for this offer ⛔️`;
2608
+ offersWithStats.push({ offer, stats });
2609
+ continue;
2610
+ }
2611
+ const redeemedTimes = redeemedTimesForCurrentOffer;
2612
+ const isRedeemed = redeemedTimes > 0;
2613
+ const discountSlotOccupied = isDiscountSlotOccupiedForOffer(offer);
2614
+ stats.redeemed_times = redeemedTimes;
2615
+ stats.applicable_quantity = 1;
2616
+ stats.claimable = !isRedeemed && !discountSlotOccupied;
2617
+ if (isRedeemed) {
2618
+ stats.message = 'This offer is redeemed ✅';
2619
+ }
2620
+ else if (discountSlotOccupied) {
2621
+ stats.message = 'You already have an offer applied to your order.';
2622
+ }
2623
+ else {
2624
+ totalClaimableOffers.push(offer._id);
2625
+ stats.message = `🎉 You have unlocked this offer 🎉`;
2626
+ }
2627
+ unlockedOffersApplicableTimes[offer._id] = stats.applicable_quantity;
2628
+ }
2629
+ else if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS) {
2630
+ if (offer.reward_discount_items == null)
2631
+ continue;
2632
+ const rewardExcludedRefs = offer.reward_discount_items.excluded_refs ?? [];
2633
+ if (rewardExcludedRefs.length > 0 && !hasEligibleItemsForDiscount(categories, rewardExcludedRefs)) {
2634
+ stats.progress = 0;
2635
+ stats.claimable = false;
2636
+ stats.message = `⛔️ No eligible items for this offer ⛔️`;
2637
+ offersWithStats.push({ offer, stats });
2638
+ continue;
2639
+ }
2640
+ const totalOfferItemsSelected = getTotalSelectedOfferItemsAgainstOffer(categories, offer._id);
2641
+ const applicableQuantity = offer.reward_discount_items.num_of_items || 1;
2642
+ const redeemedTimes = getItemRewardRedeemedTimes({
2643
+ totalOfferItemsSelected,
2644
+ applicableQuantity,
2645
+ });
2646
+ const isClaimable = redeemedTimes < totalUnlockableClaims;
2647
+ stats.redeemed_times = redeemedTimes;
2648
+ stats.applicable_quantity = applicableQuantity * Math.max(1, totalUnlockableClaims);
2649
+ stats.claimable = isClaimable;
2650
+ if (isClaimable) {
2651
+ totalClaimableOffers.push(offer._id);
2652
+ stats.message = `🎉 You have unlocked this offer 🎉`;
2653
+ }
2654
+ else {
2655
+ stats.message = redeemedTimes > 0 ? `This offer is redeemed ✅` : `🎉 You have unlocked this offer 🎉`;
2656
+ }
2657
+ unlockedOffersApplicableTimes[offer._id] = stats.applicable_quantity;
2658
+ }
2659
+ else if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.POINTS) {
2660
+ if (offer.reward_points == null)
2661
+ continue;
2662
+ const redeemedTimes = getOfferRedeemedTimes(offer._id);
2663
+ const maxRedeemableClaims = getPointsMaxRedeemableClaims({
2664
+ offerToCheck: offer,
2665
+ pathwayUnlockableClaims: totalUnlockableClaims,
2666
+ });
2667
+ const isClaimable = redeemedTimes < maxRedeemableClaims;
2668
+ stats.redeemed_times = redeemedTimes;
2669
+ stats.applicable_quantity = maxRedeemableClaims;
2670
+ stats.claimable = isClaimable;
2671
+ if (!isClaimable) {
2672
+ stats.message = 'This offer is redeemed ✅';
2673
+ }
2674
+ else {
2675
+ totalClaimableOffers.push(offer._id);
2676
+ stats.message = `🎉 You have unlocked this offer 🎉`;
2677
+ }
2678
+ unlockedOffersApplicableTimes[offer._id] = stats.applicable_quantity;
2679
+ }
2680
+ else if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.VOUCHER) {
2681
+ if (offer.reward_voucher == null)
2682
+ continue;
2683
+ const { rewardVoucherUnavailable, rewardVoucherLimitExhausted } = getRewardVoucherAvailability(Object.keys(offer.reward_voucher.voucher_ids));
2684
+ const redeemedTimes = getOfferRedeemedTimes(offer._id);
2685
+ const isRedeemed = redeemedTimes > 0;
2686
+ stats.redeemed_times = redeemedTimes;
2687
+ stats.applicable_quantity = 1;
2688
+ stats.claimable = !isRedeemed && !rewardVoucherUnavailable && !rewardVoucherLimitExhausted;
2689
+ if (rewardVoucherUnavailable) {
2690
+ stats.message = '⛔️ This reward is no longer available ⛔️';
2691
+ }
2692
+ else if (rewardVoucherLimitExhausted) {
2693
+ stats.message = '⛔️ You have reached your personal limit for this reward ⛔️';
2694
+ }
2695
+ else if (isRedeemed) {
2696
+ stats.message = 'This offer is redeemed ✅';
2697
+ }
2698
+ else {
2699
+ totalClaimableOffers.push(offer._id);
2700
+ stats.message = `🎉 You have unlocked this offer 🎉`;
2701
+ }
2702
+ unlockedOffersApplicableTimes[offer._id] = stats.applicable_quantity;
2703
+ }
2704
+ else if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.CASHBACK) {
2705
+ if (offer.reward_cashback == null)
2706
+ continue;
2707
+ const rewardExcludedRefs = offer.reward_cashback.excluded_refs ?? [];
2708
+ if (rewardExcludedRefs.length > 0 && !hasEligibleItemsForDiscount(categories, rewardExcludedRefs)) {
2709
+ stats.progress = 0;
2710
+ stats.claimable = false;
2711
+ stats.message = `⛔️ No eligible items for this offer ⛔️`;
2712
+ offersWithStats.push({ offer, stats });
2713
+ continue;
2714
+ }
2715
+ const redeemedTimes = getOfferRedeemedTimes(offer._id);
2716
+ if (offer.reward_cashback.is_cashback_percentage === true) {
2717
+ // Percentage cashback scales with the order total and is claimed
2718
+ // once per order; total_amount / max_claims do not apply.
2719
+ const isRedeemed = redeemedTimes > 0;
2720
+ stats.redeemed_times = redeemedTimes;
2721
+ stats.applicable_quantity = 1;
2722
+ stats.claimable = !isRedeemed;
2723
+ if (isRedeemed) {
2724
+ stats.message = 'This offer is redeemed ✅';
2725
+ }
2726
+ else {
2727
+ totalClaimableOffers.push(offer._id);
2728
+ stats.message = `🎉 You have unlocked this offer 🎉`;
2729
+ }
2730
+ }
2731
+ else {
2732
+ // Flat cashback repeats per qualifying spend chunk
2733
+ // (every total_amount unlocks one claim), capped by max_claims.
2734
+ const maxRedeemableClaims = getPathwayMaxRedeemableClaims(totalUnlockableClaims);
2735
+ const isClaimable = redeemedTimes < maxRedeemableClaims;
2736
+ stats.redeemed_times = redeemedTimes;
2737
+ stats.applicable_quantity = maxRedeemableClaims;
2738
+ stats.claimable = isClaimable;
2739
+ if (!isClaimable) {
2740
+ stats.message = 'This offer is redeemed ✅';
2741
+ }
2742
+ else {
2743
+ totalClaimableOffers.push(offer._id);
2744
+ stats.message = `🎉 You have unlocked this offer 🎉`;
2745
+ }
2746
+ }
2747
+ unlockedOffersApplicableTimes[offer._id] = stats.applicable_quantity;
2748
+ }
2749
+ else if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.GIFT_CARDS) {
2750
+ if (offer.reward_gift_cards == null)
2751
+ continue;
2752
+ const { rewardGiftCardUnavailable, rewardGiftCardLimitExhausted } = getRewardGiftCardAvailability(Object.keys(offer.reward_gift_cards.gift_card_ids));
2753
+ const redeemedTimes = getOfferRedeemedTimes(offer._id);
2754
+ const isRedeemed = redeemedTimes > 0;
2755
+ stats.redeemed_times = redeemedTimes;
2756
+ stats.applicable_quantity = 1;
2757
+ stats.claimable = !isRedeemed && !rewardGiftCardUnavailable && !rewardGiftCardLimitExhausted;
2758
+ if (rewardGiftCardUnavailable) {
2759
+ stats.message = '⛔️ This reward is no longer available ⛔️';
2760
+ }
2761
+ else if (rewardGiftCardLimitExhausted) {
2762
+ stats.message = '⛔️ You have reached your personal limit for this reward ⛔️';
2763
+ }
2764
+ else if (isRedeemed) {
2765
+ stats.message = 'This offer is redeemed ✅';
2766
+ }
2767
+ else {
2768
+ totalClaimableOffers.push(offer._id);
2769
+ stats.message = `🎉 You have unlocked this offer 🎉`;
2770
+ }
2771
+ unlockedOffersApplicableTimes[offer._id] = stats.applicable_quantity;
2772
+ }
2773
+ else if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.ITEMS) {
2774
+ if (offer.reward_items == null)
2775
+ continue;
2776
+ const totalOfferItemsSelected = getTotalSelectedOfferItemsAgainstOffer(categories, offer._id);
2777
+ const applicableQuantity = offer.reward_items.num_of_items || 1;
2778
+ const redeemedTimes = getItemRewardRedeemedTimes({
2779
+ totalOfferItemsSelected,
2780
+ applicableQuantity,
2781
+ });
2782
+ const isClaimable = redeemedTimes < totalUnlockableClaims;
2783
+ stats.redeemed_times = redeemedTimes;
2784
+ stats.applicable_quantity = applicableQuantity * Math.max(1, totalUnlockableClaims);
2785
+ stats.claimable = isClaimable;
2786
+ if (isClaimable) {
2787
+ totalClaimableOffers.push(offer._id);
2788
+ stats.message = `🎉 You have unlocked this offer 🎉`;
2789
+ }
2790
+ else {
2791
+ stats.message = redeemedTimes > 0 ? `This offer is redeemed ✅` : `🎉 You have unlocked this offer 🎉`;
2792
+ }
2793
+ unlockedOffersApplicableTimes[offer._id] = stats.applicable_quantity;
2794
+ }
2795
+ }
2796
+ applyItemRewardClaimableFallback({
2797
+ offerToCheck: offer,
2798
+ stats,
2799
+ });
2800
+ if (stats.progress >= 100 && isOfferUsesPerCustomerExhausted(offer)) {
2801
+ if (stats.claimable) {
2802
+ totalClaimableOffers = totalClaimableOffers.filter((id) => id !== offer._id);
2803
+ }
2804
+ stats.applicable_quantity = 0;
2805
+ unlockedOffersApplicableTimes[offer._id] = 0;
2806
+ stats.claimable = false;
2807
+ stats.message = '⛔️ You have reached your personal limit for this offer ⛔️';
2808
+ }
2809
+ clearBlockedRewardApplicableQuantity(offer, stats);
2810
+ stats.action_hint = getActionHint(offer, stats.claimable);
2811
+ offersWithStats.push({
2812
+ offer,
2813
+ stats,
2814
+ });
2815
+ }
2816
+ else if (offer.pathway_to_unlock_type === PATHWAY_TO_UNLOCK_TYPE_ENUM.VOUCHER) {
2817
+ if (offer.pathway_to_unlock_type_vouchers == null) {
2818
+ stats.invalid_offer = true;
2819
+ stats.claimable = false;
2820
+ stats.message = `Offer pathway to unlock type vouchers is empty`;
2821
+ offersWithStats.push({
2822
+ offer,
2823
+ stats,
2824
+ });
2825
+ continue;
2826
+ }
2827
+ const orderValue = getOfferQualifyingOrderValue({
2828
+ offer,
2829
+ categories,
2830
+ orderLevelDiscountBaseAmount,
2831
+ orderLevelDiscountAmount,
2832
+ orderDiscountDetails: order_discount_details,
2833
+ });
2834
+ const { total_amount, max_amount, max_claims, voucher_ids } = offer.pathway_to_unlock_type_vouchers;
2835
+ const voucherReferenceNumber = order_discount_details?.voucher_reference_number;
2836
+ const normalizedVoucherRef = voucherReferenceNumber?.trim().toUpperCase();
2837
+ const referencedVouchers = voucher_ids
2838
+ .map((voucherId) => vouchersById.get(voucherId))
2839
+ .filter((voucher) => voucher != null);
2840
+ const getVoucherCode = (voucher) => voucher.code.trim().toUpperCase();
2841
+ const getVoucherSpendableCount = (voucher) => spendableVoucherCodesByCode[getVoucherCode(voucher)] ?? 0;
2842
+ const redeemedTimesForOffer = getOfferRedeemedTimes(offer._id);
2843
+ const isVoucherPathwayUsageAvailable = (voucher) => {
2844
+ const maxUsesPerCustomer = voucher.max_uses_per_customer;
2845
+ if (maxUsesPerCustomer == null) {
2846
+ return true;
2847
+ }
2848
+ if (customerOfferRedemptionCounts == null) {
2849
+ // Defensive block when capped voucher counts are unavailable.
2850
+ return false;
2851
+ }
2852
+ return getCustomerUsedRedemptionCount(customerOfferRedemptionCounts, voucher._id) < maxUsesPerCustomer;
2853
+ };
2854
+ // Wallet-first unlock policy for voucher pathways:
2855
+ // - A referenced voucher must exist in wallet inventory (spendable > 0)
2856
+ // to unlock claimability.
2857
+ // - Applied voucher code is optional and only used to disambiguate when
2858
+ // multiple referenced vouchers are available in wallet.
2859
+ const referencedVouchersWithWalletAccess = referencedVouchers.filter((voucher) => getVoucherSpendableCount(voucher) > 0 && isVoucherPathwayUsageAvailable(voucher));
2860
+ const matchedReferencedVoucherByReference = normalizedVoucherRef == null
2861
+ ? null
2862
+ : (referencedVouchers.find((voucher) => getVoucherCode(voucher) === normalizedVoucherRef) ?? null);
2863
+ const matchedReferencedVoucherByCartContext = voucherPathwayCartContext.activeVoucherCode == null
2864
+ ? null
2865
+ : (referencedVouchers.find((voucher) => getVoucherCode(voucher) === voucherPathwayCartContext.activeVoucherCode) ?? null);
2866
+ const matchedVoucherForAccess = normalizedVoucherRef == null
2867
+ ? null
2868
+ : (referencedVouchersWithWalletAccess.find((voucher) => getVoucherCode(voucher) === normalizedVoucherRef) ??
2869
+ null);
2870
+ const firstReferencedVoucherWithWalletInventory = referencedVouchers.find((voucher) => getVoucherSpendableCount(voucher) > 0) ?? null;
2871
+ const singleReferencedVoucherForRedeemedClaim = redeemedTimesForOffer > 0 && referencedVouchers.length === 1 ? referencedVouchers[0] : null;
2872
+ const matchedVoucher = matchedVoucherForAccess ?? referencedVouchersWithWalletAccess[0] ?? null;
2873
+ const matchingVoucherContext = matchedVoucher ??
2874
+ matchedReferencedVoucherByReference ??
2875
+ matchedReferencedVoucherByCartContext ??
2876
+ firstReferencedVoucherWithWalletInventory ??
2877
+ singleReferencedVoucherForRedeemedClaim ??
2878
+ null;
2879
+ const hasMatchingVoucher = matchingVoucherContext != null;
2880
+ const normalizedMatchedVoucherCode = matchingVoucherContext != null ? getVoucherCode(matchingVoucherContext) : null;
2881
+ const spendableVoucherCount = normalizedMatchedVoucherCode == null ? 0 : (spendableVoucherCodesByCode[normalizedMatchedVoucherCode] ?? 0);
2882
+ const hasVoucherAccess = matchedVoucher != null || (redeemedTimesForOffer > 0 && matchingVoucherContext != null);
2883
+ const amountProgress = getPreUnlockProgressPercentage(orderValue, total_amount);
2884
+ if (!hasMatchingVoucher) {
2885
+ stats.progress = 0;
2886
+ stats.message = `Enter a matching voucher code to unlock this offer`;
2887
+ }
2888
+ else if (!hasVoucherAccess) {
2889
+ stats.progress = 0;
2890
+ stats.message = `⛔️ You are not eligible for this offer ⛔️`;
2891
+ }
2892
+ else if (max_amount != null && orderValue > max_amount) {
2893
+ stats.progress = 0;
2894
+ stats.message = `⛔️ You are not eligible for this offer ⛔️`;
2895
+ }
2896
+ else if (orderValue >= total_amount) {
2897
+ stats.progress = 100;
2898
+ stats.message = `🎉 You have unlocked this offer 🎉`;
2899
+ }
2900
+ else {
2901
+ stats.progress = amountProgress;
2902
+ stats.message = `Spend ${currency_symbol}${parseNum(total_amount - orderValue)} more in this order to unlock this offer 🔓`;
2903
+ }
2904
+ if (stats.progress >= 100) {
2905
+ if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.DISCOUNT) {
2906
+ if (offer.reward_discount == null)
2907
+ continue;
2908
+ const rewardExcludedRefs = offer.reward_discount.excluded_refs ?? [];
2909
+ if (rewardExcludedRefs.length > 0 && !hasEligibleItemsForDiscount(categories, rewardExcludedRefs)) {
2910
+ stats.progress = 0;
2911
+ stats.claimable = false;
2912
+ stats.message = `⛔️ No eligible items for this offer ⛔️`;
2913
+ offersWithStats.push({ offer, stats });
2914
+ continue;
2915
+ }
2916
+ const redeemedTimes = getOfferRedeemedTimes(offer._id);
2917
+ const isRedeemed = redeemedTimes > 0;
2918
+ const discountSlotOccupied = isDiscountSlotOccupiedForOffer(offer);
2919
+ stats.redeemed_times = redeemedTimes;
2920
+ stats.applicable_quantity = 1;
2921
+ stats.claimable = !isRedeemed && !discountSlotOccupied;
2922
+ if (isRedeemed) {
2923
+ stats.message = 'This offer is redeemed ✅';
2924
+ }
2925
+ else if (discountSlotOccupied) {
2926
+ stats.message = 'You already have an offer applied to your order.';
2927
+ }
2928
+ else {
2929
+ totalClaimableOffers.push(offer._id);
2930
+ stats.message = `🎉 You have unlocked this offer 🎉`;
2931
+ }
2932
+ unlockedOffersApplicableTimes[offer._id] = stats.applicable_quantity;
2933
+ }
2934
+ else if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS) {
2935
+ if (offer.reward_discount_items == null)
2936
+ continue;
2937
+ const rewardExcludedRefs = offer.reward_discount_items.excluded_refs ?? [];
2938
+ if (rewardExcludedRefs.length > 0 && !hasEligibleItemsForDiscount(categories, rewardExcludedRefs)) {
2939
+ stats.progress = 0;
2940
+ stats.claimable = false;
2941
+ stats.message = `⛔️ No eligible items for this offer ⛔️`;
2942
+ offersWithStats.push({ offer, stats });
2943
+ continue;
2944
+ }
2945
+ const totalOfferItemsSelected = getTotalSelectedOfferItemsAgainstOffer(categories, offer._id);
2946
+ const applicableQuantity = offer.reward_discount_items.num_of_items || 1;
2947
+ const redeemedTimes = getItemRewardRedeemedTimes({
2948
+ totalOfferItemsSelected,
2949
+ applicableQuantity,
2950
+ });
2951
+ const maxClaimsPerOrder = max_claims == null ? Infinity : Math.max(1, max_claims);
2952
+ const unlockTimesForAmount = getOrderValueClaimTimes(orderValue, total_amount);
2953
+ const voucherInventoryClaimCap = matchingVoucherContext != null ? Math.max(0, spendableVoucherCount + redeemedTimesForOffer) : Infinity;
2954
+ const totalUnlockableClaims = clampClaimsToRemainingClaimBudget(offer, Math.min(unlockTimesForAmount, maxClaimsPerOrder, voucherInventoryClaimCap));
2955
+ const isClaimable = redeemedTimes < totalUnlockableClaims;
2956
+ stats.redeemed_times = redeemedTimes;
2957
+ stats.applicable_quantity = applicableQuantity * Math.max(1, totalUnlockableClaims);
2958
+ stats.claimable = isClaimable;
2959
+ if (isClaimable) {
2960
+ totalClaimableOffers.push(offer._id);
2961
+ stats.message = `🎉 You have unlocked this offer 🎉`;
2962
+ }
2963
+ else {
2964
+ stats.message = `This offer is redeemed ✅`;
2965
+ }
2966
+ unlockedOffersApplicableTimes[offer._id] = stats.applicable_quantity;
2967
+ }
2968
+ else if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.POINTS) {
2969
+ if (offer.reward_points == null)
2970
+ continue;
2971
+ const redeemedTimes = getOfferRedeemedTimes(offer._id);
2972
+ const maxClaimsPerOrder = max_claims == null ? Infinity : Math.max(1, max_claims);
2973
+ const unlockTimesForAmount = getOrderValueClaimTimes(orderValue, total_amount);
2974
+ const voucherInventoryClaimCap = matchingVoucherContext != null ? Math.max(0, spendableVoucherCount + redeemedTimesForOffer) : Infinity;
2975
+ const totalUnlockableClaims = clampClaimsToRemainingClaimBudget(offer, Math.min(unlockTimesForAmount, maxClaimsPerOrder, voucherInventoryClaimCap));
2976
+ const maxRedeemableClaims = getPointsMaxRedeemableClaims({
2977
+ offerToCheck: offer,
2978
+ pathwayUnlockableClaims: totalUnlockableClaims,
2979
+ });
2980
+ const isClaimable = redeemedTimes < maxRedeemableClaims;
2981
+ stats.redeemed_times = redeemedTimes;
2982
+ stats.applicable_quantity = maxRedeemableClaims;
2983
+ stats.claimable = isClaimable;
2984
+ if (!isClaimable) {
2985
+ stats.message = 'This offer is redeemed ✅';
2986
+ }
2987
+ else {
2988
+ totalClaimableOffers.push(offer._id);
2989
+ stats.message = `🎉 You have unlocked this offer 🎉`;
2990
+ }
2991
+ unlockedOffersApplicableTimes[offer._id] = stats.applicable_quantity;
2992
+ }
2993
+ else if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.VOUCHER) {
2994
+ if (offer.reward_voucher == null)
2995
+ continue;
2996
+ const { rewardVoucherUnavailable, rewardVoucherLimitExhausted } = getRewardVoucherAvailability(Object.keys(offer.reward_voucher.voucher_ids));
2997
+ const redeemedTimes = getOfferRedeemedTimes(offer._id);
2998
+ const isRedeemed = redeemedTimes > 0;
2999
+ stats.redeemed_times = redeemedTimes;
3000
+ stats.applicable_quantity = 1;
3001
+ stats.claimable = !isRedeemed && !rewardVoucherUnavailable && !rewardVoucherLimitExhausted;
3002
+ if (rewardVoucherUnavailable) {
3003
+ stats.message = '⛔️ This reward is no longer available ⛔️';
3004
+ }
3005
+ else if (rewardVoucherLimitExhausted) {
3006
+ stats.message = '⛔️ You have reached your personal limit for this reward ⛔️';
3007
+ }
3008
+ else if (isRedeemed) {
3009
+ stats.message = 'This offer is redeemed ✅';
3010
+ }
3011
+ else {
3012
+ totalClaimableOffers.push(offer._id);
3013
+ stats.message = `🎉 You have unlocked this offer 🎉`;
3014
+ }
3015
+ unlockedOffersApplicableTimes[offer._id] = stats.applicable_quantity;
3016
+ }
3017
+ else if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.CASHBACK) {
3018
+ if (offer.reward_cashback == null)
3019
+ continue;
3020
+ const rewardExcludedRefs = offer.reward_cashback.excluded_refs ?? [];
3021
+ if (rewardExcludedRefs.length > 0 && !hasEligibleItemsForDiscount(categories, rewardExcludedRefs)) {
3022
+ stats.progress = 0;
3023
+ stats.claimable = false;
3024
+ stats.message = `⛔️ No eligible items for this offer ⛔️`;
3025
+ offersWithStats.push({ offer, stats });
3026
+ continue;
3027
+ }
3028
+ const redeemedTimes = getOfferRedeemedTimes(offer._id);
3029
+ if (offer.reward_cashback.is_cashback_percentage === true) {
3030
+ // Percentage cashback scales with the order total and is claimed
3031
+ // once per order; total_amount / max_claims do not apply.
3032
+ const isRedeemed = redeemedTimes > 0;
3033
+ stats.redeemed_times = redeemedTimes;
3034
+ stats.applicable_quantity = 1;
3035
+ stats.claimable = !isRedeemed;
3036
+ if (isRedeemed) {
3037
+ stats.message = 'This offer is redeemed ✅';
3038
+ }
3039
+ else {
3040
+ totalClaimableOffers.push(offer._id);
3041
+ stats.message = `🎉 You have unlocked this offer 🎉`;
3042
+ }
3043
+ }
3044
+ else {
3045
+ // Flat cashback repeats per qualifying spend chunk
3046
+ // (every total_amount unlocks one claim), capped by max_claims
3047
+ // and the voucher inventory available for this order.
3048
+ const maxClaimsPerOrder = max_claims == null ? Infinity : Math.max(1, max_claims);
3049
+ const unlockTimesForAmount = getOrderValueClaimTimes(orderValue, total_amount);
3050
+ const voucherInventoryClaimCap = matchingVoucherContext != null ? Math.max(0, spendableVoucherCount + redeemedTimesForOffer) : Infinity;
3051
+ const totalUnlockableClaims = clampClaimsToRemainingClaimBudget(offer, Math.min(unlockTimesForAmount, maxClaimsPerOrder, voucherInventoryClaimCap));
3052
+ const maxRedeemableClaims = getPathwayMaxRedeemableClaims(totalUnlockableClaims);
3053
+ const isClaimable = redeemedTimes < maxRedeemableClaims;
3054
+ stats.redeemed_times = redeemedTimes;
3055
+ stats.applicable_quantity = maxRedeemableClaims;
3056
+ stats.claimable = isClaimable;
3057
+ if (!isClaimable) {
3058
+ stats.message = 'This offer is redeemed ✅';
3059
+ }
3060
+ else {
3061
+ totalClaimableOffers.push(offer._id);
3062
+ stats.message = `🎉 You have unlocked this offer 🎉`;
3063
+ }
3064
+ }
3065
+ unlockedOffersApplicableTimes[offer._id] = stats.applicable_quantity;
3066
+ }
3067
+ else if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.GIFT_CARDS) {
3068
+ if (offer.reward_gift_cards == null)
3069
+ continue;
3070
+ const { rewardGiftCardUnavailable, rewardGiftCardLimitExhausted } = getRewardGiftCardAvailability(Object.keys(offer.reward_gift_cards.gift_card_ids));
3071
+ const redeemedTimes = getOfferRedeemedTimes(offer._id);
3072
+ const isRedeemed = redeemedTimes > 0;
3073
+ stats.redeemed_times = redeemedTimes;
3074
+ stats.applicable_quantity = 1;
3075
+ stats.claimable = !isRedeemed && !rewardGiftCardUnavailable && !rewardGiftCardLimitExhausted;
3076
+ if (rewardGiftCardUnavailable) {
3077
+ stats.message = '⛔️ This reward is no longer available ⛔️';
3078
+ }
3079
+ else if (rewardGiftCardLimitExhausted) {
3080
+ stats.message = '⛔️ You have reached your personal limit for this reward ⛔️';
3081
+ }
3082
+ else if (isRedeemed) {
3083
+ stats.message = 'This offer is redeemed ✅';
3084
+ }
3085
+ else {
3086
+ totalClaimableOffers.push(offer._id);
3087
+ stats.message = `🎉 You have unlocked this offer 🎉`;
3088
+ }
3089
+ unlockedOffersApplicableTimes[offer._id] = stats.applicable_quantity;
3090
+ }
3091
+ else if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.ITEMS) {
3092
+ if (offer.reward_items == null)
3093
+ continue;
3094
+ const totalOfferItemsSelected = getTotalSelectedOfferItemsAgainstOffer(categories, offer._id);
3095
+ const applicableQuantity = offer.reward_items.num_of_items || 1;
3096
+ const redeemedTimes = getItemRewardRedeemedTimes({
3097
+ totalOfferItemsSelected,
3098
+ applicableQuantity,
3099
+ });
3100
+ const maxClaimsPerOrder = max_claims == null ? Infinity : Math.max(1, max_claims);
3101
+ const unlockTimesForAmount = getOrderValueClaimTimes(orderValue, total_amount);
3102
+ const voucherInventoryClaimCap = matchingVoucherContext != null ? Math.max(0, spendableVoucherCount + redeemedTimesForOffer) : Infinity;
3103
+ const totalUnlockableClaims = clampClaimsToRemainingClaimBudget(offer, Math.min(unlockTimesForAmount, maxClaimsPerOrder, voucherInventoryClaimCap));
3104
+ const isClaimable = redeemedTimes < totalUnlockableClaims;
3105
+ stats.redeemed_times = redeemedTimes;
3106
+ stats.applicable_quantity = applicableQuantity * Math.max(1, totalUnlockableClaims);
3107
+ stats.claimable = isClaimable;
3108
+ if (isClaimable) {
3109
+ totalClaimableOffers.push(offer._id);
3110
+ stats.message = `🎉 You have unlocked this offer 🎉`;
3111
+ }
3112
+ else {
3113
+ stats.message = `This offer is redeemed ✅`;
3114
+ }
3115
+ unlockedOffersApplicableTimes[offer._id] = stats.applicable_quantity;
3116
+ }
3117
+ }
3118
+ applyItemRewardClaimableFallback({
3119
+ offerToCheck: offer,
3120
+ stats,
3121
+ });
3122
+ applyVoucherPathwayCartContextBlock({
3123
+ offerToCheck: offer,
3124
+ statsToUpdate: stats,
3125
+ });
3126
+ if (stats.progress >= 100 && isOfferUsesPerCustomerExhausted(offer)) {
3127
+ if (stats.claimable) {
3128
+ totalClaimableOffers = totalClaimableOffers.filter((id) => id !== offer._id);
3129
+ }
3130
+ stats.applicable_quantity = 0;
3131
+ unlockedOffersApplicableTimes[offer._id] = 0;
3132
+ stats.claimable = false;
3133
+ stats.message = '⛔️ You have reached your personal limit for this offer ⛔️';
3134
+ }
3135
+ clearBlockedRewardApplicableQuantity(offer, stats);
3136
+ stats.action_hint = getActionHint(offer, stats.claimable);
3137
+ offersWithStats.push({
3138
+ offer,
3139
+ stats,
3140
+ });
3141
+ }
3142
+ else {
3143
+ stats.invalid_offer = true;
3144
+ stats.claimable = false;
3145
+ stats.message = `Unsupported pathway to unlock type`;
3146
+ offersWithStats.push({
3147
+ offer,
3148
+ stats,
3149
+ });
3150
+ }
3151
+ }
3152
+ // When customerOfferRedemptionCounts is null, invalidate claimability for offers whose
3153
+ // reward vouchers/gift-cards have assignment limits, since we cannot verify the limit.
3154
+ if (customerOfferRedemptionCounts == null) {
3155
+ for (let i = 0; i < offersWithStats.length; i++) {
3156
+ const { offer, stats } = offersWithStats[i];
3157
+ if (!stats.claimable)
3158
+ continue;
3159
+ if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.VOUCHER && offer.reward_voucher != null) {
3160
+ const vIds = Object.keys(offer.reward_voucher.voucher_ids);
3161
+ for (let vIdx = 0; vIdx < vIds.length; vIdx++) {
3162
+ const rewardVoucher = allVouchersById.get(vIds[vIdx]);
3163
+ if (rewardVoucher != null && getRewardMaxAssignmentsPerCustomer(rewardVoucher) != null) {
3164
+ stats.claimable = false;
3165
+ stats.applicable_quantity = 0;
3166
+ unlockedOffersApplicableTimes[offer._id] = 0;
3167
+ stats.message = '⛔️ You have reached your personal limit for this reward ⛔️';
3168
+ totalClaimableOffers = totalClaimableOffers.filter((id) => id !== offer._id);
3169
+ stats.action_hint = getActionHint(offer, stats.claimable);
3170
+ break;
3171
+ }
3172
+ }
3173
+ }
3174
+ if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.GIFT_CARDS &&
3175
+ offer.reward_gift_cards != null &&
3176
+ stats.claimable) {
3177
+ const gcIds = Object.keys(offer.reward_gift_cards.gift_card_ids);
3178
+ for (let gcIdx = 0; gcIdx < gcIds.length; gcIdx++) {
3179
+ const giftCard = allGiftCardsById.get(gcIds[gcIdx]);
3180
+ if (giftCard != null && getRewardMaxAssignmentsPerCustomer(giftCard) != null) {
3181
+ stats.claimable = false;
3182
+ stats.applicable_quantity = 0;
3183
+ unlockedOffersApplicableTimes[offer._id] = 0;
3184
+ stats.message = '⛔️ You have reached your personal limit for this reward ⛔️';
3185
+ totalClaimableOffers = totalClaimableOffers.filter((id) => id !== offer._id);
3186
+ stats.action_hint = getActionHint(offer, stats.claimable);
3187
+ break;
3188
+ }
3189
+ }
3190
+ }
3191
+ }
3192
+ }
3193
+ return {
3194
+ offersWithStats,
3195
+ totalClaimableOffers,
3196
+ unlockedOffersApplicableTimes,
3197
+ offersWithStatsHashKey: getOffersWithStatsHashKey({
3198
+ offersWithStats,
3199
+ totalClaimableOffers,
3200
+ isEdit,
3201
+ itemsCount,
3202
+ itemsPrice: currentItemsPrice,
3203
+ }),
3204
+ unlockedOffersApplicableTimesHashKey: getUnlockedOffersApplicableTimesHashKey(unlockedOffersApplicableTimes, isEdit),
3205
+ };
3206
+ }
3207
+ // ===============================>>><<<=====================================
3208
+ export function generateOfferOnUpdate(partialUpdatedOffer) {
3209
+ const partialResponseOffer = {
3210
+ ...partialUpdatedOffer,
3211
+ };
3212
+ const unset = {};
3213
+ const set = {
3214
+ ...partialUpdatedOffer,
3215
+ };
3216
+ if (set.pathway_to_unlock_type === PATHWAY_TO_UNLOCK_TYPE_ENUM.ITEMS) {
3217
+ delete set.pathway_to_unlock_type_orders;
3218
+ delete set.pathway_to_unlock_type_points;
3219
+ delete set.pathway_to_unlock_type_vouchers;
3220
+ unset['pathway_to_unlock_type_orders'] = '';
3221
+ unset['pathway_to_unlock_type_points'] = '';
3222
+ unset['pathway_to_unlock_type_vouchers'] = '';
3223
+ }
3224
+ else if (set.pathway_to_unlock_type === PATHWAY_TO_UNLOCK_TYPE_ENUM.ORDERS) {
3225
+ delete set.pathway_to_unlock_type_items;
3226
+ delete set.pathway_to_unlock_type_points;
3227
+ delete set.pathway_to_unlock_type_vouchers;
3228
+ unset['pathway_to_unlock_type_items'] = '';
3229
+ unset['pathway_to_unlock_type_points'] = '';
3230
+ unset['pathway_to_unlock_type_vouchers'] = '';
3231
+ }
3232
+ else if (set.pathway_to_unlock_type === PATHWAY_TO_UNLOCK_TYPE_ENUM.POINTS) {
3233
+ delete set.pathway_to_unlock_type_items;
3234
+ delete set.pathway_to_unlock_type_orders;
3235
+ delete set.pathway_to_unlock_type_vouchers;
3236
+ unset['pathway_to_unlock_type_items'] = '';
3237
+ unset['pathway_to_unlock_type_orders'] = '';
3238
+ unset['pathway_to_unlock_type_vouchers'] = '';
3239
+ }
3240
+ else if (set.pathway_to_unlock_type === PATHWAY_TO_UNLOCK_TYPE_ENUM.VOUCHER) {
3241
+ delete set.pathway_to_unlock_type_items;
3242
+ delete set.pathway_to_unlock_type_orders;
3243
+ delete set.pathway_to_unlock_type_points;
3244
+ unset['pathway_to_unlock_type_items'] = '';
3245
+ unset['pathway_to_unlock_type_orders'] = '';
3246
+ unset['pathway_to_unlock_type_points'] = '';
3247
+ }
3248
+ if (set.reward_type === OFFER_REWARD_TYPE_ENUM.ITEMS) {
3249
+ delete set.reward_discount;
3250
+ delete set.reward_discount_items;
3251
+ delete set.reward_points;
3252
+ delete set.reward_cashback;
3253
+ delete set.reward_gift_cards;
3254
+ delete set.reward_voucher;
3255
+ unset['reward_discount'] = '';
3256
+ unset['reward_discount_items'] = '';
3257
+ unset['reward_points'] = '';
3258
+ unset['reward_cashback'] = '';
3259
+ unset['reward_gift_cards'] = '';
3260
+ unset['reward_voucher'] = '';
3261
+ }
3262
+ else if (set.reward_type === OFFER_REWARD_TYPE_ENUM.DISCOUNT) {
3263
+ delete set.reward_items;
3264
+ delete set.reward_discount_items;
3265
+ delete set.reward_points;
3266
+ delete set.reward_cashback;
3267
+ delete set.reward_gift_cards;
3268
+ delete set.reward_voucher;
3269
+ unset['reward_items'] = '';
3270
+ unset['reward_discount_items'] = '';
3271
+ unset['reward_points'] = '';
3272
+ unset['reward_cashback'] = '';
3273
+ unset['reward_gift_cards'] = '';
3274
+ unset['reward_voucher'] = '';
3275
+ }
3276
+ else if (set.reward_type === OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS) {
3277
+ delete set.reward_items;
3278
+ delete set.reward_points;
3279
+ delete set.reward_discount;
3280
+ delete set.reward_cashback;
3281
+ delete set.reward_gift_cards;
3282
+ delete set.reward_voucher;
3283
+ unset['reward_items'] = '';
3284
+ unset['reward_points'] = '';
3285
+ unset['reward_discount'] = '';
3286
+ unset['reward_cashback'] = '';
3287
+ unset['reward_gift_cards'] = '';
3288
+ unset['reward_voucher'] = '';
3289
+ }
3290
+ else if (set.reward_type === OFFER_REWARD_TYPE_ENUM.POINTS) {
3291
+ delete set.reward_items;
3292
+ delete set.reward_discount;
3293
+ delete set.reward_discount_items;
3294
+ delete set.reward_cashback;
3295
+ delete set.reward_gift_cards;
3296
+ delete set.reward_voucher;
3297
+ unset['reward_items'] = '';
3298
+ unset['reward_discount'] = '';
3299
+ unset['reward_discount_items'] = '';
3300
+ unset['reward_cashback'] = '';
3301
+ unset['reward_gift_cards'] = '';
3302
+ unset['reward_voucher'] = '';
3303
+ }
3304
+ else if (set.reward_type === OFFER_REWARD_TYPE_ENUM.CASHBACK) {
3305
+ delete set.reward_items;
3306
+ delete set.reward_discount;
3307
+ delete set.reward_discount_items;
3308
+ delete set.reward_points;
3309
+ delete set.reward_gift_cards;
3310
+ delete set.reward_voucher;
3311
+ unset['reward_items'] = '';
3312
+ unset['reward_discount'] = '';
3313
+ unset['reward_discount_items'] = '';
3314
+ unset['reward_points'] = '';
3315
+ unset['reward_gift_cards'] = '';
3316
+ unset['reward_voucher'] = '';
3317
+ }
3318
+ else if (set.reward_type === OFFER_REWARD_TYPE_ENUM.GIFT_CARDS) {
3319
+ delete set.reward_items;
3320
+ delete set.reward_discount;
3321
+ delete set.reward_discount_items;
3322
+ delete set.reward_points;
3323
+ delete set.reward_cashback;
3324
+ delete set.reward_voucher;
3325
+ unset['reward_items'] = '';
3326
+ unset['reward_discount'] = '';
3327
+ unset['reward_discount_items'] = '';
3328
+ unset['reward_points'] = '';
3329
+ unset['reward_cashback'] = '';
3330
+ unset['reward_voucher'] = '';
3331
+ }
3332
+ else if (set.reward_type === OFFER_REWARD_TYPE_ENUM.VOUCHER) {
3333
+ delete set.reward_items;
3334
+ delete set.reward_discount;
3335
+ delete set.reward_discount_items;
3336
+ delete set.reward_points;
3337
+ delete set.reward_cashback;
3338
+ delete set.reward_gift_cards;
3339
+ unset['reward_items'] = '';
3340
+ unset['reward_discount'] = '';
3341
+ unset['reward_discount_items'] = '';
3342
+ unset['reward_points'] = '';
3343
+ unset['reward_cashback'] = '';
3344
+ unset['reward_gift_cards'] = '';
3345
+ }
3346
+ const updateOperation = {
3347
+ ...(Object.keys(set).length > 0 ? { $set: set } : {}),
3348
+ ...(Object.keys(unset).length > 0 ? { $unset: unset } : {}),
3349
+ };
3350
+ return { updateOperation, partialResponseOffer };
3351
+ }