addio-admin-sdk 1.7.131 → 1.7.132

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 (562) hide show
  1. package/.babelrc +17 -17
  2. package/.env +15 -0
  3. package/.env.dev +14 -14
  4. package/.github/workflows/run_unit_test.yaml +48 -48
  5. package/addio-sdk-doc.md +1473 -1473
  6. package/changelog.md +544 -544
  7. package/dist/Interfaces/Address/index.d.ts +21 -21
  8. package/dist/Interfaces/Address/index.js +16 -16
  9. package/dist/Interfaces/Algolia/index.d.ts +177 -177
  10. package/dist/Interfaces/Algolia/index.js +2 -2
  11. package/dist/Interfaces/Attachement/index.d.ts +5 -5
  12. package/dist/Interfaces/Attachement/index.js +2 -2
  13. package/dist/Interfaces/Attribute/index.d.ts +53 -53
  14. package/dist/Interfaces/Attribute/index.js +10 -10
  15. package/dist/Interfaces/BGJob/index.d.ts +56 -56
  16. package/dist/Interfaces/BGJob/index.js +25 -25
  17. package/dist/Interfaces/BaseClass/index.d.ts +8 -8
  18. package/dist/Interfaces/BaseClass/index.js +2 -2
  19. package/dist/Interfaces/Blog/IBlogArticle.d.ts +18 -18
  20. package/dist/Interfaces/Blog/IBlogArticle.js +2 -2
  21. package/dist/Interfaces/Blog/IBlogAuthor.d.ts +7 -7
  22. package/dist/Interfaces/Blog/IBlogAuthor.js +2 -2
  23. package/dist/Interfaces/Blog/IBlogCategory.d.ts +9 -9
  24. package/dist/Interfaces/Blog/IBlogCategory.js +2 -2
  25. package/dist/Interfaces/Blog/IBlogComment.d.ts +13 -13
  26. package/dist/Interfaces/Blog/IBlogComment.js +2 -2
  27. package/dist/Interfaces/Blog/IBlogKeywords.d.ts +9 -9
  28. package/dist/Interfaces/Blog/IBlogKeywords.js +2 -2
  29. package/dist/Interfaces/Booking/index.d.ts +74 -74
  30. package/dist/Interfaces/Booking/index.js +17 -17
  31. package/dist/Interfaces/Brand/index.d.ts +15 -15
  32. package/dist/Interfaces/Brand/index.js +2 -2
  33. package/dist/Interfaces/CMS/index.d.ts +28 -28
  34. package/dist/Interfaces/CMS/index.js +5 -5
  35. package/dist/Interfaces/Cart/IElavonPayload.d.ts +93 -93
  36. package/dist/Interfaces/Cart/IElavonPayload.js +17 -17
  37. package/dist/Interfaces/Cart/IPandaPayload.d.ts +64 -64
  38. package/dist/Interfaces/Cart/IPandaPayload.js +18 -18
  39. package/dist/Interfaces/Cart/IPaymentCard.d.ts +22 -22
  40. package/dist/Interfaces/Cart/IPaymentCard.js +44 -44
  41. package/dist/Interfaces/Cart/IPaypalPayload.d.ts +9 -9
  42. package/dist/Interfaces/Cart/IPaypalPayload.js +2 -2
  43. package/dist/Interfaces/Cart/IPaysafePayload.d.ts +72 -72
  44. package/dist/Interfaces/Cart/IPaysafePayload.js +2 -2
  45. package/dist/Interfaces/Cart/IStripePayload.d.ts +66 -66
  46. package/dist/Interfaces/Cart/IStripePayload.js +2 -2
  47. package/dist/Interfaces/Cart/index.d.ts +439 -439
  48. package/dist/Interfaces/Cart/index.js +197 -197
  49. package/dist/Interfaces/CartReservedQuantities/index.d.ts +10 -10
  50. package/dist/Interfaces/CartReservedQuantities/index.js +2 -2
  51. package/dist/Interfaces/Catalogue/index.d.ts +68 -68
  52. package/dist/Interfaces/Catalogue/index.js +37 -37
  53. package/dist/Interfaces/Category/index.d.ts +33 -33
  54. package/dist/Interfaces/Category/index.js +2 -2
  55. package/dist/Interfaces/Chart/index.d.ts +11 -11
  56. package/dist/Interfaces/Chart/index.js +2 -2
  57. package/dist/Interfaces/Class/index.d.ts +8 -8
  58. package/dist/Interfaces/Class/index.js +2 -2
  59. package/dist/Interfaces/Consent/index.d.ts +6 -6
  60. package/dist/Interfaces/Consent/index.js +2 -2
  61. package/dist/Interfaces/Context/IContextProps.d.ts +4 -4
  62. package/dist/Interfaces/Context/IContextProps.js +2 -2
  63. package/dist/Interfaces/Context/IContextState.d.ts +15 -15
  64. package/dist/Interfaces/Context/IContextState.js +2 -2
  65. package/dist/Interfaces/Customer/ICustomerBadge.d.ts +2 -2
  66. package/dist/Interfaces/Customer/ICustomerBadge.js +2 -2
  67. package/dist/Interfaces/Customer/ICustomerRating.d.ts +10 -10
  68. package/dist/Interfaces/Customer/ICustomerRating.js +2 -2
  69. package/dist/Interfaces/Customer/IStoreCredit.d.ts +13 -13
  70. package/dist/Interfaces/Customer/IStoreCredit.js +2 -2
  71. package/dist/Interfaces/Customer/index.d.ts +104 -104
  72. package/dist/Interfaces/Customer/index.js +148 -148
  73. package/dist/Interfaces/Declination/index.d.ts +114 -114
  74. package/dist/Interfaces/Declination/index.js +66 -66
  75. package/dist/Interfaces/Document/index.d.ts +8 -8
  76. package/dist/Interfaces/Document/index.js +2 -2
  77. package/dist/Interfaces/Elastic/index.d.ts +89 -89
  78. package/dist/Interfaces/Elastic/index.js +2 -2
  79. package/dist/Interfaces/Email/CustomGR/I3DPrintEmail.d.ts +11 -11
  80. package/dist/Interfaces/Email/CustomGR/I3DPrintEmail.js +2 -2
  81. package/dist/Interfaces/Email/CustomGR/IBorrowToolsEmail.d.ts +15 -15
  82. package/dist/Interfaces/Email/CustomGR/IBorrowToolsEmail.js +2 -2
  83. package/dist/Interfaces/Email/CustomGR/IPickupMaterialsEmail.d.ts +12 -12
  84. package/dist/Interfaces/Email/CustomGR/IPickupMaterialsEmail.js +2 -2
  85. package/dist/Interfaces/Email/CustomGR/IPreMeetingFormEmail.d.ts +36 -36
  86. package/dist/Interfaces/Email/CustomGR/IPreMeetingFormEmail.js +2 -2
  87. package/dist/Interfaces/Email/CustomGR/ISponsorRequestEmail.d.ts +12 -12
  88. package/dist/Interfaces/Email/CustomGR/ISponsorRequestEmail.js +2 -2
  89. package/dist/Interfaces/Email/CustomGR/ITransportEmail.d.ts +12 -12
  90. package/dist/Interfaces/Email/CustomGR/ITransportEmail.js +2 -2
  91. package/dist/Interfaces/Email/CustomGR/ITransportQuoteEmail.d.ts +12 -12
  92. package/dist/Interfaces/Email/CustomGR/ITransportQuoteEmail.js +2 -2
  93. package/dist/Interfaces/Email/CustomGR/IVegetalsEmail.d.ts +16 -16
  94. package/dist/Interfaces/Email/CustomGR/IVegetalsEmail.js +2 -2
  95. package/dist/Interfaces/Email/CustomGR/IWishlistEmail.d.ts +15 -15
  96. package/dist/Interfaces/Email/CustomGR/IWishlistEmail.js +2 -2
  97. package/dist/Interfaces/Email/IAbandonnedCartEmail.d.ts +29 -29
  98. package/dist/Interfaces/Email/IAbandonnedCartEmail.js +2 -2
  99. package/dist/Interfaces/Email/IAccountConfirmationEmail.d.ts +22 -22
  100. package/dist/Interfaces/Email/IAccountConfirmationEmail.js +2 -2
  101. package/dist/Interfaces/Email/IApplicationEmail.d.ts +19 -19
  102. package/dist/Interfaces/Email/IApplicationEmail.js +2 -2
  103. package/dist/Interfaces/Email/IBackInStockEmail.d.ts +21 -21
  104. package/dist/Interfaces/Email/IBackInStockEmail.js +2 -2
  105. package/dist/Interfaces/Email/IContactEmail.d.ts +20 -20
  106. package/dist/Interfaces/Email/IContactEmail.js +2 -2
  107. package/dist/Interfaces/Email/ICustomerBookingAdminEmail.d.ts +15 -15
  108. package/dist/Interfaces/Email/ICustomerBookingAdminEmail.js +2 -2
  109. package/dist/Interfaces/Email/ICustomerBookingEmail.d.ts +14 -14
  110. package/dist/Interfaces/Email/ICustomerBookingEmail.js +2 -2
  111. package/dist/Interfaces/Email/IEmail.d.ts +20 -20
  112. package/dist/Interfaces/Email/IEmail.js +60 -60
  113. package/dist/Interfaces/Email/IOrderConfirmationEmail.d.ts +47 -47
  114. package/dist/Interfaces/Email/IOrderConfirmationEmail.js +2 -2
  115. package/dist/Interfaces/Email/IPasswordResetEmail.d.ts +17 -17
  116. package/dist/Interfaces/Email/IPasswordResetEmail.js +2 -2
  117. package/dist/Interfaces/Email/IPhotoShootEmail.d.ts +14 -14
  118. package/dist/Interfaces/Email/IPhotoShootEmail.js +2 -2
  119. package/dist/Interfaces/Email/IPickupConfirmation.d.ts +23 -23
  120. package/dist/Interfaces/Email/IPickupConfirmation.js +2 -2
  121. package/dist/Interfaces/Email/IShippingConfirmation.d.ts +23 -23
  122. package/dist/Interfaces/Email/IShippingConfirmation.js +2 -2
  123. package/dist/Interfaces/Email/IWelcomeEmail.d.ts +19 -19
  124. package/dist/Interfaces/Email/IWelcomeEmail.js +2 -2
  125. package/dist/Interfaces/ExportSchema/index.d.ts +7 -7
  126. package/dist/Interfaces/ExportSchema/index.js +2 -2
  127. package/dist/Interfaces/ExternalService/BaseExternalService.d.ts +12 -12
  128. package/dist/Interfaces/ExternalService/BaseExternalService.js +2 -2
  129. package/dist/Interfaces/ExternalService/ExternalProductsService.d.ts +4 -4
  130. package/dist/Interfaces/ExternalService/ExternalProductsService.js +2 -2
  131. package/dist/Interfaces/ExternalService/index.d.ts +9 -9
  132. package/dist/Interfaces/ExternalService/index.js +2 -2
  133. package/dist/Interfaces/FirstOrderTracking/index.d.ts +5 -5
  134. package/dist/Interfaces/FirstOrderTracking/index.js +2 -2
  135. package/dist/Interfaces/G2/index.d.ts +556 -556
  136. package/dist/Interfaces/G2/index.js +38 -38
  137. package/dist/Interfaces/Indexed/Product/IIndexedLastSavedProduct.d.ts +20 -20
  138. package/dist/Interfaces/Indexed/Product/IIndexedLastSavedProduct.js +2 -2
  139. package/dist/Interfaces/Indexed/Product/index.d.ts +103 -103
  140. package/dist/Interfaces/Indexed/Product/index.js +253 -253
  141. package/dist/Interfaces/Inventory/index.d.ts +19 -19
  142. package/dist/Interfaces/Inventory/index.js +8 -8
  143. package/dist/Interfaces/Invoice/index.d.ts +4 -4
  144. package/dist/Interfaces/Invoice/index.js +2 -2
  145. package/dist/Interfaces/MarketplacePublication/MarketplaceOrderData.d.ts +3 -3
  146. package/dist/Interfaces/MarketplacePublication/MarketplaceOrderData.js +2 -2
  147. package/dist/Interfaces/MarketplacePublication/index.d.ts +23 -23
  148. package/dist/Interfaces/MarketplacePublication/index.js +22 -22
  149. package/dist/Interfaces/Menu/index.d.ts +40 -40
  150. package/dist/Interfaces/Menu/index.js +16 -16
  151. package/dist/Interfaces/Note/index.d.ts +10 -10
  152. package/dist/Interfaces/Note/index.js +7 -7
  153. package/dist/Interfaces/Operations/ICreatedBy.d.ts +6 -6
  154. package/dist/Interfaces/Operations/ICreatedBy.js +2 -2
  155. package/dist/Interfaces/Operations/IUpdate.d.ts +5 -5
  156. package/dist/Interfaces/Operations/IUpdate.js +2 -2
  157. package/dist/Interfaces/Order/index.d.ts +4 -4
  158. package/dist/Interfaces/Order/index.js +2 -2
  159. package/dist/Interfaces/Org/IRelUser.d.ts +9 -9
  160. package/dist/Interfaces/Org/IRelUser.js +2 -2
  161. package/dist/Interfaces/Org/index.d.ts +29 -29
  162. package/dist/Interfaces/Org/index.js +12 -12
  163. package/dist/Interfaces/Payment/index.d.ts +26 -26
  164. package/dist/Interfaces/Payment/index.js +14 -14
  165. package/dist/Interfaces/Product/IAttributeFamily.d.ts +6 -6
  166. package/dist/Interfaces/Product/IAttributeFamily.js +2 -2
  167. package/dist/Interfaces/Product/IImportProduct.d.ts +42 -42
  168. package/dist/Interfaces/Product/IImportProduct.js +882 -882
  169. package/dist/Interfaces/Product/IInventoryItem.d.ts +74 -74
  170. package/dist/Interfaces/Product/IInventoryItem.js +38 -38
  171. package/dist/Interfaces/Product/IPricing.d.ts +177 -177
  172. package/dist/Interfaces/Product/IPricing.js +180 -180
  173. package/dist/Interfaces/Product/index.d.ts +138 -138
  174. package/dist/Interfaces/Product/index.js +64 -64
  175. package/dist/Interfaces/ProductAttribute/index.d.ts +11 -11
  176. package/dist/Interfaces/ProductAttribute/index.js +2 -2
  177. package/dist/Interfaces/PromiseToPurchase/BankType.d.ts +41 -41
  178. package/dist/Interfaces/PromiseToPurchase/BankType.js +41 -41
  179. package/dist/Interfaces/PromiseToPurchase/IIndexedBankUsed.d.ts +33 -33
  180. package/dist/Interfaces/PromiseToPurchase/IIndexedBankUsed.js +15 -15
  181. package/dist/Interfaces/PromiseToPurchase/IIndexedCustomerPromiseToPurchase.d.ts +19 -19
  182. package/dist/Interfaces/PromiseToPurchase/IIndexedCustomerPromiseToPurchase.js +2 -2
  183. package/dist/Interfaces/PromiseToPurchase/index.d.ts +50 -50
  184. package/dist/Interfaces/PromiseToPurchase/index.js +13 -13
  185. package/dist/Interfaces/PurchaseOrder/index.d.ts +17 -17
  186. package/dist/Interfaces/PurchaseOrder/index.js +2 -2
  187. package/dist/Interfaces/Query/IBrandQueryOptions.d.ts +11 -11
  188. package/dist/Interfaces/Query/IBrandQueryOptions.js +2 -2
  189. package/dist/Interfaces/Query/ICategoryQueryOptions.d.ts +11 -11
  190. package/dist/Interfaces/Query/ICategoryQueryOptions.js +2 -2
  191. package/dist/Interfaces/Query/IProductQueryOptions.d.ts +16 -16
  192. package/dist/Interfaces/Query/IProductQueryOptions.js +2 -2
  193. package/dist/Interfaces/Quote/index.d.ts +5 -5
  194. package/dist/Interfaces/Quote/index.js +2 -2
  195. package/dist/Interfaces/Refunds/index.d.ts +106 -106
  196. package/dist/Interfaces/Refunds/index.js +2 -2
  197. package/dist/Interfaces/Rules/IDiscountRule.d.ts +155 -155
  198. package/dist/Interfaces/Rules/IDiscountRule.js +114 -114
  199. package/dist/Interfaces/Schedule/index.d.ts +48 -48
  200. package/dist/Interfaces/Schedule/index.js +2 -2
  201. package/dist/Interfaces/Services/IAddServiceResponse.d.ts +4 -4
  202. package/dist/Interfaces/Services/IAddServiceResponse.js +2 -2
  203. package/dist/Interfaces/Services/IService.d.ts +16 -16
  204. package/dist/Interfaces/Services/IService.js +2 -2
  205. package/dist/Interfaces/Services/IServiceSecret.d.ts +8 -8
  206. package/dist/Interfaces/Services/IServiceSecret.js +2 -2
  207. package/dist/Interfaces/Shipping/Shipstation/carriers.d.ts +10 -10
  208. package/dist/Interfaces/Shipping/Shipstation/carriers.js +2 -2
  209. package/dist/Interfaces/Shipping/Shipstation/order.d.ts +227 -227
  210. package/dist/Interfaces/Shipping/Shipstation/order.js +2 -2
  211. package/dist/Interfaces/Shipping/Shipstation/quote.d.ts +31 -31
  212. package/dist/Interfaces/Shipping/Shipstation/quote.js +2 -2
  213. package/dist/Interfaces/Shipping/Shiptime/order.d.ts +54 -54
  214. package/dist/Interfaces/Shipping/Shiptime/order.js +71 -71
  215. package/dist/Interfaces/Shipping/Shiptime/quote.d.ts +111 -111
  216. package/dist/Interfaces/Shipping/Shiptime/quote.js +2 -2
  217. package/dist/Interfaces/Slider/GR.d.ts +114 -114
  218. package/dist/Interfaces/Slider/GR.js +271 -271
  219. package/dist/Interfaces/Slider/index.d.ts +30 -30
  220. package/dist/Interfaces/Slider/index.js +2 -2
  221. package/dist/Interfaces/Space/IExternalService.d.ts +52 -52
  222. package/dist/Interfaces/Space/IExternalService.js +43 -43
  223. package/dist/Interfaces/Space/IMember.d.ts +16 -16
  224. package/dist/Interfaces/Space/IMember.js +9 -9
  225. package/dist/Interfaces/Space/index.d.ts +401 -401
  226. package/dist/Interfaces/Space/index.js +172 -172
  227. package/dist/Interfaces/Specials/gr.d.ts +61 -61
  228. package/dist/Interfaces/Specials/gr.js +2 -2
  229. package/dist/Interfaces/StockNotification/index.d.ts +7 -7
  230. package/dist/Interfaces/StockNotification/index.js +2 -2
  231. package/dist/Interfaces/Store/index.d.ts +63 -63
  232. package/dist/Interfaces/Store/index.js +27 -27
  233. package/dist/Interfaces/Supplier/ICommand.d.ts +11 -11
  234. package/dist/Interfaces/Supplier/ICommand.js +2 -2
  235. package/dist/Interfaces/Supplier/index.d.ts +36 -36
  236. package/dist/Interfaces/Supplier/index.js +24 -24
  237. package/dist/Interfaces/TCG/index.d.ts +161 -161
  238. package/dist/Interfaces/TCG/index.js +54 -54
  239. package/dist/Interfaces/Tag/index.d.ts +18 -18
  240. package/dist/Interfaces/Tag/index.js +2 -2
  241. package/dist/Interfaces/Tax/index.d.ts +13 -13
  242. package/dist/Interfaces/Tax/index.js +2 -2
  243. package/dist/Interfaces/TransferRequest/index.d.ts +103 -103
  244. package/dist/Interfaces/TransferRequest/index.js +46 -46
  245. package/dist/Interfaces/Translation/index.d.ts +8 -8
  246. package/dist/Interfaces/Translation/index.js +5 -5
  247. package/dist/Interfaces/Update/index.d.ts +10 -10
  248. package/dist/Interfaces/Update/index.js +2 -2
  249. package/dist/Interfaces/User/IUser.d.ts +65 -65
  250. package/dist/Interfaces/User/IUser.js +8 -8
  251. package/dist/Interfaces/Version/index.d.ts +11 -11
  252. package/dist/Interfaces/Version/index.js +2 -2
  253. package/dist/Interfaces/Wishlist/index.d.ts +7 -7
  254. package/dist/Interfaces/Wishlist/index.js +2 -2
  255. package/dist/constants/Interfaces/IBaseApi.d.ts +15 -15
  256. package/dist/constants/Interfaces/IBaseApi.js +2 -2
  257. package/dist/constants/Interfaces/IEndpointResult.d.ts +9 -9
  258. package/dist/constants/Interfaces/IEndpointResult.js +2 -2
  259. package/dist/constants/enums.d.ts +6 -6
  260. package/dist/constants/enums.js +10 -10
  261. package/dist/constants/services.d.ts +2 -2
  262. package/dist/constants/services.js +112 -112
  263. package/dist/constants/version.d.ts +2 -2
  264. package/dist/constants/version.js +5 -5
  265. package/dist/index.d.ts +50 -50
  266. package/dist/index.js +266 -266
  267. package/dist/lib/Attribute/index.d.ts +14 -14
  268. package/dist/lib/Attribute/index.js +186 -186
  269. package/dist/lib/BGJob/index.d.ts +9 -9
  270. package/dist/lib/BGJob/index.js +216 -216
  271. package/dist/lib/BackgroundWorker/index.d.ts +34 -34
  272. package/dist/lib/BackgroundWorker/index.js +59 -59
  273. package/dist/lib/Blog/BlogArticle.d.ts +5 -5
  274. package/dist/lib/Blog/BlogArticle.js +10 -10
  275. package/dist/lib/Blog/BlogAuthor.d.ts +5 -5
  276. package/dist/lib/Blog/BlogAuthor.js +10 -10
  277. package/dist/lib/Blog/BlogCategory.d.ts +5 -5
  278. package/dist/lib/Blog/BlogCategory.js +10 -10
  279. package/dist/lib/Blog/BlogKeyword.d.ts +5 -5
  280. package/dist/lib/Blog/BlogKeyword.js +10 -10
  281. package/dist/lib/Booking/index.d.ts +85 -85
  282. package/dist/lib/Booking/index.js +596 -596
  283. package/dist/lib/Brand/index.d.ts +26 -26
  284. package/dist/lib/Brand/index.js +131 -131
  285. package/dist/lib/Cart/index.d.ts +335 -335
  286. package/dist/lib/Cart/index.js +3977 -3977
  287. package/dist/lib/CartReservedQuantities/index.d.ts +49 -49
  288. package/dist/lib/CartReservedQuantities/index.js +159 -159
  289. package/dist/lib/Catalogue/index.d.ts +15 -15
  290. package/dist/lib/Catalogue/index.js +78 -78
  291. package/dist/lib/Category/index.d.ts +34 -34
  292. package/dist/lib/Category/index.js +230 -230
  293. package/dist/lib/Class/index.d.ts +16 -16
  294. package/dist/lib/Class/index.js +66 -66
  295. package/dist/lib/Consent/index.d.ts +4 -4
  296. package/dist/lib/Consent/index.js +29 -29
  297. package/dist/lib/Customer/index.d.ts +30 -30
  298. package/dist/lib/Customer/index.js +92 -92
  299. package/dist/lib/Declination/index.d.ts +9 -9
  300. package/dist/lib/Declination/index.js +26 -26
  301. package/dist/lib/Discount/index.d.ts +27 -27
  302. package/dist/lib/Discount/index.js +493 -493
  303. package/dist/lib/ElasticSearch/index.d.ts +13 -13
  304. package/dist/lib/ElasticSearch/index.js +50 -50
  305. package/dist/lib/Elavon/index.d.ts +18 -18
  306. package/dist/lib/Elavon/index.js +135 -135
  307. package/dist/lib/Email/AbandonedCartEmail.d.ts +16 -16
  308. package/dist/lib/Email/AbandonedCartEmail.js +24 -24
  309. package/dist/lib/Email/AccountConfirmationEmail.d.ts +19 -19
  310. package/dist/lib/Email/AccountConfirmationEmail.js +30 -30
  311. package/dist/lib/Email/AdminOrderConfirmationEmail.d.ts +16 -16
  312. package/dist/lib/Email/AdminOrderConfirmationEmail.js +24 -24
  313. package/dist/lib/Email/ApplicationEmail.d.ts +16 -16
  314. package/dist/lib/Email/ApplicationEmail.js +24 -24
  315. package/dist/lib/Email/BackInStockEmail.d.ts +16 -16
  316. package/dist/lib/Email/BackInStockEmail.js +24 -24
  317. package/dist/lib/Email/ContactEmail.d.ts +16 -16
  318. package/dist/lib/Email/ContactEmail.js +24 -24
  319. package/dist/lib/Email/CustomerBookingAdminEmail.d.ts +16 -16
  320. package/dist/lib/Email/CustomerBookingAdminEmail.js +24 -24
  321. package/dist/lib/Email/CustomerBookingEmail.d.ts +16 -16
  322. package/dist/lib/Email/CustomerBookingEmail.js +24 -24
  323. package/dist/lib/Email/OrderConfirmationEmail.d.ts +16 -16
  324. package/dist/lib/Email/OrderConfirmationEmail.js +24 -24
  325. package/dist/lib/Email/OrderDenounciationEmail.d.ts +16 -16
  326. package/dist/lib/Email/OrderDenounciationEmail.js +24 -24
  327. package/dist/lib/Email/OrderSampleEmail.d.ts +16 -16
  328. package/dist/lib/Email/OrderSampleEmail.js +24 -24
  329. package/dist/lib/Email/OtherTypeEmails.d.ts +16 -16
  330. package/dist/lib/Email/OtherTypeEmails.js +27 -27
  331. package/dist/lib/Email/PasswordResetEmail.d.ts +16 -16
  332. package/dist/lib/Email/PasswordResetEmail.js +24 -24
  333. package/dist/lib/Email/PhotoShootEmail.d.ts +16 -16
  334. package/dist/lib/Email/PhotoShootEmail.js +24 -24
  335. package/dist/lib/Email/PickUpConfirmation.d.ts +16 -16
  336. package/dist/lib/Email/PickUpConfirmation.js +24 -24
  337. package/dist/lib/Email/ShippingConfirmation.d.ts +16 -16
  338. package/dist/lib/Email/ShippingConfirmation.js +24 -24
  339. package/dist/lib/Email/WelcomeEmail.d.ts +16 -16
  340. package/dist/lib/Email/WelcomeEmail.js +24 -24
  341. package/dist/lib/Email/index.d.ts +16 -16
  342. package/dist/lib/Email/index.js +31 -31
  343. package/dist/lib/ExternalService/Ebay.d.ts +74 -74
  344. package/dist/lib/ExternalService/Ebay.js +124 -124
  345. package/dist/lib/ExternalService/index.d.ts +5 -5
  346. package/dist/lib/ExternalService/index.js +10 -10
  347. package/dist/lib/FirstOrderTracking/index.d.ts +5 -5
  348. package/dist/lib/FirstOrderTracking/index.js +10 -10
  349. package/dist/lib/Indexed/IndexedCart.d.ts +13 -13
  350. package/dist/lib/Indexed/IndexedCart.js +91 -91
  351. package/dist/lib/Indexed/Product.d.ts +17 -17
  352. package/dist/lib/Indexed/Product.js +98 -98
  353. package/dist/lib/Inventory/index.d.ts +112 -112
  354. package/dist/lib/Inventory/index.js +492 -492
  355. package/dist/lib/Invoice/index.d.ts +16 -16
  356. package/dist/lib/Invoice/index.js +21 -21
  357. package/dist/lib/MarketplacePublication/index.d.ts +9 -9
  358. package/dist/lib/MarketplacePublication/index.js +426 -426
  359. package/dist/lib/Menu/index.d.ts +11 -11
  360. package/dist/lib/Menu/index.js +107 -107
  361. package/dist/lib/MongoDB/BaseAPI.d.ts +18 -18
  362. package/dist/lib/MongoDB/BaseAPI.js +200 -200
  363. package/dist/lib/Note/index.d.ts +4 -4
  364. package/dist/lib/Note/index.js +6 -6
  365. package/dist/lib/Order/index.d.ts +27 -27
  366. package/dist/lib/Order/index.js +56 -56
  367. package/dist/lib/Org/index.d.ts +68 -68
  368. package/dist/lib/Org/index.js +216 -216
  369. package/dist/lib/PandaPay/index.d.ts +16 -16
  370. package/dist/lib/PandaPay/index.js +176 -176
  371. package/dist/lib/Paysafe/index.d.ts +11 -11
  372. package/dist/lib/Paysafe/index.js +41 -41
  373. package/dist/lib/Product/index.d.ts +182 -182
  374. package/dist/lib/Product/index.js +847 -847
  375. package/dist/lib/ProductAttribute/index.d.ts +15 -15
  376. package/dist/lib/ProductAttribute/index.js +45 -45
  377. package/dist/lib/PromiseToPurchase/index.d.ts +109 -109
  378. package/dist/lib/PromiseToPurchase/index.js +343 -343
  379. package/dist/lib/PurchaseOrder/index.d.ts +20 -20
  380. package/dist/lib/PurchaseOrder/index.js +28 -28
  381. package/dist/lib/Queue/index.d.ts +40 -40
  382. package/dist/lib/Queue/index.js +254 -254
  383. package/dist/lib/Schedule/index.d.ts +5 -5
  384. package/dist/lib/Schedule/index.js +12 -12
  385. package/dist/lib/Service/Enum/ServiceEnum.d.ts +3 -3
  386. package/dist/lib/Service/Enum/ServiceEnum.js +7 -7
  387. package/dist/lib/Service/index.d.ts +13 -13
  388. package/dist/lib/Service/index.js +21 -21
  389. package/dist/lib/Shipment/index.d.ts +28 -28
  390. package/dist/lib/Shipment/index.js +370 -370
  391. package/dist/lib/Slider/index.d.ts +22 -22
  392. package/dist/lib/Slider/index.js +119 -119
  393. package/dist/lib/Space/index.d.ts +1069 -1069
  394. package/dist/lib/Space/index.js +5638 -5638
  395. package/dist/lib/StockNotification/index.d.ts +4 -4
  396. package/dist/lib/StockNotification/index.js +6 -6
  397. package/dist/lib/Store/index.d.ts +5 -5
  398. package/dist/lib/Store/index.js +12 -12
  399. package/dist/lib/Supplier/Command.d.ts +5 -5
  400. package/dist/lib/Supplier/Command.js +10 -10
  401. package/dist/lib/Supplier/index.d.ts +25 -25
  402. package/dist/lib/Supplier/index.js +27 -27
  403. package/dist/lib/Tags/index.d.ts +6 -6
  404. package/dist/lib/Tags/index.js +26 -26
  405. package/dist/lib/Tax/index.d.ts +8 -8
  406. package/dist/lib/Tax/index.js +54 -54
  407. package/dist/lib/TransferRequest/index.d.ts +290 -290
  408. package/dist/lib/TransferRequest/index.js +1026 -1026
  409. package/dist/lib/Update/index.d.ts +10 -10
  410. package/dist/lib/Update/index.js +22 -22
  411. package/dist/lib/User/index.d.ts +89 -89
  412. package/dist/lib/User/index.js +328 -328
  413. package/dist/lib/Wishlist/index.d.ts +5 -5
  414. package/dist/lib/Wishlist/index.js +10 -10
  415. package/dist/lib/base.d.ts +14 -14
  416. package/dist/lib/base.js +62 -62
  417. package/dist/lib/baseService.d.ts +17 -17
  418. package/dist/lib/baseService.js +69 -69
  419. package/dist/rules/GR/constants/data.d.ts +26 -26
  420. package/dist/rules/GR/constants/data.js +77 -77
  421. package/dist/rules/GR/constants/expedition.d.ts +4 -4
  422. package/dist/rules/GR/constants/expedition.js +9 -9
  423. package/dist/rules/GR/constants/products.d.ts +14 -14
  424. package/dist/rules/GR/constants/products.js +254 -254
  425. package/dist/rules/GR/interfaces/cart.d.ts +84 -84
  426. package/dist/rules/GR/interfaces/cart.js +41 -41
  427. package/dist/rules/GR/interfaces/data.d.ts +99 -99
  428. package/dist/rules/GR/interfaces/data.js +112 -112
  429. package/dist/rules/GR/interfaces/products.d.ts +61 -61
  430. package/dist/rules/GR/interfaces/products.js +10 -10
  431. package/dist/rules/GR/utils/cart.d.ts +95 -95
  432. package/dist/rules/GR/utils/cart.js +797 -797
  433. package/dist/rules/GR/utils/data.d.ts +3 -3
  434. package/dist/rules/GR/utils/data.js +28 -28
  435. package/dist/rules/GR/utils/expedition.d.ts +140 -140
  436. package/dist/rules/GR/utils/expedition.js +1933 -1933
  437. package/dist/rules/GR/utils/g2.d.ts +209 -209
  438. package/dist/rules/GR/utils/g2.js +999 -999
  439. package/dist/rules/GR/utils/invoices.d.ts +51 -51
  440. package/dist/rules/GR/utils/invoices.js +215 -215
  441. package/dist/rules/GR/utils/products.d.ts +276 -276
  442. package/dist/rules/GR/utils/products.js +1335 -1335
  443. package/dist/rules/GR/utils/upsells.d.ts +111 -111
  444. package/dist/rules/GR/utils/upsells.js +215 -215
  445. package/dist/services/database/BaseProvider.d.ts +29 -29
  446. package/dist/services/database/BaseProvider.js +28 -28
  447. package/dist/services/database/BatchUtils.d.ts +14 -14
  448. package/dist/services/database/BatchUtils.js +43 -43
  449. package/dist/services/database/Config.d.ts +2 -2
  450. package/dist/services/database/Config.js +5 -5
  451. package/dist/services/database/DatabaseService.d.ts +125 -125
  452. package/dist/services/database/DatabaseService.js +237 -237
  453. package/dist/services/database/FirebaseProvider.d.ts +17 -17
  454. package/dist/services/database/FirebaseProvider.js +235 -235
  455. package/dist/services/database/NotFirebaseProvider.d.ts +49 -49
  456. package/dist/services/database/NotFirebaseProvider.js +262 -262
  457. package/dist/services/g2/G2OrderSlip.d.ts +49 -49
  458. package/dist/services/g2/G2OrderSlip.js +228 -228
  459. package/dist/services/g2/utils.d.ts +19 -19
  460. package/dist/services/g2/utils.js +953 -953
  461. package/dist/services/logs/index.d.ts +23 -23
  462. package/dist/services/logs/index.js +66 -66
  463. package/dist/services/products/BaseClass.d.ts +50 -50
  464. package/dist/services/products/BaseClass.js +66 -66
  465. package/dist/services/products/TCGService.d.ts +32 -32
  466. package/dist/services/products/TCGService.js +555 -555
  467. package/dist/services/products/utils.d.ts +31 -31
  468. package/dist/services/products/utils.js +144 -144
  469. package/dist/utils/algolia.d.ts +46 -46
  470. package/dist/utils/algolia.js +21 -21
  471. package/dist/utils/anonymisation.d.ts +54 -54
  472. package/dist/utils/anonymisation.js +280 -280
  473. package/dist/utils/array.d.ts +5 -5
  474. package/dist/utils/array.js +14 -14
  475. package/dist/utils/aws.d.ts +36 -36
  476. package/dist/utils/aws.js +154 -154
  477. package/dist/utils/booking.d.ts +30 -30
  478. package/dist/utils/booking.js +127 -127
  479. package/dist/utils/cart.d.ts +250 -250
  480. package/dist/utils/cart.js +1121 -1121
  481. package/dist/utils/categories.d.ts +2 -2
  482. package/dist/utils/categories.js +54 -54
  483. package/dist/utils/cmv.d.ts +10 -10
  484. package/dist/utils/cmv.js +107 -107
  485. package/dist/utils/console.d.ts +6 -6
  486. package/dist/utils/console.js +59 -59
  487. package/dist/utils/context.d.ts +20 -20
  488. package/dist/utils/context.js +61 -61
  489. package/dist/utils/currency.d.ts +6 -6
  490. package/dist/utils/currency.js +91 -91
  491. package/dist/utils/data.d.ts +31 -31
  492. package/dist/utils/data.js +296 -296
  493. package/dist/utils/date.d.ts +1 -1
  494. package/dist/utils/date.js +16 -16
  495. package/dist/utils/dimensions.d.ts +3 -3
  496. package/dist/utils/dimensions.js +16 -16
  497. package/dist/utils/discount.d.ts +164 -164
  498. package/dist/utils/discount.js +1111 -1111
  499. package/dist/utils/errors.d.ts +113 -113
  500. package/dist/utils/errors.js +113 -113
  501. package/dist/utils/file-admin.d.ts +8 -8
  502. package/dist/utils/file-admin.js +39 -39
  503. package/dist/utils/file.d.ts +39 -39
  504. package/dist/utils/file.js +208 -208
  505. package/dist/utils/firebase-admin.d.ts +11 -11
  506. package/dist/utils/firebase-admin.js +73 -73
  507. package/dist/utils/firebase.d.ts +58 -58
  508. package/dist/utils/firebase.js +148 -148
  509. package/dist/utils/import.d.ts +1 -1
  510. package/dist/utils/import.js +21 -21
  511. package/dist/utils/inventories.d.ts +101 -101
  512. package/dist/utils/inventories.js +467 -467
  513. package/dist/utils/locale.d.ts +24 -24
  514. package/dist/utils/locale.js +87 -87
  515. package/dist/utils/mailchimp.d.ts +58 -58
  516. package/dist/utils/mailchimp.js +531 -531
  517. package/dist/utils/mathUtils.d.ts +17 -17
  518. package/dist/utils/mathUtils.js +324 -324
  519. package/dist/utils/mongodb.d.ts +1 -1
  520. package/dist/utils/mongodb.js +22 -22
  521. package/dist/utils/object.d.ts +32 -32
  522. package/dist/utils/object.js +133 -133
  523. package/dist/utils/payment.d.ts +10 -10
  524. package/dist/utils/payment.js +23 -23
  525. package/dist/utils/products.d.ts +39 -39
  526. package/dist/utils/products.js +195 -195
  527. package/dist/utils/promiseToPurchase.d.ts +88 -88
  528. package/dist/utils/promiseToPurchase.js +229 -229
  529. package/dist/utils/prosprsearch.d.ts +42 -42
  530. package/dist/utils/prosprsearch.js +216 -216
  531. package/dist/utils/refunds.d.ts +2 -2
  532. package/dist/utils/refunds.js +21 -21
  533. package/dist/utils/sdc.d.ts +10 -10
  534. package/dist/utils/sdc.js +1309 -1309
  535. package/dist/utils/searchIndexes.d.ts +58 -58
  536. package/dist/utils/searchIndexes.js +247 -247
  537. package/dist/utils/services.d.ts +42 -42
  538. package/dist/utils/services.js +409 -409
  539. package/dist/utils/shipment.d.ts +110 -110
  540. package/dist/utils/shipment.js +345 -345
  541. package/dist/utils/simpletexting.d.ts +2 -2
  542. package/dist/utils/simpletexting.js +45 -45
  543. package/dist/utils/sliders.d.ts +4 -4
  544. package/dist/utils/sliders.js +24 -24
  545. package/dist/utils/string.d.ts +16 -16
  546. package/dist/utils/string.js +192 -192
  547. package/dist/utils/tcgService.d.ts +74 -73
  548. package/dist/utils/tcgService.js +300 -285
  549. package/dist/utils/tcgService.js.map +1 -1
  550. package/dist/utils/tools.d.ts +5 -5
  551. package/dist/utils/tools.js +13 -13
  552. package/dist/utils/transferRequests.d.ts +43 -43
  553. package/dist/utils/transferRequests.js +67 -67
  554. package/dist/utils/update.d.ts +7 -7
  555. package/dist/utils/update.js +137 -137
  556. package/dist/utils/weight.d.ts +3 -3
  557. package/dist/utils/weight.js +16 -16
  558. package/dist/utils/zones.d.ts +11 -11
  559. package/dist/utils/zones.js +218 -218
  560. package/package.json +107 -107
  561. package/publish.sh +143 -143
  562. package/readme.md +182 -182
@@ -1,1122 +1,1122 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.shouldIgnoreInventoryForItem = exports.getPurchasedPalletsQuantityForCustomer = exports.validateStoreCreditUsage = exports.calculateAmountForCustomPromo = exports.constructStoreCreditPaymentEntry = exports.getLastUserWhoTookPayment = exports.getCartPaymentMethods = exports.getAddressStrArray = exports.adjustPromoPrice = exports.getOriginalDiscountPriceForItem = exports.getOriginalPromoPriceForItem = exports.getAllPromoAppliedPrices = exports.getSubtotalToCheckForPromo = exports.getILangForUpdateType = exports.getItemsToUpdateByTransfer = exports.getItemSaleUnitSlug = exports.getActiveTransfersByItemInCart = exports.getModifiedItems = exports.getOrderStoreInfo = exports.checkIfShippingSameAsBilling = exports.getShippingStoreInfo = exports.getAssignedToInfo = exports.getPaidByForIndexedCart = exports.getIndexedCartData = exports.getTaxProvinceFromShippingAddress = exports.getCurrentProvince = exports.verifyAndReturnToBeAddedCartItems = exports.addCartItems = exports.generateCartItemForSku = exports.getActualDiscountPrice = exports.getActualPromoPrice = exports.priceWasOverridden = exports.deleteCartItem = exports.verifyAndReturnToBeUpdatedCartItems = exports.updateCartItems = void 0;
7
- const toNumber_1 = __importDefault(require("lodash/toNumber"));
8
- const findIndex_1 = __importDefault(require("lodash/findIndex"));
9
- const remove_1 = __importDefault(require("lodash/remove"));
10
- const flatten_1 = __importDefault(require("lodash/flatten"));
11
- const orderBy_1 = __importDefault(require("lodash/orderBy"));
12
- const uniq_1 = __importDefault(require("lodash/uniq"));
13
- const moment_1 = __importDefault(require("moment"));
14
- const isEqual_1 = __importDefault(require("lodash/isEqual"));
15
- const find_1 = __importDefault(require("lodash/find"));
16
- const isNumber_1 = __importDefault(require("lodash/isNumber"));
17
- const round_1 = __importDefault(require("lodash/round"));
18
- const sumBy_1 = __importDefault(require("lodash/sumBy"));
19
- const Cart_1 = require("../Interfaces/Cart");
20
- const string_1 = require("./string");
21
- const g2_1 = require("../rules/GR/utils/g2");
22
- const object_1 = require("./object");
23
- const invoices_1 = require("../rules/GR/utils/invoices");
24
- const data_1 = require("./data");
25
- const services_1 = require("./services");
26
- const discount_1 = require("./discount");
27
- const IDiscountRule_1 = require("../Interfaces/Rules/IDiscountRule");
28
- const products_1 = require("./products");
29
- const TransferRequest_1 = require("../Interfaces/TransferRequest");
30
- const cart_1 = require("../rules/GR/utils/cart");
31
- const cart_2 = require("../rules/GR/interfaces/cart");
32
- const inventories_1 = require("./inventories");
33
- const searchIndexes_1 = require("./searchIndexes");
34
- const Cart_2 = __importDefault(require("../lib/Cart"));
35
- const updateCartItems = async (currentCart, items, fetchInventory, shouldCheckInventory = true, handleInventoryError) => {
36
- let updatedCart = Object.assign({}, currentCart);
37
- const itemsToUpdate = Array.isArray(items) ? items : [items];
38
- const updatedItems = [];
39
- for (const item of itemsToUpdate) {
40
- const cartItemIndex = (0, findIndex_1.default)(updatedCart.items, (i) => i.sku === item.sku);
41
- const cartItem = cartItemIndex !== -1 ? updatedCart.items[cartItemIndex] : undefined;
42
- if (!!cartItem) {
43
- if (!!shouldCheckInventory) {
44
- let inventoryItem = undefined;
45
- try {
46
- inventoryItem = !!cartItem && !!cartItem.is_service ? undefined : await fetchInventory(item.sku);
47
- }
48
- catch (e) {
49
- console.log('error on fetching inventoryItem: ', e);
50
- }
51
- if (!!inventoryItem) {
52
- const webStore = inventoryItem.web_inventory;
53
- // If the item is NOT infinite_stock ans is NOT a service
54
- if (!!!inventoryItem.is_infinite_stock && !!!cartItem.is_service) {
55
- // If webstore is not defined or the avaibility = 0
56
- if (!!!webStore || !!!webStore.available) {
57
- continue;
58
- }
59
- // If the quantity we are setting is more than the available qte of the item
60
- if (item.qte > webStore.available) {
61
- if (!!handleInventoryError) {
62
- await handleInventoryError(true);
63
- }
64
- updatedItems.push({
65
- sku: item.sku,
66
- updated: false
67
- });
68
- continue;
69
- }
70
- }
71
- }
72
- }
73
- updatedCart.items[cartItemIndex] = Object.assign(Object.assign({}, cartItem), { qte: item.qte, qte_override: item.qte_override });
74
- updatedItems.push({ sku: item.sku, updated: true });
75
- }
76
- }
77
- return { updatedCart, updatedItems };
78
- };
79
- exports.updateCartItems = updateCartItems;
80
- /**
81
- * For now, copy of `updateCartItems` function in most aspects, with slight optim. Meant to replace updateCartItems eventually!
82
- * Verify a list of items that could be added to a cart. Returns the list of items to update as well as the updated cart data.
83
- * @param currentCartItems
84
- * @param items
85
- * @param fetchInventory
86
- * @param options.shouldCheckInventory
87
- * @param options.handleInventoryError
88
- * @param options.shouldCheckStoreInventory
89
- * @param options.useReservedInventory if the inventory is reserved on add to cart
90
- */
91
- const verifyAndReturnToBeUpdatedCartItems = async (currentCartItems, items, fetchInventory, options = {}) => {
92
- let updatedCartItems = [...currentCartItems];
93
- const updatedDetails = [];
94
- for (const item of items) {
95
- const cartItemIndex = (0, findIndex_1.default)(updatedCartItems, (i) => i.sku === item.sku);
96
- const cartItem = cartItemIndex !== -1 ? updatedCartItems[cartItemIndex] : undefined;
97
- if (!!cartItem) {
98
- if (!!options.shouldCheckInventory) {
99
- let inventoryItem = undefined;
100
- try {
101
- inventoryItem = !!cartItem && !!cartItem.is_service ? undefined : await fetchInventory(item.sku);
102
- }
103
- catch (e) {
104
- console.log('error on fetching inventoryItem: ', e);
105
- throw new Error('unable to fetch inventory'); // prevent adding without check
106
- }
107
- if (!!inventoryItem) {
108
- // Check store inventory if specified, or default to web inventory
109
- let inventoryToCheck;
110
- if (options.shouldCheckStoreInventory) {
111
- const sameStoreInventory = inventoryItem.inventories.find((i) => i.store_id == options.shouldCheckStoreInventory);
112
- if (!!sameStoreInventory) {
113
- inventoryToCheck = sameStoreInventory.qty.available;
114
- }
115
- }
116
- else {
117
- inventoryToCheck = (0, object_1.recursiveCheckObject)(inventoryItem, 'web_inventory.available');
118
- }
119
- // If no inventory found, continue
120
- if (typeof inventoryToCheck == 'undefined') {
121
- updatedDetails.push({
122
- sku: item.sku,
123
- updated: false
124
- });
125
- continue;
126
- }
127
- // If the item is NOT infinite_stock and is NOT a service
128
- if (!!!inventoryItem.is_infinite_stock && !!!cartItem.is_service) {
129
- // If the avaibility = 0
130
- let qtyToTest = item.qte;
131
- if (!!options.useReservedInventory) {
132
- // only test for added qty, if it's reduced then test will pass even if no item left
133
- qtyToTest = item.qte - cartItem.qte;
134
- }
135
- // If the quantity we are setting is more than the available qte of the item
136
- if (qtyToTest > inventoryToCheck) {
137
- if (!!options.handleInventoryError) {
138
- await options.handleInventoryError(true);
139
- }
140
- updatedDetails.push({
141
- sku: item.sku,
142
- updated: false
143
- });
144
- continue;
145
- }
146
- }
147
- }
148
- }
149
- updatedCartItems[cartItemIndex] = Object.assign(Object.assign({}, cartItem), { qte: item.qte, qte_override: item.qte_override });
150
- updatedDetails.push({ sku: item.sku, updated: true });
151
- }
152
- }
153
- return { updatedCartItems, updatedDetails };
154
- };
155
- exports.verifyAndReturnToBeUpdatedCartItems = verifyAndReturnToBeUpdatedCartItems;
156
- const deleteCartItem = (currentCart, sku, onlyIfUpsellOf) => {
157
- const deletedItemsCart = Object.assign({}, currentCart);
158
- sku.forEach((itm) => (0, remove_1.default)(deletedItemsCart.items, (item) => {
159
- if (!!item.is_upsell_of_sku && !!onlyIfUpsellOf)
160
- return item.sku === itm && item.is_upsell_of_sku === onlyIfUpsellOf;
161
- return item.sku === itm;
162
- }));
163
- return deletedItemsCart;
164
- };
165
- exports.deleteCartItem = deleteCartItem;
166
- const priceWasOverridden = (itemToCheck) => {
167
- return ((!!itemToCheck.promo_price && !!itemToCheck.promo_price.overridden) ||
168
- (!!itemToCheck.discount_price && !!itemToCheck.discount_price.overridden));
169
- };
170
- exports.priceWasOverridden = priceWasOverridden;
171
- const getActualPromoPrice = (item, output) => {
172
- const orgPrice = (0, exports.getActualDiscountPrice)(item, products_1.unitTypeEnum.AMOUNT);
173
- let price = orgPrice; // default value
174
- if (!!item.promo_price) {
175
- price = item.promo_price.amount; // this is the first promo
176
- }
177
- if (output === products_1.unitTypeEnum.PERCENT)
178
- return !!!orgPrice ? 0 : (1 - price / orgPrice) * 100;
179
- return price;
180
- };
181
- exports.getActualPromoPrice = getActualPromoPrice;
182
- const getActualDiscountPrice = (item, output) => {
183
- let price = item.regular_price.amount; // default value
184
- if (!!item.discount_price) {
185
- price = item.discount_price.amount; // this is the first promo
186
- }
187
- if (output === products_1.unitTypeEnum.PERCENT)
188
- return (1 - price / item.regular_price.amount) * 100;
189
- return price;
190
- };
191
- exports.getActualDiscountPrice = getActualDiscountPrice;
192
- /**
193
- * Generate a cart item from corresonding indexedProduct
194
- * @param indexedProduct
195
- * @param sku
196
- * @param qte
197
- */
198
- const generateCartItemForSku = async (indexedProduct, sku, qte) => {
199
- try {
200
- // Isolate decli with corresponding sku
201
- const sameDecli = indexedProduct.declinations.find((d) => d.sku == sku);
202
- if (!sameDecli)
203
- throw new Error('Could not find decli in product!');
204
- // Construct CartItem from decli and prod values
205
- let decliImgs = sameDecli.images_path;
206
- if (!decliImgs || decliImgs.length == 0) {
207
- const parentImgs = indexedProduct.image_files;
208
- if (!!parentImgs && parentImgs.length)
209
- decliImgs = parentImgs.slice(0, 1);
210
- else
211
- decliImgs = [];
212
- }
213
- return Object.assign(Object.assign(Object.assign({}, sameDecli), (!!decliImgs.length ? { images_path: decliImgs } : {})), { qte: qte, parent_slug: indexedProduct.slug, product_upsells: indexedProduct.product_upsells, categories: indexedProduct.categories });
214
- }
215
- catch (e) {
216
- console.log('error on converting prod to cart item: ', e.toString());
217
- return;
218
- }
219
- };
220
- exports.generateCartItemForSku = generateCartItemForSku;
221
- const addCartItems = async (currentCart, newItems, fetchInventory, shouldCheckInventory = true, handleInventoryError, defaultAdd = false, isServiceUpsellOfSku = false, customPriceList) => {
222
- let newCart = Object.assign({}, currentCart);
223
- let items = [...newItems];
224
- if (!!customPriceList) {
225
- items = items.map((i) => !!(0, exports.priceWasOverridden)(i) ? i : (0, g2_1.checkForCustomPriceEquivalent)(i, customPriceList));
226
- }
227
- let itemsToUpdate = [];
228
- const shouldAddItem = async (cartItem) => {
229
- const checkInventory = !!shouldCheckInventory && !!!cartItem.is_service && !!!cartItem.is_upsell_of_sku;
230
- let inventoryItem;
231
- if (!!fetchInventory) {
232
- try {
233
- inventoryItem = !!cartItem.is_service ? undefined : await fetchInventory(cartItem.sku);
234
- }
235
- catch (e) {
236
- console.log('error on fetching inventory: ', e);
237
- }
238
- }
239
- const itemAlreadyInCart = (0, findIndex_1.default)(newCart.items, (item) => item.sku === cartItem.sku);
240
- if (!!checkInventory) {
241
- // If inventory not found, return error
242
- if (!!!inventoryItem)
243
- return 'already_max_qte';
244
- // If the webstore is not defined or the avaibility = 0
245
- if (!!inventoryItem.is_infinite_stock || !!cartItem.is_service || !!cartItem.is_sample)
246
- return cartItem;
247
- if (!!!inventoryItem.web_inventory || !!!inventoryItem.web_inventory.available) {
248
- return false;
249
- }
250
- if (cartItem.qte > inventoryItem.web_inventory.available) {
251
- return 'already_max_qte';
252
- }
253
- if (itemAlreadyInCart !== -1 && !!!isServiceUpsellOfSku) {
254
- // If the quantity we are adding is more than the available qte of the item
255
- if (!!shouldCheckInventory && !!inventoryItem.web_inventory && !!inventoryItem.web_inventory.available) {
256
- if ((0, toNumber_1.default)(newCart.items[itemAlreadyInCart].qte) + (0, toNumber_1.default)(cartItem.qte) >
257
- (0, toNumber_1.default)(inventoryItem.web_inventory.available)) {
258
- return 'already_max_qte';
259
- }
260
- }
261
- itemsToUpdate.push({
262
- sku: cartItem.sku,
263
- qte: (0, toNumber_1.default)(newCart.items[itemAlreadyInCart].qte) + (0, toNumber_1.default)(cartItem.qte)
264
- });
265
- return false;
266
- }
267
- }
268
- if (itemAlreadyInCart !== -1) {
269
- itemsToUpdate.push({
270
- sku: cartItem.sku,
271
- qte: (0, toNumber_1.default)(newCart.items[itemAlreadyInCart].qte) + (0, toNumber_1.default)(cartItem.qte)
272
- });
273
- return false;
274
- }
275
- return cartItem;
276
- };
277
- const itemsToAdd = Array.isArray(items)
278
- ? !!defaultAdd
279
- ? items
280
- : await Promise.all(items.map(async (cartItem) => await shouldAddItem(cartItem)))
281
- : !!defaultAdd
282
- ? [items]
283
- : [await shouldAddItem(items)];
284
- const filteredItems = itemsToAdd.filter((item) => !!item && item !== 'already_max_qte');
285
- const hasMaxQtyItems = itemsToAdd.find((i) => i === 'already_max_qte');
286
- if (!!hasMaxQtyItems && !!handleInventoryError) {
287
- await handleInventoryError(false);
288
- }
289
- if (!!itemsToUpdate.length) {
290
- const updateResult = await (0, exports.updateCartItems)(currentCart, itemsToUpdate, fetchInventory, shouldCheckInventory, handleInventoryError);
291
- if (!!updateResult) {
292
- newCart = updateResult.updatedCart;
293
- }
294
- }
295
- newCart = Object.assign(Object.assign({}, newCart), { items: [...newCart.items, ...filteredItems] });
296
- return {
297
- cartData: newCart,
298
- added: !!filteredItems && !!filteredItems.length,
299
- updated: !!itemsToUpdate && !!itemsToUpdate.length,
300
- maxQtyItems: !!hasMaxQtyItems
301
- };
302
- };
303
- exports.addCartItems = addCartItems;
304
- /**
305
- * Optimized copy of addCartItems function for now. Will eventually replace addCartItems.
306
- * Verify a list of items to be potentially added to cart.
307
- * @param currentCart
308
- * @param newItems
309
- * @param fetchInventory
310
- * @param options
311
- */
312
- const verifyAndReturnToBeAddedCartItems = async (currentCart, newItems, fetchInventory, options = {}) => {
313
- let newCart = Object.assign({}, currentCart);
314
- let items = [...newItems];
315
- if (!!options.customPriceList) {
316
- items = items.map((i) => !!(0, exports.priceWasOverridden)(i) ? i : (0, g2_1.checkForCustomPriceEquivalent)(i, options.customPriceList));
317
- }
318
- let itemsToUpdate = [];
319
- const shouldAddItem = async (cartItem) => {
320
- const checkInventory = !!options.shouldCheckInventory && !!!cartItem.is_service && !!!cartItem.is_upsell_of_sku;
321
- let inventoryItem;
322
- if (!!fetchInventory) {
323
- try {
324
- inventoryItem = !!cartItem.is_service ? undefined : await fetchInventory(cartItem.sku);
325
- }
326
- catch (e) {
327
- console.log('error on fetching inventory: ', e);
328
- }
329
- }
330
- const itemAlreadyInCart = (0, findIndex_1.default)(newCart.items, (item) => item.sku === cartItem.sku);
331
- if (!!checkInventory) {
332
- // If inventory not found, return error
333
- if (!!!inventoryItem)
334
- return 'inventory_not_found';
335
- // Check if item's inventory is not followed (if item is a service, a sample, etc...). Skip check if true
336
- if (inventoryItem.is_infinite_stock || cartItem.is_service || cartItem.is_sample)
337
- return cartItem;
338
- // Check store inventory if specified, or default to web inventory
339
- let inventoryToCheck;
340
- if (options.shouldCheckStoreInventory) {
341
- const sameStoreInventory = inventoryItem.inventories.find((i) => i.store_id == options.shouldCheckStoreInventory);
342
- if (!!sameStoreInventory) {
343
- inventoryToCheck = sameStoreInventory.qty.available;
344
- }
345
- }
346
- else {
347
- inventoryToCheck = (0, object_1.recursiveCheckObject)(inventoryItem, 'web_inventory.available');
348
- }
349
- // If no inventory found, return false
350
- if (typeof inventoryToCheck == 'undefined') {
351
- return 'inventory_not_found';
352
- }
353
- if (cartItem.qte > inventoryToCheck) {
354
- return 'already_max_qte';
355
- }
356
- // If item already in cart
357
- if (itemAlreadyInCart !== -1 && !!!options.isServiceUpsellOfSku) {
358
- // If the quantity we are adding is more than the available qte of the item
359
- if (!!options.shouldCheckInventory && !!inventoryToCheck && !options.useReservedInventory) {
360
- if ((0, toNumber_1.default)(newCart.items[itemAlreadyInCart].qte) + (0, toNumber_1.default)(cartItem.qte) > (0, toNumber_1.default)(inventoryToCheck)) {
361
- return 'already_max_qte';
362
- }
363
- }
364
- itemsToUpdate.push({
365
- sku: cartItem.sku,
366
- qte: (0, toNumber_1.default)(newCart.items[itemAlreadyInCart].qte) + (0, toNumber_1.default)(cartItem.qte)
367
- });
368
- return false;
369
- }
370
- }
371
- if (itemAlreadyInCart !== -1) {
372
- itemsToUpdate.push({
373
- sku: cartItem.sku,
374
- qte: (0, toNumber_1.default)(newCart.items[itemAlreadyInCart].qte) + (0, toNumber_1.default)(cartItem.qte)
375
- });
376
- return false;
377
- }
378
- return cartItem;
379
- };
380
- const itemsToUse = Array.isArray(items) ? items : [items];
381
- const itemsToAdd = !!options.defaultAdd
382
- ? itemsToUse
383
- : await Promise.all(itemsToUse.map(async (cartItem) => await shouldAddItem(cartItem)));
384
- const filteredItems = itemsToAdd.filter((item) => !!item && typeof item !== 'string');
385
- const hasErrors = itemsToAdd.some((i) => i === 'already_max_qte' || i === 'inventory_not_found');
386
- if (!!hasErrors && !!options.handleInventoryError) {
387
- await options.handleInventoryError(false);
388
- }
389
- if (!!itemsToUpdate.length) {
390
- const updateResult = await (0, exports.verifyAndReturnToBeUpdatedCartItems)(currentCart.items, itemsToUpdate, fetchInventory, {
391
- shouldCheckInventory: false
392
- });
393
- if (!!updateResult) {
394
- newCart.items = updateResult.updatedCartItems;
395
- }
396
- }
397
- newCart = Object.assign(Object.assign({}, newCart), { items: [...newCart.items, ...filteredItems] });
398
- return {
399
- cartData: newCart,
400
- added: !!filteredItems && !!filteredItems.length,
401
- updated: !!itemsToUpdate && !!itemsToUpdate.length,
402
- hasErrors: hasErrors
403
- };
404
- };
405
- exports.verifyAndReturnToBeAddedCartItems = verifyAndReturnToBeAddedCartItems;
406
- // Get province from province array with english, french or abbreviation
407
- const getCurrentProvince = (provinceToCheck) => {
408
- let formattedProvince = (0, string_1.stripAccents)(provinceToCheck.toLowerCase());
409
- return (0, find_1.default)(data_1.provinces, (province) => (0, string_1.stripAccents)(province.value.toLowerCase()) === formattedProvince ||
410
- (0, string_1.stripAccents)(province.label.toLowerCase()) === formattedProvince ||
411
- (0, string_1.stripAccents)(province.label_en.toLowerCase()) === formattedProvince);
412
- };
413
- exports.getCurrentProvince = getCurrentProvince;
414
- const getTaxProvinceFromShippingAddress = (address) => {
415
- let taxProvince;
416
- const shippingState = address.state.toLowerCase();
417
- const shortCartShippingState = data_1.provinces.find((p) => p.value.toLowerCase() == shippingState ||
418
- p.label.toLocaleLowerCase() == shippingState ||
419
- p.label_en.toLowerCase() == shippingState);
420
- if (!!shortCartShippingState)
421
- taxProvince = shortCartShippingState.value;
422
- return taxProvince;
423
- };
424
- exports.getTaxProvinceFromShippingAddress = getTaxProvinceFromShippingAddress;
425
- /**
426
- * Constructs and returns data for indexed cart (algolia or addio)
427
- * @param cartData - Current cart data
428
- * @param space - Space object
429
- * @param options.setPaidAtIfUndefined - Optionnal - If true, will set paid_at with current date
430
- * @param options.customer - Optionnal - If defined, adds info based on customer to indexedCart
431
- * @param option.createdAt - Optionnal - If defined, added to indexedCart, else null value added
432
- * @param option.updatedAt - Optionnal - If defined, added to indexedCart, else null value added
433
- * @param associatedTransfers - Optionnal, used to pass transfers and statuses to indexed cart. Will only be added if cart's has_transfers prop is true
434
- * @returns <IIndexedCart>
435
- */
436
- const getIndexedCartData = (cartData, space, options = {}) => {
437
- var _a, _b, _c, _d, _e;
438
- const getPaidAt = () => {
439
- let paidAt;
440
- try {
441
- paidAt =
442
- !!cartData && !!cartData.paid_at
443
- ? (0, data_1.formatDate)(cartData.paid_at)
444
- : !!options.setPaidAtIfUndefined
445
- ? (0, moment_1.default)().toDate()
446
- : null;
447
- }
448
- catch (error) {
449
- paidAt = cartData.paid_at || null;
450
- }
451
- return { paid_at: !!paidAt ? (0, moment_1.default)(paidAt).unix() : null };
452
- };
453
- const itemDict = {};
454
- for (let item of cartData.items) {
455
- itemDict[item.sku] = Object.assign(Object.assign({ qty: item.qte, refunded_qty: (_a = item.refunded_qty) !== null && _a !== void 0 ? _a : 0, refunded: (_b = item.refunded) !== null && _b !== void 0 ? _b : false }, (typeof item.qte_reserved != 'undefined' ? { reserved_qty: item.qte_reserved } : {})), (typeof item.qte_bypass_inventory_check != 'undefined'
456
- ? { bypass_inventory_check_qty: item.qte_bypass_inventory_check }
457
- : {}));
458
- }
459
- const cartPromos = (0, discount_1.getCartPromo)(cartData);
460
- // If the cart has a promo applied with a promo code, or a discount on a product added via the POS, save info to index
461
- let hasPromos = !!cartPromos && !!cartPromos.length;
462
- let hasCustomDiscount = !!cartData.items.some((i) => !!(0, object_1.recursiveCheckObject)(i, 'promo_price.authorization.note') ||
463
- !!(0, object_1.recursiveCheckObject)(i, 'discount_price.authorization.note'));
464
- const indexedCartData = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ objectID: cartData.id, cart_type: cartData.cart_type, status: cartData.status, ref: cartData.ref || '', invoice_ref: (_c = cartData.invoice_ref) !== null && _c !== void 0 ? _c : null, created_at: !!options.createdAt ? (0, moment_1.default)(options.createdAt).unix() : null, updated_at: !!options.updatedAt
465
- ? (0, moment_1.default)(options.updatedAt).unix()
466
- : !!cartData.paid_at
467
- ? getPaidAt().paid_at
468
- : (0, moment_1.default)().unix(), processed_at: !!cartData.processed_by && !!cartData.processed_by.date
469
- ? (0, moment_1.default)((0, data_1.formatDate)(cartData.processed_by.date)).unix()
470
- : null }, (typeof cartData.to_be_verified_by_clerk !== 'undefined'
471
- ? { to_be_verified_by_clerk: cartData.to_be_verified_by_clerk }
472
- : {})), { on_hold: cartData.on_hold, is_on_hold: !!cartData.on_hold,
473
- // --------------------------------
474
- // #region PROMOS
475
- cart_promos_applied: cartPromos !== null && cartPromos !== void 0 ? cartPromos : null, has_promos: !!hasPromos ? hasPromos : null, has_custom_discount: !!hasCustomDiscount ? hasCustomDiscount : null,
476
- // #endregion
477
- // --------------------------------
478
- // #region ITEMS AND SPECIFIC TYPES
479
- items: itemDict, is_booking: !!cartData.is_booking, is_promise_to_purchase: !!cartData.promise_to_purchase,
480
- // #endregion
481
- // --------------------------------
482
- // #region TRANSFERS
483
- has_transfers: !!cartData.has_transfers && !!options.associatedTransfers ? options.associatedTransfers : undefined }), getPaidAt()), (0, exports.getPaidByForIndexedCart)(cartData)), { subtotal: cartData.subtotal, total: cartData.total,
484
- // #endregions
485
- // --------------------------------
486
- // #region EXPEDITION
487
- is_pickup: !!cartData.is_pickup, out_of_zone: !!cartData.shipping_payload && !!cartData.shipping_payload.isOutOfArea, billing_phone: cartData.billing_address ? cartData.billing_address.expedition_recipient_phone : null, shipping_phone: cartData.shipping_address ? cartData.shipping_address.expedition_recipient_phone : null,
488
- // #endregion
489
- // --------------------------------
490
- // #region CUSTOMER
491
- customer_id: !!cartData.customer_id ? cartData.customer_id : null, customer_name: cartData.billing_address ? cartData.billing_address.expedition_recipient_name : null, customer_email: cartData.customer_info && cartData.customer_info.customer_default_email
492
- ? cartData.customer_info.customer_default_email
493
- : cartData.user_email
494
- ? cartData.user_email
495
- : null, customer_company_name: !!(0, object_1.recursiveCheckObject)(cartData, 'customer_info.company_name')
496
- ? (0, object_1.recursiveCheckObject)(cartData, 'customer_info.company_name')
497
- : !!options.customer && !!(0, object_1.recursiveCheckObject)(options.customer, 'company_info.invoice_info.legal_name')
498
- ? (0, object_1.recursiveCheckObject)(options.customer, 'company_info.invoice_info.legal_name')
499
- : null, is_detail_customer: !!!cartData.customer_info || !!!cartData.customer_info.pro_title || !!!cartData.customer_info.pro_proof_doc, customer_type: !!(0, object_1.recursiveCheckObject)(cartData, 'customer_info.pro_title')
500
- ? Cart_1.CartCustomerEnum.PRO
501
- : !!cartData.customer_id
502
- ? Cart_1.CartCustomerEnum.CONNECTED
503
- : Cart_1.CartCustomerEnum.GUEST, customer_rep: !!options.customer ? options.customer.represented_by : null, customer_external_class: (0, object_1.recursiveCheckObject)(cartData, 'customer_info.customer_external_class') ||
504
- (0, object_1.recursiveCheckObject)(options.customer, 'basic_info.customer_professionnal_info.external_customer_class') ||
505
- null,
506
- // #endregion
507
- // --------------------------------
508
- // #region SEO / MARKETING
509
- keywords: (0, uniq_1.default)((0, flatten_1.default)(cartData.items.map((item) => {
510
- // Now adds parent_name to keywords if found in cart_item
511
- return [...(item.parent_name || []).map((n) => n.value), ...(item.name || []).map((n) => n.value), item.sku];
512
- }))), cart_slug_list: (0, uniq_1.default)(cartData.items.map((item) => {
513
- return item.parent_slug || '';
514
- })), from_marketplace: (_d = cartData.from_marketplace) !== null && _d !== void 0 ? _d : null }), (!!space.data().id && [services_1.SpaceIdEnum.GR, services_1.SpaceIdEnum.CMV].includes(space.data().id)
515
- ? Object.assign(Object.assign({}, (0, exports.getShippingStoreInfo)(cartData, space)), (services_1.SpaceIdEnum.GR === space.data().id
516
- ? Object.assign(Object.assign({ order_type: (0, invoices_1.getOrderTypeString)(cartData, {
517
- frOnly: true,
518
- slugSafe: (0, cart_1.checkIfCartContainsType)(cart_2.CartGeneralTypeEnum.BOOKING_BETON, cartData),
519
- installAsType: true
520
- }) }, (0, exports.getAssignedToInfo)(cartData)), { project_number: (_e = (0, object_1.recursiveCheckObject)(cartData, 'shipping_payload.orderOrProjectNumber')) !== null && _e !== void 0 ? _e : null }) : {})) : {})
521
- // #endregion
522
- );
523
- return indexedCartData;
524
- };
525
- exports.getIndexedCartData = getIndexedCartData;
526
- const getPaidByForIndexedCart = (order) => {
527
- if (!!!order.paid_by && !!!order.custom_payment_type)
528
- return { paid_by: null, multiple_payments: null };
529
- const currentPaidBy = !!order.custom_payment_type && !!order.custom_payment_type.method
530
- ? order.custom_payment_type.method
531
- : order.paid_by;
532
- // If order has multiple payment types...
533
- if (currentPaidBy === Cart_1.PaymentTypeEnum.MULTIPLE && !!order.payment_details && !!order.payment_details.length) {
534
- const firstPayment = order.payment_details.length === 1 || order.payment_details[0].method !== Cart_1.PaymentTypeEnum.TOBERECEIVED
535
- ? order.payment_details[0]
536
- : order.payment_details[1];
537
- return {
538
- paid_by: firstPayment.method,
539
- multiple_payments: order.payment_details.length > 1
540
- };
541
- }
542
- else {
543
- return {
544
- paid_by: currentPaidBy !== null && currentPaidBy !== void 0 ? currentPaidBy : null,
545
- multiple_payments: null
546
- };
547
- }
548
- };
549
- exports.getPaidByForIndexedCart = getPaidByForIndexedCart;
550
- const getAssignedToInfo = (order) => {
551
- if (!!!order.assigned_to || !!!order.assigned_to.length)
552
- return { assigned_to: null };
553
- const mostRecentAssignedTo = (0, orderBy_1.default)(order.assigned_to, (assigned) => (0, moment_1.default)((0, data_1.formatDate)(assigned.date)).unix(), 'desc')[0];
554
- if (!!!mostRecentAssignedTo || !!!mostRecentAssignedTo.is_active)
555
- return { assigned_to: null };
556
- return {
557
- assigned_to: mostRecentAssignedTo.user_name
558
- };
559
- };
560
- exports.getAssignedToInfo = getAssignedToInfo;
561
- const getShippingStoreInfo = (order, space) => {
562
- if (!!order.is_pickup) {
563
- if (!!order.shipping_payload && !!order.shipping_payload.pickup_store && !!order.shipping_payload.pickup_store.id)
564
- return {
565
- store: {
566
- id: order.shipping_payload.pickup_store.id,
567
- name: order.shipping_payload.pickup_store.name
568
- }
569
- };
570
- if (!!order.shipping_address)
571
- return {
572
- store: (0, exports.getOrderStoreInfo)(space.data(), order.shipping_address.address)
573
- };
574
- }
575
- return { store: { id: 'Livraison', name: 'Livraison' } };
576
- };
577
- exports.getShippingStoreInfo = getShippingStoreInfo;
578
- const checkIfShippingSameAsBilling = (cart) => {
579
- return (!!cart.shipping_address &&
580
- !!cart.billing_address &&
581
- (0, isEqual_1.default)(cart.shipping_address.address, cart.billing_address.address));
582
- };
583
- exports.checkIfShippingSameAsBilling = checkIfShippingSameAsBilling;
584
- const getOrderStoreInfo = (spaceData, storeAddress) => {
585
- // Pour algo, si informations du store correspondant non-trouvés, renvoit un 'all' pour qu'il affiche tout le temps
586
- const defaultStoreInfo = {
587
- id: 'all',
588
- name: 'all'
589
- };
590
- try {
591
- if (!!!storeAddress || !!!spaceData)
592
- return defaultStoreInfo;
593
- const allStores = spaceData.stores_warehouses;
594
- const sameStore = allStores.find((store) => store.address.postal_code === storeAddress.postal_code);
595
- if (!!!sameStore)
596
- return defaultStoreInfo;
597
- return {
598
- id: sameStore.id,
599
- name: sameStore.name
600
- };
601
- }
602
- catch (e) {
603
- console.log('error on fetching store info for algo order: ', e);
604
- return defaultStoreInfo;
605
- }
606
- };
607
- exports.getOrderStoreInfo = getOrderStoreInfo;
608
- const getModifiedItems = (newItems, oldItems) => {
609
- let itemsForInventory = [];
610
- for (const i of newItems) {
611
- const itemInOldArray = oldItems.find((o) => o.sku === i.sku);
612
- // If the item was not in the old cart, keep all its info
613
- if (!!!itemInOldArray) {
614
- itemsForInventory = [...itemsForInventory, i];
615
- continue;
616
- }
617
- // If the item is the same in the old cart and in the new one, do nothing
618
- if (i.qte === itemInOldArray.qte)
619
- continue;
620
- // If we are here, it means the item is still in the cart, but it's quantities changed. If the new qte is smaller, the new qte will be negative to add items back to inventory
621
- const newQte = i.qte - itemInOldArray.qte;
622
- itemsForInventory = [
623
- ...itemsForInventory,
624
- Object.assign(Object.assign({}, i), { qte: newQte })
625
- ];
626
- }
627
- for (const i of oldItems) {
628
- const itemInNewArray = newItems.find((o) => o.sku === i.sku);
629
- // If the item used to be in the cart, but is no longer there, save all it's quantity as negative to put it back in the inventory
630
- if (!!!itemInNewArray) {
631
- itemsForInventory = [
632
- ...itemsForInventory,
633
- Object.assign(Object.assign({}, i), { qte: i.qte == 0 ? 0 : i.qte * -1 })
634
- ];
635
- }
636
- }
637
- return itemsForInventory;
638
- };
639
- exports.getModifiedItems = getModifiedItems;
640
- /**
641
- * Get all active transfers for a cart where given items are found
642
- * @param allTransfersForCart All transfers associated to a given cart
643
- * @param cartItems All cart items for whitch to check transfers if found
644
- */
645
- const getActiveTransfersByItemInCart = (allTransfersForCart, cartItems) => {
646
- if (!!!allTransfersForCart || !!!allTransfersForCart.length)
647
- return [];
648
- const allActive = allTransfersForCart.filter((t) => !!!t.data().completed);
649
- if (!!!allActive.length)
650
- return [];
651
- let foundInTransfer = [];
652
- for (let item of cartItems) {
653
- const sameInTransfers = allActive.filter((t) => t.data().products.some((p) => p.sku == item.sku));
654
- if (!!sameInTransfers)
655
- foundInTransfer.push({
656
- sku: item.sku,
657
- transfers: sameInTransfers,
658
- hasUpdatableTransfer: sameInTransfers.some((t) => t.transferAllowsIndependantProductUpdate()),
659
- hasNonUpdatableTransfer: sameInTransfers.some((t) => !t.transferAllowsIndependantProductUpdate())
660
- });
661
- }
662
- return foundInTransfer;
663
- };
664
- exports.getActiveTransfersByItemInCart = getActiveTransfersByItemInCart;
665
- /**
666
- * Get the sale unit slug for a cart item
667
- *
668
- * @param item the cart item
669
- * @returns unit slug or empty if not found
670
- */
671
- const getItemSaleUnitSlug = (item) => {
672
- const unit = (item.other_units || []).find((x) => x.is_sale_unit);
673
- return unit ? unit.unit_slug : '';
674
- };
675
- exports.getItemSaleUnitSlug = getItemSaleUnitSlug;
676
- /**
677
- * Constructs an object for each transfer, with corresponding products to update and by which quantity
678
- * @param allCartTransfers All transfer objects associated to a given cart
679
- * @param updatedItems Array of pertinent data per item updated to determine which transfers to update quantities for
680
- * @returns {TransfersWithItemsToUpdate | undefined}
681
- */
682
- const getItemsToUpdateByTransfer = (allCartTransfers, updatedItems) => {
683
- if (!!!allCartTransfers.length || !!!updatedItems.length)
684
- return;
685
- const skusFoundInTransfers = (0, exports.getActiveTransfersByItemInCart)(allCartTransfers, updatedItems.map((upItem) => upItem.item));
686
- if (!!!skusFoundInTransfers.length)
687
- return;
688
- let transfersToUpdate = {};
689
- for (let upItem of updatedItems) {
690
- const sku = upItem.item.sku;
691
- const qteToUpdate = upItem.qteToUpdate;
692
- let sameItemData = skusFoundInTransfers.find((s) => s.sku == sku);
693
- if (!!!sameItemData || !!!sameItemData.transfers.length)
694
- continue;
695
- const transfersWithSameItem = sameItemData.transfers;
696
- const filteredInventoriesByTransferStores = !!upItem.inventoryItem
697
- ? upItem.inventoryItem.inventories.filter((i) => transfersWithSameItem.some((t) => !!t.data().from && t.data().from == i.store_id))
698
- : undefined;
699
- // A. If quantities are to be added...
700
- if (qteToUpdate > 0) {
701
- const inventoryUnitQteToUpdate = (0, inventories_1.getConvertedUnitQuantity)(upItem.item.other_units, qteToUpdate, 'inventory_unit', true);
702
- // A1. ... If some transfers are currently at status INITIALIZED (with no "from" store set), add to first initialized found (since quantities can be redistributed by store when opening transfer)
703
- const initializedStatusTransfers = transfersWithSameItem.filter((t) => t.data().status == TransferRequest_1.TransferRequestStatusEnum.INITIATED);
704
- if (!!initializedStatusTransfers.length) {
705
- const firstTransfer = initializedStatusTransfers[0];
706
- const transferID = firstTransfer.data().id;
707
- if (!!!transferID)
708
- continue;
709
- const dataForTransfer = transfersToUpdate[transferID] || [];
710
- dataForTransfer.push({
711
- sku,
712
- ajustmentQte: inventoryUnitQteToUpdate
713
- });
714
- transfersToUpdate[transferID] = dataForTransfer;
715
- continue;
716
- }
717
- // A2. ... Else, add to transfer where store has most quantities
718
- // TODO - Should we check if quantities are available in store before adding to transfer ?
719
- // TODO - Maybe based on if property space.options.transfer_requests.dont_limit_qty ?
720
- const storeWithMostQuantities = !!filteredInventoriesByTransferStores
721
- ? filteredInventoriesByTransferStores.reduce((storeA, storeB) => (0, toNumber_1.default)(storeA.qty.available) > (0, toNumber_1.default)(storeB.qty.available) ? storeA : storeB)
722
- : undefined;
723
- const transferToUse = !!storeWithMostQuantities
724
- ? transfersWithSameItem.find((t) => t.data().from == storeWithMostQuantities.store_id)
725
- : transfersWithSameItem[0];
726
- if (!!!transferToUse || !!!transferToUse.data().id)
727
- continue;
728
- const dataForTransfer = transfersToUpdate[transferToUse.data().id] || [];
729
- dataForTransfer.push({ sku, ajustmentQte: inventoryUnitQteToUpdate });
730
- transfersToUpdate[transferToUse.data().id] = dataForTransfer;
731
- continue;
732
- }
733
- // B. If quantities are to be removed...
734
- if (qteToUpdate < 0) {
735
- // ... remove from all transfers until done, starting with transfers at status INITIALIZED, then by the store with the least quantities currently available
736
- let qteToRemove = qteToUpdate * -1; // change to positive value to facilitate checks later. Will be changed to negative when saved in qteToUpdate props for each transfer
737
- let inventoryUnitQteToRemove = (0, inventories_1.getConvertedUnitQuantity)(upItem.item.other_units, qteToRemove, 'inventory_unit', true);
738
- const inventoriesByAvailabilityAsc = (0, orderBy_1.default)(filteredInventoriesByTransferStores, (i) => (0, toNumber_1.default)(i.qty.available));
739
- const transfersByInventory = (0, orderBy_1.default)(transfersWithSameItem, (t) => [
740
- t.data().status == TransferRequest_1.TransferRequestStatusEnum.INITIATED ? 0 : 1,
741
- inventoriesByAvailabilityAsc.findIndex((i) => i.store_id == t.data().from)
742
- ]);
743
- for (let transfer of transfersByInventory) {
744
- if (!!!transfer.data().id)
745
- continue;
746
- const sameProd = transfer.data().products.find((p) => p.sku == sku);
747
- if (!!!sameProd)
748
- continue;
749
- const currentQte = sameProd.qte;
750
- const qteToBeUpdated = currentQte < inventoryUnitQteToRemove ? currentQte : inventoryUnitQteToRemove;
751
- const dataForTransfer = transfersToUpdate[transfer.data().id] || [];
752
- dataForTransfer.push({ sku, ajustmentQte: qteToBeUpdated == 0 ? qteToBeUpdated : qteToBeUpdated * -1 }); // value changed back to a negative here
753
- transfersToUpdate[transfer.data().id] = dataForTransfer;
754
- inventoryUnitQteToRemove -= qteToBeUpdated;
755
- if (qteToRemove <= 0)
756
- break;
757
- }
758
- }
759
- }
760
- return transfersToUpdate;
761
- };
762
- exports.getItemsToUpdateByTransfer = getItemsToUpdateByTransfer;
763
- const getILangForUpdateType = (updateType) => {
764
- const dict = {
765
- [`${Cart_1.UpdateTypeEnum.CART_CONTENT}`]: { fr: 'Ajustement de la commande', en: 'Updated cart content' },
766
- [`${Cart_1.UpdateTypeEnum.PROCESSING_STORE}`]: {
767
- fr: 'Changement succ. de traitement',
768
- en: 'Updated processing store'
769
- }
770
- };
771
- return dict[updateType || Cart_1.UpdateTypeEnum.CART_CONTENT];
772
- };
773
- exports.getILangForUpdateType = getILangForUpdateType;
774
- const getSubtotalToCheckForPromo = (allCartItems, currentCartSubtotal, space, feePromosTotalRemoved, removeServiceFees) => {
775
- // ** NEW - Now excludes escompte supp. products from services when checking subtotal for promotions
776
- const serviceFeeProducts = !!!removeServiceFees
777
- ? []
778
- : allCartItems.filter((i) => !!i.is_service && !(0, g2_1.isEscompteSuppItem)(i.sku));
779
- const serviceFeeSubtotal = !!!serviceFeeProducts.length
780
- ? 0
781
- : (0, sumBy_1.default)(serviceFeeProducts, (i) => {
782
- const itemPrice = (0, products_1.getLowestPrice)(i).price.amount;
783
- return (0, round_1.default)(((0, isNumber_1.default)(itemPrice) ? Number(itemPrice) : 0) * i.qte, space.data().product_preferences.decimals || 2);
784
- });
785
- let totalRemoved = serviceFeeSubtotal;
786
- // If there is a service and fees total, calculates the service and fees total after taking into account their promos
787
- if (!!totalRemoved) {
788
- totalRemoved -= feePromosTotalRemoved;
789
- }
790
- // Removes that calculated total from the current subtotal to get the subtotal without services and fees, in order to calculate the right promo amount
791
- return currentCartSubtotal - totalRemoved;
792
- };
793
- exports.getSubtotalToCheckForPromo = getSubtotalToCheckForPromo;
794
- const getAllPromoAppliedPrices = (allPromos, subtotalToUse, items, space, isRefund) => {
795
- var _a;
796
- let promoAmounts = [];
797
- let updatedSubtotal = subtotalToUse;
798
- // REMOVE PAYMENT INCENTIVE PROMOS FROM ARRAY
799
- // Since this type of promos ('total_after_taxes') must be calculated and
800
- // removed from total amount AFTER shipping and taxes are calculated,
801
- // they will be dealt with later in process and must not count in "subtotalWithoutPromotions" prop
802
- let cartPromos = allPromos.filter((c) => c.applies_to != Cart_1.CartPromoAppliesToEnum.TOTAL_AFTER_TAXES);
803
- // REORDER PROMOS
804
- // a. if promos apply to products, bring to front of array
805
- // b. if promos contain a promo_code that applies to subtotal,
806
- // push it to the end of the array to check that one last
807
- cartPromos = (0, orderBy_1.default)(cartPromos, (p) => {
808
- if ([Cart_1.CartPromoAppliesToEnum.PRODUCT, Cart_1.CartPromoAppliesToEnum.ITEMS].includes(p.applies_to))
809
- return 1;
810
- if (p.promo_code && p.applies_to === Cart_1.CartPromoAppliesToEnum.SUBTOTAL) {
811
- return 3;
812
- }
813
- return 2;
814
- });
815
- let feePromosTotal = 0;
816
- for (let aPromo of cartPromos) {
817
- let productTotalAmount = 0;
818
- if ((isRefund || updatedSubtotal > 0) &&
819
- !!aPromo &&
820
- (aPromo.applies_to === Cart_1.CartPromoAppliesToEnum.SUBTOTAL || aPromo.applies_to === Cart_1.CartPromoAppliesToEnum.PRODUCT)) {
821
- let amountToRemove = 0;
822
- const amountUnit = aPromo.amount_unit || IDiscountRule_1.ResultActionEnum.PERCENT;
823
- const appliesToProduct = aPromo.applies_to === Cart_1.CartPromoAppliesToEnum.PRODUCT;
824
- const subtotalToCheck = !!aPromo.exclude_services_and_fees &&
825
- !![IDiscountRule_1.ResultActionEnum.PERCENT, IDiscountRule_1.ResultActionEnum.PERCENT_SKU, IDiscountRule_1.ResultActionEnum.PERCENT_CATEGORY].includes(amountUnit) &&
826
- !!!appliesToProduct
827
- ? (0, exports.getSubtotalToCheckForPromo)(items, updatedSubtotal, space, feePromosTotal, true)
828
- : updatedSubtotal;
829
- if (appliesToProduct) {
830
- let skuArray = [];
831
- if (!!aPromo.item_given) {
832
- skuArray = (0, discount_1.getSkuArrayForPromo)(aPromo.item_given);
833
- }
834
- const itemToCheck = items.filter((item) => !!aPromo && !!skuArray.includes(item.sku));
835
- for (const anItem of itemToCheck) {
836
- productTotalAmount += amountUnit.includes('amount')
837
- ? anItem.qte
838
- : (0, products_1.getLowestPrice)(anItem).price.amount * anItem.qte;
839
- const newAmountToRemove = (0, data_1.getPromoTotalAmount)(items, aPromo, 'number', anItem.sku);
840
- if (typeof newAmountToRemove !== 'number')
841
- continue;
842
- if (!!anItem && !!anItem.is_service)
843
- feePromosTotal += newAmountToRemove;
844
- amountToRemove += newAmountToRemove;
845
- }
846
- }
847
- else {
848
- amountToRemove = (_a = aPromo.amount_removed) !== null && _a !== void 0 ? _a : 0;
849
- }
850
- // round amountToRemove before removing from subtotal
851
- amountToRemove = (0, round_1.default)(amountToRemove, 2);
852
- const newSubtotal = amountUnit === IDiscountRule_1.ResultActionEnum.AMOUNT || aPromo.applies_to === Cart_1.CartPromoAppliesToEnum.PRODUCT
853
- ? updatedSubtotal - amountToRemove
854
- : updatedSubtotal - subtotalToCheck * (amountToRemove / 100);
855
- if (!!aPromo.discount_id) {
856
- promoAmounts.push({
857
- id: aPromo.discount_id,
858
- subtotalBefore: updatedSubtotal,
859
- subtotalAfter: (0, round_1.default)(newSubtotal, 2),
860
- amountRemoved: amountToRemove,
861
- productTotalAmount: productTotalAmount,
862
- appliesTo: aPromo.applies_to
863
- });
864
- }
865
- updatedSubtotal = (0, round_1.default)(newSubtotal, 2);
866
- }
867
- }
868
- return promoAmounts;
869
- };
870
- exports.getAllPromoAppliedPrices = getAllPromoAppliedPrices;
871
- /**
872
- Retrieves the original discount price of an item.
873
- @param {ICartItem} item - The cart item object.
874
- @param {'%' | '$'} output - The desired output format: percentage ('%') or currency ('$').
875
- @returns - The original discount price.
876
- */
877
- const getOriginalPromoPriceForItem = (item, output) => {
878
- const orgPrice = (0, exports.getOriginalDiscountPriceForItem)(item, products_1.unitTypeEnum.AMOUNT);
879
- let price = orgPrice; // default value
880
- const customItem = item.promo_price;
881
- if (!!customItem) {
882
- if (typeof customItem.original_amount !== 'undefined')
883
- // previous real promo
884
- price = customItem.original_amount;
885
- else
886
- price = !!customItem.overridden ? orgPrice : customItem.amount; // this is the first promo
887
- }
888
- if (output === products_1.unitTypeEnum.AMOUNT && price === 0 && orgPrice === 0)
889
- return 0;
890
- if (output === products_1.unitTypeEnum.PERCENT)
891
- return (1 - price / orgPrice) * 100;
892
- return price;
893
- };
894
- exports.getOriginalPromoPriceForItem = getOriginalPromoPriceForItem;
895
- /**
896
- Retrieves the original promo price of an item.
897
- @param {ICartItem} item - The cart item object.
898
- @param {unitTypeEnum} output - The desired output format: PERCENT ('%') or AMOUNT ('$').
899
- @returns - The original promo price.
900
- */
901
- const getOriginalDiscountPriceForItem = (item, output) => {
902
- let price = item.regular_price.amount; // default value
903
- const customItem = item.discount_price;
904
- if (!!customItem) {
905
- if (typeof customItem.original_amount !== 'undefined' &&
906
- (customItem.price_type !== products_1.priceTypeEnum.TIER_PRICING || !!customItem.overridden))
907
- // previous real promo
908
- price = customItem.original_amount;
909
- else if (!!!customItem.overridden)
910
- price = customItem.amount; // this is the first promo
911
- }
912
- if (output === products_1.unitTypeEnum.PERCENT)
913
- return (1 - price / item.regular_price.amount) * 100;
914
- return price;
915
- };
916
- exports.getOriginalDiscountPriceForItem = getOriginalDiscountPriceForItem;
917
- /**
918
- * Reajusts promo price with a provided "original" regular price amount
919
- * @param item
920
- * @param original
921
- * @returns the cart item with updated promo price
922
- */
923
- const adjustPromoPrice = (item, original) => {
924
- // get % of the promo
925
- if (!!!item.promo_price)
926
- return item; // no promo price
927
- const promo = (0, exports.getOriginalPromoPriceForItem)(item, products_1.unitTypeEnum.AMOUNT);
928
- const rate = promo / original;
929
- if (rate == 1)
930
- return item; // no change needed
931
- return Object.assign(Object.assign({}, item), { promo_price: Object.assign(Object.assign({}, item.promo_price), { original_amount: !!item.promo_price.original_amount
932
- ? item.promo_price.original_amount
933
- : item.promo_price.amount, amount: (0, exports.getActualDiscountPrice)(item, products_1.unitTypeEnum.AMOUNT) * rate }) });
934
- };
935
- exports.adjustPromoPrice = adjustPromoPrice;
936
- const getAddressStrArray = (address) => {
937
- return [
938
- `${!!address.app ? address.app + ' - ' : ''}${address.line1 || ''}`,
939
- `${!!address.city ? address.city + ', ' : ''}${address.state || ''} ${address.postal_code || ''}`
940
- ].filter((addr) => !!addr.trim());
941
- };
942
- exports.getAddressStrArray = getAddressStrArray;
943
- /**
944
- * Returns all payement methods for a given cart
945
- * @param cartData
946
- */
947
- const getCartPaymentMethods = (cartData) => {
948
- return !!cartData.payment_details
949
- ? (cartData.payment_details || []).map((p) => p.method)
950
- : !!cartData.paid_by
951
- ? [cartData.paid_by]
952
- : [];
953
- };
954
- exports.getCartPaymentMethods = getCartPaymentMethods;
955
- /**
956
- * Return last user to take payment for cart. Checks in order : 'completed_by' -> 'updated_by' -> 'processed_by' -> 'created_by'
957
- * @param cartData The cart to check
958
- * @param startCheckAt The step to start check at. Defaults to 'processed_by'
959
- */
960
- const getLastUserWhoTookPayment = (cartData, startCheckAt = 'processed_by') => {
961
- let foundUser = undefined;
962
- let allSteps = ['completed_by', 'updated_by', 'processed_by', 'created_by'];
963
- // Splice original array to only keep entries from specified startCheckAt property
964
- allSteps.splice(allSteps.indexOf(startCheckAt));
965
- const checkCartProp = (property) => {
966
- const foundData = cartData[property];
967
- if (!!!foundData)
968
- return;
969
- if (Array.isArray(foundData)) {
970
- return foundData.find((d) => d.took_payment);
971
- }
972
- return foundData;
973
- };
974
- for (const stepToCheck of allSteps) {
975
- foundUser = checkCartProp(stepToCheck);
976
- if (foundUser)
977
- break;
978
- }
979
- return foundUser;
980
- };
981
- exports.getLastUserWhoTookPayment = getLastUserWhoTookPayment;
982
- /**
983
- * Constructs and returns an IPayment object for store credit
984
- * @param storeCreditSlug The associated store credit's slug
985
- * @param amount The amount of credits used as payment
986
- * @returns {IPayment}
987
- */
988
- const constructStoreCreditPaymentEntry = (storeCreditSlug, amount) => {
989
- return {
990
- amount,
991
- method: Cart_1.PaymentTypeEnum.STORE_CREDITS,
992
- paid_at: new Date(),
993
- ref: storeCreditSlug
994
- };
995
- };
996
- exports.constructStoreCreditPaymentEntry = constructStoreCreditPaymentEntry;
997
- // #region CUSTOM PRICES AND ESCOMPTES (added by POS)
998
- /**
999
- * Calculates applied amout for a custom added promo.
1000
- * @param item Cart item on which custom promo was applied
1001
- * @param type The custom promo type (unit price of added escompte)
1002
- * @param amount The fixed amount or percentage of custom price allocated
1003
- * @param substractAmountIfUnitPrice Optionnal. If true, amount received is removed from initialPrice. Else, amount is returned as is.
1004
- * @returns {number}
1005
- */
1006
- const calculateAmountForCustomPromo = (item, type, amount, substractAmountIfUnitPrice) => {
1007
- const initialPrice = !!item.discount_price ? item.discount_price.amount : item.regular_price.amount;
1008
- if (type === Cart_1.CustomPromoType.UNIT_PRICE) {
1009
- if (!substractAmountIfUnitPrice)
1010
- return amount;
1011
- return initialPrice - amount;
1012
- }
1013
- const promoAmount = (initialPrice * amount) / 100;
1014
- return initialPrice - promoAmount;
1015
- };
1016
- exports.calculateAmountForCustomPromo = calculateAmountForCustomPromo;
1017
- // #endregion
1018
- // #region STORE CREDIT MANAGEMENT
1019
- /**
1020
- * Check if credit quantity for cart is valid and available.
1021
- * @param creditToBeUsedInCart Amount to be used in credits.
1022
- * @param customerID The customer's ID to check for available store credits.
1023
- * @param space The current space obj
1024
- * @param creditSlug La référence au type de store credit à vérifier
1025
- */
1026
- const validateStoreCreditUsage = async (creditToBeUsedInCart, customerID, space, creditSlug) => {
1027
- const hasStoreCreditsSet = space.options.checkIfOptionIsSet('payment.space_has_store_credits');
1028
- if (!hasStoreCreditsSet) {
1029
- return {
1030
- valid: false,
1031
- error: {
1032
- en: 'This retailer does not support store credits.',
1033
- fr: "Ce commerçant n'offre pas de crédits en magasin."
1034
- }
1035
- };
1036
- }
1037
- if (!customerID) {
1038
- return {
1039
- valid: false,
1040
- error: {
1041
- en: 'Only logged-in users can use the credits.',
1042
- fr: 'Seuls les utilisateur connectés peuvent utiliser les crédits.'
1043
- }
1044
- };
1045
- }
1046
- const creditAmount = creditToBeUsedInCart !== null && creditToBeUsedInCart !== void 0 ? creditToBeUsedInCart : 0;
1047
- // VALIDATIONS
1048
- // a. Valide que le crédit demandé est positif
1049
- let valid = creditAmount >= 0;
1050
- // b. Valide que le client a le reste nécessaire pour utiliser ses crédits comme mode de paiement
1051
- if (valid) {
1052
- let clientCheck = await space.customers.credits.validate(customerID, creditSlug, creditAmount);
1053
- valid = !clientCheck;
1054
- }
1055
- return Object.assign({ valid }, (!valid
1056
- ? {
1057
- error: {
1058
- en: 'Insufficient credits.',
1059
- fr: 'Crédits insufisant.'
1060
- }
1061
- }
1062
- : {}));
1063
- };
1064
- exports.validateStoreCreditUsage = validateStoreCreditUsage;
1065
- // #endregion
1066
- /**
1067
- * Get total quantity of pallets purchased by a customer
1068
- * @param space - Space object
1069
- * @param customerId - Customer ID
1070
- * @returns Total quantity of pallets purchased
1071
- */
1072
- const getPurchasedPalletsQuantityForCustomer = async (space, customerId) => {
1073
- const palletSku = '210000000';
1074
- const completedStatus = Cart_1.CartStatusEnum.COMPLETED;
1075
- try {
1076
- // 1. Get search index info for the space
1077
- const searchInfo = (0, searchIndexes_1.getFetchInfoAlgoliaAddioSearch)(space);
1078
- // 2. Fetch indexed completed orders for this customer that contain the pallet SKU (from 2026-01-01)
1079
- const startDate = (0, moment_1.default)('2026-01-01');
1080
- const endDate = (0, moment_1.default)();
1081
- const filterStr = `customer_id:${customerId} AND status:${completedStatus} AND (created_at:${startDate.unix()} TO ${endDate.unix()}) AND (items.${palletSku}.refunded:false OR items.${palletSku}.refunded:true)`;
1082
- // 3. Fetch all pages and sum pallet quantities
1083
- let totalPallets = 0;
1084
- let currentPage = 0;
1085
- let nbPages = 1;
1086
- while (currentPage < nbPages) {
1087
- const indexedOrders = await Cart_2.default.fetch({
1088
- app: searchInfo.app,
1089
- api: searchInfo.api,
1090
- space,
1091
- filters: '',
1092
- hpp: 1000,
1093
- page: currentPage,
1094
- query: '',
1095
- indice: 'orders',
1096
- f: filterStr,
1097
- useProspr: searchInfo.useProspr
1098
- });
1099
- nbPages = indexedOrders.nbPages;
1100
- if (!!indexedOrders.hits && !!indexedOrders.hits.length) {
1101
- indexedOrders.hits.forEach((indexedOrder) => {
1102
- const palletItem = !!indexedOrder.items ? indexedOrder.items[palletSku] : undefined;
1103
- if (palletItem) {
1104
- totalPallets += (0, toNumber_1.default)(palletItem.qty || 0);
1105
- }
1106
- });
1107
- }
1108
- currentPage++;
1109
- }
1110
- return totalPallets;
1111
- }
1112
- catch (error) {
1113
- console.error('Error fetching purchased pallets:', error);
1114
- throw new Error(`Failed to fetch purchased pallets: ${error}`);
1115
- }
1116
- };
1117
- exports.getPurchasedPalletsQuantityForCustomer = getPurchasedPalletsQuantityForCustomer;
1118
- const shouldIgnoreInventoryForItem = (item) => {
1119
- return !!item.is_service || !!item.is_temp_prod || !!item.is_sample;
1120
- };
1121
- exports.shouldIgnoreInventoryForItem = shouldIgnoreInventoryForItem;
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.shouldIgnoreInventoryForItem = exports.getPurchasedPalletsQuantityForCustomer = exports.validateStoreCreditUsage = exports.calculateAmountForCustomPromo = exports.constructStoreCreditPaymentEntry = exports.getLastUserWhoTookPayment = exports.getCartPaymentMethods = exports.getAddressStrArray = exports.adjustPromoPrice = exports.getOriginalDiscountPriceForItem = exports.getOriginalPromoPriceForItem = exports.getAllPromoAppliedPrices = exports.getSubtotalToCheckForPromo = exports.getILangForUpdateType = exports.getItemsToUpdateByTransfer = exports.getItemSaleUnitSlug = exports.getActiveTransfersByItemInCart = exports.getModifiedItems = exports.getOrderStoreInfo = exports.checkIfShippingSameAsBilling = exports.getShippingStoreInfo = exports.getAssignedToInfo = exports.getPaidByForIndexedCart = exports.getIndexedCartData = exports.getTaxProvinceFromShippingAddress = exports.getCurrentProvince = exports.verifyAndReturnToBeAddedCartItems = exports.addCartItems = exports.generateCartItemForSku = exports.getActualDiscountPrice = exports.getActualPromoPrice = exports.priceWasOverridden = exports.deleteCartItem = exports.verifyAndReturnToBeUpdatedCartItems = exports.updateCartItems = void 0;
7
+ const toNumber_1 = __importDefault(require("lodash/toNumber"));
8
+ const findIndex_1 = __importDefault(require("lodash/findIndex"));
9
+ const remove_1 = __importDefault(require("lodash/remove"));
10
+ const flatten_1 = __importDefault(require("lodash/flatten"));
11
+ const orderBy_1 = __importDefault(require("lodash/orderBy"));
12
+ const uniq_1 = __importDefault(require("lodash/uniq"));
13
+ const moment_1 = __importDefault(require("moment"));
14
+ const isEqual_1 = __importDefault(require("lodash/isEqual"));
15
+ const find_1 = __importDefault(require("lodash/find"));
16
+ const isNumber_1 = __importDefault(require("lodash/isNumber"));
17
+ const round_1 = __importDefault(require("lodash/round"));
18
+ const sumBy_1 = __importDefault(require("lodash/sumBy"));
19
+ const Cart_1 = require("../Interfaces/Cart");
20
+ const string_1 = require("./string");
21
+ const g2_1 = require("../rules/GR/utils/g2");
22
+ const object_1 = require("./object");
23
+ const invoices_1 = require("../rules/GR/utils/invoices");
24
+ const data_1 = require("./data");
25
+ const services_1 = require("./services");
26
+ const discount_1 = require("./discount");
27
+ const IDiscountRule_1 = require("../Interfaces/Rules/IDiscountRule");
28
+ const products_1 = require("./products");
29
+ const TransferRequest_1 = require("../Interfaces/TransferRequest");
30
+ const cart_1 = require("../rules/GR/utils/cart");
31
+ const cart_2 = require("../rules/GR/interfaces/cart");
32
+ const inventories_1 = require("./inventories");
33
+ const searchIndexes_1 = require("./searchIndexes");
34
+ const Cart_2 = __importDefault(require("../lib/Cart"));
35
+ const updateCartItems = async (currentCart, items, fetchInventory, shouldCheckInventory = true, handleInventoryError) => {
36
+ let updatedCart = Object.assign({}, currentCart);
37
+ const itemsToUpdate = Array.isArray(items) ? items : [items];
38
+ const updatedItems = [];
39
+ for (const item of itemsToUpdate) {
40
+ const cartItemIndex = (0, findIndex_1.default)(updatedCart.items, (i) => i.sku === item.sku);
41
+ const cartItem = cartItemIndex !== -1 ? updatedCart.items[cartItemIndex] : undefined;
42
+ if (!!cartItem) {
43
+ if (!!shouldCheckInventory) {
44
+ let inventoryItem = undefined;
45
+ try {
46
+ inventoryItem = !!cartItem && !!cartItem.is_service ? undefined : await fetchInventory(item.sku);
47
+ }
48
+ catch (e) {
49
+ console.log('error on fetching inventoryItem: ', e);
50
+ }
51
+ if (!!inventoryItem) {
52
+ const webStore = inventoryItem.web_inventory;
53
+ // If the item is NOT infinite_stock ans is NOT a service
54
+ if (!!!inventoryItem.is_infinite_stock && !!!cartItem.is_service) {
55
+ // If webstore is not defined or the avaibility = 0
56
+ if (!!!webStore || !!!webStore.available) {
57
+ continue;
58
+ }
59
+ // If the quantity we are setting is more than the available qte of the item
60
+ if (item.qte > webStore.available) {
61
+ if (!!handleInventoryError) {
62
+ await handleInventoryError(true);
63
+ }
64
+ updatedItems.push({
65
+ sku: item.sku,
66
+ updated: false
67
+ });
68
+ continue;
69
+ }
70
+ }
71
+ }
72
+ }
73
+ updatedCart.items[cartItemIndex] = Object.assign(Object.assign({}, cartItem), { qte: item.qte, qte_override: item.qte_override });
74
+ updatedItems.push({ sku: item.sku, updated: true });
75
+ }
76
+ }
77
+ return { updatedCart, updatedItems };
78
+ };
79
+ exports.updateCartItems = updateCartItems;
80
+ /**
81
+ * For now, copy of `updateCartItems` function in most aspects, with slight optim. Meant to replace updateCartItems eventually!
82
+ * Verify a list of items that could be added to a cart. Returns the list of items to update as well as the updated cart data.
83
+ * @param currentCartItems
84
+ * @param items
85
+ * @param fetchInventory
86
+ * @param options.shouldCheckInventory
87
+ * @param options.handleInventoryError
88
+ * @param options.shouldCheckStoreInventory
89
+ * @param options.useReservedInventory if the inventory is reserved on add to cart
90
+ */
91
+ const verifyAndReturnToBeUpdatedCartItems = async (currentCartItems, items, fetchInventory, options = {}) => {
92
+ let updatedCartItems = [...currentCartItems];
93
+ const updatedDetails = [];
94
+ for (const item of items) {
95
+ const cartItemIndex = (0, findIndex_1.default)(updatedCartItems, (i) => i.sku === item.sku);
96
+ const cartItem = cartItemIndex !== -1 ? updatedCartItems[cartItemIndex] : undefined;
97
+ if (!!cartItem) {
98
+ if (!!options.shouldCheckInventory) {
99
+ let inventoryItem = undefined;
100
+ try {
101
+ inventoryItem = !!cartItem && !!cartItem.is_service ? undefined : await fetchInventory(item.sku);
102
+ }
103
+ catch (e) {
104
+ console.log('error on fetching inventoryItem: ', e);
105
+ throw new Error('unable to fetch inventory'); // prevent adding without check
106
+ }
107
+ if (!!inventoryItem) {
108
+ // Check store inventory if specified, or default to web inventory
109
+ let inventoryToCheck;
110
+ if (options.shouldCheckStoreInventory) {
111
+ const sameStoreInventory = inventoryItem.inventories.find((i) => i.store_id == options.shouldCheckStoreInventory);
112
+ if (!!sameStoreInventory) {
113
+ inventoryToCheck = sameStoreInventory.qty.available;
114
+ }
115
+ }
116
+ else {
117
+ inventoryToCheck = (0, object_1.recursiveCheckObject)(inventoryItem, 'web_inventory.available');
118
+ }
119
+ // If no inventory found, continue
120
+ if (typeof inventoryToCheck == 'undefined') {
121
+ updatedDetails.push({
122
+ sku: item.sku,
123
+ updated: false
124
+ });
125
+ continue;
126
+ }
127
+ // If the item is NOT infinite_stock and is NOT a service
128
+ if (!!!inventoryItem.is_infinite_stock && !!!cartItem.is_service) {
129
+ // If the avaibility = 0
130
+ let qtyToTest = item.qte;
131
+ if (!!options.useReservedInventory) {
132
+ // only test for added qty, if it's reduced then test will pass even if no item left
133
+ qtyToTest = item.qte - cartItem.qte;
134
+ }
135
+ // If the quantity we are setting is more than the available qte of the item
136
+ if (qtyToTest > inventoryToCheck) {
137
+ if (!!options.handleInventoryError) {
138
+ await options.handleInventoryError(true);
139
+ }
140
+ updatedDetails.push({
141
+ sku: item.sku,
142
+ updated: false
143
+ });
144
+ continue;
145
+ }
146
+ }
147
+ }
148
+ }
149
+ updatedCartItems[cartItemIndex] = Object.assign(Object.assign({}, cartItem), { qte: item.qte, qte_override: item.qte_override });
150
+ updatedDetails.push({ sku: item.sku, updated: true });
151
+ }
152
+ }
153
+ return { updatedCartItems, updatedDetails };
154
+ };
155
+ exports.verifyAndReturnToBeUpdatedCartItems = verifyAndReturnToBeUpdatedCartItems;
156
+ const deleteCartItem = (currentCart, sku, onlyIfUpsellOf) => {
157
+ const deletedItemsCart = Object.assign({}, currentCart);
158
+ sku.forEach((itm) => (0, remove_1.default)(deletedItemsCart.items, (item) => {
159
+ if (!!item.is_upsell_of_sku && !!onlyIfUpsellOf)
160
+ return item.sku === itm && item.is_upsell_of_sku === onlyIfUpsellOf;
161
+ return item.sku === itm;
162
+ }));
163
+ return deletedItemsCart;
164
+ };
165
+ exports.deleteCartItem = deleteCartItem;
166
+ const priceWasOverridden = (itemToCheck) => {
167
+ return ((!!itemToCheck.promo_price && !!itemToCheck.promo_price.overridden) ||
168
+ (!!itemToCheck.discount_price && !!itemToCheck.discount_price.overridden));
169
+ };
170
+ exports.priceWasOverridden = priceWasOverridden;
171
+ const getActualPromoPrice = (item, output) => {
172
+ const orgPrice = (0, exports.getActualDiscountPrice)(item, products_1.unitTypeEnum.AMOUNT);
173
+ let price = orgPrice; // default value
174
+ if (!!item.promo_price) {
175
+ price = item.promo_price.amount; // this is the first promo
176
+ }
177
+ if (output === products_1.unitTypeEnum.PERCENT)
178
+ return !!!orgPrice ? 0 : (1 - price / orgPrice) * 100;
179
+ return price;
180
+ };
181
+ exports.getActualPromoPrice = getActualPromoPrice;
182
+ const getActualDiscountPrice = (item, output) => {
183
+ let price = item.regular_price.amount; // default value
184
+ if (!!item.discount_price) {
185
+ price = item.discount_price.amount; // this is the first promo
186
+ }
187
+ if (output === products_1.unitTypeEnum.PERCENT)
188
+ return (1 - price / item.regular_price.amount) * 100;
189
+ return price;
190
+ };
191
+ exports.getActualDiscountPrice = getActualDiscountPrice;
192
+ /**
193
+ * Generate a cart item from corresonding indexedProduct
194
+ * @param indexedProduct
195
+ * @param sku
196
+ * @param qte
197
+ */
198
+ const generateCartItemForSku = async (indexedProduct, sku, qte) => {
199
+ try {
200
+ // Isolate decli with corresponding sku
201
+ const sameDecli = indexedProduct.declinations.find((d) => d.sku == sku);
202
+ if (!sameDecli)
203
+ throw new Error('Could not find decli in product!');
204
+ // Construct CartItem from decli and prod values
205
+ let decliImgs = sameDecli.images_path;
206
+ if (!decliImgs || decliImgs.length == 0) {
207
+ const parentImgs = indexedProduct.image_files;
208
+ if (!!parentImgs && parentImgs.length)
209
+ decliImgs = parentImgs.slice(0, 1);
210
+ else
211
+ decliImgs = [];
212
+ }
213
+ return Object.assign(Object.assign(Object.assign({}, sameDecli), (!!decliImgs.length ? { images_path: decliImgs } : {})), { qte: qte, parent_slug: indexedProduct.slug, product_upsells: indexedProduct.product_upsells, categories: indexedProduct.categories });
214
+ }
215
+ catch (e) {
216
+ console.log('error on converting prod to cart item: ', e.toString());
217
+ return;
218
+ }
219
+ };
220
+ exports.generateCartItemForSku = generateCartItemForSku;
221
+ const addCartItems = async (currentCart, newItems, fetchInventory, shouldCheckInventory = true, handleInventoryError, defaultAdd = false, isServiceUpsellOfSku = false, customPriceList) => {
222
+ let newCart = Object.assign({}, currentCart);
223
+ let items = [...newItems];
224
+ if (!!customPriceList) {
225
+ items = items.map((i) => !!(0, exports.priceWasOverridden)(i) ? i : (0, g2_1.checkForCustomPriceEquivalent)(i, customPriceList));
226
+ }
227
+ let itemsToUpdate = [];
228
+ const shouldAddItem = async (cartItem) => {
229
+ const checkInventory = !!shouldCheckInventory && !!!cartItem.is_service && !!!cartItem.is_upsell_of_sku;
230
+ let inventoryItem;
231
+ if (!!fetchInventory) {
232
+ try {
233
+ inventoryItem = !!cartItem.is_service ? undefined : await fetchInventory(cartItem.sku);
234
+ }
235
+ catch (e) {
236
+ console.log('error on fetching inventory: ', e);
237
+ }
238
+ }
239
+ const itemAlreadyInCart = (0, findIndex_1.default)(newCart.items, (item) => item.sku === cartItem.sku);
240
+ if (!!checkInventory) {
241
+ // If inventory not found, return error
242
+ if (!!!inventoryItem)
243
+ return 'already_max_qte';
244
+ // If the webstore is not defined or the avaibility = 0
245
+ if (!!inventoryItem.is_infinite_stock || !!cartItem.is_service || !!cartItem.is_sample)
246
+ return cartItem;
247
+ if (!!!inventoryItem.web_inventory || !!!inventoryItem.web_inventory.available) {
248
+ return false;
249
+ }
250
+ if (cartItem.qte > inventoryItem.web_inventory.available) {
251
+ return 'already_max_qte';
252
+ }
253
+ if (itemAlreadyInCart !== -1 && !!!isServiceUpsellOfSku) {
254
+ // If the quantity we are adding is more than the available qte of the item
255
+ if (!!shouldCheckInventory && !!inventoryItem.web_inventory && !!inventoryItem.web_inventory.available) {
256
+ if ((0, toNumber_1.default)(newCart.items[itemAlreadyInCart].qte) + (0, toNumber_1.default)(cartItem.qte) >
257
+ (0, toNumber_1.default)(inventoryItem.web_inventory.available)) {
258
+ return 'already_max_qte';
259
+ }
260
+ }
261
+ itemsToUpdate.push({
262
+ sku: cartItem.sku,
263
+ qte: (0, toNumber_1.default)(newCart.items[itemAlreadyInCart].qte) + (0, toNumber_1.default)(cartItem.qte)
264
+ });
265
+ return false;
266
+ }
267
+ }
268
+ if (itemAlreadyInCart !== -1) {
269
+ itemsToUpdate.push({
270
+ sku: cartItem.sku,
271
+ qte: (0, toNumber_1.default)(newCart.items[itemAlreadyInCart].qte) + (0, toNumber_1.default)(cartItem.qte)
272
+ });
273
+ return false;
274
+ }
275
+ return cartItem;
276
+ };
277
+ const itemsToAdd = Array.isArray(items)
278
+ ? !!defaultAdd
279
+ ? items
280
+ : await Promise.all(items.map(async (cartItem) => await shouldAddItem(cartItem)))
281
+ : !!defaultAdd
282
+ ? [items]
283
+ : [await shouldAddItem(items)];
284
+ const filteredItems = itemsToAdd.filter((item) => !!item && item !== 'already_max_qte');
285
+ const hasMaxQtyItems = itemsToAdd.find((i) => i === 'already_max_qte');
286
+ if (!!hasMaxQtyItems && !!handleInventoryError) {
287
+ await handleInventoryError(false);
288
+ }
289
+ if (!!itemsToUpdate.length) {
290
+ const updateResult = await (0, exports.updateCartItems)(currentCart, itemsToUpdate, fetchInventory, shouldCheckInventory, handleInventoryError);
291
+ if (!!updateResult) {
292
+ newCart = updateResult.updatedCart;
293
+ }
294
+ }
295
+ newCart = Object.assign(Object.assign({}, newCart), { items: [...newCart.items, ...filteredItems] });
296
+ return {
297
+ cartData: newCart,
298
+ added: !!filteredItems && !!filteredItems.length,
299
+ updated: !!itemsToUpdate && !!itemsToUpdate.length,
300
+ maxQtyItems: !!hasMaxQtyItems
301
+ };
302
+ };
303
+ exports.addCartItems = addCartItems;
304
+ /**
305
+ * Optimized copy of addCartItems function for now. Will eventually replace addCartItems.
306
+ * Verify a list of items to be potentially added to cart.
307
+ * @param currentCart
308
+ * @param newItems
309
+ * @param fetchInventory
310
+ * @param options
311
+ */
312
+ const verifyAndReturnToBeAddedCartItems = async (currentCart, newItems, fetchInventory, options = {}) => {
313
+ let newCart = Object.assign({}, currentCart);
314
+ let items = [...newItems];
315
+ if (!!options.customPriceList) {
316
+ items = items.map((i) => !!(0, exports.priceWasOverridden)(i) ? i : (0, g2_1.checkForCustomPriceEquivalent)(i, options.customPriceList));
317
+ }
318
+ let itemsToUpdate = [];
319
+ const shouldAddItem = async (cartItem) => {
320
+ const checkInventory = !!options.shouldCheckInventory && !!!cartItem.is_service && !!!cartItem.is_upsell_of_sku;
321
+ let inventoryItem;
322
+ if (!!fetchInventory) {
323
+ try {
324
+ inventoryItem = !!cartItem.is_service ? undefined : await fetchInventory(cartItem.sku);
325
+ }
326
+ catch (e) {
327
+ console.log('error on fetching inventory: ', e);
328
+ }
329
+ }
330
+ const itemAlreadyInCart = (0, findIndex_1.default)(newCart.items, (item) => item.sku === cartItem.sku);
331
+ if (!!checkInventory) {
332
+ // If inventory not found, return error
333
+ if (!!!inventoryItem)
334
+ return 'inventory_not_found';
335
+ // Check if item's inventory is not followed (if item is a service, a sample, etc...). Skip check if true
336
+ if (inventoryItem.is_infinite_stock || cartItem.is_service || cartItem.is_sample)
337
+ return cartItem;
338
+ // Check store inventory if specified, or default to web inventory
339
+ let inventoryToCheck;
340
+ if (options.shouldCheckStoreInventory) {
341
+ const sameStoreInventory = inventoryItem.inventories.find((i) => i.store_id == options.shouldCheckStoreInventory);
342
+ if (!!sameStoreInventory) {
343
+ inventoryToCheck = sameStoreInventory.qty.available;
344
+ }
345
+ }
346
+ else {
347
+ inventoryToCheck = (0, object_1.recursiveCheckObject)(inventoryItem, 'web_inventory.available');
348
+ }
349
+ // If no inventory found, return false
350
+ if (typeof inventoryToCheck == 'undefined') {
351
+ return 'inventory_not_found';
352
+ }
353
+ if (cartItem.qte > inventoryToCheck) {
354
+ return 'already_max_qte';
355
+ }
356
+ // If item already in cart
357
+ if (itemAlreadyInCart !== -1 && !!!options.isServiceUpsellOfSku) {
358
+ // If the quantity we are adding is more than the available qte of the item
359
+ if (!!options.shouldCheckInventory && !!inventoryToCheck && !options.useReservedInventory) {
360
+ if ((0, toNumber_1.default)(newCart.items[itemAlreadyInCart].qte) + (0, toNumber_1.default)(cartItem.qte) > (0, toNumber_1.default)(inventoryToCheck)) {
361
+ return 'already_max_qte';
362
+ }
363
+ }
364
+ itemsToUpdate.push({
365
+ sku: cartItem.sku,
366
+ qte: (0, toNumber_1.default)(newCart.items[itemAlreadyInCart].qte) + (0, toNumber_1.default)(cartItem.qte)
367
+ });
368
+ return false;
369
+ }
370
+ }
371
+ if (itemAlreadyInCart !== -1) {
372
+ itemsToUpdate.push({
373
+ sku: cartItem.sku,
374
+ qte: (0, toNumber_1.default)(newCart.items[itemAlreadyInCart].qte) + (0, toNumber_1.default)(cartItem.qte)
375
+ });
376
+ return false;
377
+ }
378
+ return cartItem;
379
+ };
380
+ const itemsToUse = Array.isArray(items) ? items : [items];
381
+ const itemsToAdd = !!options.defaultAdd
382
+ ? itemsToUse
383
+ : await Promise.all(itemsToUse.map(async (cartItem) => await shouldAddItem(cartItem)));
384
+ const filteredItems = itemsToAdd.filter((item) => !!item && typeof item !== 'string');
385
+ const hasErrors = itemsToAdd.some((i) => i === 'already_max_qte' || i === 'inventory_not_found');
386
+ if (!!hasErrors && !!options.handleInventoryError) {
387
+ await options.handleInventoryError(false);
388
+ }
389
+ if (!!itemsToUpdate.length) {
390
+ const updateResult = await (0, exports.verifyAndReturnToBeUpdatedCartItems)(currentCart.items, itemsToUpdate, fetchInventory, {
391
+ shouldCheckInventory: false
392
+ });
393
+ if (!!updateResult) {
394
+ newCart.items = updateResult.updatedCartItems;
395
+ }
396
+ }
397
+ newCart = Object.assign(Object.assign({}, newCart), { items: [...newCart.items, ...filteredItems] });
398
+ return {
399
+ cartData: newCart,
400
+ added: !!filteredItems && !!filteredItems.length,
401
+ updated: !!itemsToUpdate && !!itemsToUpdate.length,
402
+ hasErrors: hasErrors
403
+ };
404
+ };
405
+ exports.verifyAndReturnToBeAddedCartItems = verifyAndReturnToBeAddedCartItems;
406
+ // Get province from province array with english, french or abbreviation
407
+ const getCurrentProvince = (provinceToCheck) => {
408
+ let formattedProvince = (0, string_1.stripAccents)(provinceToCheck.toLowerCase());
409
+ return (0, find_1.default)(data_1.provinces, (province) => (0, string_1.stripAccents)(province.value.toLowerCase()) === formattedProvince ||
410
+ (0, string_1.stripAccents)(province.label.toLowerCase()) === formattedProvince ||
411
+ (0, string_1.stripAccents)(province.label_en.toLowerCase()) === formattedProvince);
412
+ };
413
+ exports.getCurrentProvince = getCurrentProvince;
414
+ const getTaxProvinceFromShippingAddress = (address) => {
415
+ let taxProvince;
416
+ const shippingState = address.state.toLowerCase();
417
+ const shortCartShippingState = data_1.provinces.find((p) => p.value.toLowerCase() == shippingState ||
418
+ p.label.toLocaleLowerCase() == shippingState ||
419
+ p.label_en.toLowerCase() == shippingState);
420
+ if (!!shortCartShippingState)
421
+ taxProvince = shortCartShippingState.value;
422
+ return taxProvince;
423
+ };
424
+ exports.getTaxProvinceFromShippingAddress = getTaxProvinceFromShippingAddress;
425
+ /**
426
+ * Constructs and returns data for indexed cart (algolia or addio)
427
+ * @param cartData - Current cart data
428
+ * @param space - Space object
429
+ * @param options.setPaidAtIfUndefined - Optionnal - If true, will set paid_at with current date
430
+ * @param options.customer - Optionnal - If defined, adds info based on customer to indexedCart
431
+ * @param option.createdAt - Optionnal - If defined, added to indexedCart, else null value added
432
+ * @param option.updatedAt - Optionnal - If defined, added to indexedCart, else null value added
433
+ * @param associatedTransfers - Optionnal, used to pass transfers and statuses to indexed cart. Will only be added if cart's has_transfers prop is true
434
+ * @returns <IIndexedCart>
435
+ */
436
+ const getIndexedCartData = (cartData, space, options = {}) => {
437
+ var _a, _b, _c, _d, _e;
438
+ const getPaidAt = () => {
439
+ let paidAt;
440
+ try {
441
+ paidAt =
442
+ !!cartData && !!cartData.paid_at
443
+ ? (0, data_1.formatDate)(cartData.paid_at)
444
+ : !!options.setPaidAtIfUndefined
445
+ ? (0, moment_1.default)().toDate()
446
+ : null;
447
+ }
448
+ catch (error) {
449
+ paidAt = cartData.paid_at || null;
450
+ }
451
+ return { paid_at: !!paidAt ? (0, moment_1.default)(paidAt).unix() : null };
452
+ };
453
+ const itemDict = {};
454
+ for (let item of cartData.items) {
455
+ itemDict[item.sku] = Object.assign(Object.assign({ qty: item.qte, refunded_qty: (_a = item.refunded_qty) !== null && _a !== void 0 ? _a : 0, refunded: (_b = item.refunded) !== null && _b !== void 0 ? _b : false }, (typeof item.qte_reserved != 'undefined' ? { reserved_qty: item.qte_reserved } : {})), (typeof item.qte_bypass_inventory_check != 'undefined'
456
+ ? { bypass_inventory_check_qty: item.qte_bypass_inventory_check }
457
+ : {}));
458
+ }
459
+ const cartPromos = (0, discount_1.getCartPromo)(cartData);
460
+ // If the cart has a promo applied with a promo code, or a discount on a product added via the POS, save info to index
461
+ let hasPromos = !!cartPromos && !!cartPromos.length;
462
+ let hasCustomDiscount = !!cartData.items.some((i) => !!(0, object_1.recursiveCheckObject)(i, 'promo_price.authorization.note') ||
463
+ !!(0, object_1.recursiveCheckObject)(i, 'discount_price.authorization.note'));
464
+ const indexedCartData = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ objectID: cartData.id, cart_type: cartData.cart_type, status: cartData.status, ref: cartData.ref || '', invoice_ref: (_c = cartData.invoice_ref) !== null && _c !== void 0 ? _c : null, created_at: !!options.createdAt ? (0, moment_1.default)(options.createdAt).unix() : null, updated_at: !!options.updatedAt
465
+ ? (0, moment_1.default)(options.updatedAt).unix()
466
+ : !!cartData.paid_at
467
+ ? getPaidAt().paid_at
468
+ : (0, moment_1.default)().unix(), processed_at: !!cartData.processed_by && !!cartData.processed_by.date
469
+ ? (0, moment_1.default)((0, data_1.formatDate)(cartData.processed_by.date)).unix()
470
+ : null }, (typeof cartData.to_be_verified_by_clerk !== 'undefined'
471
+ ? { to_be_verified_by_clerk: cartData.to_be_verified_by_clerk }
472
+ : {})), { on_hold: cartData.on_hold, is_on_hold: !!cartData.on_hold,
473
+ // --------------------------------
474
+ // #region PROMOS
475
+ cart_promos_applied: cartPromos !== null && cartPromos !== void 0 ? cartPromos : null, has_promos: !!hasPromos ? hasPromos : null, has_custom_discount: !!hasCustomDiscount ? hasCustomDiscount : null,
476
+ // #endregion
477
+ // --------------------------------
478
+ // #region ITEMS AND SPECIFIC TYPES
479
+ items: itemDict, is_booking: !!cartData.is_booking, is_promise_to_purchase: !!cartData.promise_to_purchase,
480
+ // #endregion
481
+ // --------------------------------
482
+ // #region TRANSFERS
483
+ has_transfers: !!cartData.has_transfers && !!options.associatedTransfers ? options.associatedTransfers : undefined }), getPaidAt()), (0, exports.getPaidByForIndexedCart)(cartData)), { subtotal: cartData.subtotal, total: cartData.total,
484
+ // #endregions
485
+ // --------------------------------
486
+ // #region EXPEDITION
487
+ is_pickup: !!cartData.is_pickup, out_of_zone: !!cartData.shipping_payload && !!cartData.shipping_payload.isOutOfArea, billing_phone: cartData.billing_address ? cartData.billing_address.expedition_recipient_phone : null, shipping_phone: cartData.shipping_address ? cartData.shipping_address.expedition_recipient_phone : null,
488
+ // #endregion
489
+ // --------------------------------
490
+ // #region CUSTOMER
491
+ customer_id: !!cartData.customer_id ? cartData.customer_id : null, customer_name: cartData.billing_address ? cartData.billing_address.expedition_recipient_name : null, customer_email: cartData.customer_info && cartData.customer_info.customer_default_email
492
+ ? cartData.customer_info.customer_default_email
493
+ : cartData.user_email
494
+ ? cartData.user_email
495
+ : null, customer_company_name: !!(0, object_1.recursiveCheckObject)(cartData, 'customer_info.company_name')
496
+ ? (0, object_1.recursiveCheckObject)(cartData, 'customer_info.company_name')
497
+ : !!options.customer && !!(0, object_1.recursiveCheckObject)(options.customer, 'company_info.invoice_info.legal_name')
498
+ ? (0, object_1.recursiveCheckObject)(options.customer, 'company_info.invoice_info.legal_name')
499
+ : null, is_detail_customer: !!!cartData.customer_info || !!!cartData.customer_info.pro_title || !!!cartData.customer_info.pro_proof_doc, customer_type: !!(0, object_1.recursiveCheckObject)(cartData, 'customer_info.pro_title')
500
+ ? Cart_1.CartCustomerEnum.PRO
501
+ : !!cartData.customer_id
502
+ ? Cart_1.CartCustomerEnum.CONNECTED
503
+ : Cart_1.CartCustomerEnum.GUEST, customer_rep: !!options.customer ? options.customer.represented_by : null, customer_external_class: (0, object_1.recursiveCheckObject)(cartData, 'customer_info.customer_external_class') ||
504
+ (0, object_1.recursiveCheckObject)(options.customer, 'basic_info.customer_professionnal_info.external_customer_class') ||
505
+ null,
506
+ // #endregion
507
+ // --------------------------------
508
+ // #region SEO / MARKETING
509
+ keywords: (0, uniq_1.default)((0, flatten_1.default)(cartData.items.map((item) => {
510
+ // Now adds parent_name to keywords if found in cart_item
511
+ return [...(item.parent_name || []).map((n) => n.value), ...(item.name || []).map((n) => n.value), item.sku];
512
+ }))), cart_slug_list: (0, uniq_1.default)(cartData.items.map((item) => {
513
+ return item.parent_slug || '';
514
+ })), from_marketplace: (_d = cartData.from_marketplace) !== null && _d !== void 0 ? _d : null }), (!!space.data().id && [services_1.SpaceIdEnum.GR, services_1.SpaceIdEnum.CMV].includes(space.data().id)
515
+ ? Object.assign(Object.assign({}, (0, exports.getShippingStoreInfo)(cartData, space)), (services_1.SpaceIdEnum.GR === space.data().id
516
+ ? Object.assign(Object.assign({ order_type: (0, invoices_1.getOrderTypeString)(cartData, {
517
+ frOnly: true,
518
+ slugSafe: (0, cart_1.checkIfCartContainsType)(cart_2.CartGeneralTypeEnum.BOOKING_BETON, cartData),
519
+ installAsType: true
520
+ }) }, (0, exports.getAssignedToInfo)(cartData)), { project_number: (_e = (0, object_1.recursiveCheckObject)(cartData, 'shipping_payload.orderOrProjectNumber')) !== null && _e !== void 0 ? _e : null }) : {})) : {})
521
+ // #endregion
522
+ );
523
+ return indexedCartData;
524
+ };
525
+ exports.getIndexedCartData = getIndexedCartData;
526
+ const getPaidByForIndexedCart = (order) => {
527
+ if (!!!order.paid_by && !!!order.custom_payment_type)
528
+ return { paid_by: null, multiple_payments: null };
529
+ const currentPaidBy = !!order.custom_payment_type && !!order.custom_payment_type.method
530
+ ? order.custom_payment_type.method
531
+ : order.paid_by;
532
+ // If order has multiple payment types...
533
+ if (currentPaidBy === Cart_1.PaymentTypeEnum.MULTIPLE && !!order.payment_details && !!order.payment_details.length) {
534
+ const firstPayment = order.payment_details.length === 1 || order.payment_details[0].method !== Cart_1.PaymentTypeEnum.TOBERECEIVED
535
+ ? order.payment_details[0]
536
+ : order.payment_details[1];
537
+ return {
538
+ paid_by: firstPayment.method,
539
+ multiple_payments: order.payment_details.length > 1
540
+ };
541
+ }
542
+ else {
543
+ return {
544
+ paid_by: currentPaidBy !== null && currentPaidBy !== void 0 ? currentPaidBy : null,
545
+ multiple_payments: null
546
+ };
547
+ }
548
+ };
549
+ exports.getPaidByForIndexedCart = getPaidByForIndexedCart;
550
+ const getAssignedToInfo = (order) => {
551
+ if (!!!order.assigned_to || !!!order.assigned_to.length)
552
+ return { assigned_to: null };
553
+ const mostRecentAssignedTo = (0, orderBy_1.default)(order.assigned_to, (assigned) => (0, moment_1.default)((0, data_1.formatDate)(assigned.date)).unix(), 'desc')[0];
554
+ if (!!!mostRecentAssignedTo || !!!mostRecentAssignedTo.is_active)
555
+ return { assigned_to: null };
556
+ return {
557
+ assigned_to: mostRecentAssignedTo.user_name
558
+ };
559
+ };
560
+ exports.getAssignedToInfo = getAssignedToInfo;
561
+ const getShippingStoreInfo = (order, space) => {
562
+ if (!!order.is_pickup) {
563
+ if (!!order.shipping_payload && !!order.shipping_payload.pickup_store && !!order.shipping_payload.pickup_store.id)
564
+ return {
565
+ store: {
566
+ id: order.shipping_payload.pickup_store.id,
567
+ name: order.shipping_payload.pickup_store.name
568
+ }
569
+ };
570
+ if (!!order.shipping_address)
571
+ return {
572
+ store: (0, exports.getOrderStoreInfo)(space.data(), order.shipping_address.address)
573
+ };
574
+ }
575
+ return { store: { id: 'Livraison', name: 'Livraison' } };
576
+ };
577
+ exports.getShippingStoreInfo = getShippingStoreInfo;
578
+ const checkIfShippingSameAsBilling = (cart) => {
579
+ return (!!cart.shipping_address &&
580
+ !!cart.billing_address &&
581
+ (0, isEqual_1.default)(cart.shipping_address.address, cart.billing_address.address));
582
+ };
583
+ exports.checkIfShippingSameAsBilling = checkIfShippingSameAsBilling;
584
+ const getOrderStoreInfo = (spaceData, storeAddress) => {
585
+ // Pour algo, si informations du store correspondant non-trouvés, renvoit un 'all' pour qu'il affiche tout le temps
586
+ const defaultStoreInfo = {
587
+ id: 'all',
588
+ name: 'all'
589
+ };
590
+ try {
591
+ if (!!!storeAddress || !!!spaceData)
592
+ return defaultStoreInfo;
593
+ const allStores = spaceData.stores_warehouses;
594
+ const sameStore = allStores.find((store) => store.address.postal_code === storeAddress.postal_code);
595
+ if (!!!sameStore)
596
+ return defaultStoreInfo;
597
+ return {
598
+ id: sameStore.id,
599
+ name: sameStore.name
600
+ };
601
+ }
602
+ catch (e) {
603
+ console.log('error on fetching store info for algo order: ', e);
604
+ return defaultStoreInfo;
605
+ }
606
+ };
607
+ exports.getOrderStoreInfo = getOrderStoreInfo;
608
+ const getModifiedItems = (newItems, oldItems) => {
609
+ let itemsForInventory = [];
610
+ for (const i of newItems) {
611
+ const itemInOldArray = oldItems.find((o) => o.sku === i.sku);
612
+ // If the item was not in the old cart, keep all its info
613
+ if (!!!itemInOldArray) {
614
+ itemsForInventory = [...itemsForInventory, i];
615
+ continue;
616
+ }
617
+ // If the item is the same in the old cart and in the new one, do nothing
618
+ if (i.qte === itemInOldArray.qte)
619
+ continue;
620
+ // If we are here, it means the item is still in the cart, but it's quantities changed. If the new qte is smaller, the new qte will be negative to add items back to inventory
621
+ const newQte = i.qte - itemInOldArray.qte;
622
+ itemsForInventory = [
623
+ ...itemsForInventory,
624
+ Object.assign(Object.assign({}, i), { qte: newQte })
625
+ ];
626
+ }
627
+ for (const i of oldItems) {
628
+ const itemInNewArray = newItems.find((o) => o.sku === i.sku);
629
+ // If the item used to be in the cart, but is no longer there, save all it's quantity as negative to put it back in the inventory
630
+ if (!!!itemInNewArray) {
631
+ itemsForInventory = [
632
+ ...itemsForInventory,
633
+ Object.assign(Object.assign({}, i), { qte: i.qte == 0 ? 0 : i.qte * -1 })
634
+ ];
635
+ }
636
+ }
637
+ return itemsForInventory;
638
+ };
639
+ exports.getModifiedItems = getModifiedItems;
640
+ /**
641
+ * Get all active transfers for a cart where given items are found
642
+ * @param allTransfersForCart All transfers associated to a given cart
643
+ * @param cartItems All cart items for whitch to check transfers if found
644
+ */
645
+ const getActiveTransfersByItemInCart = (allTransfersForCart, cartItems) => {
646
+ if (!!!allTransfersForCart || !!!allTransfersForCart.length)
647
+ return [];
648
+ const allActive = allTransfersForCart.filter((t) => !!!t.data().completed);
649
+ if (!!!allActive.length)
650
+ return [];
651
+ let foundInTransfer = [];
652
+ for (let item of cartItems) {
653
+ const sameInTransfers = allActive.filter((t) => t.data().products.some((p) => p.sku == item.sku));
654
+ if (!!sameInTransfers)
655
+ foundInTransfer.push({
656
+ sku: item.sku,
657
+ transfers: sameInTransfers,
658
+ hasUpdatableTransfer: sameInTransfers.some((t) => t.transferAllowsIndependantProductUpdate()),
659
+ hasNonUpdatableTransfer: sameInTransfers.some((t) => !t.transferAllowsIndependantProductUpdate())
660
+ });
661
+ }
662
+ return foundInTransfer;
663
+ };
664
+ exports.getActiveTransfersByItemInCart = getActiveTransfersByItemInCart;
665
+ /**
666
+ * Get the sale unit slug for a cart item
667
+ *
668
+ * @param item the cart item
669
+ * @returns unit slug or empty if not found
670
+ */
671
+ const getItemSaleUnitSlug = (item) => {
672
+ const unit = (item.other_units || []).find((x) => x.is_sale_unit);
673
+ return unit ? unit.unit_slug : '';
674
+ };
675
+ exports.getItemSaleUnitSlug = getItemSaleUnitSlug;
676
+ /**
677
+ * Constructs an object for each transfer, with corresponding products to update and by which quantity
678
+ * @param allCartTransfers All transfer objects associated to a given cart
679
+ * @param updatedItems Array of pertinent data per item updated to determine which transfers to update quantities for
680
+ * @returns {TransfersWithItemsToUpdate | undefined}
681
+ */
682
+ const getItemsToUpdateByTransfer = (allCartTransfers, updatedItems) => {
683
+ if (!!!allCartTransfers.length || !!!updatedItems.length)
684
+ return;
685
+ const skusFoundInTransfers = (0, exports.getActiveTransfersByItemInCart)(allCartTransfers, updatedItems.map((upItem) => upItem.item));
686
+ if (!!!skusFoundInTransfers.length)
687
+ return;
688
+ let transfersToUpdate = {};
689
+ for (let upItem of updatedItems) {
690
+ const sku = upItem.item.sku;
691
+ const qteToUpdate = upItem.qteToUpdate;
692
+ let sameItemData = skusFoundInTransfers.find((s) => s.sku == sku);
693
+ if (!!!sameItemData || !!!sameItemData.transfers.length)
694
+ continue;
695
+ const transfersWithSameItem = sameItemData.transfers;
696
+ const filteredInventoriesByTransferStores = !!upItem.inventoryItem
697
+ ? upItem.inventoryItem.inventories.filter((i) => transfersWithSameItem.some((t) => !!t.data().from && t.data().from == i.store_id))
698
+ : undefined;
699
+ // A. If quantities are to be added...
700
+ if (qteToUpdate > 0) {
701
+ const inventoryUnitQteToUpdate = (0, inventories_1.getConvertedUnitQuantity)(upItem.item.other_units, qteToUpdate, 'inventory_unit', true);
702
+ // A1. ... If some transfers are currently at status INITIALIZED (with no "from" store set), add to first initialized found (since quantities can be redistributed by store when opening transfer)
703
+ const initializedStatusTransfers = transfersWithSameItem.filter((t) => t.data().status == TransferRequest_1.TransferRequestStatusEnum.INITIATED);
704
+ if (!!initializedStatusTransfers.length) {
705
+ const firstTransfer = initializedStatusTransfers[0];
706
+ const transferID = firstTransfer.data().id;
707
+ if (!!!transferID)
708
+ continue;
709
+ const dataForTransfer = transfersToUpdate[transferID] || [];
710
+ dataForTransfer.push({
711
+ sku,
712
+ ajustmentQte: inventoryUnitQteToUpdate
713
+ });
714
+ transfersToUpdate[transferID] = dataForTransfer;
715
+ continue;
716
+ }
717
+ // A2. ... Else, add to transfer where store has most quantities
718
+ // TODO - Should we check if quantities are available in store before adding to transfer ?
719
+ // TODO - Maybe based on if property space.options.transfer_requests.dont_limit_qty ?
720
+ const storeWithMostQuantities = !!filteredInventoriesByTransferStores
721
+ ? filteredInventoriesByTransferStores.reduce((storeA, storeB) => (0, toNumber_1.default)(storeA.qty.available) > (0, toNumber_1.default)(storeB.qty.available) ? storeA : storeB)
722
+ : undefined;
723
+ const transferToUse = !!storeWithMostQuantities
724
+ ? transfersWithSameItem.find((t) => t.data().from == storeWithMostQuantities.store_id)
725
+ : transfersWithSameItem[0];
726
+ if (!!!transferToUse || !!!transferToUse.data().id)
727
+ continue;
728
+ const dataForTransfer = transfersToUpdate[transferToUse.data().id] || [];
729
+ dataForTransfer.push({ sku, ajustmentQte: inventoryUnitQteToUpdate });
730
+ transfersToUpdate[transferToUse.data().id] = dataForTransfer;
731
+ continue;
732
+ }
733
+ // B. If quantities are to be removed...
734
+ if (qteToUpdate < 0) {
735
+ // ... remove from all transfers until done, starting with transfers at status INITIALIZED, then by the store with the least quantities currently available
736
+ let qteToRemove = qteToUpdate * -1; // change to positive value to facilitate checks later. Will be changed to negative when saved in qteToUpdate props for each transfer
737
+ let inventoryUnitQteToRemove = (0, inventories_1.getConvertedUnitQuantity)(upItem.item.other_units, qteToRemove, 'inventory_unit', true);
738
+ const inventoriesByAvailabilityAsc = (0, orderBy_1.default)(filteredInventoriesByTransferStores, (i) => (0, toNumber_1.default)(i.qty.available));
739
+ const transfersByInventory = (0, orderBy_1.default)(transfersWithSameItem, (t) => [
740
+ t.data().status == TransferRequest_1.TransferRequestStatusEnum.INITIATED ? 0 : 1,
741
+ inventoriesByAvailabilityAsc.findIndex((i) => i.store_id == t.data().from)
742
+ ]);
743
+ for (let transfer of transfersByInventory) {
744
+ if (!!!transfer.data().id)
745
+ continue;
746
+ const sameProd = transfer.data().products.find((p) => p.sku == sku);
747
+ if (!!!sameProd)
748
+ continue;
749
+ const currentQte = sameProd.qte;
750
+ const qteToBeUpdated = currentQte < inventoryUnitQteToRemove ? currentQte : inventoryUnitQteToRemove;
751
+ const dataForTransfer = transfersToUpdate[transfer.data().id] || [];
752
+ dataForTransfer.push({ sku, ajustmentQte: qteToBeUpdated == 0 ? qteToBeUpdated : qteToBeUpdated * -1 }); // value changed back to a negative here
753
+ transfersToUpdate[transfer.data().id] = dataForTransfer;
754
+ inventoryUnitQteToRemove -= qteToBeUpdated;
755
+ if (qteToRemove <= 0)
756
+ break;
757
+ }
758
+ }
759
+ }
760
+ return transfersToUpdate;
761
+ };
762
+ exports.getItemsToUpdateByTransfer = getItemsToUpdateByTransfer;
763
+ const getILangForUpdateType = (updateType) => {
764
+ const dict = {
765
+ [`${Cart_1.UpdateTypeEnum.CART_CONTENT}`]: { fr: 'Ajustement de la commande', en: 'Updated cart content' },
766
+ [`${Cart_1.UpdateTypeEnum.PROCESSING_STORE}`]: {
767
+ fr: 'Changement succ. de traitement',
768
+ en: 'Updated processing store'
769
+ }
770
+ };
771
+ return dict[updateType || Cart_1.UpdateTypeEnum.CART_CONTENT];
772
+ };
773
+ exports.getILangForUpdateType = getILangForUpdateType;
774
+ const getSubtotalToCheckForPromo = (allCartItems, currentCartSubtotal, space, feePromosTotalRemoved, removeServiceFees) => {
775
+ // ** NEW - Now excludes escompte supp. products from services when checking subtotal for promotions
776
+ const serviceFeeProducts = !!!removeServiceFees
777
+ ? []
778
+ : allCartItems.filter((i) => !!i.is_service && !(0, g2_1.isEscompteSuppItem)(i.sku));
779
+ const serviceFeeSubtotal = !!!serviceFeeProducts.length
780
+ ? 0
781
+ : (0, sumBy_1.default)(serviceFeeProducts, (i) => {
782
+ const itemPrice = (0, products_1.getLowestPrice)(i).price.amount;
783
+ return (0, round_1.default)(((0, isNumber_1.default)(itemPrice) ? Number(itemPrice) : 0) * i.qte, space.data().product_preferences.decimals || 2);
784
+ });
785
+ let totalRemoved = serviceFeeSubtotal;
786
+ // If there is a service and fees total, calculates the service and fees total after taking into account their promos
787
+ if (!!totalRemoved) {
788
+ totalRemoved -= feePromosTotalRemoved;
789
+ }
790
+ // Removes that calculated total from the current subtotal to get the subtotal without services and fees, in order to calculate the right promo amount
791
+ return currentCartSubtotal - totalRemoved;
792
+ };
793
+ exports.getSubtotalToCheckForPromo = getSubtotalToCheckForPromo;
794
+ const getAllPromoAppliedPrices = (allPromos, subtotalToUse, items, space, isRefund) => {
795
+ var _a;
796
+ let promoAmounts = [];
797
+ let updatedSubtotal = subtotalToUse;
798
+ // REMOVE PAYMENT INCENTIVE PROMOS FROM ARRAY
799
+ // Since this type of promos ('total_after_taxes') must be calculated and
800
+ // removed from total amount AFTER shipping and taxes are calculated,
801
+ // they will be dealt with later in process and must not count in "subtotalWithoutPromotions" prop
802
+ let cartPromos = allPromos.filter((c) => c.applies_to != Cart_1.CartPromoAppliesToEnum.TOTAL_AFTER_TAXES);
803
+ // REORDER PROMOS
804
+ // a. if promos apply to products, bring to front of array
805
+ // b. if promos contain a promo_code that applies to subtotal,
806
+ // push it to the end of the array to check that one last
807
+ cartPromos = (0, orderBy_1.default)(cartPromos, (p) => {
808
+ if ([Cart_1.CartPromoAppliesToEnum.PRODUCT, Cart_1.CartPromoAppliesToEnum.ITEMS].includes(p.applies_to))
809
+ return 1;
810
+ if (p.promo_code && p.applies_to === Cart_1.CartPromoAppliesToEnum.SUBTOTAL) {
811
+ return 3;
812
+ }
813
+ return 2;
814
+ });
815
+ let feePromosTotal = 0;
816
+ for (let aPromo of cartPromos) {
817
+ let productTotalAmount = 0;
818
+ if ((isRefund || updatedSubtotal > 0) &&
819
+ !!aPromo &&
820
+ (aPromo.applies_to === Cart_1.CartPromoAppliesToEnum.SUBTOTAL || aPromo.applies_to === Cart_1.CartPromoAppliesToEnum.PRODUCT)) {
821
+ let amountToRemove = 0;
822
+ const amountUnit = aPromo.amount_unit || IDiscountRule_1.ResultActionEnum.PERCENT;
823
+ const appliesToProduct = aPromo.applies_to === Cart_1.CartPromoAppliesToEnum.PRODUCT;
824
+ const subtotalToCheck = !!aPromo.exclude_services_and_fees &&
825
+ !![IDiscountRule_1.ResultActionEnum.PERCENT, IDiscountRule_1.ResultActionEnum.PERCENT_SKU, IDiscountRule_1.ResultActionEnum.PERCENT_CATEGORY].includes(amountUnit) &&
826
+ !!!appliesToProduct
827
+ ? (0, exports.getSubtotalToCheckForPromo)(items, updatedSubtotal, space, feePromosTotal, true)
828
+ : updatedSubtotal;
829
+ if (appliesToProduct) {
830
+ let skuArray = [];
831
+ if (!!aPromo.item_given) {
832
+ skuArray = (0, discount_1.getSkuArrayForPromo)(aPromo.item_given);
833
+ }
834
+ const itemToCheck = items.filter((item) => !!aPromo && !!skuArray.includes(item.sku));
835
+ for (const anItem of itemToCheck) {
836
+ productTotalAmount += amountUnit.includes('amount')
837
+ ? anItem.qte
838
+ : (0, products_1.getLowestPrice)(anItem).price.amount * anItem.qte;
839
+ const newAmountToRemove = (0, data_1.getPromoTotalAmount)(items, aPromo, 'number', anItem.sku);
840
+ if (typeof newAmountToRemove !== 'number')
841
+ continue;
842
+ if (!!anItem && !!anItem.is_service)
843
+ feePromosTotal += newAmountToRemove;
844
+ amountToRemove += newAmountToRemove;
845
+ }
846
+ }
847
+ else {
848
+ amountToRemove = (_a = aPromo.amount_removed) !== null && _a !== void 0 ? _a : 0;
849
+ }
850
+ // round amountToRemove before removing from subtotal
851
+ amountToRemove = (0, round_1.default)(amountToRemove, 2);
852
+ const newSubtotal = amountUnit === IDiscountRule_1.ResultActionEnum.AMOUNT || aPromo.applies_to === Cart_1.CartPromoAppliesToEnum.PRODUCT
853
+ ? updatedSubtotal - amountToRemove
854
+ : updatedSubtotal - subtotalToCheck * (amountToRemove / 100);
855
+ if (!!aPromo.discount_id) {
856
+ promoAmounts.push({
857
+ id: aPromo.discount_id,
858
+ subtotalBefore: updatedSubtotal,
859
+ subtotalAfter: (0, round_1.default)(newSubtotal, 2),
860
+ amountRemoved: amountToRemove,
861
+ productTotalAmount: productTotalAmount,
862
+ appliesTo: aPromo.applies_to
863
+ });
864
+ }
865
+ updatedSubtotal = (0, round_1.default)(newSubtotal, 2);
866
+ }
867
+ }
868
+ return promoAmounts;
869
+ };
870
+ exports.getAllPromoAppliedPrices = getAllPromoAppliedPrices;
871
+ /**
872
+ Retrieves the original discount price of an item.
873
+ @param {ICartItem} item - The cart item object.
874
+ @param {'%' | '$'} output - The desired output format: percentage ('%') or currency ('$').
875
+ @returns - The original discount price.
876
+ */
877
+ const getOriginalPromoPriceForItem = (item, output) => {
878
+ const orgPrice = (0, exports.getOriginalDiscountPriceForItem)(item, products_1.unitTypeEnum.AMOUNT);
879
+ let price = orgPrice; // default value
880
+ const customItem = item.promo_price;
881
+ if (!!customItem) {
882
+ if (typeof customItem.original_amount !== 'undefined')
883
+ // previous real promo
884
+ price = customItem.original_amount;
885
+ else
886
+ price = !!customItem.overridden ? orgPrice : customItem.amount; // this is the first promo
887
+ }
888
+ if (output === products_1.unitTypeEnum.AMOUNT && price === 0 && orgPrice === 0)
889
+ return 0;
890
+ if (output === products_1.unitTypeEnum.PERCENT)
891
+ return (1 - price / orgPrice) * 100;
892
+ return price;
893
+ };
894
+ exports.getOriginalPromoPriceForItem = getOriginalPromoPriceForItem;
895
+ /**
896
+ Retrieves the original promo price of an item.
897
+ @param {ICartItem} item - The cart item object.
898
+ @param {unitTypeEnum} output - The desired output format: PERCENT ('%') or AMOUNT ('$').
899
+ @returns - The original promo price.
900
+ */
901
+ const getOriginalDiscountPriceForItem = (item, output) => {
902
+ let price = item.regular_price.amount; // default value
903
+ const customItem = item.discount_price;
904
+ if (!!customItem) {
905
+ if (typeof customItem.original_amount !== 'undefined' &&
906
+ (customItem.price_type !== products_1.priceTypeEnum.TIER_PRICING || !!customItem.overridden))
907
+ // previous real promo
908
+ price = customItem.original_amount;
909
+ else if (!!!customItem.overridden)
910
+ price = customItem.amount; // this is the first promo
911
+ }
912
+ if (output === products_1.unitTypeEnum.PERCENT)
913
+ return (1 - price / item.regular_price.amount) * 100;
914
+ return price;
915
+ };
916
+ exports.getOriginalDiscountPriceForItem = getOriginalDiscountPriceForItem;
917
+ /**
918
+ * Reajusts promo price with a provided "original" regular price amount
919
+ * @param item
920
+ * @param original
921
+ * @returns the cart item with updated promo price
922
+ */
923
+ const adjustPromoPrice = (item, original) => {
924
+ // get % of the promo
925
+ if (!!!item.promo_price)
926
+ return item; // no promo price
927
+ const promo = (0, exports.getOriginalPromoPriceForItem)(item, products_1.unitTypeEnum.AMOUNT);
928
+ const rate = promo / original;
929
+ if (rate == 1)
930
+ return item; // no change needed
931
+ return Object.assign(Object.assign({}, item), { promo_price: Object.assign(Object.assign({}, item.promo_price), { original_amount: !!item.promo_price.original_amount
932
+ ? item.promo_price.original_amount
933
+ : item.promo_price.amount, amount: (0, exports.getActualDiscountPrice)(item, products_1.unitTypeEnum.AMOUNT) * rate }) });
934
+ };
935
+ exports.adjustPromoPrice = adjustPromoPrice;
936
+ const getAddressStrArray = (address) => {
937
+ return [
938
+ `${!!address.app ? address.app + ' - ' : ''}${address.line1 || ''}`,
939
+ `${!!address.city ? address.city + ', ' : ''}${address.state || ''} ${address.postal_code || ''}`
940
+ ].filter((addr) => !!addr.trim());
941
+ };
942
+ exports.getAddressStrArray = getAddressStrArray;
943
+ /**
944
+ * Returns all payement methods for a given cart
945
+ * @param cartData
946
+ */
947
+ const getCartPaymentMethods = (cartData) => {
948
+ return !!cartData.payment_details
949
+ ? (cartData.payment_details || []).map((p) => p.method)
950
+ : !!cartData.paid_by
951
+ ? [cartData.paid_by]
952
+ : [];
953
+ };
954
+ exports.getCartPaymentMethods = getCartPaymentMethods;
955
+ /**
956
+ * Return last user to take payment for cart. Checks in order : 'completed_by' -> 'updated_by' -> 'processed_by' -> 'created_by'
957
+ * @param cartData The cart to check
958
+ * @param startCheckAt The step to start check at. Defaults to 'processed_by'
959
+ */
960
+ const getLastUserWhoTookPayment = (cartData, startCheckAt = 'processed_by') => {
961
+ let foundUser = undefined;
962
+ let allSteps = ['completed_by', 'updated_by', 'processed_by', 'created_by'];
963
+ // Splice original array to only keep entries from specified startCheckAt property
964
+ allSteps.splice(allSteps.indexOf(startCheckAt));
965
+ const checkCartProp = (property) => {
966
+ const foundData = cartData[property];
967
+ if (!!!foundData)
968
+ return;
969
+ if (Array.isArray(foundData)) {
970
+ return foundData.find((d) => d.took_payment);
971
+ }
972
+ return foundData;
973
+ };
974
+ for (const stepToCheck of allSteps) {
975
+ foundUser = checkCartProp(stepToCheck);
976
+ if (foundUser)
977
+ break;
978
+ }
979
+ return foundUser;
980
+ };
981
+ exports.getLastUserWhoTookPayment = getLastUserWhoTookPayment;
982
+ /**
983
+ * Constructs and returns an IPayment object for store credit
984
+ * @param storeCreditSlug The associated store credit's slug
985
+ * @param amount The amount of credits used as payment
986
+ * @returns {IPayment}
987
+ */
988
+ const constructStoreCreditPaymentEntry = (storeCreditSlug, amount) => {
989
+ return {
990
+ amount,
991
+ method: Cart_1.PaymentTypeEnum.STORE_CREDITS,
992
+ paid_at: new Date(),
993
+ ref: storeCreditSlug
994
+ };
995
+ };
996
+ exports.constructStoreCreditPaymentEntry = constructStoreCreditPaymentEntry;
997
+ // #region CUSTOM PRICES AND ESCOMPTES (added by POS)
998
+ /**
999
+ * Calculates applied amout for a custom added promo.
1000
+ * @param item Cart item on which custom promo was applied
1001
+ * @param type The custom promo type (unit price of added escompte)
1002
+ * @param amount The fixed amount or percentage of custom price allocated
1003
+ * @param substractAmountIfUnitPrice Optionnal. If true, amount received is removed from initialPrice. Else, amount is returned as is.
1004
+ * @returns {number}
1005
+ */
1006
+ const calculateAmountForCustomPromo = (item, type, amount, substractAmountIfUnitPrice) => {
1007
+ const initialPrice = !!item.discount_price ? item.discount_price.amount : item.regular_price.amount;
1008
+ if (type === Cart_1.CustomPromoType.UNIT_PRICE) {
1009
+ if (!substractAmountIfUnitPrice)
1010
+ return amount;
1011
+ return initialPrice - amount;
1012
+ }
1013
+ const promoAmount = (initialPrice * amount) / 100;
1014
+ return initialPrice - promoAmount;
1015
+ };
1016
+ exports.calculateAmountForCustomPromo = calculateAmountForCustomPromo;
1017
+ // #endregion
1018
+ // #region STORE CREDIT MANAGEMENT
1019
+ /**
1020
+ * Check if credit quantity for cart is valid and available.
1021
+ * @param creditToBeUsedInCart Amount to be used in credits.
1022
+ * @param customerID The customer's ID to check for available store credits.
1023
+ * @param space The current space obj
1024
+ * @param creditSlug La référence au type de store credit à vérifier
1025
+ */
1026
+ const validateStoreCreditUsage = async (creditToBeUsedInCart, customerID, space, creditSlug) => {
1027
+ const hasStoreCreditsSet = space.options.checkIfOptionIsSet('payment.space_has_store_credits');
1028
+ if (!hasStoreCreditsSet) {
1029
+ return {
1030
+ valid: false,
1031
+ error: {
1032
+ en: 'This retailer does not support store credits.',
1033
+ fr: "Ce commerçant n'offre pas de crédits en magasin."
1034
+ }
1035
+ };
1036
+ }
1037
+ if (!customerID) {
1038
+ return {
1039
+ valid: false,
1040
+ error: {
1041
+ en: 'Only logged-in users can use the credits.',
1042
+ fr: 'Seuls les utilisateur connectés peuvent utiliser les crédits.'
1043
+ }
1044
+ };
1045
+ }
1046
+ const creditAmount = creditToBeUsedInCart !== null && creditToBeUsedInCart !== void 0 ? creditToBeUsedInCart : 0;
1047
+ // VALIDATIONS
1048
+ // a. Valide que le crédit demandé est positif
1049
+ let valid = creditAmount >= 0;
1050
+ // b. Valide que le client a le reste nécessaire pour utiliser ses crédits comme mode de paiement
1051
+ if (valid) {
1052
+ let clientCheck = await space.customers.credits.validate(customerID, creditSlug, creditAmount);
1053
+ valid = !clientCheck;
1054
+ }
1055
+ return Object.assign({ valid }, (!valid
1056
+ ? {
1057
+ error: {
1058
+ en: 'Insufficient credits.',
1059
+ fr: 'Crédits insufisant.'
1060
+ }
1061
+ }
1062
+ : {}));
1063
+ };
1064
+ exports.validateStoreCreditUsage = validateStoreCreditUsage;
1065
+ // #endregion
1066
+ /**
1067
+ * Get total quantity of pallets purchased by a customer
1068
+ * @param space - Space object
1069
+ * @param customerId - Customer ID
1070
+ * @returns Total quantity of pallets purchased
1071
+ */
1072
+ const getPurchasedPalletsQuantityForCustomer = async (space, customerId) => {
1073
+ const palletSku = '210000000';
1074
+ const completedStatus = Cart_1.CartStatusEnum.COMPLETED;
1075
+ try {
1076
+ // 1. Get search index info for the space
1077
+ const searchInfo = (0, searchIndexes_1.getFetchInfoAlgoliaAddioSearch)(space);
1078
+ // 2. Fetch indexed completed orders for this customer that contain the pallet SKU (from 2026-01-01)
1079
+ const startDate = (0, moment_1.default)('2026-01-01');
1080
+ const endDate = (0, moment_1.default)();
1081
+ const filterStr = `customer_id:${customerId} AND status:${completedStatus} AND (created_at:${startDate.unix()} TO ${endDate.unix()}) AND (items.${palletSku}.refunded:false OR items.${palletSku}.refunded:true)`;
1082
+ // 3. Fetch all pages and sum pallet quantities
1083
+ let totalPallets = 0;
1084
+ let currentPage = 0;
1085
+ let nbPages = 1;
1086
+ while (currentPage < nbPages) {
1087
+ const indexedOrders = await Cart_2.default.fetch({
1088
+ app: searchInfo.app,
1089
+ api: searchInfo.api,
1090
+ space,
1091
+ filters: '',
1092
+ hpp: 1000,
1093
+ page: currentPage,
1094
+ query: '',
1095
+ indice: 'orders',
1096
+ f: filterStr,
1097
+ useProspr: searchInfo.useProspr
1098
+ });
1099
+ nbPages = indexedOrders.nbPages;
1100
+ if (!!indexedOrders.hits && !!indexedOrders.hits.length) {
1101
+ indexedOrders.hits.forEach((indexedOrder) => {
1102
+ const palletItem = !!indexedOrder.items ? indexedOrder.items[palletSku] : undefined;
1103
+ if (palletItem) {
1104
+ totalPallets += (0, toNumber_1.default)(palletItem.qty || 0);
1105
+ }
1106
+ });
1107
+ }
1108
+ currentPage++;
1109
+ }
1110
+ return totalPallets;
1111
+ }
1112
+ catch (error) {
1113
+ console.error('Error fetching purchased pallets:', error);
1114
+ throw new Error(`Failed to fetch purchased pallets: ${error}`);
1115
+ }
1116
+ };
1117
+ exports.getPurchasedPalletsQuantityForCustomer = getPurchasedPalletsQuantityForCustomer;
1118
+ const shouldIgnoreInventoryForItem = (item) => {
1119
+ return !!item.is_service || !!item.is_temp_prod || !!item.is_sample;
1120
+ };
1121
+ exports.shouldIgnoreInventoryForItem = shouldIgnoreInventoryForItem;
1122
1122
  //# sourceMappingURL=cart.js.map