addio-admin-sdk 1.7.144 → 1.7.145

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