addio-admin-sdk 1.7.196 → 1.7.197

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (589) hide show
  1. package/.babelrc +17 -17
  2. package/.env +14 -0
  3. package/.env.dev +14 -14
  4. package/.github/workflows/run_unit_test.yaml +48 -48
  5. package/.github/workflows/update_docs.yaml +32 -32
  6. package/addio-sdk-doc.md +1473 -1473
  7. package/changelog.md +582 -582
  8. package/dist/Interfaces/Address/index.d.ts +21 -21
  9. package/dist/Interfaces/Address/index.js +16 -16
  10. package/dist/Interfaces/Algolia/index.d.ts +183 -182
  11. package/dist/Interfaces/Algolia/index.js +2 -2
  12. package/dist/Interfaces/Attachement/index.d.ts +5 -5
  13. package/dist/Interfaces/Attachement/index.js +2 -2
  14. package/dist/Interfaces/Attribute/index.d.ts +53 -53
  15. package/dist/Interfaces/Attribute/index.js +10 -10
  16. package/dist/Interfaces/BGJob/index.d.ts +56 -56
  17. package/dist/Interfaces/BGJob/index.js +25 -25
  18. package/dist/Interfaces/BaseClass/index.d.ts +8 -8
  19. package/dist/Interfaces/BaseClass/index.js +2 -2
  20. package/dist/Interfaces/Blog/IBlogArticle.d.ts +18 -18
  21. package/dist/Interfaces/Blog/IBlogArticle.js +2 -2
  22. package/dist/Interfaces/Blog/IBlogAuthor.d.ts +7 -7
  23. package/dist/Interfaces/Blog/IBlogAuthor.js +2 -2
  24. package/dist/Interfaces/Blog/IBlogCategory.d.ts +9 -9
  25. package/dist/Interfaces/Blog/IBlogCategory.js +2 -2
  26. package/dist/Interfaces/Blog/IBlogComment.d.ts +13 -13
  27. package/dist/Interfaces/Blog/IBlogComment.js +2 -2
  28. package/dist/Interfaces/Blog/IBlogKeywords.d.ts +9 -9
  29. package/dist/Interfaces/Blog/IBlogKeywords.js +2 -2
  30. package/dist/Interfaces/Booking/index.d.ts +74 -74
  31. package/dist/Interfaces/Booking/index.js +17 -17
  32. package/dist/Interfaces/Brand/index.d.ts +15 -15
  33. package/dist/Interfaces/Brand/index.js +2 -2
  34. package/dist/Interfaces/Buylist/index.d.ts +19 -19
  35. package/dist/Interfaces/Buylist/index.js +2 -2
  36. package/dist/Interfaces/CMS/index.d.ts +28 -28
  37. package/dist/Interfaces/CMS/index.js +5 -5
  38. package/dist/Interfaces/Cart/IElavonPayload.d.ts +93 -93
  39. package/dist/Interfaces/Cart/IElavonPayload.js +17 -17
  40. package/dist/Interfaces/Cart/IMarketPayload.d.ts +12 -12
  41. package/dist/Interfaces/Cart/IMarketPayload.js +2 -2
  42. package/dist/Interfaces/Cart/IPandaPayload.d.ts +64 -64
  43. package/dist/Interfaces/Cart/IPandaPayload.js +18 -18
  44. package/dist/Interfaces/Cart/IPaymentCard.d.ts +22 -22
  45. package/dist/Interfaces/Cart/IPaymentCard.js +44 -44
  46. package/dist/Interfaces/Cart/IPaypalPayload.d.ts +9 -9
  47. package/dist/Interfaces/Cart/IPaypalPayload.js +2 -2
  48. package/dist/Interfaces/Cart/IPaysafePayload.d.ts +72 -72
  49. package/dist/Interfaces/Cart/IPaysafePayload.js +2 -2
  50. package/dist/Interfaces/Cart/IStripePayload.d.ts +66 -66
  51. package/dist/Interfaces/Cart/IStripePayload.js +2 -2
  52. package/dist/Interfaces/Cart/index.d.ts +478 -476
  53. package/dist/Interfaces/Cart/index.js +283 -283
  54. package/dist/Interfaces/Cart/index.js.map +1 -1
  55. package/dist/Interfaces/CartReservedQuantities/index.d.ts +10 -10
  56. package/dist/Interfaces/CartReservedQuantities/index.js +2 -2
  57. package/dist/Interfaces/CashDrawers/index.d.ts +38 -38
  58. package/dist/Interfaces/CashDrawers/index.js +19 -19
  59. package/dist/Interfaces/Catalogue/index.d.ts +68 -68
  60. package/dist/Interfaces/Catalogue/index.js +37 -37
  61. package/dist/Interfaces/Category/index.d.ts +33 -33
  62. package/dist/Interfaces/Category/index.js +2 -2
  63. package/dist/Interfaces/Chart/index.d.ts +11 -11
  64. package/dist/Interfaces/Chart/index.js +2 -2
  65. package/dist/Interfaces/Class/index.d.ts +8 -8
  66. package/dist/Interfaces/Class/index.js +2 -2
  67. package/dist/Interfaces/Consent/index.d.ts +6 -6
  68. package/dist/Interfaces/Consent/index.js +2 -2
  69. package/dist/Interfaces/Context/IContextProps.d.ts +4 -4
  70. package/dist/Interfaces/Context/IContextProps.js +2 -2
  71. package/dist/Interfaces/Context/IContextState.d.ts +15 -15
  72. package/dist/Interfaces/Context/IContextState.js +2 -2
  73. package/dist/Interfaces/Customer/ICustomerBadge.d.ts +2 -2
  74. package/dist/Interfaces/Customer/ICustomerBadge.js +2 -2
  75. package/dist/Interfaces/Customer/ICustomerRating.d.ts +10 -10
  76. package/dist/Interfaces/Customer/ICustomerRating.js +2 -2
  77. package/dist/Interfaces/Customer/IStoreCredit.d.ts +13 -13
  78. package/dist/Interfaces/Customer/IStoreCredit.js +2 -2
  79. package/dist/Interfaces/Customer/index.d.ts +104 -104
  80. package/dist/Interfaces/Customer/index.js +148 -148
  81. package/dist/Interfaces/Declination/index.d.ts +133 -117
  82. package/dist/Interfaces/Declination/index.js +83 -66
  83. package/dist/Interfaces/Declination/index.js.map +1 -1
  84. package/dist/Interfaces/Document/index.d.ts +8 -8
  85. package/dist/Interfaces/Document/index.js +2 -2
  86. package/dist/Interfaces/Elastic/index.d.ts +89 -89
  87. package/dist/Interfaces/Elastic/index.js +2 -2
  88. package/dist/Interfaces/Email/CustomGR/I3DPrintEmail.d.ts +11 -11
  89. package/dist/Interfaces/Email/CustomGR/I3DPrintEmail.js +2 -2
  90. package/dist/Interfaces/Email/CustomGR/IBorrowToolsEmail.d.ts +15 -15
  91. package/dist/Interfaces/Email/CustomGR/IBorrowToolsEmail.js +2 -2
  92. package/dist/Interfaces/Email/CustomGR/IPickupMaterialsEmail.d.ts +12 -12
  93. package/dist/Interfaces/Email/CustomGR/IPickupMaterialsEmail.js +2 -2
  94. package/dist/Interfaces/Email/CustomGR/IPreMeetingFormEmail.d.ts +36 -36
  95. package/dist/Interfaces/Email/CustomGR/IPreMeetingFormEmail.js +2 -2
  96. package/dist/Interfaces/Email/CustomGR/ISponsorRequestEmail.d.ts +12 -12
  97. package/dist/Interfaces/Email/CustomGR/ISponsorRequestEmail.js +2 -2
  98. package/dist/Interfaces/Email/CustomGR/ITransportEmail.d.ts +12 -12
  99. package/dist/Interfaces/Email/CustomGR/ITransportEmail.js +2 -2
  100. package/dist/Interfaces/Email/CustomGR/ITransportQuoteEmail.d.ts +12 -12
  101. package/dist/Interfaces/Email/CustomGR/ITransportQuoteEmail.js +2 -2
  102. package/dist/Interfaces/Email/CustomGR/IVegetalsEmail.d.ts +16 -16
  103. package/dist/Interfaces/Email/CustomGR/IVegetalsEmail.js +2 -2
  104. package/dist/Interfaces/Email/CustomGR/IWishlistEmail.d.ts +15 -15
  105. package/dist/Interfaces/Email/CustomGR/IWishlistEmail.js +2 -2
  106. package/dist/Interfaces/Email/IAbandonnedCartEmail.d.ts +29 -29
  107. package/dist/Interfaces/Email/IAbandonnedCartEmail.js +2 -2
  108. package/dist/Interfaces/Email/IAccountConfirmationEmail.d.ts +22 -22
  109. package/dist/Interfaces/Email/IAccountConfirmationEmail.js +2 -2
  110. package/dist/Interfaces/Email/IApplicationEmail.d.ts +19 -19
  111. package/dist/Interfaces/Email/IApplicationEmail.js +2 -2
  112. package/dist/Interfaces/Email/IBackInStockEmail.d.ts +21 -21
  113. package/dist/Interfaces/Email/IBackInStockEmail.js +2 -2
  114. package/dist/Interfaces/Email/IContactEmail.d.ts +20 -20
  115. package/dist/Interfaces/Email/IContactEmail.js +2 -2
  116. package/dist/Interfaces/Email/ICustomerBookingAdminEmail.d.ts +15 -15
  117. package/dist/Interfaces/Email/ICustomerBookingAdminEmail.js +2 -2
  118. package/dist/Interfaces/Email/ICustomerBookingEmail.d.ts +14 -14
  119. package/dist/Interfaces/Email/ICustomerBookingEmail.js +2 -2
  120. package/dist/Interfaces/Email/IEmail.d.ts +20 -20
  121. package/dist/Interfaces/Email/IEmail.js +46 -46
  122. package/dist/Interfaces/Email/IOrderConfirmationEmail.d.ts +47 -47
  123. package/dist/Interfaces/Email/IOrderConfirmationEmail.js +2 -2
  124. package/dist/Interfaces/Email/IPasswordResetEmail.d.ts +17 -17
  125. package/dist/Interfaces/Email/IPasswordResetEmail.js +2 -2
  126. package/dist/Interfaces/Email/IPhotoShootEmail.d.ts +14 -14
  127. package/dist/Interfaces/Email/IPhotoShootEmail.js +2 -2
  128. package/dist/Interfaces/Email/IPickupConfirmation.d.ts +23 -23
  129. package/dist/Interfaces/Email/IPickupConfirmation.js +2 -2
  130. package/dist/Interfaces/Email/IShippingConfirmation.d.ts +23 -23
  131. package/dist/Interfaces/Email/IShippingConfirmation.js +2 -2
  132. package/dist/Interfaces/Email/IWelcomeEmail.d.ts +19 -19
  133. package/dist/Interfaces/Email/IWelcomeEmail.js +2 -2
  134. package/dist/Interfaces/ExportSchema/index.d.ts +7 -7
  135. package/dist/Interfaces/ExportSchema/index.js +2 -2
  136. package/dist/Interfaces/ExternalService/BaseExternalService.d.ts +12 -12
  137. package/dist/Interfaces/ExternalService/BaseExternalService.js +2 -2
  138. package/dist/Interfaces/ExternalService/ExternalProductsService.d.ts +4 -4
  139. package/dist/Interfaces/ExternalService/ExternalProductsService.js +2 -2
  140. package/dist/Interfaces/ExternalService/index.d.ts +9 -9
  141. package/dist/Interfaces/ExternalService/index.js +2 -2
  142. package/dist/Interfaces/FirstOrderTracking/index.d.ts +5 -5
  143. package/dist/Interfaces/FirstOrderTracking/index.js +2 -2
  144. package/dist/Interfaces/G2/index.d.ts +557 -557
  145. package/dist/Interfaces/G2/index.js +39 -39
  146. package/dist/Interfaces/Indexed/Product/IIndexedLastSavedProduct.d.ts +20 -20
  147. package/dist/Interfaces/Indexed/Product/IIndexedLastSavedProduct.js +2 -2
  148. package/dist/Interfaces/Indexed/Product/index.d.ts +126 -111
  149. package/dist/Interfaces/Indexed/Product/index.js +372 -302
  150. package/dist/Interfaces/Indexed/Product/index.js.map +1 -1
  151. package/dist/Interfaces/Inventory/index.d.ts +19 -19
  152. package/dist/Interfaces/Inventory/index.js +8 -8
  153. package/dist/Interfaces/Invoice/index.d.ts +4 -4
  154. package/dist/Interfaces/Invoice/index.js +2 -2
  155. package/dist/Interfaces/MarketplacePublication/MarketplaceOrderData.d.ts +3 -3
  156. package/dist/Interfaces/MarketplacePublication/MarketplaceOrderData.js +2 -2
  157. package/dist/Interfaces/MarketplacePublication/index.d.ts +23 -23
  158. package/dist/Interfaces/MarketplacePublication/index.js +22 -22
  159. package/dist/Interfaces/Menu/index.d.ts +40 -40
  160. package/dist/Interfaces/Menu/index.js +16 -16
  161. package/dist/Interfaces/Note/index.d.ts +10 -10
  162. package/dist/Interfaces/Note/index.js +7 -7
  163. package/dist/Interfaces/Operations/ICreatedBy.d.ts +6 -6
  164. package/dist/Interfaces/Operations/ICreatedBy.js +2 -2
  165. package/dist/Interfaces/Operations/IUpdate.d.ts +5 -5
  166. package/dist/Interfaces/Operations/IUpdate.js +2 -2
  167. package/dist/Interfaces/Order/index.d.ts +4 -4
  168. package/dist/Interfaces/Order/index.js +2 -2
  169. package/dist/Interfaces/Org/IRelUser.d.ts +9 -9
  170. package/dist/Interfaces/Org/IRelUser.js +2 -2
  171. package/dist/Interfaces/Org/index.d.ts +29 -29
  172. package/dist/Interfaces/Org/index.js +12 -12
  173. package/dist/Interfaces/Payment/index.d.ts +26 -26
  174. package/dist/Interfaces/Payment/index.js +14 -14
  175. package/dist/Interfaces/Product/IAttributeFamily.d.ts +6 -6
  176. package/dist/Interfaces/Product/IAttributeFamily.js +2 -2
  177. package/dist/Interfaces/Product/IImportProduct.d.ts +42 -42
  178. package/dist/Interfaces/Product/IImportProduct.js +882 -882
  179. package/dist/Interfaces/Product/IInventoryItem.d.ts +74 -74
  180. package/dist/Interfaces/Product/IInventoryItem.js +38 -38
  181. package/dist/Interfaces/Product/IPricing.d.ts +177 -177
  182. package/dist/Interfaces/Product/IPricing.js +180 -180
  183. package/dist/Interfaces/Product/index.d.ts +137 -137
  184. package/dist/Interfaces/Product/index.js +64 -64
  185. package/dist/Interfaces/ProductAttribute/index.d.ts +11 -11
  186. package/dist/Interfaces/ProductAttribute/index.js +2 -2
  187. package/dist/Interfaces/PromiseToPurchase/BankType.d.ts +41 -41
  188. package/dist/Interfaces/PromiseToPurchase/BankType.js +41 -41
  189. package/dist/Interfaces/PromiseToPurchase/IIndexedBankUsed.d.ts +33 -33
  190. package/dist/Interfaces/PromiseToPurchase/IIndexedBankUsed.js +15 -15
  191. package/dist/Interfaces/PromiseToPurchase/IIndexedCustomerPromiseToPurchase.d.ts +19 -19
  192. package/dist/Interfaces/PromiseToPurchase/IIndexedCustomerPromiseToPurchase.js +2 -2
  193. package/dist/Interfaces/PromiseToPurchase/index.d.ts +50 -50
  194. package/dist/Interfaces/PromiseToPurchase/index.js +13 -13
  195. package/dist/Interfaces/PurchaseOrder/index.d.ts +17 -17
  196. package/dist/Interfaces/PurchaseOrder/index.js +2 -2
  197. package/dist/Interfaces/Query/IBrandQueryOptions.d.ts +11 -11
  198. package/dist/Interfaces/Query/IBrandQueryOptions.js +2 -2
  199. package/dist/Interfaces/Query/ICategoryQueryOptions.d.ts +11 -11
  200. package/dist/Interfaces/Query/ICategoryQueryOptions.js +2 -2
  201. package/dist/Interfaces/Query/IProductQueryOptions.d.ts +16 -16
  202. package/dist/Interfaces/Query/IProductQueryOptions.js +2 -2
  203. package/dist/Interfaces/Quote/index.d.ts +5 -5
  204. package/dist/Interfaces/Quote/index.js +2 -2
  205. package/dist/Interfaces/Refunds/index.d.ts +106 -106
  206. package/dist/Interfaces/Refunds/index.js +2 -2
  207. package/dist/Interfaces/Rules/IDiscountRule.d.ts +156 -156
  208. package/dist/Interfaces/Rules/IDiscountRule.js +114 -114
  209. package/dist/Interfaces/Schedule/index.d.ts +48 -48
  210. package/dist/Interfaces/Schedule/index.js +2 -2
  211. package/dist/Interfaces/Services/IAddServiceResponse.d.ts +4 -4
  212. package/dist/Interfaces/Services/IAddServiceResponse.js +2 -2
  213. package/dist/Interfaces/Services/IService.d.ts +16 -16
  214. package/dist/Interfaces/Services/IService.js +2 -2
  215. package/dist/Interfaces/Services/IServiceSecret.d.ts +8 -8
  216. package/dist/Interfaces/Services/IServiceSecret.js +2 -2
  217. package/dist/Interfaces/Shipping/Shipstation/carriers.d.ts +10 -10
  218. package/dist/Interfaces/Shipping/Shipstation/carriers.js +2 -2
  219. package/dist/Interfaces/Shipping/Shipstation/order.d.ts +227 -227
  220. package/dist/Interfaces/Shipping/Shipstation/order.js +2 -2
  221. package/dist/Interfaces/Shipping/Shipstation/quote.d.ts +31 -31
  222. package/dist/Interfaces/Shipping/Shipstation/quote.js +2 -2
  223. package/dist/Interfaces/Shipping/Shiptime/order.d.ts +54 -54
  224. package/dist/Interfaces/Shipping/Shiptime/order.js +71 -71
  225. package/dist/Interfaces/Shipping/Shiptime/quote.d.ts +111 -111
  226. package/dist/Interfaces/Shipping/Shiptime/quote.js +2 -2
  227. package/dist/Interfaces/Slider/GR.d.ts +114 -114
  228. package/dist/Interfaces/Slider/GR.js +271 -271
  229. package/dist/Interfaces/Slider/index.d.ts +30 -30
  230. package/dist/Interfaces/Slider/index.js +2 -2
  231. package/dist/Interfaces/Space/IExternalService.d.ts +54 -54
  232. package/dist/Interfaces/Space/IExternalService.js +45 -45
  233. package/dist/Interfaces/Space/IMember.d.ts +16 -16
  234. package/dist/Interfaces/Space/IMember.js +9 -9
  235. package/dist/Interfaces/Space/index.d.ts +414 -414
  236. package/dist/Interfaces/Space/index.js +176 -176
  237. package/dist/Interfaces/Specials/gr.d.ts +61 -61
  238. package/dist/Interfaces/Specials/gr.js +2 -2
  239. package/dist/Interfaces/StockNotification/index.d.ts +7 -7
  240. package/dist/Interfaces/StockNotification/index.js +2 -2
  241. package/dist/Interfaces/Store/index.d.ts +63 -63
  242. package/dist/Interfaces/Store/index.js +27 -27
  243. package/dist/Interfaces/Supplier/ICommand.d.ts +11 -11
  244. package/dist/Interfaces/Supplier/ICommand.js +2 -2
  245. package/dist/Interfaces/Supplier/index.d.ts +36 -36
  246. package/dist/Interfaces/Supplier/index.js +24 -24
  247. package/dist/Interfaces/TCG/index.d.ts +200 -200
  248. package/dist/Interfaces/TCG/index.js +59 -59
  249. package/dist/Interfaces/Tag/index.d.ts +18 -18
  250. package/dist/Interfaces/Tag/index.js +2 -2
  251. package/dist/Interfaces/Tax/index.d.ts +13 -13
  252. package/dist/Interfaces/Tax/index.js +2 -2
  253. package/dist/Interfaces/TransferRequest/index.d.ts +103 -103
  254. package/dist/Interfaces/TransferRequest/index.js +46 -46
  255. package/dist/Interfaces/Translation/index.d.ts +8 -8
  256. package/dist/Interfaces/Translation/index.js +5 -5
  257. package/dist/Interfaces/Update/index.d.ts +10 -10
  258. package/dist/Interfaces/Update/index.js +2 -2
  259. package/dist/Interfaces/User/IUser.d.ts +65 -65
  260. package/dist/Interfaces/User/IUser.js +8 -8
  261. package/dist/Interfaces/Version/index.d.ts +11 -11
  262. package/dist/Interfaces/Version/index.js +2 -2
  263. package/dist/Interfaces/Wishlist/index.d.ts +7 -7
  264. package/dist/Interfaces/Wishlist/index.js +2 -2
  265. package/dist/constants/Interfaces/IBaseApi.d.ts +15 -15
  266. package/dist/constants/Interfaces/IBaseApi.js +2 -2
  267. package/dist/constants/Interfaces/IEndpointResult.d.ts +9 -9
  268. package/dist/constants/Interfaces/IEndpointResult.js +2 -2
  269. package/dist/constants/enums.d.ts +6 -6
  270. package/dist/constants/enums.js +10 -10
  271. package/dist/constants/services.d.ts +2 -2
  272. package/dist/constants/services.js +122 -122
  273. package/dist/constants/version.d.ts +2 -2
  274. package/dist/constants/version.js +5 -5
  275. package/dist/index.d.ts +50 -50
  276. package/dist/index.js +266 -266
  277. package/dist/lib/Attribute/index.d.ts +14 -14
  278. package/dist/lib/Attribute/index.js +186 -186
  279. package/dist/lib/BGJob/index.d.ts +9 -9
  280. package/dist/lib/BGJob/index.js +216 -216
  281. package/dist/lib/BackgroundWorker/index.d.ts +34 -34
  282. package/dist/lib/BackgroundWorker/index.js +59 -59
  283. package/dist/lib/Blog/BlogArticle.d.ts +5 -5
  284. package/dist/lib/Blog/BlogArticle.js +10 -10
  285. package/dist/lib/Blog/BlogAuthor.d.ts +5 -5
  286. package/dist/lib/Blog/BlogAuthor.js +10 -10
  287. package/dist/lib/Blog/BlogCategory.d.ts +5 -5
  288. package/dist/lib/Blog/BlogCategory.js +10 -10
  289. package/dist/lib/Blog/BlogKeyword.d.ts +5 -5
  290. package/dist/lib/Blog/BlogKeyword.js +10 -10
  291. package/dist/lib/Booking/index.d.ts +85 -85
  292. package/dist/lib/Booking/index.js +596 -596
  293. package/dist/lib/Brand/index.d.ts +26 -26
  294. package/dist/lib/Brand/index.js +131 -131
  295. package/dist/lib/Cart/index.d.ts +357 -357
  296. package/dist/lib/Cart/index.js +4052 -4052
  297. package/dist/lib/CartReservedQuantities/index.d.ts +49 -49
  298. package/dist/lib/CartReservedQuantities/index.js +159 -159
  299. package/dist/lib/CashDrawerShift/index.d.ts +84 -84
  300. package/dist/lib/CashDrawerShift/index.js +206 -206
  301. package/dist/lib/Catalogue/index.d.ts +15 -15
  302. package/dist/lib/Catalogue/index.js +78 -78
  303. package/dist/lib/Category/index.d.ts +34 -34
  304. package/dist/lib/Category/index.js +230 -230
  305. package/dist/lib/Class/index.d.ts +16 -16
  306. package/dist/lib/Class/index.js +66 -66
  307. package/dist/lib/Consent/index.d.ts +4 -4
  308. package/dist/lib/Consent/index.js +29 -29
  309. package/dist/lib/Customer/index.d.ts +30 -30
  310. package/dist/lib/Customer/index.js +92 -92
  311. package/dist/lib/Declination/index.d.ts +9 -9
  312. package/dist/lib/Declination/index.js +26 -26
  313. package/dist/lib/Discount/index.d.ts +27 -27
  314. package/dist/lib/Discount/index.js +493 -493
  315. package/dist/lib/ElasticSearch/index.d.ts +13 -13
  316. package/dist/lib/ElasticSearch/index.js +50 -50
  317. package/dist/lib/Elavon/index.d.ts +18 -18
  318. package/dist/lib/Elavon/index.js +135 -135
  319. package/dist/lib/Email/AbandonedCartEmail.d.ts +16 -16
  320. package/dist/lib/Email/AbandonedCartEmail.js +24 -24
  321. package/dist/lib/Email/AccountConfirmationEmail.d.ts +19 -19
  322. package/dist/lib/Email/AccountConfirmationEmail.js +30 -30
  323. package/dist/lib/Email/AdminOrderConfirmationEmail.d.ts +16 -16
  324. package/dist/lib/Email/AdminOrderConfirmationEmail.js +24 -24
  325. package/dist/lib/Email/ApplicationEmail.d.ts +16 -16
  326. package/dist/lib/Email/ApplicationEmail.js +24 -24
  327. package/dist/lib/Email/BackInStockEmail.d.ts +16 -16
  328. package/dist/lib/Email/BackInStockEmail.js +24 -24
  329. package/dist/lib/Email/ContactEmail.d.ts +16 -16
  330. package/dist/lib/Email/ContactEmail.js +24 -24
  331. package/dist/lib/Email/CustomerBookingAdminEmail.d.ts +16 -16
  332. package/dist/lib/Email/CustomerBookingAdminEmail.js +24 -24
  333. package/dist/lib/Email/CustomerBookingEmail.d.ts +16 -16
  334. package/dist/lib/Email/CustomerBookingEmail.js +24 -24
  335. package/dist/lib/Email/OrderConfirmationEmail.d.ts +16 -16
  336. package/dist/lib/Email/OrderConfirmationEmail.js +24 -24
  337. package/dist/lib/Email/OrderDenounciationEmail.d.ts +16 -16
  338. package/dist/lib/Email/OrderDenounciationEmail.js +24 -24
  339. package/dist/lib/Email/OrderSampleEmail.d.ts +16 -16
  340. package/dist/lib/Email/OrderSampleEmail.js +24 -24
  341. package/dist/lib/Email/OtherTypeEmails.d.ts +16 -16
  342. package/dist/lib/Email/OtherTypeEmails.js +27 -27
  343. package/dist/lib/Email/PasswordResetEmail.d.ts +16 -16
  344. package/dist/lib/Email/PasswordResetEmail.js +24 -24
  345. package/dist/lib/Email/PhotoShootEmail.d.ts +16 -16
  346. package/dist/lib/Email/PhotoShootEmail.js +24 -24
  347. package/dist/lib/Email/PickUpConfirmation.d.ts +16 -16
  348. package/dist/lib/Email/PickUpConfirmation.js +24 -24
  349. package/dist/lib/Email/ShippingConfirmation.d.ts +16 -16
  350. package/dist/lib/Email/ShippingConfirmation.js +24 -24
  351. package/dist/lib/Email/WelcomeEmail.d.ts +16 -16
  352. package/dist/lib/Email/WelcomeEmail.js +24 -24
  353. package/dist/lib/Email/index.d.ts +16 -16
  354. package/dist/lib/Email/index.js +31 -31
  355. package/dist/lib/ExternalService/Ebay.d.ts +74 -74
  356. package/dist/lib/ExternalService/Ebay.js +124 -124
  357. package/dist/lib/ExternalService/index.d.ts +5 -5
  358. package/dist/lib/ExternalService/index.js +10 -10
  359. package/dist/lib/FirstOrderTracking/index.d.ts +5 -5
  360. package/dist/lib/FirstOrderTracking/index.js +10 -10
  361. package/dist/lib/Indexed/IndexedCart.d.ts +13 -13
  362. package/dist/lib/Indexed/IndexedCart.js +91 -91
  363. package/dist/lib/Indexed/Product.d.ts +17 -17
  364. package/dist/lib/Indexed/Product.js +98 -98
  365. package/dist/lib/Inventory/index.d.ts +131 -131
  366. package/dist/lib/Inventory/index.js +545 -545
  367. package/dist/lib/Invoice/index.d.ts +16 -16
  368. package/dist/lib/Invoice/index.js +21 -21
  369. package/dist/lib/MarketplacePublication/index.d.ts +9 -9
  370. package/dist/lib/MarketplacePublication/index.js +426 -426
  371. package/dist/lib/Menu/index.d.ts +11 -11
  372. package/dist/lib/Menu/index.js +107 -107
  373. package/dist/lib/MongoDB/BaseAPI.d.ts +18 -18
  374. package/dist/lib/MongoDB/BaseAPI.js +200 -200
  375. package/dist/lib/Note/index.d.ts +4 -4
  376. package/dist/lib/Note/index.js +6 -6
  377. package/dist/lib/Order/index.d.ts +27 -27
  378. package/dist/lib/Order/index.js +56 -56
  379. package/dist/lib/Org/index.d.ts +68 -68
  380. package/dist/lib/Org/index.js +216 -216
  381. package/dist/lib/PandaPay/index.d.ts +16 -16
  382. package/dist/lib/PandaPay/index.js +176 -176
  383. package/dist/lib/Paysafe/index.d.ts +11 -11
  384. package/dist/lib/Paysafe/index.js +41 -41
  385. package/dist/lib/Product/index.d.ts +182 -182
  386. package/dist/lib/Product/index.js +847 -847
  387. package/dist/lib/ProductAttribute/index.d.ts +15 -15
  388. package/dist/lib/ProductAttribute/index.js +45 -45
  389. package/dist/lib/PromiseToPurchase/index.d.ts +109 -109
  390. package/dist/lib/PromiseToPurchase/index.js +343 -343
  391. package/dist/lib/PurchaseOrder/index.d.ts +20 -20
  392. package/dist/lib/PurchaseOrder/index.js +28 -28
  393. package/dist/lib/Schedule/index.d.ts +5 -5
  394. package/dist/lib/Schedule/index.js +12 -12
  395. package/dist/lib/Service/Enum/ServiceEnum.d.ts +3 -3
  396. package/dist/lib/Service/Enum/ServiceEnum.js +7 -7
  397. package/dist/lib/Service/index.d.ts +13 -13
  398. package/dist/lib/Service/index.js +21 -21
  399. package/dist/lib/Shipment/index.d.ts +28 -28
  400. package/dist/lib/Shipment/index.js +370 -370
  401. package/dist/lib/Slider/index.d.ts +22 -22
  402. package/dist/lib/Slider/index.js +119 -119
  403. package/dist/lib/Space/index.d.ts +1181 -1181
  404. package/dist/lib/Space/index.js +5860 -5856
  405. package/dist/lib/Space/index.js.map +1 -1
  406. package/dist/lib/StockNotification/index.d.ts +4 -4
  407. package/dist/lib/StockNotification/index.js +6 -6
  408. package/dist/lib/Store/index.d.ts +5 -5
  409. package/dist/lib/Store/index.js +12 -12
  410. package/dist/lib/Supplier/Command.d.ts +5 -5
  411. package/dist/lib/Supplier/Command.js +10 -10
  412. package/dist/lib/Supplier/index.d.ts +25 -25
  413. package/dist/lib/Supplier/index.js +27 -27
  414. package/dist/lib/Tags/index.d.ts +6 -6
  415. package/dist/lib/Tags/index.js +26 -26
  416. package/dist/lib/Tax/index.d.ts +8 -8
  417. package/dist/lib/Tax/index.js +54 -54
  418. package/dist/lib/TransferRequest/index.d.ts +298 -298
  419. package/dist/lib/TransferRequest/index.js +1106 -1106
  420. package/dist/lib/Update/index.d.ts +10 -10
  421. package/dist/lib/Update/index.js +22 -22
  422. package/dist/lib/User/index.d.ts +89 -89
  423. package/dist/lib/User/index.js +328 -328
  424. package/dist/lib/Wishlist/index.d.ts +5 -5
  425. package/dist/lib/Wishlist/index.js +10 -10
  426. package/dist/lib/base.d.ts +14 -14
  427. package/dist/lib/base.js +62 -62
  428. package/dist/lib/baseService.d.ts +17 -17
  429. package/dist/lib/baseService.js +69 -69
  430. package/dist/rules/ADD/utils/buyback.d.ts +4 -4
  431. package/dist/rules/ADD/utils/buyback.js +135 -135
  432. package/dist/rules/GR/constants/data.d.ts +26 -26
  433. package/dist/rules/GR/constants/data.js +81 -81
  434. package/dist/rules/GR/constants/expedition.d.ts +4 -4
  435. package/dist/rules/GR/constants/expedition.js +9 -9
  436. package/dist/rules/GR/constants/products.d.ts +27 -22
  437. package/dist/rules/GR/constants/products.js +272 -263
  438. package/dist/rules/GR/constants/products.js.map +1 -1
  439. package/dist/rules/GR/interfaces/cart.d.ts +85 -84
  440. package/dist/rules/GR/interfaces/cart.js +42 -41
  441. package/dist/rules/GR/interfaces/cart.js.map +1 -1
  442. package/dist/rules/GR/interfaces/data.d.ts +101 -101
  443. package/dist/rules/GR/interfaces/data.js +114 -114
  444. package/dist/rules/GR/interfaces/products.d.ts +61 -61
  445. package/dist/rules/GR/interfaces/products.js +10 -10
  446. package/dist/rules/GR/utils/cart.d.ts +95 -95
  447. package/dist/rules/GR/utils/cart.js +879 -839
  448. package/dist/rules/GR/utils/cart.js.map +1 -1
  449. package/dist/rules/GR/utils/data.d.ts +3 -3
  450. package/dist/rules/GR/utils/data.js +28 -28
  451. package/dist/rules/GR/utils/expedition.d.ts +140 -140
  452. package/dist/rules/GR/utils/expedition.js +2098 -2017
  453. package/dist/rules/GR/utils/expedition.js.map +1 -1
  454. package/dist/rules/GR/utils/g2.d.ts +209 -209
  455. package/dist/rules/GR/utils/g2.js +1002 -1002
  456. package/dist/rules/GR/utils/invoices.d.ts +51 -51
  457. package/dist/rules/GR/utils/invoices.js +218 -215
  458. package/dist/rules/GR/utils/invoices.js.map +1 -1
  459. package/dist/rules/GR/utils/products.d.ts +277 -277
  460. package/dist/rules/GR/utils/products.js +1358 -1350
  461. package/dist/rules/GR/utils/products.js.map +1 -1
  462. package/dist/rules/GR/utils/upsells.d.ts +113 -111
  463. package/dist/rules/GR/utils/upsells.js +215 -215
  464. package/dist/services/database/BaseProvider.d.ts +29 -29
  465. package/dist/services/database/BaseProvider.js +28 -28
  466. package/dist/services/database/BatchUtils.d.ts +14 -14
  467. package/dist/services/database/BatchUtils.js +43 -43
  468. package/dist/services/database/Config.d.ts +2 -2
  469. package/dist/services/database/Config.js +5 -5
  470. package/dist/services/database/DatabaseService.d.ts +125 -125
  471. package/dist/services/database/DatabaseService.js +237 -237
  472. package/dist/services/database/FirebaseProvider.d.ts +17 -17
  473. package/dist/services/database/FirebaseProvider.js +235 -235
  474. package/dist/services/database/NotFirebaseProvider.d.ts +49 -49
  475. package/dist/services/database/NotFirebaseProvider.js +262 -262
  476. package/dist/services/g2/G2OrderSlip.d.ts +49 -49
  477. package/dist/services/g2/G2OrderSlip.js +228 -228
  478. package/dist/services/g2/utils.d.ts +19 -19
  479. package/dist/services/g2/utils.js +969 -968
  480. package/dist/services/g2/utils.js.map +1 -1
  481. package/dist/services/logs/index.d.ts +23 -23
  482. package/dist/services/logs/index.js +66 -66
  483. package/dist/services/marketplace/BaseMarketServiceClass.d.ts +78 -78
  484. package/dist/services/marketplace/BaseMarketServiceClass.js +141 -141
  485. package/dist/services/marketplace/CardtraderServiceClass.d.ts +38 -38
  486. package/dist/services/marketplace/CardtraderServiceClass.js +226 -226
  487. package/dist/services/marketplace/utils.d.ts +17 -17
  488. package/dist/services/marketplace/utils.js +32 -32
  489. package/dist/services/products/BaseClass.d.ts +79 -79
  490. package/dist/services/products/BaseClass.js +144 -144
  491. package/dist/services/products/TCGService.d.ts +29 -29
  492. package/dist/services/products/TCGService.js +503 -503
  493. package/dist/services/products/utils.d.ts +31 -31
  494. package/dist/services/products/utils.js +144 -144
  495. package/dist/utils/algolia.d.ts +46 -46
  496. package/dist/utils/algolia.js +21 -21
  497. package/dist/utils/anonymisation.d.ts +54 -54
  498. package/dist/utils/anonymisation.js +280 -280
  499. package/dist/utils/array.d.ts +5 -5
  500. package/dist/utils/array.js +14 -14
  501. package/dist/utils/aws.d.ts +36 -36
  502. package/dist/utils/aws.js +154 -154
  503. package/dist/utils/booking.d.ts +30 -30
  504. package/dist/utils/booking.js +127 -127
  505. package/dist/utils/cart.d.ts +279 -274
  506. package/dist/utils/cart.js +1152 -1143
  507. package/dist/utils/cart.js.map +1 -1
  508. package/dist/utils/categories.d.ts +2 -2
  509. package/dist/utils/categories.js +54 -54
  510. package/dist/utils/cmv.d.ts +12 -12
  511. package/dist/utils/cmv.js +108 -108
  512. package/dist/utils/console.d.ts +6 -6
  513. package/dist/utils/console.js +59 -59
  514. package/dist/utils/context.d.ts +20 -20
  515. package/dist/utils/context.js +61 -61
  516. package/dist/utils/currency.d.ts +6 -6
  517. package/dist/utils/currency.js +91 -91
  518. package/dist/utils/data.d.ts +31 -31
  519. package/dist/utils/data.js +302 -302
  520. package/dist/utils/date.d.ts +1 -1
  521. package/dist/utils/date.js +16 -16
  522. package/dist/utils/dimensions.d.ts +3 -3
  523. package/dist/utils/dimensions.js +16 -16
  524. package/dist/utils/discount.d.ts +192 -192
  525. package/dist/utils/discount.js +1180 -1180
  526. package/dist/utils/errors.d.ts +133 -133
  527. package/dist/utils/errors.js +171 -171
  528. package/dist/utils/file-admin.d.ts +8 -8
  529. package/dist/utils/file-admin.js +39 -39
  530. package/dist/utils/file.d.ts +39 -39
  531. package/dist/utils/file.js +208 -208
  532. package/dist/utils/firebase-admin.d.ts +11 -11
  533. package/dist/utils/firebase-admin.js +73 -73
  534. package/dist/utils/firebase.d.ts +58 -58
  535. package/dist/utils/firebase.js +148 -148
  536. package/dist/utils/import.d.ts +1 -1
  537. package/dist/utils/import.js +21 -21
  538. package/dist/utils/inventories.d.ts +101 -101
  539. package/dist/utils/inventories.js +467 -467
  540. package/dist/utils/locale.d.ts +24 -24
  541. package/dist/utils/locale.js +91 -91
  542. package/dist/utils/mailchimp.d.ts +58 -58
  543. package/dist/utils/mailchimp.js +531 -531
  544. package/dist/utils/mathUtils.d.ts +17 -17
  545. package/dist/utils/mathUtils.js +324 -324
  546. package/dist/utils/mongodb.d.ts +1 -1
  547. package/dist/utils/mongodb.js +22 -22
  548. package/dist/utils/object.d.ts +32 -32
  549. package/dist/utils/object.js +133 -133
  550. package/dist/utils/payment.d.ts +10 -10
  551. package/dist/utils/payment.js +23 -23
  552. package/dist/utils/products.d.ts +47 -47
  553. package/dist/utils/products.js +214 -214
  554. package/dist/utils/promiseToPurchase.d.ts +121 -121
  555. package/dist/utils/promiseToPurchase.js +329 -329
  556. package/dist/utils/prosprsearch.d.ts +42 -42
  557. package/dist/utils/prosprsearch.js +216 -216
  558. package/dist/utils/refunds.d.ts +2 -2
  559. package/dist/utils/refunds.js +21 -21
  560. package/dist/utils/sdc.d.ts +10 -10
  561. package/dist/utils/sdc.js +1309 -1309
  562. package/dist/utils/searchIndexes.d.ts +58 -58
  563. package/dist/utils/searchIndexes.js +247 -247
  564. package/dist/utils/services.d.ts +44 -44
  565. package/dist/utils/services.js +415 -415
  566. package/dist/utils/shipment.d.ts +110 -110
  567. package/dist/utils/shipment.js +341 -345
  568. package/dist/utils/shipment.js.map +1 -1
  569. package/dist/utils/simpletexting.d.ts +2 -2
  570. package/dist/utils/simpletexting.js +45 -45
  571. package/dist/utils/sliders.d.ts +4 -4
  572. package/dist/utils/sliders.js +24 -24
  573. package/dist/utils/string.d.ts +16 -16
  574. package/dist/utils/string.js +192 -192
  575. package/dist/utils/tcgService.d.ts +129 -129
  576. package/dist/utils/tcgService.js +494 -494
  577. package/dist/utils/tools.d.ts +5 -5
  578. package/dist/utils/tools.js +13 -13
  579. package/dist/utils/transferRequests.d.ts +43 -43
  580. package/dist/utils/transferRequests.js +67 -67
  581. package/dist/utils/update.d.ts +7 -7
  582. package/dist/utils/update.js +137 -137
  583. package/dist/utils/weight.d.ts +3 -3
  584. package/dist/utils/weight.js +16 -16
  585. package/dist/utils/zones.d.ts +11 -11
  586. package/dist/utils/zones.js +218 -218
  587. package/package.json +107 -107
  588. package/publish.sh +143 -143
  589. package/readme.md +182 -182
@@ -1,1107 +1,1107 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- var _a;
6
- Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.TransferRequest = void 0;
8
- const TransferRequest_1 = require("../../Interfaces/TransferRequest");
9
- // Classes
10
- const DatabaseService_1 = __importDefault(require("../../services/database/DatabaseService"));
11
- const baseService_1 = require("../baseService");
12
- const Inventory_1 = __importDefault(require("../Inventory"));
13
- const Space_1 = __importDefault(require("../Space"));
14
- // Utils
15
- const toNumber_1 = __importDefault(require("lodash/toNumber"));
16
- const ceil_1 = __importDefault(require("lodash/ceil"));
17
- const round_1 = __importDefault(require("lodash/round"));
18
- const data_1 = require("../../utils/data");
19
- const inventories_1 = require("../../utils/inventories");
20
- const transferRequests_1 = require("../../utils/transferRequests");
21
- const sumBy_1 = __importDefault(require("lodash/sumBy"));
22
- const weight_1 = require("../../utils/weight");
23
- const algolia_1 = require("../../utils/algolia");
24
- const __1 = require("../..");
25
- const console_1 = require("../../utils/console");
26
- const context_1 = require("../../utils/context");
27
- const tools_1 = require("../../utils/tools");
28
- const products_1 = require("../../rules/GR/utils/products");
29
- const Cart_1 = require("../../Interfaces/Cart");
30
- class TransferRequest extends baseService_1.BaseServiceClass {
31
- constructor(_data, _collection, _user) {
32
- super(_data, _collection, _user);
33
- this._listener = null;
34
- this.prevProducts = [];
35
- this.prevFromStore = undefined;
36
- this.processData = (data) => (Object.assign(Object.assign({}, data), { transfer_updates: data.transfer_updates.map((update) => (Object.assign(Object.assign({}, update), { date: (0, data_1.formatDate)(update.date) }))) }));
37
- this.getCollectionObj = (collPath) => {
38
- if (DatabaseService_1.default.getPathParent(this._collection.path) == '/')
39
- return;
40
- const coll = DatabaseService_1.default.asCollectionObject(DatabaseService_1.default.getPathParent(this._collection.path), collPath);
41
- return coll;
42
- };
43
- /**
44
- * Check if current space has option to update inventory on status changed to TO_BE_PREPARED
45
- * @param space Optionnal. IF not provided, will fetch space from DB
46
- */
47
- this._checkIfInventoryUpdatedOnStatusToBePrepared = async (space) => {
48
- if (!space)
49
- space = await Space_1.default.getCurrentSpaceWithRef(this._collection.path, this._user);
50
- return !!space.options.checkIfOptionIsSet('transfer_requests.ajust_inventory_on_to_be_prepared');
51
- };
52
- /**
53
- * Test if the transfer can be closed
54
- * @returns true if the status allow to close the transfer
55
- */
56
- this.checkIfTransferCanBeClosedManually = () => {
57
- return this._data.status == TransferRequest_1.TransferRequestStatusEnum.RECEIVED_PARTIAL;
58
- };
59
- this.transferAllowAssignFromStore = () => TransferRequest.transferAllowAssignFromStore(this._data);
60
- this.transferAllowEditFromStore = () => TransferRequest.transferAllowEditFromStore(this._data);
61
- this.transferAllowAddProductOnEdit = () => TransferRequest.transferAllowAddProductOnEdit(this._data);
62
- this.transferAllowProductDelete = () => TransferRequest.transferAllowProductDelete(this._data);
63
- this.transferAllowEditProductOnEdit = () => TransferRequest.transferAllowEditProductOnEdit(this._data);
64
- this.transferAllowDeleteProductOnEdit = () => TransferRequest.transferAllowProductDelete(this._data);
65
- this.transferShouldDisplayWeight = () => TransferRequest.transferShouldDisplayWeight(this._data);
66
- this.transferAllowsIndependantProductUpdate = (spaceOptions) => TransferRequest.transferAllowsIndependantProductUpdate(this._data, spaceOptions);
67
- this.fetchAssociatedCart = async () => {
68
- if (!!!this._data.associated_order)
69
- return;
70
- let associatedCart = undefined;
71
- try {
72
- const space = await Space_1.default.getCurrentSpaceWithRef(this._collection.path, this._user);
73
- const cartQuery = await space.carts.get({
74
- query: [{ field: 'ref', operator: '==', value: this._data.associated_order }]
75
- });
76
- if (!!cartQuery && !!cartQuery.length)
77
- associatedCart = cartQuery[0];
78
- }
79
- catch (e) {
80
- console.log('could not fetch cart associated to transfer: ', e.toString());
81
- }
82
- return associatedCart;
83
- };
84
- this.addProduct = (sku, parent_slug, qte, name, image, other_units, weight, count_in_pallet_total) => {
85
- const data = this.data();
86
- if (!TransferRequest.transferAllowEditProductOnEdit(this._data))
87
- return false;
88
- let updatedProducts = data.products;
89
- if (!updatedProducts.find((p) => p.sku == sku)) {
90
- updatedProducts.push({
91
- sku,
92
- parent_slug,
93
- qte,
94
- name,
95
- image,
96
- other_units,
97
- weight,
98
- count_in_pallet_total,
99
- qte_received: 0
100
- });
101
- }
102
- else {
103
- updatedProducts = updatedProducts.map((p) => {
104
- if (p.sku !== sku)
105
- return p;
106
- return Object.assign(Object.assign({}, p), { qte: p.qte + qte <= 1 ? 1 : p.qte + qte });
107
- });
108
- }
109
- this._data = Object.assign(Object.assign({}, data), { products: updatedProducts });
110
- return true;
111
- };
112
- this.editProduct = (sku, newQte) => {
113
- const data = this.data();
114
- if (!TransferRequest.transferAllowEditProductOnEdit(this._data))
115
- return false;
116
- this._data = Object.assign(Object.assign({}, data), { products: data.products.map((p) => {
117
- if (p.sku !== sku)
118
- return p;
119
- return Object.assign(Object.assign({}, p), { qte: newQte });
120
- }) });
121
- return true;
122
- };
123
- this.deleteProduct = (sku) => {
124
- const data = this.data();
125
- if (!TransferRequest.transferAllowProductDelete(this._data))
126
- return false;
127
- this._data = Object.assign(Object.assign({}, data), { products: data.products.filter((p) => p.sku !== sku) });
128
- return true;
129
- };
130
- this.data = () => this._data;
131
- this.isListening = () => !!this._listener;
132
- this.killListener = () => {
133
- if (!!!this._listener)
134
- return false;
135
- this._listener = null;
136
- return true;
137
- };
138
- this.listen = (callback) => {
139
- if (!!this._listener)
140
- return false;
141
- DatabaseService_1.default.registerListener((snap) => {
142
- if (snap === null)
143
- this._listener = null;
144
- if (snap.length === 0)
145
- this._listener = null;
146
- snap.map((s) => {
147
- if (s.id == this.data().id) {
148
- this._data = this.processData(s.data);
149
- if (!!callback)
150
- callback();
151
- }
152
- });
153
- }, this._collection.path, { id: this.data().id });
154
- return true;
155
- };
156
- this._getTransferRef = async () => {
157
- let newRef = undefined;
158
- try {
159
- const space = await Space_1.default.getCurrentSpaceWithRef(this._collection.path, this._user);
160
- const token = (0, context_1.getSpaceTokenFromSpaceOnly)(space);
161
- const api = __1.API_URL;
162
- let triesLeft = 3;
163
- while (triesLeft > 0) {
164
- try {
165
- const resp = await fetch(`${api}/transfers/refnumber`, {
166
- method: 'GET',
167
- headers: {
168
- 'Content-Type': 'application/json',
169
- Authorization: `Bearer ${token}`
170
- }
171
- });
172
- if (resp.status >= 200 && resp.status < 300) {
173
- const data = await resp.json();
174
- if (data.status == 'success') {
175
- newRef = (0, toNumber_1.default)(data.result);
176
- break;
177
- }
178
- }
179
- }
180
- catch (e) {
181
- console.log('Error fetching transfer number', e);
182
- }
183
- await (0, tools_1.waitFor)(1000); // wait a second before trying again, server needs to recover
184
- triesLeft--;
185
- }
186
- if (triesLeft == 0)
187
- throw new Error('could not get a Ref number');
188
- return newRef;
189
- }
190
- catch (e) {
191
- console.log('error on fetching new transfer ref: ', e.toString());
192
- return;
193
- }
194
- };
195
- this.save = async (partial, saveToDatabase = true, merge = true) => {
196
- const saveResult = await super.save(partial, undefined, saveToDatabase, undefined, merge);
197
- if (typeof saveResult === 'string') {
198
- this._data = Object.assign(Object.assign({}, this._data), { id: saveResult });
199
- }
200
- return saveResult;
201
- };
202
- /**
203
- * Validate the quantities set before submit
204
- * @param strictQty Tell if we should only allow equal quantity
205
- * @returns
206
- */
207
- this.validateBeforeSubmit = async (strictQty = true) => {
208
- if (strictQty) {
209
- return this.data().products.every((p) => typeof p.qte_validation == 'undefined' || p.qte === p.qte_validation);
210
- }
211
- return this.data().products.every((p) => typeof p.qte_validation == 'undefined' || p.qte_validation >= 0);
212
- };
213
- // --------------------------------------------------------------------
214
- // #region QUANTITIES AND INVENTORY MANAGEMENT
215
- /**
216
- * Strip out the validation qty field in products data
217
- * Do this before saving so the qte_validation doesnt get save in database
218
- * @param copyQte should copy validation qty to the actual qty
219
- */
220
- this.clearValidationQuantitiesFromProductData = (copyQte = false) => {
221
- this._data = Object.assign(Object.assign({}, this._data), { products: this._data.products.map((p) => (Object.assign(Object.assign({}, p), { qte: copyQte ? p.qte_validation || 0 : p.qte, qte_validation: undefined }))) });
222
- };
223
- /**
224
- * Add the validation quantities to the received amount
225
- */
226
- this.addValidationQuantitiesToReceivedQuantities = () => {
227
- this._data = Object.assign(Object.assign({}, this._data), { products: this._data.products.map((p) => (Object.assign(Object.assign({}, p), { qte_received: (p.qte_validation || 0) + (p.qte_received || 0), qte_validation: undefined }))) });
228
- };
229
- /**
230
- * Return the previous quantity received for the provided sku
231
- * @param sku the product sku to get
232
- * @returns
233
- */
234
- this.getPreviousReceivedQuantity = (sku) => {
235
- const entry = this._data.transfer_updates.find((u) => (u.status == TransferRequest_1.TransferRequestStatusEnum.RECEIVED_PARTIAL || u.status == TransferRequest_1.TransferRequestStatusEnum.RECEIVED) &&
236
- u.products &&
237
- u.products[sku]);
238
- if (entry) {
239
- // if we got an entry then the sku exists inside
240
- return entry.products[sku].qte_after;
241
- }
242
- return 0;
243
- };
244
- /**
245
- * Return the original reuested quantity
246
- * @param sku the product sku to get
247
- * @returns
248
- */
249
- this.getOriginalRequestedQuantity = (sku) => {
250
- const product = this._data.products.find((p) => p.sku == sku);
251
- if (!product)
252
- return 0;
253
- let result = product.qte;
254
- this._data.transfer_updates.map((u) => {
255
- if (u.status != TransferRequest_1.TransferRequestStatusEnum.RECEIVED_PARTIAL &&
256
- u.status != TransferRequest_1.TransferRequestStatusEnum.RECEIVED &&
257
- u.products &&
258
- u.products[sku])
259
- result = u.products[sku].qte_before;
260
- });
261
- return result;
262
- };
263
- /**
264
- * Get the quantity at the requested status
265
- * @param sku the product sku
266
- * @param status the status to look for
267
- * @returns the quantity at the specified status
268
- */
269
- this.getQuantityAtStatus = (sku, status) => {
270
- const statusPos = (0, transferRequests_1.getOrderPositionForStatus)(status, TransferRequest_1.transferRequestStatusOrder) || 0;
271
- // If status if first status in order
272
- if (statusPos == 0) {
273
- const updates = this._data.transfer_updates.filter((u) => u.status == status);
274
- // If no updates were done to products at same status. get original request quantity. Else, keep going in logic!
275
- if (!updates.some((u) => !!u.products && !!u.products && !!u.products[sku]))
276
- return this.getOriginalRequestedQuantity(sku);
277
- }
278
- const product = this._data.products.find((p) => p.sku == sku);
279
- if (!product)
280
- return 0;
281
- let result = product.qte;
282
- for (let i of this._data.transfer_updates) {
283
- if (((0, transferRequests_1.getOrderPositionForStatus)(i.status, TransferRequest_1.transferRequestStatusOrder) || 0) <= statusPos &&
284
- i.products &&
285
- i.products[sku]) {
286
- result = i.products[sku].qte_after;
287
- break;
288
- }
289
- }
290
- return result;
291
- };
292
- this.getInventoryQuantitiesStillMissingForCartTransfer = (associatedCart, itemSku, otherUnits) => {
293
- var _b;
294
- if (!!!associatedCart)
295
- return 0;
296
- const sameProd = associatedCart.data().items.find((i) => i.sku == itemSku);
297
- if (!!!sameProd)
298
- return 0;
299
- const alreadyReservedQuantities = (_b = sameProd.qte_reserved) !== null && _b !== void 0 ? _b : 0;
300
- const quantitiesNeededForCart = sameProd.qte - alreadyReservedQuantities;
301
- const convertedToInventoryForCartQuantities = (0, inventories_1.getConvertedUnitQuantity)(otherUnits, quantitiesNeededForCart, 'inventory_unit');
302
- return convertedToInventoryForCartQuantities;
303
- };
304
- this.handleFreeTransitInventory = async () => {
305
- if (!this._data.from || this._data.status != TransferRequest_1.TransferRequestStatusEnum.RECEIVED_PARTIAL)
306
- return false;
307
- try {
308
- const inventoryColl = this.getCollectionObj('inventories');
309
- if (!inventoryColl)
310
- return false;
311
- for (const product of this._data.products) {
312
- if (product.qte_received >= product.qte)
313
- continue;
314
- const inventoryItemQuery = await DatabaseService_1.default.getDocument(inventoryColl.path, product.sku);
315
- if (!inventoryItemQuery.exists)
316
- continue;
317
- const inventoryItem = new Inventory_1.default(inventoryItemQuery.data, inventoryColl, this._user);
318
- await inventoryItem.handleCancelInTransit(this._data.from, product.qte - product.qte_received, // TODO - NEW INVENTORY UNIT : Here in old logic we didn't change to inventory unit. Normal?
319
- undefined, !!this._data.associated_order);
320
- }
321
- }
322
- catch (err) {
323
- console.log('err', err);
324
- return false;
325
- }
326
- };
327
- this.handleChangeStoreInventory = async (newStatus, space) => {
328
- // test if can be processed
329
- if (!this._data.from)
330
- return false;
331
- try {
332
- const inventoryColl = this.getCollectionObj('inventories');
333
- if (!inventoryColl)
334
- return false;
335
- const shouldUpdateOnToBePrepared = await this._checkIfInventoryUpdatedOnStatusToBePrepared(space);
336
- // Fetch associated cart
337
- let associatedCart;
338
- if (newStatus == TransferRequest_1.TransferRequestStatusEnum.RECEIVED ||
339
- newStatus == TransferRequest_1.TransferRequestStatusEnum.RECEIVED_PARTIAL ||
340
- (shouldUpdateOnToBePrepared && newStatus == TransferRequest_1.TransferRequestStatusEnum.TO_BE_PREPARED)) {
341
- try {
342
- associatedCart = await this.fetchAssociatedCart();
343
- }
344
- catch (e) {
345
- console.log('error on fetching cart for transfer: ', e.toString());
346
- }
347
- }
348
- for (const product of this._data.products) {
349
- const inventoryItemQuery = await DatabaseService_1.default.getDocument(inventoryColl.path, product.sku);
350
- if (!inventoryItemQuery.exists)
351
- continue;
352
- const inventoryItem = new Inventory_1.default(inventoryItemQuery.data, inventoryColl, this._user);
353
- const sameCartItem = associatedCart === null || associatedCart === void 0 ? void 0 : associatedCart.data().items.find((i) => i.sku == product.sku);
354
- switch (newStatus) {
355
- case TransferRequest_1.TransferRequestStatusEnum.TO_BE_PREPARED:
356
- if (shouldUpdateOnToBePrepared) {
357
- const diffInQuantities = !!sameCartItem
358
- ? product.qte - (0, inventories_1.getConvertedUnitQuantity)(sameCartItem.other_units, sameCartItem.qte, 'inventory_unit')
359
- : 0;
360
- await inventoryItem.handleTransferToBePrepared(this._data.from, product.qte, undefined, !!this._data.associated_order, diffInQuantities > 0 ? diffInQuantities : undefined // If positive difference found between item qte in cart and transfert quantity, make sure equivalent is also reserved for web inventory
361
- );
362
- }
363
- break;
364
- case TransferRequest_1.TransferRequestStatusEnum.IN_TRANSIT:
365
- await inventoryItem.handleTransferInTransit(this._data.from, product.qte, undefined, !!this._data.associated_order, shouldUpdateOnToBePrepared);
366
- break;
367
- case TransferRequest_1.TransferRequestStatusEnum.RECEIVED:
368
- case TransferRequest_1.TransferRequestStatusEnum.RECEIVED_PARTIAL:
369
- const qteReceivedSinceLastStatus = product.qte_received - this.getPreviousReceivedQuantity(product.sku);
370
- if (qteReceivedSinceLastStatus == 0)
371
- continue; // no need to update inventory if no quantities were received
372
- // If associated cart was already processed, ignore reserved quantities (all quantities received should be added to available quantities)
373
- // Else, calculate missing quantities for transfer
374
- const cartWasProcessed = !!associatedCart && associatedCart.data().status > Cart_1.CartStatusEnum.CHECKOUT_PAYMENT_SUCCESS;
375
- const qteToReserve = cartWasProcessed
376
- ? undefined
377
- : this.getInventoryQuantitiesStillMissingForCartTransfer(associatedCart, product.sku, inventoryItem.data().other_units);
378
- await inventoryItem.handleTransferReceived(this._data.from, this._data.to, qteReceivedSinceLastStatus, undefined, {
379
- forOrder: !!this._data.associated_order,
380
- maxProcessingQte: typeof qteToReserve == 'number' && qteToReserve >= 0
381
- ? qteToReserve > qteReceivedSinceLastStatus
382
- ? qteReceivedSinceLastStatus
383
- : qteToReserve
384
- : 0,
385
- // If cart was already processed, skip web inventory update for availalble quantities
386
- skipWebUpdateForAvailable: cartWasProcessed,
387
- additionnalWebQuantitiesReserved: shouldUpdateOnToBePrepared
388
- });
389
- break;
390
- }
391
- continue;
392
- }
393
- return true;
394
- }
395
- catch (err) {
396
- console.log('err', err);
397
- return false;
398
- }
399
- };
400
- this.handleLiberateToBePreparedReservedQuantities = async (space) => {
401
- const inventoryReservedOnToBePrepared = await this._checkIfInventoryUpdatedOnStatusToBePrepared(space);
402
- // If space option not set, return without updated inventory
403
- if (!inventoryReservedOnToBePrepared)
404
- return true;
405
- if (!this._data.from)
406
- return false;
407
- try {
408
- const inventoryColl = this.getCollectionObj('inventories');
409
- if (!inventoryColl)
410
- return false;
411
- // Fetch associated cart
412
- let associatedCart;
413
- try {
414
- associatedCart = await this.fetchAssociatedCart();
415
- }
416
- catch (e) {
417
- console.log('error on fetching cart for transfer: ', e.toString());
418
- }
419
- for (let product of this._data.products) {
420
- const inventoryItemQuery = await DatabaseService_1.default.getDocument(inventoryColl.path, product.sku);
421
- if (!inventoryItemQuery.exists)
422
- continue;
423
- const inventoryItem = new Inventory_1.default(inventoryItemQuery.data, inventoryColl, this._user);
424
- // Check associated cart (if existing) for item with same sku, then check if more quantities were reserved by transfer than what was needed for order
425
- const sameCartItem = associatedCart === null || associatedCart === void 0 ? void 0 : associatedCart.data().items.find((i) => i.sku == product.sku);
426
- const extraWebQteReserved = !!sameCartItem
427
- ? product.qte - (0, inventories_1.getConvertedUnitQuantity)(sameCartItem.other_units, sameCartItem.qte, 'inventory_unit')
428
- : 0;
429
- await inventoryItem.handleCancelToBePrepared(this._data.from, product.qte, undefined, !!this._data.associated_order, extraWebQteReserved > 0 ? extraWebQteReserved : undefined);
430
- }
431
- return true;
432
- }
433
- catch (e) {
434
- console.log('error on releasing inventory for cancelled transfer: ', e.toString());
435
- return false;
436
- }
437
- };
438
- /**
439
- * Update transfer's associated cart with new reserved quantities. Called when quantities received for transfer.
440
- */
441
- this.handleUpdateAssociatedCartReservedQuantities = async () => {
442
- var _b, _c;
443
- const associatedCart = await this.fetchAssociatedCart();
444
- if (!!!associatedCart)
445
- return;
446
- // If cart was already processed (status > 5) skip cart quantity update
447
- if (associatedCart.data().status > Cart_1.CartStatusEnum.CHECKOUT_PAYMENT_SUCCESS)
448
- return;
449
- let somethingHasChanged = false;
450
- let cartItems = associatedCart.data().items;
451
- let updatedCartItems = [];
452
- for (let item of cartItems) {
453
- const sameInTransfer = this._data.products.find((p) => p.sku == item.sku);
454
- if (!!!sameInTransfer) {
455
- updatedCartItems.push(item);
456
- continue;
457
- }
458
- const sellUnit = (item.other_units || []).find((o) => o.is_sale_unit);
459
- const unitHasDecimals = !!sellUnit && (0, products_1.productUnitSupportsDecimals)(sellUnit.unit_slug);
460
- // If reserved quantity is already same or larger than expected quantities, no need to update product
461
- if (typeof item.qte_reserved == 'number' && (0, round_1.default)(item.qte_reserved, unitHasDecimals ? 2 : 0) >= item.qte) {
462
- updatedCartItems.push(item);
463
- continue;
464
- }
465
- // If no quantities were received since last status change, no need to update product
466
- const qteReceivedSinceLastStatus = sameInTransfer.qte_received - this.getPreviousReceivedQuantity(sameInTransfer.sku);
467
- if (!!!qteReceivedSinceLastStatus) {
468
- updatedCartItems.push(item);
469
- continue;
470
- }
471
- // Set new reserved quantities, capping at the quantity asked initially for order (rest is sent to available inventory for store when transfer is received)
472
- const reservedQteInInventoryUnit = (0, inventories_1.getConvertedUnitQuantity)(item.other_units, (_b = item.qte_reserved) !== null && _b !== void 0 ? _b : 0, 'inventory_unit');
473
- const qteInInventoryUnit = (0, inventories_1.getConvertedUnitQuantity)(item.other_units, (_c = item.qte) !== null && _c !== void 0 ? _c : 0, 'inventory_unit');
474
- const newReservedQte = reservedQteInInventoryUnit + qteReceivedSinceLastStatus;
475
- updatedCartItems.push(Object.assign(Object.assign({}, item), { qte_reserved: (0, inventories_1.getConvertedUnitQuantity)(item.other_units, newReservedQte > qteInInventoryUnit ? qteInInventoryUnit : newReservedQte, 'sale_unit', true) }));
476
- somethingHasChanged = true;
477
- }
478
- if (!!!somethingHasChanged)
479
- return;
480
- try {
481
- await associatedCart.save({ items: updatedCartItems, id: associatedCart.data().id }, undefined, true, true, true); // Will save partial cart only. Skips indexed cart save (does not trigger cloud functions)
482
- }
483
- catch (e) {
484
- console.log('error on saving cart with new qte_received in items: ', e.toString());
485
- }
486
- };
487
- /**
488
- * Use provided update object to construct new products object for current transfer
489
- * @param updatesToDo The product updates to apply
490
- * @param updatesToDo.sku The product sku to update
491
- * @param updatesToDo.ajustementQte The quantity to ajust. Must be negative if quantity REMOVED, and positive if ADDED.
492
- */
493
- this.constructProductObjFromUpdates = (updatesToDo) => {
494
- let updatedProducts = this._data.products.map((currentProd) => {
495
- const sameInUpdates = updatesToDo.find((u) => u.sku == currentProd.sku);
496
- if (!!!sameInUpdates)
497
- return currentProd;
498
- // Calculated new quantity with ajustmentQte, rounded up to zero
499
- let newQte = currentProd.qte + sameInUpdates.ajustmentQte;
500
- if (newQte < 0)
501
- newQte = 0;
502
- return Object.assign(Object.assign({}, currentProd), { qte: newQte });
503
- });
504
- return updatedProducts;
505
- };
506
- /**
507
- * Will update content in transfer without triggering a status change, if current transfer status permits. Still adds entry to the transfer_updates array.
508
- * @param updatedContent.products The array of products to update product
509
- * @param updatedContent.fromStore The new from store slug value if changed
510
- * @param options Options to create the associated transfer_updates entry
511
- * @param cancelTransferIfAllProductsAtZero Optionnal. If transfer should be auto-cancelled if all products are now at 0 quantities
512
- */
513
- this.saveUpdatesToContentOnly = async (updatedContent, options, cancelTransferIfAllProductsAtZero, updateContext = TransferRequest_1.TransferRequestUpdateContextEnum.TRANSFER_UPDATED) => {
514
- var _b;
515
- const spaceOptions = (_b = options.space) === null || _b === void 0 ? void 0 : _b.options.get();
516
- if (updatedContent.products) {
517
- if (!TransferRequest.transferAllowsIndependantProductUpdate(this._data, spaceOptions)) {
518
- throw new Error('Cannot update products without changing status for current transfer status.');
519
- }
520
- await this.save({ products: updatedContent.products }, false, true);
521
- // if validation quantities found, push values to qte and remove prop
522
- if (!!updatedContent.products.some((p) => typeof p.qte_validation == 'number')) {
523
- this.clearValidationQuantitiesFromProductData(true);
524
- }
525
- }
526
- if (updatedContent.fromStore) {
527
- if (!TransferRequest.transferAllowEditFromStore(this._data)) {
528
- throw new Error('Cannot update origin store for this transfer.');
529
- }
530
- await this.save({ from: updatedContent.fromStore }, false, true);
531
- }
532
- try {
533
- const statusPositionObj = await this._getOrderObject();
534
- // If flag to cancel transfer is provided and all products are now at 0 quantities, change status to cancelled. Else, keep current status
535
- const shouldCancelTransfer = updatedContent.products &&
536
- cancelTransferIfAllProductsAtZero &&
537
- updatedContent.products.every((p) => p.qte <= 0) &&
538
- TransferRequest.checkIfTransferCanBeCancelled(this._data.status, statusPositionObj);
539
- const statusToUse = !!shouldCancelTransfer ? TransferRequest_1.TransferRequestStatusEnum.CANCELLED : this._data.status;
540
- // Create new update entry for transfer and save
541
- const newUpdates = this._generateNewTransferStatusUpdates(statusToUse, options.user, options.comment, undefined, updateContext);
542
- await this.save(Object.assign({ transfer_updates: newUpdates }, (shouldCancelTransfer ? { status: statusToUse, completed: true } : {})), true, true);
543
- }
544
- catch (e) {
545
- const errorStr = 'error on updating products independantly from status: ' + e.toString();
546
- console.log(errorStr);
547
- throw new Error(errorStr);
548
- }
549
- return this.data();
550
- };
551
- // #endregion
552
- // --------------------------------------------------------------------
553
- // #region SPECIFIC PROP MANAGEMENT
554
- /**
555
- * Change or set the draft property value
556
- * @param newVal The new value to assign
557
- */
558
- this.setDraftValue = (newVal) => {
559
- this._data = Object.assign(Object.assign({}, this._data), { draft: newVal });
560
- };
561
- /**
562
- * Change or set the associated_order property value
563
- * @param newVal The new value to assign
564
- */
565
- this.setAssociatedOrder = (newVal) => {
566
- this._data = Object.assign(Object.assign({}, this._data), { associated_order: newVal });
567
- };
568
- /**
569
- * Change or set the transport_ref property value
570
- * @param newVal The new value to assign
571
- * @param saveToDatabase Do we save the new value in the database
572
- */
573
- this.setTransportRef = async (newVal, saveToDatabase = false) => {
574
- await this.save({ transport_ref: newVal }, saveToDatabase, true);
575
- };
576
- /**
577
- * Set the original transfer id property value
578
- * @param newVal The new value to assign
579
- */
580
- this.setOriginalTransferId = async (newVal) => {
581
- this._data = Object.assign(Object.assign({}, this._data), { original_transfer_id: newVal });
582
- };
583
- /**
584
- * Change the completed status to true and save to database
585
- */
586
- this.setAsCompleted = async (user, comment) => {
587
- this._generateNewTransferStatusUpdates(this._data.status, user, `Fermé manuellement${!!comment ? ' : ' + comment : ''}`, this._data.products, TransferRequest_1.TransferRequestUpdateContextEnum.TRANSFER_COMPLETED_MANUALLY);
588
- // cancel any transit items
589
- await this.handleFreeTransitInventory();
590
- await this.save({ completed: true }, true, true);
591
- };
592
- // --------------------------------------------------------------------
593
- // #region STATUS MANAGEMENT
594
- this.changeStatus = async (newStatus, comment, user, saveToDatabase = true, options = {}) => {
595
- const saveOptions = {
596
- comment,
597
- user,
598
- saveToDatabase,
599
- originalRequestProducts: options.originalRequestProducts,
600
- space: options.space
601
- };
602
- let fncToCall;
603
- switch (newStatus) {
604
- case TransferRequest_1.TransferRequestStatusEnum.OPEN:
605
- fncToCall = this.updateToStatus.open;
606
- break;
607
- case TransferRequest_1.TransferRequestStatusEnum.TO_BE_PREPARED:
608
- fncToCall = this.updateToStatus.toBePrepared;
609
- break;
610
- case TransferRequest_1.TransferRequestStatusEnum.IN_TRANSIT:
611
- fncToCall = this.updateToStatus.inTransit;
612
- break;
613
- case TransferRequest_1.TransferRequestStatusEnum.RECEIVED:
614
- fncToCall = this.updateToStatus.received;
615
- break;
616
- case TransferRequest_1.TransferRequestStatusEnum.RECEIVED_PARTIAL:
617
- saveOptions.markAsCompleted = options.setAsCompleted;
618
- fncToCall = this.updateToStatus.receivedPartial;
619
- break;
620
- case TransferRequest_1.TransferRequestStatusEnum.CANCELLED:
621
- fncToCall = this.updateToStatus.cancelled;
622
- break;
623
- }
624
- if (!!!fncToCall)
625
- throw new Error('No status update function associated to provided status! Returning.');
626
- try {
627
- await fncToCall(saveOptions, options.context);
628
- return this.data();
629
- }
630
- catch (e) {
631
- throw new Error('Impossible de soumettre le(s) transfert(s)');
632
- }
633
- };
634
- /**
635
- * Generates updates array and saves transfer for the first time in the database.
636
- * @param currentUser
637
- * @param comment
638
- * @param saveToDatabase
639
- * @throws if transfer already has an ID or doesn't have a status set
640
- */
641
- this.saveNewTransfer = async (currentUser, comment, saveToDatabase = true, skipRef) => {
642
- if (!!this.data().id)
643
- throw 'Cette demande de transfert existe déjà en base de données!';
644
- if (!!!this.data().status)
645
- throw "Cette demande n'a pas encore de statut initial, et ne peut être sauvegardée!";
646
- const newUpdates = this._generateNewTransferStatusUpdates(this.data().status, currentUser, comment);
647
- let newTransferRef = undefined;
648
- if (!!!skipRef) {
649
- // Fetch next ref for transfer
650
- newTransferRef = await this._getTransferRef();
651
- }
652
- return await this.save(Object.assign(Object.assign({}, this.data()), { ref: newTransferRef, transfer_updates: newUpdates }), saveToDatabase);
653
- };
654
- /**
655
- * Get the weight of a selected sku in this transfer
656
- * @param sku the product sku
657
- * @param unit the unit to return
658
- * @returns the weight in the requested unit
659
- */
660
- this.getProductWeight = (sku, unit = 'pounds') => {
661
- const item = this.data().products.find((p) => p.sku == sku);
662
- if (!item)
663
- return 0;
664
- if (!!!item.weight)
665
- return 0;
666
- const value = (0, toNumber_1.default)(item.weight.value) || 0;
667
- return item.weight.unit === unit ? value * item.qte : (0, weight_1.convertWeight)(value, item.weight.unit, unit) * item.qte;
668
- };
669
- /**
670
- * Fetches applicable transfer status order object by checking space_options for current space.
671
- */
672
- this._getOrderObject = async (space) => {
673
- if (!space)
674
- space = await Space_1.default.getCurrentSpaceWithRef(this._collection.path, this._user);
675
- return space.transferRequests.getTransferStatusOrder();
676
- };
677
- /**
678
- * Checks if provided "new" status follows current transfer status in the correct transfer status order for space.
679
- * @param statusToCheck
680
- */
681
- this._checkIfCanChangeToStatus = async (statusToCheck, space) => {
682
- const currentStatus = this._data.status;
683
- if (currentStatus == statusToCheck)
684
- return true;
685
- try {
686
- const orderObj = await this._getOrderObject(space);
687
- const possibleNextStatus = (0, transferRequests_1.getTransferStatusAfter)(currentStatus, orderObj);
688
- return possibleNextStatus !== null && possibleNextStatus.values.includes(statusToCheck);
689
- }
690
- catch (e) {
691
- console.log('error on checking status change: ', e.toString());
692
- return false;
693
- }
694
- };
695
- /**
696
- * Creates new entry for a status change, copies transfer_updates property and adds new entry to the start of copied array.
697
- * @param newStatus
698
- * @param user The email (or id) of Addio user that triggered the status change
699
- * @param comment The user added comment for status change (can be undefined)
700
- * @returns The copied array with the new value added.
701
- */
702
- this._generateNewTransferStatusUpdates = (newStatus, user, comment, originalRequestProducts, context) => {
703
- const updates = this._data.transfer_updates;
704
- const newProducts = this._data.products;
705
- const newFromStore = this._data.from;
706
- // If props id is set in transfer request (meaning it was saved to database at least once),
707
- // create products update obj if some changes were made
708
- let prodUpdateObj = {};
709
- // Id set means the transfer was saved to database
710
- if (!!this._data.id || !!originalRequestProducts) {
711
- if (newStatus == TransferRequest_1.TransferRequestStatusEnum.RECEIVED || newStatus == TransferRequest_1.TransferRequestStatusEnum.RECEIVED_PARTIAL) {
712
- // at this step only received qty is allowed to change
713
- for (let prod of newProducts) {
714
- const addedQty = prod.qte_received - this.getPreviousReceivedQuantity(prod.sku);
715
- if (addedQty != 0) {
716
- prodUpdateObj[prod.sku] = {
717
- qte_before: prod.qte_received - addedQty,
718
- qte_after: prod.qte_received,
719
- name: prod.name
720
- };
721
- }
722
- }
723
- }
724
- else {
725
- // Use provided prevProducts, or "normal" prevProducts if undefined, for comparaison with new products
726
- const prevProducts = !!originalRequestProducts ? originalRequestProducts : this.prevProducts;
727
- for (let prod of newProducts) {
728
- const name = prod.name;
729
- const sameInPrev = prevProducts.find((p) => p.sku == prod.sku);
730
- // a. If product not found in prev array, it was added to transfer, add entry to update obj
731
- if (!!!sameInPrev) {
732
- prodUpdateObj[prod.sku] = { qte_before: 0, qte_after: prod.qte, name };
733
- }
734
- // b. If product's quantities are different, add entry to update obj
735
- else if (sameInPrev.qte !== prod.qte) {
736
- prodUpdateObj[prod.sku] = { qte_before: sameInPrev.qte, qte_after: prod.qte, name };
737
- }
738
- }
739
- // Always use "normal" prevProducts for check here
740
- for (let prevProd of this.prevProducts) {
741
- const sameInNew = newProducts.find((p) => p.sku == prevProd.sku);
742
- // c. If product in prev array but not in new one, it was deleted fron transfer, add entry to update obj
743
- if (!!!sameInNew) {
744
- prodUpdateObj[prevProd.sku] = { qte_before: prevProd.qte, qte_after: 0, name: prevProd.name };
745
- }
746
- }
747
- }
748
- }
749
- // Add new update obj at start of array
750
- updates.unshift(Object.assign({ status: newStatus, date: new Date(), updated_by: user, comment: comment, products: !!Object.keys(prodUpdateObj).length ? prodUpdateObj : null, fromStore: this.prevFromStore != this._data.from && this._data.status == TransferRequest_1.TransferRequestStatusEnum.OPEN
751
- ? { before: this.prevFromStore || '', after: newFromStore || '' }
752
- : null }, (!!context ? { context } : {})));
753
- return updates;
754
- };
755
- /**
756
- * Saves provided status to TransferRequest data. Also generates and saves new entry for `transfer_updates` array.
757
- * @param newStatus
758
- * @param options
759
- */
760
- this._saveNewStatus = async (newStatus, options, forceCompleted = false, context = TransferRequest_1.TransferRequestUpdateContextEnum.TRANSFER_STATUS_CHANGE) => {
761
- const newUpdates = this._generateNewTransferStatusUpdates(newStatus, options.user, options.comment, options.originalRequestProducts, context);
762
- const completedProps = options.markAsCompleted;
763
- const canSetAsCompleted = !!completedProps && TransferRequest.checkIfStatusCountsAsCompleted(newStatus);
764
- if (!!completedProps && !canSetAsCompleted) {
765
- console.log('Could not set completed property to true since provided new status was not found in "elligible" array!');
766
- }
767
- try {
768
- const response = await this.save(Object.assign({ status: newStatus, transfer_updates: newUpdates }, (forceCompleted || canSetAsCompleted ? { completed: true } : {})), options.saveToDatabase);
769
- if (!!!response)
770
- throw new Error('Error while saving the transfer reqeust.');
771
- }
772
- catch (e) {
773
- console.error('Error while saving the transfer reqeust.');
774
- throw new Error('Error while saving the transfer reqeust.');
775
- }
776
- };
777
- /**
778
- * Checks update eligibility, then updates status to OPEN.
779
- * @param options
780
- */
781
- this._setAsOpen = async (options) => {
782
- const newStatus = TransferRequest_1.TransferRequestStatusEnum.OPEN;
783
- const statusChangeValid = await this._checkIfCanChangeToStatus(newStatus, options.space);
784
- if (!statusChangeValid)
785
- throw new Error('Trying to change to wrong status! Returning.');
786
- await this._saveNewStatus(newStatus, options);
787
- };
788
- /**
789
- * Checks update eligibility, then updates status to TO_BE_PREPARED. Also updates inventory for the origin store (but only if space_option set in space).
790
- * @param options
791
- */
792
- this._setAsToBePrepared = async (options) => {
793
- const newStatus = TransferRequest_1.TransferRequestStatusEnum.TO_BE_PREPARED;
794
- const statusChangeValid = await this._checkIfCanChangeToStatus(newStatus, options.space);
795
- if (!statusChangeValid)
796
- throw new Error('Trying to change to wrong status! Returning.');
797
- // Call to update inventory. If space does not have option set to update inventory on TO_BE_PREPARED, will simply return true.
798
- const inventoryChangeSuccess = await this.handleChangeStoreInventory(newStatus, options.space);
799
- if (!!!inventoryChangeSuccess) {
800
- throw "Une erreur est survenue lors de la mise à jour de l'inventaire.";
801
- }
802
- await this._saveNewStatus(newStatus, options);
803
- };
804
- /**
805
- * Checks update eligibility, then updates status to IN_TRANSIT. Also updates inventory for the origin store.
806
- * @param options
807
- */
808
- this._setAsInTransit = async (options) => {
809
- const newStatus = TransferRequest_1.TransferRequestStatusEnum.IN_TRANSIT;
810
- const statusChangeValid = await this._checkIfCanChangeToStatus(newStatus, options.space);
811
- if (!statusChangeValid)
812
- throw new Error('Trying to change to wrong status! Returning.');
813
- const inventoryChangesSuccess = await this.handleChangeStoreInventory(newStatus, options.space);
814
- if (!!!inventoryChangesSuccess) {
815
- throw "Une erreur est survenue lors de la mise à jour de l'inventaire.";
816
- }
817
- await this._saveNewStatus(newStatus, options);
818
- };
819
- /**
820
- * Checks update eligibility, then updates status to RECEIVED. Also updates inventory for both stores.
821
- * @param options
822
- */
823
- this._setAsReceived = async (options) => {
824
- const newStatus = TransferRequest_1.TransferRequestStatusEnum.RECEIVED;
825
- const statusChangeValid = await this._checkIfCanChangeToStatus(newStatus, options.space);
826
- if (!statusChangeValid)
827
- throw new Error('Trying to change to wrong status! Returning.');
828
- // Update inventory for items received
829
- const inventoryChangesSuccess = await this.handleChangeStoreInventory(newStatus);
830
- if (!!!inventoryChangesSuccess) {
831
- throw "Une erreur est survenue lors de la mise à jour de l'inventaire.";
832
- }
833
- // Update associated cart for reserved quantities
834
- await this.handleUpdateAssociatedCartReservedQuantities();
835
- // Update transfer and status
836
- await this._saveNewStatus(newStatus, options, true);
837
- };
838
- /**
839
- * Checks update eligibility, then updates status to RECEIVED_PARTIAL. Also updates inventory for both stores.
840
- * @param options
841
- * @todo Update inventory logic to deal with partially received quantities.
842
- */
843
- this._setAsReceivedPartially = async (options) => {
844
- const newStatus = TransferRequest_1.TransferRequestStatusEnum.RECEIVED_PARTIAL;
845
- const statusChangeValid = await this._checkIfCanChangeToStatus(newStatus, options.space);
846
- if (!statusChangeValid)
847
- throw new Error('Trying to change to wrong status! Returning.');
848
- const inventoryChangesSuccess = await this.handleChangeStoreInventory(newStatus);
849
- if (!!!inventoryChangesSuccess) {
850
- throw "Une erreur est survenue lors de la mise à jour de l'inventaire.";
851
- }
852
- // Update associated cart for reserved quantities
853
- await this.handleUpdateAssociatedCartReservedQuantities();
854
- // Update transfer and status
855
- await this._saveNewStatus(newStatus, options);
856
- };
857
- /**
858
- * Checks if transfer can be cancelled, and if so, updates status to CANCELLED.
859
- * @param options
860
- */
861
- this._setAsCancelled = async (options, context) => {
862
- const newStatus = TransferRequest_1.TransferRequestStatusEnum.CANCELLED;
863
- const statusPositionObj = await this._getOrderObject();
864
- const canBeCancelled = TransferRequest.checkIfTransferCanBeCancelled(this._data.status, statusPositionObj);
865
- if (!canBeCancelled) {
866
- throw new Error('transfer cannot be cancelled, status is same of after IN_TRANSIT');
867
- }
868
- // Check and liberate reserved inventory on cancelled to_be_prepared transfer
869
- if (this._data.status == TransferRequest_1.TransferRequestStatusEnum.TO_BE_PREPARED) {
870
- await this.handleLiberateToBePreparedReservedQuantities(options.space);
871
- }
872
- await this._saveNewStatus(newStatus, options, true, context);
873
- };
874
- /**
875
- * Object regrouping all status change functions
876
- */
877
- this.updateToStatus = {
878
- open: this._setAsOpen,
879
- toBePrepared: this._setAsToBePrepared,
880
- inTransit: this._setAsInTransit,
881
- received: this._setAsReceived,
882
- receivedPartial: this._setAsReceivedPartially,
883
- cancelled: this._setAsCancelled
884
- };
885
- // #endregion
886
- // --------------------------------------------------------------------
887
- // #region FORMAT DATA
888
- /**
889
- * Get formatted ref string for the transfer.
890
- * @param spaceTransferSettings
891
- * @returns {string | undefined}
892
- */
893
- this.getFormattedRef = (spaceTransferSettings) => {
894
- if (typeof this._data.ref == 'undefined') {
895
- console.log('transfer has no ref, returning!');
896
- return;
897
- }
898
- if (!!!spaceTransferSettings)
899
- return this._data.ref.toString();
900
- const prefix = spaceTransferSettings.prefix;
901
- const suffix = spaceTransferSettings.suffix;
902
- return `${prefix ? prefix + '-' : ''}${this._data.ref}${suffix ? '-' + suffix : ''}`;
903
- };
904
- // Format dates in data
905
- this._data = this.processData(_data);
906
- // Keep products in current transfer for update reference
907
- if (!!this._data.products.length) {
908
- this.prevProducts = [...this._data.products];
909
- }
910
- // Keep from store in current transfer for update reference
911
- if (!!this._data.from)
912
- this.prevFromStore = this._data.from;
913
- }
914
- }
915
- exports.TransferRequest = TransferRequest;
916
- _a = TransferRequest;
917
- TransferRequest.fetch = async ({ app, api, hpp = 10, page = 0, query = '', filters = '', indice = 'transfer_request', f = '', space, useProspr = false }) => {
918
- try {
919
- let prosprSearch = false;
920
- if (!!space) {
921
- const prosprService = space
922
- .data()
923
- .external_services.find((es) => es.external_service_name.toLowerCase().trim() === 'prosprsearch');
924
- prosprSearch = !!prosprService && prosprService.is_active;
925
- }
926
- const algolia = (0, algolia_1.createClient)({
927
- app,
928
- indexId: `${__1.isTestEnv ? 'test' : 'prod'}_${indice}`,
929
- key: !!useProspr ? api : prosprSearch && !!space ? space.preferences.prosprsearch.app() : api,
930
- prospr: !!prosprSearch || !!useProspr
931
- });
932
- const results = await algolia.search(query, {
933
- hitsPerPage: hpp,
934
- facetFilters: filters,
935
- filters: f,
936
- page,
937
- facets: ['*']
938
- });
939
- return results;
940
- }
941
- catch (error) {
942
- (0, console_1.errorMessage)(error);
943
- throw error;
944
- }
945
- };
946
- TransferRequest.getStatusLabel = (status) => {
947
- switch (status) {
948
- case TransferRequest_1.TransferRequestStatusEnum.INITIATED:
949
- return 'Initialisée';
950
- case TransferRequest_1.TransferRequestStatusEnum.OPEN:
951
- return 'Ouverte';
952
- case TransferRequest_1.TransferRequestStatusEnum.TO_BE_PREPARED:
953
- return 'À préparer';
954
- case TransferRequest_1.TransferRequestStatusEnum.IN_TRANSIT:
955
- return 'En transit';
956
- case TransferRequest_1.TransferRequestStatusEnum.CANCELLED:
957
- return 'Annulée';
958
- case TransferRequest_1.TransferRequestStatusEnum.RECEIVED_PARTIAL:
959
- return 'Reçue partiellement';
960
- case TransferRequest_1.TransferRequestStatusEnum.RECEIVED:
961
- return 'Reçue';
962
- }
963
- };
964
- TransferRequest.checkIfTransferCanBeCancelled = (currentTransferStatus, statusOrderObj) => {
965
- const currentPosition = (0, transferRequests_1.getOrderPositionForStatus)(currentTransferStatus, statusOrderObj);
966
- if (typeof currentPosition != 'number') {
967
- console.log('could not compare status since currentPosition was not found');
968
- return false;
969
- }
970
- const inTransitPosition = (0, transferRequests_1.getOrderPositionForStatus)(TransferRequest_1.TransferRequestStatusEnum.IN_TRANSIT, statusOrderObj);
971
- if (typeof inTransitPosition != 'number') {
972
- console.log('could not compare status since inTransitPosition was not found');
973
- return false;
974
- }
975
- return (0, toNumber_1.default)(currentPosition) < (0, toNumber_1.default)(inTransitPosition);
976
- };
977
- /**
978
- * Checks if provided status is included in "completed" transfer statuses list.
979
- * @param statusToCheck
980
- */
981
- TransferRequest.checkIfStatusCountsAsCompleted = (statusToCheck) => {
982
- return [
983
- TransferRequest_1.TransferRequestStatusEnum.RECEIVED,
984
- TransferRequest_1.TransferRequestStatusEnum.RECEIVED_PARTIAL,
985
- TransferRequest_1.TransferRequestStatusEnum.CANCELLED
986
- ].includes(statusToCheck);
987
- };
988
- TransferRequest.transferAllowAssignFromStore = (data) => {
989
- if (!!data.completed)
990
- return false;
991
- // Id set means the transfer was saved to database
992
- return !!data.id && TransferRequest_1.TransferRequestStatusEnum.INITIATED === data.status;
993
- };
994
- TransferRequest.transferAllowEditFromStore = (data) => {
995
- if (!!data.completed)
996
- return false;
997
- // Id set means the transfer was saved to database
998
- return !!data.id && TransferRequest_1.TransferRequestStatusEnum.OPEN === data.status;
999
- };
1000
- /**
1001
- * Test if the transfer allow adding products
1002
- * @param data the request data to verify
1003
- * @returns true if can add product
1004
- */
1005
- TransferRequest.transferAllowAddProductOnEdit = (data) => {
1006
- if (!!data.completed)
1007
- return false;
1008
- if (data.draft)
1009
- return true;
1010
- return [TransferRequest_1.TransferRequestStatusEnum.INITIATED].includes(data.status);
1011
- };
1012
- /**
1013
- * Test if the transfer allow deleteing products
1014
- * @param data the request data to verify
1015
- * @returns true if can delete product
1016
- */
1017
- TransferRequest.transferAllowProductDelete = (data) => {
1018
- if (!!data.completed)
1019
- return false;
1020
- // Id not set yet means the transfer is in creation mode. Product deletion should be allowed!
1021
- if (!!!data.id)
1022
- return true;
1023
- return [TransferRequest_1.TransferRequestStatusEnum.INITIATED].includes(data.status);
1024
- };
1025
- /**
1026
- * Test if the transfer allow editing products
1027
- * @param data the request data to verify
1028
- * @returns true if can be edited
1029
- */
1030
- TransferRequest.transferAllowEditProductOnEdit = (data) => {
1031
- if (!!data.completed)
1032
- return false;
1033
- return [
1034
- TransferRequest_1.TransferRequestStatusEnum.INITIATED,
1035
- TransferRequest_1.TransferRequestStatusEnum.OPEN,
1036
- TransferRequest_1.TransferRequestStatusEnum.TO_BE_PREPARED
1037
- ].includes(data.status);
1038
- };
1039
- /**
1040
- * Test if the transfer allow deleteing products when editing (not changing status)
1041
- * @param data the request data to verify
1042
- * @returns {boolean} true if can delete product
1043
- */
1044
- TransferRequest.transferAllowDeleteProductOnEdit = (data) => {
1045
- if (!!data.completed)
1046
- return false;
1047
- // Id not set yet means the transfer is in creation mode. Product deletion should be allowed!
1048
- if (!!!data.id)
1049
- return true;
1050
- return [TransferRequest_1.TransferRequestStatusEnum.INITIATED, TransferRequest_1.TransferRequestStatusEnum.OPEN].includes(data.status);
1051
- };
1052
- /**
1053
- * Test if the transfer has reached a state where it should display weight
1054
- * @param data the request data to verify
1055
- * @returns {boolean}
1056
- */
1057
- TransferRequest.transferShouldDisplayWeight = (data) => {
1058
- return ![TransferRequest_1.TransferRequestStatusEnum.INITIATED].includes(data.status);
1059
- };
1060
- /**
1061
- * Test if the transfer allows products to be updated without a status change
1062
- * @param data the request data to verify
1063
- * @param spaceOptions Optionnal. If provided, check added before pushing TO_BE_PREPARED status, to see if `ajust_inventory_on_to_be_prepared` is not set (or else, status not elligible)
1064
- * @returns {boolean}
1065
- */
1066
- TransferRequest.transferAllowsIndependantProductUpdate = (data, spaceOptions) => {
1067
- var _b;
1068
- if (!!data.completed)
1069
- return false;
1070
- let acceptedStatuses = [TransferRequest_1.TransferRequestStatusEnum.INITIATED, TransferRequest_1.TransferRequestStatusEnum.OPEN];
1071
- // If no cart associated to transfer, update can be done at TO_BE_PREPARED status as well
1072
- if (!data.associated_order && (!spaceOptions || !((_b = spaceOptions.transfer_requests) === null || _b === void 0 ? void 0 : _b.ajust_inventory_on_to_be_prepared)))
1073
- acceptedStatuses.push(TransferRequest_1.TransferRequestStatusEnum.TO_BE_PREPARED);
1074
- return acceptedStatuses.includes(data.status);
1075
- };
1076
- /**
1077
- * Get the total estimated weight by calculating each product's weigth times inventory quantity
1078
- * @param unit the unit to return
1079
- * @returns the weight in the requested unit
1080
- */
1081
- TransferRequest.getTotalWeight = (products, unit = 'pounds') => {
1082
- return (0, sumBy_1.default)(products, (item) => {
1083
- if (!!!item.weight)
1084
- return 0;
1085
- const value = (0, toNumber_1.default)(item.weight.value) || 0;
1086
- return item.weight.unit === unit ? value * item.qte : (0, weight_1.convertWeight)(value, item.weight.unit, unit) * item.qte;
1087
- });
1088
- };
1089
- /**
1090
- * Get the total calculated pallet quantities for all transfer items
1091
- * @param items
1092
- * @returns
1093
- */
1094
- TransferRequest.getTotalPalletQte = (items) => {
1095
- const total = (0, sumBy_1.default)(items.map((item) => {
1096
- if (!!!item.other_units || !!!item.count_in_pallet_total) {
1097
- return 0;
1098
- }
1099
- const paletteUnit = item.other_units.find((u) => u.unit_slug === 'pal');
1100
- if (!!!paletteUnit || !!!paletteUnit.fitting_unit) {
1101
- return 0;
1102
- }
1103
- return item.qte / paletteUnit.fitting_unit;
1104
- }));
1105
- return (0, ceil_1.default)(total);
1106
- };
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ var _a;
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.TransferRequest = void 0;
8
+ const TransferRequest_1 = require("../../Interfaces/TransferRequest");
9
+ // Classes
10
+ const DatabaseService_1 = __importDefault(require("../../services/database/DatabaseService"));
11
+ const baseService_1 = require("../baseService");
12
+ const Inventory_1 = __importDefault(require("../Inventory"));
13
+ const Space_1 = __importDefault(require("../Space"));
14
+ // Utils
15
+ const toNumber_1 = __importDefault(require("lodash/toNumber"));
16
+ const ceil_1 = __importDefault(require("lodash/ceil"));
17
+ const round_1 = __importDefault(require("lodash/round"));
18
+ const data_1 = require("../../utils/data");
19
+ const inventories_1 = require("../../utils/inventories");
20
+ const transferRequests_1 = require("../../utils/transferRequests");
21
+ const sumBy_1 = __importDefault(require("lodash/sumBy"));
22
+ const weight_1 = require("../../utils/weight");
23
+ const algolia_1 = require("../../utils/algolia");
24
+ const __1 = require("../..");
25
+ const console_1 = require("../../utils/console");
26
+ const context_1 = require("../../utils/context");
27
+ const tools_1 = require("../../utils/tools");
28
+ const products_1 = require("../../rules/GR/utils/products");
29
+ const Cart_1 = require("../../Interfaces/Cart");
30
+ class TransferRequest extends baseService_1.BaseServiceClass {
31
+ constructor(_data, _collection, _user) {
32
+ super(_data, _collection, _user);
33
+ this._listener = null;
34
+ this.prevProducts = [];
35
+ this.prevFromStore = undefined;
36
+ this.processData = (data) => (Object.assign(Object.assign({}, data), { transfer_updates: data.transfer_updates.map((update) => (Object.assign(Object.assign({}, update), { date: (0, data_1.formatDate)(update.date) }))) }));
37
+ this.getCollectionObj = (collPath) => {
38
+ if (DatabaseService_1.default.getPathParent(this._collection.path) == '/')
39
+ return;
40
+ const coll = DatabaseService_1.default.asCollectionObject(DatabaseService_1.default.getPathParent(this._collection.path), collPath);
41
+ return coll;
42
+ };
43
+ /**
44
+ * Check if current space has option to update inventory on status changed to TO_BE_PREPARED
45
+ * @param space Optionnal. IF not provided, will fetch space from DB
46
+ */
47
+ this._checkIfInventoryUpdatedOnStatusToBePrepared = async (space) => {
48
+ if (!space)
49
+ space = await Space_1.default.getCurrentSpaceWithRef(this._collection.path, this._user);
50
+ return !!space.options.checkIfOptionIsSet('transfer_requests.ajust_inventory_on_to_be_prepared');
51
+ };
52
+ /**
53
+ * Test if the transfer can be closed
54
+ * @returns true if the status allow to close the transfer
55
+ */
56
+ this.checkIfTransferCanBeClosedManually = () => {
57
+ return this._data.status == TransferRequest_1.TransferRequestStatusEnum.RECEIVED_PARTIAL;
58
+ };
59
+ this.transferAllowAssignFromStore = () => TransferRequest.transferAllowAssignFromStore(this._data);
60
+ this.transferAllowEditFromStore = () => TransferRequest.transferAllowEditFromStore(this._data);
61
+ this.transferAllowAddProductOnEdit = () => TransferRequest.transferAllowAddProductOnEdit(this._data);
62
+ this.transferAllowProductDelete = () => TransferRequest.transferAllowProductDelete(this._data);
63
+ this.transferAllowEditProductOnEdit = () => TransferRequest.transferAllowEditProductOnEdit(this._data);
64
+ this.transferAllowDeleteProductOnEdit = () => TransferRequest.transferAllowProductDelete(this._data);
65
+ this.transferShouldDisplayWeight = () => TransferRequest.transferShouldDisplayWeight(this._data);
66
+ this.transferAllowsIndependantProductUpdate = (spaceOptions) => TransferRequest.transferAllowsIndependantProductUpdate(this._data, spaceOptions);
67
+ this.fetchAssociatedCart = async () => {
68
+ if (!!!this._data.associated_order)
69
+ return;
70
+ let associatedCart = undefined;
71
+ try {
72
+ const space = await Space_1.default.getCurrentSpaceWithRef(this._collection.path, this._user);
73
+ const cartQuery = await space.carts.get({
74
+ query: [{ field: 'ref', operator: '==', value: this._data.associated_order }]
75
+ });
76
+ if (!!cartQuery && !!cartQuery.length)
77
+ associatedCart = cartQuery[0];
78
+ }
79
+ catch (e) {
80
+ console.log('could not fetch cart associated to transfer: ', e.toString());
81
+ }
82
+ return associatedCart;
83
+ };
84
+ this.addProduct = (sku, parent_slug, qte, name, image, other_units, weight, count_in_pallet_total) => {
85
+ const data = this.data();
86
+ if (!TransferRequest.transferAllowEditProductOnEdit(this._data))
87
+ return false;
88
+ let updatedProducts = data.products;
89
+ if (!updatedProducts.find((p) => p.sku == sku)) {
90
+ updatedProducts.push({
91
+ sku,
92
+ parent_slug,
93
+ qte,
94
+ name,
95
+ image,
96
+ other_units,
97
+ weight,
98
+ count_in_pallet_total,
99
+ qte_received: 0
100
+ });
101
+ }
102
+ else {
103
+ updatedProducts = updatedProducts.map((p) => {
104
+ if (p.sku !== sku)
105
+ return p;
106
+ return Object.assign(Object.assign({}, p), { qte: p.qte + qte <= 1 ? 1 : p.qte + qte });
107
+ });
108
+ }
109
+ this._data = Object.assign(Object.assign({}, data), { products: updatedProducts });
110
+ return true;
111
+ };
112
+ this.editProduct = (sku, newQte) => {
113
+ const data = this.data();
114
+ if (!TransferRequest.transferAllowEditProductOnEdit(this._data))
115
+ return false;
116
+ this._data = Object.assign(Object.assign({}, data), { products: data.products.map((p) => {
117
+ if (p.sku !== sku)
118
+ return p;
119
+ return Object.assign(Object.assign({}, p), { qte: newQte });
120
+ }) });
121
+ return true;
122
+ };
123
+ this.deleteProduct = (sku) => {
124
+ const data = this.data();
125
+ if (!TransferRequest.transferAllowProductDelete(this._data))
126
+ return false;
127
+ this._data = Object.assign(Object.assign({}, data), { products: data.products.filter((p) => p.sku !== sku) });
128
+ return true;
129
+ };
130
+ this.data = () => this._data;
131
+ this.isListening = () => !!this._listener;
132
+ this.killListener = () => {
133
+ if (!!!this._listener)
134
+ return false;
135
+ this._listener = null;
136
+ return true;
137
+ };
138
+ this.listen = (callback) => {
139
+ if (!!this._listener)
140
+ return false;
141
+ DatabaseService_1.default.registerListener((snap) => {
142
+ if (snap === null)
143
+ this._listener = null;
144
+ if (snap.length === 0)
145
+ this._listener = null;
146
+ snap.map((s) => {
147
+ if (s.id == this.data().id) {
148
+ this._data = this.processData(s.data);
149
+ if (!!callback)
150
+ callback();
151
+ }
152
+ });
153
+ }, this._collection.path, { id: this.data().id });
154
+ return true;
155
+ };
156
+ this._getTransferRef = async () => {
157
+ let newRef = undefined;
158
+ try {
159
+ const space = await Space_1.default.getCurrentSpaceWithRef(this._collection.path, this._user);
160
+ const token = (0, context_1.getSpaceTokenFromSpaceOnly)(space);
161
+ const api = __1.API_URL;
162
+ let triesLeft = 3;
163
+ while (triesLeft > 0) {
164
+ try {
165
+ const resp = await fetch(`${api}/transfers/refnumber`, {
166
+ method: 'GET',
167
+ headers: {
168
+ 'Content-Type': 'application/json',
169
+ Authorization: `Bearer ${token}`
170
+ }
171
+ });
172
+ if (resp.status >= 200 && resp.status < 300) {
173
+ const data = await resp.json();
174
+ if (data.status == 'success') {
175
+ newRef = (0, toNumber_1.default)(data.result);
176
+ break;
177
+ }
178
+ }
179
+ }
180
+ catch (e) {
181
+ console.log('Error fetching transfer number', e);
182
+ }
183
+ await (0, tools_1.waitFor)(1000); // wait a second before trying again, server needs to recover
184
+ triesLeft--;
185
+ }
186
+ if (triesLeft == 0)
187
+ throw new Error('could not get a Ref number');
188
+ return newRef;
189
+ }
190
+ catch (e) {
191
+ console.log('error on fetching new transfer ref: ', e.toString());
192
+ return;
193
+ }
194
+ };
195
+ this.save = async (partial, saveToDatabase = true, merge = true) => {
196
+ const saveResult = await super.save(partial, undefined, saveToDatabase, undefined, merge);
197
+ if (typeof saveResult === 'string') {
198
+ this._data = Object.assign(Object.assign({}, this._data), { id: saveResult });
199
+ }
200
+ return saveResult;
201
+ };
202
+ /**
203
+ * Validate the quantities set before submit
204
+ * @param strictQty Tell if we should only allow equal quantity
205
+ * @returns
206
+ */
207
+ this.validateBeforeSubmit = async (strictQty = true) => {
208
+ if (strictQty) {
209
+ return this.data().products.every((p) => typeof p.qte_validation == 'undefined' || p.qte === p.qte_validation);
210
+ }
211
+ return this.data().products.every((p) => typeof p.qte_validation == 'undefined' || p.qte_validation >= 0);
212
+ };
213
+ // --------------------------------------------------------------------
214
+ // #region QUANTITIES AND INVENTORY MANAGEMENT
215
+ /**
216
+ * Strip out the validation qty field in products data
217
+ * Do this before saving so the qte_validation doesnt get save in database
218
+ * @param copyQte should copy validation qty to the actual qty
219
+ */
220
+ this.clearValidationQuantitiesFromProductData = (copyQte = false) => {
221
+ this._data = Object.assign(Object.assign({}, this._data), { products: this._data.products.map((p) => (Object.assign(Object.assign({}, p), { qte: copyQte ? p.qte_validation || 0 : p.qte, qte_validation: undefined }))) });
222
+ };
223
+ /**
224
+ * Add the validation quantities to the received amount
225
+ */
226
+ this.addValidationQuantitiesToReceivedQuantities = () => {
227
+ this._data = Object.assign(Object.assign({}, this._data), { products: this._data.products.map((p) => (Object.assign(Object.assign({}, p), { qte_received: (p.qte_validation || 0) + (p.qte_received || 0), qte_validation: undefined }))) });
228
+ };
229
+ /**
230
+ * Return the previous quantity received for the provided sku
231
+ * @param sku the product sku to get
232
+ * @returns
233
+ */
234
+ this.getPreviousReceivedQuantity = (sku) => {
235
+ const entry = this._data.transfer_updates.find((u) => (u.status == TransferRequest_1.TransferRequestStatusEnum.RECEIVED_PARTIAL || u.status == TransferRequest_1.TransferRequestStatusEnum.RECEIVED) &&
236
+ u.products &&
237
+ u.products[sku]);
238
+ if (entry) {
239
+ // if we got an entry then the sku exists inside
240
+ return entry.products[sku].qte_after;
241
+ }
242
+ return 0;
243
+ };
244
+ /**
245
+ * Return the original reuested quantity
246
+ * @param sku the product sku to get
247
+ * @returns
248
+ */
249
+ this.getOriginalRequestedQuantity = (sku) => {
250
+ const product = this._data.products.find((p) => p.sku == sku);
251
+ if (!product)
252
+ return 0;
253
+ let result = product.qte;
254
+ this._data.transfer_updates.map((u) => {
255
+ if (u.status != TransferRequest_1.TransferRequestStatusEnum.RECEIVED_PARTIAL &&
256
+ u.status != TransferRequest_1.TransferRequestStatusEnum.RECEIVED &&
257
+ u.products &&
258
+ u.products[sku])
259
+ result = u.products[sku].qte_before;
260
+ });
261
+ return result;
262
+ };
263
+ /**
264
+ * Get the quantity at the requested status
265
+ * @param sku the product sku
266
+ * @param status the status to look for
267
+ * @returns the quantity at the specified status
268
+ */
269
+ this.getQuantityAtStatus = (sku, status) => {
270
+ const statusPos = (0, transferRequests_1.getOrderPositionForStatus)(status, TransferRequest_1.transferRequestStatusOrder) || 0;
271
+ // If status if first status in order
272
+ if (statusPos == 0) {
273
+ const updates = this._data.transfer_updates.filter((u) => u.status == status);
274
+ // If no updates were done to products at same status. get original request quantity. Else, keep going in logic!
275
+ if (!updates.some((u) => !!u.products && !!u.products && !!u.products[sku]))
276
+ return this.getOriginalRequestedQuantity(sku);
277
+ }
278
+ const product = this._data.products.find((p) => p.sku == sku);
279
+ if (!product)
280
+ return 0;
281
+ let result = product.qte;
282
+ for (let i of this._data.transfer_updates) {
283
+ if (((0, transferRequests_1.getOrderPositionForStatus)(i.status, TransferRequest_1.transferRequestStatusOrder) || 0) <= statusPos &&
284
+ i.products &&
285
+ i.products[sku]) {
286
+ result = i.products[sku].qte_after;
287
+ break;
288
+ }
289
+ }
290
+ return result;
291
+ };
292
+ this.getInventoryQuantitiesStillMissingForCartTransfer = (associatedCart, itemSku, otherUnits) => {
293
+ var _b;
294
+ if (!!!associatedCart)
295
+ return 0;
296
+ const sameProd = associatedCart.data().items.find((i) => i.sku == itemSku);
297
+ if (!!!sameProd)
298
+ return 0;
299
+ const alreadyReservedQuantities = (_b = sameProd.qte_reserved) !== null && _b !== void 0 ? _b : 0;
300
+ const quantitiesNeededForCart = sameProd.qte - alreadyReservedQuantities;
301
+ const convertedToInventoryForCartQuantities = (0, inventories_1.getConvertedUnitQuantity)(otherUnits, quantitiesNeededForCart, 'inventory_unit');
302
+ return convertedToInventoryForCartQuantities;
303
+ };
304
+ this.handleFreeTransitInventory = async () => {
305
+ if (!this._data.from || this._data.status != TransferRequest_1.TransferRequestStatusEnum.RECEIVED_PARTIAL)
306
+ return false;
307
+ try {
308
+ const inventoryColl = this.getCollectionObj('inventories');
309
+ if (!inventoryColl)
310
+ return false;
311
+ for (const product of this._data.products) {
312
+ if (product.qte_received >= product.qte)
313
+ continue;
314
+ const inventoryItemQuery = await DatabaseService_1.default.getDocument(inventoryColl.path, product.sku);
315
+ if (!inventoryItemQuery.exists)
316
+ continue;
317
+ const inventoryItem = new Inventory_1.default(inventoryItemQuery.data, inventoryColl, this._user);
318
+ await inventoryItem.handleCancelInTransit(this._data.from, product.qte - product.qte_received, // TODO - NEW INVENTORY UNIT : Here in old logic we didn't change to inventory unit. Normal?
319
+ undefined, !!this._data.associated_order);
320
+ }
321
+ }
322
+ catch (err) {
323
+ console.log('err', err);
324
+ return false;
325
+ }
326
+ };
327
+ this.handleChangeStoreInventory = async (newStatus, space) => {
328
+ // test if can be processed
329
+ if (!this._data.from)
330
+ return false;
331
+ try {
332
+ const inventoryColl = this.getCollectionObj('inventories');
333
+ if (!inventoryColl)
334
+ return false;
335
+ const shouldUpdateOnToBePrepared = await this._checkIfInventoryUpdatedOnStatusToBePrepared(space);
336
+ // Fetch associated cart
337
+ let associatedCart;
338
+ if (newStatus == TransferRequest_1.TransferRequestStatusEnum.RECEIVED ||
339
+ newStatus == TransferRequest_1.TransferRequestStatusEnum.RECEIVED_PARTIAL ||
340
+ (shouldUpdateOnToBePrepared && newStatus == TransferRequest_1.TransferRequestStatusEnum.TO_BE_PREPARED)) {
341
+ try {
342
+ associatedCart = await this.fetchAssociatedCart();
343
+ }
344
+ catch (e) {
345
+ console.log('error on fetching cart for transfer: ', e.toString());
346
+ }
347
+ }
348
+ for (const product of this._data.products) {
349
+ const inventoryItemQuery = await DatabaseService_1.default.getDocument(inventoryColl.path, product.sku);
350
+ if (!inventoryItemQuery.exists)
351
+ continue;
352
+ const inventoryItem = new Inventory_1.default(inventoryItemQuery.data, inventoryColl, this._user);
353
+ const sameCartItem = associatedCart === null || associatedCart === void 0 ? void 0 : associatedCart.data().items.find((i) => i.sku == product.sku);
354
+ switch (newStatus) {
355
+ case TransferRequest_1.TransferRequestStatusEnum.TO_BE_PREPARED:
356
+ if (shouldUpdateOnToBePrepared) {
357
+ const diffInQuantities = !!sameCartItem
358
+ ? product.qte - (0, inventories_1.getConvertedUnitQuantity)(sameCartItem.other_units, sameCartItem.qte, 'inventory_unit')
359
+ : 0;
360
+ await inventoryItem.handleTransferToBePrepared(this._data.from, product.qte, undefined, !!this._data.associated_order, diffInQuantities > 0 ? diffInQuantities : undefined // If positive difference found between item qte in cart and transfert quantity, make sure equivalent is also reserved for web inventory
361
+ );
362
+ }
363
+ break;
364
+ case TransferRequest_1.TransferRequestStatusEnum.IN_TRANSIT:
365
+ await inventoryItem.handleTransferInTransit(this._data.from, product.qte, undefined, !!this._data.associated_order, shouldUpdateOnToBePrepared);
366
+ break;
367
+ case TransferRequest_1.TransferRequestStatusEnum.RECEIVED:
368
+ case TransferRequest_1.TransferRequestStatusEnum.RECEIVED_PARTIAL:
369
+ const qteReceivedSinceLastStatus = product.qte_received - this.getPreviousReceivedQuantity(product.sku);
370
+ if (qteReceivedSinceLastStatus == 0)
371
+ continue; // no need to update inventory if no quantities were received
372
+ // If associated cart was already processed, ignore reserved quantities (all quantities received should be added to available quantities)
373
+ // Else, calculate missing quantities for transfer
374
+ const cartWasProcessed = !!associatedCart && associatedCart.data().status > Cart_1.CartStatusEnum.CHECKOUT_PAYMENT_SUCCESS;
375
+ const qteToReserve = cartWasProcessed
376
+ ? undefined
377
+ : this.getInventoryQuantitiesStillMissingForCartTransfer(associatedCart, product.sku, inventoryItem.data().other_units);
378
+ await inventoryItem.handleTransferReceived(this._data.from, this._data.to, qteReceivedSinceLastStatus, undefined, {
379
+ forOrder: !!this._data.associated_order,
380
+ maxProcessingQte: typeof qteToReserve == 'number' && qteToReserve >= 0
381
+ ? qteToReserve > qteReceivedSinceLastStatus
382
+ ? qteReceivedSinceLastStatus
383
+ : qteToReserve
384
+ : 0,
385
+ // If cart was already processed, skip web inventory update for availalble quantities
386
+ skipWebUpdateForAvailable: cartWasProcessed,
387
+ additionnalWebQuantitiesReserved: shouldUpdateOnToBePrepared
388
+ });
389
+ break;
390
+ }
391
+ continue;
392
+ }
393
+ return true;
394
+ }
395
+ catch (err) {
396
+ console.log('err', err);
397
+ return false;
398
+ }
399
+ };
400
+ this.handleLiberateToBePreparedReservedQuantities = async (space) => {
401
+ const inventoryReservedOnToBePrepared = await this._checkIfInventoryUpdatedOnStatusToBePrepared(space);
402
+ // If space option not set, return without updated inventory
403
+ if (!inventoryReservedOnToBePrepared)
404
+ return true;
405
+ if (!this._data.from)
406
+ return false;
407
+ try {
408
+ const inventoryColl = this.getCollectionObj('inventories');
409
+ if (!inventoryColl)
410
+ return false;
411
+ // Fetch associated cart
412
+ let associatedCart;
413
+ try {
414
+ associatedCart = await this.fetchAssociatedCart();
415
+ }
416
+ catch (e) {
417
+ console.log('error on fetching cart for transfer: ', e.toString());
418
+ }
419
+ for (let product of this._data.products) {
420
+ const inventoryItemQuery = await DatabaseService_1.default.getDocument(inventoryColl.path, product.sku);
421
+ if (!inventoryItemQuery.exists)
422
+ continue;
423
+ const inventoryItem = new Inventory_1.default(inventoryItemQuery.data, inventoryColl, this._user);
424
+ // Check associated cart (if existing) for item with same sku, then check if more quantities were reserved by transfer than what was needed for order
425
+ const sameCartItem = associatedCart === null || associatedCart === void 0 ? void 0 : associatedCart.data().items.find((i) => i.sku == product.sku);
426
+ const extraWebQteReserved = !!sameCartItem
427
+ ? product.qte - (0, inventories_1.getConvertedUnitQuantity)(sameCartItem.other_units, sameCartItem.qte, 'inventory_unit')
428
+ : 0;
429
+ await inventoryItem.handleCancelToBePrepared(this._data.from, product.qte, undefined, !!this._data.associated_order, extraWebQteReserved > 0 ? extraWebQteReserved : undefined);
430
+ }
431
+ return true;
432
+ }
433
+ catch (e) {
434
+ console.log('error on releasing inventory for cancelled transfer: ', e.toString());
435
+ return false;
436
+ }
437
+ };
438
+ /**
439
+ * Update transfer's associated cart with new reserved quantities. Called when quantities received for transfer.
440
+ */
441
+ this.handleUpdateAssociatedCartReservedQuantities = async () => {
442
+ var _b, _c;
443
+ const associatedCart = await this.fetchAssociatedCart();
444
+ if (!!!associatedCart)
445
+ return;
446
+ // If cart was already processed (status > 5) skip cart quantity update
447
+ if (associatedCart.data().status > Cart_1.CartStatusEnum.CHECKOUT_PAYMENT_SUCCESS)
448
+ return;
449
+ let somethingHasChanged = false;
450
+ let cartItems = associatedCart.data().items;
451
+ let updatedCartItems = [];
452
+ for (let item of cartItems) {
453
+ const sameInTransfer = this._data.products.find((p) => p.sku == item.sku);
454
+ if (!!!sameInTransfer) {
455
+ updatedCartItems.push(item);
456
+ continue;
457
+ }
458
+ const sellUnit = (item.other_units || []).find((o) => o.is_sale_unit);
459
+ const unitHasDecimals = !!sellUnit && (0, products_1.productUnitSupportsDecimals)(sellUnit.unit_slug);
460
+ // If reserved quantity is already same or larger than expected quantities, no need to update product
461
+ if (typeof item.qte_reserved == 'number' && (0, round_1.default)(item.qte_reserved, unitHasDecimals ? 2 : 0) >= item.qte) {
462
+ updatedCartItems.push(item);
463
+ continue;
464
+ }
465
+ // If no quantities were received since last status change, no need to update product
466
+ const qteReceivedSinceLastStatus = sameInTransfer.qte_received - this.getPreviousReceivedQuantity(sameInTransfer.sku);
467
+ if (!!!qteReceivedSinceLastStatus) {
468
+ updatedCartItems.push(item);
469
+ continue;
470
+ }
471
+ // Set new reserved quantities, capping at the quantity asked initially for order (rest is sent to available inventory for store when transfer is received)
472
+ const reservedQteInInventoryUnit = (0, inventories_1.getConvertedUnitQuantity)(item.other_units, (_b = item.qte_reserved) !== null && _b !== void 0 ? _b : 0, 'inventory_unit');
473
+ const qteInInventoryUnit = (0, inventories_1.getConvertedUnitQuantity)(item.other_units, (_c = item.qte) !== null && _c !== void 0 ? _c : 0, 'inventory_unit');
474
+ const newReservedQte = reservedQteInInventoryUnit + qteReceivedSinceLastStatus;
475
+ updatedCartItems.push(Object.assign(Object.assign({}, item), { qte_reserved: (0, inventories_1.getConvertedUnitQuantity)(item.other_units, newReservedQte > qteInInventoryUnit ? qteInInventoryUnit : newReservedQte, 'sale_unit', true) }));
476
+ somethingHasChanged = true;
477
+ }
478
+ if (!!!somethingHasChanged)
479
+ return;
480
+ try {
481
+ await associatedCart.save({ items: updatedCartItems, id: associatedCart.data().id }, undefined, true, true, true); // Will save partial cart only. Skips indexed cart save (does not trigger cloud functions)
482
+ }
483
+ catch (e) {
484
+ console.log('error on saving cart with new qte_received in items: ', e.toString());
485
+ }
486
+ };
487
+ /**
488
+ * Use provided update object to construct new products object for current transfer
489
+ * @param updatesToDo The product updates to apply
490
+ * @param updatesToDo.sku The product sku to update
491
+ * @param updatesToDo.ajustementQte The quantity to ajust. Must be negative if quantity REMOVED, and positive if ADDED.
492
+ */
493
+ this.constructProductObjFromUpdates = (updatesToDo) => {
494
+ let updatedProducts = this._data.products.map((currentProd) => {
495
+ const sameInUpdates = updatesToDo.find((u) => u.sku == currentProd.sku);
496
+ if (!!!sameInUpdates)
497
+ return currentProd;
498
+ // Calculated new quantity with ajustmentQte, rounded up to zero
499
+ let newQte = currentProd.qte + sameInUpdates.ajustmentQte;
500
+ if (newQte < 0)
501
+ newQte = 0;
502
+ return Object.assign(Object.assign({}, currentProd), { qte: newQte });
503
+ });
504
+ return updatedProducts;
505
+ };
506
+ /**
507
+ * Will update content in transfer without triggering a status change, if current transfer status permits. Still adds entry to the transfer_updates array.
508
+ * @param updatedContent.products The array of products to update product
509
+ * @param updatedContent.fromStore The new from store slug value if changed
510
+ * @param options Options to create the associated transfer_updates entry
511
+ * @param cancelTransferIfAllProductsAtZero Optionnal. If transfer should be auto-cancelled if all products are now at 0 quantities
512
+ */
513
+ this.saveUpdatesToContentOnly = async (updatedContent, options, cancelTransferIfAllProductsAtZero, updateContext = TransferRequest_1.TransferRequestUpdateContextEnum.TRANSFER_UPDATED) => {
514
+ var _b;
515
+ const spaceOptions = (_b = options.space) === null || _b === void 0 ? void 0 : _b.options.get();
516
+ if (updatedContent.products) {
517
+ if (!TransferRequest.transferAllowsIndependantProductUpdate(this._data, spaceOptions)) {
518
+ throw new Error('Cannot update products without changing status for current transfer status.');
519
+ }
520
+ await this.save({ products: updatedContent.products }, false, true);
521
+ // if validation quantities found, push values to qte and remove prop
522
+ if (!!updatedContent.products.some((p) => typeof p.qte_validation == 'number')) {
523
+ this.clearValidationQuantitiesFromProductData(true);
524
+ }
525
+ }
526
+ if (updatedContent.fromStore) {
527
+ if (!TransferRequest.transferAllowEditFromStore(this._data)) {
528
+ throw new Error('Cannot update origin store for this transfer.');
529
+ }
530
+ await this.save({ from: updatedContent.fromStore }, false, true);
531
+ }
532
+ try {
533
+ const statusPositionObj = await this._getOrderObject();
534
+ // If flag to cancel transfer is provided and all products are now at 0 quantities, change status to cancelled. Else, keep current status
535
+ const shouldCancelTransfer = updatedContent.products &&
536
+ cancelTransferIfAllProductsAtZero &&
537
+ updatedContent.products.every((p) => p.qte <= 0) &&
538
+ TransferRequest.checkIfTransferCanBeCancelled(this._data.status, statusPositionObj);
539
+ const statusToUse = !!shouldCancelTransfer ? TransferRequest_1.TransferRequestStatusEnum.CANCELLED : this._data.status;
540
+ // Create new update entry for transfer and save
541
+ const newUpdates = this._generateNewTransferStatusUpdates(statusToUse, options.user, options.comment, undefined, updateContext);
542
+ await this.save(Object.assign({ transfer_updates: newUpdates }, (shouldCancelTransfer ? { status: statusToUse, completed: true } : {})), true, true);
543
+ }
544
+ catch (e) {
545
+ const errorStr = 'error on updating products independantly from status: ' + e.toString();
546
+ console.log(errorStr);
547
+ throw new Error(errorStr);
548
+ }
549
+ return this.data();
550
+ };
551
+ // #endregion
552
+ // --------------------------------------------------------------------
553
+ // #region SPECIFIC PROP MANAGEMENT
554
+ /**
555
+ * Change or set the draft property value
556
+ * @param newVal The new value to assign
557
+ */
558
+ this.setDraftValue = (newVal) => {
559
+ this._data = Object.assign(Object.assign({}, this._data), { draft: newVal });
560
+ };
561
+ /**
562
+ * Change or set the associated_order property value
563
+ * @param newVal The new value to assign
564
+ */
565
+ this.setAssociatedOrder = (newVal) => {
566
+ this._data = Object.assign(Object.assign({}, this._data), { associated_order: newVal });
567
+ };
568
+ /**
569
+ * Change or set the transport_ref property value
570
+ * @param newVal The new value to assign
571
+ * @param saveToDatabase Do we save the new value in the database
572
+ */
573
+ this.setTransportRef = async (newVal, saveToDatabase = false) => {
574
+ await this.save({ transport_ref: newVal }, saveToDatabase, true);
575
+ };
576
+ /**
577
+ * Set the original transfer id property value
578
+ * @param newVal The new value to assign
579
+ */
580
+ this.setOriginalTransferId = async (newVal) => {
581
+ this._data = Object.assign(Object.assign({}, this._data), { original_transfer_id: newVal });
582
+ };
583
+ /**
584
+ * Change the completed status to true and save to database
585
+ */
586
+ this.setAsCompleted = async (user, comment) => {
587
+ this._generateNewTransferStatusUpdates(this._data.status, user, `Fermé manuellement${!!comment ? ' : ' + comment : ''}`, this._data.products, TransferRequest_1.TransferRequestUpdateContextEnum.TRANSFER_COMPLETED_MANUALLY);
588
+ // cancel any transit items
589
+ await this.handleFreeTransitInventory();
590
+ await this.save({ completed: true }, true, true);
591
+ };
592
+ // --------------------------------------------------------------------
593
+ // #region STATUS MANAGEMENT
594
+ this.changeStatus = async (newStatus, comment, user, saveToDatabase = true, options = {}) => {
595
+ const saveOptions = {
596
+ comment,
597
+ user,
598
+ saveToDatabase,
599
+ originalRequestProducts: options.originalRequestProducts,
600
+ space: options.space
601
+ };
602
+ let fncToCall;
603
+ switch (newStatus) {
604
+ case TransferRequest_1.TransferRequestStatusEnum.OPEN:
605
+ fncToCall = this.updateToStatus.open;
606
+ break;
607
+ case TransferRequest_1.TransferRequestStatusEnum.TO_BE_PREPARED:
608
+ fncToCall = this.updateToStatus.toBePrepared;
609
+ break;
610
+ case TransferRequest_1.TransferRequestStatusEnum.IN_TRANSIT:
611
+ fncToCall = this.updateToStatus.inTransit;
612
+ break;
613
+ case TransferRequest_1.TransferRequestStatusEnum.RECEIVED:
614
+ fncToCall = this.updateToStatus.received;
615
+ break;
616
+ case TransferRequest_1.TransferRequestStatusEnum.RECEIVED_PARTIAL:
617
+ saveOptions.markAsCompleted = options.setAsCompleted;
618
+ fncToCall = this.updateToStatus.receivedPartial;
619
+ break;
620
+ case TransferRequest_1.TransferRequestStatusEnum.CANCELLED:
621
+ fncToCall = this.updateToStatus.cancelled;
622
+ break;
623
+ }
624
+ if (!!!fncToCall)
625
+ throw new Error('No status update function associated to provided status! Returning.');
626
+ try {
627
+ await fncToCall(saveOptions, options.context);
628
+ return this.data();
629
+ }
630
+ catch (e) {
631
+ throw new Error('Impossible de soumettre le(s) transfert(s)');
632
+ }
633
+ };
634
+ /**
635
+ * Generates updates array and saves transfer for the first time in the database.
636
+ * @param currentUser
637
+ * @param comment
638
+ * @param saveToDatabase
639
+ * @throws if transfer already has an ID or doesn't have a status set
640
+ */
641
+ this.saveNewTransfer = async (currentUser, comment, saveToDatabase = true, skipRef) => {
642
+ if (!!this.data().id)
643
+ throw 'Cette demande de transfert existe déjà en base de données!';
644
+ if (!!!this.data().status)
645
+ throw "Cette demande n'a pas encore de statut initial, et ne peut être sauvegardée!";
646
+ const newUpdates = this._generateNewTransferStatusUpdates(this.data().status, currentUser, comment);
647
+ let newTransferRef = undefined;
648
+ if (!!!skipRef) {
649
+ // Fetch next ref for transfer
650
+ newTransferRef = await this._getTransferRef();
651
+ }
652
+ return await this.save(Object.assign(Object.assign({}, this.data()), { ref: newTransferRef, transfer_updates: newUpdates }), saveToDatabase);
653
+ };
654
+ /**
655
+ * Get the weight of a selected sku in this transfer
656
+ * @param sku the product sku
657
+ * @param unit the unit to return
658
+ * @returns the weight in the requested unit
659
+ */
660
+ this.getProductWeight = (sku, unit = 'pounds') => {
661
+ const item = this.data().products.find((p) => p.sku == sku);
662
+ if (!item)
663
+ return 0;
664
+ if (!!!item.weight)
665
+ return 0;
666
+ const value = (0, toNumber_1.default)(item.weight.value) || 0;
667
+ return item.weight.unit === unit ? value * item.qte : (0, weight_1.convertWeight)(value, item.weight.unit, unit) * item.qte;
668
+ };
669
+ /**
670
+ * Fetches applicable transfer status order object by checking space_options for current space.
671
+ */
672
+ this._getOrderObject = async (space) => {
673
+ if (!space)
674
+ space = await Space_1.default.getCurrentSpaceWithRef(this._collection.path, this._user);
675
+ return space.transferRequests.getTransferStatusOrder();
676
+ };
677
+ /**
678
+ * Checks if provided "new" status follows current transfer status in the correct transfer status order for space.
679
+ * @param statusToCheck
680
+ */
681
+ this._checkIfCanChangeToStatus = async (statusToCheck, space) => {
682
+ const currentStatus = this._data.status;
683
+ if (currentStatus == statusToCheck)
684
+ return true;
685
+ try {
686
+ const orderObj = await this._getOrderObject(space);
687
+ const possibleNextStatus = (0, transferRequests_1.getTransferStatusAfter)(currentStatus, orderObj);
688
+ return possibleNextStatus !== null && possibleNextStatus.values.includes(statusToCheck);
689
+ }
690
+ catch (e) {
691
+ console.log('error on checking status change: ', e.toString());
692
+ return false;
693
+ }
694
+ };
695
+ /**
696
+ * Creates new entry for a status change, copies transfer_updates property and adds new entry to the start of copied array.
697
+ * @param newStatus
698
+ * @param user The email (or id) of Addio user that triggered the status change
699
+ * @param comment The user added comment for status change (can be undefined)
700
+ * @returns The copied array with the new value added.
701
+ */
702
+ this._generateNewTransferStatusUpdates = (newStatus, user, comment, originalRequestProducts, context) => {
703
+ const updates = this._data.transfer_updates;
704
+ const newProducts = this._data.products;
705
+ const newFromStore = this._data.from;
706
+ // If props id is set in transfer request (meaning it was saved to database at least once),
707
+ // create products update obj if some changes were made
708
+ let prodUpdateObj = {};
709
+ // Id set means the transfer was saved to database
710
+ if (!!this._data.id || !!originalRequestProducts) {
711
+ if (newStatus == TransferRequest_1.TransferRequestStatusEnum.RECEIVED || newStatus == TransferRequest_1.TransferRequestStatusEnum.RECEIVED_PARTIAL) {
712
+ // at this step only received qty is allowed to change
713
+ for (let prod of newProducts) {
714
+ const addedQty = prod.qte_received - this.getPreviousReceivedQuantity(prod.sku);
715
+ if (addedQty != 0) {
716
+ prodUpdateObj[prod.sku] = {
717
+ qte_before: prod.qte_received - addedQty,
718
+ qte_after: prod.qte_received,
719
+ name: prod.name
720
+ };
721
+ }
722
+ }
723
+ }
724
+ else {
725
+ // Use provided prevProducts, or "normal" prevProducts if undefined, for comparaison with new products
726
+ const prevProducts = !!originalRequestProducts ? originalRequestProducts : this.prevProducts;
727
+ for (let prod of newProducts) {
728
+ const name = prod.name;
729
+ const sameInPrev = prevProducts.find((p) => p.sku == prod.sku);
730
+ // a. If product not found in prev array, it was added to transfer, add entry to update obj
731
+ if (!!!sameInPrev) {
732
+ prodUpdateObj[prod.sku] = { qte_before: 0, qte_after: prod.qte, name };
733
+ }
734
+ // b. If product's quantities are different, add entry to update obj
735
+ else if (sameInPrev.qte !== prod.qte) {
736
+ prodUpdateObj[prod.sku] = { qte_before: sameInPrev.qte, qte_after: prod.qte, name };
737
+ }
738
+ }
739
+ // Always use "normal" prevProducts for check here
740
+ for (let prevProd of this.prevProducts) {
741
+ const sameInNew = newProducts.find((p) => p.sku == prevProd.sku);
742
+ // c. If product in prev array but not in new one, it was deleted fron transfer, add entry to update obj
743
+ if (!!!sameInNew) {
744
+ prodUpdateObj[prevProd.sku] = { qte_before: prevProd.qte, qte_after: 0, name: prevProd.name };
745
+ }
746
+ }
747
+ }
748
+ }
749
+ // Add new update obj at start of array
750
+ updates.unshift(Object.assign({ status: newStatus, date: new Date(), updated_by: user, comment: comment, products: !!Object.keys(prodUpdateObj).length ? prodUpdateObj : null, fromStore: this.prevFromStore != this._data.from && this._data.status == TransferRequest_1.TransferRequestStatusEnum.OPEN
751
+ ? { before: this.prevFromStore || '', after: newFromStore || '' }
752
+ : null }, (!!context ? { context } : {})));
753
+ return updates;
754
+ };
755
+ /**
756
+ * Saves provided status to TransferRequest data. Also generates and saves new entry for `transfer_updates` array.
757
+ * @param newStatus
758
+ * @param options
759
+ */
760
+ this._saveNewStatus = async (newStatus, options, forceCompleted = false, context = TransferRequest_1.TransferRequestUpdateContextEnum.TRANSFER_STATUS_CHANGE) => {
761
+ const newUpdates = this._generateNewTransferStatusUpdates(newStatus, options.user, options.comment, options.originalRequestProducts, context);
762
+ const completedProps = options.markAsCompleted;
763
+ const canSetAsCompleted = !!completedProps && TransferRequest.checkIfStatusCountsAsCompleted(newStatus);
764
+ if (!!completedProps && !canSetAsCompleted) {
765
+ console.log('Could not set completed property to true since provided new status was not found in "elligible" array!');
766
+ }
767
+ try {
768
+ const response = await this.save(Object.assign({ status: newStatus, transfer_updates: newUpdates }, (forceCompleted || canSetAsCompleted ? { completed: true } : {})), options.saveToDatabase);
769
+ if (!!!response)
770
+ throw new Error('Error while saving the transfer reqeust.');
771
+ }
772
+ catch (e) {
773
+ console.error('Error while saving the transfer reqeust.');
774
+ throw new Error('Error while saving the transfer reqeust.');
775
+ }
776
+ };
777
+ /**
778
+ * Checks update eligibility, then updates status to OPEN.
779
+ * @param options
780
+ */
781
+ this._setAsOpen = async (options) => {
782
+ const newStatus = TransferRequest_1.TransferRequestStatusEnum.OPEN;
783
+ const statusChangeValid = await this._checkIfCanChangeToStatus(newStatus, options.space);
784
+ if (!statusChangeValid)
785
+ throw new Error('Trying to change to wrong status! Returning.');
786
+ await this._saveNewStatus(newStatus, options);
787
+ };
788
+ /**
789
+ * Checks update eligibility, then updates status to TO_BE_PREPARED. Also updates inventory for the origin store (but only if space_option set in space).
790
+ * @param options
791
+ */
792
+ this._setAsToBePrepared = async (options) => {
793
+ const newStatus = TransferRequest_1.TransferRequestStatusEnum.TO_BE_PREPARED;
794
+ const statusChangeValid = await this._checkIfCanChangeToStatus(newStatus, options.space);
795
+ if (!statusChangeValid)
796
+ throw new Error('Trying to change to wrong status! Returning.');
797
+ // Call to update inventory. If space does not have option set to update inventory on TO_BE_PREPARED, will simply return true.
798
+ const inventoryChangeSuccess = await this.handleChangeStoreInventory(newStatus, options.space);
799
+ if (!!!inventoryChangeSuccess) {
800
+ throw "Une erreur est survenue lors de la mise à jour de l'inventaire.";
801
+ }
802
+ await this._saveNewStatus(newStatus, options);
803
+ };
804
+ /**
805
+ * Checks update eligibility, then updates status to IN_TRANSIT. Also updates inventory for the origin store.
806
+ * @param options
807
+ */
808
+ this._setAsInTransit = async (options) => {
809
+ const newStatus = TransferRequest_1.TransferRequestStatusEnum.IN_TRANSIT;
810
+ const statusChangeValid = await this._checkIfCanChangeToStatus(newStatus, options.space);
811
+ if (!statusChangeValid)
812
+ throw new Error('Trying to change to wrong status! Returning.');
813
+ const inventoryChangesSuccess = await this.handleChangeStoreInventory(newStatus, options.space);
814
+ if (!!!inventoryChangesSuccess) {
815
+ throw "Une erreur est survenue lors de la mise à jour de l'inventaire.";
816
+ }
817
+ await this._saveNewStatus(newStatus, options);
818
+ };
819
+ /**
820
+ * Checks update eligibility, then updates status to RECEIVED. Also updates inventory for both stores.
821
+ * @param options
822
+ */
823
+ this._setAsReceived = async (options) => {
824
+ const newStatus = TransferRequest_1.TransferRequestStatusEnum.RECEIVED;
825
+ const statusChangeValid = await this._checkIfCanChangeToStatus(newStatus, options.space);
826
+ if (!statusChangeValid)
827
+ throw new Error('Trying to change to wrong status! Returning.');
828
+ // Update inventory for items received
829
+ const inventoryChangesSuccess = await this.handleChangeStoreInventory(newStatus);
830
+ if (!!!inventoryChangesSuccess) {
831
+ throw "Une erreur est survenue lors de la mise à jour de l'inventaire.";
832
+ }
833
+ // Update associated cart for reserved quantities
834
+ await this.handleUpdateAssociatedCartReservedQuantities();
835
+ // Update transfer and status
836
+ await this._saveNewStatus(newStatus, options, true);
837
+ };
838
+ /**
839
+ * Checks update eligibility, then updates status to RECEIVED_PARTIAL. Also updates inventory for both stores.
840
+ * @param options
841
+ * @todo Update inventory logic to deal with partially received quantities.
842
+ */
843
+ this._setAsReceivedPartially = async (options) => {
844
+ const newStatus = TransferRequest_1.TransferRequestStatusEnum.RECEIVED_PARTIAL;
845
+ const statusChangeValid = await this._checkIfCanChangeToStatus(newStatus, options.space);
846
+ if (!statusChangeValid)
847
+ throw new Error('Trying to change to wrong status! Returning.');
848
+ const inventoryChangesSuccess = await this.handleChangeStoreInventory(newStatus);
849
+ if (!!!inventoryChangesSuccess) {
850
+ throw "Une erreur est survenue lors de la mise à jour de l'inventaire.";
851
+ }
852
+ // Update associated cart for reserved quantities
853
+ await this.handleUpdateAssociatedCartReservedQuantities();
854
+ // Update transfer and status
855
+ await this._saveNewStatus(newStatus, options);
856
+ };
857
+ /**
858
+ * Checks if transfer can be cancelled, and if so, updates status to CANCELLED.
859
+ * @param options
860
+ */
861
+ this._setAsCancelled = async (options, context) => {
862
+ const newStatus = TransferRequest_1.TransferRequestStatusEnum.CANCELLED;
863
+ const statusPositionObj = await this._getOrderObject();
864
+ const canBeCancelled = TransferRequest.checkIfTransferCanBeCancelled(this._data.status, statusPositionObj);
865
+ if (!canBeCancelled) {
866
+ throw new Error('transfer cannot be cancelled, status is same of after IN_TRANSIT');
867
+ }
868
+ // Check and liberate reserved inventory on cancelled to_be_prepared transfer
869
+ if (this._data.status == TransferRequest_1.TransferRequestStatusEnum.TO_BE_PREPARED) {
870
+ await this.handleLiberateToBePreparedReservedQuantities(options.space);
871
+ }
872
+ await this._saveNewStatus(newStatus, options, true, context);
873
+ };
874
+ /**
875
+ * Object regrouping all status change functions
876
+ */
877
+ this.updateToStatus = {
878
+ open: this._setAsOpen,
879
+ toBePrepared: this._setAsToBePrepared,
880
+ inTransit: this._setAsInTransit,
881
+ received: this._setAsReceived,
882
+ receivedPartial: this._setAsReceivedPartially,
883
+ cancelled: this._setAsCancelled
884
+ };
885
+ // #endregion
886
+ // --------------------------------------------------------------------
887
+ // #region FORMAT DATA
888
+ /**
889
+ * Get formatted ref string for the transfer.
890
+ * @param spaceTransferSettings
891
+ * @returns {string | undefined}
892
+ */
893
+ this.getFormattedRef = (spaceTransferSettings) => {
894
+ if (typeof this._data.ref == 'undefined') {
895
+ console.log('transfer has no ref, returning!');
896
+ return;
897
+ }
898
+ if (!!!spaceTransferSettings)
899
+ return this._data.ref.toString();
900
+ const prefix = spaceTransferSettings.prefix;
901
+ const suffix = spaceTransferSettings.suffix;
902
+ return `${prefix ? prefix + '-' : ''}${this._data.ref}${suffix ? '-' + suffix : ''}`;
903
+ };
904
+ // Format dates in data
905
+ this._data = this.processData(_data);
906
+ // Keep products in current transfer for update reference
907
+ if (!!this._data.products.length) {
908
+ this.prevProducts = [...this._data.products];
909
+ }
910
+ // Keep from store in current transfer for update reference
911
+ if (!!this._data.from)
912
+ this.prevFromStore = this._data.from;
913
+ }
914
+ }
915
+ exports.TransferRequest = TransferRequest;
916
+ _a = TransferRequest;
917
+ TransferRequest.fetch = async ({ app, api, hpp = 10, page = 0, query = '', filters = '', indice = 'transfer_request', f = '', space, useProspr = false }) => {
918
+ try {
919
+ let prosprSearch = false;
920
+ if (!!space) {
921
+ const prosprService = space
922
+ .data()
923
+ .external_services.find((es) => es.external_service_name.toLowerCase().trim() === 'prosprsearch');
924
+ prosprSearch = !!prosprService && prosprService.is_active;
925
+ }
926
+ const algolia = (0, algolia_1.createClient)({
927
+ app,
928
+ indexId: `${__1.isTestEnv ? 'test' : 'prod'}_${indice}`,
929
+ key: !!useProspr ? api : prosprSearch && !!space ? space.preferences.prosprsearch.app() : api,
930
+ prospr: !!prosprSearch || !!useProspr
931
+ });
932
+ const results = await algolia.search(query, {
933
+ hitsPerPage: hpp,
934
+ facetFilters: filters,
935
+ filters: f,
936
+ page,
937
+ facets: ['*']
938
+ });
939
+ return results;
940
+ }
941
+ catch (error) {
942
+ (0, console_1.errorMessage)(error);
943
+ throw error;
944
+ }
945
+ };
946
+ TransferRequest.getStatusLabel = (status) => {
947
+ switch (status) {
948
+ case TransferRequest_1.TransferRequestStatusEnum.INITIATED:
949
+ return 'Initialisée';
950
+ case TransferRequest_1.TransferRequestStatusEnum.OPEN:
951
+ return 'Ouverte';
952
+ case TransferRequest_1.TransferRequestStatusEnum.TO_BE_PREPARED:
953
+ return 'À préparer';
954
+ case TransferRequest_1.TransferRequestStatusEnum.IN_TRANSIT:
955
+ return 'En transit';
956
+ case TransferRequest_1.TransferRequestStatusEnum.CANCELLED:
957
+ return 'Annulée';
958
+ case TransferRequest_1.TransferRequestStatusEnum.RECEIVED_PARTIAL:
959
+ return 'Reçue partiellement';
960
+ case TransferRequest_1.TransferRequestStatusEnum.RECEIVED:
961
+ return 'Reçue';
962
+ }
963
+ };
964
+ TransferRequest.checkIfTransferCanBeCancelled = (currentTransferStatus, statusOrderObj) => {
965
+ const currentPosition = (0, transferRequests_1.getOrderPositionForStatus)(currentTransferStatus, statusOrderObj);
966
+ if (typeof currentPosition != 'number') {
967
+ console.log('could not compare status since currentPosition was not found');
968
+ return false;
969
+ }
970
+ const inTransitPosition = (0, transferRequests_1.getOrderPositionForStatus)(TransferRequest_1.TransferRequestStatusEnum.IN_TRANSIT, statusOrderObj);
971
+ if (typeof inTransitPosition != 'number') {
972
+ console.log('could not compare status since inTransitPosition was not found');
973
+ return false;
974
+ }
975
+ return (0, toNumber_1.default)(currentPosition) < (0, toNumber_1.default)(inTransitPosition);
976
+ };
977
+ /**
978
+ * Checks if provided status is included in "completed" transfer statuses list.
979
+ * @param statusToCheck
980
+ */
981
+ TransferRequest.checkIfStatusCountsAsCompleted = (statusToCheck) => {
982
+ return [
983
+ TransferRequest_1.TransferRequestStatusEnum.RECEIVED,
984
+ TransferRequest_1.TransferRequestStatusEnum.RECEIVED_PARTIAL,
985
+ TransferRequest_1.TransferRequestStatusEnum.CANCELLED
986
+ ].includes(statusToCheck);
987
+ };
988
+ TransferRequest.transferAllowAssignFromStore = (data) => {
989
+ if (!!data.completed)
990
+ return false;
991
+ // Id set means the transfer was saved to database
992
+ return !!data.id && TransferRequest_1.TransferRequestStatusEnum.INITIATED === data.status;
993
+ };
994
+ TransferRequest.transferAllowEditFromStore = (data) => {
995
+ if (!!data.completed)
996
+ return false;
997
+ // Id set means the transfer was saved to database
998
+ return !!data.id && TransferRequest_1.TransferRequestStatusEnum.OPEN === data.status;
999
+ };
1000
+ /**
1001
+ * Test if the transfer allow adding products
1002
+ * @param data the request data to verify
1003
+ * @returns true if can add product
1004
+ */
1005
+ TransferRequest.transferAllowAddProductOnEdit = (data) => {
1006
+ if (!!data.completed)
1007
+ return false;
1008
+ if (data.draft)
1009
+ return true;
1010
+ return [TransferRequest_1.TransferRequestStatusEnum.INITIATED].includes(data.status);
1011
+ };
1012
+ /**
1013
+ * Test if the transfer allow deleteing products
1014
+ * @param data the request data to verify
1015
+ * @returns true if can delete product
1016
+ */
1017
+ TransferRequest.transferAllowProductDelete = (data) => {
1018
+ if (!!data.completed)
1019
+ return false;
1020
+ // Id not set yet means the transfer is in creation mode. Product deletion should be allowed!
1021
+ if (!!!data.id)
1022
+ return true;
1023
+ return [TransferRequest_1.TransferRequestStatusEnum.INITIATED].includes(data.status);
1024
+ };
1025
+ /**
1026
+ * Test if the transfer allow editing products
1027
+ * @param data the request data to verify
1028
+ * @returns true if can be edited
1029
+ */
1030
+ TransferRequest.transferAllowEditProductOnEdit = (data) => {
1031
+ if (!!data.completed)
1032
+ return false;
1033
+ return [
1034
+ TransferRequest_1.TransferRequestStatusEnum.INITIATED,
1035
+ TransferRequest_1.TransferRequestStatusEnum.OPEN,
1036
+ TransferRequest_1.TransferRequestStatusEnum.TO_BE_PREPARED
1037
+ ].includes(data.status);
1038
+ };
1039
+ /**
1040
+ * Test if the transfer allow deleteing products when editing (not changing status)
1041
+ * @param data the request data to verify
1042
+ * @returns {boolean} true if can delete product
1043
+ */
1044
+ TransferRequest.transferAllowDeleteProductOnEdit = (data) => {
1045
+ if (!!data.completed)
1046
+ return false;
1047
+ // Id not set yet means the transfer is in creation mode. Product deletion should be allowed!
1048
+ if (!!!data.id)
1049
+ return true;
1050
+ return [TransferRequest_1.TransferRequestStatusEnum.INITIATED, TransferRequest_1.TransferRequestStatusEnum.OPEN].includes(data.status);
1051
+ };
1052
+ /**
1053
+ * Test if the transfer has reached a state where it should display weight
1054
+ * @param data the request data to verify
1055
+ * @returns {boolean}
1056
+ */
1057
+ TransferRequest.transferShouldDisplayWeight = (data) => {
1058
+ return ![TransferRequest_1.TransferRequestStatusEnum.INITIATED].includes(data.status);
1059
+ };
1060
+ /**
1061
+ * Test if the transfer allows products to be updated without a status change
1062
+ * @param data the request data to verify
1063
+ * @param spaceOptions Optionnal. If provided, check added before pushing TO_BE_PREPARED status, to see if `ajust_inventory_on_to_be_prepared` is not set (or else, status not elligible)
1064
+ * @returns {boolean}
1065
+ */
1066
+ TransferRequest.transferAllowsIndependantProductUpdate = (data, spaceOptions) => {
1067
+ var _b;
1068
+ if (!!data.completed)
1069
+ return false;
1070
+ let acceptedStatuses = [TransferRequest_1.TransferRequestStatusEnum.INITIATED, TransferRequest_1.TransferRequestStatusEnum.OPEN];
1071
+ // If no cart associated to transfer, update can be done at TO_BE_PREPARED status as well
1072
+ if (!data.associated_order && (!spaceOptions || !((_b = spaceOptions.transfer_requests) === null || _b === void 0 ? void 0 : _b.ajust_inventory_on_to_be_prepared)))
1073
+ acceptedStatuses.push(TransferRequest_1.TransferRequestStatusEnum.TO_BE_PREPARED);
1074
+ return acceptedStatuses.includes(data.status);
1075
+ };
1076
+ /**
1077
+ * Get the total estimated weight by calculating each product's weigth times inventory quantity
1078
+ * @param unit the unit to return
1079
+ * @returns the weight in the requested unit
1080
+ */
1081
+ TransferRequest.getTotalWeight = (products, unit = 'pounds') => {
1082
+ return (0, sumBy_1.default)(products, (item) => {
1083
+ if (!!!item.weight)
1084
+ return 0;
1085
+ const value = (0, toNumber_1.default)(item.weight.value) || 0;
1086
+ return item.weight.unit === unit ? value * item.qte : (0, weight_1.convertWeight)(value, item.weight.unit, unit) * item.qte;
1087
+ });
1088
+ };
1089
+ /**
1090
+ * Get the total calculated pallet quantities for all transfer items
1091
+ * @param items
1092
+ * @returns
1093
+ */
1094
+ TransferRequest.getTotalPalletQte = (items) => {
1095
+ const total = (0, sumBy_1.default)(items.map((item) => {
1096
+ if (!!!item.other_units || !!!item.count_in_pallet_total) {
1097
+ return 0;
1098
+ }
1099
+ const paletteUnit = item.other_units.find((u) => u.unit_slug === 'pal');
1100
+ if (!!!paletteUnit || !!!paletteUnit.fitting_unit) {
1101
+ return 0;
1102
+ }
1103
+ return item.qte / paletteUnit.fitting_unit;
1104
+ }));
1105
+ return (0, ceil_1.default)(total);
1106
+ };
1107
1107
  //# sourceMappingURL=index.js.map