addio-admin-sdk 1.7.196 → 1.7.197

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 (589) hide show
  1. package/.babelrc +17 -17
  2. package/.env +14 -0
  3. package/.env.dev +14 -14
  4. package/.github/workflows/run_unit_test.yaml +48 -48
  5. package/.github/workflows/update_docs.yaml +32 -32
  6. package/addio-sdk-doc.md +1473 -1473
  7. package/changelog.md +582 -582
  8. package/dist/Interfaces/Address/index.d.ts +21 -21
  9. package/dist/Interfaces/Address/index.js +16 -16
  10. package/dist/Interfaces/Algolia/index.d.ts +183 -182
  11. package/dist/Interfaces/Algolia/index.js +2 -2
  12. package/dist/Interfaces/Attachement/index.d.ts +5 -5
  13. package/dist/Interfaces/Attachement/index.js +2 -2
  14. package/dist/Interfaces/Attribute/index.d.ts +53 -53
  15. package/dist/Interfaces/Attribute/index.js +10 -10
  16. package/dist/Interfaces/BGJob/index.d.ts +56 -56
  17. package/dist/Interfaces/BGJob/index.js +25 -25
  18. package/dist/Interfaces/BaseClass/index.d.ts +8 -8
  19. package/dist/Interfaces/BaseClass/index.js +2 -2
  20. package/dist/Interfaces/Blog/IBlogArticle.d.ts +18 -18
  21. package/dist/Interfaces/Blog/IBlogArticle.js +2 -2
  22. package/dist/Interfaces/Blog/IBlogAuthor.d.ts +7 -7
  23. package/dist/Interfaces/Blog/IBlogAuthor.js +2 -2
  24. package/dist/Interfaces/Blog/IBlogCategory.d.ts +9 -9
  25. package/dist/Interfaces/Blog/IBlogCategory.js +2 -2
  26. package/dist/Interfaces/Blog/IBlogComment.d.ts +13 -13
  27. package/dist/Interfaces/Blog/IBlogComment.js +2 -2
  28. package/dist/Interfaces/Blog/IBlogKeywords.d.ts +9 -9
  29. package/dist/Interfaces/Blog/IBlogKeywords.js +2 -2
  30. package/dist/Interfaces/Booking/index.d.ts +74 -74
  31. package/dist/Interfaces/Booking/index.js +17 -17
  32. package/dist/Interfaces/Brand/index.d.ts +15 -15
  33. package/dist/Interfaces/Brand/index.js +2 -2
  34. package/dist/Interfaces/Buylist/index.d.ts +19 -19
  35. package/dist/Interfaces/Buylist/index.js +2 -2
  36. package/dist/Interfaces/CMS/index.d.ts +28 -28
  37. package/dist/Interfaces/CMS/index.js +5 -5
  38. package/dist/Interfaces/Cart/IElavonPayload.d.ts +93 -93
  39. package/dist/Interfaces/Cart/IElavonPayload.js +17 -17
  40. package/dist/Interfaces/Cart/IMarketPayload.d.ts +12 -12
  41. package/dist/Interfaces/Cart/IMarketPayload.js +2 -2
  42. package/dist/Interfaces/Cart/IPandaPayload.d.ts +64 -64
  43. package/dist/Interfaces/Cart/IPandaPayload.js +18 -18
  44. package/dist/Interfaces/Cart/IPaymentCard.d.ts +22 -22
  45. package/dist/Interfaces/Cart/IPaymentCard.js +44 -44
  46. package/dist/Interfaces/Cart/IPaypalPayload.d.ts +9 -9
  47. package/dist/Interfaces/Cart/IPaypalPayload.js +2 -2
  48. package/dist/Interfaces/Cart/IPaysafePayload.d.ts +72 -72
  49. package/dist/Interfaces/Cart/IPaysafePayload.js +2 -2
  50. package/dist/Interfaces/Cart/IStripePayload.d.ts +66 -66
  51. package/dist/Interfaces/Cart/IStripePayload.js +2 -2
  52. package/dist/Interfaces/Cart/index.d.ts +478 -476
  53. package/dist/Interfaces/Cart/index.js +283 -283
  54. package/dist/Interfaces/Cart/index.js.map +1 -1
  55. package/dist/Interfaces/CartReservedQuantities/index.d.ts +10 -10
  56. package/dist/Interfaces/CartReservedQuantities/index.js +2 -2
  57. package/dist/Interfaces/CashDrawers/index.d.ts +38 -38
  58. package/dist/Interfaces/CashDrawers/index.js +19 -19
  59. package/dist/Interfaces/Catalogue/index.d.ts +68 -68
  60. package/dist/Interfaces/Catalogue/index.js +37 -37
  61. package/dist/Interfaces/Category/index.d.ts +33 -33
  62. package/dist/Interfaces/Category/index.js +2 -2
  63. package/dist/Interfaces/Chart/index.d.ts +11 -11
  64. package/dist/Interfaces/Chart/index.js +2 -2
  65. package/dist/Interfaces/Class/index.d.ts +8 -8
  66. package/dist/Interfaces/Class/index.js +2 -2
  67. package/dist/Interfaces/Consent/index.d.ts +6 -6
  68. package/dist/Interfaces/Consent/index.js +2 -2
  69. package/dist/Interfaces/Context/IContextProps.d.ts +4 -4
  70. package/dist/Interfaces/Context/IContextProps.js +2 -2
  71. package/dist/Interfaces/Context/IContextState.d.ts +15 -15
  72. package/dist/Interfaces/Context/IContextState.js +2 -2
  73. package/dist/Interfaces/Customer/ICustomerBadge.d.ts +2 -2
  74. package/dist/Interfaces/Customer/ICustomerBadge.js +2 -2
  75. package/dist/Interfaces/Customer/ICustomerRating.d.ts +10 -10
  76. package/dist/Interfaces/Customer/ICustomerRating.js +2 -2
  77. package/dist/Interfaces/Customer/IStoreCredit.d.ts +13 -13
  78. package/dist/Interfaces/Customer/IStoreCredit.js +2 -2
  79. package/dist/Interfaces/Customer/index.d.ts +104 -104
  80. package/dist/Interfaces/Customer/index.js +148 -148
  81. package/dist/Interfaces/Declination/index.d.ts +133 -117
  82. package/dist/Interfaces/Declination/index.js +83 -66
  83. package/dist/Interfaces/Declination/index.js.map +1 -1
  84. package/dist/Interfaces/Document/index.d.ts +8 -8
  85. package/dist/Interfaces/Document/index.js +2 -2
  86. package/dist/Interfaces/Elastic/index.d.ts +89 -89
  87. package/dist/Interfaces/Elastic/index.js +2 -2
  88. package/dist/Interfaces/Email/CustomGR/I3DPrintEmail.d.ts +11 -11
  89. package/dist/Interfaces/Email/CustomGR/I3DPrintEmail.js +2 -2
  90. package/dist/Interfaces/Email/CustomGR/IBorrowToolsEmail.d.ts +15 -15
  91. package/dist/Interfaces/Email/CustomGR/IBorrowToolsEmail.js +2 -2
  92. package/dist/Interfaces/Email/CustomGR/IPickupMaterialsEmail.d.ts +12 -12
  93. package/dist/Interfaces/Email/CustomGR/IPickupMaterialsEmail.js +2 -2
  94. package/dist/Interfaces/Email/CustomGR/IPreMeetingFormEmail.d.ts +36 -36
  95. package/dist/Interfaces/Email/CustomGR/IPreMeetingFormEmail.js +2 -2
  96. package/dist/Interfaces/Email/CustomGR/ISponsorRequestEmail.d.ts +12 -12
  97. package/dist/Interfaces/Email/CustomGR/ISponsorRequestEmail.js +2 -2
  98. package/dist/Interfaces/Email/CustomGR/ITransportEmail.d.ts +12 -12
  99. package/dist/Interfaces/Email/CustomGR/ITransportEmail.js +2 -2
  100. package/dist/Interfaces/Email/CustomGR/ITransportQuoteEmail.d.ts +12 -12
  101. package/dist/Interfaces/Email/CustomGR/ITransportQuoteEmail.js +2 -2
  102. package/dist/Interfaces/Email/CustomGR/IVegetalsEmail.d.ts +16 -16
  103. package/dist/Interfaces/Email/CustomGR/IVegetalsEmail.js +2 -2
  104. package/dist/Interfaces/Email/CustomGR/IWishlistEmail.d.ts +15 -15
  105. package/dist/Interfaces/Email/CustomGR/IWishlistEmail.js +2 -2
  106. package/dist/Interfaces/Email/IAbandonnedCartEmail.d.ts +29 -29
  107. package/dist/Interfaces/Email/IAbandonnedCartEmail.js +2 -2
  108. package/dist/Interfaces/Email/IAccountConfirmationEmail.d.ts +22 -22
  109. package/dist/Interfaces/Email/IAccountConfirmationEmail.js +2 -2
  110. package/dist/Interfaces/Email/IApplicationEmail.d.ts +19 -19
  111. package/dist/Interfaces/Email/IApplicationEmail.js +2 -2
  112. package/dist/Interfaces/Email/IBackInStockEmail.d.ts +21 -21
  113. package/dist/Interfaces/Email/IBackInStockEmail.js +2 -2
  114. package/dist/Interfaces/Email/IContactEmail.d.ts +20 -20
  115. package/dist/Interfaces/Email/IContactEmail.js +2 -2
  116. package/dist/Interfaces/Email/ICustomerBookingAdminEmail.d.ts +15 -15
  117. package/dist/Interfaces/Email/ICustomerBookingAdminEmail.js +2 -2
  118. package/dist/Interfaces/Email/ICustomerBookingEmail.d.ts +14 -14
  119. package/dist/Interfaces/Email/ICustomerBookingEmail.js +2 -2
  120. package/dist/Interfaces/Email/IEmail.d.ts +20 -20
  121. package/dist/Interfaces/Email/IEmail.js +46 -46
  122. package/dist/Interfaces/Email/IOrderConfirmationEmail.d.ts +47 -47
  123. package/dist/Interfaces/Email/IOrderConfirmationEmail.js +2 -2
  124. package/dist/Interfaces/Email/IPasswordResetEmail.d.ts +17 -17
  125. package/dist/Interfaces/Email/IPasswordResetEmail.js +2 -2
  126. package/dist/Interfaces/Email/IPhotoShootEmail.d.ts +14 -14
  127. package/dist/Interfaces/Email/IPhotoShootEmail.js +2 -2
  128. package/dist/Interfaces/Email/IPickupConfirmation.d.ts +23 -23
  129. package/dist/Interfaces/Email/IPickupConfirmation.js +2 -2
  130. package/dist/Interfaces/Email/IShippingConfirmation.d.ts +23 -23
  131. package/dist/Interfaces/Email/IShippingConfirmation.js +2 -2
  132. package/dist/Interfaces/Email/IWelcomeEmail.d.ts +19 -19
  133. package/dist/Interfaces/Email/IWelcomeEmail.js +2 -2
  134. package/dist/Interfaces/ExportSchema/index.d.ts +7 -7
  135. package/dist/Interfaces/ExportSchema/index.js +2 -2
  136. package/dist/Interfaces/ExternalService/BaseExternalService.d.ts +12 -12
  137. package/dist/Interfaces/ExternalService/BaseExternalService.js +2 -2
  138. package/dist/Interfaces/ExternalService/ExternalProductsService.d.ts +4 -4
  139. package/dist/Interfaces/ExternalService/ExternalProductsService.js +2 -2
  140. package/dist/Interfaces/ExternalService/index.d.ts +9 -9
  141. package/dist/Interfaces/ExternalService/index.js +2 -2
  142. package/dist/Interfaces/FirstOrderTracking/index.d.ts +5 -5
  143. package/dist/Interfaces/FirstOrderTracking/index.js +2 -2
  144. package/dist/Interfaces/G2/index.d.ts +557 -557
  145. package/dist/Interfaces/G2/index.js +39 -39
  146. package/dist/Interfaces/Indexed/Product/IIndexedLastSavedProduct.d.ts +20 -20
  147. package/dist/Interfaces/Indexed/Product/IIndexedLastSavedProduct.js +2 -2
  148. package/dist/Interfaces/Indexed/Product/index.d.ts +126 -111
  149. package/dist/Interfaces/Indexed/Product/index.js +372 -302
  150. package/dist/Interfaces/Indexed/Product/index.js.map +1 -1
  151. package/dist/Interfaces/Inventory/index.d.ts +19 -19
  152. package/dist/Interfaces/Inventory/index.js +8 -8
  153. package/dist/Interfaces/Invoice/index.d.ts +4 -4
  154. package/dist/Interfaces/Invoice/index.js +2 -2
  155. package/dist/Interfaces/MarketplacePublication/MarketplaceOrderData.d.ts +3 -3
  156. package/dist/Interfaces/MarketplacePublication/MarketplaceOrderData.js +2 -2
  157. package/dist/Interfaces/MarketplacePublication/index.d.ts +23 -23
  158. package/dist/Interfaces/MarketplacePublication/index.js +22 -22
  159. package/dist/Interfaces/Menu/index.d.ts +40 -40
  160. package/dist/Interfaces/Menu/index.js +16 -16
  161. package/dist/Interfaces/Note/index.d.ts +10 -10
  162. package/dist/Interfaces/Note/index.js +7 -7
  163. package/dist/Interfaces/Operations/ICreatedBy.d.ts +6 -6
  164. package/dist/Interfaces/Operations/ICreatedBy.js +2 -2
  165. package/dist/Interfaces/Operations/IUpdate.d.ts +5 -5
  166. package/dist/Interfaces/Operations/IUpdate.js +2 -2
  167. package/dist/Interfaces/Order/index.d.ts +4 -4
  168. package/dist/Interfaces/Order/index.js +2 -2
  169. package/dist/Interfaces/Org/IRelUser.d.ts +9 -9
  170. package/dist/Interfaces/Org/IRelUser.js +2 -2
  171. package/dist/Interfaces/Org/index.d.ts +29 -29
  172. package/dist/Interfaces/Org/index.js +12 -12
  173. package/dist/Interfaces/Payment/index.d.ts +26 -26
  174. package/dist/Interfaces/Payment/index.js +14 -14
  175. package/dist/Interfaces/Product/IAttributeFamily.d.ts +6 -6
  176. package/dist/Interfaces/Product/IAttributeFamily.js +2 -2
  177. package/dist/Interfaces/Product/IImportProduct.d.ts +42 -42
  178. package/dist/Interfaces/Product/IImportProduct.js +882 -882
  179. package/dist/Interfaces/Product/IInventoryItem.d.ts +74 -74
  180. package/dist/Interfaces/Product/IInventoryItem.js +38 -38
  181. package/dist/Interfaces/Product/IPricing.d.ts +177 -177
  182. package/dist/Interfaces/Product/IPricing.js +180 -180
  183. package/dist/Interfaces/Product/index.d.ts +137 -137
  184. package/dist/Interfaces/Product/index.js +64 -64
  185. package/dist/Interfaces/ProductAttribute/index.d.ts +11 -11
  186. package/dist/Interfaces/ProductAttribute/index.js +2 -2
  187. package/dist/Interfaces/PromiseToPurchase/BankType.d.ts +41 -41
  188. package/dist/Interfaces/PromiseToPurchase/BankType.js +41 -41
  189. package/dist/Interfaces/PromiseToPurchase/IIndexedBankUsed.d.ts +33 -33
  190. package/dist/Interfaces/PromiseToPurchase/IIndexedBankUsed.js +15 -15
  191. package/dist/Interfaces/PromiseToPurchase/IIndexedCustomerPromiseToPurchase.d.ts +19 -19
  192. package/dist/Interfaces/PromiseToPurchase/IIndexedCustomerPromiseToPurchase.js +2 -2
  193. package/dist/Interfaces/PromiseToPurchase/index.d.ts +50 -50
  194. package/dist/Interfaces/PromiseToPurchase/index.js +13 -13
  195. package/dist/Interfaces/PurchaseOrder/index.d.ts +17 -17
  196. package/dist/Interfaces/PurchaseOrder/index.js +2 -2
  197. package/dist/Interfaces/Query/IBrandQueryOptions.d.ts +11 -11
  198. package/dist/Interfaces/Query/IBrandQueryOptions.js +2 -2
  199. package/dist/Interfaces/Query/ICategoryQueryOptions.d.ts +11 -11
  200. package/dist/Interfaces/Query/ICategoryQueryOptions.js +2 -2
  201. package/dist/Interfaces/Query/IProductQueryOptions.d.ts +16 -16
  202. package/dist/Interfaces/Query/IProductQueryOptions.js +2 -2
  203. package/dist/Interfaces/Quote/index.d.ts +5 -5
  204. package/dist/Interfaces/Quote/index.js +2 -2
  205. package/dist/Interfaces/Refunds/index.d.ts +106 -106
  206. package/dist/Interfaces/Refunds/index.js +2 -2
  207. package/dist/Interfaces/Rules/IDiscountRule.d.ts +156 -156
  208. package/dist/Interfaces/Rules/IDiscountRule.js +114 -114
  209. package/dist/Interfaces/Schedule/index.d.ts +48 -48
  210. package/dist/Interfaces/Schedule/index.js +2 -2
  211. package/dist/Interfaces/Services/IAddServiceResponse.d.ts +4 -4
  212. package/dist/Interfaces/Services/IAddServiceResponse.js +2 -2
  213. package/dist/Interfaces/Services/IService.d.ts +16 -16
  214. package/dist/Interfaces/Services/IService.js +2 -2
  215. package/dist/Interfaces/Services/IServiceSecret.d.ts +8 -8
  216. package/dist/Interfaces/Services/IServiceSecret.js +2 -2
  217. package/dist/Interfaces/Shipping/Shipstation/carriers.d.ts +10 -10
  218. package/dist/Interfaces/Shipping/Shipstation/carriers.js +2 -2
  219. package/dist/Interfaces/Shipping/Shipstation/order.d.ts +227 -227
  220. package/dist/Interfaces/Shipping/Shipstation/order.js +2 -2
  221. package/dist/Interfaces/Shipping/Shipstation/quote.d.ts +31 -31
  222. package/dist/Interfaces/Shipping/Shipstation/quote.js +2 -2
  223. package/dist/Interfaces/Shipping/Shiptime/order.d.ts +54 -54
  224. package/dist/Interfaces/Shipping/Shiptime/order.js +71 -71
  225. package/dist/Interfaces/Shipping/Shiptime/quote.d.ts +111 -111
  226. package/dist/Interfaces/Shipping/Shiptime/quote.js +2 -2
  227. package/dist/Interfaces/Slider/GR.d.ts +114 -114
  228. package/dist/Interfaces/Slider/GR.js +271 -271
  229. package/dist/Interfaces/Slider/index.d.ts +30 -30
  230. package/dist/Interfaces/Slider/index.js +2 -2
  231. package/dist/Interfaces/Space/IExternalService.d.ts +54 -54
  232. package/dist/Interfaces/Space/IExternalService.js +45 -45
  233. package/dist/Interfaces/Space/IMember.d.ts +16 -16
  234. package/dist/Interfaces/Space/IMember.js +9 -9
  235. package/dist/Interfaces/Space/index.d.ts +414 -414
  236. package/dist/Interfaces/Space/index.js +176 -176
  237. package/dist/Interfaces/Specials/gr.d.ts +61 -61
  238. package/dist/Interfaces/Specials/gr.js +2 -2
  239. package/dist/Interfaces/StockNotification/index.d.ts +7 -7
  240. package/dist/Interfaces/StockNotification/index.js +2 -2
  241. package/dist/Interfaces/Store/index.d.ts +63 -63
  242. package/dist/Interfaces/Store/index.js +27 -27
  243. package/dist/Interfaces/Supplier/ICommand.d.ts +11 -11
  244. package/dist/Interfaces/Supplier/ICommand.js +2 -2
  245. package/dist/Interfaces/Supplier/index.d.ts +36 -36
  246. package/dist/Interfaces/Supplier/index.js +24 -24
  247. package/dist/Interfaces/TCG/index.d.ts +200 -200
  248. package/dist/Interfaces/TCG/index.js +59 -59
  249. package/dist/Interfaces/Tag/index.d.ts +18 -18
  250. package/dist/Interfaces/Tag/index.js +2 -2
  251. package/dist/Interfaces/Tax/index.d.ts +13 -13
  252. package/dist/Interfaces/Tax/index.js +2 -2
  253. package/dist/Interfaces/TransferRequest/index.d.ts +103 -103
  254. package/dist/Interfaces/TransferRequest/index.js +46 -46
  255. package/dist/Interfaces/Translation/index.d.ts +8 -8
  256. package/dist/Interfaces/Translation/index.js +5 -5
  257. package/dist/Interfaces/Update/index.d.ts +10 -10
  258. package/dist/Interfaces/Update/index.js +2 -2
  259. package/dist/Interfaces/User/IUser.d.ts +65 -65
  260. package/dist/Interfaces/User/IUser.js +8 -8
  261. package/dist/Interfaces/Version/index.d.ts +11 -11
  262. package/dist/Interfaces/Version/index.js +2 -2
  263. package/dist/Interfaces/Wishlist/index.d.ts +7 -7
  264. package/dist/Interfaces/Wishlist/index.js +2 -2
  265. package/dist/constants/Interfaces/IBaseApi.d.ts +15 -15
  266. package/dist/constants/Interfaces/IBaseApi.js +2 -2
  267. package/dist/constants/Interfaces/IEndpointResult.d.ts +9 -9
  268. package/dist/constants/Interfaces/IEndpointResult.js +2 -2
  269. package/dist/constants/enums.d.ts +6 -6
  270. package/dist/constants/enums.js +10 -10
  271. package/dist/constants/services.d.ts +2 -2
  272. package/dist/constants/services.js +122 -122
  273. package/dist/constants/version.d.ts +2 -2
  274. package/dist/constants/version.js +5 -5
  275. package/dist/index.d.ts +50 -50
  276. package/dist/index.js +266 -266
  277. package/dist/lib/Attribute/index.d.ts +14 -14
  278. package/dist/lib/Attribute/index.js +186 -186
  279. package/dist/lib/BGJob/index.d.ts +9 -9
  280. package/dist/lib/BGJob/index.js +216 -216
  281. package/dist/lib/BackgroundWorker/index.d.ts +34 -34
  282. package/dist/lib/BackgroundWorker/index.js +59 -59
  283. package/dist/lib/Blog/BlogArticle.d.ts +5 -5
  284. package/dist/lib/Blog/BlogArticle.js +10 -10
  285. package/dist/lib/Blog/BlogAuthor.d.ts +5 -5
  286. package/dist/lib/Blog/BlogAuthor.js +10 -10
  287. package/dist/lib/Blog/BlogCategory.d.ts +5 -5
  288. package/dist/lib/Blog/BlogCategory.js +10 -10
  289. package/dist/lib/Blog/BlogKeyword.d.ts +5 -5
  290. package/dist/lib/Blog/BlogKeyword.js +10 -10
  291. package/dist/lib/Booking/index.d.ts +85 -85
  292. package/dist/lib/Booking/index.js +596 -596
  293. package/dist/lib/Brand/index.d.ts +26 -26
  294. package/dist/lib/Brand/index.js +131 -131
  295. package/dist/lib/Cart/index.d.ts +357 -357
  296. package/dist/lib/Cart/index.js +4052 -4052
  297. package/dist/lib/CartReservedQuantities/index.d.ts +49 -49
  298. package/dist/lib/CartReservedQuantities/index.js +159 -159
  299. package/dist/lib/CashDrawerShift/index.d.ts +84 -84
  300. package/dist/lib/CashDrawerShift/index.js +206 -206
  301. package/dist/lib/Catalogue/index.d.ts +15 -15
  302. package/dist/lib/Catalogue/index.js +78 -78
  303. package/dist/lib/Category/index.d.ts +34 -34
  304. package/dist/lib/Category/index.js +230 -230
  305. package/dist/lib/Class/index.d.ts +16 -16
  306. package/dist/lib/Class/index.js +66 -66
  307. package/dist/lib/Consent/index.d.ts +4 -4
  308. package/dist/lib/Consent/index.js +29 -29
  309. package/dist/lib/Customer/index.d.ts +30 -30
  310. package/dist/lib/Customer/index.js +92 -92
  311. package/dist/lib/Declination/index.d.ts +9 -9
  312. package/dist/lib/Declination/index.js +26 -26
  313. package/dist/lib/Discount/index.d.ts +27 -27
  314. package/dist/lib/Discount/index.js +493 -493
  315. package/dist/lib/ElasticSearch/index.d.ts +13 -13
  316. package/dist/lib/ElasticSearch/index.js +50 -50
  317. package/dist/lib/Elavon/index.d.ts +18 -18
  318. package/dist/lib/Elavon/index.js +135 -135
  319. package/dist/lib/Email/AbandonedCartEmail.d.ts +16 -16
  320. package/dist/lib/Email/AbandonedCartEmail.js +24 -24
  321. package/dist/lib/Email/AccountConfirmationEmail.d.ts +19 -19
  322. package/dist/lib/Email/AccountConfirmationEmail.js +30 -30
  323. package/dist/lib/Email/AdminOrderConfirmationEmail.d.ts +16 -16
  324. package/dist/lib/Email/AdminOrderConfirmationEmail.js +24 -24
  325. package/dist/lib/Email/ApplicationEmail.d.ts +16 -16
  326. package/dist/lib/Email/ApplicationEmail.js +24 -24
  327. package/dist/lib/Email/BackInStockEmail.d.ts +16 -16
  328. package/dist/lib/Email/BackInStockEmail.js +24 -24
  329. package/dist/lib/Email/ContactEmail.d.ts +16 -16
  330. package/dist/lib/Email/ContactEmail.js +24 -24
  331. package/dist/lib/Email/CustomerBookingAdminEmail.d.ts +16 -16
  332. package/dist/lib/Email/CustomerBookingAdminEmail.js +24 -24
  333. package/dist/lib/Email/CustomerBookingEmail.d.ts +16 -16
  334. package/dist/lib/Email/CustomerBookingEmail.js +24 -24
  335. package/dist/lib/Email/OrderConfirmationEmail.d.ts +16 -16
  336. package/dist/lib/Email/OrderConfirmationEmail.js +24 -24
  337. package/dist/lib/Email/OrderDenounciationEmail.d.ts +16 -16
  338. package/dist/lib/Email/OrderDenounciationEmail.js +24 -24
  339. package/dist/lib/Email/OrderSampleEmail.d.ts +16 -16
  340. package/dist/lib/Email/OrderSampleEmail.js +24 -24
  341. package/dist/lib/Email/OtherTypeEmails.d.ts +16 -16
  342. package/dist/lib/Email/OtherTypeEmails.js +27 -27
  343. package/dist/lib/Email/PasswordResetEmail.d.ts +16 -16
  344. package/dist/lib/Email/PasswordResetEmail.js +24 -24
  345. package/dist/lib/Email/PhotoShootEmail.d.ts +16 -16
  346. package/dist/lib/Email/PhotoShootEmail.js +24 -24
  347. package/dist/lib/Email/PickUpConfirmation.d.ts +16 -16
  348. package/dist/lib/Email/PickUpConfirmation.js +24 -24
  349. package/dist/lib/Email/ShippingConfirmation.d.ts +16 -16
  350. package/dist/lib/Email/ShippingConfirmation.js +24 -24
  351. package/dist/lib/Email/WelcomeEmail.d.ts +16 -16
  352. package/dist/lib/Email/WelcomeEmail.js +24 -24
  353. package/dist/lib/Email/index.d.ts +16 -16
  354. package/dist/lib/Email/index.js +31 -31
  355. package/dist/lib/ExternalService/Ebay.d.ts +74 -74
  356. package/dist/lib/ExternalService/Ebay.js +124 -124
  357. package/dist/lib/ExternalService/index.d.ts +5 -5
  358. package/dist/lib/ExternalService/index.js +10 -10
  359. package/dist/lib/FirstOrderTracking/index.d.ts +5 -5
  360. package/dist/lib/FirstOrderTracking/index.js +10 -10
  361. package/dist/lib/Indexed/IndexedCart.d.ts +13 -13
  362. package/dist/lib/Indexed/IndexedCart.js +91 -91
  363. package/dist/lib/Indexed/Product.d.ts +17 -17
  364. package/dist/lib/Indexed/Product.js +98 -98
  365. package/dist/lib/Inventory/index.d.ts +131 -131
  366. package/dist/lib/Inventory/index.js +545 -545
  367. package/dist/lib/Invoice/index.d.ts +16 -16
  368. package/dist/lib/Invoice/index.js +21 -21
  369. package/dist/lib/MarketplacePublication/index.d.ts +9 -9
  370. package/dist/lib/MarketplacePublication/index.js +426 -426
  371. package/dist/lib/Menu/index.d.ts +11 -11
  372. package/dist/lib/Menu/index.js +107 -107
  373. package/dist/lib/MongoDB/BaseAPI.d.ts +18 -18
  374. package/dist/lib/MongoDB/BaseAPI.js +200 -200
  375. package/dist/lib/Note/index.d.ts +4 -4
  376. package/dist/lib/Note/index.js +6 -6
  377. package/dist/lib/Order/index.d.ts +27 -27
  378. package/dist/lib/Order/index.js +56 -56
  379. package/dist/lib/Org/index.d.ts +68 -68
  380. package/dist/lib/Org/index.js +216 -216
  381. package/dist/lib/PandaPay/index.d.ts +16 -16
  382. package/dist/lib/PandaPay/index.js +176 -176
  383. package/dist/lib/Paysafe/index.d.ts +11 -11
  384. package/dist/lib/Paysafe/index.js +41 -41
  385. package/dist/lib/Product/index.d.ts +182 -182
  386. package/dist/lib/Product/index.js +847 -847
  387. package/dist/lib/ProductAttribute/index.d.ts +15 -15
  388. package/dist/lib/ProductAttribute/index.js +45 -45
  389. package/dist/lib/PromiseToPurchase/index.d.ts +109 -109
  390. package/dist/lib/PromiseToPurchase/index.js +343 -343
  391. package/dist/lib/PurchaseOrder/index.d.ts +20 -20
  392. package/dist/lib/PurchaseOrder/index.js +28 -28
  393. package/dist/lib/Schedule/index.d.ts +5 -5
  394. package/dist/lib/Schedule/index.js +12 -12
  395. package/dist/lib/Service/Enum/ServiceEnum.d.ts +3 -3
  396. package/dist/lib/Service/Enum/ServiceEnum.js +7 -7
  397. package/dist/lib/Service/index.d.ts +13 -13
  398. package/dist/lib/Service/index.js +21 -21
  399. package/dist/lib/Shipment/index.d.ts +28 -28
  400. package/dist/lib/Shipment/index.js +370 -370
  401. package/dist/lib/Slider/index.d.ts +22 -22
  402. package/dist/lib/Slider/index.js +119 -119
  403. package/dist/lib/Space/index.d.ts +1181 -1181
  404. package/dist/lib/Space/index.js +5860 -5856
  405. package/dist/lib/Space/index.js.map +1 -1
  406. package/dist/lib/StockNotification/index.d.ts +4 -4
  407. package/dist/lib/StockNotification/index.js +6 -6
  408. package/dist/lib/Store/index.d.ts +5 -5
  409. package/dist/lib/Store/index.js +12 -12
  410. package/dist/lib/Supplier/Command.d.ts +5 -5
  411. package/dist/lib/Supplier/Command.js +10 -10
  412. package/dist/lib/Supplier/index.d.ts +25 -25
  413. package/dist/lib/Supplier/index.js +27 -27
  414. package/dist/lib/Tags/index.d.ts +6 -6
  415. package/dist/lib/Tags/index.js +26 -26
  416. package/dist/lib/Tax/index.d.ts +8 -8
  417. package/dist/lib/Tax/index.js +54 -54
  418. package/dist/lib/TransferRequest/index.d.ts +298 -298
  419. package/dist/lib/TransferRequest/index.js +1106 -1106
  420. package/dist/lib/Update/index.d.ts +10 -10
  421. package/dist/lib/Update/index.js +22 -22
  422. package/dist/lib/User/index.d.ts +89 -89
  423. package/dist/lib/User/index.js +328 -328
  424. package/dist/lib/Wishlist/index.d.ts +5 -5
  425. package/dist/lib/Wishlist/index.js +10 -10
  426. package/dist/lib/base.d.ts +14 -14
  427. package/dist/lib/base.js +62 -62
  428. package/dist/lib/baseService.d.ts +17 -17
  429. package/dist/lib/baseService.js +69 -69
  430. package/dist/rules/ADD/utils/buyback.d.ts +4 -4
  431. package/dist/rules/ADD/utils/buyback.js +135 -135
  432. package/dist/rules/GR/constants/data.d.ts +26 -26
  433. package/dist/rules/GR/constants/data.js +81 -81
  434. package/dist/rules/GR/constants/expedition.d.ts +4 -4
  435. package/dist/rules/GR/constants/expedition.js +9 -9
  436. package/dist/rules/GR/constants/products.d.ts +27 -22
  437. package/dist/rules/GR/constants/products.js +272 -263
  438. package/dist/rules/GR/constants/products.js.map +1 -1
  439. package/dist/rules/GR/interfaces/cart.d.ts +85 -84
  440. package/dist/rules/GR/interfaces/cart.js +42 -41
  441. package/dist/rules/GR/interfaces/cart.js.map +1 -1
  442. package/dist/rules/GR/interfaces/data.d.ts +101 -101
  443. package/dist/rules/GR/interfaces/data.js +114 -114
  444. package/dist/rules/GR/interfaces/products.d.ts +61 -61
  445. package/dist/rules/GR/interfaces/products.js +10 -10
  446. package/dist/rules/GR/utils/cart.d.ts +95 -95
  447. package/dist/rules/GR/utils/cart.js +879 -839
  448. package/dist/rules/GR/utils/cart.js.map +1 -1
  449. package/dist/rules/GR/utils/data.d.ts +3 -3
  450. package/dist/rules/GR/utils/data.js +28 -28
  451. package/dist/rules/GR/utils/expedition.d.ts +140 -140
  452. package/dist/rules/GR/utils/expedition.js +2098 -2017
  453. package/dist/rules/GR/utils/expedition.js.map +1 -1
  454. package/dist/rules/GR/utils/g2.d.ts +209 -209
  455. package/dist/rules/GR/utils/g2.js +1002 -1002
  456. package/dist/rules/GR/utils/invoices.d.ts +51 -51
  457. package/dist/rules/GR/utils/invoices.js +218 -215
  458. package/dist/rules/GR/utils/invoices.js.map +1 -1
  459. package/dist/rules/GR/utils/products.d.ts +277 -277
  460. package/dist/rules/GR/utils/products.js +1358 -1350
  461. package/dist/rules/GR/utils/products.js.map +1 -1
  462. package/dist/rules/GR/utils/upsells.d.ts +113 -111
  463. package/dist/rules/GR/utils/upsells.js +215 -215
  464. package/dist/services/database/BaseProvider.d.ts +29 -29
  465. package/dist/services/database/BaseProvider.js +28 -28
  466. package/dist/services/database/BatchUtils.d.ts +14 -14
  467. package/dist/services/database/BatchUtils.js +43 -43
  468. package/dist/services/database/Config.d.ts +2 -2
  469. package/dist/services/database/Config.js +5 -5
  470. package/dist/services/database/DatabaseService.d.ts +125 -125
  471. package/dist/services/database/DatabaseService.js +237 -237
  472. package/dist/services/database/FirebaseProvider.d.ts +17 -17
  473. package/dist/services/database/FirebaseProvider.js +235 -235
  474. package/dist/services/database/NotFirebaseProvider.d.ts +49 -49
  475. package/dist/services/database/NotFirebaseProvider.js +262 -262
  476. package/dist/services/g2/G2OrderSlip.d.ts +49 -49
  477. package/dist/services/g2/G2OrderSlip.js +228 -228
  478. package/dist/services/g2/utils.d.ts +19 -19
  479. package/dist/services/g2/utils.js +969 -968
  480. package/dist/services/g2/utils.js.map +1 -1
  481. package/dist/services/logs/index.d.ts +23 -23
  482. package/dist/services/logs/index.js +66 -66
  483. package/dist/services/marketplace/BaseMarketServiceClass.d.ts +78 -78
  484. package/dist/services/marketplace/BaseMarketServiceClass.js +141 -141
  485. package/dist/services/marketplace/CardtraderServiceClass.d.ts +38 -38
  486. package/dist/services/marketplace/CardtraderServiceClass.js +226 -226
  487. package/dist/services/marketplace/utils.d.ts +17 -17
  488. package/dist/services/marketplace/utils.js +32 -32
  489. package/dist/services/products/BaseClass.d.ts +79 -79
  490. package/dist/services/products/BaseClass.js +144 -144
  491. package/dist/services/products/TCGService.d.ts +29 -29
  492. package/dist/services/products/TCGService.js +503 -503
  493. package/dist/services/products/utils.d.ts +31 -31
  494. package/dist/services/products/utils.js +144 -144
  495. package/dist/utils/algolia.d.ts +46 -46
  496. package/dist/utils/algolia.js +21 -21
  497. package/dist/utils/anonymisation.d.ts +54 -54
  498. package/dist/utils/anonymisation.js +280 -280
  499. package/dist/utils/array.d.ts +5 -5
  500. package/dist/utils/array.js +14 -14
  501. package/dist/utils/aws.d.ts +36 -36
  502. package/dist/utils/aws.js +154 -154
  503. package/dist/utils/booking.d.ts +30 -30
  504. package/dist/utils/booking.js +127 -127
  505. package/dist/utils/cart.d.ts +279 -274
  506. package/dist/utils/cart.js +1152 -1143
  507. package/dist/utils/cart.js.map +1 -1
  508. package/dist/utils/categories.d.ts +2 -2
  509. package/dist/utils/categories.js +54 -54
  510. package/dist/utils/cmv.d.ts +12 -12
  511. package/dist/utils/cmv.js +108 -108
  512. package/dist/utils/console.d.ts +6 -6
  513. package/dist/utils/console.js +59 -59
  514. package/dist/utils/context.d.ts +20 -20
  515. package/dist/utils/context.js +61 -61
  516. package/dist/utils/currency.d.ts +6 -6
  517. package/dist/utils/currency.js +91 -91
  518. package/dist/utils/data.d.ts +31 -31
  519. package/dist/utils/data.js +302 -302
  520. package/dist/utils/date.d.ts +1 -1
  521. package/dist/utils/date.js +16 -16
  522. package/dist/utils/dimensions.d.ts +3 -3
  523. package/dist/utils/dimensions.js +16 -16
  524. package/dist/utils/discount.d.ts +192 -192
  525. package/dist/utils/discount.js +1180 -1180
  526. package/dist/utils/errors.d.ts +133 -133
  527. package/dist/utils/errors.js +171 -171
  528. package/dist/utils/file-admin.d.ts +8 -8
  529. package/dist/utils/file-admin.js +39 -39
  530. package/dist/utils/file.d.ts +39 -39
  531. package/dist/utils/file.js +208 -208
  532. package/dist/utils/firebase-admin.d.ts +11 -11
  533. package/dist/utils/firebase-admin.js +73 -73
  534. package/dist/utils/firebase.d.ts +58 -58
  535. package/dist/utils/firebase.js +148 -148
  536. package/dist/utils/import.d.ts +1 -1
  537. package/dist/utils/import.js +21 -21
  538. package/dist/utils/inventories.d.ts +101 -101
  539. package/dist/utils/inventories.js +467 -467
  540. package/dist/utils/locale.d.ts +24 -24
  541. package/dist/utils/locale.js +91 -91
  542. package/dist/utils/mailchimp.d.ts +58 -58
  543. package/dist/utils/mailchimp.js +531 -531
  544. package/dist/utils/mathUtils.d.ts +17 -17
  545. package/dist/utils/mathUtils.js +324 -324
  546. package/dist/utils/mongodb.d.ts +1 -1
  547. package/dist/utils/mongodb.js +22 -22
  548. package/dist/utils/object.d.ts +32 -32
  549. package/dist/utils/object.js +133 -133
  550. package/dist/utils/payment.d.ts +10 -10
  551. package/dist/utils/payment.js +23 -23
  552. package/dist/utils/products.d.ts +47 -47
  553. package/dist/utils/products.js +214 -214
  554. package/dist/utils/promiseToPurchase.d.ts +121 -121
  555. package/dist/utils/promiseToPurchase.js +329 -329
  556. package/dist/utils/prosprsearch.d.ts +42 -42
  557. package/dist/utils/prosprsearch.js +216 -216
  558. package/dist/utils/refunds.d.ts +2 -2
  559. package/dist/utils/refunds.js +21 -21
  560. package/dist/utils/sdc.d.ts +10 -10
  561. package/dist/utils/sdc.js +1309 -1309
  562. package/dist/utils/searchIndexes.d.ts +58 -58
  563. package/dist/utils/searchIndexes.js +247 -247
  564. package/dist/utils/services.d.ts +44 -44
  565. package/dist/utils/services.js +415 -415
  566. package/dist/utils/shipment.d.ts +110 -110
  567. package/dist/utils/shipment.js +341 -345
  568. package/dist/utils/shipment.js.map +1 -1
  569. package/dist/utils/simpletexting.d.ts +2 -2
  570. package/dist/utils/simpletexting.js +45 -45
  571. package/dist/utils/sliders.d.ts +4 -4
  572. package/dist/utils/sliders.js +24 -24
  573. package/dist/utils/string.d.ts +16 -16
  574. package/dist/utils/string.js +192 -192
  575. package/dist/utils/tcgService.d.ts +129 -129
  576. package/dist/utils/tcgService.js +494 -494
  577. package/dist/utils/tools.d.ts +5 -5
  578. package/dist/utils/tools.js +13 -13
  579. package/dist/utils/transferRequests.d.ts +43 -43
  580. package/dist/utils/transferRequests.js +67 -67
  581. package/dist/utils/update.d.ts +7 -7
  582. package/dist/utils/update.js +137 -137
  583. package/dist/utils/weight.d.ts +3 -3
  584. package/dist/utils/weight.js +16 -16
  585. package/dist/utils/zones.d.ts +11 -11
  586. package/dist/utils/zones.js +218 -218
  587. package/package.json +107 -107
  588. package/publish.sh +143 -143
  589. package/readme.md +182 -182
@@ -1,1181 +1,1181 @@
1
- "use strict";
2
- var __rest = (this && this.__rest) || function (s, e) {
3
- var t = {};
4
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
5
- t[p] = s[p];
6
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
7
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
8
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
9
- t[p[i]] = s[p[i]];
10
- }
11
- return t;
12
- };
13
- var __importDefault = (this && this.__importDefault) || function (mod) {
14
- return (mod && mod.__esModule) ? mod : { "default": mod };
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.getPaymentIncentiveDiscount = exports.getPaymentIncentiveDiscountInfo = exports.getAfterTaxesPromoInCart = exports.getAfterTaxesPromosTotalAmount = exports.checkIfCouldApplyIncentivePromo = exports.getOnlyServicesAndFeesSubtotal = exports.getExcludedItemsSubtotal = exports.getStandardCartPromoFromDiscount = exports.applyDiscountToCart = exports.checkIfCanAddPromo = exports.getItemCategorySlugArray = exports.getResultAppliedDiscountSkus = exports.getSkuArrayForPromo = exports.applyDiscountToPrice = exports.applyDiscountRulesOnProduct = exports.getNewDiscountPriceFromTierPricing = exports.applyTierPricing = exports.getTierPricingToApply = exports.checkPromoCodeEligibility = exports.hasApplicableItemsForPromoExclusions = exports.getCartPromoType = exports.checkAttributes = exports.getResultRuleDetail = exports.shouldApplyRuleToDeclination = exports.getAppliedAmountsForSubtotalPromosOnCart = exports.getCartPromosByAppliesTo = exports.getSubtotalWithoutProductPromos = exports.isPromoAPercentage = exports.shouldCheckPromoCode = exports.getCartPromo = void 0;
18
- const IDiscountRule_1 = require("../Interfaces/Rules/IDiscountRule");
19
- const Cart_1 = require("../Interfaces/Cart");
20
- const flatten_1 = __importDefault(require("lodash/flatten"));
21
- const round_1 = __importDefault(require("lodash/round"));
22
- const sumBy_1 = __importDefault(require("lodash/sumBy"));
23
- const toNumber_1 = __importDefault(require("lodash/toNumber"));
24
- const orderBy_1 = __importDefault(require("lodash/orderBy"));
25
- const locale_1 = require("./locale");
26
- const currency_1 = require("./currency");
27
- const moment_1 = __importDefault(require("moment"));
28
- const data_1 = require("./data");
29
- const products_1 = require("./products");
30
- const cart_1 = require("../rules/GR/utils/cart");
31
- const cart_2 = require("../rules/GR/interfaces/cart");
32
- const object_1 = require("./object");
33
- const data_2 = require("../rules/GR/constants/data");
34
- const g2_1 = require("../rules/GR/utils/g2");
35
- // -----------------------------------------------------------------------------------
36
- // #region GENERAL
37
- /**
38
- * Get formatted array of cart promos applied to a specific cart
39
- * @param cartData
40
- */
41
- const getCartPromo = (cartData) => {
42
- if (!!!cartData.cart_promo_applied && !!!cartData.cart_promos_applied)
43
- return;
44
- return !!cartData.cart_promo_applied
45
- ? [cartData.cart_promo_applied]
46
- : !!cartData.cart_promos_applied
47
- ? cartData.cart_promos_applied
48
- : [];
49
- };
50
- exports.getCartPromo = getCartPromo;
51
- /**
52
- * Check if current cart promos applied contain a promo_code type promotion
53
- * @param cartData
54
- */
55
- const shouldCheckPromoCode = (cartData) => {
56
- return ((!!cartData.cart_promos_applied && !!cartData.cart_promos_applied.some((p) => p.promo_code)) ||
57
- (!!cartData.cart_promo_applied && !!cartData.cart_promo_applied.promo_code));
58
- };
59
- exports.shouldCheckPromoCode = shouldCheckPromoCode;
60
- /**
61
- * Check if promo is expressed as a percentage
62
- * @param promo The promo to check. Works for cart applied promo as well as discount rule
63
- * @param options.includePaymentIncentiveInCheck Optionnal. If payement incentive promotions should also be included in check
64
- * @returns {boolean}
65
- */
66
- const isPromoAPercentage = (promo, options = {}) => {
67
- const promoPercentOptions = [
68
- IDiscountRule_1.ResultActionEnum.PERCENT,
69
- IDiscountRule_1.ResultActionEnum.PERCENT_CATEGORY,
70
- IDiscountRule_1.ResultActionEnum.PERCENT_SKU
71
- ];
72
- if (options.includePaymentIncentiveInCheck)
73
- promoPercentOptions.push(IDiscountRule_1.ResultActionEnum.PERCENT_AFTER_TAXES);
74
- let propertyToCheck = (0, object_1.recursiveCheckObject)(promo, 'result.action') || (0, object_1.recursiveCheckObject)(promo, 'amount_unit');
75
- if (!!!propertyToCheck && options.defaultToPercent)
76
- propertyToCheck = IDiscountRule_1.ResultActionEnum.PERCENT;
77
- return !!propertyToCheck && promoPercentOptions.includes(propertyToCheck);
78
- };
79
- exports.isPromoAPercentage = isPromoAPercentage;
80
- const getSubtotalWithoutProductPromos = (cartData, itemPromos) => {
81
- const currentSubtotal = cartData.subtotalWithoutPromotions || cartData.subtotal;
82
- let allProductSubtotalAmounts = (0, sumBy_1.default)(itemPromos, (i) => !!(0, data_1.getPromoTotalAmount)(cartData.items, i, 'number')
83
- ? (0, data_1.getPromoTotalAmount)(cartData.items, i, 'number')
84
- : 0);
85
- return currentSubtotal - allProductSubtotalAmounts;
86
- };
87
- exports.getSubtotalWithoutProductPromos = getSubtotalWithoutProductPromos;
88
- const getCartPromosByAppliesTo = (cartData) => {
89
- const appliedPromos = (0, exports.getCartPromo)(cartData) || [];
90
- let subtotalPromos = appliedPromos.filter((p) => p.applies_to == Cart_1.CartPromoAppliesToEnum.SUBTOTAL);
91
- let itemPromos = appliedPromos.filter((p) => p.applies_to == Cart_1.CartPromoAppliesToEnum.PRODUCT);
92
- let afterTaxesPromos = appliedPromos.filter((p) => p.applies_to == Cart_1.CartPromoAppliesToEnum.TOTAL_AFTER_TAXES);
93
- return {
94
- subtotal: subtotalPromos,
95
- items: itemPromos,
96
- afterTaxes: afterTaxesPromos
97
- };
98
- };
99
- exports.getCartPromosByAppliesTo = getCartPromosByAppliesTo;
100
- const getAppliedAmountsForSubtotalPromosOnCart = (cartData) => {
101
- const activePromos = (0, exports.getCartPromosByAppliesTo)(cartData);
102
- let currentSubtotal = (0, exports.getSubtotalWithoutProductPromos)(cartData, activePromos.items);
103
- let promoAmounts = {};
104
- for (let promo of activePromos.subtotal.filter((p) => !!p.discount_id)) {
105
- if (!!!promo.amount_removed)
106
- continue;
107
- let amountRemoved = promo.amount_removed;
108
- const excludedTotal = !!promo.exclude_services_and_fees || !!promo.exclude_discounted_products
109
- ? (0, exports.getExcludedItemsSubtotal)(cartData.items, activePromos.items, {
110
- excludeServices: !!promo.exclude_services_and_fees,
111
- excludeDiscounted: !!promo.exclude_discounted_products
112
- })
113
- : 0;
114
- if ((0, exports.isPromoAPercentage)(promo, { defaultToPercent: true })) {
115
- // Excludes fees/services and/or already discounted products from the calculation based on the promotion option
116
- amountRemoved = (0, round_1.default)((promo.amount_removed / 100) * (currentSubtotal - excludedTotal), 3);
117
- }
118
- promoAmounts[promo.discount_id] = amountRemoved;
119
- currentSubtotal -= amountRemoved;
120
- }
121
- return promoAmounts;
122
- };
123
- exports.getAppliedAmountsForSubtotalPromosOnCart = getAppliedAmountsForSubtotalPromosOnCart;
124
- // #endregion
125
- // -----------------------------------------------------------------------------------
126
- // #region CHECK DISCOUNT ELIGIBILITY
127
- /**
128
- * Check if a discount rule applies to a specific declination
129
- * @param discount_rule - The discount rule to check
130
- * @param declination - The declination to compare
131
- * @param parentSlug - Optionnal. Used to check parent product slug with 'product' rule specifications. If not provided and 'product' rule found, returns true by default for rule check
132
- */
133
- const shouldApplyRuleToDeclination = (discount_rule, declination, parentSlug) => {
134
- // If discount has no rules, it means it applies to declination automatically
135
- if (!!!discount_rule.rules || !!!discount_rule.rules.length)
136
- return true;
137
- const currentDiscountMap = discount_rule.rules.map((rule) => {
138
- const todayDate = (0, moment_1.default)().format('YYYY-MM-DD');
139
- switch (rule.field) {
140
- case IDiscountRule_1.RuleFieldEnum.PRODUCT_PRICE:
141
- return (0, flatten_1.default)(rule.ruleDetails.map((ruleDetail) => {
142
- return [rule.condition, (0, exports.getResultRuleDetail)(ruleDetail, declination.price.regular.amount)];
143
- }));
144
- case IDiscountRule_1.RuleFieldEnum.SKU:
145
- return (0, flatten_1.default)(rule.ruleDetails.map((ruleDetail) => {
146
- return [rule.condition, (0, exports.getResultRuleDetail)(ruleDetail, declination.sku)];
147
- }));
148
- case IDiscountRule_1.RuleFieldEnum.DECLINATION:
149
- // case 'slug':
150
- return (0, flatten_1.default)(rule.ruleDetails.map((ruleDetail) => {
151
- return [rule.condition, declination.sku === ruleDetail.value[0]];
152
- }));
153
- case IDiscountRule_1.RuleFieldEnum.PRODUCT:
154
- return (0, flatten_1.default)(rule.ruleDetails.map((ruleDetail) => {
155
- return [rule.condition, !!!parentSlug || (0, exports.getResultRuleDetail)(ruleDetail, parentSlug)];
156
- }));
157
- case IDiscountRule_1.RuleFieldEnum.DATE:
158
- case IDiscountRule_1.RuleFieldEnum.WEEKDAY:
159
- return (0, flatten_1.default)(rule.ruleDetails.map((ruleDetail) => {
160
- return [rule.condition, (0, exports.getResultRuleDetail)(ruleDetail, (0, moment_1.default)(todayDate).toDate())];
161
- }));
162
- case IDiscountRule_1.RuleFieldEnum.ATTRIBUTE:
163
- return (0, flatten_1.default)(rule.ruleDetails.map((ruleDetail) => {
164
- return [rule.condition, (0, exports.checkAttributes)(ruleDetail, declination.attributes)];
165
- }));
166
- default:
167
- return [IDiscountRule_1.RuleConditionEnum.AND, true];
168
- }
169
- });
170
- return _checkRuleApplicationArray(currentDiscountMap);
171
- };
172
- exports.shouldApplyRuleToDeclination = shouldApplyRuleToDeclination;
173
- /**
174
- * Check if a specific rule of a discount rule is respected
175
- * @param ruleDetail - The rule details object to check
176
- * @param cartValue - The value to compare with rule specifications
177
- */
178
- const getResultRuleDetail = (ruleDetail, cartValue, log) => {
179
- let ruleRespected = false;
180
- let isDate = false;
181
- try {
182
- let amountValue;
183
- let amountValue2;
184
- switch (true) {
185
- case typeof cartValue === 'number':
186
- if (ruleDetail.operator === 'between') {
187
- amountValue = Number(ruleDetail.value[0].toString().replace(',', '.')) || [];
188
- amountValue2 = Number(ruleDetail.value[1].toString().replace(',', '.')) || [];
189
- }
190
- else {
191
- amountValue = ruleDetail.value.map((v) => Number(v.toString().replace(',', '.'))) || [];
192
- amountValue2 = 0 || [];
193
- }
194
- break;
195
- case typeof cartValue === 'string' && !!!moment_1.default.isDate((0, data_1.formatDate)(cartValue)):
196
- if (ruleDetail.operator === 'between') {
197
- amountValue = ruleDetail.value[0] || [];
198
- amountValue2 = ruleDetail.value[1] || [];
199
- }
200
- else {
201
- amountValue2 = [];
202
- amountValue = ruleDetail.value || [];
203
- }
204
- break;
205
- default:
206
- if (!!log)
207
- console.log('HERE!');
208
- cartValue = (0, data_1.formatDate)(cartValue);
209
- if (typeof ruleDetail.value[0] === 'number') {
210
- if ((0, moment_1.default)(cartValue).isValid())
211
- cartValue = (0, moment_1.default)(cartValue).day();
212
- amountValue = ruleDetail.value || [];
213
- }
214
- else {
215
- isDate = true;
216
- amountValue = (0, moment_1.default)(ruleDetail.value[0]);
217
- if (!!ruleDetail.value[1] && moment_1.default.isDate(ruleDetail.value[1])) {
218
- amountValue2 = (0, moment_1.default)(ruleDetail.value[1]);
219
- }
220
- else {
221
- amountValue2 = (0, moment_1.default)();
222
- }
223
- switch (ruleDetail.operator) {
224
- case '==':
225
- ruleRespected = amountValue.isSame((0, moment_1.default)(cartValue), 'date');
226
- break;
227
- case '!=':
228
- ruleRespected = !!!amountValue.isSame((0, moment_1.default)(cartValue), 'date');
229
- break;
230
- case '<=':
231
- ruleRespected = (0, moment_1.default)(cartValue).isSameOrBefore(amountValue, 'date');
232
- break;
233
- case '>=':
234
- ruleRespected = (0, moment_1.default)(cartValue).isSameOrAfter(amountValue, 'date');
235
- break;
236
- case '<':
237
- ruleRespected = (0, moment_1.default)(cartValue).isBefore(amountValue, 'date');
238
- break;
239
- case '>':
240
- ruleRespected = (0, moment_1.default)(cartValue).isAfter(amountValue, 'date');
241
- break;
242
- case 'between':
243
- ruleRespected = (0, moment_1.default)(cartValue).isBetween(amountValue, amountValue2, 'date', '[]');
244
- break;
245
- case 'contains':
246
- default:
247
- ruleRespected = false;
248
- }
249
- }
250
- }
251
- if (!!!isDate) {
252
- if (!Array.isArray(amountValue) && ruleDetail.operator !== 'between') {
253
- amountValue = [amountValue];
254
- }
255
- switch (ruleDetail.operator) {
256
- case '==':
257
- ruleRespected = !!amountValue.some((v) => v === cartValue);
258
- break;
259
- case '!=':
260
- ruleRespected = !!amountValue.every((v) => v !== cartValue);
261
- break;
262
- case '<=':
263
- ruleRespected = !!amountValue.some((v) => cartValue <= v);
264
- break;
265
- case '>=':
266
- ruleRespected = !!amountValue.some((v) => cartValue >= v);
267
- break;
268
- case '<':
269
- ruleRespected = !!amountValue.some((v) => cartValue < v);
270
- break;
271
- case '>':
272
- ruleRespected = !!amountValue.some((v) => cartValue > v);
273
- break;
274
- case 'between':
275
- ruleRespected = cartValue > amountValue && cartValue < amountValue2;
276
- break;
277
- case 'contains':
278
- ruleRespected = !!amountValue.some((v) => cartValue.toString().indexOf(v.toString()) !== -1);
279
- break;
280
- case 'contains-not':
281
- ruleRespected = !!!amountValue.some((v) => cartValue.toString().indexOf(v.toString()) !== -1);
282
- break;
283
- }
284
- }
285
- }
286
- catch (error) {
287
- console.log(error.toString());
288
- }
289
- return ruleRespected;
290
- };
291
- exports.getResultRuleDetail = getResultRuleDetail;
292
- /**
293
- * Check if rule applied to product attributes is respected for specific declination attributes
294
- * @param attributeAndValues - The rule details object to check
295
- * @param arrDeclinationAttributes - The declinations attributes to compare
296
- */
297
- const checkAttributes = (attributeAndValues, arrDeclinationAttributes) => {
298
- const parentAttributeID = attributeAndValues.value[0].parentAttribute;
299
- const attributeValues = attributeAndValues.value[0].attributeOptions;
300
- const operator = attributeAndValues.operator;
301
- let matchingAttributes = false;
302
- // const attrArray = arrDeclinationAttributes.map(decliAttr=>Array.isArray(decliAttr)?decliAttr.values[0].)
303
- for (let declinationAttribute of arrDeclinationAttributes) {
304
- if (!!matchingAttributes)
305
- return true;
306
- if (declinationAttribute.attribute_id !== parentAttributeID)
307
- continue;
308
- if (!!declinationAttribute.values) {
309
- matchingAttributes =
310
- operator === '=='
311
- ? attributeValues.some((attr) => declinationAttribute.values.some((value) => value.slug === attr))
312
- : !!!attributeValues.some((attr) => declinationAttribute.values.some((value) => value.slug === attr));
313
- }
314
- }
315
- return matchingAttributes;
316
- };
317
- exports.checkAttributes = checkAttributes;
318
- const getCartPromoType = (discount) => {
319
- return !!discount.result.action
320
- ? discount.result.action === IDiscountRule_1.ResultActionEnum.GET
321
- ? Cart_1.CartPromoAppliesToEnum.ITEMS
322
- : [IDiscountRule_1.ResultActionEnum.FREE_SHIPPING, IDiscountRule_1.ResultActionEnum.FLATERATE_SHIPPING].includes(discount.result.action)
323
- ? Cart_1.CartPromoAppliesToEnum.SHIPPING
324
- : [
325
- IDiscountRule_1.ResultActionEnum.AMOUNT_SKU,
326
- IDiscountRule_1.ResultActionEnum.PERCENT_SKU,
327
- IDiscountRule_1.ResultActionEnum.AMOUNT_CATEGORY,
328
- IDiscountRule_1.ResultActionEnum.PERCENT_CATEGORY
329
- ].includes(discount.result.action)
330
- ? Cart_1.CartPromoAppliesToEnum.PRODUCT
331
- : [IDiscountRule_1.ResultActionEnum.AMOUNT_AFTER_TAXES, IDiscountRule_1.ResultActionEnum.PERCENT_AFTER_TAXES].includes(discount.result.action)
332
- ? Cart_1.CartPromoAppliesToEnum.TOTAL_AFTER_TAXES
333
- : Cart_1.CartPromoAppliesToEnum.SUBTOTAL
334
- : Cart_1.CartPromoAppliesToEnum.SUBTOTAL;
335
- };
336
- exports.getCartPromoType = getCartPromoType;
337
- /**
338
- * Check if a cart still holds at least one item a promo could apply to, once its exclusion options are removed
339
- * @param cart - The cart to check
340
- * @param discount - The discount rule holding the exclusion options
341
- */
342
- const hasApplicableItemsForPromoExclusions = (cart, discount) => {
343
- const excludeServices = !!discount.result.exclude_services_and_fees;
344
- const excludeDiscounted = !!discount.result.exclude_discounted_products;
345
- if (discount.result.action !== IDiscountRule_1.ResultActionEnum.PERCENT || (!!!excludeServices && !!!excludeDiscounted))
346
- return true;
347
- return cart.items.some((i) => !!!(0, g2_1.isEscompteSuppItem)(i.sku) &&
348
- !(excludeServices && !!i.is_service) &&
349
- !(excludeDiscounted && (0, products_1.isDiscountedItemForPromoExclusion)(i)));
350
- };
351
- exports.hasApplicableItemsForPromoExclusions = hasApplicableItemsForPromoExclusions;
352
- /**
353
- * Check if promo code can be applied to a specific cart
354
- * @param cart - The cart to check
355
- * @param promoCode - The discount rule with promo code to check
356
- */
357
- const checkPromoCodeEligibility = (cart, promoCode) => {
358
- var _a;
359
- let currentDiscountMap = [];
360
- const promoType = (0, exports.getCartPromoType)(promoCode);
361
- const currentPromos = (_a = (0, exports.getCartPromo)(cart)) !== null && _a !== void 0 ? _a : [];
362
- // Only one promo for total_after_taxes can be applied to cart
363
- if (promoType == Cart_1.CartPromoAppliesToEnum.TOTAL_AFTER_TAXES &&
364
- currentPromos.some((p) => p.applies_to == Cart_1.CartPromoAppliesToEnum.TOTAL_AFTER_TAXES)) {
365
- return false;
366
- }
367
- if (promoType === Cart_1.CartPromoAppliesToEnum.SHIPPING && (!!cart.is_pickup || !!!cart.shipping_selected)) {
368
- return false;
369
- }
370
- // Si tous les produits sont exclus, la promo ne s'applique sur rien donc elle n'est pas éligible
371
- if (!!!(0, exports.hasApplicableItemsForPromoExclusions)(cart, promoCode))
372
- return false;
373
- if (promoType === Cart_1.CartPromoAppliesToEnum.PRODUCT &&
374
- (!!promoCode.result.action_sku || !!promoCode.result.action_categories)) {
375
- const itemsWherePromoApplicable = (0, exports.getResultAppliedDiscountSkus)(cart.items, promoCode);
376
- if (!!!itemsWherePromoApplicable.length)
377
- return false;
378
- }
379
- const rules = promoCode.rules;
380
- if (!!promoCode.noExtraRules || !!!rules || !!!rules.length)
381
- return true;
382
- currentDiscountMap = rules.map((rule) => _checkIfRuleAppliesToCart(rule, promoCode.appliesTo, cart));
383
- return _checkRuleApplicationArray(currentDiscountMap);
384
- };
385
- exports.checkPromoCodeEligibility = checkPromoCodeEligibility;
386
- // #endregion
387
- // -----------------------------------------------------------------------------------
388
- // #region TIER PRICING
389
- /**
390
- * Returns tier pricing step that should be applied for provided quantity, or undefined if none should apply
391
- * @param tierPricingToCheck - the indexed tier-pricing array to check
392
- * @param qte
393
- */
394
- const getTierPricingToApply = (tierPricingToCheck, qte) => {
395
- if (!!!tierPricingToCheck)
396
- return;
397
- return tierPricingToCheck.find((tp) => (0, toNumber_1.default)(tp.from) <= qte && (!!!tp.to || (0, toNumber_1.default)(tp.to) >= qte));
398
- };
399
- exports.getTierPricingToApply = getTierPricingToApply;
400
- /**
401
- * Converts tier-pricing found in discount_rule to IIndexedTierPricing.
402
- * @param discountRule - the tier-pricing tier discountRule to check
403
- * @param price - declinations regular price from which tier-pricing result is calculated
404
- * @param space
405
- * @param decimals - the amount of decimals to show on tier-pricing result
406
- */
407
- const applyTierPricing = (discountRule, price, space, decimals) => {
408
- if (!!!discountRule.rules || !!!discountRule.rules.length)
409
- return [];
410
- if (!!discountRule.draft)
411
- return [];
412
- const rule = discountRule.rules.find((_rule) => _rule.field === IDiscountRule_1.RuleFieldEnum.QUANTITY && _rule.ruleDetails.find((detail) => detail.operator === 'between'));
413
- if (!!!rule)
414
- return [];
415
- const details = rule.ruleDetails.find((detail) => detail.operator === 'between');
416
- if (!!!details)
417
- return [];
418
- return [
419
- {
420
- from: !!!details.value[1] || !!!(0, toNumber_1.default)(details.value[1])
421
- ? details.value[0]
422
- : (0, toNumber_1.default)(details.value[0]) < (0, toNumber_1.default)(details.value[1])
423
- ? details.value[0]
424
- : details.value[1],
425
- to: !!!details.value[1] || !!!(0, toNumber_1.default)(details.value[1])
426
- ? 0
427
- : (0, toNumber_1.default)(details.value[0]) > (0, toNumber_1.default)(details.value[1])
428
- ? details.value[0]
429
- : details.value[1],
430
- price: (0, currency_1.calculateAmountByCurrencyAllDetails)(space, space.preferences.default.currency(), (0, round_1.default)((0, exports.applyDiscountToPrice)(Number(price), discountRule.result), !!decimals ? decimals : 2)),
431
- check_attribute_value: !!discountRule.appliesTo.check_attribute_value
432
- ? discountRule.appliesTo.check_attribute_value
433
- : '',
434
- check_other_items_category: !!discountRule.appliesTo.check_other_items_category
435
- ? discountRule.appliesTo.check_other_items_category
436
- : '',
437
- name: discountRule.name
438
- }
439
- ];
440
- };
441
- exports.applyTierPricing = applyTierPricing;
442
- /**
443
- * Calculate new discount_price object for cart item base on qte and tier_pricing
444
- * @param item - the item to check
445
- * @param setOriginalPrice - if original_amount should be set instead of discount_price.amount
446
- * @param originalDecli - Optionnal. The IIndexedDeclination used to construct the cart item originally.
447
- */
448
- const getNewDiscountPriceFromTierPricing = (item, setOriginalPrice, originalDecli) => {
449
- const tierPricingToApply = (0, exports.getTierPricingToApply)(item.tier_pricing, item.qte);
450
- const currentDiscountPrice = item.discount_price;
451
- const currentIsTierPricing = !!currentDiscountPrice && currentDiscountPrice.price_type === 'tierpricing';
452
- const originalDiscountAmount = !!currentDiscountPrice ? currentDiscountPrice.original_amount : null;
453
- let prevDiscountPrice = null;
454
- if (!!currentIsTierPricing && typeof originalDiscountAmount === 'number') {
455
- const { price_type, original_amount } = currentDiscountPrice, rest = __rest(currentDiscountPrice, ["price_type", "original_amount"]);
456
- prevDiscountPrice = Object.assign(Object.assign({}, rest), { amount: original_amount });
457
- }
458
- // if current quantity does not fit in any defined tier_pricing tiers
459
- if (!!!tierPricingToApply) {
460
- // if current item has overidden price as discount_price, set original_amount props instead of amount
461
- if (!!setOriginalPrice && !!currentDiscountPrice) {
462
- let amountToSet = item.regular_price.amount;
463
- // if originalDecli was provided, fetch true original price from decli, else use items's regular price
464
- if (!!originalDecli) {
465
- const calculatedPrice = (0, products_1.getLowestPrice)(Object.assign(Object.assign({}, originalDecli), { qte: item.qte }));
466
- amountToSet = calculatedPrice.price.amount;
467
- }
468
- return Object.assign(Object.assign({}, currentDiscountPrice), { original_amount: !!originalDecli ? amountToSet : item.regular_price.amount });
469
- }
470
- // if current discount_price has 'tierpricing' price_type, return prevDiscountPrice
471
- // else, return current item discount_price
472
- return !!currentIsTierPricing ? prevDiscountPrice : (currentDiscountPrice !== null && currentDiscountPrice !== void 0 ? currentDiscountPrice : null);
473
- }
474
- // if current item has overidden price as discount_price,
475
- if (!!setOriginalPrice && !!currentDiscountPrice) {
476
- return Object.assign(Object.assign({}, currentDiscountPrice), { original_amount: tierPricingToApply.price.amount });
477
- }
478
- return Object.assign(Object.assign(Object.assign({}, tierPricingToApply.price), { price_type: 'tierpricing' }), (!!currentDiscountPrice
479
- ? {
480
- original_amount: typeof originalDiscountAmount === 'number' ? originalDiscountAmount : currentDiscountPrice.amount
481
- }
482
- : {}));
483
- };
484
- exports.getNewDiscountPriceFromTierPricing = getNewDiscountPriceFromTierPricing;
485
- // #endregion
486
- // -----------------------------------------------------------------------------------
487
- // #region APPLY DISCOUNTS/PROMOS
488
- /**
489
- * Get discounted price after applying discount rules to a provided price
490
- * @param discount_rules - The discount rules to apply
491
- * @param amount - The initial amount on which to apply discounts
492
- * @param space
493
- */
494
- const applyDiscountRulesOnProduct = (discount_rules, amount, space) => {
495
- if (!!!discount_rules || !!!discount_rules.length)
496
- return undefined;
497
- let discountIndex = 0;
498
- let allPromo = discount_rules.filter((discount_rule) => discount_rule.discountRule_type !== 'tier-pricing');
499
- let current_promo_price = Number(amount);
500
- for (const discount of allPromo) {
501
- if (discountIndex > 0 && !discount.is_stackable)
502
- break;
503
- let amountToRemove = (0, exports.isPromoAPercentage)(discount)
504
- ? (Number(discount.result.action_value) / 100) * current_promo_price
505
- : Number(discount.result.action_value);
506
- current_promo_price -= amountToRemove;
507
- discountIndex++;
508
- }
509
- const spaceProductPrefs = space.preferences.products.get();
510
- const allowNegativePrices = !!spaceProductPrefs && !!spaceProductPrefs.allow_negative_prices;
511
- return current_promo_price === Number(amount)
512
- ? undefined
513
- : current_promo_price < 0 && !!!allowNegativePrices
514
- ? 0
515
- : current_promo_price;
516
- };
517
- exports.applyDiscountRulesOnProduct = applyDiscountRulesOnProduct;
518
- /**
519
- * Get result of discount rule discount on a provided amount
520
- * @param initial - The price on which to apply the discount
521
- * @param discountResultObj - The discount rule result object
522
- */
523
- const applyDiscountToPrice = (initial, discountResultObj) => {
524
- return discountResultObj.action === 'amount'
525
- ? initial - Number(discountResultObj.action_value)
526
- : initial * (1 - Number(discountResultObj.action_value) / 100);
527
- };
528
- exports.applyDiscountToPrice = applyDiscountToPrice;
529
- /**
530
- * Get sku(s) affected by a promo as an array of strings
531
- * @param valueToConvert - The sku or sku array associated with the promo
532
- * @returns And array of strings
533
- */
534
- const getSkuArrayForPromo = (valueToConvert) => {
535
- if (!!Array.isArray(valueToConvert))
536
- return valueToConvert;
537
- return [valueToConvert];
538
- };
539
- exports.getSkuArrayForPromo = getSkuArrayForPromo;
540
- /**
541
- * Returns a list of all skus where promo applied to specific products should apply. Check for both amount/percent_sku and amount/percent_category options.
542
- * @param cartItems - The current cart items
543
- * @param promoToCheck - The promo to check
544
- * @returns An array of strings
545
- */
546
- const getResultAppliedDiscountSkus = (cartItems, promoToCheck) => {
547
- var _a, _b, _c;
548
- const action = (_a = promoToCheck.result.action) !== null && _a !== void 0 ? _a : '';
549
- const skuArray = (0, exports.getSkuArrayForPromo)((_b = promoToCheck.result.action_sku) !== null && _b !== void 0 ? _b : []);
550
- const categoryArray = (_c = promoToCheck.result.action_categories) !== null && _c !== void 0 ? _c : [];
551
- const productsToApplyPromo = cartItems
552
- .filter((item) => {
553
- if (!!['amount_category', 'percent_category'].includes(action)) {
554
- const categorySlugsToCheck = (0, exports.getItemCategorySlugArray)(item.categories);
555
- // Check if one of the slugs in item is EXACTLY the same as a category slug found in discount
556
- // -- Done to remove cases where slug in discount is found partially in one of the levels
557
- return categoryArray.some((cat) => categorySlugsToCheck.includes(cat));
558
- }
559
- return skuArray.includes(item.sku);
560
- })
561
- .map((item) => item.sku);
562
- return productsToApplyPromo;
563
- };
564
- exports.getResultAppliedDiscountSkus = getResultAppliedDiscountSkus;
565
- /**
566
- * Creates array of all category level slugs for a cart item.
567
- * @param itemCategories - Value found in props cart.categories
568
- * @returns An array of strings
569
- */
570
- const getItemCategorySlugArray = (itemCategories) => {
571
- if (!!!itemCategories)
572
- return [];
573
- // 1. Reorder item categories by key (can be in diff order in database)
574
- const orderedByLevel = (0, orderBy_1.default)(Object.entries(itemCategories), ([key, _value]) => key);
575
- // 2. Then, isolate last category level's value, since it should contain all category levels seperated by string ' > '
576
- const lastLevelCategory = !!orderedByLevel.length ? orderedByLevel[orderedByLevel.length - 1][1] : '';
577
- // 3. Split on ' > ' to create array of possible category slug values.
578
- // Check if one of the slugs is EXACTLY the same as the category slug found in le discount
579
- return lastLevelCategory.split(' > ');
580
- };
581
- exports.getItemCategorySlugArray = getItemCategorySlugArray;
582
- /**
583
- * Check if provided discount can be added to currently applied discounts for cart.
584
- * @param promoToCheck
585
- * @param currentPromos
586
- * @param isMultiPromo
587
- */
588
- const checkIfCanAddPromo = (promoToCheck, currentPromos, isMultiPromo) => {
589
- if (!!!currentPromos || !!!currentPromos.length)
590
- return { canAdd: true };
591
- const currentPromosHasPromo = !!currentPromos.some((e) => e.discount_id === promoToCheck.id);
592
- if (!!currentPromosHasPromo)
593
- return { canAdd: false, reason: Cart_1.CartErrorEnum.CART_DISCOUNT_CANT_APPLY };
594
- if (!!isMultiPromo) {
595
- const isStackable = !!promoToCheck.is_stackable && !!currentPromos.every((x) => !!x.stackable);
596
- return { canAdd: isStackable, reason: !isStackable ? Cart_1.CartErrorEnum.CART_DISCOUNT_NOT_STACKABLE : undefined };
597
- }
598
- return { canAdd: true };
599
- };
600
- exports.checkIfCanAddPromo = checkIfCanAddPromo;
601
- /**
602
- * Apply all valid discounts found in a specific cart's discount_rules props to cart
603
- * @param cart - The cart to check
604
- * @param isMultiPromo
605
- * @param forceShipping - If cart should be considered as a shipping cart, even if is_pickup is true
606
- */
607
- const applyDiscountToCart = (cart, isMultiPromo, forceShipping = false, forcedPromos) => {
608
- var _a;
609
- const discountRules = !!forcedPromos
610
- ? ((_a = cart.discount_rules) !== null && _a !== void 0 ? _a : []).filter((d) => (!!d.created && (0, moment_1.default)((0, data_1.formatDate)(d.created)).isBefore((0, moment_1.default)((0, data_1.formatDate)(cart.paid_at)))) ||
611
- (!!d.promo_code && !!d.promo_code.code) ||
612
- !!!d.created)
613
- : cart.discount_rules;
614
- if (!!!discountRules || !!!discountRules.length) {
615
- return Object.assign(Object.assign(Object.assign({}, cart), (!!cart.cart_promo_applied ? { cart_promo_applied: null } : {})), (!!cart.cart_promos_applied ? { cart_promos_applied: null } : {}));
616
- }
617
- // Remove all promos not found in cart discount_rules array
618
- let newCart = Object.assign(Object.assign(Object.assign({}, cart), (!!cart.cart_promo_applied &&
619
- !!!discountRules.some((dr) => dr.id === cart.cart_promo_applied.discount_id)
620
- ? { cart_promo_applied: null }
621
- : {})), (!!cart.cart_promos_applied
622
- ? {
623
- cart_promos_applied: cart.cart_promos_applied.filter((promo) => discountRules.some((dr) => dr.id === promo.discount_id))
624
- }
625
- : {}));
626
- // Chaque fois que les totaux sont recalculés :
627
- // -- on vérifie les codes promos déjà dans le panier qui s'appliquent sur des skus OU catégories spécifiques
628
- // -- s'ils n'ont plus d'affaire à s'appliquer, on les retire du cartPromosApplied
629
- // -- si de nouveaux produits eligibles sont ajoutés, on modifie le array de item_given avec les nouvelles valeurs à jour.
630
- const currentPromos = (0, exports.getCartPromo)(newCart);
631
- if (!!currentPromos) {
632
- let shouldRemovePromo = [];
633
- let shouldUpdatePromo = [];
634
- // const currentPromoCodesApplied = currentPromos.filter((p) => !!p.promo_code)
635
- for (const appliedPromo of currentPromos) {
636
- if (appliedPromo.applies_to === Cart_1.CartPromoAppliesToEnum.PRODUCT && !!appliedPromo.item_given) {
637
- const sameInCartDiscounts = discountRules.find((d) => d.id == appliedPromo.discount_id);
638
- if (!!sameInCartDiscounts) {
639
- const itemsWherePromoApplicable = (0, exports.getResultAppliedDiscountSkus)(cart.items, sameInCartDiscounts);
640
- if (!!!itemsWherePromoApplicable.length && !!appliedPromo.discount_id) {
641
- shouldRemovePromo.push(appliedPromo.discount_id);
642
- }
643
- else if (itemsWherePromoApplicable.length !== appliedPromo.item_given.length) {
644
- shouldUpdatePromo.push(Object.assign(Object.assign({}, appliedPromo), { item_given: itemsWherePromoApplicable }));
645
- }
646
- }
647
- }
648
- }
649
- // Update cart_promos_applied to remove unapplicable promos and update promos to current cart items
650
- newCart = Object.assign(Object.assign({}, newCart), (!!newCart.cart_promos_applied
651
- ? {
652
- cart_promos_applied: newCart.cart_promos_applied
653
- .filter((promo) => !shouldRemovePromo.includes(promo.discount_id))
654
- .map((promo) => {
655
- if (!!!shouldUpdatePromo.length)
656
- return promo;
657
- const sameInUpdated = shouldUpdatePromo.find((p) => p.discount_id == promo.discount_id);
658
- return sameInUpdated !== null && sameInUpdated !== void 0 ? sameInUpdated : promo;
659
- })
660
- }
661
- : {}));
662
- }
663
- for (const discount of discountRules) {
664
- if (!!discount.promo_code && !!discount.promo_code.code) {
665
- // CHECK FOR PROMO_CODE ELIGIBILITY
666
- const promoCodeInCart = (currentPromos || []).find((p) => p.discount_id == discount.id);
667
- if (!!promoCodeInCart) {
668
- const shouldStillApplyCode = (0, exports.checkPromoCodeEligibility)(newCart, discount);
669
- if (!!!shouldStillApplyCode) {
670
- newCart = Object.assign(Object.assign(Object.assign({}, newCart), (!!newCart.cart_promo_applied && newCart.cart_promo_applied.discount_id === discount.id
671
- ? { cart_promo_applied: null }
672
- : {})), (!!newCart.cart_promos_applied
673
- ? {
674
- cart_promos_applied: newCart.cart_promos_applied.filter((p) => p.discount_id !== discount.id)
675
- }
676
- : {}));
677
- }
678
- }
679
- continue;
680
- }
681
- const promoType = (0, exports.getCartPromoType)(discount);
682
- let currentDiscountMap = [];
683
- if (promoType == Cart_1.CartPromoAppliesToEnum.TOTAL_AFTER_TAXES &&
684
- ((0, exports.getCartPromo)(newCart) || []).some((p) => p.applies_to == Cart_1.CartPromoAppliesToEnum.TOTAL_AFTER_TAXES && p.discount_id != discount.id)) {
685
- currentDiscountMap = [[IDiscountRule_1.RuleConditionEnum.AND, false]];
686
- }
687
- else if (promoType === Cart_1.CartPromoAppliesToEnum.SHIPPING &&
688
- (!!cart.is_pickup || !!!cart.shipping_selected) &&
689
- !!!forceShipping) {
690
- currentDiscountMap = [[IDiscountRule_1.RuleConditionEnum.AND, false]];
691
- }
692
- else if (!!!(0, exports.hasApplicableItemsForPromoExclusions)(cart, discount)) {
693
- // Remise sans code : si tous les produits sont exclus, on la retire au lieu de l'appliquer à 0.00$
694
- currentDiscountMap = [[IDiscountRule_1.RuleConditionEnum.AND, false]];
695
- }
696
- else if (!!!discount.rules || !!!discount.rules.length) {
697
- currentDiscountMap = [[IDiscountRule_1.RuleConditionEnum.AND, true]];
698
- }
699
- else if (!!discount.draft) {
700
- currentDiscountMap = [[IDiscountRule_1.RuleConditionEnum.AND, true]];
701
- }
702
- else {
703
- currentDiscountMap = discount.rules.map((rule) => _checkIfRuleAppliesToCart(rule, discount.appliesTo, cart));
704
- }
705
- if (_checkRuleApplicationArray(currentDiscountMap)) {
706
- if (discount.draft) {
707
- newCart = Object.assign(Object.assign(Object.assign({}, newCart), (!!newCart.cart_promo_applied && newCart.cart_promo_applied.discount_id === discount.id
708
- ? { cart_promo_applied: null }
709
- : {})), (!!newCart.cart_promos_applied
710
- ? {
711
- cart_promos_applied: newCart.cart_promos_applied.filter((p) => p.discount_id !== discount.id)
712
- }
713
- : {}));
714
- }
715
- else {
716
- if (promoType === Cart_1.CartPromoAppliesToEnum.PRODUCT &&
717
- (!!discount.result.action_sku || !!discount.result.action_categories)) {
718
- const productsToApplyPromo = (0, exports.getResultAppliedDiscountSkus)(cart.items, discount);
719
- if (!!productsToApplyPromo.length) {
720
- const newPromo = Object.assign(Object.assign({ promo_name: (0, locale_1.getLocaleOfDictionnary)(discount.name, cart.locale), applies_to: promoType, amount_removed: Number(discount.result.action_value), amount_unit: discount.result.action, item_given: productsToApplyPromo, item_given_amount: 0, free_shipping: discount.result.action === IDiscountRule_1.ResultActionEnum.FREE_SHIPPING, flatrate_shipping: 0, stackable: discount.is_stackable, discount_id: discount.id, promo_code: !!discount.promo_code ? discount.promo_code.code : undefined }, (typeof discount.result.exclude_services_and_fees === 'boolean'
721
- ? {
722
- exclude_services_and_fees: discount.result.exclude_services_and_fees
723
- }
724
- : {})), (typeof discount.result.exclude_discounted_products === 'boolean'
725
- ? {
726
- exclude_discounted_products: discount.result.exclude_discounted_products
727
- }
728
- : {}));
729
- if ((0, exports.checkIfCanAddPromo)(discount, (0, exports.getCartPromo)(newCart), isMultiPromo).canAdd) {
730
- newCart = Object.assign(Object.assign({}, newCart), { cart_promos_applied: [...(newCart.cart_promos_applied || []), newPromo] });
731
- }
732
- }
733
- else {
734
- newCart = Object.assign(Object.assign(Object.assign({}, newCart), (!!newCart.cart_promo_applied && newCart.cart_promo_applied.discount_id === discount.id
735
- ? { cart_promo_applied: null }
736
- : {})), (!!newCart.cart_promos_applied
737
- ? {
738
- cart_promos_applied: newCart.cart_promos_applied.filter((p) => p.discount_id !== discount.id)
739
- }
740
- : {}));
741
- }
742
- }
743
- else {
744
- const newPromo = Object.assign(Object.assign({ promo_name: (0, locale_1.getLocaleOfDictionnary)(discount.name, cart.locale), applies_to: promoType, amount_removed: promoType !== Cart_1.CartPromoAppliesToEnum.SHIPPING ? Number(discount.result.action_value) : 0, amount_unit: discount.result.action, item_given: promoType === Cart_1.CartPromoAppliesToEnum.ITEMS ? discount.result.action_value.toString() : '', item_given_amount: promoType === Cart_1.CartPromoAppliesToEnum.ITEMS && !!discount.result.action_qte
745
- ? Number(discount.result.action_qte)
746
- : 0, stackable: discount.is_stackable, discount_id: discount.id, free_shipping: discount.result.action === IDiscountRule_1.ResultActionEnum.FREE_SHIPPING, flatrate_shipping: promoType === Cart_1.CartPromoAppliesToEnum.SHIPPING &&
747
- discount.result.action === IDiscountRule_1.ResultActionEnum.FLATERATE_SHIPPING
748
- ? Number(discount.result.action_value)
749
- : 0, promo_code: !!discount.promo_code ? discount.promo_code.code : undefined }, (typeof discount.result.exclude_services_and_fees === 'boolean'
750
- ? {
751
- exclude_services_and_fees: discount.result.exclude_services_and_fees
752
- }
753
- : {})), (typeof discount.result.exclude_discounted_products === 'boolean'
754
- ? {
755
- exclude_discounted_products: discount.result.exclude_discounted_products
756
- }
757
- : {}));
758
- if ((0, exports.checkIfCanAddPromo)(discount, (0, exports.getCartPromo)(newCart), isMultiPromo).canAdd) {
759
- newCart = Object.assign(Object.assign({}, newCart), { cart_promos_applied: [...(newCart.cart_promos_applied || []), newPromo] });
760
- }
761
- }
762
- }
763
- }
764
- else {
765
- newCart = Object.assign(Object.assign(Object.assign({}, newCart), (!!cart.cart_promo_applied && cart.cart_promo_applied.discount_id === discount.id
766
- ? { cart_promo_applied: null }
767
- : {})), (!!newCart.cart_promos_applied
768
- ? {
769
- cart_promos_applied: newCart.cart_promos_applied.filter((p) => p.discount_id !== discount.id)
770
- }
771
- : {}));
772
- }
773
- }
774
- if (!!newCart.cart_promos_applied && !!isMultiPromo) {
775
- const shippingPromo = newCart.cart_promos_applied.filter((x) => x.applies_to === Cart_1.CartPromoAppliesToEnum.SHIPPING);
776
- if (!!shippingPromo && !!shippingPromo.length) {
777
- let flatPrice = 1000000;
778
- let promo = 0;
779
- for (let i = 0; i < shippingPromo.length; i++) {
780
- if (shippingPromo[i].amount_unit === 'free_shipping') {
781
- // si free on stop la
782
- promo = i;
783
- break;
784
- }
785
- if (!!shippingPromo[i].flatrate_shipping && shippingPromo[i].flatrate_shipping < flatPrice) {
786
- promo = i;
787
- flatPrice = shippingPromo[i].flatrate_shipping;
788
- }
789
- }
790
- const promoSansShipping = newCart.cart_promos_applied.filter((x) => x.applies_to !== Cart_1.CartPromoAppliesToEnum.SHIPPING);
791
- newCart = Object.assign(Object.assign({}, newCart), { cart_promos_applied: [...promoSansShipping, shippingPromo[promo]] });
792
- }
793
- }
794
- if (!!forcedPromos && !!forcedPromos.length) {
795
- const appliedPromos = !!newCart.cart_promos_applied && !!newCart.cart_promos_applied.length
796
- ? newCart.cart_promos_applied.map((p) => p.discount_id)
797
- : [];
798
- const newForcedPromos = forcedPromos.filter((f) => !!!appliedPromos.includes(f.discount_id));
799
- newCart = Object.assign(Object.assign({}, newCart), { cart_promos_applied: [
800
- ...(!!newCart.cart_promos_applied && !!newCart.cart_promos_applied.length ? newCart.cart_promos_applied : []),
801
- ...newForcedPromos
802
- ] });
803
- }
804
- return Object.assign(Object.assign({}, newCart), { free_shipping: !!newCart.cart_promos_applied
805
- ? newCart.cart_promos_applied.some((p) => !!p.free_shipping)
806
- : !!newCart.cart_promo_applied && newCart.cart_promo_applied.free_shipping });
807
- };
808
- exports.applyDiscountToCart = applyDiscountToCart;
809
- /**
810
- * Get the ICartPromoApplied object for a specified discount_rule. Only works for promos that do not apply to products of certain categories/skus.
811
- * @param cart
812
- * @param discount
813
- */
814
- const getStandardCartPromoFromDiscount = (cart, discount) => {
815
- const promoType = (0, exports.getCartPromoType)(discount);
816
- return Object.assign(Object.assign({ promo_name: (0, locale_1.getLocaleOfDictionnary)(discount.name, cart.locale), applies_to: promoType, amount_removed: promoType !== Cart_1.CartPromoAppliesToEnum.SHIPPING ? Number(discount.result.action_value) : 0, amount_unit: discount.result.action, item_given: promoType === Cart_1.CartPromoAppliesToEnum.ITEMS ? discount.result.action_value.toString() : '', item_given_amount: promoType === Cart_1.CartPromoAppliesToEnum.ITEMS && !!discount.result.action_qte
817
- ? Number(discount.result.action_qte)
818
- : 0, stackable: discount.is_stackable, discount_id: discount.id, free_shipping: discount.result.action === IDiscountRule_1.ResultActionEnum.FREE_SHIPPING, flatrate_shipping: promoType === Cart_1.CartPromoAppliesToEnum.SHIPPING && discount.result.action === IDiscountRule_1.ResultActionEnum.FLATERATE_SHIPPING
819
- ? Number(discount.result.action_value)
820
- : 0, promo_code: !!discount.promo_code ? discount.promo_code.code : undefined }, (typeof discount.result.exclude_services_and_fees === 'boolean'
821
- ? {
822
- exclude_services_and_fees: discount.result.exclude_services_and_fees
823
- }
824
- : {})), (typeof discount.result.exclude_discounted_products === 'boolean'
825
- ? {
826
- exclude_discounted_products: discount.result.exclude_discounted_products
827
- }
828
- : {}));
829
- };
830
- exports.getStandardCartPromoFromDiscount = getStandardCartPromoFromDiscount;
831
- /**
832
- Calculates the cumulative subtotal for all service/fee/discounted items in cart, including any applied promos. Usefull when calculating a promo's amount when all fees and services should be excluded.
833
- * @param items - The cart items to check
834
- * @param itemPromos - All currently active cartPromos that apply to items in cart. Sent seperatly in case local state is different from current cartData.
835
- * @param options - Which exclusions are active + rounding precision for line totals (defaults to 3)
836
- * @returns {number}
837
- */
838
- const getExcludedItemsSubtotal = (items, itemPromos, options) => {
839
- const { excludeServices, excludeDiscounted, decimals = 3 } = options;
840
- let total = 0;
841
- items.forEach((i) => {
842
- if (!!(0, g2_1.isEscompteSuppItem)(i.sku))
843
- return;
844
- const excludedAsService = !!excludeServices && !!i.is_service;
845
- const excludedAsDiscounted = !!excludeDiscounted && (0, products_1.isDiscountedItemForPromoExclusion)(i);
846
- if (!excludedAsService && !excludedAsDiscounted)
847
- return;
848
- total += (0, round_1.default)(i.qte * (0, products_1.getLowestPrice)(i).price.amount, decimals);
849
- const associatedPromos = itemPromos.filter((p) => { var _a; return (0, exports.getSkuArrayForPromo)((_a = p.item_given) !== null && _a !== void 0 ? _a : []).includes(i.sku); });
850
- for (const promo of associatedPromos) {
851
- const amount = (0, data_1.getPromoTotalAmount)(items, promo, 'number', i.sku);
852
- if (typeof amount === 'number')
853
- total -= amount;
854
- }
855
- });
856
- return total;
857
- };
858
- exports.getExcludedItemsSubtotal = getExcludedItemsSubtotal;
859
- /**
860
- * Calculates the cumulative subtotal for all service/fee type items in cart, including any applied promos. Usefull when calculating a promo's amount when all fees and services should be excluded.
861
- * @param cartData - The cartData to check
862
- * @param allCurrentAppliedToItemPromos - All currently active cartPromos that apply to items in cart. Sent seperatly in case local state is different from current cartData.
863
- * @returns A number
864
- */
865
- const getOnlyServicesAndFeesSubtotal = (cartData, allCurrentAppliedToItemPromos) => {
866
- // Calculate the subtotal for just the fees and services, including their promos
867
- // ** NEW - Now does not count escompte supp products as services when in promo on subtotal check
868
- let servicesAndFeesTotal = 0;
869
- cartData.items.forEach((i) => {
870
- if (!!!i.is_service || !!(0, g2_1.isEscompteSuppItem)(i.sku))
871
- return;
872
- const associatedPromos = allCurrentAppliedToItemPromos.filter((p) => { var _a; return (0, exports.getSkuArrayForPromo)((_a = p.item_given) !== null && _a !== void 0 ? _a : []).includes(i.sku); });
873
- servicesAndFeesTotal += (0, round_1.default)(i.qte * (0, products_1.getLowestPrice)(i).price.amount, 3);
874
- if (!!associatedPromos.length) {
875
- for (const promo of associatedPromos) {
876
- if (!!!promo.amount_removed)
877
- continue;
878
- if ((0, exports.isPromoAPercentage)(promo, { defaultToPercent: true })) {
879
- servicesAndFeesTotal -= (0, round_1.default)((promo.amount_removed / 100) * (i.qte * (0, products_1.getLowestPrice)(i).price.amount), 3);
880
- }
881
- else {
882
- servicesAndFeesTotal -= promo.amount_removed * i.qte;
883
- }
884
- }
885
- }
886
- });
887
- return servicesAndFeesTotal;
888
- };
889
- exports.getOnlyServicesAndFeesSubtotal = getOnlyServicesAndFeesSubtotal;
890
- // =========================================================
891
- // #region UTILS FOR APPLYING CART DISCOUNTS AND PROMO CODES
892
- const _checkIfRuleAppliesToCart = (rule, appliesTo, cart) => {
893
- var _a;
894
- const todayDate = (0, moment_1.default)().toDate();
895
- const ruleCondition = (_a = rule.condition) !== null && _a !== void 0 ? _a : IDiscountRule_1.RuleConditionEnum.AND;
896
- switch (rule.field) {
897
- case IDiscountRule_1.RuleFieldEnum.CART_TOTAL:
898
- return (0, flatten_1.default)(rule.ruleDetails.map((ruleDetail) => {
899
- return [ruleCondition, (0, exports.getResultRuleDetail)(ruleDetail, cart.subtotal)];
900
- }));
901
- case IDiscountRule_1.RuleFieldEnum.CART_ITEM_TOTAL:
902
- let totalCartItems = (0, sumBy_1.default)(cart.items, (item) => item.qte);
903
- if (!!appliesTo.check_other_items_category) {
904
- const correspondingCartItems = cart.items.filter((item) => {
905
- if (!!item.tier_pricing && !!item.tier_pricing.length) {
906
- return (!!item.tier_pricing[0].check_other_items_category &&
907
- item.tier_pricing[0].check_other_items_category === appliesTo.check_other_items_category);
908
- }
909
- return false;
910
- });
911
- totalCartItems = (0, sumBy_1.default)(correspondingCartItems, (item) => {
912
- let amountInBox = 1;
913
- const qte = item.qte;
914
- if (!!item.attributes['8OUv9qj0aDbiLOovd4dp']) {
915
- amountInBox = Number(item.attributes['8OUv9qj0aDbiLOovd4dp']);
916
- }
917
- return amountInBox * qte;
918
- });
919
- }
920
- return (0, flatten_1.default)(rule.ruleDetails.map((ruleDetail) => {
921
- return [ruleCondition, (0, exports.getResultRuleDetail)(ruleDetail, totalCartItems)];
922
- }));
923
- case IDiscountRule_1.RuleFieldEnum.CART_ITEM:
924
- if (!!cart) {
925
- return (0, flatten_1.default)(rule.ruleDetails.map((ruleDetail) => {
926
- if (ruleDetail.operator === 'contains') {
927
- return [ruleCondition, ruleDetail.value.every((v) => !!cart.items.some((item) => item.sku === v))];
928
- }
929
- return [ruleCondition, !!!cart.items.find((item) => !!ruleDetail.value.find((v) => v === item.sku))];
930
- }));
931
- }
932
- case IDiscountRule_1.RuleFieldEnum.CUSTOMER:
933
- return (0, flatten_1.default)(rule.ruleDetails.map((ruleDetail) => {
934
- return [ruleCondition, cart.customer_id === ruleDetail.value[0]];
935
- }));
936
- case IDiscountRule_1.RuleFieldEnum.CUSTOMER_TYPE:
937
- return (0, flatten_1.default)(rule.ruleDetails.map((ruleDetail) => {
938
- if (ruleDetail.operator === '!=') {
939
- return [
940
- ruleCondition,
941
- (!!cart.customer_info && !!!cart.customer_info.pro_title) ||
942
- (!!cart.customer_info &&
943
- !!cart.customer_info.pro_title &&
944
- !!!ruleDetail.value.includes(cart.customer_info.pro_title))
945
- ];
946
- }
947
- return [
948
- ruleCondition,
949
- !!cart.customer_info &&
950
- !!cart.customer_info.pro_title &&
951
- !!ruleDetail.value.includes(cart.customer_info.pro_title)
952
- ];
953
- }));
954
- case IDiscountRule_1.RuleFieldEnum.DATE:
955
- return (0, flatten_1.default)(rule.ruleDetails.map((ruleDetail) => {
956
- return [ruleCondition, (0, exports.getResultRuleDetail)(ruleDetail, todayDate)];
957
- }));
958
- case IDiscountRule_1.RuleFieldEnum.WEEKDAY:
959
- return (0, flatten_1.default)(rule.ruleDetails.map((ruleDetail) => {
960
- return [ruleCondition, (0, exports.getResultRuleDetail)(ruleDetail, todayDate)];
961
- }));
962
- case IDiscountRule_1.RuleFieldEnum.CART_PLATFORM:
963
- const cartPlatform = !![Cart_1.CartTypeEnum.POS, Cart_1.CartTypeEnum.POS_TRANSACTIONNAL].includes(cart.cart_type)
964
- ? Cart_1.CartTypeEnum.POS
965
- : Cart_1.CartTypeEnum.WEB;
966
- return (0, flatten_1.default)(rule.ruleDetails.map((ruleDetail) => {
967
- return [ruleCondition, (0, exports.getResultRuleDetail)(ruleDetail, cartPlatform)];
968
- }));
969
- case IDiscountRule_1.RuleFieldEnum.CART_TYPE:
970
- const cartType = cart.cart_content_type === Cart_1.CartContentTypeEnum.MIXED
971
- ? Cart_1.CartContentTypeEnum.MIXED
972
- : !!(0, cart_1.checkIfCartContainsType)(cart_2.CartGeneralTypeEnum.INSTALLATION, cart)
973
- ? cart_2.CartGeneralTypeEnum.INSTALLATION
974
- : (0, cart_1.getCartType)(cart);
975
- return (0, flatten_1.default)(rule.ruleDetails.map((ruleDetail) => {
976
- let result = (0, exports.getResultRuleDetail)(ruleDetail, cartType);
977
- for (const value of ruleDetail.value) {
978
- if (value === cart_2.CartGeneralTypeEnum.GRASS && cartType === cart_2.CartGeneralTypeEnum.INSTALLATION)
979
- result = true;
980
- }
981
- return [ruleCondition, result];
982
- }));
983
- case IDiscountRule_1.RuleFieldEnum.CART_ITEM_CATEGORIES:
984
- return (0, flatten_1.default)(rule.ruleDetails.map((ruleDetail) => {
985
- let result = ruleDetail.operator !== 'contains';
986
- for (const i of cart.items) {
987
- const categorySlugsToCheck = (0, exports.getItemCategorySlugArray)(i.categories);
988
- if (!!categorySlugsToCheck.length) {
989
- for (const ruleValue of ruleDetail.value) {
990
- if (!!categorySlugsToCheck.includes(ruleValue))
991
- result = ruleDetail.operator !== 'contains' ? false : true;
992
- }
993
- }
994
- }
995
- return [ruleCondition, result];
996
- }));
997
- case IDiscountRule_1.RuleFieldEnum.ORDER_DAY:
998
- const order_day_day = !!cart.shipping_payload && !!cart.shipping_payload.delivery_or_pickup_date
999
- ? cart.shipping_payload.delivery_or_pickup_date
1000
- : '';
1001
- return (0, flatten_1.default)(rule.ruleDetails.map((ruleDetail) => {
1002
- return [ruleCondition, !!order_day_day ? (0, exports.getResultRuleDetail)(ruleDetail, (0, moment_1.default)(order_day_day).day()) : false];
1003
- }));
1004
- case IDiscountRule_1.RuleFieldEnum.ORDER_TYPE:
1005
- return (0, flatten_1.default)(rule.ruleDetails.map((ruleDetail) => {
1006
- return [
1007
- ruleCondition,
1008
- !!cart.is_pickup
1009
- ? ruleDetail.operator === '=='
1010
- ? !!ruleDetail.value.includes('pickup')
1011
- : !!!ruleDetail.value.includes('pickup')
1012
- : ruleDetail.operator === '=='
1013
- ? !!ruleDetail.value.includes('shipping')
1014
- : !!!ruleDetail.value.includes('shipping')
1015
- ];
1016
- }));
1017
- case IDiscountRule_1.RuleFieldEnum.PAYMENT_METHOD:
1018
- // If incentive custom_payment_type is registered, let this check pass, since payment_method will only be chosen on last step
1019
- // NOTE - Used to only apply to POS and POS_TRASACTIONNAL carts, now applies to all carts.
1020
- if (
1021
- // cart.cart_type != CartTypeEnum.WEB &&
1022
- cart.custom_payment_type &&
1023
- cart.custom_payment_type.method == Cart_1.CustomPaymentTypeEnum.INCENTIVE) {
1024
- return [ruleCondition, true];
1025
- }
1026
- const paymentTypesToCompare = !!cart.custom_payment_type
1027
- ? [cart.custom_payment_type.method]
1028
- : !!(0, object_1.recursiveCheckObject)(cart, 'shipping_payload.chosen_payment')
1029
- ? [(0, object_1.recursiveCheckObject)(cart, 'shipping_payload.chosen_payment')]
1030
- : !!cart.payment_details && cart.payment_details.length
1031
- ? cart.payment_details.map((p) => p.method)
1032
- : !!cart.paid_by
1033
- ? [cart.paid_by]
1034
- : [];
1035
- return (0, flatten_1.default)(rule.ruleDetails.map((ruleDetail) => {
1036
- // Si contains, doit contenir AU MOINS UN des modes de paiement ciblés
1037
- // Si contains-not, ne doit pas contenir QUE les modes de paiement exclus
1038
- let result = ruleDetail.operator == 'contains'
1039
- ? paymentTypesToCompare.some((type) => ruleDetail.value.includes(type))
1040
- : !paymentTypesToCompare.every((type) => ruleDetail.value.includes(type));
1041
- return [ruleCondition, result];
1042
- }));
1043
- case IDiscountRule_1.RuleFieldEnum.CUSTOMER_TERMS_CODE:
1044
- let customerTermsCode = (0, object_1.recursiveCheckObject)(cart, 'customer_info.terms_code');
1045
- let customerPrevTermsCode = (0, object_1.recursiveCheckObject)(cart, 'customer_info.previous_terms_code');
1046
- let trueTermsCode = customerTermsCode == 'HOLD' ? 'HOLD' : (customerPrevTermsCode !== null && customerPrevTermsCode !== void 0 ? customerPrevTermsCode : customerTermsCode);
1047
- let termsCodeToCheck = !!!trueTermsCode
1048
- ? undefined
1049
- : data_2.allCodesForHold.includes(trueTermsCode)
1050
- ? 'HOLD'
1051
- : data_2.allCodesForPSL.includes(trueTermsCode)
1052
- ? 'P.S.L'
1053
- : 'NET30';
1054
- return (0, flatten_1.default)(rule.ruleDetails.map((ruleDetail) => {
1055
- let operator = ruleDetail.operator;
1056
- if (!!!termsCodeToCheck)
1057
- return [IDiscountRule_1.RuleConditionEnum.AND, operator == '!='];
1058
- return [
1059
- ruleCondition,
1060
- operator == '=='
1061
- ? ruleDetail.value.includes(termsCodeToCheck)
1062
- : !ruleDetail.value.includes(termsCodeToCheck)
1063
- ];
1064
- }));
1065
- default:
1066
- return [IDiscountRule_1.RuleConditionEnum.AND, true];
1067
- }
1068
- };
1069
- /**
1070
- * Checks if discount rule should be applied to cart based on each rule verification results.
1071
- * @param checkedRulesApplicationArray - Array where each position is a verified rule result (condition with passed of failed (boolean))
1072
- * @returns A boolean
1073
- */
1074
- const _checkRuleApplicationArray = (checkedRulesApplicationArray) => {
1075
- return ((checkedRulesApplicationArray.some((option) => !!option && option.indexOf(IDiscountRule_1.RuleConditionEnum.OR) !== -1) &&
1076
- checkedRulesApplicationArray.some((option) => !!option && option.indexOf(true) !== -1)) ||
1077
- (checkedRulesApplicationArray.some((option) => !!option && option.indexOf(IDiscountRule_1.RuleConditionEnum.AND) !== -1) &&
1078
- !checkedRulesApplicationArray.some((option) => !!option && option.indexOf(false) !== -1)));
1079
- };
1080
- // #endregion
1081
- // #endregion
1082
- // -----------------------------------------------------------------------------------
1083
- // #region PAYMENT INCENTIVE DISCOUNTS/PROMOS
1084
- /**
1085
- * Checks if an incentive discount could (in theory) by added to provided cart, by checking found incentive discount's rule array.
1086
- * @param cartData - The cart to check (checks discount_rules for incentive)
1087
- * @param skipCheckFor - If certain rules should be ignore for check
1088
- * @returns a boolean
1089
- */
1090
- const checkIfCouldApplyIncentivePromo = (cartData, skipCheckFor = []) => {
1091
- let afterTaxesPromo = cartData.discount_rules.find((d) => !d.draft &&
1092
- (d.result.action == IDiscountRule_1.ResultActionEnum.PERCENT_AFTER_TAXES ||
1093
- d.result.action == IDiscountRule_1.ResultActionEnum.AMOUNT_AFTER_TAXES));
1094
- if (!!!afterTaxesPromo)
1095
- return false;
1096
- if (!!!afterTaxesPromo.rules || afterTaxesPromo.rules.length == 0)
1097
- return true;
1098
- const appliesTo = afterTaxesPromo.appliesTo;
1099
- const canApply = afterTaxesPromo.rules.map((r) => {
1100
- if (r.field && skipCheckFor.includes(r.field))
1101
- return [IDiscountRule_1.RuleConditionEnum.AND, true];
1102
- return _checkIfRuleAppliesToCart(r, appliesTo, cartData);
1103
- });
1104
- return _checkRuleApplicationArray(canApply);
1105
- };
1106
- exports.checkIfCouldApplyIncentivePromo = checkIfCouldApplyIncentivePromo;
1107
- /**
1108
- * Calculates amount to be removed for payment incentive type promos.
1109
- * @param cartData
1110
- * @param checkDiscountRules - Optionnal. If cart discount_rules should be checked if cart_promos_applied does not have promo yet.
1111
- */
1112
- const getAfterTaxesPromosTotalAmount = (cartData, checkDiscountRules) => {
1113
- let currentSubtotal = cartData.subtotal;
1114
- let afterTaxesPromo = (0, exports.getAfterTaxesPromoInCart)(cartData, checkDiscountRules);
1115
- let totalAmountForAfterTaxesPromos = 0;
1116
- if (!!afterTaxesPromo && !!afterTaxesPromo.amount_removed) {
1117
- if ((0, exports.isPromoAPercentage)(afterTaxesPromo, { includePaymentIncentiveInCheck: true })) {
1118
- totalAmountForAfterTaxesPromos += currentSubtotal * (afterTaxesPromo.amount_removed / 100);
1119
- }
1120
- else {
1121
- totalAmountForAfterTaxesPromos += afterTaxesPromo.amount_removed;
1122
- }
1123
- }
1124
- return totalAmountForAfterTaxesPromos;
1125
- };
1126
- exports.getAfterTaxesPromosTotalAmount = getAfterTaxesPromosTotalAmount;
1127
- /**
1128
- * Returns cart_promos_applied corresponding to payment incentive, if found. Can also check in discount_rules if props provided
1129
- * @param cartData
1130
- * @param checkDiscountRules - Optionnal. If the function should check in cart discount_rules if nothing found in cart_promos_applied or if value differs between discount and promo applied
1131
- */
1132
- const getAfterTaxesPromoInCart = (cartData, checkDiscountRules) => {
1133
- var _a;
1134
- let cartPromos = (_a = (0, exports.getCartPromo)(cartData)) !== null && _a !== void 0 ? _a : [];
1135
- let incentivePromo = cartPromos.find((p) => p.applies_to === Cart_1.CartPromoAppliesToEnum.TOTAL_AFTER_TAXES);
1136
- // Check discount_rule in case value changed or cart promo
1137
- let discountIncentive = (0, exports.getPaymentIncentiveDiscount)(cartData.discount_rules);
1138
- if (!!checkDiscountRules &&
1139
- !!discountIncentive &&
1140
- (!!!incentivePromo || discountIncentive.result.action_value != incentivePromo.amount_removed)) {
1141
- incentivePromo = (0, exports.getStandardCartPromoFromDiscount)(cartData, discountIncentive);
1142
- }
1143
- return incentivePromo;
1144
- };
1145
- exports.getAfterTaxesPromoInCart = getAfterTaxesPromoInCart;
1146
- /**
1147
- * Returns the information regarding the payment incentive promo if found in cart's discount_rules
1148
- * @param cartData
1149
- * @param checkForAllPaidByDiscounts Optionnal. If defined, will check all discounts if no specific incentive found
1150
- */
1151
- const getPaymentIncentiveDiscountInfo = (cartData, checkForAllPaidByDiscounts) => {
1152
- let appliesToPaymentTypes = undefined;
1153
- let paymentIncentiveDiscount = (0, exports.getPaymentIncentiveDiscount)(cartData.discount_rules);
1154
- if (!!!paymentIncentiveDiscount) {
1155
- // If not found and props set, check all discounts and use first found with rule on payment methode
1156
- if (!!checkForAllPaidByDiscounts)
1157
- paymentIncentiveDiscount = cartData.discount_rules.find((d) => (d.rules || []).some((r) => r.field == IDiscountRule_1.RuleFieldEnum.PAYMENT_METHOD));
1158
- if (!!!paymentIncentiveDiscount)
1159
- return;
1160
- }
1161
- let ruleForPaymentType = (paymentIncentiveDiscount.rules || []).find((rule) => rule.field == IDiscountRule_1.RuleFieldEnum.PAYMENT_METHOD);
1162
- if (!!ruleForPaymentType) {
1163
- appliesToPaymentTypes = {
1164
- amount: (0, toNumber_1.default)(paymentIncentiveDiscount.result.action_value),
1165
- isPercent: (0, exports.isPromoAPercentage)(paymentIncentiveDiscount, { includePaymentIncentiveInCheck: true }),
1166
- paymentTypes: (0, flatten_1.default)(ruleForPaymentType.ruleDetails.map((d) => (0, flatten_1.default)(d.value)))
1167
- };
1168
- }
1169
- return appliesToPaymentTypes;
1170
- };
1171
- exports.getPaymentIncentiveDiscountInfo = getPaymentIncentiveDiscountInfo;
1172
- const getPaymentIncentiveDiscount = (discountRules) => {
1173
- if (!!!discountRules)
1174
- return;
1175
- let paymentIncentiveDiscount = discountRules.find((d) => !!d.result.action &&
1176
- [IDiscountRule_1.ResultActionEnum.AMOUNT_AFTER_TAXES, IDiscountRule_1.ResultActionEnum.PERCENT_AFTER_TAXES].includes(d.result.action));
1177
- return paymentIncentiveDiscount;
1178
- };
1179
- exports.getPaymentIncentiveDiscount = getPaymentIncentiveDiscount;
1180
- // #endregion
1
+ "use strict";
2
+ var __rest = (this && this.__rest) || function (s, e) {
3
+ var t = {};
4
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
5
+ t[p] = s[p];
6
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
7
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
8
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
9
+ t[p[i]] = s[p[i]];
10
+ }
11
+ return t;
12
+ };
13
+ var __importDefault = (this && this.__importDefault) || function (mod) {
14
+ return (mod && mod.__esModule) ? mod : { "default": mod };
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.getPaymentIncentiveDiscount = exports.getPaymentIncentiveDiscountInfo = exports.getAfterTaxesPromoInCart = exports.getAfterTaxesPromosTotalAmount = exports.checkIfCouldApplyIncentivePromo = exports.getOnlyServicesAndFeesSubtotal = exports.getExcludedItemsSubtotal = exports.getStandardCartPromoFromDiscount = exports.applyDiscountToCart = exports.checkIfCanAddPromo = exports.getItemCategorySlugArray = exports.getResultAppliedDiscountSkus = exports.getSkuArrayForPromo = exports.applyDiscountToPrice = exports.applyDiscountRulesOnProduct = exports.getNewDiscountPriceFromTierPricing = exports.applyTierPricing = exports.getTierPricingToApply = exports.checkPromoCodeEligibility = exports.hasApplicableItemsForPromoExclusions = exports.getCartPromoType = exports.checkAttributes = exports.getResultRuleDetail = exports.shouldApplyRuleToDeclination = exports.getAppliedAmountsForSubtotalPromosOnCart = exports.getCartPromosByAppliesTo = exports.getSubtotalWithoutProductPromos = exports.isPromoAPercentage = exports.shouldCheckPromoCode = exports.getCartPromo = void 0;
18
+ const IDiscountRule_1 = require("../Interfaces/Rules/IDiscountRule");
19
+ const Cart_1 = require("../Interfaces/Cart");
20
+ const flatten_1 = __importDefault(require("lodash/flatten"));
21
+ const round_1 = __importDefault(require("lodash/round"));
22
+ const sumBy_1 = __importDefault(require("lodash/sumBy"));
23
+ const toNumber_1 = __importDefault(require("lodash/toNumber"));
24
+ const orderBy_1 = __importDefault(require("lodash/orderBy"));
25
+ const locale_1 = require("./locale");
26
+ const currency_1 = require("./currency");
27
+ const moment_1 = __importDefault(require("moment"));
28
+ const data_1 = require("./data");
29
+ const products_1 = require("./products");
30
+ const cart_1 = require("../rules/GR/utils/cart");
31
+ const cart_2 = require("../rules/GR/interfaces/cart");
32
+ const object_1 = require("./object");
33
+ const data_2 = require("../rules/GR/constants/data");
34
+ const g2_1 = require("../rules/GR/utils/g2");
35
+ // -----------------------------------------------------------------------------------
36
+ // #region GENERAL
37
+ /**
38
+ * Get formatted array of cart promos applied to a specific cart
39
+ * @param cartData
40
+ */
41
+ const getCartPromo = (cartData) => {
42
+ if (!!!cartData.cart_promo_applied && !!!cartData.cart_promos_applied)
43
+ return;
44
+ return !!cartData.cart_promo_applied
45
+ ? [cartData.cart_promo_applied]
46
+ : !!cartData.cart_promos_applied
47
+ ? cartData.cart_promos_applied
48
+ : [];
49
+ };
50
+ exports.getCartPromo = getCartPromo;
51
+ /**
52
+ * Check if current cart promos applied contain a promo_code type promotion
53
+ * @param cartData
54
+ */
55
+ const shouldCheckPromoCode = (cartData) => {
56
+ return ((!!cartData.cart_promos_applied && !!cartData.cart_promos_applied.some((p) => p.promo_code)) ||
57
+ (!!cartData.cart_promo_applied && !!cartData.cart_promo_applied.promo_code));
58
+ };
59
+ exports.shouldCheckPromoCode = shouldCheckPromoCode;
60
+ /**
61
+ * Check if promo is expressed as a percentage
62
+ * @param promo The promo to check. Works for cart applied promo as well as discount rule
63
+ * @param options.includePaymentIncentiveInCheck Optionnal. If payement incentive promotions should also be included in check
64
+ * @returns {boolean}
65
+ */
66
+ const isPromoAPercentage = (promo, options = {}) => {
67
+ const promoPercentOptions = [
68
+ IDiscountRule_1.ResultActionEnum.PERCENT,
69
+ IDiscountRule_1.ResultActionEnum.PERCENT_CATEGORY,
70
+ IDiscountRule_1.ResultActionEnum.PERCENT_SKU
71
+ ];
72
+ if (options.includePaymentIncentiveInCheck)
73
+ promoPercentOptions.push(IDiscountRule_1.ResultActionEnum.PERCENT_AFTER_TAXES);
74
+ let propertyToCheck = (0, object_1.recursiveCheckObject)(promo, 'result.action') || (0, object_1.recursiveCheckObject)(promo, 'amount_unit');
75
+ if (!!!propertyToCheck && options.defaultToPercent)
76
+ propertyToCheck = IDiscountRule_1.ResultActionEnum.PERCENT;
77
+ return !!propertyToCheck && promoPercentOptions.includes(propertyToCheck);
78
+ };
79
+ exports.isPromoAPercentage = isPromoAPercentage;
80
+ const getSubtotalWithoutProductPromos = (cartData, itemPromos) => {
81
+ const currentSubtotal = cartData.subtotalWithoutPromotions || cartData.subtotal;
82
+ let allProductSubtotalAmounts = (0, sumBy_1.default)(itemPromos, (i) => !!(0, data_1.getPromoTotalAmount)(cartData.items, i, 'number')
83
+ ? (0, data_1.getPromoTotalAmount)(cartData.items, i, 'number')
84
+ : 0);
85
+ return currentSubtotal - allProductSubtotalAmounts;
86
+ };
87
+ exports.getSubtotalWithoutProductPromos = getSubtotalWithoutProductPromos;
88
+ const getCartPromosByAppliesTo = (cartData) => {
89
+ const appliedPromos = (0, exports.getCartPromo)(cartData) || [];
90
+ let subtotalPromos = appliedPromos.filter((p) => p.applies_to == Cart_1.CartPromoAppliesToEnum.SUBTOTAL);
91
+ let itemPromos = appliedPromos.filter((p) => p.applies_to == Cart_1.CartPromoAppliesToEnum.PRODUCT);
92
+ let afterTaxesPromos = appliedPromos.filter((p) => p.applies_to == Cart_1.CartPromoAppliesToEnum.TOTAL_AFTER_TAXES);
93
+ return {
94
+ subtotal: subtotalPromos,
95
+ items: itemPromos,
96
+ afterTaxes: afterTaxesPromos
97
+ };
98
+ };
99
+ exports.getCartPromosByAppliesTo = getCartPromosByAppliesTo;
100
+ const getAppliedAmountsForSubtotalPromosOnCart = (cartData) => {
101
+ const activePromos = (0, exports.getCartPromosByAppliesTo)(cartData);
102
+ let currentSubtotal = (0, exports.getSubtotalWithoutProductPromos)(cartData, activePromos.items);
103
+ let promoAmounts = {};
104
+ for (let promo of activePromos.subtotal.filter((p) => !!p.discount_id)) {
105
+ if (!!!promo.amount_removed)
106
+ continue;
107
+ let amountRemoved = promo.amount_removed;
108
+ const excludedTotal = !!promo.exclude_services_and_fees || !!promo.exclude_discounted_products
109
+ ? (0, exports.getExcludedItemsSubtotal)(cartData.items, activePromos.items, {
110
+ excludeServices: !!promo.exclude_services_and_fees,
111
+ excludeDiscounted: !!promo.exclude_discounted_products
112
+ })
113
+ : 0;
114
+ if ((0, exports.isPromoAPercentage)(promo, { defaultToPercent: true })) {
115
+ // Excludes fees/services and/or already discounted products from the calculation based on the promotion option
116
+ amountRemoved = (0, round_1.default)((promo.amount_removed / 100) * (currentSubtotal - excludedTotal), 3);
117
+ }
118
+ promoAmounts[promo.discount_id] = amountRemoved;
119
+ currentSubtotal -= amountRemoved;
120
+ }
121
+ return promoAmounts;
122
+ };
123
+ exports.getAppliedAmountsForSubtotalPromosOnCart = getAppliedAmountsForSubtotalPromosOnCart;
124
+ // #endregion
125
+ // -----------------------------------------------------------------------------------
126
+ // #region CHECK DISCOUNT ELIGIBILITY
127
+ /**
128
+ * Check if a discount rule applies to a specific declination
129
+ * @param discount_rule - The discount rule to check
130
+ * @param declination - The declination to compare
131
+ * @param parentSlug - Optionnal. Used to check parent product slug with 'product' rule specifications. If not provided and 'product' rule found, returns true by default for rule check
132
+ */
133
+ const shouldApplyRuleToDeclination = (discount_rule, declination, parentSlug) => {
134
+ // If discount has no rules, it means it applies to declination automatically
135
+ if (!!!discount_rule.rules || !!!discount_rule.rules.length)
136
+ return true;
137
+ const currentDiscountMap = discount_rule.rules.map((rule) => {
138
+ const todayDate = (0, moment_1.default)().format('YYYY-MM-DD');
139
+ switch (rule.field) {
140
+ case IDiscountRule_1.RuleFieldEnum.PRODUCT_PRICE:
141
+ return (0, flatten_1.default)(rule.ruleDetails.map((ruleDetail) => {
142
+ return [rule.condition, (0, exports.getResultRuleDetail)(ruleDetail, declination.price.regular.amount)];
143
+ }));
144
+ case IDiscountRule_1.RuleFieldEnum.SKU:
145
+ return (0, flatten_1.default)(rule.ruleDetails.map((ruleDetail) => {
146
+ return [rule.condition, (0, exports.getResultRuleDetail)(ruleDetail, declination.sku)];
147
+ }));
148
+ case IDiscountRule_1.RuleFieldEnum.DECLINATION:
149
+ // case 'slug':
150
+ return (0, flatten_1.default)(rule.ruleDetails.map((ruleDetail) => {
151
+ return [rule.condition, declination.sku === ruleDetail.value[0]];
152
+ }));
153
+ case IDiscountRule_1.RuleFieldEnum.PRODUCT:
154
+ return (0, flatten_1.default)(rule.ruleDetails.map((ruleDetail) => {
155
+ return [rule.condition, !!!parentSlug || (0, exports.getResultRuleDetail)(ruleDetail, parentSlug)];
156
+ }));
157
+ case IDiscountRule_1.RuleFieldEnum.DATE:
158
+ case IDiscountRule_1.RuleFieldEnum.WEEKDAY:
159
+ return (0, flatten_1.default)(rule.ruleDetails.map((ruleDetail) => {
160
+ return [rule.condition, (0, exports.getResultRuleDetail)(ruleDetail, (0, moment_1.default)(todayDate).toDate())];
161
+ }));
162
+ case IDiscountRule_1.RuleFieldEnum.ATTRIBUTE:
163
+ return (0, flatten_1.default)(rule.ruleDetails.map((ruleDetail) => {
164
+ return [rule.condition, (0, exports.checkAttributes)(ruleDetail, declination.attributes)];
165
+ }));
166
+ default:
167
+ return [IDiscountRule_1.RuleConditionEnum.AND, true];
168
+ }
169
+ });
170
+ return _checkRuleApplicationArray(currentDiscountMap);
171
+ };
172
+ exports.shouldApplyRuleToDeclination = shouldApplyRuleToDeclination;
173
+ /**
174
+ * Check if a specific rule of a discount rule is respected
175
+ * @param ruleDetail - The rule details object to check
176
+ * @param cartValue - The value to compare with rule specifications
177
+ */
178
+ const getResultRuleDetail = (ruleDetail, cartValue, log) => {
179
+ let ruleRespected = false;
180
+ let isDate = false;
181
+ try {
182
+ let amountValue;
183
+ let amountValue2;
184
+ switch (true) {
185
+ case typeof cartValue === 'number':
186
+ if (ruleDetail.operator === 'between') {
187
+ amountValue = Number(ruleDetail.value[0].toString().replace(',', '.')) || [];
188
+ amountValue2 = Number(ruleDetail.value[1].toString().replace(',', '.')) || [];
189
+ }
190
+ else {
191
+ amountValue = ruleDetail.value.map((v) => Number(v.toString().replace(',', '.'))) || [];
192
+ amountValue2 = 0 || [];
193
+ }
194
+ break;
195
+ case typeof cartValue === 'string' && !!!moment_1.default.isDate((0, data_1.formatDate)(cartValue)):
196
+ if (ruleDetail.operator === 'between') {
197
+ amountValue = ruleDetail.value[0] || [];
198
+ amountValue2 = ruleDetail.value[1] || [];
199
+ }
200
+ else {
201
+ amountValue2 = [];
202
+ amountValue = ruleDetail.value || [];
203
+ }
204
+ break;
205
+ default:
206
+ if (!!log)
207
+ console.log('HERE!');
208
+ cartValue = (0, data_1.formatDate)(cartValue);
209
+ if (typeof ruleDetail.value[0] === 'number') {
210
+ if ((0, moment_1.default)(cartValue).isValid())
211
+ cartValue = (0, moment_1.default)(cartValue).day();
212
+ amountValue = ruleDetail.value || [];
213
+ }
214
+ else {
215
+ isDate = true;
216
+ amountValue = (0, moment_1.default)(ruleDetail.value[0]);
217
+ if (!!ruleDetail.value[1] && moment_1.default.isDate(ruleDetail.value[1])) {
218
+ amountValue2 = (0, moment_1.default)(ruleDetail.value[1]);
219
+ }
220
+ else {
221
+ amountValue2 = (0, moment_1.default)();
222
+ }
223
+ switch (ruleDetail.operator) {
224
+ case '==':
225
+ ruleRespected = amountValue.isSame((0, moment_1.default)(cartValue), 'date');
226
+ break;
227
+ case '!=':
228
+ ruleRespected = !!!amountValue.isSame((0, moment_1.default)(cartValue), 'date');
229
+ break;
230
+ case '<=':
231
+ ruleRespected = (0, moment_1.default)(cartValue).isSameOrBefore(amountValue, 'date');
232
+ break;
233
+ case '>=':
234
+ ruleRespected = (0, moment_1.default)(cartValue).isSameOrAfter(amountValue, 'date');
235
+ break;
236
+ case '<':
237
+ ruleRespected = (0, moment_1.default)(cartValue).isBefore(amountValue, 'date');
238
+ break;
239
+ case '>':
240
+ ruleRespected = (0, moment_1.default)(cartValue).isAfter(amountValue, 'date');
241
+ break;
242
+ case 'between':
243
+ ruleRespected = (0, moment_1.default)(cartValue).isBetween(amountValue, amountValue2, 'date', '[]');
244
+ break;
245
+ case 'contains':
246
+ default:
247
+ ruleRespected = false;
248
+ }
249
+ }
250
+ }
251
+ if (!!!isDate) {
252
+ if (!Array.isArray(amountValue) && ruleDetail.operator !== 'between') {
253
+ amountValue = [amountValue];
254
+ }
255
+ switch (ruleDetail.operator) {
256
+ case '==':
257
+ ruleRespected = !!amountValue.some((v) => v === cartValue);
258
+ break;
259
+ case '!=':
260
+ ruleRespected = !!amountValue.every((v) => v !== cartValue);
261
+ break;
262
+ case '<=':
263
+ ruleRespected = !!amountValue.some((v) => cartValue <= v);
264
+ break;
265
+ case '>=':
266
+ ruleRespected = !!amountValue.some((v) => cartValue >= v);
267
+ break;
268
+ case '<':
269
+ ruleRespected = !!amountValue.some((v) => cartValue < v);
270
+ break;
271
+ case '>':
272
+ ruleRespected = !!amountValue.some((v) => cartValue > v);
273
+ break;
274
+ case 'between':
275
+ ruleRespected = cartValue > amountValue && cartValue < amountValue2;
276
+ break;
277
+ case 'contains':
278
+ ruleRespected = !!amountValue.some((v) => cartValue.toString().indexOf(v.toString()) !== -1);
279
+ break;
280
+ case 'contains-not':
281
+ ruleRespected = !!!amountValue.some((v) => cartValue.toString().indexOf(v.toString()) !== -1);
282
+ break;
283
+ }
284
+ }
285
+ }
286
+ catch (error) {
287
+ console.log(error.toString());
288
+ }
289
+ return ruleRespected;
290
+ };
291
+ exports.getResultRuleDetail = getResultRuleDetail;
292
+ /**
293
+ * Check if rule applied to product attributes is respected for specific declination attributes
294
+ * @param attributeAndValues - The rule details object to check
295
+ * @param arrDeclinationAttributes - The declinations attributes to compare
296
+ */
297
+ const checkAttributes = (attributeAndValues, arrDeclinationAttributes) => {
298
+ const parentAttributeID = attributeAndValues.value[0].parentAttribute;
299
+ const attributeValues = attributeAndValues.value[0].attributeOptions;
300
+ const operator = attributeAndValues.operator;
301
+ let matchingAttributes = false;
302
+ // const attrArray = arrDeclinationAttributes.map(decliAttr=>Array.isArray(decliAttr)?decliAttr.values[0].)
303
+ for (let declinationAttribute of arrDeclinationAttributes) {
304
+ if (!!matchingAttributes)
305
+ return true;
306
+ if (declinationAttribute.attribute_id !== parentAttributeID)
307
+ continue;
308
+ if (!!declinationAttribute.values) {
309
+ matchingAttributes =
310
+ operator === '=='
311
+ ? attributeValues.some((attr) => declinationAttribute.values.some((value) => value.slug === attr))
312
+ : !!!attributeValues.some((attr) => declinationAttribute.values.some((value) => value.slug === attr));
313
+ }
314
+ }
315
+ return matchingAttributes;
316
+ };
317
+ exports.checkAttributes = checkAttributes;
318
+ const getCartPromoType = (discount) => {
319
+ return !!discount.result.action
320
+ ? discount.result.action === IDiscountRule_1.ResultActionEnum.GET
321
+ ? Cart_1.CartPromoAppliesToEnum.ITEMS
322
+ : [IDiscountRule_1.ResultActionEnum.FREE_SHIPPING, IDiscountRule_1.ResultActionEnum.FLATERATE_SHIPPING].includes(discount.result.action)
323
+ ? Cart_1.CartPromoAppliesToEnum.SHIPPING
324
+ : [
325
+ IDiscountRule_1.ResultActionEnum.AMOUNT_SKU,
326
+ IDiscountRule_1.ResultActionEnum.PERCENT_SKU,
327
+ IDiscountRule_1.ResultActionEnum.AMOUNT_CATEGORY,
328
+ IDiscountRule_1.ResultActionEnum.PERCENT_CATEGORY
329
+ ].includes(discount.result.action)
330
+ ? Cart_1.CartPromoAppliesToEnum.PRODUCT
331
+ : [IDiscountRule_1.ResultActionEnum.AMOUNT_AFTER_TAXES, IDiscountRule_1.ResultActionEnum.PERCENT_AFTER_TAXES].includes(discount.result.action)
332
+ ? Cart_1.CartPromoAppliesToEnum.TOTAL_AFTER_TAXES
333
+ : Cart_1.CartPromoAppliesToEnum.SUBTOTAL
334
+ : Cart_1.CartPromoAppliesToEnum.SUBTOTAL;
335
+ };
336
+ exports.getCartPromoType = getCartPromoType;
337
+ /**
338
+ * Check if a cart still holds at least one item a promo could apply to, once its exclusion options are removed
339
+ * @param cart - The cart to check
340
+ * @param discount - The discount rule holding the exclusion options
341
+ */
342
+ const hasApplicableItemsForPromoExclusions = (cart, discount) => {
343
+ const excludeServices = !!discount.result.exclude_services_and_fees;
344
+ const excludeDiscounted = !!discount.result.exclude_discounted_products;
345
+ if (discount.result.action !== IDiscountRule_1.ResultActionEnum.PERCENT || (!!!excludeServices && !!!excludeDiscounted))
346
+ return true;
347
+ return cart.items.some((i) => !!!(0, g2_1.isEscompteSuppItem)(i.sku) &&
348
+ !(excludeServices && !!i.is_service) &&
349
+ !(excludeDiscounted && (0, products_1.isDiscountedItemForPromoExclusion)(i)));
350
+ };
351
+ exports.hasApplicableItemsForPromoExclusions = hasApplicableItemsForPromoExclusions;
352
+ /**
353
+ * Check if promo code can be applied to a specific cart
354
+ * @param cart - The cart to check
355
+ * @param promoCode - The discount rule with promo code to check
356
+ */
357
+ const checkPromoCodeEligibility = (cart, promoCode) => {
358
+ var _a;
359
+ let currentDiscountMap = [];
360
+ const promoType = (0, exports.getCartPromoType)(promoCode);
361
+ const currentPromos = (_a = (0, exports.getCartPromo)(cart)) !== null && _a !== void 0 ? _a : [];
362
+ // Only one promo for total_after_taxes can be applied to cart
363
+ if (promoType == Cart_1.CartPromoAppliesToEnum.TOTAL_AFTER_TAXES &&
364
+ currentPromos.some((p) => p.applies_to == Cart_1.CartPromoAppliesToEnum.TOTAL_AFTER_TAXES)) {
365
+ return false;
366
+ }
367
+ if (promoType === Cart_1.CartPromoAppliesToEnum.SHIPPING && (!!cart.is_pickup || !!!cart.shipping_selected)) {
368
+ return false;
369
+ }
370
+ // Si tous les produits sont exclus, la promo ne s'applique sur rien donc elle n'est pas éligible
371
+ if (!!!(0, exports.hasApplicableItemsForPromoExclusions)(cart, promoCode))
372
+ return false;
373
+ if (promoType === Cart_1.CartPromoAppliesToEnum.PRODUCT &&
374
+ (!!promoCode.result.action_sku || !!promoCode.result.action_categories)) {
375
+ const itemsWherePromoApplicable = (0, exports.getResultAppliedDiscountSkus)(cart.items, promoCode);
376
+ if (!!!itemsWherePromoApplicable.length)
377
+ return false;
378
+ }
379
+ const rules = promoCode.rules;
380
+ if (!!promoCode.noExtraRules || !!!rules || !!!rules.length)
381
+ return true;
382
+ currentDiscountMap = rules.map((rule) => _checkIfRuleAppliesToCart(rule, promoCode.appliesTo, cart));
383
+ return _checkRuleApplicationArray(currentDiscountMap);
384
+ };
385
+ exports.checkPromoCodeEligibility = checkPromoCodeEligibility;
386
+ // #endregion
387
+ // -----------------------------------------------------------------------------------
388
+ // #region TIER PRICING
389
+ /**
390
+ * Returns tier pricing step that should be applied for provided quantity, or undefined if none should apply
391
+ * @param tierPricingToCheck - the indexed tier-pricing array to check
392
+ * @param qte
393
+ */
394
+ const getTierPricingToApply = (tierPricingToCheck, qte) => {
395
+ if (!!!tierPricingToCheck)
396
+ return;
397
+ return tierPricingToCheck.find((tp) => (0, toNumber_1.default)(tp.from) <= qte && (!!!tp.to || (0, toNumber_1.default)(tp.to) >= qte));
398
+ };
399
+ exports.getTierPricingToApply = getTierPricingToApply;
400
+ /**
401
+ * Converts tier-pricing found in discount_rule to IIndexedTierPricing.
402
+ * @param discountRule - the tier-pricing tier discountRule to check
403
+ * @param price - declinations regular price from which tier-pricing result is calculated
404
+ * @param space
405
+ * @param decimals - the amount of decimals to show on tier-pricing result
406
+ */
407
+ const applyTierPricing = (discountRule, price, space, decimals) => {
408
+ if (!!!discountRule.rules || !!!discountRule.rules.length)
409
+ return [];
410
+ if (!!discountRule.draft)
411
+ return [];
412
+ const rule = discountRule.rules.find((_rule) => _rule.field === IDiscountRule_1.RuleFieldEnum.QUANTITY && _rule.ruleDetails.find((detail) => detail.operator === 'between'));
413
+ if (!!!rule)
414
+ return [];
415
+ const details = rule.ruleDetails.find((detail) => detail.operator === 'between');
416
+ if (!!!details)
417
+ return [];
418
+ return [
419
+ {
420
+ from: !!!details.value[1] || !!!(0, toNumber_1.default)(details.value[1])
421
+ ? details.value[0]
422
+ : (0, toNumber_1.default)(details.value[0]) < (0, toNumber_1.default)(details.value[1])
423
+ ? details.value[0]
424
+ : details.value[1],
425
+ to: !!!details.value[1] || !!!(0, toNumber_1.default)(details.value[1])
426
+ ? 0
427
+ : (0, toNumber_1.default)(details.value[0]) > (0, toNumber_1.default)(details.value[1])
428
+ ? details.value[0]
429
+ : details.value[1],
430
+ price: (0, currency_1.calculateAmountByCurrencyAllDetails)(space, space.preferences.default.currency(), (0, round_1.default)((0, exports.applyDiscountToPrice)(Number(price), discountRule.result), !!decimals ? decimals : 2)),
431
+ check_attribute_value: !!discountRule.appliesTo.check_attribute_value
432
+ ? discountRule.appliesTo.check_attribute_value
433
+ : '',
434
+ check_other_items_category: !!discountRule.appliesTo.check_other_items_category
435
+ ? discountRule.appliesTo.check_other_items_category
436
+ : '',
437
+ name: discountRule.name
438
+ }
439
+ ];
440
+ };
441
+ exports.applyTierPricing = applyTierPricing;
442
+ /**
443
+ * Calculate new discount_price object for cart item base on qte and tier_pricing
444
+ * @param item - the item to check
445
+ * @param setOriginalPrice - if original_amount should be set instead of discount_price.amount
446
+ * @param originalDecli - Optionnal. The IIndexedDeclination used to construct the cart item originally.
447
+ */
448
+ const getNewDiscountPriceFromTierPricing = (item, setOriginalPrice, originalDecli) => {
449
+ const tierPricingToApply = (0, exports.getTierPricingToApply)(item.tier_pricing, item.qte);
450
+ const currentDiscountPrice = item.discount_price;
451
+ const currentIsTierPricing = !!currentDiscountPrice && currentDiscountPrice.price_type === 'tierpricing';
452
+ const originalDiscountAmount = !!currentDiscountPrice ? currentDiscountPrice.original_amount : null;
453
+ let prevDiscountPrice = null;
454
+ if (!!currentIsTierPricing && typeof originalDiscountAmount === 'number') {
455
+ const { price_type, original_amount } = currentDiscountPrice, rest = __rest(currentDiscountPrice, ["price_type", "original_amount"]);
456
+ prevDiscountPrice = Object.assign(Object.assign({}, rest), { amount: original_amount });
457
+ }
458
+ // if current quantity does not fit in any defined tier_pricing tiers
459
+ if (!!!tierPricingToApply) {
460
+ // if current item has overidden price as discount_price, set original_amount props instead of amount
461
+ if (!!setOriginalPrice && !!currentDiscountPrice) {
462
+ let amountToSet = item.regular_price.amount;
463
+ // if originalDecli was provided, fetch true original price from decli, else use items's regular price
464
+ if (!!originalDecli) {
465
+ const calculatedPrice = (0, products_1.getLowestPrice)(Object.assign(Object.assign({}, originalDecli), { qte: item.qte }));
466
+ amountToSet = calculatedPrice.price.amount;
467
+ }
468
+ return Object.assign(Object.assign({}, currentDiscountPrice), { original_amount: !!originalDecli ? amountToSet : item.regular_price.amount });
469
+ }
470
+ // if current discount_price has 'tierpricing' price_type, return prevDiscountPrice
471
+ // else, return current item discount_price
472
+ return !!currentIsTierPricing ? prevDiscountPrice : (currentDiscountPrice !== null && currentDiscountPrice !== void 0 ? currentDiscountPrice : null);
473
+ }
474
+ // if current item has overidden price as discount_price,
475
+ if (!!setOriginalPrice && !!currentDiscountPrice) {
476
+ return Object.assign(Object.assign({}, currentDiscountPrice), { original_amount: tierPricingToApply.price.amount });
477
+ }
478
+ return Object.assign(Object.assign(Object.assign({}, tierPricingToApply.price), { price_type: 'tierpricing' }), (!!currentDiscountPrice
479
+ ? {
480
+ original_amount: typeof originalDiscountAmount === 'number' ? originalDiscountAmount : currentDiscountPrice.amount
481
+ }
482
+ : {}));
483
+ };
484
+ exports.getNewDiscountPriceFromTierPricing = getNewDiscountPriceFromTierPricing;
485
+ // #endregion
486
+ // -----------------------------------------------------------------------------------
487
+ // #region APPLY DISCOUNTS/PROMOS
488
+ /**
489
+ * Get discounted price after applying discount rules to a provided price
490
+ * @param discount_rules - The discount rules to apply
491
+ * @param amount - The initial amount on which to apply discounts
492
+ * @param space
493
+ */
494
+ const applyDiscountRulesOnProduct = (discount_rules, amount, space) => {
495
+ if (!!!discount_rules || !!!discount_rules.length)
496
+ return undefined;
497
+ let discountIndex = 0;
498
+ let allPromo = discount_rules.filter((discount_rule) => discount_rule.discountRule_type !== 'tier-pricing');
499
+ let current_promo_price = Number(amount);
500
+ for (const discount of allPromo) {
501
+ if (discountIndex > 0 && !discount.is_stackable)
502
+ break;
503
+ let amountToRemove = (0, exports.isPromoAPercentage)(discount)
504
+ ? (Number(discount.result.action_value) / 100) * current_promo_price
505
+ : Number(discount.result.action_value);
506
+ current_promo_price -= amountToRemove;
507
+ discountIndex++;
508
+ }
509
+ const spaceProductPrefs = space.preferences.products.get();
510
+ const allowNegativePrices = !!spaceProductPrefs && !!spaceProductPrefs.allow_negative_prices;
511
+ return current_promo_price === Number(amount)
512
+ ? undefined
513
+ : current_promo_price < 0 && !!!allowNegativePrices
514
+ ? 0
515
+ : current_promo_price;
516
+ };
517
+ exports.applyDiscountRulesOnProduct = applyDiscountRulesOnProduct;
518
+ /**
519
+ * Get result of discount rule discount on a provided amount
520
+ * @param initial - The price on which to apply the discount
521
+ * @param discountResultObj - The discount rule result object
522
+ */
523
+ const applyDiscountToPrice = (initial, discountResultObj) => {
524
+ return discountResultObj.action === 'amount'
525
+ ? initial - Number(discountResultObj.action_value)
526
+ : initial * (1 - Number(discountResultObj.action_value) / 100);
527
+ };
528
+ exports.applyDiscountToPrice = applyDiscountToPrice;
529
+ /**
530
+ * Get sku(s) affected by a promo as an array of strings
531
+ * @param valueToConvert - The sku or sku array associated with the promo
532
+ * @returns And array of strings
533
+ */
534
+ const getSkuArrayForPromo = (valueToConvert) => {
535
+ if (!!Array.isArray(valueToConvert))
536
+ return valueToConvert;
537
+ return [valueToConvert];
538
+ };
539
+ exports.getSkuArrayForPromo = getSkuArrayForPromo;
540
+ /**
541
+ * Returns a list of all skus where promo applied to specific products should apply. Check for both amount/percent_sku and amount/percent_category options.
542
+ * @param cartItems - The current cart items
543
+ * @param promoToCheck - The promo to check
544
+ * @returns An array of strings
545
+ */
546
+ const getResultAppliedDiscountSkus = (cartItems, promoToCheck) => {
547
+ var _a, _b, _c;
548
+ const action = (_a = promoToCheck.result.action) !== null && _a !== void 0 ? _a : '';
549
+ const skuArray = (0, exports.getSkuArrayForPromo)((_b = promoToCheck.result.action_sku) !== null && _b !== void 0 ? _b : []);
550
+ const categoryArray = (_c = promoToCheck.result.action_categories) !== null && _c !== void 0 ? _c : [];
551
+ const productsToApplyPromo = cartItems
552
+ .filter((item) => {
553
+ if (!!['amount_category', 'percent_category'].includes(action)) {
554
+ const categorySlugsToCheck = (0, exports.getItemCategorySlugArray)(item.categories);
555
+ // Check if one of the slugs in item is EXACTLY the same as a category slug found in discount
556
+ // -- Done to remove cases where slug in discount is found partially in one of the levels
557
+ return categoryArray.some((cat) => categorySlugsToCheck.includes(cat));
558
+ }
559
+ return skuArray.includes(item.sku);
560
+ })
561
+ .map((item) => item.sku);
562
+ return productsToApplyPromo;
563
+ };
564
+ exports.getResultAppliedDiscountSkus = getResultAppliedDiscountSkus;
565
+ /**
566
+ * Creates array of all category level slugs for a cart item.
567
+ * @param itemCategories - Value found in props cart.categories
568
+ * @returns An array of strings
569
+ */
570
+ const getItemCategorySlugArray = (itemCategories) => {
571
+ if (!!!itemCategories)
572
+ return [];
573
+ // 1. Reorder item categories by key (can be in diff order in database)
574
+ const orderedByLevel = (0, orderBy_1.default)(Object.entries(itemCategories), ([key, _value]) => key);
575
+ // 2. Then, isolate last category level's value, since it should contain all category levels seperated by string ' > '
576
+ const lastLevelCategory = !!orderedByLevel.length ? orderedByLevel[orderedByLevel.length - 1][1] : '';
577
+ // 3. Split on ' > ' to create array of possible category slug values.
578
+ // Check if one of the slugs is EXACTLY the same as the category slug found in le discount
579
+ return lastLevelCategory.split(' > ');
580
+ };
581
+ exports.getItemCategorySlugArray = getItemCategorySlugArray;
582
+ /**
583
+ * Check if provided discount can be added to currently applied discounts for cart.
584
+ * @param promoToCheck
585
+ * @param currentPromos
586
+ * @param isMultiPromo
587
+ */
588
+ const checkIfCanAddPromo = (promoToCheck, currentPromos, isMultiPromo) => {
589
+ if (!!!currentPromos || !!!currentPromos.length)
590
+ return { canAdd: true };
591
+ const currentPromosHasPromo = !!currentPromos.some((e) => e.discount_id === promoToCheck.id);
592
+ if (!!currentPromosHasPromo)
593
+ return { canAdd: false, reason: Cart_1.CartErrorEnum.CART_DISCOUNT_CANT_APPLY };
594
+ if (!!isMultiPromo) {
595
+ const isStackable = !!promoToCheck.is_stackable && !!currentPromos.every((x) => !!x.stackable);
596
+ return { canAdd: isStackable, reason: !isStackable ? Cart_1.CartErrorEnum.CART_DISCOUNT_NOT_STACKABLE : undefined };
597
+ }
598
+ return { canAdd: true };
599
+ };
600
+ exports.checkIfCanAddPromo = checkIfCanAddPromo;
601
+ /**
602
+ * Apply all valid discounts found in a specific cart's discount_rules props to cart
603
+ * @param cart - The cart to check
604
+ * @param isMultiPromo
605
+ * @param forceShipping - If cart should be considered as a shipping cart, even if is_pickup is true
606
+ */
607
+ const applyDiscountToCart = (cart, isMultiPromo, forceShipping = false, forcedPromos) => {
608
+ var _a;
609
+ const discountRules = !!forcedPromos
610
+ ? ((_a = cart.discount_rules) !== null && _a !== void 0 ? _a : []).filter((d) => (!!d.created && (0, moment_1.default)((0, data_1.formatDate)(d.created)).isBefore((0, moment_1.default)((0, data_1.formatDate)(cart.paid_at)))) ||
611
+ (!!d.promo_code && !!d.promo_code.code) ||
612
+ !!!d.created)
613
+ : cart.discount_rules;
614
+ if (!!!discountRules || !!!discountRules.length) {
615
+ return Object.assign(Object.assign(Object.assign({}, cart), (!!cart.cart_promo_applied ? { cart_promo_applied: null } : {})), (!!cart.cart_promos_applied ? { cart_promos_applied: null } : {}));
616
+ }
617
+ // Remove all promos not found in cart discount_rules array
618
+ let newCart = Object.assign(Object.assign(Object.assign({}, cart), (!!cart.cart_promo_applied &&
619
+ !!!discountRules.some((dr) => dr.id === cart.cart_promo_applied.discount_id)
620
+ ? { cart_promo_applied: null }
621
+ : {})), (!!cart.cart_promos_applied
622
+ ? {
623
+ cart_promos_applied: cart.cart_promos_applied.filter((promo) => discountRules.some((dr) => dr.id === promo.discount_id))
624
+ }
625
+ : {}));
626
+ // Chaque fois que les totaux sont recalculés :
627
+ // -- on vérifie les codes promos déjà dans le panier qui s'appliquent sur des skus OU catégories spécifiques
628
+ // -- s'ils n'ont plus d'affaire à s'appliquer, on les retire du cartPromosApplied
629
+ // -- si de nouveaux produits eligibles sont ajoutés, on modifie le array de item_given avec les nouvelles valeurs à jour.
630
+ const currentPromos = (0, exports.getCartPromo)(newCart);
631
+ if (!!currentPromos) {
632
+ let shouldRemovePromo = [];
633
+ let shouldUpdatePromo = [];
634
+ // const currentPromoCodesApplied = currentPromos.filter((p) => !!p.promo_code)
635
+ for (const appliedPromo of currentPromos) {
636
+ if (appliedPromo.applies_to === Cart_1.CartPromoAppliesToEnum.PRODUCT && !!appliedPromo.item_given) {
637
+ const sameInCartDiscounts = discountRules.find((d) => d.id == appliedPromo.discount_id);
638
+ if (!!sameInCartDiscounts) {
639
+ const itemsWherePromoApplicable = (0, exports.getResultAppliedDiscountSkus)(cart.items, sameInCartDiscounts);
640
+ if (!!!itemsWherePromoApplicable.length && !!appliedPromo.discount_id) {
641
+ shouldRemovePromo.push(appliedPromo.discount_id);
642
+ }
643
+ else if (itemsWherePromoApplicable.length !== appliedPromo.item_given.length) {
644
+ shouldUpdatePromo.push(Object.assign(Object.assign({}, appliedPromo), { item_given: itemsWherePromoApplicable }));
645
+ }
646
+ }
647
+ }
648
+ }
649
+ // Update cart_promos_applied to remove unapplicable promos and update promos to current cart items
650
+ newCart = Object.assign(Object.assign({}, newCart), (!!newCart.cart_promos_applied
651
+ ? {
652
+ cart_promos_applied: newCart.cart_promos_applied
653
+ .filter((promo) => !shouldRemovePromo.includes(promo.discount_id))
654
+ .map((promo) => {
655
+ if (!!!shouldUpdatePromo.length)
656
+ return promo;
657
+ const sameInUpdated = shouldUpdatePromo.find((p) => p.discount_id == promo.discount_id);
658
+ return sameInUpdated !== null && sameInUpdated !== void 0 ? sameInUpdated : promo;
659
+ })
660
+ }
661
+ : {}));
662
+ }
663
+ for (const discount of discountRules) {
664
+ if (!!discount.promo_code && !!discount.promo_code.code) {
665
+ // CHECK FOR PROMO_CODE ELIGIBILITY
666
+ const promoCodeInCart = (currentPromos || []).find((p) => p.discount_id == discount.id);
667
+ if (!!promoCodeInCart) {
668
+ const shouldStillApplyCode = (0, exports.checkPromoCodeEligibility)(newCart, discount);
669
+ if (!!!shouldStillApplyCode) {
670
+ newCart = Object.assign(Object.assign(Object.assign({}, newCart), (!!newCart.cart_promo_applied && newCart.cart_promo_applied.discount_id === discount.id
671
+ ? { cart_promo_applied: null }
672
+ : {})), (!!newCart.cart_promos_applied
673
+ ? {
674
+ cart_promos_applied: newCart.cart_promos_applied.filter((p) => p.discount_id !== discount.id)
675
+ }
676
+ : {}));
677
+ }
678
+ }
679
+ continue;
680
+ }
681
+ const promoType = (0, exports.getCartPromoType)(discount);
682
+ let currentDiscountMap = [];
683
+ if (promoType == Cart_1.CartPromoAppliesToEnum.TOTAL_AFTER_TAXES &&
684
+ ((0, exports.getCartPromo)(newCart) || []).some((p) => p.applies_to == Cart_1.CartPromoAppliesToEnum.TOTAL_AFTER_TAXES && p.discount_id != discount.id)) {
685
+ currentDiscountMap = [[IDiscountRule_1.RuleConditionEnum.AND, false]];
686
+ }
687
+ else if (promoType === Cart_1.CartPromoAppliesToEnum.SHIPPING &&
688
+ (!!cart.is_pickup || !!!cart.shipping_selected) &&
689
+ !!!forceShipping) {
690
+ currentDiscountMap = [[IDiscountRule_1.RuleConditionEnum.AND, false]];
691
+ }
692
+ else if (!!!(0, exports.hasApplicableItemsForPromoExclusions)(cart, discount)) {
693
+ // Remise sans code : si tous les produits sont exclus, on la retire au lieu de l'appliquer à 0.00$
694
+ currentDiscountMap = [[IDiscountRule_1.RuleConditionEnum.AND, false]];
695
+ }
696
+ else if (!!!discount.rules || !!!discount.rules.length) {
697
+ currentDiscountMap = [[IDiscountRule_1.RuleConditionEnum.AND, true]];
698
+ }
699
+ else if (!!discount.draft) {
700
+ currentDiscountMap = [[IDiscountRule_1.RuleConditionEnum.AND, true]];
701
+ }
702
+ else {
703
+ currentDiscountMap = discount.rules.map((rule) => _checkIfRuleAppliesToCart(rule, discount.appliesTo, cart));
704
+ }
705
+ if (_checkRuleApplicationArray(currentDiscountMap)) {
706
+ if (discount.draft) {
707
+ newCart = Object.assign(Object.assign(Object.assign({}, newCart), (!!newCart.cart_promo_applied && newCart.cart_promo_applied.discount_id === discount.id
708
+ ? { cart_promo_applied: null }
709
+ : {})), (!!newCart.cart_promos_applied
710
+ ? {
711
+ cart_promos_applied: newCart.cart_promos_applied.filter((p) => p.discount_id !== discount.id)
712
+ }
713
+ : {}));
714
+ }
715
+ else {
716
+ if (promoType === Cart_1.CartPromoAppliesToEnum.PRODUCT &&
717
+ (!!discount.result.action_sku || !!discount.result.action_categories)) {
718
+ const productsToApplyPromo = (0, exports.getResultAppliedDiscountSkus)(cart.items, discount);
719
+ if (!!productsToApplyPromo.length) {
720
+ const newPromo = Object.assign(Object.assign({ promo_name: (0, locale_1.getLocaleOfDictionnary)(discount.name, cart.locale), applies_to: promoType, amount_removed: Number(discount.result.action_value), amount_unit: discount.result.action, item_given: productsToApplyPromo, item_given_amount: 0, free_shipping: discount.result.action === IDiscountRule_1.ResultActionEnum.FREE_SHIPPING, flatrate_shipping: 0, stackable: discount.is_stackable, discount_id: discount.id, promo_code: !!discount.promo_code ? discount.promo_code.code : undefined }, (typeof discount.result.exclude_services_and_fees === 'boolean'
721
+ ? {
722
+ exclude_services_and_fees: discount.result.exclude_services_and_fees
723
+ }
724
+ : {})), (typeof discount.result.exclude_discounted_products === 'boolean'
725
+ ? {
726
+ exclude_discounted_products: discount.result.exclude_discounted_products
727
+ }
728
+ : {}));
729
+ if ((0, exports.checkIfCanAddPromo)(discount, (0, exports.getCartPromo)(newCart), isMultiPromo).canAdd) {
730
+ newCart = Object.assign(Object.assign({}, newCart), { cart_promos_applied: [...(newCart.cart_promos_applied || []), newPromo] });
731
+ }
732
+ }
733
+ else {
734
+ newCart = Object.assign(Object.assign(Object.assign({}, newCart), (!!newCart.cart_promo_applied && newCart.cart_promo_applied.discount_id === discount.id
735
+ ? { cart_promo_applied: null }
736
+ : {})), (!!newCart.cart_promos_applied
737
+ ? {
738
+ cart_promos_applied: newCart.cart_promos_applied.filter((p) => p.discount_id !== discount.id)
739
+ }
740
+ : {}));
741
+ }
742
+ }
743
+ else {
744
+ const newPromo = Object.assign(Object.assign({ promo_name: (0, locale_1.getLocaleOfDictionnary)(discount.name, cart.locale), applies_to: promoType, amount_removed: promoType !== Cart_1.CartPromoAppliesToEnum.SHIPPING ? Number(discount.result.action_value) : 0, amount_unit: discount.result.action, item_given: promoType === Cart_1.CartPromoAppliesToEnum.ITEMS ? discount.result.action_value.toString() : '', item_given_amount: promoType === Cart_1.CartPromoAppliesToEnum.ITEMS && !!discount.result.action_qte
745
+ ? Number(discount.result.action_qte)
746
+ : 0, stackable: discount.is_stackable, discount_id: discount.id, free_shipping: discount.result.action === IDiscountRule_1.ResultActionEnum.FREE_SHIPPING, flatrate_shipping: promoType === Cart_1.CartPromoAppliesToEnum.SHIPPING &&
747
+ discount.result.action === IDiscountRule_1.ResultActionEnum.FLATERATE_SHIPPING
748
+ ? Number(discount.result.action_value)
749
+ : 0, promo_code: !!discount.promo_code ? discount.promo_code.code : undefined }, (typeof discount.result.exclude_services_and_fees === 'boolean'
750
+ ? {
751
+ exclude_services_and_fees: discount.result.exclude_services_and_fees
752
+ }
753
+ : {})), (typeof discount.result.exclude_discounted_products === 'boolean'
754
+ ? {
755
+ exclude_discounted_products: discount.result.exclude_discounted_products
756
+ }
757
+ : {}));
758
+ if ((0, exports.checkIfCanAddPromo)(discount, (0, exports.getCartPromo)(newCart), isMultiPromo).canAdd) {
759
+ newCart = Object.assign(Object.assign({}, newCart), { cart_promos_applied: [...(newCart.cart_promos_applied || []), newPromo] });
760
+ }
761
+ }
762
+ }
763
+ }
764
+ else {
765
+ newCart = Object.assign(Object.assign(Object.assign({}, newCart), (!!cart.cart_promo_applied && cart.cart_promo_applied.discount_id === discount.id
766
+ ? { cart_promo_applied: null }
767
+ : {})), (!!newCart.cart_promos_applied
768
+ ? {
769
+ cart_promos_applied: newCart.cart_promos_applied.filter((p) => p.discount_id !== discount.id)
770
+ }
771
+ : {}));
772
+ }
773
+ }
774
+ if (!!newCart.cart_promos_applied && !!isMultiPromo) {
775
+ const shippingPromo = newCart.cart_promos_applied.filter((x) => x.applies_to === Cart_1.CartPromoAppliesToEnum.SHIPPING);
776
+ if (!!shippingPromo && !!shippingPromo.length) {
777
+ let flatPrice = 1000000;
778
+ let promo = 0;
779
+ for (let i = 0; i < shippingPromo.length; i++) {
780
+ if (shippingPromo[i].amount_unit === 'free_shipping') {
781
+ // si free on stop la
782
+ promo = i;
783
+ break;
784
+ }
785
+ if (!!shippingPromo[i].flatrate_shipping && shippingPromo[i].flatrate_shipping < flatPrice) {
786
+ promo = i;
787
+ flatPrice = shippingPromo[i].flatrate_shipping;
788
+ }
789
+ }
790
+ const promoSansShipping = newCart.cart_promos_applied.filter((x) => x.applies_to !== Cart_1.CartPromoAppliesToEnum.SHIPPING);
791
+ newCart = Object.assign(Object.assign({}, newCart), { cart_promos_applied: [...promoSansShipping, shippingPromo[promo]] });
792
+ }
793
+ }
794
+ if (!!forcedPromos && !!forcedPromos.length) {
795
+ const appliedPromos = !!newCart.cart_promos_applied && !!newCart.cart_promos_applied.length
796
+ ? newCart.cart_promos_applied.map((p) => p.discount_id)
797
+ : [];
798
+ const newForcedPromos = forcedPromos.filter((f) => !!!appliedPromos.includes(f.discount_id));
799
+ newCart = Object.assign(Object.assign({}, newCart), { cart_promos_applied: [
800
+ ...(!!newCart.cart_promos_applied && !!newCart.cart_promos_applied.length ? newCart.cart_promos_applied : []),
801
+ ...newForcedPromos
802
+ ] });
803
+ }
804
+ return Object.assign(Object.assign({}, newCart), { free_shipping: !!newCart.cart_promos_applied
805
+ ? newCart.cart_promos_applied.some((p) => !!p.free_shipping)
806
+ : !!newCart.cart_promo_applied && newCart.cart_promo_applied.free_shipping });
807
+ };
808
+ exports.applyDiscountToCart = applyDiscountToCart;
809
+ /**
810
+ * Get the ICartPromoApplied object for a specified discount_rule. Only works for promos that do not apply to products of certain categories/skus.
811
+ * @param cart
812
+ * @param discount
813
+ */
814
+ const getStandardCartPromoFromDiscount = (cart, discount) => {
815
+ const promoType = (0, exports.getCartPromoType)(discount);
816
+ return Object.assign(Object.assign({ promo_name: (0, locale_1.getLocaleOfDictionnary)(discount.name, cart.locale), applies_to: promoType, amount_removed: promoType !== Cart_1.CartPromoAppliesToEnum.SHIPPING ? Number(discount.result.action_value) : 0, amount_unit: discount.result.action, item_given: promoType === Cart_1.CartPromoAppliesToEnum.ITEMS ? discount.result.action_value.toString() : '', item_given_amount: promoType === Cart_1.CartPromoAppliesToEnum.ITEMS && !!discount.result.action_qte
817
+ ? Number(discount.result.action_qte)
818
+ : 0, stackable: discount.is_stackable, discount_id: discount.id, free_shipping: discount.result.action === IDiscountRule_1.ResultActionEnum.FREE_SHIPPING, flatrate_shipping: promoType === Cart_1.CartPromoAppliesToEnum.SHIPPING && discount.result.action === IDiscountRule_1.ResultActionEnum.FLATERATE_SHIPPING
819
+ ? Number(discount.result.action_value)
820
+ : 0, promo_code: !!discount.promo_code ? discount.promo_code.code : undefined }, (typeof discount.result.exclude_services_and_fees === 'boolean'
821
+ ? {
822
+ exclude_services_and_fees: discount.result.exclude_services_and_fees
823
+ }
824
+ : {})), (typeof discount.result.exclude_discounted_products === 'boolean'
825
+ ? {
826
+ exclude_discounted_products: discount.result.exclude_discounted_products
827
+ }
828
+ : {}));
829
+ };
830
+ exports.getStandardCartPromoFromDiscount = getStandardCartPromoFromDiscount;
831
+ /**
832
+ Calculates the cumulative subtotal for all service/fee/discounted items in cart, including any applied promos. Usefull when calculating a promo's amount when all fees and services should be excluded.
833
+ * @param items - The cart items to check
834
+ * @param itemPromos - All currently active cartPromos that apply to items in cart. Sent seperatly in case local state is different from current cartData.
835
+ * @param options - Which exclusions are active + rounding precision for line totals (defaults to 3)
836
+ * @returns {number}
837
+ */
838
+ const getExcludedItemsSubtotal = (items, itemPromos, options) => {
839
+ const { excludeServices, excludeDiscounted, decimals = 3 } = options;
840
+ let total = 0;
841
+ items.forEach((i) => {
842
+ if (!!(0, g2_1.isEscompteSuppItem)(i.sku))
843
+ return;
844
+ const excludedAsService = !!excludeServices && !!i.is_service;
845
+ const excludedAsDiscounted = !!excludeDiscounted && (0, products_1.isDiscountedItemForPromoExclusion)(i);
846
+ if (!excludedAsService && !excludedAsDiscounted)
847
+ return;
848
+ total += (0, round_1.default)(i.qte * (0, products_1.getLowestPrice)(i).price.amount, decimals);
849
+ const associatedPromos = itemPromos.filter((p) => { var _a; return (0, exports.getSkuArrayForPromo)((_a = p.item_given) !== null && _a !== void 0 ? _a : []).includes(i.sku); });
850
+ for (const promo of associatedPromos) {
851
+ const amount = (0, data_1.getPromoTotalAmount)(items, promo, 'number', i.sku);
852
+ if (typeof amount === 'number')
853
+ total -= amount;
854
+ }
855
+ });
856
+ return total;
857
+ };
858
+ exports.getExcludedItemsSubtotal = getExcludedItemsSubtotal;
859
+ /**
860
+ * Calculates the cumulative subtotal for all service/fee type items in cart, including any applied promos. Usefull when calculating a promo's amount when all fees and services should be excluded.
861
+ * @param cartData - The cartData to check
862
+ * @param allCurrentAppliedToItemPromos - All currently active cartPromos that apply to items in cart. Sent seperatly in case local state is different from current cartData.
863
+ * @returns A number
864
+ */
865
+ const getOnlyServicesAndFeesSubtotal = (cartData, allCurrentAppliedToItemPromos) => {
866
+ // Calculate the subtotal for just the fees and services, including their promos
867
+ // ** NEW - Now does not count escompte supp products as services when in promo on subtotal check
868
+ let servicesAndFeesTotal = 0;
869
+ cartData.items.forEach((i) => {
870
+ if (!!!i.is_service || !!(0, g2_1.isEscompteSuppItem)(i.sku))
871
+ return;
872
+ const associatedPromos = allCurrentAppliedToItemPromos.filter((p) => { var _a; return (0, exports.getSkuArrayForPromo)((_a = p.item_given) !== null && _a !== void 0 ? _a : []).includes(i.sku); });
873
+ servicesAndFeesTotal += (0, round_1.default)(i.qte * (0, products_1.getLowestPrice)(i).price.amount, 3);
874
+ if (!!associatedPromos.length) {
875
+ for (const promo of associatedPromos) {
876
+ if (!!!promo.amount_removed)
877
+ continue;
878
+ if ((0, exports.isPromoAPercentage)(promo, { defaultToPercent: true })) {
879
+ servicesAndFeesTotal -= (0, round_1.default)((promo.amount_removed / 100) * (i.qte * (0, products_1.getLowestPrice)(i).price.amount), 3);
880
+ }
881
+ else {
882
+ servicesAndFeesTotal -= promo.amount_removed * i.qte;
883
+ }
884
+ }
885
+ }
886
+ });
887
+ return servicesAndFeesTotal;
888
+ };
889
+ exports.getOnlyServicesAndFeesSubtotal = getOnlyServicesAndFeesSubtotal;
890
+ // =========================================================
891
+ // #region UTILS FOR APPLYING CART DISCOUNTS AND PROMO CODES
892
+ const _checkIfRuleAppliesToCart = (rule, appliesTo, cart) => {
893
+ var _a;
894
+ const todayDate = (0, moment_1.default)().toDate();
895
+ const ruleCondition = (_a = rule.condition) !== null && _a !== void 0 ? _a : IDiscountRule_1.RuleConditionEnum.AND;
896
+ switch (rule.field) {
897
+ case IDiscountRule_1.RuleFieldEnum.CART_TOTAL:
898
+ return (0, flatten_1.default)(rule.ruleDetails.map((ruleDetail) => {
899
+ return [ruleCondition, (0, exports.getResultRuleDetail)(ruleDetail, cart.subtotal)];
900
+ }));
901
+ case IDiscountRule_1.RuleFieldEnum.CART_ITEM_TOTAL:
902
+ let totalCartItems = (0, sumBy_1.default)(cart.items, (item) => item.qte);
903
+ if (!!appliesTo.check_other_items_category) {
904
+ const correspondingCartItems = cart.items.filter((item) => {
905
+ if (!!item.tier_pricing && !!item.tier_pricing.length) {
906
+ return (!!item.tier_pricing[0].check_other_items_category &&
907
+ item.tier_pricing[0].check_other_items_category === appliesTo.check_other_items_category);
908
+ }
909
+ return false;
910
+ });
911
+ totalCartItems = (0, sumBy_1.default)(correspondingCartItems, (item) => {
912
+ let amountInBox = 1;
913
+ const qte = item.qte;
914
+ if (!!item.attributes['8OUv9qj0aDbiLOovd4dp']) {
915
+ amountInBox = Number(item.attributes['8OUv9qj0aDbiLOovd4dp']);
916
+ }
917
+ return amountInBox * qte;
918
+ });
919
+ }
920
+ return (0, flatten_1.default)(rule.ruleDetails.map((ruleDetail) => {
921
+ return [ruleCondition, (0, exports.getResultRuleDetail)(ruleDetail, totalCartItems)];
922
+ }));
923
+ case IDiscountRule_1.RuleFieldEnum.CART_ITEM:
924
+ if (!!cart) {
925
+ return (0, flatten_1.default)(rule.ruleDetails.map((ruleDetail) => {
926
+ if (ruleDetail.operator === 'contains') {
927
+ return [ruleCondition, ruleDetail.value.every((v) => !!cart.items.some((item) => item.sku === v))];
928
+ }
929
+ return [ruleCondition, !!!cart.items.find((item) => !!ruleDetail.value.find((v) => v === item.sku))];
930
+ }));
931
+ }
932
+ case IDiscountRule_1.RuleFieldEnum.CUSTOMER:
933
+ return (0, flatten_1.default)(rule.ruleDetails.map((ruleDetail) => {
934
+ return [ruleCondition, cart.customer_id === ruleDetail.value[0]];
935
+ }));
936
+ case IDiscountRule_1.RuleFieldEnum.CUSTOMER_TYPE:
937
+ return (0, flatten_1.default)(rule.ruleDetails.map((ruleDetail) => {
938
+ if (ruleDetail.operator === '!=') {
939
+ return [
940
+ ruleCondition,
941
+ (!!cart.customer_info && !!!cart.customer_info.pro_title) ||
942
+ (!!cart.customer_info &&
943
+ !!cart.customer_info.pro_title &&
944
+ !!!ruleDetail.value.includes(cart.customer_info.pro_title))
945
+ ];
946
+ }
947
+ return [
948
+ ruleCondition,
949
+ !!cart.customer_info &&
950
+ !!cart.customer_info.pro_title &&
951
+ !!ruleDetail.value.includes(cart.customer_info.pro_title)
952
+ ];
953
+ }));
954
+ case IDiscountRule_1.RuleFieldEnum.DATE:
955
+ return (0, flatten_1.default)(rule.ruleDetails.map((ruleDetail) => {
956
+ return [ruleCondition, (0, exports.getResultRuleDetail)(ruleDetail, todayDate)];
957
+ }));
958
+ case IDiscountRule_1.RuleFieldEnum.WEEKDAY:
959
+ return (0, flatten_1.default)(rule.ruleDetails.map((ruleDetail) => {
960
+ return [ruleCondition, (0, exports.getResultRuleDetail)(ruleDetail, todayDate)];
961
+ }));
962
+ case IDiscountRule_1.RuleFieldEnum.CART_PLATFORM:
963
+ const cartPlatform = !![Cart_1.CartTypeEnum.POS, Cart_1.CartTypeEnum.POS_TRANSACTIONNAL].includes(cart.cart_type)
964
+ ? Cart_1.CartTypeEnum.POS
965
+ : Cart_1.CartTypeEnum.WEB;
966
+ return (0, flatten_1.default)(rule.ruleDetails.map((ruleDetail) => {
967
+ return [ruleCondition, (0, exports.getResultRuleDetail)(ruleDetail, cartPlatform)];
968
+ }));
969
+ case IDiscountRule_1.RuleFieldEnum.CART_TYPE:
970
+ const cartType = cart.cart_content_type === Cart_1.CartContentTypeEnum.MIXED
971
+ ? Cart_1.CartContentTypeEnum.MIXED
972
+ : !!(0, cart_1.checkIfCartContainsType)(cart_2.CartGeneralTypeEnum.INSTALLATION, cart)
973
+ ? cart_2.CartGeneralTypeEnum.INSTALLATION
974
+ : (0, cart_1.getCartType)(cart);
975
+ return (0, flatten_1.default)(rule.ruleDetails.map((ruleDetail) => {
976
+ let result = (0, exports.getResultRuleDetail)(ruleDetail, cartType);
977
+ for (const value of ruleDetail.value) {
978
+ if (value === cart_2.CartGeneralTypeEnum.GRASS && cartType === cart_2.CartGeneralTypeEnum.INSTALLATION)
979
+ result = true;
980
+ }
981
+ return [ruleCondition, result];
982
+ }));
983
+ case IDiscountRule_1.RuleFieldEnum.CART_ITEM_CATEGORIES:
984
+ return (0, flatten_1.default)(rule.ruleDetails.map((ruleDetail) => {
985
+ let result = ruleDetail.operator !== 'contains';
986
+ for (const i of cart.items) {
987
+ const categorySlugsToCheck = (0, exports.getItemCategorySlugArray)(i.categories);
988
+ if (!!categorySlugsToCheck.length) {
989
+ for (const ruleValue of ruleDetail.value) {
990
+ if (!!categorySlugsToCheck.includes(ruleValue))
991
+ result = ruleDetail.operator !== 'contains' ? false : true;
992
+ }
993
+ }
994
+ }
995
+ return [ruleCondition, result];
996
+ }));
997
+ case IDiscountRule_1.RuleFieldEnum.ORDER_DAY:
998
+ const order_day_day = !!cart.shipping_payload && !!cart.shipping_payload.delivery_or_pickup_date
999
+ ? cart.shipping_payload.delivery_or_pickup_date
1000
+ : '';
1001
+ return (0, flatten_1.default)(rule.ruleDetails.map((ruleDetail) => {
1002
+ return [ruleCondition, !!order_day_day ? (0, exports.getResultRuleDetail)(ruleDetail, (0, moment_1.default)(order_day_day).day()) : false];
1003
+ }));
1004
+ case IDiscountRule_1.RuleFieldEnum.ORDER_TYPE:
1005
+ return (0, flatten_1.default)(rule.ruleDetails.map((ruleDetail) => {
1006
+ return [
1007
+ ruleCondition,
1008
+ !!cart.is_pickup
1009
+ ? ruleDetail.operator === '=='
1010
+ ? !!ruleDetail.value.includes('pickup')
1011
+ : !!!ruleDetail.value.includes('pickup')
1012
+ : ruleDetail.operator === '=='
1013
+ ? !!ruleDetail.value.includes('shipping')
1014
+ : !!!ruleDetail.value.includes('shipping')
1015
+ ];
1016
+ }));
1017
+ case IDiscountRule_1.RuleFieldEnum.PAYMENT_METHOD:
1018
+ // If incentive custom_payment_type is registered, let this check pass, since payment_method will only be chosen on last step
1019
+ // NOTE - Used to only apply to POS and POS_TRASACTIONNAL carts, now applies to all carts.
1020
+ if (
1021
+ // cart.cart_type != CartTypeEnum.WEB &&
1022
+ cart.custom_payment_type &&
1023
+ cart.custom_payment_type.method == Cart_1.CustomPaymentTypeEnum.INCENTIVE) {
1024
+ return [ruleCondition, true];
1025
+ }
1026
+ const paymentTypesToCompare = !!cart.custom_payment_type
1027
+ ? [cart.custom_payment_type.method]
1028
+ : !!(0, object_1.recursiveCheckObject)(cart, 'shipping_payload.chosen_payment')
1029
+ ? [(0, object_1.recursiveCheckObject)(cart, 'shipping_payload.chosen_payment')]
1030
+ : !!cart.payment_details && cart.payment_details.length
1031
+ ? cart.payment_details.map((p) => p.method)
1032
+ : !!cart.paid_by
1033
+ ? [cart.paid_by]
1034
+ : [];
1035
+ return (0, flatten_1.default)(rule.ruleDetails.map((ruleDetail) => {
1036
+ // Si contains, doit contenir AU MOINS UN des modes de paiement ciblés
1037
+ // Si contains-not, ne doit pas contenir QUE les modes de paiement exclus
1038
+ let result = ruleDetail.operator == 'contains'
1039
+ ? paymentTypesToCompare.some((type) => ruleDetail.value.includes(type))
1040
+ : !paymentTypesToCompare.every((type) => ruleDetail.value.includes(type));
1041
+ return [ruleCondition, result];
1042
+ }));
1043
+ case IDiscountRule_1.RuleFieldEnum.CUSTOMER_TERMS_CODE:
1044
+ let customerTermsCode = (0, object_1.recursiveCheckObject)(cart, 'customer_info.terms_code');
1045
+ let customerPrevTermsCode = (0, object_1.recursiveCheckObject)(cart, 'customer_info.previous_terms_code');
1046
+ let trueTermsCode = customerTermsCode == 'HOLD' ? 'HOLD' : (customerPrevTermsCode !== null && customerPrevTermsCode !== void 0 ? customerPrevTermsCode : customerTermsCode);
1047
+ let termsCodeToCheck = !!!trueTermsCode
1048
+ ? undefined
1049
+ : data_2.allCodesForHold.includes(trueTermsCode)
1050
+ ? 'HOLD'
1051
+ : data_2.allCodesForPSL.includes(trueTermsCode)
1052
+ ? 'P.S.L'
1053
+ : 'NET30';
1054
+ return (0, flatten_1.default)(rule.ruleDetails.map((ruleDetail) => {
1055
+ let operator = ruleDetail.operator;
1056
+ if (!!!termsCodeToCheck)
1057
+ return [IDiscountRule_1.RuleConditionEnum.AND, operator == '!='];
1058
+ return [
1059
+ ruleCondition,
1060
+ operator == '=='
1061
+ ? ruleDetail.value.includes(termsCodeToCheck)
1062
+ : !ruleDetail.value.includes(termsCodeToCheck)
1063
+ ];
1064
+ }));
1065
+ default:
1066
+ return [IDiscountRule_1.RuleConditionEnum.AND, true];
1067
+ }
1068
+ };
1069
+ /**
1070
+ * Checks if discount rule should be applied to cart based on each rule verification results.
1071
+ * @param checkedRulesApplicationArray - Array where each position is a verified rule result (condition with passed of failed (boolean))
1072
+ * @returns A boolean
1073
+ */
1074
+ const _checkRuleApplicationArray = (checkedRulesApplicationArray) => {
1075
+ return ((checkedRulesApplicationArray.some((option) => !!option && option.indexOf(IDiscountRule_1.RuleConditionEnum.OR) !== -1) &&
1076
+ checkedRulesApplicationArray.some((option) => !!option && option.indexOf(true) !== -1)) ||
1077
+ (checkedRulesApplicationArray.some((option) => !!option && option.indexOf(IDiscountRule_1.RuleConditionEnum.AND) !== -1) &&
1078
+ !checkedRulesApplicationArray.some((option) => !!option && option.indexOf(false) !== -1)));
1079
+ };
1080
+ // #endregion
1081
+ // #endregion
1082
+ // -----------------------------------------------------------------------------------
1083
+ // #region PAYMENT INCENTIVE DISCOUNTS/PROMOS
1084
+ /**
1085
+ * Checks if an incentive discount could (in theory) by added to provided cart, by checking found incentive discount's rule array.
1086
+ * @param cartData - The cart to check (checks discount_rules for incentive)
1087
+ * @param skipCheckFor - If certain rules should be ignore for check
1088
+ * @returns a boolean
1089
+ */
1090
+ const checkIfCouldApplyIncentivePromo = (cartData, skipCheckFor = []) => {
1091
+ let afterTaxesPromo = cartData.discount_rules.find((d) => !d.draft &&
1092
+ (d.result.action == IDiscountRule_1.ResultActionEnum.PERCENT_AFTER_TAXES ||
1093
+ d.result.action == IDiscountRule_1.ResultActionEnum.AMOUNT_AFTER_TAXES));
1094
+ if (!!!afterTaxesPromo)
1095
+ return false;
1096
+ if (!!!afterTaxesPromo.rules || afterTaxesPromo.rules.length == 0)
1097
+ return true;
1098
+ const appliesTo = afterTaxesPromo.appliesTo;
1099
+ const canApply = afterTaxesPromo.rules.map((r) => {
1100
+ if (r.field && skipCheckFor.includes(r.field))
1101
+ return [IDiscountRule_1.RuleConditionEnum.AND, true];
1102
+ return _checkIfRuleAppliesToCart(r, appliesTo, cartData);
1103
+ });
1104
+ return _checkRuleApplicationArray(canApply);
1105
+ };
1106
+ exports.checkIfCouldApplyIncentivePromo = checkIfCouldApplyIncentivePromo;
1107
+ /**
1108
+ * Calculates amount to be removed for payment incentive type promos.
1109
+ * @param cartData
1110
+ * @param checkDiscountRules - Optionnal. If cart discount_rules should be checked if cart_promos_applied does not have promo yet.
1111
+ */
1112
+ const getAfterTaxesPromosTotalAmount = (cartData, checkDiscountRules) => {
1113
+ let currentSubtotal = cartData.subtotal;
1114
+ let afterTaxesPromo = (0, exports.getAfterTaxesPromoInCart)(cartData, checkDiscountRules);
1115
+ let totalAmountForAfterTaxesPromos = 0;
1116
+ if (!!afterTaxesPromo && !!afterTaxesPromo.amount_removed) {
1117
+ if ((0, exports.isPromoAPercentage)(afterTaxesPromo, { includePaymentIncentiveInCheck: true })) {
1118
+ totalAmountForAfterTaxesPromos += currentSubtotal * (afterTaxesPromo.amount_removed / 100);
1119
+ }
1120
+ else {
1121
+ totalAmountForAfterTaxesPromos += afterTaxesPromo.amount_removed;
1122
+ }
1123
+ }
1124
+ return totalAmountForAfterTaxesPromos;
1125
+ };
1126
+ exports.getAfterTaxesPromosTotalAmount = getAfterTaxesPromosTotalAmount;
1127
+ /**
1128
+ * Returns cart_promos_applied corresponding to payment incentive, if found. Can also check in discount_rules if props provided
1129
+ * @param cartData
1130
+ * @param checkDiscountRules - Optionnal. If the function should check in cart discount_rules if nothing found in cart_promos_applied or if value differs between discount and promo applied
1131
+ */
1132
+ const getAfterTaxesPromoInCart = (cartData, checkDiscountRules) => {
1133
+ var _a;
1134
+ let cartPromos = (_a = (0, exports.getCartPromo)(cartData)) !== null && _a !== void 0 ? _a : [];
1135
+ let incentivePromo = cartPromos.find((p) => p.applies_to === Cart_1.CartPromoAppliesToEnum.TOTAL_AFTER_TAXES);
1136
+ // Check discount_rule in case value changed or cart promo
1137
+ let discountIncentive = (0, exports.getPaymentIncentiveDiscount)(cartData.discount_rules);
1138
+ if (!!checkDiscountRules &&
1139
+ !!discountIncentive &&
1140
+ (!!!incentivePromo || discountIncentive.result.action_value != incentivePromo.amount_removed)) {
1141
+ incentivePromo = (0, exports.getStandardCartPromoFromDiscount)(cartData, discountIncentive);
1142
+ }
1143
+ return incentivePromo;
1144
+ };
1145
+ exports.getAfterTaxesPromoInCart = getAfterTaxesPromoInCart;
1146
+ /**
1147
+ * Returns the information regarding the payment incentive promo if found in cart's discount_rules
1148
+ * @param cartData
1149
+ * @param checkForAllPaidByDiscounts Optionnal. If defined, will check all discounts if no specific incentive found
1150
+ */
1151
+ const getPaymentIncentiveDiscountInfo = (cartData, checkForAllPaidByDiscounts) => {
1152
+ let appliesToPaymentTypes = undefined;
1153
+ let paymentIncentiveDiscount = (0, exports.getPaymentIncentiveDiscount)(cartData.discount_rules);
1154
+ if (!!!paymentIncentiveDiscount) {
1155
+ // If not found and props set, check all discounts and use first found with rule on payment methode
1156
+ if (!!checkForAllPaidByDiscounts)
1157
+ paymentIncentiveDiscount = cartData.discount_rules.find((d) => (d.rules || []).some((r) => r.field == IDiscountRule_1.RuleFieldEnum.PAYMENT_METHOD));
1158
+ if (!!!paymentIncentiveDiscount)
1159
+ return;
1160
+ }
1161
+ let ruleForPaymentType = (paymentIncentiveDiscount.rules || []).find((rule) => rule.field == IDiscountRule_1.RuleFieldEnum.PAYMENT_METHOD);
1162
+ if (!!ruleForPaymentType) {
1163
+ appliesToPaymentTypes = {
1164
+ amount: (0, toNumber_1.default)(paymentIncentiveDiscount.result.action_value),
1165
+ isPercent: (0, exports.isPromoAPercentage)(paymentIncentiveDiscount, { includePaymentIncentiveInCheck: true }),
1166
+ paymentTypes: (0, flatten_1.default)(ruleForPaymentType.ruleDetails.map((d) => (0, flatten_1.default)(d.value)))
1167
+ };
1168
+ }
1169
+ return appliesToPaymentTypes;
1170
+ };
1171
+ exports.getPaymentIncentiveDiscountInfo = getPaymentIncentiveDiscountInfo;
1172
+ const getPaymentIncentiveDiscount = (discountRules) => {
1173
+ if (!!!discountRules)
1174
+ return;
1175
+ let paymentIncentiveDiscount = discountRules.find((d) => !!d.result.action &&
1176
+ [IDiscountRule_1.ResultActionEnum.AMOUNT_AFTER_TAXES, IDiscountRule_1.ResultActionEnum.PERCENT_AFTER_TAXES].includes(d.result.action));
1177
+ return paymentIncentiveDiscount;
1178
+ };
1179
+ exports.getPaymentIncentiveDiscount = getPaymentIncentiveDiscount;
1180
+ // #endregion
1181
1181
  //# sourceMappingURL=discount.js.map