addio-admin-sdk 1.7.193 → 1.7.195

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 (578) hide show
  1. package/.babelrc +17 -17
  2. package/.env.dev +14 -14
  3. package/.github/workflows/run_unit_test.yaml +48 -48
  4. package/.github/workflows/update_docs.yaml +32 -32
  5. package/addio-sdk-doc.md +1473 -1473
  6. package/changelog.md +582 -573
  7. package/dist/Interfaces/Address/index.d.ts +21 -21
  8. package/dist/Interfaces/Address/index.js +16 -16
  9. package/dist/Interfaces/Algolia/index.d.ts +182 -182
  10. package/dist/Interfaces/Algolia/index.js +2 -2
  11. package/dist/Interfaces/Attachement/index.d.ts +5 -5
  12. package/dist/Interfaces/Attachement/index.js +2 -2
  13. package/dist/Interfaces/Attribute/index.d.ts +53 -53
  14. package/dist/Interfaces/Attribute/index.js +10 -10
  15. package/dist/Interfaces/BGJob/index.d.ts +56 -56
  16. package/dist/Interfaces/BGJob/index.js +25 -25
  17. package/dist/Interfaces/BaseClass/index.d.ts +8 -8
  18. package/dist/Interfaces/BaseClass/index.js +2 -2
  19. package/dist/Interfaces/Blog/IBlogArticle.d.ts +18 -18
  20. package/dist/Interfaces/Blog/IBlogArticle.js +2 -2
  21. package/dist/Interfaces/Blog/IBlogAuthor.d.ts +7 -7
  22. package/dist/Interfaces/Blog/IBlogAuthor.js +2 -2
  23. package/dist/Interfaces/Blog/IBlogCategory.d.ts +9 -9
  24. package/dist/Interfaces/Blog/IBlogCategory.js +2 -2
  25. package/dist/Interfaces/Blog/IBlogComment.d.ts +13 -13
  26. package/dist/Interfaces/Blog/IBlogComment.js +2 -2
  27. package/dist/Interfaces/Blog/IBlogKeywords.d.ts +9 -9
  28. package/dist/Interfaces/Blog/IBlogKeywords.js +2 -2
  29. package/dist/Interfaces/Booking/index.d.ts +74 -74
  30. package/dist/Interfaces/Booking/index.js +17 -17
  31. package/dist/Interfaces/Brand/index.d.ts +15 -15
  32. package/dist/Interfaces/Brand/index.js +2 -2
  33. package/dist/Interfaces/Buylist/index.d.ts +19 -19
  34. package/dist/Interfaces/Buylist/index.js +2 -2
  35. package/dist/Interfaces/CMS/index.d.ts +28 -28
  36. package/dist/Interfaces/CMS/index.js +5 -5
  37. package/dist/Interfaces/Cart/IElavonPayload.d.ts +93 -93
  38. package/dist/Interfaces/Cart/IElavonPayload.js +17 -17
  39. package/dist/Interfaces/Cart/IMarketPayload.d.ts +12 -12
  40. package/dist/Interfaces/Cart/IMarketPayload.js +2 -2
  41. package/dist/Interfaces/Cart/IPandaPayload.d.ts +64 -64
  42. package/dist/Interfaces/Cart/IPandaPayload.js +18 -18
  43. package/dist/Interfaces/Cart/IPaymentCard.d.ts +22 -22
  44. package/dist/Interfaces/Cart/IPaymentCard.js +44 -44
  45. package/dist/Interfaces/Cart/IPaypalPayload.d.ts +9 -9
  46. package/dist/Interfaces/Cart/IPaypalPayload.js +2 -2
  47. package/dist/Interfaces/Cart/IPaysafePayload.d.ts +72 -72
  48. package/dist/Interfaces/Cart/IPaysafePayload.js +2 -2
  49. package/dist/Interfaces/Cart/IStripePayload.d.ts +66 -66
  50. package/dist/Interfaces/Cart/IStripePayload.js +2 -2
  51. package/dist/Interfaces/Cart/index.d.ts +471 -471
  52. package/dist/Interfaces/Cart/index.js +279 -279
  53. package/dist/Interfaces/CartReservedQuantities/index.d.ts +10 -10
  54. package/dist/Interfaces/CartReservedQuantities/index.js +2 -2
  55. package/dist/Interfaces/CashDrawers/index.d.ts +38 -38
  56. package/dist/Interfaces/CashDrawers/index.js +19 -19
  57. package/dist/Interfaces/Catalogue/index.d.ts +68 -68
  58. package/dist/Interfaces/Catalogue/index.js +37 -37
  59. package/dist/Interfaces/Category/index.d.ts +33 -33
  60. package/dist/Interfaces/Category/index.js +2 -2
  61. package/dist/Interfaces/Chart/index.d.ts +11 -11
  62. package/dist/Interfaces/Chart/index.js +2 -2
  63. package/dist/Interfaces/Class/index.d.ts +8 -8
  64. package/dist/Interfaces/Class/index.js +2 -2
  65. package/dist/Interfaces/Consent/index.d.ts +6 -6
  66. package/dist/Interfaces/Consent/index.js +2 -2
  67. package/dist/Interfaces/Context/IContextProps.d.ts +4 -4
  68. package/dist/Interfaces/Context/IContextProps.js +2 -2
  69. package/dist/Interfaces/Context/IContextState.d.ts +15 -15
  70. package/dist/Interfaces/Context/IContextState.js +2 -2
  71. package/dist/Interfaces/Customer/ICustomerBadge.d.ts +2 -2
  72. package/dist/Interfaces/Customer/ICustomerBadge.js +2 -2
  73. package/dist/Interfaces/Customer/ICustomerRating.d.ts +10 -10
  74. package/dist/Interfaces/Customer/ICustomerRating.js +2 -2
  75. package/dist/Interfaces/Customer/IStoreCredit.d.ts +13 -13
  76. package/dist/Interfaces/Customer/IStoreCredit.js +2 -2
  77. package/dist/Interfaces/Customer/index.d.ts +104 -104
  78. package/dist/Interfaces/Customer/index.js +148 -148
  79. package/dist/Interfaces/Declination/index.d.ts +117 -117
  80. package/dist/Interfaces/Declination/index.js +66 -66
  81. package/dist/Interfaces/Document/index.d.ts +8 -8
  82. package/dist/Interfaces/Document/index.js +2 -2
  83. package/dist/Interfaces/Elastic/index.d.ts +89 -89
  84. package/dist/Interfaces/Elastic/index.js +2 -2
  85. package/dist/Interfaces/Email/CustomGR/I3DPrintEmail.d.ts +11 -11
  86. package/dist/Interfaces/Email/CustomGR/I3DPrintEmail.js +2 -2
  87. package/dist/Interfaces/Email/CustomGR/IBorrowToolsEmail.d.ts +15 -15
  88. package/dist/Interfaces/Email/CustomGR/IBorrowToolsEmail.js +2 -2
  89. package/dist/Interfaces/Email/CustomGR/IPickupMaterialsEmail.d.ts +12 -12
  90. package/dist/Interfaces/Email/CustomGR/IPickupMaterialsEmail.js +2 -2
  91. package/dist/Interfaces/Email/CustomGR/IPreMeetingFormEmail.d.ts +36 -36
  92. package/dist/Interfaces/Email/CustomGR/IPreMeetingFormEmail.js +2 -2
  93. package/dist/Interfaces/Email/CustomGR/ISponsorRequestEmail.d.ts +12 -12
  94. package/dist/Interfaces/Email/CustomGR/ISponsorRequestEmail.js +2 -2
  95. package/dist/Interfaces/Email/CustomGR/ITransportEmail.d.ts +12 -12
  96. package/dist/Interfaces/Email/CustomGR/ITransportEmail.js +2 -2
  97. package/dist/Interfaces/Email/CustomGR/ITransportQuoteEmail.d.ts +12 -12
  98. package/dist/Interfaces/Email/CustomGR/ITransportQuoteEmail.js +2 -2
  99. package/dist/Interfaces/Email/CustomGR/IVegetalsEmail.d.ts +16 -16
  100. package/dist/Interfaces/Email/CustomGR/IVegetalsEmail.js +2 -2
  101. package/dist/Interfaces/Email/CustomGR/IWishlistEmail.d.ts +15 -15
  102. package/dist/Interfaces/Email/CustomGR/IWishlistEmail.js +2 -2
  103. package/dist/Interfaces/Email/IAbandonnedCartEmail.d.ts +29 -29
  104. package/dist/Interfaces/Email/IAbandonnedCartEmail.js +2 -2
  105. package/dist/Interfaces/Email/IAccountConfirmationEmail.d.ts +22 -22
  106. package/dist/Interfaces/Email/IAccountConfirmationEmail.js +2 -2
  107. package/dist/Interfaces/Email/IApplicationEmail.d.ts +19 -19
  108. package/dist/Interfaces/Email/IApplicationEmail.js +2 -2
  109. package/dist/Interfaces/Email/IBackInStockEmail.d.ts +21 -21
  110. package/dist/Interfaces/Email/IBackInStockEmail.js +2 -2
  111. package/dist/Interfaces/Email/IContactEmail.d.ts +20 -20
  112. package/dist/Interfaces/Email/IContactEmail.js +2 -2
  113. package/dist/Interfaces/Email/ICustomerBookingAdminEmail.d.ts +15 -15
  114. package/dist/Interfaces/Email/ICustomerBookingAdminEmail.js +2 -2
  115. package/dist/Interfaces/Email/ICustomerBookingEmail.d.ts +14 -14
  116. package/dist/Interfaces/Email/ICustomerBookingEmail.js +2 -2
  117. package/dist/Interfaces/Email/IEmail.d.ts +20 -20
  118. package/dist/Interfaces/Email/IEmail.js +46 -46
  119. package/dist/Interfaces/Email/IOrderConfirmationEmail.d.ts +47 -47
  120. package/dist/Interfaces/Email/IOrderConfirmationEmail.js +2 -2
  121. package/dist/Interfaces/Email/IPasswordResetEmail.d.ts +17 -17
  122. package/dist/Interfaces/Email/IPasswordResetEmail.js +2 -2
  123. package/dist/Interfaces/Email/IPhotoShootEmail.d.ts +14 -14
  124. package/dist/Interfaces/Email/IPhotoShootEmail.js +2 -2
  125. package/dist/Interfaces/Email/IPickupConfirmation.d.ts +23 -23
  126. package/dist/Interfaces/Email/IPickupConfirmation.js +2 -2
  127. package/dist/Interfaces/Email/IShippingConfirmation.d.ts +23 -23
  128. package/dist/Interfaces/Email/IShippingConfirmation.js +2 -2
  129. package/dist/Interfaces/Email/IWelcomeEmail.d.ts +19 -19
  130. package/dist/Interfaces/Email/IWelcomeEmail.js +2 -2
  131. package/dist/Interfaces/ExportSchema/index.d.ts +7 -7
  132. package/dist/Interfaces/ExportSchema/index.js +2 -2
  133. package/dist/Interfaces/ExternalService/BaseExternalService.d.ts +12 -12
  134. package/dist/Interfaces/ExternalService/BaseExternalService.js +2 -2
  135. package/dist/Interfaces/ExternalService/ExternalProductsService.d.ts +4 -4
  136. package/dist/Interfaces/ExternalService/ExternalProductsService.js +2 -2
  137. package/dist/Interfaces/ExternalService/index.d.ts +9 -9
  138. package/dist/Interfaces/ExternalService/index.js +2 -2
  139. package/dist/Interfaces/FirstOrderTracking/index.d.ts +5 -5
  140. package/dist/Interfaces/FirstOrderTracking/index.js +2 -2
  141. package/dist/Interfaces/G2/index.d.ts +557 -557
  142. package/dist/Interfaces/G2/index.js +39 -39
  143. package/dist/Interfaces/Indexed/Product/IIndexedLastSavedProduct.d.ts +20 -20
  144. package/dist/Interfaces/Indexed/Product/IIndexedLastSavedProduct.js +2 -2
  145. package/dist/Interfaces/Indexed/Product/index.d.ts +111 -111
  146. package/dist/Interfaces/Indexed/Product/index.js +302 -302
  147. package/dist/Interfaces/Inventory/index.d.ts +19 -19
  148. package/dist/Interfaces/Inventory/index.js +8 -8
  149. package/dist/Interfaces/Invoice/index.d.ts +4 -4
  150. package/dist/Interfaces/Invoice/index.js +2 -2
  151. package/dist/Interfaces/MarketplacePublication/MarketplaceOrderData.d.ts +3 -3
  152. package/dist/Interfaces/MarketplacePublication/MarketplaceOrderData.js +2 -2
  153. package/dist/Interfaces/MarketplacePublication/index.d.ts +23 -23
  154. package/dist/Interfaces/MarketplacePublication/index.js +22 -22
  155. package/dist/Interfaces/Menu/index.d.ts +40 -40
  156. package/dist/Interfaces/Menu/index.js +16 -16
  157. package/dist/Interfaces/Note/index.d.ts +10 -10
  158. package/dist/Interfaces/Note/index.js +7 -7
  159. package/dist/Interfaces/Operations/ICreatedBy.d.ts +6 -6
  160. package/dist/Interfaces/Operations/ICreatedBy.js +2 -2
  161. package/dist/Interfaces/Operations/IUpdate.d.ts +5 -5
  162. package/dist/Interfaces/Operations/IUpdate.js +2 -2
  163. package/dist/Interfaces/Order/index.d.ts +4 -4
  164. package/dist/Interfaces/Order/index.js +2 -2
  165. package/dist/Interfaces/Org/IRelUser.d.ts +9 -9
  166. package/dist/Interfaces/Org/IRelUser.js +2 -2
  167. package/dist/Interfaces/Org/index.d.ts +29 -29
  168. package/dist/Interfaces/Org/index.js +12 -12
  169. package/dist/Interfaces/Payment/index.d.ts +26 -26
  170. package/dist/Interfaces/Payment/index.js +14 -14
  171. package/dist/Interfaces/Product/IAttributeFamily.d.ts +6 -6
  172. package/dist/Interfaces/Product/IAttributeFamily.js +2 -2
  173. package/dist/Interfaces/Product/IImportProduct.d.ts +42 -42
  174. package/dist/Interfaces/Product/IImportProduct.js +882 -882
  175. package/dist/Interfaces/Product/IInventoryItem.d.ts +74 -74
  176. package/dist/Interfaces/Product/IInventoryItem.js +38 -38
  177. package/dist/Interfaces/Product/IPricing.d.ts +177 -177
  178. package/dist/Interfaces/Product/IPricing.js +180 -180
  179. package/dist/Interfaces/Product/index.d.ts +137 -137
  180. package/dist/Interfaces/Product/index.js +64 -64
  181. package/dist/Interfaces/ProductAttribute/index.d.ts +11 -11
  182. package/dist/Interfaces/ProductAttribute/index.js +2 -2
  183. package/dist/Interfaces/PromiseToPurchase/BankType.d.ts +41 -41
  184. package/dist/Interfaces/PromiseToPurchase/BankType.js +41 -41
  185. package/dist/Interfaces/PromiseToPurchase/IIndexedBankUsed.d.ts +33 -33
  186. package/dist/Interfaces/PromiseToPurchase/IIndexedBankUsed.js +15 -15
  187. package/dist/Interfaces/PromiseToPurchase/IIndexedCustomerPromiseToPurchase.d.ts +19 -19
  188. package/dist/Interfaces/PromiseToPurchase/IIndexedCustomerPromiseToPurchase.js +2 -2
  189. package/dist/Interfaces/PromiseToPurchase/index.d.ts +50 -50
  190. package/dist/Interfaces/PromiseToPurchase/index.js +13 -13
  191. package/dist/Interfaces/PurchaseOrder/index.d.ts +17 -17
  192. package/dist/Interfaces/PurchaseOrder/index.js +2 -2
  193. package/dist/Interfaces/Query/IBrandQueryOptions.d.ts +11 -11
  194. package/dist/Interfaces/Query/IBrandQueryOptions.js +2 -2
  195. package/dist/Interfaces/Query/ICategoryQueryOptions.d.ts +11 -11
  196. package/dist/Interfaces/Query/ICategoryQueryOptions.js +2 -2
  197. package/dist/Interfaces/Query/IProductQueryOptions.d.ts +16 -16
  198. package/dist/Interfaces/Query/IProductQueryOptions.js +2 -2
  199. package/dist/Interfaces/Quote/index.d.ts +5 -5
  200. package/dist/Interfaces/Quote/index.js +2 -2
  201. package/dist/Interfaces/Refunds/index.d.ts +106 -106
  202. package/dist/Interfaces/Refunds/index.js +2 -2
  203. package/dist/Interfaces/Rules/IDiscountRule.d.ts +156 -156
  204. package/dist/Interfaces/Rules/IDiscountRule.js +114 -114
  205. package/dist/Interfaces/Schedule/index.d.ts +48 -48
  206. package/dist/Interfaces/Schedule/index.js +2 -2
  207. package/dist/Interfaces/Services/IAddServiceResponse.d.ts +4 -4
  208. package/dist/Interfaces/Services/IAddServiceResponse.js +2 -2
  209. package/dist/Interfaces/Services/IService.d.ts +16 -16
  210. package/dist/Interfaces/Services/IService.js +2 -2
  211. package/dist/Interfaces/Services/IServiceSecret.d.ts +8 -8
  212. package/dist/Interfaces/Services/IServiceSecret.js +2 -2
  213. package/dist/Interfaces/Shipping/Shipstation/carriers.d.ts +10 -10
  214. package/dist/Interfaces/Shipping/Shipstation/carriers.js +2 -2
  215. package/dist/Interfaces/Shipping/Shipstation/order.d.ts +227 -227
  216. package/dist/Interfaces/Shipping/Shipstation/order.js +2 -2
  217. package/dist/Interfaces/Shipping/Shipstation/quote.d.ts +31 -31
  218. package/dist/Interfaces/Shipping/Shipstation/quote.js +2 -2
  219. package/dist/Interfaces/Shipping/Shiptime/order.d.ts +54 -54
  220. package/dist/Interfaces/Shipping/Shiptime/order.js +71 -71
  221. package/dist/Interfaces/Shipping/Shiptime/quote.d.ts +111 -111
  222. package/dist/Interfaces/Shipping/Shiptime/quote.js +2 -2
  223. package/dist/Interfaces/Slider/GR.d.ts +114 -114
  224. package/dist/Interfaces/Slider/GR.js +271 -271
  225. package/dist/Interfaces/Slider/index.d.ts +30 -30
  226. package/dist/Interfaces/Slider/index.js +2 -2
  227. package/dist/Interfaces/Space/IExternalService.d.ts +54 -54
  228. package/dist/Interfaces/Space/IExternalService.js +45 -45
  229. package/dist/Interfaces/Space/IMember.d.ts +16 -16
  230. package/dist/Interfaces/Space/IMember.js +9 -9
  231. package/dist/Interfaces/Space/index.d.ts +414 -414
  232. package/dist/Interfaces/Space/index.js +176 -176
  233. package/dist/Interfaces/Specials/gr.d.ts +61 -61
  234. package/dist/Interfaces/Specials/gr.js +2 -2
  235. package/dist/Interfaces/StockNotification/index.d.ts +7 -7
  236. package/dist/Interfaces/StockNotification/index.js +2 -2
  237. package/dist/Interfaces/Store/index.d.ts +63 -63
  238. package/dist/Interfaces/Store/index.js +27 -27
  239. package/dist/Interfaces/Supplier/ICommand.d.ts +11 -11
  240. package/dist/Interfaces/Supplier/ICommand.js +2 -2
  241. package/dist/Interfaces/Supplier/index.d.ts +36 -36
  242. package/dist/Interfaces/Supplier/index.js +24 -24
  243. package/dist/Interfaces/TCG/index.d.ts +200 -200
  244. package/dist/Interfaces/TCG/index.js +59 -59
  245. package/dist/Interfaces/Tag/index.d.ts +18 -18
  246. package/dist/Interfaces/Tag/index.js +2 -2
  247. package/dist/Interfaces/Tax/index.d.ts +13 -13
  248. package/dist/Interfaces/Tax/index.js +2 -2
  249. package/dist/Interfaces/TransferRequest/index.d.ts +103 -103
  250. package/dist/Interfaces/TransferRequest/index.js +46 -46
  251. package/dist/Interfaces/Translation/index.d.ts +8 -8
  252. package/dist/Interfaces/Translation/index.js +5 -5
  253. package/dist/Interfaces/Update/index.d.ts +10 -10
  254. package/dist/Interfaces/Update/index.js +2 -2
  255. package/dist/Interfaces/User/IUser.d.ts +65 -65
  256. package/dist/Interfaces/User/IUser.js +8 -8
  257. package/dist/Interfaces/Version/index.d.ts +11 -11
  258. package/dist/Interfaces/Version/index.js +2 -2
  259. package/dist/Interfaces/Wishlist/index.d.ts +7 -7
  260. package/dist/Interfaces/Wishlist/index.js +2 -2
  261. package/dist/constants/Interfaces/IBaseApi.d.ts +15 -15
  262. package/dist/constants/Interfaces/IBaseApi.js +2 -2
  263. package/dist/constants/Interfaces/IEndpointResult.d.ts +9 -9
  264. package/dist/constants/Interfaces/IEndpointResult.js +2 -2
  265. package/dist/constants/enums.d.ts +6 -6
  266. package/dist/constants/enums.js +10 -10
  267. package/dist/constants/services.d.ts +2 -2
  268. package/dist/constants/services.js +122 -122
  269. package/dist/constants/version.d.ts +2 -2
  270. package/dist/constants/version.js +5 -5
  271. package/dist/index.d.ts +50 -50
  272. package/dist/index.js +266 -266
  273. package/dist/lib/Attribute/index.d.ts +14 -14
  274. package/dist/lib/Attribute/index.js +186 -186
  275. package/dist/lib/BGJob/index.d.ts +9 -9
  276. package/dist/lib/BGJob/index.js +216 -216
  277. package/dist/lib/BackgroundWorker/index.d.ts +34 -34
  278. package/dist/lib/BackgroundWorker/index.js +59 -59
  279. package/dist/lib/Blog/BlogArticle.d.ts +5 -5
  280. package/dist/lib/Blog/BlogArticle.js +10 -10
  281. package/dist/lib/Blog/BlogAuthor.d.ts +5 -5
  282. package/dist/lib/Blog/BlogAuthor.js +10 -10
  283. package/dist/lib/Blog/BlogCategory.d.ts +5 -5
  284. package/dist/lib/Blog/BlogCategory.js +10 -10
  285. package/dist/lib/Blog/BlogKeyword.d.ts +5 -5
  286. package/dist/lib/Blog/BlogKeyword.js +10 -10
  287. package/dist/lib/Booking/index.d.ts +85 -85
  288. package/dist/lib/Booking/index.js +596 -596
  289. package/dist/lib/Brand/index.d.ts +26 -26
  290. package/dist/lib/Brand/index.js +131 -131
  291. package/dist/lib/Cart/index.d.ts +357 -357
  292. package/dist/lib/Cart/index.js +4052 -4062
  293. package/dist/lib/Cart/index.js.map +1 -1
  294. package/dist/lib/CartReservedQuantities/index.d.ts +49 -49
  295. package/dist/lib/CartReservedQuantities/index.js +159 -159
  296. package/dist/lib/CashDrawerShift/index.d.ts +84 -84
  297. package/dist/lib/CashDrawerShift/index.js +206 -206
  298. package/dist/lib/Catalogue/index.d.ts +15 -15
  299. package/dist/lib/Catalogue/index.js +78 -78
  300. package/dist/lib/Category/index.d.ts +34 -34
  301. package/dist/lib/Category/index.js +230 -230
  302. package/dist/lib/Class/index.d.ts +16 -16
  303. package/dist/lib/Class/index.js +66 -66
  304. package/dist/lib/Consent/index.d.ts +4 -4
  305. package/dist/lib/Consent/index.js +29 -29
  306. package/dist/lib/Customer/index.d.ts +30 -30
  307. package/dist/lib/Customer/index.js +92 -92
  308. package/dist/lib/Declination/index.d.ts +9 -9
  309. package/dist/lib/Declination/index.js +26 -26
  310. package/dist/lib/Discount/index.d.ts +27 -27
  311. package/dist/lib/Discount/index.js +493 -493
  312. package/dist/lib/ElasticSearch/index.d.ts +13 -13
  313. package/dist/lib/ElasticSearch/index.js +50 -50
  314. package/dist/lib/Elavon/index.d.ts +18 -18
  315. package/dist/lib/Elavon/index.js +135 -135
  316. package/dist/lib/Email/AbandonedCartEmail.d.ts +16 -16
  317. package/dist/lib/Email/AbandonedCartEmail.js +24 -24
  318. package/dist/lib/Email/AccountConfirmationEmail.d.ts +19 -19
  319. package/dist/lib/Email/AccountConfirmationEmail.js +30 -30
  320. package/dist/lib/Email/AdminOrderConfirmationEmail.d.ts +16 -16
  321. package/dist/lib/Email/AdminOrderConfirmationEmail.js +24 -24
  322. package/dist/lib/Email/ApplicationEmail.d.ts +16 -16
  323. package/dist/lib/Email/ApplicationEmail.js +24 -24
  324. package/dist/lib/Email/BackInStockEmail.d.ts +16 -16
  325. package/dist/lib/Email/BackInStockEmail.js +24 -24
  326. package/dist/lib/Email/ContactEmail.d.ts +16 -16
  327. package/dist/lib/Email/ContactEmail.js +24 -24
  328. package/dist/lib/Email/CustomerBookingAdminEmail.d.ts +16 -16
  329. package/dist/lib/Email/CustomerBookingAdminEmail.js +24 -24
  330. package/dist/lib/Email/CustomerBookingEmail.d.ts +16 -16
  331. package/dist/lib/Email/CustomerBookingEmail.js +24 -24
  332. package/dist/lib/Email/OrderConfirmationEmail.d.ts +16 -16
  333. package/dist/lib/Email/OrderConfirmationEmail.js +24 -24
  334. package/dist/lib/Email/OrderDenounciationEmail.d.ts +16 -16
  335. package/dist/lib/Email/OrderDenounciationEmail.js +24 -24
  336. package/dist/lib/Email/OrderSampleEmail.d.ts +16 -16
  337. package/dist/lib/Email/OrderSampleEmail.js +24 -24
  338. package/dist/lib/Email/OtherTypeEmails.d.ts +16 -16
  339. package/dist/lib/Email/OtherTypeEmails.js +27 -27
  340. package/dist/lib/Email/PasswordResetEmail.d.ts +16 -16
  341. package/dist/lib/Email/PasswordResetEmail.js +24 -24
  342. package/dist/lib/Email/PhotoShootEmail.d.ts +16 -16
  343. package/dist/lib/Email/PhotoShootEmail.js +24 -24
  344. package/dist/lib/Email/PickUpConfirmation.d.ts +16 -16
  345. package/dist/lib/Email/PickUpConfirmation.js +24 -24
  346. package/dist/lib/Email/ShippingConfirmation.d.ts +16 -16
  347. package/dist/lib/Email/ShippingConfirmation.js +24 -24
  348. package/dist/lib/Email/WelcomeEmail.d.ts +16 -16
  349. package/dist/lib/Email/WelcomeEmail.js +24 -24
  350. package/dist/lib/Email/index.d.ts +16 -16
  351. package/dist/lib/Email/index.js +31 -31
  352. package/dist/lib/ExternalService/Ebay.d.ts +74 -74
  353. package/dist/lib/ExternalService/Ebay.js +124 -124
  354. package/dist/lib/ExternalService/index.d.ts +5 -5
  355. package/dist/lib/ExternalService/index.js +10 -10
  356. package/dist/lib/FirstOrderTracking/index.d.ts +5 -5
  357. package/dist/lib/FirstOrderTracking/index.js +10 -10
  358. package/dist/lib/Indexed/IndexedCart.d.ts +13 -13
  359. package/dist/lib/Indexed/IndexedCart.js +91 -91
  360. package/dist/lib/Indexed/Product.d.ts +17 -17
  361. package/dist/lib/Indexed/Product.js +98 -98
  362. package/dist/lib/Inventory/index.d.ts +131 -131
  363. package/dist/lib/Inventory/index.js +545 -545
  364. package/dist/lib/Invoice/index.d.ts +16 -16
  365. package/dist/lib/Invoice/index.js +21 -21
  366. package/dist/lib/MarketplacePublication/index.d.ts +9 -9
  367. package/dist/lib/MarketplacePublication/index.js +426 -426
  368. package/dist/lib/Menu/index.d.ts +11 -11
  369. package/dist/lib/Menu/index.js +107 -107
  370. package/dist/lib/MongoDB/BaseAPI.d.ts +18 -18
  371. package/dist/lib/MongoDB/BaseAPI.js +200 -200
  372. package/dist/lib/Note/index.d.ts +4 -4
  373. package/dist/lib/Note/index.js +6 -6
  374. package/dist/lib/Order/index.d.ts +27 -27
  375. package/dist/lib/Order/index.js +56 -56
  376. package/dist/lib/Org/index.d.ts +68 -68
  377. package/dist/lib/Org/index.js +216 -216
  378. package/dist/lib/PandaPay/index.d.ts +16 -16
  379. package/dist/lib/PandaPay/index.js +176 -176
  380. package/dist/lib/Paysafe/index.d.ts +11 -11
  381. package/dist/lib/Paysafe/index.js +41 -41
  382. package/dist/lib/Product/index.d.ts +182 -182
  383. package/dist/lib/Product/index.js +847 -847
  384. package/dist/lib/ProductAttribute/index.d.ts +15 -15
  385. package/dist/lib/ProductAttribute/index.js +45 -45
  386. package/dist/lib/PromiseToPurchase/index.d.ts +109 -109
  387. package/dist/lib/PromiseToPurchase/index.js +343 -343
  388. package/dist/lib/PurchaseOrder/index.d.ts +20 -20
  389. package/dist/lib/PurchaseOrder/index.js +28 -28
  390. package/dist/lib/Schedule/index.d.ts +5 -5
  391. package/dist/lib/Schedule/index.js +12 -12
  392. package/dist/lib/Service/Enum/ServiceEnum.d.ts +3 -3
  393. package/dist/lib/Service/Enum/ServiceEnum.js +7 -7
  394. package/dist/lib/Service/index.d.ts +13 -13
  395. package/dist/lib/Service/index.js +21 -21
  396. package/dist/lib/Shipment/index.d.ts +28 -28
  397. package/dist/lib/Shipment/index.js +370 -370
  398. package/dist/lib/Slider/index.d.ts +22 -22
  399. package/dist/lib/Slider/index.js +119 -119
  400. package/dist/lib/Space/index.d.ts +1181 -1181
  401. package/dist/lib/Space/index.js +5841 -5841
  402. package/dist/lib/StockNotification/index.d.ts +4 -4
  403. package/dist/lib/StockNotification/index.js +6 -6
  404. package/dist/lib/Store/index.d.ts +5 -5
  405. package/dist/lib/Store/index.js +12 -12
  406. package/dist/lib/Supplier/Command.d.ts +5 -5
  407. package/dist/lib/Supplier/Command.js +10 -10
  408. package/dist/lib/Supplier/index.d.ts +25 -25
  409. package/dist/lib/Supplier/index.js +27 -27
  410. package/dist/lib/Tags/index.d.ts +6 -6
  411. package/dist/lib/Tags/index.js +26 -26
  412. package/dist/lib/Tax/index.d.ts +8 -8
  413. package/dist/lib/Tax/index.js +54 -54
  414. package/dist/lib/TransferRequest/index.d.ts +298 -298
  415. package/dist/lib/TransferRequest/index.js +1106 -1106
  416. package/dist/lib/Update/index.d.ts +10 -10
  417. package/dist/lib/Update/index.js +22 -22
  418. package/dist/lib/User/index.d.ts +89 -89
  419. package/dist/lib/User/index.js +328 -328
  420. package/dist/lib/Wishlist/index.d.ts +5 -5
  421. package/dist/lib/Wishlist/index.js +10 -10
  422. package/dist/lib/base.d.ts +14 -14
  423. package/dist/lib/base.js +62 -62
  424. package/dist/lib/baseService.d.ts +17 -17
  425. package/dist/lib/baseService.js +69 -69
  426. package/dist/rules/ADD/utils/buyback.d.ts +4 -4
  427. package/dist/rules/ADD/utils/buyback.js +135 -135
  428. package/dist/rules/GR/constants/data.d.ts +26 -26
  429. package/dist/rules/GR/constants/data.js +81 -81
  430. package/dist/rules/GR/constants/expedition.d.ts +4 -4
  431. package/dist/rules/GR/constants/expedition.js +9 -9
  432. package/dist/rules/GR/constants/products.d.ts +22 -22
  433. package/dist/rules/GR/constants/products.js +263 -263
  434. package/dist/rules/GR/interfaces/cart.d.ts +84 -84
  435. package/dist/rules/GR/interfaces/cart.js +41 -41
  436. package/dist/rules/GR/interfaces/data.d.ts +101 -101
  437. package/dist/rules/GR/interfaces/data.js +114 -114
  438. package/dist/rules/GR/interfaces/products.d.ts +61 -61
  439. package/dist/rules/GR/interfaces/products.js +10 -10
  440. package/dist/rules/GR/utils/cart.d.ts +95 -95
  441. package/dist/rules/GR/utils/cart.js +839 -839
  442. package/dist/rules/GR/utils/data.d.ts +3 -3
  443. package/dist/rules/GR/utils/data.js +28 -28
  444. package/dist/rules/GR/utils/expedition.d.ts +140 -140
  445. package/dist/rules/GR/utils/expedition.js +2017 -2017
  446. package/dist/rules/GR/utils/g2.d.ts +209 -209
  447. package/dist/rules/GR/utils/g2.js +1002 -1002
  448. package/dist/rules/GR/utils/invoices.d.ts +51 -51
  449. package/dist/rules/GR/utils/invoices.js +215 -215
  450. package/dist/rules/GR/utils/products.d.ts +277 -277
  451. package/dist/rules/GR/utils/products.js +1350 -1350
  452. package/dist/rules/GR/utils/upsells.d.ts +111 -111
  453. package/dist/rules/GR/utils/upsells.js +215 -215
  454. package/dist/services/database/BaseProvider.d.ts +29 -29
  455. package/dist/services/database/BaseProvider.js +28 -28
  456. package/dist/services/database/BatchUtils.d.ts +14 -14
  457. package/dist/services/database/BatchUtils.js +43 -43
  458. package/dist/services/database/Config.d.ts +2 -2
  459. package/dist/services/database/Config.js +5 -5
  460. package/dist/services/database/DatabaseService.d.ts +125 -125
  461. package/dist/services/database/DatabaseService.js +237 -237
  462. package/dist/services/database/FirebaseProvider.d.ts +17 -17
  463. package/dist/services/database/FirebaseProvider.js +235 -235
  464. package/dist/services/database/NotFirebaseProvider.d.ts +49 -49
  465. package/dist/services/database/NotFirebaseProvider.js +262 -262
  466. package/dist/services/g2/G2OrderSlip.d.ts +49 -49
  467. package/dist/services/g2/G2OrderSlip.js +228 -228
  468. package/dist/services/g2/utils.d.ts +19 -19
  469. package/dist/services/g2/utils.js +968 -968
  470. package/dist/services/logs/index.d.ts +23 -23
  471. package/dist/services/logs/index.js +66 -66
  472. package/dist/services/marketplace/BaseMarketServiceClass.d.ts +78 -78
  473. package/dist/services/marketplace/BaseMarketServiceClass.js +141 -141
  474. package/dist/services/marketplace/CardtraderServiceClass.d.ts +38 -38
  475. package/dist/services/marketplace/CardtraderServiceClass.js +226 -226
  476. package/dist/services/marketplace/utils.d.ts +17 -17
  477. package/dist/services/marketplace/utils.js +32 -32
  478. package/dist/services/products/BaseClass.d.ts +79 -79
  479. package/dist/services/products/BaseClass.js +144 -144
  480. package/dist/services/products/TCGService.d.ts +29 -29
  481. package/dist/services/products/TCGService.js +503 -503
  482. package/dist/services/products/utils.d.ts +31 -31
  483. package/dist/services/products/utils.js +144 -144
  484. package/dist/utils/algolia.d.ts +46 -46
  485. package/dist/utils/algolia.js +21 -21
  486. package/dist/utils/anonymisation.d.ts +54 -54
  487. package/dist/utils/anonymisation.js +280 -280
  488. package/dist/utils/array.d.ts +5 -5
  489. package/dist/utils/array.js +14 -14
  490. package/dist/utils/aws.d.ts +36 -36
  491. package/dist/utils/aws.js +154 -154
  492. package/dist/utils/booking.d.ts +30 -30
  493. package/dist/utils/booking.js +127 -127
  494. package/dist/utils/cart.d.ts +274 -274
  495. package/dist/utils/cart.js +1143 -1143
  496. package/dist/utils/categories.d.ts +2 -2
  497. package/dist/utils/categories.js +54 -54
  498. package/dist/utils/cmv.d.ts +12 -12
  499. package/dist/utils/cmv.js +108 -108
  500. package/dist/utils/console.d.ts +6 -6
  501. package/dist/utils/console.js +59 -59
  502. package/dist/utils/context.d.ts +20 -20
  503. package/dist/utils/context.js +61 -61
  504. package/dist/utils/currency.d.ts +6 -6
  505. package/dist/utils/currency.js +91 -91
  506. package/dist/utils/data.d.ts +31 -31
  507. package/dist/utils/data.js +302 -302
  508. package/dist/utils/date.d.ts +1 -1
  509. package/dist/utils/date.js +16 -16
  510. package/dist/utils/dimensions.d.ts +3 -3
  511. package/dist/utils/dimensions.js +16 -16
  512. package/dist/utils/discount.d.ts +192 -192
  513. package/dist/utils/discount.js +1180 -1180
  514. package/dist/utils/errors.d.ts +133 -133
  515. package/dist/utils/errors.js +171 -171
  516. package/dist/utils/file-admin.d.ts +8 -8
  517. package/dist/utils/file-admin.js +39 -39
  518. package/dist/utils/file.d.ts +39 -39
  519. package/dist/utils/file.js +208 -208
  520. package/dist/utils/firebase-admin.d.ts +11 -11
  521. package/dist/utils/firebase-admin.js +73 -73
  522. package/dist/utils/firebase.d.ts +58 -58
  523. package/dist/utils/firebase.js +148 -148
  524. package/dist/utils/import.d.ts +1 -1
  525. package/dist/utils/import.js +21 -21
  526. package/dist/utils/inventories.d.ts +101 -101
  527. package/dist/utils/inventories.js +467 -467
  528. package/dist/utils/locale.d.ts +24 -24
  529. package/dist/utils/locale.js +91 -91
  530. package/dist/utils/mailchimp.d.ts +58 -58
  531. package/dist/utils/mailchimp.js +531 -531
  532. package/dist/utils/mathUtils.d.ts +17 -17
  533. package/dist/utils/mathUtils.js +324 -324
  534. package/dist/utils/mongodb.d.ts +1 -1
  535. package/dist/utils/mongodb.js +22 -22
  536. package/dist/utils/object.d.ts +32 -32
  537. package/dist/utils/object.js +133 -133
  538. package/dist/utils/payment.d.ts +10 -10
  539. package/dist/utils/payment.js +23 -23
  540. package/dist/utils/products.d.ts +47 -47
  541. package/dist/utils/products.js +214 -214
  542. package/dist/utils/products.js.map +1 -1
  543. package/dist/utils/promiseToPurchase.d.ts +121 -121
  544. package/dist/utils/promiseToPurchase.js +329 -329
  545. package/dist/utils/prosprsearch.d.ts +42 -42
  546. package/dist/utils/prosprsearch.js +216 -216
  547. package/dist/utils/refunds.d.ts +2 -2
  548. package/dist/utils/refunds.js +21 -21
  549. package/dist/utils/sdc.d.ts +10 -10
  550. package/dist/utils/sdc.js +1309 -1309
  551. package/dist/utils/searchIndexes.d.ts +58 -58
  552. package/dist/utils/searchIndexes.js +247 -247
  553. package/dist/utils/services.d.ts +44 -44
  554. package/dist/utils/services.js +415 -415
  555. package/dist/utils/shipment.d.ts +110 -110
  556. package/dist/utils/shipment.js +345 -345
  557. package/dist/utils/simpletexting.d.ts +2 -2
  558. package/dist/utils/simpletexting.js +45 -45
  559. package/dist/utils/sliders.d.ts +4 -4
  560. package/dist/utils/sliders.js +24 -24
  561. package/dist/utils/string.d.ts +16 -16
  562. package/dist/utils/string.js +192 -192
  563. package/dist/utils/tcgService.d.ts +98 -98
  564. package/dist/utils/tcgService.js +425 -425
  565. package/dist/utils/tools.d.ts +5 -5
  566. package/dist/utils/tools.js +13 -13
  567. package/dist/utils/transferRequests.d.ts +43 -43
  568. package/dist/utils/transferRequests.js +67 -67
  569. package/dist/utils/update.d.ts +7 -7
  570. package/dist/utils/update.js +137 -137
  571. package/dist/utils/weight.d.ts +3 -3
  572. package/dist/utils/weight.js +16 -16
  573. package/dist/utils/zones.d.ts +11 -11
  574. package/dist/utils/zones.js +218 -218
  575. package/package.json +107 -107
  576. package/publish.sh +143 -143
  577. package/readme.md +182 -182
  578. package/.env +0 -14
@@ -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