addio-admin-sdk 1.7.196 → 1.7.198

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