addio-admin-sdk 1.6.5

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 (854) hide show
  1. package/.babelrc +17 -0
  2. package/.env.dev +15 -0
  3. package/.github/workflows/publish_coverage.yaml +69 -0
  4. package/addio-sdk-doc.md +1380 -0
  5. package/changelog.md +353 -0
  6. package/dist/Interfaces/Address/index.d.ts +21 -0
  7. package/dist/Interfaces/Address/index.js +17 -0
  8. package/dist/Interfaces/Address/index.js.map +1 -0
  9. package/dist/Interfaces/Algolia/index.d.ts +145 -0
  10. package/dist/Interfaces/Algolia/index.js +3 -0
  11. package/dist/Interfaces/Algolia/index.js.map +1 -0
  12. package/dist/Interfaces/Attachement/index.d.ts +5 -0
  13. package/dist/Interfaces/Attachement/index.js +3 -0
  14. package/dist/Interfaces/Attachement/index.js.map +1 -0
  15. package/dist/Interfaces/Attribute/index.d.ts +47 -0
  16. package/dist/Interfaces/Attribute/index.js +11 -0
  17. package/dist/Interfaces/Attribute/index.js.map +1 -0
  18. package/dist/Interfaces/BGJob/index.d.ts +56 -0
  19. package/dist/Interfaces/BGJob/index.js +37 -0
  20. package/dist/Interfaces/BGJob/index.js.map +1 -0
  21. package/dist/Interfaces/BaseClass/index.d.ts +8 -0
  22. package/dist/Interfaces/BaseClass/index.js +3 -0
  23. package/dist/Interfaces/BaseClass/index.js.map +1 -0
  24. package/dist/Interfaces/Blog/IBlogArticle.d.ts +18 -0
  25. package/dist/Interfaces/Blog/IBlogArticle.js +3 -0
  26. package/dist/Interfaces/Blog/IBlogArticle.js.map +1 -0
  27. package/dist/Interfaces/Blog/IBlogAuthor.d.ts +7 -0
  28. package/dist/Interfaces/Blog/IBlogAuthor.js +3 -0
  29. package/dist/Interfaces/Blog/IBlogAuthor.js.map +1 -0
  30. package/dist/Interfaces/Blog/IBlogCategory.d.ts +9 -0
  31. package/dist/Interfaces/Blog/IBlogCategory.js +3 -0
  32. package/dist/Interfaces/Blog/IBlogCategory.js.map +1 -0
  33. package/dist/Interfaces/Blog/IBlogComment.d.ts +13 -0
  34. package/dist/Interfaces/Blog/IBlogComment.js +3 -0
  35. package/dist/Interfaces/Blog/IBlogComment.js.map +1 -0
  36. package/dist/Interfaces/Blog/IBlogKeywords.d.ts +9 -0
  37. package/dist/Interfaces/Blog/IBlogKeywords.js +3 -0
  38. package/dist/Interfaces/Blog/IBlogKeywords.js.map +1 -0
  39. package/dist/Interfaces/Booking/index.d.ts +68 -0
  40. package/dist/Interfaces/Booking/index.js +18 -0
  41. package/dist/Interfaces/Booking/index.js.map +1 -0
  42. package/dist/Interfaces/Brand/index.d.ts +13 -0
  43. package/dist/Interfaces/Brand/index.js +3 -0
  44. package/dist/Interfaces/Brand/index.js.map +1 -0
  45. package/dist/Interfaces/CMS/Creator/index.d.ts +12 -0
  46. package/dist/Interfaces/CMS/Creator/index.js +3 -0
  47. package/dist/Interfaces/CMS/Creator/index.js.map +1 -0
  48. package/dist/Interfaces/CMS/Reader/index.d.ts +47 -0
  49. package/dist/Interfaces/CMS/Reader/index.js +3 -0
  50. package/dist/Interfaces/CMS/Reader/index.js.map +1 -0
  51. package/dist/Interfaces/CMS/index.d.ts +25 -0
  52. package/dist/Interfaces/CMS/index.js +3 -0
  53. package/dist/Interfaces/CMS/index.js.map +1 -0
  54. package/dist/Interfaces/Cart/IPandaPayload.d.ts +64 -0
  55. package/dist/Interfaces/Cart/IPandaPayload.js +19 -0
  56. package/dist/Interfaces/Cart/IPandaPayload.js.map +1 -0
  57. package/dist/Interfaces/Cart/IPaymentCard.d.ts +22 -0
  58. package/dist/Interfaces/Cart/IPaymentCard.js +45 -0
  59. package/dist/Interfaces/Cart/IPaymentCard.js.map +1 -0
  60. package/dist/Interfaces/Cart/IPaypalPayload.d.ts +9 -0
  61. package/dist/Interfaces/Cart/IPaypalPayload.js +3 -0
  62. package/dist/Interfaces/Cart/IPaypalPayload.js.map +1 -0
  63. package/dist/Interfaces/Cart/IPaysafePayload.d.ts +72 -0
  64. package/dist/Interfaces/Cart/IPaysafePayload.js +3 -0
  65. package/dist/Interfaces/Cart/IPaysafePayload.js.map +1 -0
  66. package/dist/Interfaces/Cart/IStripePayload.d.ts +66 -0
  67. package/dist/Interfaces/Cart/IStripePayload.js +3 -0
  68. package/dist/Interfaces/Cart/IStripePayload.js.map +1 -0
  69. package/dist/Interfaces/Cart/index.d.ts +395 -0
  70. package/dist/Interfaces/Cart/index.js +182 -0
  71. package/dist/Interfaces/Cart/index.js.map +1 -0
  72. package/dist/Interfaces/Catalogue/index.d.ts +68 -0
  73. package/dist/Interfaces/Catalogue/index.js +38 -0
  74. package/dist/Interfaces/Catalogue/index.js.map +1 -0
  75. package/dist/Interfaces/Category/index.d.ts +26 -0
  76. package/dist/Interfaces/Category/index.js +3 -0
  77. package/dist/Interfaces/Category/index.js.map +1 -0
  78. package/dist/Interfaces/Chart/index.d.ts +11 -0
  79. package/dist/Interfaces/Chart/index.js +3 -0
  80. package/dist/Interfaces/Chart/index.js.map +1 -0
  81. package/dist/Interfaces/Class/index.d.ts +8 -0
  82. package/dist/Interfaces/Class/index.js +3 -0
  83. package/dist/Interfaces/Class/index.js.map +1 -0
  84. package/dist/Interfaces/Consent/index.d.ts +6 -0
  85. package/dist/Interfaces/Consent/index.js +3 -0
  86. package/dist/Interfaces/Consent/index.js.map +1 -0
  87. package/dist/Interfaces/Context/IContextProps.d.ts +5 -0
  88. package/dist/Interfaces/Context/IContextProps.js +3 -0
  89. package/dist/Interfaces/Context/IContextProps.js.map +1 -0
  90. package/dist/Interfaces/Context/IContextState.d.ts +15 -0
  91. package/dist/Interfaces/Context/IContextState.js +3 -0
  92. package/dist/Interfaces/Context/IContextState.js.map +1 -0
  93. package/dist/Interfaces/Customer/ICustomerBadge.d.ts +2 -0
  94. package/dist/Interfaces/Customer/ICustomerBadge.js +3 -0
  95. package/dist/Interfaces/Customer/ICustomerBadge.js.map +1 -0
  96. package/dist/Interfaces/Customer/ICustomerRating.d.ts +10 -0
  97. package/dist/Interfaces/Customer/ICustomerRating.js +3 -0
  98. package/dist/Interfaces/Customer/ICustomerRating.js.map +1 -0
  99. package/dist/Interfaces/Customer/index.d.ts +92 -0
  100. package/dist/Interfaces/Customer/index.js +159 -0
  101. package/dist/Interfaces/Customer/index.js.map +1 -0
  102. package/dist/Interfaces/Declination/index.d.ts +106 -0
  103. package/dist/Interfaces/Declination/index.js +65 -0
  104. package/dist/Interfaces/Declination/index.js.map +1 -0
  105. package/dist/Interfaces/Delivery/CalendarDay.d.ts +9 -0
  106. package/dist/Interfaces/Delivery/CalendarDay.js +12 -0
  107. package/dist/Interfaces/Delivery/CalendarDay.js.map +1 -0
  108. package/dist/Interfaces/Delivery/Driver.d.ts +7 -0
  109. package/dist/Interfaces/Delivery/Driver.js +10 -0
  110. package/dist/Interfaces/Delivery/Driver.js.map +1 -0
  111. package/dist/Interfaces/Delivery/PlannedOrder.d.ts +26 -0
  112. package/dist/Interfaces/Delivery/PlannedOrder.js +20 -0
  113. package/dist/Interfaces/Delivery/PlannedOrder.js.map +1 -0
  114. package/dist/Interfaces/Delivery/ScheduledRun.d.ts +14 -0
  115. package/dist/Interfaces/Delivery/ScheduledRun.js +15 -0
  116. package/dist/Interfaces/Delivery/ScheduledRun.js.map +1 -0
  117. package/dist/Interfaces/Delivery/Truck.d.ts +21 -0
  118. package/dist/Interfaces/Delivery/Truck.js +25 -0
  119. package/dist/Interfaces/Delivery/Truck.js.map +1 -0
  120. package/dist/Interfaces/Directions/index.d.ts +72 -0
  121. package/dist/Interfaces/Directions/index.js +3 -0
  122. package/dist/Interfaces/Directions/index.js.map +1 -0
  123. package/dist/Interfaces/Document/index.d.ts +8 -0
  124. package/dist/Interfaces/Document/index.js +3 -0
  125. package/dist/Interfaces/Document/index.js.map +1 -0
  126. package/dist/Interfaces/Elastic/index.d.ts +89 -0
  127. package/dist/Interfaces/Elastic/index.js +3 -0
  128. package/dist/Interfaces/Elastic/index.js.map +1 -0
  129. package/dist/Interfaces/Email/CustomGR/I3DPrintEmail.d.ts +11 -0
  130. package/dist/Interfaces/Email/CustomGR/I3DPrintEmail.js +3 -0
  131. package/dist/Interfaces/Email/CustomGR/I3DPrintEmail.js.map +1 -0
  132. package/dist/Interfaces/Email/CustomGR/IBorrowToolsEmail.d.ts +15 -0
  133. package/dist/Interfaces/Email/CustomGR/IBorrowToolsEmail.js +3 -0
  134. package/dist/Interfaces/Email/CustomGR/IBorrowToolsEmail.js.map +1 -0
  135. package/dist/Interfaces/Email/CustomGR/IPickupMaterialsEmail.d.ts +12 -0
  136. package/dist/Interfaces/Email/CustomGR/IPickupMaterialsEmail.js +3 -0
  137. package/dist/Interfaces/Email/CustomGR/IPickupMaterialsEmail.js.map +1 -0
  138. package/dist/Interfaces/Email/CustomGR/IPreMeetingFormEmail.d.ts +36 -0
  139. package/dist/Interfaces/Email/CustomGR/IPreMeetingFormEmail.js +3 -0
  140. package/dist/Interfaces/Email/CustomGR/IPreMeetingFormEmail.js.map +1 -0
  141. package/dist/Interfaces/Email/CustomGR/ISponsorRequestEmail.d.ts +12 -0
  142. package/dist/Interfaces/Email/CustomGR/ISponsorRequestEmail.js +3 -0
  143. package/dist/Interfaces/Email/CustomGR/ISponsorRequestEmail.js.map +1 -0
  144. package/dist/Interfaces/Email/CustomGR/ITransportEmail.d.ts +12 -0
  145. package/dist/Interfaces/Email/CustomGR/ITransportEmail.js +3 -0
  146. package/dist/Interfaces/Email/CustomGR/ITransportEmail.js.map +1 -0
  147. package/dist/Interfaces/Email/CustomGR/ITransportQuoteEmail.d.ts +12 -0
  148. package/dist/Interfaces/Email/CustomGR/ITransportQuoteEmail.js +3 -0
  149. package/dist/Interfaces/Email/CustomGR/ITransportQuoteEmail.js.map +1 -0
  150. package/dist/Interfaces/Email/CustomGR/IVegetalsEmail.d.ts +16 -0
  151. package/dist/Interfaces/Email/CustomGR/IVegetalsEmail.js +3 -0
  152. package/dist/Interfaces/Email/CustomGR/IVegetalsEmail.js.map +1 -0
  153. package/dist/Interfaces/Email/CustomGR/IWishlistEmail.d.ts +15 -0
  154. package/dist/Interfaces/Email/CustomGR/IWishlistEmail.js +3 -0
  155. package/dist/Interfaces/Email/CustomGR/IWishlistEmail.js.map +1 -0
  156. package/dist/Interfaces/Email/IAbandonnedCartEmail.d.ts +29 -0
  157. package/dist/Interfaces/Email/IAbandonnedCartEmail.js +3 -0
  158. package/dist/Interfaces/Email/IAbandonnedCartEmail.js.map +1 -0
  159. package/dist/Interfaces/Email/IAccountConfirmationEmail.d.ts +22 -0
  160. package/dist/Interfaces/Email/IAccountConfirmationEmail.js +3 -0
  161. package/dist/Interfaces/Email/IAccountConfirmationEmail.js.map +1 -0
  162. package/dist/Interfaces/Email/IApplicationEmail.d.ts +19 -0
  163. package/dist/Interfaces/Email/IApplicationEmail.js +3 -0
  164. package/dist/Interfaces/Email/IApplicationEmail.js.map +1 -0
  165. package/dist/Interfaces/Email/IBackInStockEmail.d.ts +21 -0
  166. package/dist/Interfaces/Email/IBackInStockEmail.js +3 -0
  167. package/dist/Interfaces/Email/IBackInStockEmail.js.map +1 -0
  168. package/dist/Interfaces/Email/IContactEmail.d.ts +20 -0
  169. package/dist/Interfaces/Email/IContactEmail.js +3 -0
  170. package/dist/Interfaces/Email/IContactEmail.js.map +1 -0
  171. package/dist/Interfaces/Email/ICustomerBookingAdminEmail.d.ts +15 -0
  172. package/dist/Interfaces/Email/ICustomerBookingAdminEmail.js +3 -0
  173. package/dist/Interfaces/Email/ICustomerBookingAdminEmail.js.map +1 -0
  174. package/dist/Interfaces/Email/ICustomerBookingEmail.d.ts +14 -0
  175. package/dist/Interfaces/Email/ICustomerBookingEmail.js +3 -0
  176. package/dist/Interfaces/Email/ICustomerBookingEmail.js.map +1 -0
  177. package/dist/Interfaces/Email/IEmail.d.ts +20 -0
  178. package/dist/Interfaces/Email/IEmail.js +70 -0
  179. package/dist/Interfaces/Email/IEmail.js.map +1 -0
  180. package/dist/Interfaces/Email/IOrderConfirmationEmail.d.ts +47 -0
  181. package/dist/Interfaces/Email/IOrderConfirmationEmail.js +3 -0
  182. package/dist/Interfaces/Email/IOrderConfirmationEmail.js.map +1 -0
  183. package/dist/Interfaces/Email/IPasswordResetEmail.d.ts +17 -0
  184. package/dist/Interfaces/Email/IPasswordResetEmail.js +3 -0
  185. package/dist/Interfaces/Email/IPasswordResetEmail.js.map +1 -0
  186. package/dist/Interfaces/Email/IPhotoShootEmail.d.ts +14 -0
  187. package/dist/Interfaces/Email/IPhotoShootEmail.js +3 -0
  188. package/dist/Interfaces/Email/IPhotoShootEmail.js.map +1 -0
  189. package/dist/Interfaces/Email/IPickupConfirmation.d.ts +23 -0
  190. package/dist/Interfaces/Email/IPickupConfirmation.js +3 -0
  191. package/dist/Interfaces/Email/IPickupConfirmation.js.map +1 -0
  192. package/dist/Interfaces/Email/IQuoteApprobationEmail.d.ts +29 -0
  193. package/dist/Interfaces/Email/IQuoteApprobationEmail.js +3 -0
  194. package/dist/Interfaces/Email/IQuoteApprobationEmail.js.map +1 -0
  195. package/dist/Interfaces/Email/IShippingConfirmation.d.ts +23 -0
  196. package/dist/Interfaces/Email/IShippingConfirmation.js +3 -0
  197. package/dist/Interfaces/Email/IShippingConfirmation.js.map +1 -0
  198. package/dist/Interfaces/Email/IWelcomeEmail.d.ts +19 -0
  199. package/dist/Interfaces/Email/IWelcomeEmail.js +3 -0
  200. package/dist/Interfaces/Email/IWelcomeEmail.js.map +1 -0
  201. package/dist/Interfaces/ExportSchema/index.d.ts +7 -0
  202. package/dist/Interfaces/ExportSchema/index.js +3 -0
  203. package/dist/Interfaces/ExportSchema/index.js.map +1 -0
  204. package/dist/Interfaces/ExternalService/BaseExternalService.d.ts +12 -0
  205. package/dist/Interfaces/ExternalService/BaseExternalService.js +3 -0
  206. package/dist/Interfaces/ExternalService/BaseExternalService.js.map +1 -0
  207. package/dist/Interfaces/ExternalService/index.d.ts +9 -0
  208. package/dist/Interfaces/ExternalService/index.js +3 -0
  209. package/dist/Interfaces/ExternalService/index.js.map +1 -0
  210. package/dist/Interfaces/G2/index.d.ts +286 -0
  211. package/dist/Interfaces/G2/index.js +32 -0
  212. package/dist/Interfaces/G2/index.js.map +1 -0
  213. package/dist/Interfaces/Indexed/Product/IIndexedLastSavedProduct.d.ts +20 -0
  214. package/dist/Interfaces/Indexed/Product/IIndexedLastSavedProduct.js +3 -0
  215. package/dist/Interfaces/Indexed/Product/IIndexedLastSavedProduct.js.map +1 -0
  216. package/dist/Interfaces/Indexed/Product/index.d.ts +91 -0
  217. package/dist/Interfaces/Indexed/Product/index.js +316 -0
  218. package/dist/Interfaces/Indexed/Product/index.js.map +1 -0
  219. package/dist/Interfaces/Inventory/index.d.ts +19 -0
  220. package/dist/Interfaces/Inventory/index.js +9 -0
  221. package/dist/Interfaces/Inventory/index.js.map +1 -0
  222. package/dist/Interfaces/Invoice/index.d.ts +4 -0
  223. package/dist/Interfaces/Invoice/index.js +3 -0
  224. package/dist/Interfaces/Invoice/index.js.map +1 -0
  225. package/dist/Interfaces/MarketplacePublication/MarketplaceOrderData.d.ts +3 -0
  226. package/dist/Interfaces/MarketplacePublication/MarketplaceOrderData.js +3 -0
  227. package/dist/Interfaces/MarketplacePublication/MarketplaceOrderData.js.map +1 -0
  228. package/dist/Interfaces/MarketplacePublication/index.d.ts +23 -0
  229. package/dist/Interfaces/MarketplacePublication/index.js +34 -0
  230. package/dist/Interfaces/MarketplacePublication/index.js.map +1 -0
  231. package/dist/Interfaces/Operations/ICreatedBy.d.ts +6 -0
  232. package/dist/Interfaces/Operations/ICreatedBy.js +3 -0
  233. package/dist/Interfaces/Operations/ICreatedBy.js.map +1 -0
  234. package/dist/Interfaces/Operations/IUpdate.d.ts +5 -0
  235. package/dist/Interfaces/Operations/IUpdate.js +3 -0
  236. package/dist/Interfaces/Operations/IUpdate.js.map +1 -0
  237. package/dist/Interfaces/Order/index.d.ts +4 -0
  238. package/dist/Interfaces/Order/index.js +3 -0
  239. package/dist/Interfaces/Order/index.js.map +1 -0
  240. package/dist/Interfaces/Org/IRelUser.d.ts +9 -0
  241. package/dist/Interfaces/Org/IRelUser.js +3 -0
  242. package/dist/Interfaces/Org/IRelUser.js.map +1 -0
  243. package/dist/Interfaces/Org/index.d.ts +29 -0
  244. package/dist/Interfaces/Org/index.js +13 -0
  245. package/dist/Interfaces/Org/index.js.map +1 -0
  246. package/dist/Interfaces/Payment/index.d.ts +11 -0
  247. package/dist/Interfaces/Payment/index.js +3 -0
  248. package/dist/Interfaces/Payment/index.js.map +1 -0
  249. package/dist/Interfaces/Product/IAttributeFamily.d.ts +6 -0
  250. package/dist/Interfaces/Product/IAttributeFamily.js +3 -0
  251. package/dist/Interfaces/Product/IAttributeFamily.js.map +1 -0
  252. package/dist/Interfaces/Product/IImportProduct.d.ts +42 -0
  253. package/dist/Interfaces/Product/IImportProduct.js +967 -0
  254. package/dist/Interfaces/Product/IImportProduct.js.map +1 -0
  255. package/dist/Interfaces/Product/IInventoryItem.d.ts +81 -0
  256. package/dist/Interfaces/Product/IInventoryItem.js +37 -0
  257. package/dist/Interfaces/Product/IInventoryItem.js.map +1 -0
  258. package/dist/Interfaces/Product/IPricing.d.ts +177 -0
  259. package/dist/Interfaces/Product/IPricing.js +175 -0
  260. package/dist/Interfaces/Product/IPricing.js.map +1 -0
  261. package/dist/Interfaces/Product/index.d.ts +121 -0
  262. package/dist/Interfaces/Product/index.js +57 -0
  263. package/dist/Interfaces/Product/index.js.map +1 -0
  264. package/dist/Interfaces/ProductAttribute/index.d.ts +11 -0
  265. package/dist/Interfaces/ProductAttribute/index.js +3 -0
  266. package/dist/Interfaces/ProductAttribute/index.js.map +1 -0
  267. package/dist/Interfaces/ProductGroup/index.d.ts +20 -0
  268. package/dist/Interfaces/ProductGroup/index.js +3 -0
  269. package/dist/Interfaces/ProductGroup/index.js.map +1 -0
  270. package/dist/Interfaces/PromiseToPurchase/BankType.d.ts +41 -0
  271. package/dist/Interfaces/PromiseToPurchase/BankType.js +43 -0
  272. package/dist/Interfaces/PromiseToPurchase/BankType.js.map +1 -0
  273. package/dist/Interfaces/PromiseToPurchase/IIndexedBankUsed.d.ts +33 -0
  274. package/dist/Interfaces/PromiseToPurchase/IIndexedBankUsed.js +16 -0
  275. package/dist/Interfaces/PromiseToPurchase/IIndexedBankUsed.js.map +1 -0
  276. package/dist/Interfaces/PromiseToPurchase/IIndexedCustomerPromiseToPurchase.d.ts +19 -0
  277. package/dist/Interfaces/PromiseToPurchase/IIndexedCustomerPromiseToPurchase.js +3 -0
  278. package/dist/Interfaces/PromiseToPurchase/IIndexedCustomerPromiseToPurchase.js.map +1 -0
  279. package/dist/Interfaces/PromiseToPurchase/index.d.ts +50 -0
  280. package/dist/Interfaces/PromiseToPurchase/index.js +14 -0
  281. package/dist/Interfaces/PromiseToPurchase/index.js.map +1 -0
  282. package/dist/Interfaces/PurchaseOrder/index.d.ts +17 -0
  283. package/dist/Interfaces/PurchaseOrder/index.js +3 -0
  284. package/dist/Interfaces/PurchaseOrder/index.js.map +1 -0
  285. package/dist/Interfaces/Query/IBrandQueryOptions.d.ts +11 -0
  286. package/dist/Interfaces/Query/IBrandQueryOptions.js +3 -0
  287. package/dist/Interfaces/Query/IBrandQueryOptions.js.map +1 -0
  288. package/dist/Interfaces/Query/ICategoryQueryOptions.d.ts +11 -0
  289. package/dist/Interfaces/Query/ICategoryQueryOptions.js +3 -0
  290. package/dist/Interfaces/Query/ICategoryQueryOptions.js.map +1 -0
  291. package/dist/Interfaces/Query/IProductQueryOptions.d.ts +15 -0
  292. package/dist/Interfaces/Query/IProductQueryOptions.js +3 -0
  293. package/dist/Interfaces/Query/IProductQueryOptions.js.map +1 -0
  294. package/dist/Interfaces/Quote/QuoteCMS/actions.d.ts +6 -0
  295. package/dist/Interfaces/Quote/QuoteCMS/actions.js +50 -0
  296. package/dist/Interfaces/Quote/QuoteCMS/actions.js.map +1 -0
  297. package/dist/Interfaces/Quote/QuoteCMS/defaults.d.ts +4 -0
  298. package/dist/Interfaces/Quote/QuoteCMS/defaults.js +32 -0
  299. package/dist/Interfaces/Quote/QuoteCMS/defaults.js.map +1 -0
  300. package/dist/Interfaces/Quote/QuoteCMS/enums.d.ts +50 -0
  301. package/dist/Interfaces/Quote/QuoteCMS/enums.js +61 -0
  302. package/dist/Interfaces/Quote/QuoteCMS/enums.js.map +1 -0
  303. package/dist/Interfaces/Quote/index.d.ts +5 -0
  304. package/dist/Interfaces/Quote/index.js +3 -0
  305. package/dist/Interfaces/Quote/index.js.map +1 -0
  306. package/dist/Interfaces/Rules/IDiscountRule.d.ts +131 -0
  307. package/dist/Interfaces/Rules/IDiscountRule.js +96 -0
  308. package/dist/Interfaces/Rules/IDiscountRule.js.map +1 -0
  309. package/dist/Interfaces/Services/IAddServiceResponse.d.ts +4 -0
  310. package/dist/Interfaces/Services/IAddServiceResponse.js +3 -0
  311. package/dist/Interfaces/Services/IAddServiceResponse.js.map +1 -0
  312. package/dist/Interfaces/Services/IService.d.ts +12 -0
  313. package/dist/Interfaces/Services/IService.js +3 -0
  314. package/dist/Interfaces/Services/IService.js.map +1 -0
  315. package/dist/Interfaces/Services/IServiceSecret.d.ts +8 -0
  316. package/dist/Interfaces/Services/IServiceSecret.js +3 -0
  317. package/dist/Interfaces/Services/IServiceSecret.js.map +1 -0
  318. package/dist/Interfaces/Shipping/Shipstation/carriers.d.ts +10 -0
  319. package/dist/Interfaces/Shipping/Shipstation/carriers.js +3 -0
  320. package/dist/Interfaces/Shipping/Shipstation/carriers.js.map +1 -0
  321. package/dist/Interfaces/Shipping/Shipstation/order.d.ts +227 -0
  322. package/dist/Interfaces/Shipping/Shipstation/order.js +3 -0
  323. package/dist/Interfaces/Shipping/Shipstation/order.js.map +1 -0
  324. package/dist/Interfaces/Shipping/Shipstation/quote.d.ts +31 -0
  325. package/dist/Interfaces/Shipping/Shipstation/quote.js +3 -0
  326. package/dist/Interfaces/Shipping/Shipstation/quote.js.map +1 -0
  327. package/dist/Interfaces/Shipping/Shiptime/order.d.ts +54 -0
  328. package/dist/Interfaces/Shipping/Shiptime/order.js +49 -0
  329. package/dist/Interfaces/Shipping/Shiptime/order.js.map +1 -0
  330. package/dist/Interfaces/Shipping/Shiptime/quote.d.ts +111 -0
  331. package/dist/Interfaces/Shipping/Shiptime/quote.js +3 -0
  332. package/dist/Interfaces/Shipping/Shiptime/quote.js.map +1 -0
  333. package/dist/Interfaces/Slider/GR.d.ts +130 -0
  334. package/dist/Interfaces/Slider/GR.js +272 -0
  335. package/dist/Interfaces/Slider/GR.js.map +1 -0
  336. package/dist/Interfaces/Slider/index.d.ts +14 -0
  337. package/dist/Interfaces/Slider/index.js +3 -0
  338. package/dist/Interfaces/Slider/index.js.map +1 -0
  339. package/dist/Interfaces/Space/IMember.d.ts +16 -0
  340. package/dist/Interfaces/Space/IMember.js +10 -0
  341. package/dist/Interfaces/Space/IMember.js.map +1 -0
  342. package/dist/Interfaces/Space/index.d.ts +311 -0
  343. package/dist/Interfaces/Space/index.js +78 -0
  344. package/dist/Interfaces/Space/index.js.map +1 -0
  345. package/dist/Interfaces/Specials/bb.d.ts +27 -0
  346. package/dist/Interfaces/Specials/bb.js +23 -0
  347. package/dist/Interfaces/Specials/bb.js.map +1 -0
  348. package/dist/Interfaces/Specials/gr.d.ts +61 -0
  349. package/dist/Interfaces/Specials/gr.js +3 -0
  350. package/dist/Interfaces/Specials/gr.js.map +1 -0
  351. package/dist/Interfaces/StockNotification/index.d.ts +7 -0
  352. package/dist/Interfaces/StockNotification/index.js +3 -0
  353. package/dist/Interfaces/StockNotification/index.js.map +1 -0
  354. package/dist/Interfaces/Store/index.d.ts +60 -0
  355. package/dist/Interfaces/Store/index.js +28 -0
  356. package/dist/Interfaces/Store/index.js.map +1 -0
  357. package/dist/Interfaces/Supplier/ICommand.d.ts +11 -0
  358. package/dist/Interfaces/Supplier/ICommand.js +3 -0
  359. package/dist/Interfaces/Supplier/ICommand.js.map +1 -0
  360. package/dist/Interfaces/Supplier/index.d.ts +36 -0
  361. package/dist/Interfaces/Supplier/index.js +25 -0
  362. package/dist/Interfaces/Supplier/index.js.map +1 -0
  363. package/dist/Interfaces/Tag/index.d.ts +18 -0
  364. package/dist/Interfaces/Tag/index.js +3 -0
  365. package/dist/Interfaces/Tag/index.js.map +1 -0
  366. package/dist/Interfaces/Tax/index.d.ts +12 -0
  367. package/dist/Interfaces/Tax/index.js +3 -0
  368. package/dist/Interfaces/Tax/index.js.map +1 -0
  369. package/dist/Interfaces/TransferRequest/index.d.ts +32 -0
  370. package/dist/Interfaces/TransferRequest/index.js +27 -0
  371. package/dist/Interfaces/TransferRequest/index.js.map +1 -0
  372. package/dist/Interfaces/Translation/index.d.ts +4 -0
  373. package/dist/Interfaces/Translation/index.js +3 -0
  374. package/dist/Interfaces/Translation/index.js.map +1 -0
  375. package/dist/Interfaces/Update/index.d.ts +10 -0
  376. package/dist/Interfaces/Update/index.js +3 -0
  377. package/dist/Interfaces/Update/index.js.map +1 -0
  378. package/dist/Interfaces/User/IUser.d.ts +29 -0
  379. package/dist/Interfaces/User/IUser.js +9 -0
  380. package/dist/Interfaces/User/IUser.js.map +1 -0
  381. package/dist/Interfaces/Version/index.d.ts +11 -0
  382. package/dist/Interfaces/Version/index.js +3 -0
  383. package/dist/Interfaces/Version/index.js.map +1 -0
  384. package/dist/Interfaces/Wishlist/index.d.ts +7 -0
  385. package/dist/Interfaces/Wishlist/index.js +3 -0
  386. package/dist/Interfaces/Wishlist/index.js.map +1 -0
  387. package/dist/constants/Interfaces/IBaseApi.d.ts +15 -0
  388. package/dist/constants/Interfaces/IBaseApi.js +3 -0
  389. package/dist/constants/Interfaces/IBaseApi.js.map +1 -0
  390. package/dist/constants/Interfaces/IEndpointResult.d.ts +9 -0
  391. package/dist/constants/Interfaces/IEndpointResult.js +3 -0
  392. package/dist/constants/Interfaces/IEndpointResult.js.map +1 -0
  393. package/dist/constants/enums.d.ts +6 -0
  394. package/dist/constants/enums.js +11 -0
  395. package/dist/constants/enums.js.map +1 -0
  396. package/dist/constants/errors.d.ts +27 -0
  397. package/dist/constants/errors.js +33 -0
  398. package/dist/constants/errors.js.map +1 -0
  399. package/dist/constants/version.d.ts +2 -0
  400. package/dist/constants/version.js +6 -0
  401. package/dist/constants/version.js.map +1 -0
  402. package/dist/index.d.ts +32 -0
  403. package/dist/index.js +417 -0
  404. package/dist/index.js.map +1 -0
  405. package/dist/lib/Attribute/index.d.ts +14 -0
  406. package/dist/lib/Attribute/index.js +250 -0
  407. package/dist/lib/Attribute/index.js.map +1 -0
  408. package/dist/lib/BGJob/index.d.ts +9 -0
  409. package/dist/lib/BGJob/index.js +377 -0
  410. package/dist/lib/BGJob/index.js.map +1 -0
  411. package/dist/lib/BackgroundWorker/index.d.ts +34 -0
  412. package/dist/lib/BackgroundWorker/index.js +73 -0
  413. package/dist/lib/BackgroundWorker/index.js.map +1 -0
  414. package/dist/lib/Blog/BlogArticle.d.ts +5 -0
  415. package/dist/lib/Blog/BlogArticle.js +29 -0
  416. package/dist/lib/Blog/BlogArticle.js.map +1 -0
  417. package/dist/lib/Blog/BlogAuthor.d.ts +5 -0
  418. package/dist/lib/Blog/BlogAuthor.js +29 -0
  419. package/dist/lib/Blog/BlogAuthor.js.map +1 -0
  420. package/dist/lib/Blog/BlogCategory.d.ts +5 -0
  421. package/dist/lib/Blog/BlogCategory.js +29 -0
  422. package/dist/lib/Blog/BlogCategory.js.map +1 -0
  423. package/dist/lib/Blog/BlogKeyword.d.ts +5 -0
  424. package/dist/lib/Blog/BlogKeyword.js +29 -0
  425. package/dist/lib/Blog/BlogKeyword.js.map +1 -0
  426. package/dist/lib/Booking/index.d.ts +63 -0
  427. package/dist/lib/Booking/index.js +814 -0
  428. package/dist/lib/Booking/index.js.map +1 -0
  429. package/dist/lib/Brand/index.d.ts +17 -0
  430. package/dist/lib/Brand/index.js +274 -0
  431. package/dist/lib/Brand/index.js.map +1 -0
  432. package/dist/lib/CMS/Creator/index.d.ts +38 -0
  433. package/dist/lib/CMS/Creator/index.js +625 -0
  434. package/dist/lib/CMS/Creator/index.js.map +1 -0
  435. package/dist/lib/CMS/Reader/index.d.ts +64 -0
  436. package/dist/lib/CMS/Reader/index.js +1174 -0
  437. package/dist/lib/CMS/Reader/index.js.map +1 -0
  438. package/dist/lib/CMS/Utils.d.ts +1 -0
  439. package/dist/lib/CMS/Utils.js +30 -0
  440. package/dist/lib/CMS/Utils.js.map +1 -0
  441. package/dist/lib/CMS/Writer/index.d.ts +6 -0
  442. package/dist/lib/CMS/Writer/index.js +91 -0
  443. package/dist/lib/CMS/Writer/index.js.map +1 -0
  444. package/dist/lib/Cart/index.d.ts +184 -0
  445. package/dist/lib/Cart/index.js +3644 -0
  446. package/dist/lib/Cart/index.js.map +1 -0
  447. package/dist/lib/Catalogue/index.d.ts +11 -0
  448. package/dist/lib/Catalogue/index.js +205 -0
  449. package/dist/lib/Catalogue/index.js.map +1 -0
  450. package/dist/lib/Category/index.d.ts +26 -0
  451. package/dist/lib/Category/index.js +358 -0
  452. package/dist/lib/Category/index.js.map +1 -0
  453. package/dist/lib/Class/index.d.ts +12 -0
  454. package/dist/lib/Class/index.js +160 -0
  455. package/dist/lib/Class/index.js.map +1 -0
  456. package/dist/lib/Consent/index.d.ts +4 -0
  457. package/dist/lib/Consent/index.js +80 -0
  458. package/dist/lib/Consent/index.js.map +1 -0
  459. package/dist/lib/Customer/index.d.ts +10 -0
  460. package/dist/lib/Customer/index.js +141 -0
  461. package/dist/lib/Customer/index.js.map +1 -0
  462. package/dist/lib/Declination/index.d.ts +10 -0
  463. package/dist/lib/Declination/index.js +86 -0
  464. package/dist/lib/Declination/index.js.map +1 -0
  465. package/dist/lib/Delivery/CalendarDay.d.ts +10 -0
  466. package/dist/lib/Delivery/CalendarDay.js +149 -0
  467. package/dist/lib/Delivery/CalendarDay.js.map +1 -0
  468. package/dist/lib/Delivery/Dispatch.d.ts +56 -0
  469. package/dist/lib/Delivery/Dispatch.js +1055 -0
  470. package/dist/lib/Delivery/Dispatch.js.map +1 -0
  471. package/dist/lib/Delivery/Driver.d.ts +12 -0
  472. package/dist/lib/Delivery/Driver.js +153 -0
  473. package/dist/lib/Delivery/Driver.js.map +1 -0
  474. package/dist/lib/Delivery/PlannedOrder.d.ts +15 -0
  475. package/dist/lib/Delivery/PlannedOrder.js +237 -0
  476. package/dist/lib/Delivery/PlannedOrder.js.map +1 -0
  477. package/dist/lib/Delivery/ScheduledRun.d.ts +12 -0
  478. package/dist/lib/Delivery/ScheduledRun.js +165 -0
  479. package/dist/lib/Delivery/ScheduledRun.js.map +1 -0
  480. package/dist/lib/Delivery/Truck.d.ts +12 -0
  481. package/dist/lib/Delivery/Truck.js +158 -0
  482. package/dist/lib/Delivery/Truck.js.map +1 -0
  483. package/dist/lib/Discount/index.d.ts +18 -0
  484. package/dist/lib/Discount/index.js +760 -0
  485. package/dist/lib/Discount/index.js.map +1 -0
  486. package/dist/lib/ElasticSearch/index.d.ts +8 -0
  487. package/dist/lib/ElasticSearch/index.js +102 -0
  488. package/dist/lib/ElasticSearch/index.js.map +1 -0
  489. package/dist/lib/Email/AbandonedCartEmail.d.ts +8 -0
  490. package/dist/lib/Email/AbandonedCartEmail.js +79 -0
  491. package/dist/lib/Email/AbandonedCartEmail.js.map +1 -0
  492. package/dist/lib/Email/AccountConfirmationEmail.d.ts +11 -0
  493. package/dist/lib/Email/AccountConfirmationEmail.js +96 -0
  494. package/dist/lib/Email/AccountConfirmationEmail.js.map +1 -0
  495. package/dist/lib/Email/AdminOrderConfirmationEmail.d.ts +8 -0
  496. package/dist/lib/Email/AdminOrderConfirmationEmail.js +79 -0
  497. package/dist/lib/Email/AdminOrderConfirmationEmail.js.map +1 -0
  498. package/dist/lib/Email/ApplicationEmail.d.ts +8 -0
  499. package/dist/lib/Email/ApplicationEmail.js +79 -0
  500. package/dist/lib/Email/ApplicationEmail.js.map +1 -0
  501. package/dist/lib/Email/BackInStockEmail.d.ts +8 -0
  502. package/dist/lib/Email/BackInStockEmail.js +79 -0
  503. package/dist/lib/Email/BackInStockEmail.js.map +1 -0
  504. package/dist/lib/Email/ContactEmail.d.ts +8 -0
  505. package/dist/lib/Email/ContactEmail.js +79 -0
  506. package/dist/lib/Email/ContactEmail.js.map +1 -0
  507. package/dist/lib/Email/CustomerBookingAdminEmail.d.ts +8 -0
  508. package/dist/lib/Email/CustomerBookingAdminEmail.js +79 -0
  509. package/dist/lib/Email/CustomerBookingAdminEmail.js.map +1 -0
  510. package/dist/lib/Email/CustomerBookingEmail.d.ts +8 -0
  511. package/dist/lib/Email/CustomerBookingEmail.js +79 -0
  512. package/dist/lib/Email/CustomerBookingEmail.js.map +1 -0
  513. package/dist/lib/Email/OrderConfirmationEmail.d.ts +8 -0
  514. package/dist/lib/Email/OrderConfirmationEmail.js +79 -0
  515. package/dist/lib/Email/OrderConfirmationEmail.js.map +1 -0
  516. package/dist/lib/Email/OrderDenounciationEmail.d.ts +8 -0
  517. package/dist/lib/Email/OrderDenounciationEmail.js +79 -0
  518. package/dist/lib/Email/OrderDenounciationEmail.js.map +1 -0
  519. package/dist/lib/Email/OrderSampleEmail.d.ts +8 -0
  520. package/dist/lib/Email/OrderSampleEmail.js +79 -0
  521. package/dist/lib/Email/OrderSampleEmail.js.map +1 -0
  522. package/dist/lib/Email/OtherTypeEmails.d.ts +8 -0
  523. package/dist/lib/Email/OtherTypeEmails.js +91 -0
  524. package/dist/lib/Email/OtherTypeEmails.js.map +1 -0
  525. package/dist/lib/Email/PasswordResetEmail.d.ts +8 -0
  526. package/dist/lib/Email/PasswordResetEmail.js +79 -0
  527. package/dist/lib/Email/PasswordResetEmail.js.map +1 -0
  528. package/dist/lib/Email/PhotoShootEmail.d.ts +8 -0
  529. package/dist/lib/Email/PhotoShootEmail.js +79 -0
  530. package/dist/lib/Email/PhotoShootEmail.js.map +1 -0
  531. package/dist/lib/Email/PickUpConfirmation.d.ts +8 -0
  532. package/dist/lib/Email/PickUpConfirmation.js +79 -0
  533. package/dist/lib/Email/PickUpConfirmation.js.map +1 -0
  534. package/dist/lib/Email/QuoteApprobationEmail.d.ts +8 -0
  535. package/dist/lib/Email/QuoteApprobationEmail.js +79 -0
  536. package/dist/lib/Email/QuoteApprobationEmail.js.map +1 -0
  537. package/dist/lib/Email/ShippingConfirmation.d.ts +8 -0
  538. package/dist/lib/Email/ShippingConfirmation.js +79 -0
  539. package/dist/lib/Email/ShippingConfirmation.js.map +1 -0
  540. package/dist/lib/Email/WelcomeEmail.d.ts +8 -0
  541. package/dist/lib/Email/WelcomeEmail.js +79 -0
  542. package/dist/lib/Email/WelcomeEmail.js.map +1 -0
  543. package/dist/lib/Email/index.d.ts +8 -0
  544. package/dist/lib/Email/index.js +83 -0
  545. package/dist/lib/Email/index.js.map +1 -0
  546. package/dist/lib/ExternalService/Ebay.d.ts +63 -0
  547. package/dist/lib/ExternalService/Ebay.js +186 -0
  548. package/dist/lib/ExternalService/Ebay.js.map +1 -0
  549. package/dist/lib/ExternalService/index.d.ts +5 -0
  550. package/dist/lib/ExternalService/index.js +29 -0
  551. package/dist/lib/ExternalService/index.js.map +1 -0
  552. package/dist/lib/Indexed/IndexedCart.d.ts +13 -0
  553. package/dist/lib/Indexed/IndexedCart.js +195 -0
  554. package/dist/lib/Indexed/IndexedCart.js.map +1 -0
  555. package/dist/lib/Indexed/Product.d.ts +17 -0
  556. package/dist/lib/Indexed/Product.js +117 -0
  557. package/dist/lib/Indexed/Product.js.map +1 -0
  558. package/dist/lib/Inventory/__tests__.d.ts +1 -0
  559. package/dist/lib/Inventory/__tests__.js +199 -0
  560. package/dist/lib/Inventory/__tests__.js.map +1 -0
  561. package/dist/lib/Inventory/index.d.ts +31 -0
  562. package/dist/lib/Inventory/index.js +561 -0
  563. package/dist/lib/Inventory/index.js.map +1 -0
  564. package/dist/lib/Invoice/index.d.ts +5 -0
  565. package/dist/lib/Invoice/index.js +29 -0
  566. package/dist/lib/Invoice/index.js.map +1 -0
  567. package/dist/lib/MarketplacePublication/index.d.ts +9 -0
  568. package/dist/lib/MarketplacePublication/index.js +222 -0
  569. package/dist/lib/MarketplacePublication/index.js.map +1 -0
  570. package/dist/lib/MongoDB/BaseAPI.d.ts +18 -0
  571. package/dist/lib/MongoDB/BaseAPI.js +309 -0
  572. package/dist/lib/MongoDB/BaseAPI.js.map +1 -0
  573. package/dist/lib/Order/index.d.ts +7 -0
  574. package/dist/lib/Order/index.js +63 -0
  575. package/dist/lib/Order/index.js.map +1 -0
  576. package/dist/lib/Org/index.d.ts +26 -0
  577. package/dist/lib/Org/index.js +287 -0
  578. package/dist/lib/Org/index.js.map +1 -0
  579. package/dist/lib/PandaPay/index.d.ts +16 -0
  580. package/dist/lib/PandaPay/index.js +220 -0
  581. package/dist/lib/PandaPay/index.js.map +1 -0
  582. package/dist/lib/Paysafe/index.d.ts +11 -0
  583. package/dist/lib/Paysafe/index.js +101 -0
  584. package/dist/lib/Paysafe/index.js.map +1 -0
  585. package/dist/lib/Product/index.d.ts +143 -0
  586. package/dist/lib/Product/index.js +1325 -0
  587. package/dist/lib/Product/index.js.map +1 -0
  588. package/dist/lib/ProductAttribute/index.d.ts +15 -0
  589. package/dist/lib/ProductAttribute/index.js +115 -0
  590. package/dist/lib/ProductAttribute/index.js.map +1 -0
  591. package/dist/lib/ProductGroup/index.d.ts +49 -0
  592. package/dist/lib/ProductGroup/index.js +141 -0
  593. package/dist/lib/ProductGroup/index.js.map +1 -0
  594. package/dist/lib/PromiseToPurchase/index.d.ts +35 -0
  595. package/dist/lib/PromiseToPurchase/index.js +475 -0
  596. package/dist/lib/PromiseToPurchase/index.js.map +1 -0
  597. package/dist/lib/PurchaseOrder/index.d.ts +9 -0
  598. package/dist/lib/PurchaseOrder/index.js +73 -0
  599. package/dist/lib/PurchaseOrder/index.js.map +1 -0
  600. package/dist/lib/Queue/index.d.ts +40 -0
  601. package/dist/lib/Queue/index.js +255 -0
  602. package/dist/lib/Queue/index.js.map +1 -0
  603. package/dist/lib/Quote/index.d.ts +204 -0
  604. package/dist/lib/Quote/index.js +721 -0
  605. package/dist/lib/Quote/index.js.map +1 -0
  606. package/dist/lib/Service/Enum/ServiceEnum.d.ts +3 -0
  607. package/dist/lib/Service/Enum/ServiceEnum.js +8 -0
  608. package/dist/lib/Service/Enum/ServiceEnum.js.map +1 -0
  609. package/dist/lib/Service/index.d.ts +5 -0
  610. package/dist/lib/Service/index.js +58 -0
  611. package/dist/lib/Service/index.js.map +1 -0
  612. package/dist/lib/Shipment/index.d.ts +28 -0
  613. package/dist/lib/Shipment/index.js +560 -0
  614. package/dist/lib/Shipment/index.js.map +1 -0
  615. package/dist/lib/Slider/index.d.ts +18 -0
  616. package/dist/lib/Slider/index.js +233 -0
  617. package/dist/lib/Slider/index.js.map +1 -0
  618. package/dist/lib/Space/index.d.ts +758 -0
  619. package/dist/lib/Space/index.js +6692 -0
  620. package/dist/lib/Space/index.js.map +1 -0
  621. package/dist/lib/SpecialOPS/Cases/BB.d.ts +8 -0
  622. package/dist/lib/SpecialOPS/Cases/BB.js +24 -0
  623. package/dist/lib/SpecialOPS/Cases/BB.js.map +1 -0
  624. package/dist/lib/SpecialOPS/index.d.ts +14 -0
  625. package/dist/lib/SpecialOPS/index.js +21 -0
  626. package/dist/lib/SpecialOPS/index.js.map +1 -0
  627. package/dist/lib/StockNotification/index.d.ts +4 -0
  628. package/dist/lib/StockNotification/index.js +27 -0
  629. package/dist/lib/StockNotification/index.js.map +1 -0
  630. package/dist/lib/Store/index.d.ts +5 -0
  631. package/dist/lib/Store/index.js +31 -0
  632. package/dist/lib/Store/index.js.map +1 -0
  633. package/dist/lib/Supplier/Command.d.ts +5 -0
  634. package/dist/lib/Supplier/Command.js +29 -0
  635. package/dist/lib/Supplier/Command.js.map +1 -0
  636. package/dist/lib/Supplier/index.d.ts +25 -0
  637. package/dist/lib/Supplier/index.js +93 -0
  638. package/dist/lib/Supplier/index.js.map +1 -0
  639. package/dist/lib/Tags/index.d.ts +6 -0
  640. package/dist/lib/Tags/index.js +85 -0
  641. package/dist/lib/Tags/index.js.map +1 -0
  642. package/dist/lib/Tax/index.d.ts +8 -0
  643. package/dist/lib/Tax/index.js +137 -0
  644. package/dist/lib/Tax/index.js.map +1 -0
  645. package/dist/lib/TransferRequest/index.d.ts +21 -0
  646. package/dist/lib/TransferRequest/index.js +303 -0
  647. package/dist/lib/TransferRequest/index.js.map +1 -0
  648. package/dist/lib/Update/index.d.ts +10 -0
  649. package/dist/lib/Update/index.js +72 -0
  650. package/dist/lib/Update/index.js.map +1 -0
  651. package/dist/lib/User/index.d.ts +33 -0
  652. package/dist/lib/User/index.js +361 -0
  653. package/dist/lib/User/index.js.map +1 -0
  654. package/dist/lib/Wishlist/index.d.ts +5 -0
  655. package/dist/lib/Wishlist/index.js +29 -0
  656. package/dist/lib/Wishlist/index.js.map +1 -0
  657. package/dist/lib/base copy.d.ts +14 -0
  658. package/dist/lib/base copy.js +136 -0
  659. package/dist/lib/base copy.js.map +1 -0
  660. package/dist/lib/base.d.ts +14 -0
  661. package/dist/lib/base.js +136 -0
  662. package/dist/lib/base.js.map +1 -0
  663. package/dist/lib/baseService.d.ts +17 -0
  664. package/dist/lib/baseService.js +114 -0
  665. package/dist/lib/baseService.js.map +1 -0
  666. package/dist/rules/GR/constants/data.d.ts +28 -0
  667. package/dist/rules/GR/constants/data.js +58 -0
  668. package/dist/rules/GR/constants/data.js.map +1 -0
  669. package/dist/rules/GR/constants/products.d.ts +8 -0
  670. package/dist/rules/GR/constants/products.js +235 -0
  671. package/dist/rules/GR/constants/products.js.map +1 -0
  672. package/dist/rules/GR/interfaces/cart.d.ts +68 -0
  673. package/dist/rules/GR/interfaces/cart.js +50 -0
  674. package/dist/rules/GR/interfaces/cart.js.map +1 -0
  675. package/dist/rules/GR/interfaces/data.d.ts +97 -0
  676. package/dist/rules/GR/interfaces/data.js +105 -0
  677. package/dist/rules/GR/interfaces/data.js.map +1 -0
  678. package/dist/rules/GR/interfaces/products.d.ts +61 -0
  679. package/dist/rules/GR/interfaces/products.js +11 -0
  680. package/dist/rules/GR/interfaces/products.js.map +1 -0
  681. package/dist/rules/GR/utils/anonymisation.d.ts +29 -0
  682. package/dist/rules/GR/utils/anonymisation.js +269 -0
  683. package/dist/rules/GR/utils/anonymisation.js.map +1 -0
  684. package/dist/rules/GR/utils/cart.d.ts +39 -0
  685. package/dist/rules/GR/utils/cart.js +645 -0
  686. package/dist/rules/GR/utils/cart.js.map +1 -0
  687. package/dist/rules/GR/utils/data.d.ts +3 -0
  688. package/dist/rules/GR/utils/data.js +26 -0
  689. package/dist/rules/GR/utils/data.js.map +1 -0
  690. package/dist/rules/GR/utils/expedition.d.ts +70 -0
  691. package/dist/rules/GR/utils/expedition.js +1584 -0
  692. package/dist/rules/GR/utils/expedition.js.map +1 -0
  693. package/dist/rules/GR/utils/g2.d.ts +153 -0
  694. package/dist/rules/GR/utils/g2.js +915 -0
  695. package/dist/rules/GR/utils/g2.js.map +1 -0
  696. package/dist/rules/GR/utils/invoices.d.ts +5 -0
  697. package/dist/rules/GR/utils/invoices.js +141 -0
  698. package/dist/rules/GR/utils/invoices.js.map +1 -0
  699. package/dist/rules/GR/utils/products.d.ts +105 -0
  700. package/dist/rules/GR/utils/products.js +1014 -0
  701. package/dist/rules/GR/utils/products.js.map +1 -0
  702. package/dist/rules/GR/utils/upsells.d.ts +75 -0
  703. package/dist/rules/GR/utils/upsells.js +279 -0
  704. package/dist/rules/GR/utils/upsells.js.map +1 -0
  705. package/dist/services/database/AuthProvider.d.ts +3 -0
  706. package/dist/services/database/AuthProvider.js +67 -0
  707. package/dist/services/database/AuthProvider.js.map +1 -0
  708. package/dist/services/database/BaseProvider.d.ts +28 -0
  709. package/dist/services/database/BaseProvider.js +78 -0
  710. package/dist/services/database/BaseProvider.js.map +1 -0
  711. package/dist/services/database/BatchUtils.d.ts +14 -0
  712. package/dist/services/database/BatchUtils.js +89 -0
  713. package/dist/services/database/BatchUtils.js.map +1 -0
  714. package/dist/services/database/Config.d.ts +2 -0
  715. package/dist/services/database/Config.js +6 -0
  716. package/dist/services/database/Config.js.map +1 -0
  717. package/dist/services/database/DatabaseService.d.ts +41 -0
  718. package/dist/services/database/DatabaseService.js +312 -0
  719. package/dist/services/database/DatabaseService.js.map +1 -0
  720. package/dist/services/database/FirebaseProvider.d.ts +17 -0
  721. package/dist/services/database/FirebaseProvider.js +301 -0
  722. package/dist/services/database/FirebaseProvider.js.map +1 -0
  723. package/dist/services/database/NotFirebaseProvider.d.ts +35 -0
  724. package/dist/services/database/NotFirebaseProvider.js +368 -0
  725. package/dist/services/database/NotFirebaseProvider.js.map +1 -0
  726. package/dist/utils/algolia.d.ts +6 -0
  727. package/dist/utils/algolia.js +23 -0
  728. package/dist/utils/algolia.js.map +1 -0
  729. package/dist/utils/anonymisation.d.ts +30 -0
  730. package/dist/utils/anonymisation.js +270 -0
  731. package/dist/utils/anonymisation.js.map +1 -0
  732. package/dist/utils/array.d.ts +5 -0
  733. package/dist/utils/array.js +37 -0
  734. package/dist/utils/array.js.map +1 -0
  735. package/dist/utils/aws.d.ts +18 -0
  736. package/dist/utils/aws.js +144 -0
  737. package/dist/utils/aws.js.map +1 -0
  738. package/dist/utils/booking.d.ts +22 -0
  739. package/dist/utils/booking.js +176 -0
  740. package/dist/utils/booking.js.map +1 -0
  741. package/dist/utils/cart.d.ts +505 -0
  742. package/dist/utils/cart.js +504 -0
  743. package/dist/utils/cart.js.map +1 -0
  744. package/dist/utils/cmv.d.ts +10 -0
  745. package/dist/utils/cmv.js +108 -0
  746. package/dist/utils/cmv.js.map +1 -0
  747. package/dist/utils/console.d.ts +6 -0
  748. package/dist/utils/console.js +122 -0
  749. package/dist/utils/console.js.map +1 -0
  750. package/dist/utils/context.d.ts +19 -0
  751. package/dist/utils/context.js +42 -0
  752. package/dist/utils/context.js.map +1 -0
  753. package/dist/utils/currency.d.ts +6 -0
  754. package/dist/utils/currency.js +63 -0
  755. package/dist/utils/currency.js.map +1 -0
  756. package/dist/utils/data.d.ts +40 -0
  757. package/dist/utils/data.js +227 -0
  758. package/dist/utils/data.js.map +1 -0
  759. package/dist/utils/date.d.ts +1 -0
  760. package/dist/utils/date.js +17 -0
  761. package/dist/utils/date.js.map +1 -0
  762. package/dist/utils/dimensions.d.ts +3 -0
  763. package/dist/utils/dimensions.js +19 -0
  764. package/dist/utils/dimensions.js.map +1 -0
  765. package/dist/utils/discount.d.ts +33 -0
  766. package/dist/utils/discount.js +907 -0
  767. package/dist/utils/discount.js.map +1 -0
  768. package/dist/utils/env.d.ts +1 -0
  769. package/dist/utils/env.js +14 -0
  770. package/dist/utils/env.js.map +1 -0
  771. package/dist/utils/errors.d.ts +113 -0
  772. package/dist/utils/errors.js +114 -0
  773. package/dist/utils/errors.js.map +1 -0
  774. package/dist/utils/file-admin.d.ts +8 -0
  775. package/dist/utils/file-admin.js +95 -0
  776. package/dist/utils/file-admin.js.map +1 -0
  777. package/dist/utils/file.d.ts +19 -0
  778. package/dist/utils/file.js +339 -0
  779. package/dist/utils/file.js.map +1 -0
  780. package/dist/utils/firebase-admin.d.ts +2 -0
  781. package/dist/utils/firebase-admin.js +119 -0
  782. package/dist/utils/firebase-admin.js.map +1 -0
  783. package/dist/utils/firebase.d.ts +23 -0
  784. package/dist/utils/firebase.js +59 -0
  785. package/dist/utils/firebase.js.map +1 -0
  786. package/dist/utils/import.d.ts +1 -0
  787. package/dist/utils/import.js +82 -0
  788. package/dist/utils/import.js.map +1 -0
  789. package/dist/utils/inventories.d.ts +26 -0
  790. package/dist/utils/inventories.js +356 -0
  791. package/dist/utils/inventories.js.map +1 -0
  792. package/dist/utils/locale.d.ts +13 -0
  793. package/dist/utils/locale.js +68 -0
  794. package/dist/utils/locale.js.map +1 -0
  795. package/dist/utils/mailchimp.d.ts +57 -0
  796. package/dist/utils/mailchimp.js +736 -0
  797. package/dist/utils/mailchimp.js.map +1 -0
  798. package/dist/utils/math.d.ts +1 -0
  799. package/dist/utils/math.js +16 -0
  800. package/dist/utils/math.js.map +1 -0
  801. package/dist/utils/mongodb.d.ts +1 -0
  802. package/dist/utils/mongodb.js +69 -0
  803. package/dist/utils/mongodb.js.map +1 -0
  804. package/dist/utils/object.d.ts +6 -0
  805. package/dist/utils/object.js +125 -0
  806. package/dist/utils/object.js.map +1 -0
  807. package/dist/utils/payment.d.ts +10 -0
  808. package/dist/utils/payment.js +26 -0
  809. package/dist/utils/payment.js.map +1 -0
  810. package/dist/utils/products.d.ts +26 -0
  811. package/dist/utils/products.js +302 -0
  812. package/dist/utils/products.js.map +1 -0
  813. package/dist/utils/promiseToPurchase.d.ts +56 -0
  814. package/dist/utils/promiseToPurchase.js +229 -0
  815. package/dist/utils/promiseToPurchase.js.map +1 -0
  816. package/dist/utils/prosprsearch.d.ts +21 -0
  817. package/dist/utils/prosprsearch.js +277 -0
  818. package/dist/utils/prosprsearch.js.map +1 -0
  819. package/dist/utils/sdc.d.ts +10 -0
  820. package/dist/utils/sdc.js +1309 -0
  821. package/dist/utils/sdc.js.map +1 -0
  822. package/dist/utils/searchIndexes.d.ts +20 -0
  823. package/dist/utils/searchIndexes.js +274 -0
  824. package/dist/utils/searchIndexes.js.map +1 -0
  825. package/dist/utils/services.d.ts +38 -0
  826. package/dist/utils/services.js +395 -0
  827. package/dist/utils/services.js.map +1 -0
  828. package/dist/utils/shipment.d.ts +110 -0
  829. package/dist/utils/shipment.js +411 -0
  830. package/dist/utils/shipment.js.map +1 -0
  831. package/dist/utils/simpletexting.d.ts +2 -0
  832. package/dist/utils/simpletexting.js +89 -0
  833. package/dist/utils/simpletexting.js.map +1 -0
  834. package/dist/utils/slack.d.ts +33 -0
  835. package/dist/utils/slack.js +178 -0
  836. package/dist/utils/slack.js.map +1 -0
  837. package/dist/utils/sliders.d.ts +4 -0
  838. package/dist/utils/sliders.js +71 -0
  839. package/dist/utils/sliders.js.map +1 -0
  840. package/dist/utils/string.d.ts +16 -0
  841. package/dist/utils/string.js +195 -0
  842. package/dist/utils/string.js.map +1 -0
  843. package/dist/utils/update.d.ts +7 -0
  844. package/dist/utils/update.js +245 -0
  845. package/dist/utils/update.js.map +1 -0
  846. package/dist/utils/weight.d.ts +3 -0
  847. package/dist/utils/weight.js +19 -0
  848. package/dist/utils/weight.js.map +1 -0
  849. package/dist/utils/zones.d.ts +10 -0
  850. package/dist/utils/zones.js +288 -0
  851. package/dist/utils/zones.js.map +1 -0
  852. package/package.json +106 -0
  853. package/publish.sh +144 -0
  854. package/readme.md +182 -0
@@ -0,0 +1,3644 @@
1
+ "use strict";
2
+ var __extends = (this && this.__extends) || (function () {
3
+ var extendStatics = function (d, b) {
4
+ extendStatics = Object.setPrototypeOf ||
5
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
+ return extendStatics(d, b);
8
+ };
9
+ return function (d, b) {
10
+ if (typeof b !== "function" && b !== null)
11
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
+ extendStatics(d, b);
13
+ function __() { this.constructor = d; }
14
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
+ };
16
+ })();
17
+ var __assign = (this && this.__assign) || function () {
18
+ __assign = Object.assign || function(t) {
19
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
20
+ s = arguments[i];
21
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
22
+ t[p] = s[p];
23
+ }
24
+ return t;
25
+ };
26
+ return __assign.apply(this, arguments);
27
+ };
28
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
29
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
30
+ return new (P || (P = Promise))(function (resolve, reject) {
31
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
32
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
33
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
34
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
35
+ });
36
+ };
37
+ var __generator = (this && this.__generator) || function (thisArg, body) {
38
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
39
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
40
+ function verb(n) { return function (v) { return step([n, v]); }; }
41
+ function step(op) {
42
+ if (f) throw new TypeError("Generator is already executing.");
43
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
44
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
45
+ if (y = 0, t) op = [op[0] & 2, t.value];
46
+ switch (op[0]) {
47
+ case 0: case 1: t = op; break;
48
+ case 4: _.label++; return { value: op[1], done: false };
49
+ case 5: _.label++; y = op[1]; op = [0]; continue;
50
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
51
+ default:
52
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
53
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
54
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
55
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
56
+ if (t[2]) _.ops.pop();
57
+ _.trys.pop(); continue;
58
+ }
59
+ op = body.call(thisArg, _);
60
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
61
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
62
+ }
63
+ };
64
+ var __rest = (this && this.__rest) || function (s, e) {
65
+ var t = {};
66
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
67
+ t[p] = s[p];
68
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
69
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
70
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
71
+ t[p[i]] = s[p[i]];
72
+ }
73
+ return t;
74
+ };
75
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
76
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
77
+ if (ar || !(i in from)) {
78
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
79
+ ar[i] = from[i];
80
+ }
81
+ }
82
+ return to.concat(ar || Array.prototype.slice.call(from));
83
+ };
84
+ var __importDefault = (this && this.__importDefault) || function (mod) {
85
+ return (mod && mod.__esModule) ? mod : { "default": mod };
86
+ };
87
+ Object.defineProperty(exports, "__esModule", { value: true });
88
+ var find_1 = __importDefault(require("lodash/find"));
89
+ var indexOf_1 = __importDefault(require("lodash/indexOf"));
90
+ var isNumber_1 = __importDefault(require("lodash/isNumber"));
91
+ var map_1 = __importDefault(require("lodash/map"));
92
+ var max_1 = __importDefault(require("lodash/max"));
93
+ var orderBy_1 = __importDefault(require("lodash/orderBy"));
94
+ var round_1 = __importDefault(require("lodash/round"));
95
+ var sumBy_1 = __importDefault(require("lodash/sumBy"));
96
+ var toNumber_1 = __importDefault(require("lodash/toNumber"));
97
+ var toString_1 = __importDefault(require("lodash/toString"));
98
+ var uniq_1 = __importDefault(require("lodash/uniq"));
99
+ var flatten_1 = __importDefault(require("lodash/flatten"));
100
+ var discount_1 = require("../../utils/discount");
101
+ var data_1 = require("../../utils/data");
102
+ var Cart_1 = require("../../Interfaces/Cart");
103
+ var Customer_1 = __importDefault(require("../Customer"));
104
+ var console_1 = require("../../utils/console");
105
+ var weight_1 = require("../../utils/weight");
106
+ var dimensions_1 = require("../../utils/dimensions");
107
+ var Tax_1 = __importDefault(require("../Tax"));
108
+ var IDiscountRule_1 = require("../../Interfaces/Rules/IDiscountRule");
109
+ var Space_1 = __importDefault(require("../Space"));
110
+ var Shipment_1 = __importDefault(require("../Shipment"));
111
+ var Customer_2 = require("../../Interfaces/Customer");
112
+ var algolia_1 = require("../../utils/algolia");
113
+ var order_1 = require("../../Interfaces/Shipping/Shiptime/order");
114
+ var locale_1 = require("../../utils/locale");
115
+ var string_1 = require("../../utils/string");
116
+ var file_1 = require("../../utils/file");
117
+ var moment_1 = __importDefault(require("moment"));
118
+ var services_1 = require("../../utils/services");
119
+ var object_1 = require("../../utils/object");
120
+ var __1 = require("../..");
121
+ var prosprsearch_1 = require("../../utils/prosprsearch");
122
+ var products_1 = require("../../utils/products");
123
+ var context_1 = require("../../utils/context");
124
+ var PromiseToPurchase_1 = __importDefault(require("../PromiseToPurchase"));
125
+ var g2_1 = require("../../rules/GR/utils/g2");
126
+ var cart_1 = require("../../utils/cart");
127
+ var promiseToPurchase_1 = require("../../utils/promiseToPurchase");
128
+ var PromiseToPurchase_2 = require("../../Interfaces/PromiseToPurchase");
129
+ var products_2 = require("../../rules/GR/utils/products");
130
+ var baseService_1 = require("../baseService");
131
+ var DatabaseService_1 = __importDefault(require("../../services/database/DatabaseService"));
132
+ var Cart = (function (_super) {
133
+ __extends(Cart, _super);
134
+ function Cart(data, collection, user, resetErrors) {
135
+ var _this = _super.call(this, data, collection, user) || this;
136
+ _this._allTaxes = [];
137
+ _this.addError = function (error) {
138
+ _this._data = __assign(__assign({}, _this._data), { errors: (0, uniq_1.default)(__spreadArray(__spreadArray([], (!!_this._data.errors && Array.isArray(_this._data.errors) ? _this._data.errors : []), true), [error], false)) });
139
+ };
140
+ _this.clearErrors = function () {
141
+ _this._data = __assign(__assign({}, _this._data), { errors: [] });
142
+ };
143
+ _this.getCartAssignedUserData = function (user, atStore) {
144
+ return __assign({ user_name: "".concat(!!user.firstname ? user.firstname : '').concat(!!user.firstname && user.lastname ? ' ' : '').concat(!!user.lastname ? user.lastname : ''), user_external_id: !!user.external_id ? user.external_id : '', user_email: user.email, user_id: user.id, date: (0, moment_1.default)().toDate(), is_active: true }, (!!atStore ? { at_store_number: atStore.store_num, at_store_id: atStore.id } : {}));
145
+ };
146
+ _this.addAssignedUser = function (user) { return __awaiter(_this, void 0, void 0, function () {
147
+ var currentAssignedUsers, newAssignedUser, fused, error_1;
148
+ return __generator(this, function (_b) {
149
+ switch (_b.label) {
150
+ case 0:
151
+ currentAssignedUsers = this._data.assigned_to || [];
152
+ newAssignedUser = this.getCartAssignedUserData(user);
153
+ fused = __spreadArray(__spreadArray([], (!!currentAssignedUsers.length
154
+ ? currentAssignedUsers.map(function (aUser) { return (__assign(__assign({}, aUser), { is_active: false })); })
155
+ : []), true), [
156
+ newAssignedUser
157
+ ], false);
158
+ this._data = __assign(__assign({}, this._data), { assigned_to: fused });
159
+ _b.label = 1;
160
+ case 1:
161
+ _b.trys.push([1, 3, , 4]);
162
+ return [4, this.save({ id: this._data.id, assigned_to: fused }, undefined, true, true)];
163
+ case 2:
164
+ _b.sent();
165
+ return [3, 4];
166
+ case 3:
167
+ error_1 = _b.sent();
168
+ console.log('error on saving assigned user', error_1);
169
+ return [3, 4];
170
+ case 4: return [2, this._data];
171
+ }
172
+ });
173
+ }); };
174
+ _this.cancelCart = function (user) { return __awaiter(_this, void 0, void 0, function () {
175
+ var userInfo, editedCart, space, e_1, error_2;
176
+ return __generator(this, function (_b) {
177
+ switch (_b.label) {
178
+ case 0:
179
+ if (!!user) {
180
+ userInfo = {
181
+ user_name: "".concat(user.firstname, " ").concat(user.lastname),
182
+ user_email: user.email,
183
+ user_id: user.id,
184
+ user_external_id: user.external_id,
185
+ date: new Date(),
186
+ is_active: true
187
+ };
188
+ }
189
+ editedCart = __assign(__assign(__assign(__assign({ status: Cart_1.CartStatusEnum.EXT_REFUND }, (!!userInfo ? { canceled_by: userInfo } : {})), (!!this._data.check_marketing_emails ? { check_marketing_emails: false } : {})), (!!this._data.check_sms_to_send ? { check_sms_to_send: false } : {})), (!!this._data.check_retarget_marketing_emails ? { check_retarget_marketing_emails: false } : {}));
190
+ if (!(!!this._data.items && !!this._data.items.length)) return [3, 5];
191
+ _b.label = 1;
192
+ case 1:
193
+ _b.trys.push([1, 4, , 5]);
194
+ return [4, Space_1.default.getCurrentSpaceWithRef(this._collection.path, this._user)];
195
+ case 2:
196
+ space = _b.sent();
197
+ if (!!!this._data.current_store_id)
198
+ throw new Error('No store associated to cart');
199
+ return [4, space.inventory.ajust(this._data.items, 'cancelled', this._data.cart_type, this._data.current_store_id, this._data.status < Cart_1.CartStatusEnum.CART_READY_TO_PROCESS)];
200
+ case 3:
201
+ _b.sent();
202
+ return [3, 5];
203
+ case 4:
204
+ e_1 = _b.sent();
205
+ console.error(e_1);
206
+ return [3, 5];
207
+ case 5:
208
+ _b.trys.push([5, 7, , 8]);
209
+ return [4, this.save(editedCart, true)];
210
+ case 6:
211
+ _b.sent();
212
+ return [2, true];
213
+ case 7:
214
+ error_2 = _b.sent();
215
+ console.log('error on saving cancelled cart', error_2);
216
+ return [2, false];
217
+ case 8: return [2];
218
+ }
219
+ });
220
+ }); };
221
+ _this.updateCartOnLoginFetch = function (customerData, space, orgID) { return __awaiter(_this, void 0, void 0, function () {
222
+ var e_2, cartCustumerInfo, newInfo, e_3;
223
+ return __generator(this, function (_b) {
224
+ switch (_b.label) {
225
+ case 0:
226
+ _b.trys.push([0, 7, , 8]);
227
+ return [4, this.setDiscountRules()];
228
+ case 1:
229
+ _b.sent();
230
+ if (!(!!space && !!this._data.items.length)) return [3, 5];
231
+ _b.label = 2;
232
+ case 2:
233
+ _b.trys.push([2, 4, , 5]);
234
+ return [4, this.verifyCartItems(space, orgID, false)];
235
+ case 3:
236
+ _b.sent();
237
+ return [3, 5];
238
+ case 4:
239
+ e_2 = _b.sent();
240
+ console.log('error on verifyCartItems in /signin endpoint: ', e_2.toString());
241
+ return [3, 5];
242
+ case 5:
243
+ cartCustumerInfo = this.data().customer_info;
244
+ if (!!customerData.basic_info.customer_professionnal_info &&
245
+ !!customerData.basic_info.customer_professionnal_info.professionnal_title &&
246
+ ((!!cartCustumerInfo && !!!cartCustumerInfo.pro_title) || !!!cartCustumerInfo)) {
247
+ if (!!!cartCustumerInfo)
248
+ cartCustumerInfo = {};
249
+ newInfo = {
250
+ customer_id: customerData.id,
251
+ customer_info: __assign(__assign({}, cartCustumerInfo), { pro_title: customerData.basic_info.customer_professionnal_info.professionnal_title, pro_proof_doc: customerData.basic_info.customer_professionnal_info.proof_doc_value, customer_default_email: customerData.basic_info.customer_email })
252
+ };
253
+ this._data = __assign(__assign({}, this._data), newInfo);
254
+ }
255
+ return [4, this.save()];
256
+ case 6:
257
+ _b.sent();
258
+ return [2, this._data];
259
+ case 7:
260
+ e_3 = _b.sent();
261
+ console.log('error on updating cart after fetch : ', e_3.toString());
262
+ return [3, 8];
263
+ case 8: return [2];
264
+ }
265
+ });
266
+ }); };
267
+ _this.data = function () { return _this._data; };
268
+ _this.save = function (partial, options, saveToDatabase, onlyPartial) {
269
+ if (onlyPartial === void 0) { onlyPartial = false; }
270
+ return __awaiter(_this, void 0, void 0, function () {
271
+ var partialCartToSave, space, cart_promos_applied, rest, res;
272
+ return __generator(this, function (_b) {
273
+ switch (_b.label) {
274
+ case 0:
275
+ if (!!onlyPartial) {
276
+ if (!!!partial || !!!partial.id)
277
+ return [2, false];
278
+ }
279
+ partialCartToSave = __assign(__assign({}, this._data), partial);
280
+ return [4, Space_1.default.getCurrentSpaceWithRef(this._collection.path, this._user)];
281
+ case 1:
282
+ space = _b.sent();
283
+ if (!space.isMultiPromo()) {
284
+ cart_promos_applied = partialCartToSave.cart_promos_applied, rest = __rest(partialCartToSave, ["cart_promos_applied"]);
285
+ if (!!partialCartToSave.cart_promos_applied && !!partialCartToSave.cart_promos_applied.length) {
286
+ partialCartToSave = __assign(__assign({}, rest), { cart_promo_applied: partialCartToSave.cart_promos_applied[0] });
287
+ }
288
+ }
289
+ this._data = __assign({}, partialCartToSave);
290
+ return [4, _super.prototype.save.call(this, !!onlyPartial && !!partial ? __assign({}, partial) : __assign({}, partialCartToSave), options, saveToDatabase, true, undefined, undefined, !!onlyPartial && !!partial)];
291
+ case 2:
292
+ res = _b.sent();
293
+ if (!!res && typeof res === 'string')
294
+ this._data = __assign(__assign({}, this._data), { id: res });
295
+ return [2, res];
296
+ }
297
+ });
298
+ });
299
+ };
300
+ _this.getAllTaxes = function () { return _this._allTaxes; };
301
+ _this.checkout = function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_b) {
302
+ return [2, this.data().items];
303
+ }); }); };
304
+ _this.setCurrentStore = function (currentStoreId) {
305
+ _this._data = __assign(__assign({}, _this._data), { current_store_id: currentStoreId });
306
+ };
307
+ _this.getCartPromo = function () {
308
+ return (0, discount_1.getCartPromo)(_this._data);
309
+ };
310
+ _this.getSubtotalWithoutPromotions = function () {
311
+ return _this.data().subtotalWithoutPromotions;
312
+ };
313
+ _this.getSubtotal = function () {
314
+ return _this.data().subtotal;
315
+ };
316
+ _this.getAddressTo = function () { return __awaiter(_this, void 0, void 0, function () {
317
+ return __generator(this, function (_b) {
318
+ if (!!!this.data().customer_id)
319
+ throw new Error("The customer is not yet defined");
320
+ return [2];
321
+ });
322
+ }); };
323
+ _this.getAllPaidBy = function () {
324
+ var paidBy = _this.data().paid_by;
325
+ if (!!!paidBy)
326
+ return [];
327
+ if (paidBy !== Cart_1.PaymentTypeEnum.MULTIPLE)
328
+ return [paidBy];
329
+ var allPaymentMethods = (0, uniq_1.default)((_this.data().payment_details || []).map(function (p) { return p.method; }).filter(function (p) { return !!p; }));
330
+ return allPaymentMethods;
331
+ };
332
+ _this.checkIfAmountLeftToPayOnTotal = function () {
333
+ var currentPaidBy = _this.data().paid_by;
334
+ if (!!currentPaidBy && currentPaidBy !== Cart_1.PaymentTypeEnum.MULTIPLE) {
335
+ return currentPaidBy === Cart_1.PaymentTypeEnum.TOBERECEIVED;
336
+ }
337
+ var paymentDetails = _this.data().payment_details;
338
+ if (!!!paymentDetails || !!!paymentDetails.length)
339
+ return false;
340
+ var paidAmountWithoutToBeReceived = (0, sumBy_1.default)(paymentDetails.filter(function (p) { return p.method !== Cart_1.PaymentTypeEnum.TOBERECEIVED; }), 'amount');
341
+ return (0, round_1.default)(paidAmountWithoutToBeReceived, 2) !== (0, round_1.default)(_this.data().total, 2);
342
+ };
343
+ _this.getCustomerById = function () { return __awaiter(_this, void 0, void 0, function () {
344
+ var customerRequest, customerData, error_3;
345
+ var _b;
346
+ return __generator(this, function (_c) {
347
+ switch (_c.label) {
348
+ case 0:
349
+ if (DatabaseService_1.default.getPathParent(this._collection.path) == '/')
350
+ throw new Error("Can't access parent collections");
351
+ if (!!!this.data().customer_id)
352
+ throw new Error("Customer id is not defined in cart");
353
+ _c.label = 1;
354
+ case 1:
355
+ _c.trys.push([1, 3, , 4]);
356
+ return [4, DatabaseService_1.default.getDocument(DatabaseService_1.default.addToPath(DatabaseService_1.default.getPathParent(this._collection.path), 'customers'), (_b = this.data().customer_id) !== null && _b !== void 0 ? _b : '')];
357
+ case 2:
358
+ customerRequest = _c.sent();
359
+ if (!customerRequest.exists)
360
+ throw new Error("Can't find customer with id ".concat(this.data().customer_id));
361
+ customerData = customerRequest.data;
362
+ if (!!!customerData)
363
+ throw new Error("Can't find customer with id ".concat(this.data().customer_id));
364
+ return [2, new Customer_1.default(__assign(__assign({}, customerData), { id: customerRequest.id }), {
365
+ path: DatabaseService_1.default.addToPath(DatabaseService_1.default.getPathParent(this._collection.path), 'customers')
366
+ }, this._user)];
367
+ case 3:
368
+ error_3 = _c.sent();
369
+ return [2, undefined];
370
+ case 4: return [2];
371
+ }
372
+ });
373
+ }); };
374
+ _this.getCustomerByEmail = function () { return __awaiter(_this, void 0, void 0, function () {
375
+ var customerRequest, customerData, error_4;
376
+ return __generator(this, function (_b) {
377
+ switch (_b.label) {
378
+ case 0:
379
+ if (DatabaseService_1.default.getPathParent(this._collection.path) == '/')
380
+ throw new Error("Can't access parent collections");
381
+ if (!!!this.data().user_email)
382
+ throw new Error("Customer email is not defined in cart");
383
+ _b.label = 1;
384
+ case 1:
385
+ _b.trys.push([1, 3, , 4]);
386
+ return [4, DatabaseService_1.default.getDocuments(DatabaseService_1.default.addToPath(DatabaseService_1.default.getPathParent(this._collection.path), 'customers'), {
387
+ query: [
388
+ {
389
+ field: 'basic_info.customer_email',
390
+ operator: '==',
391
+ value: !!this.data().customer_info && !!this.data().customer_info.customer_default_email
392
+ ? this.data().customer_info.customer_default_email
393
+ : this.data().user_email
394
+ }
395
+ ]
396
+ })];
397
+ case 2:
398
+ customerRequest = _b.sent();
399
+ if (!!!customerRequest.length || !customerRequest[0].exists)
400
+ throw new Error("Can't find customer with email ".concat(!!this.data().customer_info && !!this.data().customer_info.customer_default_email
401
+ ? this.data().customer_info.customer_default_email
402
+ : this.data().user_email));
403
+ customerData = customerRequest[0].data;
404
+ if (!!!customerData)
405
+ throw new Error("Can't find customer with email ".concat(this.data().customer_id));
406
+ return [2, new Customer_1.default(__assign(__assign({}, customerData), { id: customerRequest[0].id }), {
407
+ path: DatabaseService_1.default.addToPath(DatabaseService_1.default.getPathParent(this._collection.path), 'customers')
408
+ }, this._user)];
409
+ case 3:
410
+ error_4 = _b.sent();
411
+ return [2, undefined];
412
+ case 4: return [2];
413
+ }
414
+ });
415
+ }); };
416
+ _this.canEnterPredefinedBox = function (box, subtotalToRespect, weightToRespect, totalItemsToRespect, space) {
417
+ if (!!subtotalToRespect) {
418
+ if (!!!_this.data().subtotal && !!space) {
419
+ _this.calculateSubtotal(space);
420
+ }
421
+ if (_this.data().subtotal > subtotalToRespect) {
422
+ return false;
423
+ }
424
+ }
425
+ if (!!weightToRespect && _this.getTotalWeight('kilograms') > weightToRespect)
426
+ return false;
427
+ var items = _this.data().items;
428
+ if (!!totalItemsToRespect && (0, sumBy_1.default)(items, function (i) { return i.qte; }) > totalItemsToRespect)
429
+ return false;
430
+ var maxHeight = (0, max_1.default)(items.map(function (i) {
431
+ return (0, dimensions_1.convertDimension)((0, string_1.convertToNumber)(i.shipping_info.height || 0), i.shipping_info.unit_measurments, 'centimeters');
432
+ })) || 0;
433
+ var maxWidth = (0, max_1.default)(items.map(function (i) {
434
+ return (0, dimensions_1.convertDimension)((0, string_1.convertToNumber)(i.shipping_info.width || 0), i.shipping_info.unit_measurments, 'centimeters');
435
+ })) || 0;
436
+ var maxLength = (0, max_1.default)(items.map(function (i) {
437
+ return (0, dimensions_1.convertDimension)((0, string_1.convertToNumber)(i.shipping_info.length || 0), i.shipping_info.unit_measurments, 'centimeters');
438
+ })) || 0;
439
+ var totalWidth = _this.getTotalWidth('centimeters');
440
+ var totalLength = _this.getTotalLength('centimeters');
441
+ var totalHeight = _this.getTotalHeight('centimeters');
442
+ var boxHeight = (0, dimensions_1.convertDimension)((0, string_1.convertToNumber)(box.height), 'inches', 'centimeters');
443
+ var boxWidth = (0, dimensions_1.convertDimension)((0, string_1.convertToNumber)(box.width), 'inches', 'centimeters');
444
+ var boxLength = (0, dimensions_1.convertDimension)((0, string_1.convertToNumber)(box.length), 'inches', 'centimeters');
445
+ return [
446
+ maxHeight <= boxHeight && maxWidth <= boxWidth && totalLength <= boxLength,
447
+ maxHeight <= boxHeight && maxLength <= boxLength && totalWidth <= boxWidth,
448
+ maxLength <= boxLength && maxWidth <= boxWidth && totalHeight <= boxHeight
449
+ ].includes(true);
450
+ };
451
+ _this.getTotalHeight = function (unit) {
452
+ if (unit === void 0) { unit = 'inches'; }
453
+ return (0, sumBy_1.default)(_this.data().items, function (item) {
454
+ if (!!item.shipping_info.is_not_shippable)
455
+ return 0;
456
+ if (!!!item.shipping_info)
457
+ return 0;
458
+ return Number((item.shipping_info.unit_measurments === unit
459
+ ? (item.shipping_info.height || 0) * item.qte
460
+ : (0, dimensions_1.convertDimension)(item.shipping_info.height || 0, item.shipping_info.unit_measurments, unit) * item.qte).toFixed(2));
461
+ });
462
+ };
463
+ _this.getTotalLength = function (unit) {
464
+ if (unit === void 0) { unit = 'inches'; }
465
+ return (0, sumBy_1.default)(_this.data().items, function (item) {
466
+ if (!!item.shipping_info.is_not_shippable)
467
+ return 0;
468
+ if (!!!item.shipping_info)
469
+ return 0;
470
+ return Number((item.shipping_info.unit_measurments === unit
471
+ ? (item.shipping_info.length || 0) * item.qte
472
+ : (0, dimensions_1.convertDimension)(item.shipping_info.length || 0, item.shipping_info.unit_measurments, unit) * item.qte).toFixed(2));
473
+ });
474
+ };
475
+ _this.getTotalWidth = function (unit) {
476
+ if (unit === void 0) { unit = 'inches'; }
477
+ return (0, sumBy_1.default)(_this.data().items, function (item) {
478
+ if (!!item.shipping_info.is_not_shippable)
479
+ return 0;
480
+ if (!!!item.shipping_info)
481
+ return 0;
482
+ return Number((item.shipping_info.unit_measurments === unit
483
+ ? (item.shipping_info.width || 0) * item.qte
484
+ : (0, dimensions_1.convertDimension)(item.shipping_info.width || 0, item.shipping_info.unit_measurments, unit) * item.qte).toFixed(2));
485
+ });
486
+ };
487
+ _this.getTotalWeight = function (unit) {
488
+ if (unit === void 0) { unit = 'pounds'; }
489
+ return (0, sumBy_1.default)(_this.data().items, function (item) {
490
+ if (!!item.shipping_info.is_not_shippable)
491
+ return 0;
492
+ if (!!!item.shipping_info)
493
+ return 0;
494
+ return item.shipping_info.unit_weight === unit
495
+ ? ((0, toNumber_1.default)(item.shipping_info.weight) || 0) * item.qte
496
+ : (0, weight_1.convertWeight)((0, toNumber_1.default)(item.shipping_info.weight) || 0, item.shipping_info.unit_weight, unit) * item.qte;
497
+ });
498
+ };
499
+ _this.addItemsToCart = function (items) { return __awaiter(_this, void 0, void 0, function () {
500
+ var itemsWithRestrictions;
501
+ return __generator(this, function (_b) {
502
+ switch (_b.label) {
503
+ case 0:
504
+ itemsWithRestrictions = this.checkProductRestrictions(items);
505
+ this._data = __assign(__assign({}, this._data), { items: itemsWithRestrictions });
506
+ return [4, this.save({
507
+ items: itemsWithRestrictions
508
+ })];
509
+ case 1:
510
+ _b.sent();
511
+ return [2, itemsWithRestrictions];
512
+ }
513
+ });
514
+ }); };
515
+ _this.refreshItems = function () { return __awaiter(_this, void 0, void 0, function () {
516
+ var itemsAndRestrictions;
517
+ return __generator(this, function (_b) {
518
+ switch (_b.label) {
519
+ case 0:
520
+ if (!!!this._data.items || !!!this._data.items.length)
521
+ return [2, []];
522
+ itemsAndRestrictions = this.checkProductRestrictions(this._data.items);
523
+ return [4, this.save({
524
+ items: itemsAndRestrictions
525
+ })];
526
+ case 1:
527
+ _b.sent();
528
+ return [2, itemsAndRestrictions];
529
+ }
530
+ });
531
+ }); };
532
+ _this.verifyCartItems = function (space, orgID, saveToDatabase) { return __awaiter(_this, void 0, void 0, function () {
533
+ var actionsDone, isGR, proCustomerTitle, proID, customPriceList, token, allItemSlugs, customPriceListQuery, e_4, verifiedItems, _loop_1, _b, _c, cartItem, err_1;
534
+ return __generator(this, function (_d) {
535
+ switch (_d.label) {
536
+ case 0:
537
+ _d.trys.push([0, 9, , 10]);
538
+ actionsDone = [];
539
+ isGR = space.data().id === services_1.SpaceIdEnum.GR;
540
+ proCustomerTitle = !!this._data.customer_info && !!this._data.customer_info.pro_title ? this._data.customer_info.pro_title : '';
541
+ proID = undefined;
542
+ if (!!proCustomerTitle) {
543
+ if (!!isGR && proCustomerTitle === 'anonymous-pos-pro') {
544
+ proID = 'BASEAS';
545
+ }
546
+ else if (!!(0, object_1.recursiveCheckObject)(this._data, 'customer_info.pro_proof_doc')) {
547
+ proID = (0, object_1.recursiveCheckObject)(this._data, 'customer_info.pro_proof_doc');
548
+ }
549
+ }
550
+ if (!!__1.isTestEnv) {
551
+ console.log('proID to check: ', proID);
552
+ console.log('proCustomerTitle: ', proCustomerTitle);
553
+ }
554
+ customPriceList = undefined;
555
+ if (!(!!isGR && !!!space.data().cms.hide_pro_prices && !!space.data().g2_price_fetch_active && !!proID && !!orgID)) return [3, 4];
556
+ token = (0, context_1.getSpaceToken)(space, orgID);
557
+ if (!!!token) return [3, 4];
558
+ _d.label = 1;
559
+ case 1:
560
+ _d.trys.push([1, 3, , 4]);
561
+ allItemSlugs = this.data()
562
+ .items.map(function (i) { return i.parent_slug; })
563
+ .filter(function (slug) { return !!slug; });
564
+ return [4, (0, g2_1.getCustomPriceList)(space, proID, undefined, (0, uniq_1.default)(allItemSlugs))];
565
+ case 2:
566
+ customPriceListQuery = _d.sent();
567
+ if (typeof customPriceListQuery !== 'string')
568
+ customPriceList = customPriceListQuery;
569
+ return [3, 4];
570
+ case 3:
571
+ e_4 = _d.sent();
572
+ console.log('error on fetching custom price list: ', e_4.toString());
573
+ return [3, 4];
574
+ case 4:
575
+ if (!!__1.isTestEnv)
576
+ console.log('customPriceList.length: ', !!customPriceList && customPriceList.length);
577
+ verifiedItems = [];
578
+ _loop_1 = function (cartItem) {
579
+ var parentProductsQuery, parentProduct, queryDeclination, queryDecliTierPricing, itemTierPricing, didApplyTier, tierPricingToApply, inventory, webInventory;
580
+ return __generator(this, function (_e) {
581
+ switch (_e.label) {
582
+ case 0:
583
+ cartItem = __assign(__assign({}, cartItem), { state_after_verification: null });
584
+ if (!!cartItem.is_temp_prod || !!cartItem.price_override) {
585
+ verifiedItems.push(cartItem);
586
+ return [2, "continue"];
587
+ }
588
+ if (!!!cartItem.parent_slug) {
589
+ if (!!__1.isTestEnv)
590
+ console.log('no parent slug');
591
+ actionsDone.push({
592
+ sku: cartItem.sku,
593
+ itemName: cartItem.name,
594
+ action: Cart_1.ActionDoneOnCartEnum.OUT_OF_STOCK_OR_NOT_FOUND
595
+ });
596
+ verifiedItems.push(__assign(__assign({}, cartItem), { state_after_verification: 'out_of_stock' }));
597
+ return [2, "continue"];
598
+ }
599
+ return [4, space.cartItem.get({
600
+ query: [
601
+ {
602
+ field: 'slug',
603
+ operator: '==',
604
+ value: cartItem.parent_slug.toLowerCase()
605
+ }
606
+ ]
607
+ })];
608
+ case 1:
609
+ parentProductsQuery = _e.sent();
610
+ if (!!!!parentProductsQuery.length) return [3, 3];
611
+ return [4, space.cartItem.get({
612
+ query: [
613
+ {
614
+ field: 'slug',
615
+ operator: '==',
616
+ value: cartItem.parent_slug
617
+ }
618
+ ]
619
+ })];
620
+ case 2:
621
+ parentProductsQuery = _e.sent();
622
+ _e.label = 3;
623
+ case 3:
624
+ if (!!!parentProductsQuery.length) {
625
+ if (!!__1.isTestEnv)
626
+ console.log('parent prod does not exist for slug: ', cartItem.parent_slug);
627
+ actionsDone.push({
628
+ sku: cartItem.sku,
629
+ itemName: cartItem.name,
630
+ action: Cart_1.ActionDoneOnCartEnum.OUT_OF_STOCK_OR_NOT_FOUND
631
+ });
632
+ verifiedItems.push(__assign(__assign({}, cartItem), { state_after_verification: 'out_of_stock' }));
633
+ return [2, "continue"];
634
+ }
635
+ parentProduct = parentProductsQuery[0];
636
+ if (!!__1.isTestEnv)
637
+ console.log('parentProduct: ', parentProduct.slug);
638
+ if (!(!!proID && !!proCustomerTitle)) return [3, 5];
639
+ return [4, (0, products_1.updateProductWithInfo)(parentProduct, '', space, space.data().id, proCustomerTitle)];
640
+ case 4:
641
+ parentProduct = _e.sent();
642
+ _e.label = 5;
643
+ case 5:
644
+ queryDeclination = parentProduct.declinations.find(function (decli) { return decli.sku === cartItem.sku; });
645
+ if (!!!queryDeclination) {
646
+ if (!!__1.isTestEnv)
647
+ console.log('could not find same decli for prod: ', cartItem.parent_slug, cartItem.sku);
648
+ actionsDone.push({
649
+ sku: cartItem.sku,
650
+ itemName: cartItem.name,
651
+ action: Cart_1.ActionDoneOnCartEnum.OUT_OF_STOCK_OR_NOT_FOUND
652
+ });
653
+ verifiedItems.push(__assign(__assign({}, cartItem), { state_after_verification: 'out_of_stock' }));
654
+ return [2, "continue"];
655
+ }
656
+ queryDecliTierPricing = !!queryDeclination.tier_pricing && !!queryDeclination.tier_pricing.length
657
+ ? queryDeclination.tier_pricing
658
+ : undefined;
659
+ itemTierPricing = !!cartItem.tier_pricing && !!cartItem.tier_pricing.length ? cartItem.tier_pricing : undefined;
660
+ didApplyTier = false;
661
+ if (!!itemTierPricing && !!!queryDecliTierPricing) {
662
+ if (!!__1.isTestEnv)
663
+ console.log('tier_pricing should not be in product. Removing from cartItem');
664
+ cartItem = __assign(__assign(__assign({}, cartItem), (!!cartItem.discount_price && cartItem.discount_price.price_type === products_1.priceTypeEnum.TIER_PRICING
665
+ ? { discount_price: null }
666
+ : {})), { tier_pricing: [] });
667
+ }
668
+ if (!!!isGR || !!!proID) {
669
+ if (!!queryDecliTierPricing) {
670
+ tierPricingToApply = (0, discount_1.getTierPricingToApply)(queryDecliTierPricing, cartItem.qte);
671
+ if (!!__1.isTestEnv)
672
+ console.log('checking tier pricing');
673
+ queryDeclination = __assign(__assign({}, queryDeclination), { discount_price: !!tierPricingToApply
674
+ ? tierPricingToApply.price
675
+ : !!queryDeclination.discount_price
676
+ ? queryDeclination.discount_price
677
+ : queryDeclination.regular_price });
678
+ didApplyTier = true;
679
+ }
680
+ if (!!!itemTierPricing && !!queryDecliTierPricing) {
681
+ if (!!__1.isTestEnv)
682
+ console.log('newTier pricing, adding to item');
683
+ cartItem = __assign(__assign({}, cartItem), { tier_pricing: queryDecliTierPricing });
684
+ }
685
+ }
686
+ if (!!__1.isTestEnv) {
687
+ console.log('appliedTier: ', !!didApplyTier);
688
+ }
689
+ if (!!customPriceList && !!customPriceList.length) {
690
+ if (!!__1.isTestEnv) {
691
+ console.log('is pro customer, checking with G2 prices then leaving');
692
+ console.log('item had promo or discount before: ', !!cartItem.promo_price || !!cartItem.discount_price);
693
+ }
694
+ cartItem = __assign({}, (0, g2_1.checkForCustomPriceEquivalent)(cartItem, customPriceList));
695
+ if (!!__1.isTestEnv) {
696
+ console.log('item has promo or discount after: ', !!cartItem.promo_price || !!cartItem.discount_price);
697
+ }
698
+ }
699
+ else {
700
+ if (cartItem.regular_price.amount !== queryDeclination.regular_price.amount &&
701
+ !!!cartItem.regular_price.price_type) {
702
+ if (!!__1.isTestEnv) {
703
+ console.log('regPrice is different');
704
+ console.log('queryItem regPrice: ', queryDeclination.regular_price.amount, ' vs cartItem regPrice : ', cartItem.regular_price.amount);
705
+ }
706
+ actionsDone.push({
707
+ sku: cartItem.sku,
708
+ itemName: cartItem.name,
709
+ action: Cart_1.ActionDoneOnCartEnum.MODIFIED_REGULAR_PRICE
710
+ });
711
+ cartItem = __assign(__assign({}, cartItem), { regular_price: queryDeclination.regular_price });
712
+ if (!!__1.isTestEnv)
713
+ console.log('new regPrice: ', cartItem.regular_price.amount);
714
+ }
715
+ if (!didApplyTier) {
716
+ if ((!!cartItem.discount_price && !!!cartItem.discount_price.price_type) ||
717
+ !!queryDeclination.discount_price) {
718
+ if (!!__1.isTestEnv)
719
+ console.log('checking discountPrice');
720
+ if (!!!cartItem.discount_price && !!queryDeclination.discount_price) {
721
+ if (!!__1.isTestEnv)
722
+ console.log('discountPrice was added');
723
+ actionsDone.push({
724
+ sku: cartItem.sku,
725
+ itemName: cartItem.name,
726
+ action: Cart_1.ActionDoneOnCartEnum.MODIFIED_DISCOUNT_PRICE
727
+ });
728
+ cartItem = __assign(__assign({}, cartItem), { discount_price: queryDeclination.discount_price });
729
+ if (!!__1.isTestEnv)
730
+ console.log('new discountPrice: ', !!cartItem.discount_price ? cartItem.discount_price.amount : 'undefined');
731
+ }
732
+ if (!!cartItem.discount_price && !!!queryDeclination.discount_price) {
733
+ if (!!__1.isTestEnv)
734
+ console.log('discountPrice was removed');
735
+ actionsDone.push({
736
+ sku: cartItem.sku,
737
+ itemName: cartItem.name,
738
+ action: Cart_1.ActionDoneOnCartEnum.MODIFIED_DISCOUNT_PRICE
739
+ });
740
+ cartItem = __assign(__assign({}, cartItem), { discount_price: null });
741
+ if (!!__1.isTestEnv)
742
+ console.log('new discountPrice: ', !!cartItem.discount_price ? cartItem.discount_price.amount : 'undefined');
743
+ }
744
+ if (!!cartItem.discount_price &&
745
+ !!queryDeclination.discount_price &&
746
+ cartItem.discount_price.amount !== queryDeclination.discount_price.amount &&
747
+ queryDeclination.discount_price.amount !== 0 &&
748
+ cartItem.discount_price.amount !== queryDeclination.regular_price.amount) {
749
+ if (!!__1.isTestEnv) {
750
+ console.log('discountPrice is different');
751
+ console.log('queryItem discount: ', queryDeclination.discount_price.amount, ' vs cartItem discount : ', cartItem.discount_price.amount);
752
+ }
753
+ actionsDone.push({
754
+ sku: cartItem.sku,
755
+ itemName: cartItem.name,
756
+ action: Cart_1.ActionDoneOnCartEnum.MODIFIED_DISCOUNT_PRICE
757
+ });
758
+ cartItem = __assign(__assign({}, cartItem), { discount_price: queryDeclination.discount_price });
759
+ if (!!__1.isTestEnv)
760
+ console.log('new discountPrice: ', !!cartItem.discount_price ? cartItem.discount_price.amount : 'undefined');
761
+ }
762
+ }
763
+ }
764
+ if (!!__1.isTestEnv)
765
+ console.log('cartItem.promo_price: ', !!cartItem.promo_price);
766
+ if (!!__1.isTestEnv)
767
+ console.log('queryDeclination.promo_price: ', !!queryDeclination.promo_price);
768
+ if (!!cartItem.promo_price || !!queryDeclination.promo_price) {
769
+ if (!!__1.isTestEnv)
770
+ console.log('checking promoPrice');
771
+ if (!!!cartItem.promo_price && !!queryDeclination.promo_price) {
772
+ if (!!__1.isTestEnv)
773
+ console.log('promoPrice was added');
774
+ actionsDone.push({
775
+ sku: cartItem.sku,
776
+ itemName: cartItem.name,
777
+ action: Cart_1.ActionDoneOnCartEnum.MODIFIED_DISCOUNT_PRICE
778
+ });
779
+ cartItem = __assign(__assign({}, cartItem), { promo_price: queryDeclination.promo_price });
780
+ if (!!__1.isTestEnv)
781
+ console.log('new promoPrice: ', !!cartItem.promo_price ? cartItem.promo_price.amount : 'undefined');
782
+ }
783
+ if (!!cartItem.promo_price && !!!queryDeclination.promo_price) {
784
+ if (!!__1.isTestEnv)
785
+ console.log('promoPrice was removed');
786
+ actionsDone.push({
787
+ sku: cartItem.sku,
788
+ itemName: cartItem.name,
789
+ action: Cart_1.ActionDoneOnCartEnum.MODIFIED_DISCOUNT_PRICE
790
+ });
791
+ cartItem = __assign(__assign({}, cartItem), { promo_price: null });
792
+ if (!!__1.isTestEnv)
793
+ console.log('new promoPrice: ', !!cartItem.promo_price ? cartItem.promo_price.amount : 'undefined');
794
+ }
795
+ if (!!cartItem.promo_price &&
796
+ !!queryDeclination.promo_price &&
797
+ !!!Number.isNaN((0, toNumber_1.default)(queryDeclination.promo_price.amount)) &&
798
+ (0, toNumber_1.default)(cartItem.promo_price.amount) !== (0, toNumber_1.default)(queryDeclination.promo_price.amount) &&
799
+ (0, toNumber_1.default)(cartItem.promo_price.amount) !== (0, toNumber_1.default)(queryDeclination.regular_price.amount)) {
800
+ if (!!__1.isTestEnv) {
801
+ console.log('promoPrice is different');
802
+ console.log('queryItem promo: ', queryDeclination.promo_price.amount, ' vs cartItem promo : ', cartItem.promo_price.amount);
803
+ }
804
+ actionsDone.push({
805
+ sku: cartItem.sku,
806
+ itemName: cartItem.name,
807
+ action: Cart_1.ActionDoneOnCartEnum.MODIFIED_DISCOUNT_PRICE
808
+ });
809
+ cartItem = __assign(__assign({}, cartItem), { promo_price: queryDeclination.promo_price });
810
+ if (!!__1.isTestEnv)
811
+ console.log('new promoPrice: ', !!cartItem.promo_price ? cartItem.promo_price.amount : 'undefined');
812
+ }
813
+ }
814
+ }
815
+ if (!(!!!isGR && !!!cartItem.is_service)) return [3, 7];
816
+ if (!!__1.isTestEnv)
817
+ console.log('checking inventory');
818
+ return [4, space.inventoryItems.getOne(queryDeclination.sku)];
819
+ case 6:
820
+ inventory = _e.sent();
821
+ if (!!inventory) {
822
+ webInventory = inventory.web_inventory;
823
+ if (((!!webInventory && (0, toNumber_1.default)(webInventory.available) <= 0) || !!!webInventory) &&
824
+ !!!inventory.is_infinite_stock) {
825
+ if (!!__1.isTestEnv)
826
+ console.log('no more stock');
827
+ actionsDone.push({
828
+ sku: cartItem.sku,
829
+ itemName: cartItem.name,
830
+ action: Cart_1.ActionDoneOnCartEnum.OUT_OF_STOCK_OR_NOT_FOUND
831
+ });
832
+ verifiedItems.push(__assign(__assign({}, cartItem), { state_after_verification: 'out_of_stock' }));
833
+ return [2, "continue"];
834
+ }
835
+ if (!!webInventory &&
836
+ !!webInventory.available &&
837
+ webInventory.available > 0 &&
838
+ (0, toNumber_1.default)(cartItem.qte) > (0, toNumber_1.default)(webInventory.available || 0) &&
839
+ !!!inventory.is_infinite_stock) {
840
+ if (!!__1.isTestEnv)
841
+ console.log('not enough stock, modified qty');
842
+ actionsDone.push({
843
+ sku: cartItem.sku,
844
+ itemName: cartItem.name,
845
+ action: Cart_1.ActionDoneOnCartEnum.MODIFIED_QTE
846
+ });
847
+ cartItem = __assign(__assign({}, cartItem), { qte: webInventory.available, state_after_verification: 'modified_qty' });
848
+ }
849
+ }
850
+ _e.label = 7;
851
+ case 7:
852
+ verifiedItems.push(cartItem);
853
+ return [2];
854
+ }
855
+ });
856
+ };
857
+ _b = 0, _c = this.data().items;
858
+ _d.label = 5;
859
+ case 5:
860
+ if (!(_b < _c.length)) return [3, 8];
861
+ cartItem = _c[_b];
862
+ return [5, _loop_1(cartItem)];
863
+ case 6:
864
+ _d.sent();
865
+ _d.label = 7;
866
+ case 7:
867
+ _b++;
868
+ return [3, 5];
869
+ case 8:
870
+ this._data = __assign(__assign({}, this._data), { items: verifiedItems.filter(function (item) { return !!item; }) });
871
+ this.save({
872
+ items: verifiedItems.filter(function (item) { return !!item; })
873
+ }, undefined, !!saveToDatabase);
874
+ return [2, actionsDone];
875
+ case 9:
876
+ err_1 = _d.sent();
877
+ throw new Error(err_1.toString());
878
+ case 10: return [2];
879
+ }
880
+ });
881
+ }); };
882
+ _this.checkProductRestrictions = function (items) {
883
+ return items.map(function (item) {
884
+ if ((!!!item.restrict_sale && !!!item.restrict_shipping) ||
885
+ (!!item.restrict_sale &&
886
+ !!!item.restrict_sale.restrict_values &&
887
+ !!item.restrict_shipping &&
888
+ !!!item.restrict_shipping.restrict_values) ||
889
+ (!!item.restrict_sale &&
890
+ !!!item.restrict_sale.restrict_values.length &&
891
+ !!item.restrict_shipping &&
892
+ !!!item.restrict_shipping.restrict_values.length)) {
893
+ return item;
894
+ }
895
+ if (!!item.restrict_sale &&
896
+ !!item.restrict_sale.restrict_values &&
897
+ !!item.restrict_sale.restrict_values.length &&
898
+ !!_this._data.customer_info) {
899
+ if (_this._data.customer_info.customer_type !== Customer_2.BasicCustomerTypeEnum.PRO ||
900
+ (_this._data.customer_info.customer_type === Customer_2.BasicCustomerTypeEnum.PRO &&
901
+ (!!!_this._data.customer_info.pro_title || !!!_this._data.customer_info.pro_proof_doc)) ||
902
+ (_this._data.customer_info.customer_type === Customer_2.BasicCustomerTypeEnum.PRO &&
903
+ !!_this._data.customer_info.pro_title &&
904
+ !item.restrict_sale.restrict_values.includes(_this._data.customer_info.pro_title))) {
905
+ item = __assign(__assign({}, item), { restrict_sale: __assign(__assign({}, item.restrict_sale), { restrict_message: _this._getRestrictionMessage(item.restrict_sale.restrict_values, 'sale') }) });
906
+ }
907
+ else {
908
+ item = __assign(__assign({}, item), { restrict_sale: __assign(__assign({}, item.restrict_sale), { restrict_message: '' }) });
909
+ }
910
+ }
911
+ if (!!item.restrict_shipping &&
912
+ !!item.restrict_shipping.restrict_values &&
913
+ !!item.restrict_shipping.restrict_values.length) {
914
+ if (item.restrict_shipping.restrict_values[0] === 'not shippable') {
915
+ item = __assign(__assign({}, item), { restrict_shipping: __assign(__assign({}, item.restrict_shipping), { restrict_message: _this._getRestrictionMessage(item.restrict_shipping.restrict_values, 'not shippable') }) });
916
+ }
917
+ else {
918
+ var shippingProvince_1 = (0, find_1.default)(data_1.provinces, function (province) {
919
+ if (!!!_this._data.shipping_address || !!!_this._data.shipping_address.address)
920
+ return false;
921
+ return province.label === _this._data.shipping_address.address.state;
922
+ });
923
+ if (!!shippingProvince_1 &&
924
+ !!!item.restrict_shipping.restrict_values.filter(function (value) { return value === shippingProvince_1.value; }).length) {
925
+ item = __assign(__assign({}, item), { restrict_shipping: __assign(__assign({}, item.restrict_shipping), { restrict_message: _this._getRestrictionMessage(item.restrict_shipping.restrict_values, 'shipping') }) });
926
+ }
927
+ else {
928
+ item = __assign(__assign({}, item), { restrict_shipping: __assign(__assign({}, item.restrict_shipping), { restrict_message: '' }) });
929
+ }
930
+ }
931
+ }
932
+ if (!!item.exclude_from_free_shipping) {
933
+ var cartPromo = _this.getCartPromo();
934
+ if (!!cartPromo && !!cartPromo.some(function (i) { return i.free_shipping; })) {
935
+ _this.excludeFreeShipping();
936
+ _this.addError(Cart_1.CartErrorEnum.FREE_SHIPPING_NOT_ELIGIBLE_BECAUSE_OF_ITEM);
937
+ }
938
+ }
939
+ return item;
940
+ });
941
+ };
942
+ _this._getRestrictionMessage = function (messageDetails, type) {
943
+ var baseMsg = '';
944
+ if (type === 'sale') {
945
+ baseMsg = "Ce produit peut seulement être acheté par les types d'utilisateurs suivants : ";
946
+ baseMsg =
947
+ baseMsg +
948
+ messageDetails.join(', ') +
949
+ ". Si c'est votre cas, assurez-vous d'être identifié comme tel dans votre profil client, en plus d'y fournir une preuve valide d'identification.";
950
+ }
951
+ if (type === 'shipping') {
952
+ baseMsg = 'Ce produit ne peut être envoyé à votre addresse. Il est limité aux provinces suivantes : ';
953
+ baseMsg =
954
+ baseMsg +
955
+ messageDetails
956
+ .map(function (detail) {
957
+ var provinceMap = (0, find_1.default)(data_1.provinces, function (province) { return province.value === detail; });
958
+ return "".concat(!!provinceMap && provinceMap.label);
959
+ })
960
+ .join();
961
+ }
962
+ if (type === 'not shippable') {
963
+ baseMsg =
964
+ "Ce produit n'est pas disponible pour la livraison. Vous pouvez soit le retirer de votre panier pour continuer, ou encore, aller cocher l'option \"Cueillette en personne\" dans l'étape information du client (Livraison)";
965
+ }
966
+ return baseMsg;
967
+ };
968
+ _this.setAllTaxes = function () { return __awaiter(_this, void 0, void 0, function () {
969
+ var _b;
970
+ return __generator(this, function (_c) {
971
+ switch (_c.label) {
972
+ case 0:
973
+ _b = this;
974
+ return [4, Tax_1.default.getAllTaxesGeneral()];
975
+ case 1:
976
+ _b._allTaxes = _c.sent();
977
+ return [2, this._allTaxes];
978
+ }
979
+ });
980
+ }); };
981
+ _this.setCartTaxes = function (defaultTax) {
982
+ _this._data = __assign(__assign({}, _this._data), { taxes: __spreadArray(__spreadArray([], _this._data.taxes, true), [defaultTax], false) });
983
+ };
984
+ _this.getATax = function (taxNameFr, taxValue, currency) {
985
+ if (currency === void 0) { currency = 'CAD'; }
986
+ var taxAmount = 0;
987
+ if ((!!_this._data.shipping_address &&
988
+ !!_this._data.shipping_address.address &&
989
+ ['ca', 'canada'].includes(_this._data.shipping_address.address.country.toLowerCase())) ||
990
+ !!_this._data.is_pickup) {
991
+ var subtotalWithoutPromotions = !!_this.data().subtotalWithoutPromotions
992
+ ? _this.data().subtotalWithoutPromotions
993
+ : _this.data().subtotal;
994
+ var subtotal = _this.data().subtotal;
995
+ var subtotalWithShipping = (0, round_1.default)(_this.data().subtotal + _this._checkShippingAmount(), 2);
996
+ var customTaxableItems = _this.data().items.filter(function (item) { return !!item.tax_family_id; });
997
+ var notTaxableItems = _this.data().items.filter(function (item) { return !!item.tax_exemption; });
998
+ var correspondingSubTax_1 = undefined;
999
+ if (!!!customTaxableItems.length) {
1000
+ taxAmount = (0, round_1.default)(subtotalWithShipping * taxValue, 2);
1001
+ }
1002
+ else {
1003
+ var totalPriceAmountCustomTaxable_1 = 0;
1004
+ customTaxableItems.map(function (item) {
1005
+ var priceToTakeOut = item.regular_price.amount;
1006
+ if (!!item.discount_price && item.regular_price > item.discount_price) {
1007
+ priceToTakeOut = item.discount_price.amount;
1008
+ }
1009
+ var correspondingTaxes = _this._allTaxes.filter(function (tax) { return tax.id === item.tax_family_id; })[0].taxes;
1010
+ correspondingSubTax_1 = correspondingTaxes.find(function (tax) { return tax.label_fr === taxNameFr; });
1011
+ if (!!correspondingSubTax_1) {
1012
+ totalPriceAmountCustomTaxable_1 += 0;
1013
+ }
1014
+ else {
1015
+ var sameTaxInCart = _this.data().taxes.find(function (tax) { return tax.taxes.find(function (t) { return taxNameFr === t.label_fr; }); });
1016
+ if (!!sameTaxInCart) {
1017
+ correspondingSubTax_1 = sameTaxInCart.taxes.find(function (tax) { return tax.label_fr === taxNameFr; });
1018
+ }
1019
+ totalPriceAmountCustomTaxable_1 += priceToTakeOut * item.qte;
1020
+ }
1021
+ });
1022
+ var ratioOfCustomTaxToSubtotal = (totalPriceAmountCustomTaxable_1 * subtotal) / subtotalWithoutPromotions;
1023
+ var defaultTaxAmount = (0, round_1.default)(subtotalWithShipping - ratioOfCustomTaxToSubtotal, 2) * taxValue;
1024
+ taxAmount = (0, round_1.default)(defaultTaxAmount, 2);
1025
+ }
1026
+ if (!!notTaxableItems.length) {
1027
+ var totalNotTaxableItems_1 = 0;
1028
+ notTaxableItems.forEach(function (item) {
1029
+ var priceToTakeOut = item.regular_price.amount;
1030
+ if (!!item.discount_price && item.regular_price > item.discount_price) {
1031
+ priceToTakeOut = item.discount_price.amount;
1032
+ }
1033
+ var productsPrice = priceToTakeOut * item.qte;
1034
+ totalNotTaxableItems_1 += productsPrice * taxValue;
1035
+ });
1036
+ taxAmount = (0, round_1.default)(taxAmount - totalNotTaxableItems_1, 2);
1037
+ }
1038
+ var sameTaxInDefaultCart = [];
1039
+ if (!!_this.data().taxes) {
1040
+ sameTaxInDefaultCart = _this.data().taxes.map(function (tax, key) {
1041
+ var taxToCheck = tax.taxes.filter(function (aTax) { return aTax.label_fr === taxNameFr; })[0];
1042
+ return [key, tax.taxes.indexOf(taxToCheck)];
1043
+ })[0];
1044
+ }
1045
+ if (sameTaxInDefaultCart.indexOf(-1) === -1) {
1046
+ _this._data = __assign(__assign({}, _this._data), { taxes: __spreadArray(__spreadArray(__spreadArray([], _this._data.taxes.slice(0, sameTaxInDefaultCart[0]), true), [
1047
+ __assign(__assign({}, _this._data.taxes[sameTaxInDefaultCart[0]]), { taxes: __spreadArray(__spreadArray(__spreadArray([], _this._data.taxes[sameTaxInDefaultCart[0]].taxes.slice(0, sameTaxInDefaultCart[1]), true), [
1048
+ __assign(__assign({}, _this._data.taxes[sameTaxInDefaultCart[0]].taxes[sameTaxInDefaultCart[1]]), { amount: (0, round_1.default)(taxAmount, 2) })
1049
+ ], false), _this._data.taxes[sameTaxInDefaultCart[0]].taxes.slice(sameTaxInDefaultCart[1] + 1), true) })
1050
+ ], false), _this._data.taxes.slice(sameTaxInDefaultCart[0] + 1), true) });
1051
+ }
1052
+ }
1053
+ return (0, round_1.default)(taxAmount, 2);
1054
+ };
1055
+ _this.setProCustomerInfo = function (customer) { return __awaiter(_this, void 0, void 0, function () {
1056
+ var proInfo, newCustomerInfo, e_5;
1057
+ var _b, _c, _d, _e, _f, _g;
1058
+ return __generator(this, function (_h) {
1059
+ switch (_h.label) {
1060
+ case 0:
1061
+ proInfo = (0, data_1.getProCustomerInfo)(customer.basic_info, customer.company_info);
1062
+ _h.label = 1;
1063
+ case 1:
1064
+ _h.trys.push([1, 3, , 4]);
1065
+ newCustomerInfo = __assign(__assign({}, (this._data.customer_info || {})), { pro_title: (_b = proInfo.pro_title) !== null && _b !== void 0 ? _b : '', pro_proof_doc: (_c = proInfo.pro_proof_doc) !== null && _c !== void 0 ? _c : '', customer_external_code: (_d = proInfo.customer_external_code) !== null && _d !== void 0 ? _d : '', customer_external_group: (_e = proInfo.customer_external_group) !== null && _e !== void 0 ? _e : '', terms_code: (_f = proInfo.terms_code) !== null && _f !== void 0 ? _f : '', company_name: (_g = proInfo.company_name) !== null && _g !== void 0 ? _g : '' });
1066
+ return [4, this.save({ customer_info: newCustomerInfo })];
1067
+ case 2:
1068
+ _h.sent();
1069
+ return [3, 4];
1070
+ case 3:
1071
+ e_5 = _h.sent();
1072
+ return [3, 4];
1073
+ case 4: return [2];
1074
+ }
1075
+ });
1076
+ }); };
1077
+ _this.setCustomerInfo = function (customer) {
1078
+ var _b, _c, _d, _e, _f, _g, _h, _j, _k;
1079
+ var proInfo = (0, object_1.recursiveCheckObject)(customer, 'basic_info.customer_professionnal_info');
1080
+ var companyName = (0, object_1.recursiveCheckObject)(customer, 'company_info.invoice_info.legal_name');
1081
+ try {
1082
+ _this._data = __assign(__assign({}, _this._data), { customer_id: (_b = customer.id) !== null && _b !== void 0 ? _b : '', user_email: (_c = customer.basic_info.customer_email) !== null && _c !== void 0 ? _c : '', customer_info: __assign({ customer_default_email: (_d = customer.basic_info.customer_email) !== null && _d !== void 0 ? _d : '', customer_type: (_e = (0, object_1.recursiveCheckObject)(customer, 'basic_info.customer_type')) !== null && _e !== void 0 ? _e : Customer_2.BasicCustomerTypeEnum.OTHER }, (!!proInfo
1083
+ ? {
1084
+ pro_title: (_f = proInfo.professionnal_title) !== null && _f !== void 0 ? _f : '',
1085
+ pro_proof_doc: (_g = proInfo.proof_doc_value) !== null && _g !== void 0 ? _g : '',
1086
+ customer_external_code: (_h = proInfo.external_customer_code) !== null && _h !== void 0 ? _h : '',
1087
+ customer_external_group: (_j = proInfo.external_customer_group) !== null && _j !== void 0 ? _j : '',
1088
+ terms_code: (_k = proInfo.terms_code) !== null && _k !== void 0 ? _k : '',
1089
+ company_name: companyName !== null && companyName !== void 0 ? companyName : ''
1090
+ }
1091
+ : {})) });
1092
+ }
1093
+ catch (err) {
1094
+ (0, console_1.errorMessage)(err);
1095
+ }
1096
+ return _this._data;
1097
+ };
1098
+ _this.createPaymentIntent = function () { return __awaiter(_this, void 0, void 0, function () {
1099
+ var space, shippingServiceCredz, _b, paymentStripeRequest, response, error_5;
1100
+ return __generator(this, function (_c) {
1101
+ switch (_c.label) {
1102
+ case 0: return [4, Space_1.default.getCurrentSpaceWithRef(this._collection.path, this._user)];
1103
+ case 1:
1104
+ space = _c.sent();
1105
+ shippingServiceCredz = space.data().external_services.find(function (es) { return !!es.is_active && es.type === 'payment'; });
1106
+ if (!!!shippingServiceCredz)
1107
+ throw new Error("Must have a payment service to use this");
1108
+ _b = shippingServiceCredz.external_service_name;
1109
+ switch (_b) {
1110
+ case 'stripe': return [3, 2];
1111
+ }
1112
+ return [3, 7];
1113
+ case 2:
1114
+ if (!!!shippingServiceCredz.external_service_infos.secret) {
1115
+ this.save({
1116
+ status: Cart_1.CartStatusEnum.CHECKOUT_PAYMENT_FAILED
1117
+ });
1118
+ throw new Error("stripe secret must be set");
1119
+ }
1120
+ _c.label = 3;
1121
+ case 3:
1122
+ _c.trys.push([3, 6, , 7]);
1123
+ return [4, fetch("/api/services/payment/stripe", {
1124
+ method: 'POST',
1125
+ headers: { 'content-type': 'application/json' },
1126
+ body: JSON.stringify({
1127
+ secret: shippingServiceCredz.external_service_infos.secret,
1128
+ amount: (0, toNumber_1.default)((this.data().total * 100).toFixed(2)),
1129
+ currency: 'cad'
1130
+ })
1131
+ })];
1132
+ case 4:
1133
+ paymentStripeRequest = _c.sent();
1134
+ return [4, paymentStripeRequest.json()];
1135
+ case 5:
1136
+ response = _c.sent();
1137
+ if (paymentStripeRequest.status.toString().charAt(0) !== '2') {
1138
+ this.save({
1139
+ status: Cart_1.CartStatusEnum.CHECKOUT_PAYMENT_FAILED
1140
+ });
1141
+ throw new Error(response.error);
1142
+ }
1143
+ return [2, response];
1144
+ case 6:
1145
+ error_5 = _c.sent();
1146
+ (0, console_1.errorMessage)("Error while striping cart ".concat(error_5, " -").concat(JSON.stringify(error_5)));
1147
+ this.save({
1148
+ status: Cart_1.CartStatusEnum.CHECKOUT_PAYMENT_FAILED
1149
+ });
1150
+ throw new Error("Error while striping cart ".concat(error_5, " -").concat(JSON.stringify(error_5)));
1151
+ case 7: throw new Error("This payment service is not handled yet");
1152
+ }
1153
+ });
1154
+ }); };
1155
+ _this.paymentDetails = function (payment_details) { return __awaiter(_this, void 0, void 0, function () {
1156
+ return __generator(this, function (_b) {
1157
+ switch (_b.label) {
1158
+ case 0: return [4, this.save({ payment_details: payment_details }, undefined, true)];
1159
+ case 1: return [2, _b.sent()];
1160
+ }
1161
+ });
1162
+ }); };
1163
+ _this.processPOSPayment = function (payment_request_payload, cart, space, isDev, saveToDatabase, indexCart) {
1164
+ if (isDev === void 0) { isDev = false; }
1165
+ if (saveToDatabase === void 0) { saveToDatabase = true; }
1166
+ if (indexCart === void 0) { indexCart = true; }
1167
+ return __awaiter(_this, void 0, void 0, function () {
1168
+ var stripe_payload, pandapay_payload, paysafe_payload, delay1, err_2, delay2, algoService, prosprService, algolia, prospr, customer, customerQuery, e_6, cartData, error_6, error_7, err_3;
1169
+ return __generator(this, function (_b) {
1170
+ switch (_b.label) {
1171
+ case 0:
1172
+ stripe_payload = undefined;
1173
+ pandapay_payload = undefined;
1174
+ paysafe_payload = undefined;
1175
+ console.log('====================');
1176
+ console.log('in processPOSPayment');
1177
+ _b.label = 1;
1178
+ case 1:
1179
+ _b.trys.push([1, 19, , 20]);
1180
+ console.log('---------------');
1181
+ delay1 = (0, moment_1.default)();
1182
+ _b.label = 2;
1183
+ case 2:
1184
+ _b.trys.push([2, 4, , 5]);
1185
+ return [4, cart.createOrderWithSuccessfulPaymentPayload({
1186
+ pandapay_payload: pandapay_payload,
1187
+ stripe_payload: stripe_payload,
1188
+ paysafe_payload: paysafe_payload,
1189
+ charge_credit: payment_request_payload.charge_credit,
1190
+ other_payment_method: payment_request_payload.other_payment_method,
1191
+ multi_payment_methods: payment_request_payload.multi_payment_methods,
1192
+ isDev: isDev,
1193
+ saveToDatabase: saveToDatabase
1194
+ })];
1195
+ case 3:
1196
+ _b.sent();
1197
+ return [3, 5];
1198
+ case 4:
1199
+ err_2 = _b.sent();
1200
+ return [2, {
1201
+ error: {
1202
+ fr: "Impossible de créer la commande avec une charge de paiement réussie. Aucune charge n'a été reçue.",
1203
+ en: 'Could not create order with successful payment payload. No payload was sent.'
1204
+ }
1205
+ }];
1206
+ case 5:
1207
+ console.log('createOrderWithSuccessfulPaymentPayload delay: ', (0, moment_1.default)().diff(delay1, 'seconds'));
1208
+ if (!!!indexCart) return [3, 18];
1209
+ console.log('---------------');
1210
+ delay2 = (0, moment_1.default)();
1211
+ algoService = space
1212
+ .data()
1213
+ .external_services.find(function (es) { return es.external_service_name.toLowerCase().trim() === 'algolia'; });
1214
+ prosprService = space
1215
+ .data()
1216
+ .external_services.find(function (es) { return es.external_service_name.toLowerCase().trim() === 'prosprsearch'; });
1217
+ if (!(!!algoService || !!prosprService)) return [3, 17];
1218
+ algolia = null;
1219
+ prospr = null;
1220
+ if (!!algoService && algoService.is_active) {
1221
+ algolia = (0, algolia_1.createClient)({
1222
+ app: space.preferences.algolia.app(),
1223
+ indexId: "".concat(__1.isTestEnv ? 'test' : 'prod', "_orders"),
1224
+ key: space.preferences.algolia.admin(),
1225
+ prospr: false
1226
+ });
1227
+ }
1228
+ if (!!prosprService && prosprService.is_active) {
1229
+ prospr = new prosprsearch_1.ProsprSearch({
1230
+ app: space.preferences.prosprsearch.app(),
1231
+ indexId: "".concat(__1.isTestEnv ? 'test' : 'prod', "_orders"),
1232
+ space: space.getId()
1233
+ });
1234
+ }
1235
+ customer = void 0;
1236
+ if (!!!cart.data().customer_id) return [3, 9];
1237
+ _b.label = 6;
1238
+ case 6:
1239
+ _b.trys.push([6, 8, , 9]);
1240
+ return [4, space.customers.get({
1241
+ query: [{ field: 'id', operator: '==', value: cart.data().customer_id }]
1242
+ })];
1243
+ case 7:
1244
+ customerQuery = _b.sent();
1245
+ if (!!customerQuery && !!customerQuery.length) {
1246
+ customer = customerQuery[0];
1247
+ }
1248
+ return [3, 9];
1249
+ case 8:
1250
+ e_6 = _b.sent();
1251
+ console.log('error while fetching customer: ', e_6.toString());
1252
+ return [3, 9];
1253
+ case 9:
1254
+ cartData = (0, cart_1.getIndexedCartData)(cart.data(), space, true, !!customer ? customer.data() : undefined, (0, moment_1.default)().toDate());
1255
+ if (!!!algolia) return [3, 13];
1256
+ _b.label = 10;
1257
+ case 10:
1258
+ _b.trys.push([10, 12, , 13]);
1259
+ return [4, algolia.saveObject(cartData)];
1260
+ case 11:
1261
+ _b.sent();
1262
+ return [3, 13];
1263
+ case 12:
1264
+ error_6 = _b.sent();
1265
+ console.log("Error while saving order in algo", error_6, error_6.toString());
1266
+ return [3, 13];
1267
+ case 13:
1268
+ if (!!!prospr) return [3, 17];
1269
+ _b.label = 14;
1270
+ case 14:
1271
+ _b.trys.push([14, 16, , 17]);
1272
+ return [4, prospr.saveObject(cartData)];
1273
+ case 15:
1274
+ _b.sent();
1275
+ return [3, 17];
1276
+ case 16:
1277
+ error_7 = _b.sent();
1278
+ console.log("Error while saving order in prospr", error_7, error_7.toString());
1279
+ return [3, 17];
1280
+ case 17:
1281
+ console.log('indexing cart delay: ', (0, moment_1.default)().diff(delay2, 'seconds'));
1282
+ _b.label = 18;
1283
+ case 18:
1284
+ console.log('=================');
1285
+ return [2, {
1286
+ accessToken: cart.data().id
1287
+ }];
1288
+ case 19:
1289
+ err_3 = _b.sent();
1290
+ console.log(err_3);
1291
+ console.log('=================');
1292
+ return [2, {
1293
+ error: {
1294
+ fr: 'Nous avons rencontré une erreur...',
1295
+ en: 'We encountered an error'
1296
+ }
1297
+ }];
1298
+ case 20: return [2];
1299
+ }
1300
+ });
1301
+ });
1302
+ };
1303
+ _this.getPaymentMethod = function (options) {
1304
+ if (!!options.multi_payment_methods && !!options.multi_payment_methods.length)
1305
+ return Cart_1.PaymentTypeEnum.MULTIPLE;
1306
+ if (!!options.paypal_payload)
1307
+ return Cart_1.PaymentTypeEnum.PAYPAL;
1308
+ if (!!options.stripe_payload || !!options.pandapay_payload || !!options.paysafe_payload)
1309
+ return Cart_1.PaymentTypeEnum.CREDIT;
1310
+ if (!!options.to_be_received ||
1311
+ (!!options.other_payment_method &&
1312
+ [Cart_1.CustomPaymentTypeEnum.DEPOT].includes(options.other_payment_method.method)))
1313
+ return Cart_1.PaymentTypeEnum.TOBERECEIVED;
1314
+ if (!!options.charge_credit)
1315
+ return Cart_1.PaymentTypeEnum.CREDITED;
1316
+ if (!!options.other_payment_method)
1317
+ return options.other_payment_method.method;
1318
+ return _this.data().paid_by;
1319
+ };
1320
+ _this.createOrderWithSuccessfulPaymentPayload = function (_b) {
1321
+ var paypal_payload = _b.paypal_payload, stripe_payload = _b.stripe_payload, pandapay_payload = _b.pandapay_payload, paysafe_payload = _b.paysafe_payload, _c = _b.charge_credit, charge_credit = _c === void 0 ? false : _c, _d = _b.other_payment_method, other_payment_method = _d === void 0 ? undefined : _d, _e = _b.multi_payment_methods, multi_payment_methods = _e === void 0 ? undefined : _e, isDev = _b.isDev, _f = _b.saveToDatabase, saveToDatabase = _f === void 0 ? true : _f;
1322
+ return __awaiter(_this, void 0, void 0, function () {
1323
+ var space, getPaymentRef, newRef, incrementSpaceRef, delay1, partialCartPaidData, delay2, isPOSTransactionnal, delay3, invoiceRef, delay5, error_8, delay6, e_7, error_9;
1324
+ var _this = this;
1325
+ return __generator(this, function (_g) {
1326
+ switch (_g.label) {
1327
+ case 0:
1328
+ console.log('====================');
1329
+ console.log('in createOrderWithSuccessfulPaymentPayload');
1330
+ if (!!!paypal_payload &&
1331
+ !!!stripe_payload &&
1332
+ !!!pandapay_payload &&
1333
+ !!!paysafe_payload &&
1334
+ !!!charge_credit &&
1335
+ !!!other_payment_method &&
1336
+ !!!multi_payment_methods)
1337
+ throw new Error("Payment intent payload must be set");
1338
+ return [4, Space_1.default.getCurrentSpaceWithRef(this._collection.path, this._user)];
1339
+ case 1:
1340
+ space = _g.sent();
1341
+ getPaymentRef = function () {
1342
+ return !!other_payment_method && !!other_payment_method.payment_ref
1343
+ ? other_payment_method.payment_ref
1344
+ : !!pandapay_payload
1345
+ ? pandapay_payload.unique_ref
1346
+ : !!paysafe_payload
1347
+ ? paysafe_payload.id
1348
+ : !!stripe_payload
1349
+ ? stripe_payload.id
1350
+ : !!paypal_payload
1351
+ ? paypal_payload.paymentID
1352
+ : !!_this.data().payment_reference
1353
+ ? _this.data().payment_reference
1354
+ : '';
1355
+ };
1356
+ newRef = !!isDev ? 123456789 : undefined;
1357
+ incrementSpaceRef = function () { return __awaiter(_this, void 0, void 0, function () {
1358
+ var error_10, cartData, exisingCartWithNewRef;
1359
+ return __generator(this, function (_b) {
1360
+ switch (_b.label) {
1361
+ case 0:
1362
+ _b.trys.push([0, 2, , 4]);
1363
+ return [4, space.incrementOrderAndInvoiceRef()];
1364
+ case 1:
1365
+ newRef = _b.sent();
1366
+ return [3, 4];
1367
+ case 2:
1368
+ error_10 = _b.sent();
1369
+ console.log("error while incrementing spage ref", error_10);
1370
+ return [4, (0, console_1.alertAdminV2)("Error while incrementaing space ref", "We got ref #".concat(newRef, " and it was impossible to increment space ref. We are in space ").concat(space.data().id), error_10.toString(), space.getRef())];
1371
+ case 3:
1372
+ _b.sent();
1373
+ return [3, 4];
1374
+ case 4:
1375
+ cartData = this.data();
1376
+ return [4, space.carts.get({
1377
+ query: [{ field: 'ref', operator: '==', value: (0, toString_1.default)(newRef) }]
1378
+ })];
1379
+ case 5:
1380
+ exisingCartWithNewRef = _b.sent();
1381
+ if (!((!!exisingCartWithNewRef && exisingCartWithNewRef.length > 0) || !!!newRef)) return [3, 7];
1382
+ if (!!cartData && !!newRef && !!cartData.id && cartData.id === exisingCartWithNewRef[0].data().id) {
1383
+ return [2];
1384
+ }
1385
+ return [4, incrementSpaceRef()];
1386
+ case 6:
1387
+ _b.sent();
1388
+ _b.label = 7;
1389
+ case 7: return [2];
1390
+ }
1391
+ });
1392
+ }); };
1393
+ console.log('---------------');
1394
+ delay1 = (0, moment_1.default)();
1395
+ if (!!isDev) return [3, 3];
1396
+ return [4, incrementSpaceRef()];
1397
+ case 2:
1398
+ _g.sent();
1399
+ _g.label = 3;
1400
+ case 3:
1401
+ console.log('increment space ref delay: ', (0, moment_1.default)().diff(delay1, 'seconds'));
1402
+ partialCartPaidData = __assign(__assign(__assign({ paid_by: this.getPaymentMethod({
1403
+ paypal_payload: paypal_payload,
1404
+ stripe_payload: stripe_payload,
1405
+ pandapay_payload: pandapay_payload,
1406
+ paysafe_payload: paysafe_payload,
1407
+ charge_credit: charge_credit,
1408
+ other_payment_method: other_payment_method,
1409
+ multi_payment_methods: multi_payment_methods
1410
+ }) }, (this._data.cart_type === Cart_1.CartTypeEnum.WEB && !!other_payment_method && !!other_payment_method.method
1411
+ ? {
1412
+ custom_payment_type: __assign({ method: other_payment_method.method }, (!!other_payment_method.amount ? { amount: other_payment_method.amount } : {}))
1413
+ }
1414
+ : {})), (!!multi_payment_methods && !!multi_payment_methods.length ? { payment_details: multi_payment_methods } : {})), { paypal_payload: paypal_payload, stripe_payload: stripe_payload, pandapay_payload: pandapay_payload, paysafe_payload: paysafe_payload, paid_at: (0, moment_1.default)().toDate(), status: Cart_1.CartStatusEnum.CHECKOUT_PAYMENT_SUCCESS, payment_reference: getPaymentRef(), ref: isDev ? "".concat((0, toString_1.default)(newRef), "-test") : (0, toString_1.default)(newRef), is_test: isDev, is: this.defineWhatICanBe() });
1415
+ _g.label = 4;
1416
+ case 4:
1417
+ _g.trys.push([4, 19, , 21]);
1418
+ console.log('---------------');
1419
+ delay2 = (0, moment_1.default)();
1420
+ return [4, this.save(partialCartPaidData, undefined, saveToDatabase)];
1421
+ case 5:
1422
+ _g.sent();
1423
+ console.log('saving to DB delay: ', (0, moment_1.default)().diff(delay2, 'seconds'));
1424
+ isPOSTransactionnal = this.data().cart_type === Cart_1.CartTypeEnum.POS_TRANSACTIONNAL;
1425
+ if (!!!isPOSTransactionnal) return [3, 8];
1426
+ console.log('---------------');
1427
+ delay3 = (0, moment_1.default)();
1428
+ return [4, this.setCartWithInvoiceRef(space, false)];
1429
+ case 6:
1430
+ invoiceRef = _g.sent();
1431
+ console.log("saving POS transactionnal cart to database: ".concat(!!saveToDatabase, ", with ref: ").concat(partialCartPaidData.ref, ", status: ").concat(partialCartPaidData.status, " and invoice ref: ").concat(partialCartPaidData.invoice_ref));
1432
+ return [4, this.save({ status: Cart_1.CartStatusEnum.COMPLETED, invoice_ref: invoiceRef }, undefined, !!saveToDatabase)];
1433
+ case 7:
1434
+ _g.sent();
1435
+ console.log('setting invoice ref delay: ', (0, moment_1.default)().diff(delay3, 'seconds'));
1436
+ _g.label = 8;
1437
+ case 8:
1438
+ console.log('---------------');
1439
+ delay5 = (0, moment_1.default)();
1440
+ _g.label = 9;
1441
+ case 9:
1442
+ _g.trys.push([9, 11, , 13]);
1443
+ return [4, space.inventory.ajust(this.data().items, 'paid', this.data().cart_type, this.data().current_store_id || '')];
1444
+ case 10:
1445
+ _g.sent();
1446
+ return [3, 13];
1447
+ case 11:
1448
+ error_8 = _g.sent();
1449
+ console.log('error while updating inventory', error_8);
1450
+ return [4, (0, console_1.alertAdminV2)("Error while updating inventory", "We are here: /src/lib/Cart/index.ts#1574. We are in space ".concat(space.data().id, ". JSON error: ").concat(JSON.stringify(error_8)), error_8.toString(), space.getRef())];
1451
+ case 12:
1452
+ _g.sent();
1453
+ return [3, 13];
1454
+ case 13:
1455
+ console.log('adjusting inventory delay: ', (0, moment_1.default)().diff(delay5, 'seconds'));
1456
+ if (!!!this._data.promise_to_purchase) return [3, 18];
1457
+ console.log('---------------');
1458
+ delay6 = (0, moment_1.default)();
1459
+ _g.label = 14;
1460
+ case 14:
1461
+ _g.trys.push([14, 16, , 17]);
1462
+ return [4, this.checkForEmptyBanksAfterPayment(space)];
1463
+ case 15:
1464
+ _g.sent();
1465
+ return [3, 17];
1466
+ case 16:
1467
+ e_7 = _g.sent();
1468
+ console.log('error on checking for empty banks after payment: ', e_7.toString());
1469
+ return [3, 17];
1470
+ case 17:
1471
+ console.log('checkForEmptyBanks delay: ', (0, moment_1.default)().diff(delay6, 'seconds'));
1472
+ _g.label = 18;
1473
+ case 18: return [3, 21];
1474
+ case 19:
1475
+ error_9 = _g.sent();
1476
+ return [4, (0, console_1.alertAdminV2)("Error while saving new cart", "We are here: /src/lib/Cart/index.ts#1352. We are in space ".concat(space.data().id, ". JSON error: ").concat(JSON.stringify(error_9)), error_9.toString(), space.getRef())];
1477
+ case 20:
1478
+ _g.sent();
1479
+ throw error_9;
1480
+ case 21:
1481
+ console.log('====================');
1482
+ return [2, this];
1483
+ }
1484
+ });
1485
+ });
1486
+ };
1487
+ _this.setCartAsCompleted = function (saveToDatabase) {
1488
+ if (saveToDatabase === void 0) { saveToDatabase = true; }
1489
+ return __awaiter(_this, void 0, void 0, function () {
1490
+ var space, delay1, skipRef, delay2, e_8;
1491
+ return __generator(this, function (_b) {
1492
+ switch (_b.label) {
1493
+ case 0:
1494
+ console.log('====================');
1495
+ console.log('in setCartAsCompleted');
1496
+ _b.label = 1;
1497
+ case 1:
1498
+ _b.trys.push([1, 6, , 7]);
1499
+ return [4, Space_1.default.getCurrentSpaceWithRef(this._collection.path, this._user)];
1500
+ case 2:
1501
+ space = _b.sent();
1502
+ if (!!!space)
1503
+ throw new Error('could not init space obj');
1504
+ console.log('---------------');
1505
+ delay1 = (0, moment_1.default)();
1506
+ skipRef = false;
1507
+ if (!!this.data().is_booking || !!this.data().is_booking_beton)
1508
+ skipRef = true;
1509
+ if (!(!!!this.data().invoice_ref && !!!skipRef)) return [3, 4];
1510
+ return [4, this.setCartWithInvoiceRef(space, false)];
1511
+ case 3:
1512
+ _b.sent();
1513
+ _b.label = 4;
1514
+ case 4:
1515
+ console.log('setting invoice ref delay: ', (0, moment_1.default)().diff(delay1, 'seconds'));
1516
+ console.log('---------------');
1517
+ delay2 = (0, moment_1.default)();
1518
+ return [4, this.save({
1519
+ status: Cart_1.CartStatusEnum.COMPLETED
1520
+ }, undefined, !!saveToDatabase)];
1521
+ case 5:
1522
+ _b.sent();
1523
+ console.log('saving cart delay: ', (0, moment_1.default)().diff(delay2, 'seconds'));
1524
+ console.log('====================');
1525
+ return [2, this];
1526
+ case 6:
1527
+ e_8 = _b.sent();
1528
+ console.log('error on setting cart as completed : ', e_8.toString());
1529
+ return [3, 7];
1530
+ case 7: return [2];
1531
+ }
1532
+ });
1533
+ });
1534
+ };
1535
+ _this.saveCartModification = function (partial, oldItems, newItems, currentUser, usedPromise, saveToDatabase) {
1536
+ if (saveToDatabase === void 0) { saveToDatabase = true; }
1537
+ return __awaiter(_this, void 0, void 0, function () {
1538
+ var itemsForInventory, space, _loop_2, this_1, _b, _c, bank, data, storeIdToUse, e_9;
1539
+ return __generator(this, function (_d) {
1540
+ switch (_d.label) {
1541
+ case 0:
1542
+ _d.trys.push([0, 7, , 8]);
1543
+ itemsForInventory = (0, cart_1.getModifiedItems)(newItems, oldItems);
1544
+ return [4, Space_1.default.getCurrentSpaceWithRef(this._collection.path, this._user)];
1545
+ case 1:
1546
+ space = _d.sent();
1547
+ if (!!!space)
1548
+ throw new Error('could not init space obj');
1549
+ if (!!!usedPromise) return [3, 5];
1550
+ _loop_2 = function (bank) {
1551
+ var promiseQuery, bankInDB, amountTotal, taxes, itemsWithoutInstallation, adjustment, remainingAmount, newRemainingAmount;
1552
+ return __generator(this, function (_e) {
1553
+ switch (_e.label) {
1554
+ case 0: return [4, space.promisesToPurchase.get({
1555
+ query: [{ field: 'id', operator: '==', value: bank.promise_id }]
1556
+ })];
1557
+ case 1:
1558
+ promiseQuery = _e.sent();
1559
+ if (!!!promiseQuery || !!!promiseQuery.length)
1560
+ return [2, "continue"];
1561
+ if (!!promiseQuery[0].data().ending_date)
1562
+ return [2, "continue"];
1563
+ bankInDB = promiseQuery[0].data().banks.find(function (b) { return b.bank_type_id === bank.bank_type_id; });
1564
+ if (!!!bankInDB || !!!bankInDB.active)
1565
+ return [2, "continue"];
1566
+ amountTotal = 0;
1567
+ taxes = this_1.data().total - this_1.data().subtotal;
1568
+ if ((0, promiseToPurchase_1.getBankTypeName)(space.bankTypes.get(), bank.bank_type_id) === 'installation') {
1569
+ amountTotal = Number((0, products_2.getInstallItemPrice)('installation-gazon', itemsForInventory.filter(function (i) { return !!i.is_service; })));
1570
+ }
1571
+ else {
1572
+ itemsWithoutInstallation = itemsForInventory.filter(function (i) { return !!!i.parent_slug || !!!['installation-gazon', 'frais-de-mobilisation'].includes(i.parent_slug); });
1573
+ itemsWithoutInstallation.map(function (i) { return (amountTotal += (0, products_1.getLowestPrice)(i).price.amount * i.qte); });
1574
+ amountTotal += taxes;
1575
+ }
1576
+ adjustment = {
1577
+ amount: amountTotal * -1,
1578
+ reason: "Modification de la commande #".concat(this_1.data().ref),
1579
+ issued_at: new Date(),
1580
+ issued_by: !!currentUser ? currentUser : (0, services_1.getDefaultSpaceUserEmail)(space.data().id)
1581
+ };
1582
+ return [4, space.promisesToPurchase.getSpecificAvailableBankAmount(bank.promise_id, bank.bank_type_id, promiseQuery[0])];
1583
+ case 2:
1584
+ remainingAmount = _e.sent();
1585
+ newRemainingAmount = void 0;
1586
+ if (!!remainingAmount && !!remainingAmount.remaining_amount) {
1587
+ newRemainingAmount = (0, round_1.default)(remainingAmount.remaining_amount, 3) + (0, round_1.default)(adjustment.amount);
1588
+ }
1589
+ return [4, promiseQuery[0].adjustAmountLeftInPromise(adjustment, bank.bank_type_id, !!newRemainingAmount && newRemainingAmount < 1)];
1590
+ case 3:
1591
+ _e.sent();
1592
+ return [2];
1593
+ }
1594
+ });
1595
+ };
1596
+ this_1 = this;
1597
+ _b = 0, _c = usedPromise.banks_used;
1598
+ _d.label = 2;
1599
+ case 2:
1600
+ if (!(_b < _c.length)) return [3, 5];
1601
+ bank = _c[_b];
1602
+ return [5, _loop_2(bank)];
1603
+ case 3:
1604
+ _d.sent();
1605
+ _d.label = 4;
1606
+ case 4:
1607
+ _b++;
1608
+ return [3, 2];
1609
+ case 5: return [4, this.save(partial, undefined, !!saveToDatabase)];
1610
+ case 6:
1611
+ _d.sent();
1612
+ data = this.data();
1613
+ storeIdToUse = !!data.current_store_id
1614
+ ? data.current_store_id
1615
+ : !!data.processed_by
1616
+ ? data.processed_by.at_store_id
1617
+ : '';
1618
+ space.inventory.ajust(itemsForInventory, 'modified', this.data().cart_type, storeIdToUse, this.data().status === 5);
1619
+ return [2, this];
1620
+ case 7:
1621
+ e_9 = _d.sent();
1622
+ console.log('error on saving cart modification : ', e_9.toString());
1623
+ return [3, 8];
1624
+ case 8: return [2];
1625
+ }
1626
+ });
1627
+ });
1628
+ };
1629
+ _this.defineWhatICanBe = function () {
1630
+ return [];
1631
+ };
1632
+ _this.checkDiscountConditions = function (discount) {
1633
+ return (0, discount_1.checkPromoCodeEligibility)(_this._data, discount);
1634
+ };
1635
+ _this.getLowestPrice = function (item) {
1636
+ var lowest = (0, products_1.getLowestPrice)(item);
1637
+ return lowest.price.amount;
1638
+ };
1639
+ _this.removeCartDiscount = function (aPromoId) { return __awaiter(_this, void 0, void 0, function () {
1640
+ return __generator(this, function (_b) {
1641
+ switch (_b.label) {
1642
+ case 0:
1643
+ this._data = __assign(__assign(__assign(__assign({}, this._data), (!!this._data.cart_promo_applied ? { cart_promo_applied: null } : {})), (!!this._data.cart_promos_applied && !!aPromoId
1644
+ ? {
1645
+ cart_promos_applied: this._data.cart_promos_applied.filter(function (p) { return p.discount_id !== aPromoId; })
1646
+ }
1647
+ : {})), { subtotalWithoutPromotions: null, free_shipping: false });
1648
+ return [4, this.calculateTotals()];
1649
+ case 1:
1650
+ _b.sent();
1651
+ return [4, this.save()];
1652
+ case 2:
1653
+ _b.sent();
1654
+ return [2, true];
1655
+ }
1656
+ });
1657
+ }); };
1658
+ _this.checkPromoCode = function (promoCode, oldPromos) { return __awaiter(_this, void 0, void 0, function () {
1659
+ var space, cartData, discountRules, discountWithSamePromoCode, fullMapPromoCode, cartPromo, freeShippingRestrictions, shippingState_1, shippingStateValue, allDiscountRulesOk, newPromo, action, err_4;
1660
+ var _b;
1661
+ return __generator(this, function (_c) {
1662
+ switch (_c.label) {
1663
+ case 0: return [4, Space_1.default.getCurrentSpaceWithRef(this._collection.path, this._user)];
1664
+ case 1:
1665
+ space = _c.sent();
1666
+ cartData = this._data;
1667
+ if (!!!cartData)
1668
+ return [2, "Une erreur s'est produite"];
1669
+ discountRules = !!oldPromos
1670
+ ? cartData.discount_rules.filter(function (d) {
1671
+ return (!!d.created && (0, moment_1.default)((0, data_1.formatDate)(d.created)).isBefore((0, moment_1.default)((0, data_1.formatDate)(cartData.paid_at)))) ||
1672
+ (!!d.promo_code && !!d.promo_code.code) ||
1673
+ !!!d.created;
1674
+ })
1675
+ : cartData.discount_rules;
1676
+ discountWithSamePromoCode = discountRules.find(function (discount) {
1677
+ return !!discount.promo_code && !!discount.promo_code.code && discount.promo_code.code === promoCode;
1678
+ });
1679
+ if (!!!discountWithSamePromoCode ||
1680
+ (!!discountWithSamePromoCode.promo_code && !!discountWithSamePromoCode.promo_code.disabled)) {
1681
+ this.addError(Cart_1.CartErrorEnum.PROMO_CODE_WRONG_CODE);
1682
+ return [2, Cart_1.CartErrorEnum.PROMO_CODE_WRONG_CODE];
1683
+ }
1684
+ fullMapPromoCode = discountWithSamePromoCode.promo_code;
1685
+ if (!!!fullMapPromoCode || !!fullMapPromoCode.disabled) {
1686
+ this.addError(Cart_1.CartErrorEnum.PROMO_CODE_WRONG_CODE);
1687
+ return [2, Cart_1.CartErrorEnum.PROMO_CODE_WRONG_CODE];
1688
+ }
1689
+ cartPromo = this.getCartPromo();
1690
+ if (!!cartPromo && !!cartPromo.length) {
1691
+ if (!!cartPromo.some(function (i) { return i.promo_code === promoCode; })) {
1692
+ this.addError(Cart_1.CartErrorEnum.PROMO_CODE_ALREADY_IN_CART);
1693
+ return [2, Cart_1.CartErrorEnum.PROMO_CODE_ALREADY_IN_CART];
1694
+ }
1695
+ if (!!cartPromo.some(function (i) { return i.promo_code; }) ||
1696
+ !!cartData.free_shipping ||
1697
+ (!!!discountWithSamePromoCode.is_stackable && !!cartPromo.length) ||
1698
+ cartPromo.some(function (x) { return !x.stackable; })) {
1699
+ this.addError(Cart_1.CartErrorEnum.PROMO_CODE_CART_ALREADY_DISCOUNTED);
1700
+ return [2, Cart_1.CartErrorEnum.PROMO_CODE_CART_ALREADY_DISCOUNTED];
1701
+ }
1702
+ }
1703
+ if (!!fullMapPromoCode.used_by_user_id && !!fullMapPromoCode.used_by_user_id.length) {
1704
+ if (!!!cartData.customer_id && !!!cartData.user_email && cartData.cart_type === Cart_1.CartTypeEnum.WEB) {
1705
+ this.addError(Cart_1.CartErrorEnum.GENERAL_ERROR_USER);
1706
+ return [2, Cart_1.CartErrorEnum.GENERAL_ERROR_USER];
1707
+ }
1708
+ if (!!cartData.customer_id) {
1709
+ if (fullMapPromoCode.used_by_user_id.includes(cartData.customer_id) && !!fullMapPromoCode.once_per_client) {
1710
+ this.addError(Cart_1.CartErrorEnum.PROMO_CODE_USED);
1711
+ return [2, Cart_1.CartErrorEnum.PROMO_CODE_USED];
1712
+ }
1713
+ }
1714
+ if (!!cartData.user_email) {
1715
+ if (fullMapPromoCode.used_by_user_id.includes(cartData.user_email) && !!fullMapPromoCode.once_per_client) {
1716
+ this.addError(Cart_1.CartErrorEnum.PROMO_CODE_USED);
1717
+ return [2, Cart_1.CartErrorEnum.PROMO_CODE_USED];
1718
+ }
1719
+ }
1720
+ }
1721
+ if (discountWithSamePromoCode.appliesTo.label === 'cart' &&
1722
+ ['flatrate_shipping', 'free_shipping'].includes(discountWithSamePromoCode.result.action)) {
1723
+ if (!!!cartData.shipping_selected) {
1724
+ this.addError(Cart_1.CartErrorEnum.PROMO_CODE_NO_SHIPPING_SELECTED);
1725
+ return [2, Cart_1.CartErrorEnum.PROMO_CODE_NO_SHIPPING_SELECTED];
1726
+ }
1727
+ if (!!cartData.is_pickup) {
1728
+ this.addError(Cart_1.CartErrorEnum.PROMO_CODE_NOT_ELIGIBLE);
1729
+ return [2, Cart_1.CartErrorEnum.PROMO_CODE_NOT_ELIGIBLE];
1730
+ }
1731
+ }
1732
+ if (discountWithSamePromoCode.appliesTo.label === 'cart' &&
1733
+ discountWithSamePromoCode.result.action === 'free_shipping') {
1734
+ freeShippingRestrictions = space.preferences.shipping.restrict.getFree();
1735
+ shippingState_1 = !!cartData.shipping_address && cartData.shipping_address.address.state;
1736
+ if (!!shippingState_1) {
1737
+ shippingStateValue = data_1.provinces.find(function (province) { return province.label === shippingState_1 || province.label_en === shippingState_1; });
1738
+ if (!!shippingStateValue) {
1739
+ if (!!freeShippingRestrictions &&
1740
+ !!freeShippingRestrictions.limit_states &&
1741
+ !freeShippingRestrictions.limit_states.includes(shippingStateValue.value)) {
1742
+ this.addError(Cart_1.CartErrorEnum.PROMO_CODE_FREE_SHIPPING);
1743
+ return [2, Cart_1.CartErrorEnum.PROMO_CODE_FREE_SHIPPING];
1744
+ }
1745
+ }
1746
+ }
1747
+ }
1748
+ allDiscountRulesOk = (0, discount_1.checkPromoCodeEligibility)(this._data, discountWithSamePromoCode);
1749
+ if (!!!allDiscountRulesOk) {
1750
+ this.addError(Cart_1.CartErrorEnum.PROMO_CODE_NOT_ELIGIBLE);
1751
+ return [2, Cart_1.CartErrorEnum.PROMO_CODE_NOT_ELIGIBLE];
1752
+ }
1753
+ _c.label = 2;
1754
+ case 2:
1755
+ _c.trys.push([2, 4, , 5]);
1756
+ newPromo = void 0;
1757
+ action = (_b = discountWithSamePromoCode.result.action) !== null && _b !== void 0 ? _b : '';
1758
+ if (action === IDiscountRule_1.ResultActionEnum.FREE_SHIPPING || action === IDiscountRule_1.ResultActionEnum.FLATERATE_SHIPPING) {
1759
+ newPromo = __assign({ promo_name: (0, locale_1.getPrincipalWord)(discountWithSamePromoCode.name, space), applies_to: (0, discount_1.getCartPromoType)(discountWithSamePromoCode), amount_removed: 2, amount_unit: action, item_given: '', item_given_amount: 0, free_shipping: action === IDiscountRule_1.ResultActionEnum.FREE_SHIPPING, stackable: discountWithSamePromoCode.is_stackable, discount_id: discountWithSamePromoCode.id, flatrate_shipping: action === IDiscountRule_1.ResultActionEnum.FLATERATE_SHIPPING ? Number(discountWithSamePromoCode.result.action_value) : 0, promo_code: promoCode }, (typeof discountWithSamePromoCode.result.exclude_services_and_fees === 'boolean'
1760
+ ? {
1761
+ exclude_services_and_fees: discountWithSamePromoCode.result.exclude_services_and_fees
1762
+ }
1763
+ : {}));
1764
+ this._data = __assign(__assign({}, cartData), { cart_promos_applied: __spreadArray(__spreadArray([], (cartData.cart_promos_applied || []), true), [newPromo], false), free_shipping: discountWithSamePromoCode.result.action === IDiscountRule_1.ResultActionEnum.FREE_SHIPPING });
1765
+ }
1766
+ else {
1767
+ newPromo = __assign({ promo_name: (0, locale_1.getPrincipalWord)(discountWithSamePromoCode.name, space), applies_to: (0, discount_1.getCartPromoType)(discountWithSamePromoCode), amount_removed: (0, toNumber_1.default)(discountWithSamePromoCode.result.action_value), amount_unit: action || IDiscountRule_1.ResultActionEnum.PERCENT, item_given: (0, discount_1.getResultAppliedDiscountSkus)(this._data.items, discountWithSamePromoCode), item_given_amount: 0, free_shipping: false, flatrate_shipping: 0, promo_code: promoCode, stackable: discountWithSamePromoCode.is_stackable, discount_id: discountWithSamePromoCode.id }, (typeof discountWithSamePromoCode.result.exclude_services_and_fees === 'boolean'
1768
+ ? {
1769
+ exclude_services_and_fees: discountWithSamePromoCode.result.exclude_services_and_fees
1770
+ }
1771
+ : {}));
1772
+ this._data = __assign(__assign({}, cartData), { cart_promos_applied: __spreadArray(__spreadArray([], (cartData.cart_promos_applied || []), true), [newPromo], false), free_shipping: false });
1773
+ }
1774
+ return [4, this.save()];
1775
+ case 3:
1776
+ _c.sent();
1777
+ return [2, ''];
1778
+ case 4:
1779
+ err_4 = _c.sent();
1780
+ console.log('error: ', err_4);
1781
+ this.addError(Cart_1.CartErrorEnum.GENERAL_ERROR);
1782
+ return [2, Cart_1.CartErrorEnum.GENERAL_ERROR];
1783
+ case 5: return [2];
1784
+ }
1785
+ });
1786
+ }); };
1787
+ _this.setDiscountRules = function (removePaymentIncentive) { return __awaiter(_this, void 0, void 0, function () {
1788
+ var space, allDiscountRules, discountsToAdd, _b, allDiscountRules_1, discount, discountData;
1789
+ return __generator(this, function (_c) {
1790
+ switch (_c.label) {
1791
+ case 0:
1792
+ if (!!this._data.is_booking || !!this._data.is_booking_beton) {
1793
+ if (!!__1.isTestEnv)
1794
+ console.log('skipping discount rule check for booking cart!');
1795
+ return [2];
1796
+ }
1797
+ return [4, Space_1.default.getCurrentSpaceWithRef(this._collection.path, this._user)];
1798
+ case 1:
1799
+ space = _c.sent();
1800
+ if (!!!space)
1801
+ return [2, new Error("Can't find space")];
1802
+ return [4, space.discountRules.get({
1803
+ query: [{ field: 'appliesTo.label', operator: '==', value: 'cart' }]
1804
+ })];
1805
+ case 2:
1806
+ allDiscountRules = _c.sent();
1807
+ discountsToAdd = [];
1808
+ for (_b = 0, allDiscountRules_1 = allDiscountRules; _b < allDiscountRules_1.length; _b++) {
1809
+ discount = allDiscountRules_1[_b];
1810
+ discountData = discount.data();
1811
+ if (!!discountData.draft)
1812
+ continue;
1813
+ if (!!removePaymentIncentive) {
1814
+ if (!!!discountData.result.action ||
1815
+ [IDiscountRule_1.ResultActionEnum.AMOUNT_AFTER_TAXES, IDiscountRule_1.ResultActionEnum.PERCENT_AFTER_TAXES].includes(discountData.result.action))
1816
+ continue;
1817
+ }
1818
+ discountsToAdd.push(discountData);
1819
+ }
1820
+ this._data = __assign(__assign({}, this._data), { discount_rules: __spreadArray(__spreadArray([], (!!this._data.is_booking && !!this._data.discount_rules ? this._data.discount_rules : []), true), discountsToAdd, true) });
1821
+ return [2];
1822
+ }
1823
+ });
1824
+ }); };
1825
+ _this.checkTierPricing = function (itemToCheck, qte, index, findWithSku, originalDecli) {
1826
+ if (findWithSku === void 0) { findWithSku = false; }
1827
+ var currentItems = _this._data.items;
1828
+ if (!!!itemToCheck)
1829
+ return currentItems;
1830
+ var item = currentItems.find(function (anItem) { return anItem.sku === (typeof itemToCheck === 'string' ? itemToCheck : itemToCheck.sku); });
1831
+ if (!!!item)
1832
+ return currentItems;
1833
+ if (!!!item.tier_pricing || !!!item.tier_pricing.length) {
1834
+ _this._updateQuantity(item, qte);
1835
+ return currentItems;
1836
+ }
1837
+ if (item.tier_pricing.some(function (aTier) { return !!aTier.check_attribute_value || !!aTier.check_other_items_category; })) {
1838
+ return _this.checkAttributes(item, qte);
1839
+ }
1840
+ var setOriginalPrice = !!item.discount_price &&
1841
+ !!item.discount_price.overridden &&
1842
+ typeof item.discount_price.original_amount === 'number';
1843
+ var newDiscountPrice = (0, discount_1.getNewDiscountPriceFromTierPricing)(item, setOriginalPrice, originalDecli);
1844
+ return _this._updateItems(!!findWithSku
1845
+ ? currentItems.map(function (i) {
1846
+ if (i.sku !== item.sku)
1847
+ return i;
1848
+ return __assign(__assign({}, i), { discount_price: newDiscountPrice, qte: qte });
1849
+ })
1850
+ : __spreadArray(__spreadArray(__spreadArray([], currentItems.slice(0, index), true), [
1851
+ __assign(__assign({}, item), { discount_price: newDiscountPrice, qte: qte })
1852
+ ], false), currentItems.slice(index + 1), true)).items;
1853
+ };
1854
+ _this._updateItems = function (items) {
1855
+ _this._data = __assign(__assign({}, _this._data), { items: items });
1856
+ return _this._data;
1857
+ };
1858
+ _this.checkAttributes = function (item, qte) {
1859
+ _this._updateQuantity(item, qte);
1860
+ if (DatabaseService_1.default.getPathParent(_this._collection.path) == '/')
1861
+ return _this._data.items;
1862
+ if (!!!item.tier_pricing)
1863
+ return _this._data.items;
1864
+ var allItems = _this._data.items.filter(function (item) { return (0, locale_1.getLocaleOfDictionnary)(item.name, _this._data.locale) !== ''; });
1865
+ var allItemsToCheck = allItems.filter(function (anItem) {
1866
+ return !!anItem.tier_pricing &&
1867
+ !!anItem.tier_pricing.length &&
1868
+ anItem !== item &&
1869
+ anItem.tier_pricing.filter(function (aTier) { return !!aTier.check_attribute_value || !!aTier.check_other_items_category; });
1870
+ });
1871
+ if (!!!allItemsToCheck.length) {
1872
+ return _this._data.items;
1873
+ }
1874
+ var tierToCheck = item.tier_pricing.find(function (aTier) { return !!aTier.check_attribute_value; });
1875
+ var attributeToCheck = !!tierToCheck && tierToCheck.check_attribute_value;
1876
+ var allSameAttribute = [];
1877
+ if (!!attributeToCheck) {
1878
+ allSameAttribute = allItemsToCheck.filter(function (anItem) { return !!anItem.attributes && !!anItem.attributes[attributeToCheck]; });
1879
+ }
1880
+ else {
1881
+ allSameAttribute = allItemsToCheck;
1882
+ }
1883
+ var categoryToCheck = !!item.tier_pricing && item.tier_pricing[0].check_other_items_category
1884
+ ? item.tier_pricing[0].check_other_items_category
1885
+ : '';
1886
+ var allSameCategory = allSameAttribute;
1887
+ if (!!categoryToCheck) {
1888
+ allSameCategory = allSameAttribute.filter(function (anItem) {
1889
+ return !!anItem.tier_pricing &&
1890
+ !!anItem.tier_pricing.filter(function (aTier) { return !!aTier.check_other_items_category && aTier.check_other_items_category === categoryToCheck; }).length;
1891
+ });
1892
+ }
1893
+ var totalQte = (0, sumBy_1.default)(allSameCategory, function (anItem) {
1894
+ try {
1895
+ if (!!!attributeToCheck)
1896
+ return anItem.qte;
1897
+ var attributes = anItem.attributes[attributeToCheck];
1898
+ if (!!!attributes || (Array.isArray(attributes) && !!!attributes.length))
1899
+ return anItem.qte;
1900
+ var firstValue = (0, isNumber_1.default)((0, toNumber_1.default)(attributes[0])) ? (0, toNumber_1.default)(attributes[0]) : 0;
1901
+ if (!!!firstValue)
1902
+ return anItem.qte;
1903
+ var attributeValue = firstValue;
1904
+ return anItem.qte * (0, toNumber_1.default)(attributeValue);
1905
+ }
1906
+ catch (err) {
1907
+ return anItem.qte;
1908
+ }
1909
+ }) || 0;
1910
+ if (!!item.tier_pricing) {
1911
+ var isFirst = true;
1912
+ var _loop_3 = function (aTier) {
1913
+ if (isFirst && (0, toNumber_1.default)(aTier.from) > totalQte) {
1914
+ var _loop_4 = function (anItem) {
1915
+ var index = _this._data.items.indexOf(anItem);
1916
+ _this._updateItems(_this._data.items.map(function (i) {
1917
+ if (i.sku !== anItem.sku)
1918
+ return i;
1919
+ return __assign(__assign({}, i), { discount_price: anItem.regular_price, qte: anItem === item ? qte : anItem.qte });
1920
+ }));
1921
+ };
1922
+ for (var _d = 0, allSameCategory_1 = allSameCategory; _d < allSameCategory_1.length; _d++) {
1923
+ var anItem = allSameCategory_1[_d];
1924
+ _loop_4(anItem);
1925
+ }
1926
+ isFirst = false;
1927
+ return "continue";
1928
+ }
1929
+ if ((0, toNumber_1.default)(aTier.from) <= totalQte && (!!!aTier.to || (0, toNumber_1.default)(aTier.to) >= totalQte)) {
1930
+ var _loop_5 = function (anItem) {
1931
+ _this._updateItems(_this._data.items.map(function (i) {
1932
+ if (i.sku !== anItem.sku)
1933
+ return i;
1934
+ if (!!!i.tier_pricing)
1935
+ return i;
1936
+ return __assign(__assign({}, i), { discount_price: anItem === item
1937
+ ? aTier.price
1938
+ : i.tier_pricing.some(function (otherTier) {
1939
+ return (0, toNumber_1.default)(otherTier.from) >= (0, toNumber_1.default)(aTier.from) &&
1940
+ (!!!otherTier.to || (0, toNumber_1.default)(otherTier.to) <= (0, toNumber_1.default)(aTier.to));
1941
+ })
1942
+ ? (i.tier_pricing.find(function (otherTier) {
1943
+ return (0, toNumber_1.default)(otherTier.from) >= (0, toNumber_1.default)(aTier.from) &&
1944
+ (!!!otherTier.to || (0, toNumber_1.default)(otherTier.to) <= (0, toNumber_1.default)(aTier.to));
1945
+ }) || { price: undefined }).price
1946
+ : null, qte: anItem === item ? qte : anItem.qte });
1947
+ }));
1948
+ };
1949
+ for (var _e = 0, allSameCategory_2 = allSameCategory; _e < allSameCategory_2.length; _e++) {
1950
+ var anItem = allSameCategory_2[_e];
1951
+ _loop_5(anItem);
1952
+ }
1953
+ }
1954
+ };
1955
+ for (var _b = 0, _c = item.tier_pricing; _b < _c.length; _b++) {
1956
+ var aTier = _c[_b];
1957
+ _loop_3(aTier);
1958
+ }
1959
+ }
1960
+ return _this._data.items;
1961
+ };
1962
+ _this._updateQuantity = function (item, qte) {
1963
+ _this._updateItems(_this._data.items.map(function (i) {
1964
+ if (i.sku !== item.sku)
1965
+ return i;
1966
+ return __assign(__assign({}, i), { qte: qte });
1967
+ }));
1968
+ };
1969
+ _this._getDefaultTaxesForCart = function (space, allTaxes) {
1970
+ var shippingAddress = _this.data().shipping_address;
1971
+ var currentTaxes = _this.data().taxes;
1972
+ var isInCanada = !!shippingAddress && !!shippingAddress.address
1973
+ ? ['ca', 'canada'].includes(shippingAddress.address.country.toLowerCase())
1974
+ : false;
1975
+ var defaultCartTaxes = currentTaxes;
1976
+ if (!!isInCanada) {
1977
+ var defaultSpaceTaxID_1 = space.getDefaultTax();
1978
+ if (!!defaultSpaceTaxID_1) {
1979
+ var defaultTax = allTaxes.find(function (t) { return t.id.toLowerCase() == defaultSpaceTaxID_1.toLowerCase(); });
1980
+ if (!!defaultTax) {
1981
+ defaultCartTaxes = [defaultTax];
1982
+ }
1983
+ }
1984
+ }
1985
+ else if (!!currentTaxes.length) {
1986
+ defaultCartTaxes = [];
1987
+ }
1988
+ return defaultCartTaxes;
1989
+ };
1990
+ _this.calculateTotals = function (currency, forcedPromos) { return __awaiter(_this, void 0, void 0, function () {
1991
+ var space, allTaxes, e_10, shippingAddress, currentTaxes, currentShippingProvince_1, newCartTaxes, newTaxes, err_5;
1992
+ return __generator(this, function (_b) {
1993
+ switch (_b.label) {
1994
+ case 0: return [4, Space_1.default.getCurrentSpaceWithRef(this._collection.path, this._user)];
1995
+ case 1:
1996
+ space = _b.sent();
1997
+ if (!!!space)
1998
+ return [2, new Error("Can't find space")];
1999
+ allTaxes = this._allTaxes;
2000
+ if (!(!!!allTaxes || !!!allTaxes.length)) return [3, 5];
2001
+ _b.label = 2;
2002
+ case 2:
2003
+ _b.trys.push([2, 4, , 5]);
2004
+ return [4, this.setAllTaxes()];
2005
+ case 3:
2006
+ allTaxes = _b.sent();
2007
+ if (!!!allTaxes.length) {
2008
+ console.log('** TAXES COULD NOT BE FETCHED **');
2009
+ }
2010
+ return [3, 5];
2011
+ case 4:
2012
+ e_10 = _b.sent();
2013
+ console.log('error on fetching taxe rates from space: ', e_10.toString());
2014
+ return [3, 5];
2015
+ case 5:
2016
+ this.calculateSubtotal(space, forcedPromos);
2017
+ shippingAddress = this.data().shipping_address;
2018
+ currentTaxes = this.data().taxes;
2019
+ if (!!shippingAddress && !!Object.entries(shippingAddress).length && shippingAddress.address) {
2020
+ currentShippingProvince_1 = (0, cart_1.getCurrentProvince)(shippingAddress.address.state);
2021
+ newCartTaxes = currentTaxes;
2022
+ if (!!currentShippingProvince_1) {
2023
+ if (!!!currentTaxes.length ||
2024
+ !!!currentTaxes.some(function (tax) { return tax.id.includes(currentShippingProvince_1.value); })) {
2025
+ newTaxes = allTaxes.find(function (tax) {
2026
+ return tax.id.toLowerCase() == currentShippingProvince_1.value.toLowerCase() ||
2027
+ (0, string_1.stripAccents)(tax.label_fr.toLowerCase()) === (0, string_1.stripAccents)(currentShippingProvince_1.label.toLowerCase()) ||
2028
+ (0, string_1.stripAccents)(tax.label_en.toLowerCase()) === (0, string_1.stripAccents)(currentShippingProvince_1.label_en.toLowerCase());
2029
+ });
2030
+ if (!!newTaxes) {
2031
+ newCartTaxes = [newTaxes];
2032
+ }
2033
+ else {
2034
+ newCartTaxes = this._getDefaultTaxesForCart(space, allTaxes);
2035
+ }
2036
+ }
2037
+ }
2038
+ else {
2039
+ newCartTaxes = this._getDefaultTaxesForCart(space, allTaxes);
2040
+ }
2041
+ this._data = __assign(__assign({}, this._data), { taxes: newCartTaxes });
2042
+ }
2043
+ _b.label = 6;
2044
+ case 6:
2045
+ _b.trys.push([6, 8, , 9]);
2046
+ this.calculateTotal(true, !!currency ? currency : space.preferences.default.currency());
2047
+ return [4, this.save(undefined, undefined, false)];
2048
+ case 7:
2049
+ _b.sent();
2050
+ return [3, 9];
2051
+ case 8:
2052
+ err_5 = _b.sent();
2053
+ (0, console_1.errorMessage)(JSON.stringify({ here: { err: err_5 } }));
2054
+ return [3, 9];
2055
+ case 9: return [2];
2056
+ }
2057
+ });
2058
+ }); };
2059
+ _this._getSubtotal = function (space, removeServiceFees) {
2060
+ return (0, sumBy_1.default)(_this.data().items, function (item) {
2061
+ if (!!item.is_service && !!removeServiceFees)
2062
+ return 0;
2063
+ var itemPrice = space.cartItem.getAppliedPrice(item).amount;
2064
+ return (0, round_1.default)(((0, isNumber_1.default)(itemPrice) ? Number(itemPrice) : 0) * item.qte, space.data().product_preferences.decimals || 2);
2065
+ });
2066
+ };
2067
+ _this._getSubtotalToCheck = function (space, feePromosTotalRemoved, removeServiceFees) {
2068
+ var serviceFeeProducts = !!!removeServiceFees ? [] : _this.data().items.filter(function (i) { return !!i.is_service; });
2069
+ var serviceFeeSubtotal = !!!serviceFeeProducts.length
2070
+ ? 0
2071
+ : (0, sumBy_1.default)(serviceFeeProducts, function (i) {
2072
+ var itemPrice = _this.getLowestPrice(i);
2073
+ return (0, round_1.default)(((0, isNumber_1.default)(itemPrice) ? Number(itemPrice) : 0) * i.qte, space.data().product_preferences.decimals || 2);
2074
+ });
2075
+ var totalRemoved = serviceFeeSubtotal;
2076
+ if (!!totalRemoved) {
2077
+ totalRemoved -= feePromosTotalRemoved;
2078
+ }
2079
+ return _this._data.subtotal - totalRemoved;
2080
+ };
2081
+ _this.calculateSubtotal = function (space, forcedPromos) {
2082
+ var _b;
2083
+ var newSubtotal = _this._getSubtotal(space);
2084
+ _this._data = __assign(__assign({}, _this._data), { subtotal: newSubtotal });
2085
+ if (newSubtotal === 0) {
2086
+ _this._data = __assign(__assign(__assign(__assign({}, _this._data), { subtotalWithoutPromotions: null }), (!!_this._data.cart_promo_applied ? { cart_promo_applied: null } : {})), (!!_this._data.cart_promos_applied ? { cart_promos_applied: null } : {}));
2087
+ }
2088
+ else {
2089
+ _this._data = (0, discount_1.applyDiscountToCart)(_this.data(), space.isMultiPromo(), false, forcedPromos);
2090
+ var currentCartPromos = _this.getCartPromo();
2091
+ if (!!currentCartPromos && !!currentCartPromos.length) {
2092
+ var oldSubtotal = _this._data.subtotal;
2093
+ var cartPromos = currentCartPromos.filter(function (c) { return c.applies_to != Cart_1.CartPromoAppliesToEnum.TOTAL_AFTER_TAXES; });
2094
+ cartPromos = (0, orderBy_1.default)(cartPromos, function (p) {
2095
+ if (p.applies_to === Cart_1.CartPromoAppliesToEnum.PRODUCT)
2096
+ return 1;
2097
+ if (p.promo_code && p.applies_to === Cart_1.CartPromoAppliesToEnum.SUBTOTAL) {
2098
+ return 3;
2099
+ }
2100
+ return 2;
2101
+ });
2102
+ var feePromosTotal = 0;
2103
+ var _loop_6 = function (aPromo) {
2104
+ if (_this._data.subtotal > 0 &&
2105
+ !!aPromo &&
2106
+ (aPromo.applies_to === Cart_1.CartPromoAppliesToEnum.SUBTOTAL ||
2107
+ aPromo.applies_to === Cart_1.CartPromoAppliesToEnum.PRODUCT)) {
2108
+ var amountToRemove = 0;
2109
+ var amountUnit = aPromo.amount_unit || IDiscountRule_1.ResultActionEnum.PERCENT;
2110
+ var appliesToProduct = aPromo.applies_to === Cart_1.CartPromoAppliesToEnum.PRODUCT;
2111
+ var subtotalToCheck = !!aPromo.exclude_services_and_fees &&
2112
+ !![IDiscountRule_1.ResultActionEnum.PERCENT, IDiscountRule_1.ResultActionEnum.PERCENT_SKU, IDiscountRule_1.ResultActionEnum.PERCENT_CATEGORY].includes(amountUnit) &&
2113
+ !!!appliesToProduct
2114
+ ? _this._getSubtotalToCheck(space, feePromosTotal, true)
2115
+ : _this._data.subtotal;
2116
+ if (aPromo.applies_to === Cart_1.CartPromoAppliesToEnum.PRODUCT) {
2117
+ var skuArray_1 = [];
2118
+ if (!!aPromo.item_given) {
2119
+ skuArray_1 = (0, discount_1.getSkuArrayForPromo)(aPromo.item_given);
2120
+ }
2121
+ var itemToCheck = _this._data.items.filter(function (item) { return !!aPromo && !!skuArray_1.includes(item.sku); });
2122
+ for (var _d = 0, itemToCheck_1 = itemToCheck; _d < itemToCheck_1.length; _d++) {
2123
+ var anItem = itemToCheck_1[_d];
2124
+ var newAmountToRemove = (0, data_1.getPromoTotalAmount)(_this._data, aPromo, 'number', anItem.sku);
2125
+ if (typeof newAmountToRemove !== 'number')
2126
+ continue;
2127
+ if (!!anItem && !!anItem.is_service)
2128
+ feePromosTotal += newAmountToRemove;
2129
+ amountToRemove += newAmountToRemove;
2130
+ }
2131
+ }
2132
+ else {
2133
+ amountToRemove = (_b = aPromo.amount_removed) !== null && _b !== void 0 ? _b : 0;
2134
+ }
2135
+ amountToRemove = (0, round_1.default)(amountToRemove, 2);
2136
+ var newSubtotal_1 = amountUnit === IDiscountRule_1.ResultActionEnum.AMOUNT || aPromo.applies_to === Cart_1.CartPromoAppliesToEnum.PRODUCT
2137
+ ? _this._data.subtotal - amountToRemove
2138
+ : _this._data.subtotal - subtotalToCheck * (amountToRemove / 100);
2139
+ _this._data = __assign(__assign({}, _this._data), { subtotalWithoutPromotions: oldSubtotal, subtotal: (0, round_1.default)(newSubtotal_1, 2) });
2140
+ }
2141
+ else if (!!aPromo && !!aPromo.free_shipping) {
2142
+ if (!!_this._data.items.some(function (item) { return !!item.exclude_from_free_shipping; })) {
2143
+ _this.addError(Cart_1.CartErrorEnum.FREE_SHIPPING_NOT_ELIGIBLE_BECAUSE_OF_ITEM);
2144
+ _this._data = __assign(__assign(__assign(__assign({}, _this._data), (!!_this._data.cart_promo_applied ? { cart_promo_applied: null } : {})), (!!_this._data.cart_promos_applied && !!aPromo.discount_id
2145
+ ? {
2146
+ cart_promos_applied: _this._data.cart_promos_applied.filter(function (p) { return p.discount_id !== aPromo.discount_id; })
2147
+ }
2148
+ : {})), { subtotalWithoutPromotions: null, free_shipping: false });
2149
+ }
2150
+ else {
2151
+ if (!!!_this._data.shipping_address) {
2152
+ _this._data = __assign(__assign(__assign(__assign({}, _this._data), (!!_this._data.cart_promo_applied ? { cart_promo_applied: null } : {})), (!!_this._data.cart_promos_applied && !!aPromo.discount_id
2153
+ ? {
2154
+ cart_promos_applied: _this._data.cart_promos_applied.filter(function (p) { return p.discount_id !== aPromo.discount_id; })
2155
+ }
2156
+ : {})), { subtotalWithoutPromotions: null });
2157
+ }
2158
+ else {
2159
+ var shippingState_2 = !!_this._data.shipping_address && _this._data.shipping_address.address.state;
2160
+ if (!!shippingState_2) {
2161
+ var shippingStateValue = data_1.provinces.find(function (province) { return province.label === shippingState_2 || province.label_en === shippingState_2; });
2162
+ if (!!shippingStateValue) {
2163
+ var freeShippingRestrictions = space.preferences.shipping.restrict.getFree();
2164
+ if (!!freeShippingRestrictions &&
2165
+ !!freeShippingRestrictions.limit_states &&
2166
+ !freeShippingRestrictions.limit_states.includes(shippingStateValue.value)) {
2167
+ _this.addError(Cart_1.CartErrorEnum.FREE_SHIPPING_NOT_ELIGIBLE_BECAUSE_OF_SHIPPING_ADDRESS);
2168
+ _this._data = __assign(__assign(__assign(__assign({}, _this._data), { cart_promo_applied: null }), (!!_this._data.cart_promos_applied && !!aPromo.discount_id
2169
+ ? {
2170
+ cart_promos_applied: _this._data.cart_promos_applied.filter(function (p) { return p.discount_id !== aPromo.discount_id; })
2171
+ }
2172
+ : {})), { subtotalWithoutPromotions: null });
2173
+ }
2174
+ }
2175
+ }
2176
+ }
2177
+ }
2178
+ }
2179
+ else {
2180
+ _this._data = __assign(__assign({}, _this._data), { subtotalWithoutPromotions: null });
2181
+ }
2182
+ };
2183
+ for (var _c = 0, cartPromos_1 = cartPromos; _c < cartPromos_1.length; _c++) {
2184
+ var aPromo = cartPromos_1[_c];
2185
+ _loop_6(aPromo);
2186
+ }
2187
+ }
2188
+ else {
2189
+ _this._data = __assign(__assign({}, _this._data), { subtotalWithoutPromotions: null });
2190
+ }
2191
+ }
2192
+ return _this._data.subtotal;
2193
+ };
2194
+ _this.calculateTotal = function (canCartBeEmpty, currency) {
2195
+ if (currency === void 0) { currency = 'CAD'; }
2196
+ var subtotal = (0, round_1.default)(_this.data().subtotal, 2);
2197
+ var total = subtotal;
2198
+ var shouldCalculate = !!canCartBeEmpty ? _this._data.items.length >= 0 : _this._data.items.length >= 1;
2199
+ if (!!shouldCalculate) {
2200
+ var shipping = _this._checkShippingAmount();
2201
+ var taxesAmount = (0, round_1.default)((0, sumBy_1.default)(_this.data().taxes, function (tax) { return (0, sumBy_1.default)(tax.taxes, function (t) { return _this.getATax(t.label_fr, t.value, currency); }); }), 2);
2202
+ total += shipping + taxesAmount;
2203
+ }
2204
+ var promoAfterTaxesAmount = (0, round_1.default)((0, discount_1.getAfterTaxesPromosTotalAmount)(_this._data), 2);
2205
+ total -= promoAfterTaxesAmount;
2206
+ total = (0, round_1.default)(total, 2);
2207
+ _this._data = __assign(__assign({}, _this._data), { promo_after_taxes_amount: promoAfterTaxesAmount || null, total: total });
2208
+ return total;
2209
+ };
2210
+ _this.getAssociatedTransferRequests = function () { return __awaiter(_this, void 0, void 0, function () {
2211
+ var space, cartTransferRequestQuery, e_11;
2212
+ return __generator(this, function (_b) {
2213
+ switch (_b.label) {
2214
+ case 0:
2215
+ _b.trys.push([0, 3, , 4]);
2216
+ return [4, Space_1.default.getCurrentSpaceWithRef(this._collection.path, this._user)];
2217
+ case 1:
2218
+ space = _b.sent();
2219
+ return [4, DatabaseService_1.default.getDocuments(DatabaseService_1.default.addToPath(space.getRef().path, space.getRef().id + '/transfer_requests'), { query: [{ field: 'associated_order', operator: '==', value: this._data.ref }] })];
2220
+ case 2:
2221
+ cartTransferRequestQuery = _b.sent();
2222
+ return [2, cartTransferRequestQuery];
2223
+ case 3:
2224
+ e_11 = _b.sent();
2225
+ console.error(e_11);
2226
+ return [2, []];
2227
+ case 4: return [2];
2228
+ }
2229
+ });
2230
+ }); };
2231
+ _this._checkShippingAmount = function () {
2232
+ var cartPromo = _this.getCartPromo();
2233
+ var cartHasFreeShipping = !!_this._data.free_shipping || (!!cartPromo && !!cartPromo.find(function (p) { return !!p.free_shipping; }));
2234
+ if (cartHasFreeShipping) {
2235
+ return 0;
2236
+ }
2237
+ var promoWithFlatrate = !!cartPromo && !!cartPromo.length && cartPromo.find(function (p) { return !!p.flatrate_shipping; });
2238
+ if (promoWithFlatrate) {
2239
+ return promoWithFlatrate.flatrate_shipping || 0;
2240
+ }
2241
+ return (0, round_1.default)(_this.data().shipping, 2);
2242
+ };
2243
+ _this.getShipping = function () {
2244
+ if (!!!_this._data.shipping)
2245
+ return 0;
2246
+ return _this._checkShippingAmount();
2247
+ };
2248
+ _this.setFreeShipping = function (aValue) {
2249
+ _this._data = __assign(__assign({}, _this._data), { free_shipping: aValue });
2250
+ };
2251
+ _this.excludeFreeShipping = function () {
2252
+ if (!!!_this._data.cart_promo_applied && !!!_this._data.cart_promos_applied)
2253
+ return;
2254
+ _this._data = __assign(__assign(__assign(__assign({}, _this._data), (!!_this._data.cart_promo_applied
2255
+ ? {
2256
+ cart_promo_applied: __assign(__assign({}, _this._data.cart_promo_applied), { free_shipping: false, flatrate_shipping: undefined })
2257
+ }
2258
+ : {})), (!!_this._data.cart_promos_applied
2259
+ ? {
2260
+ cart_promos_applied: _this._data.cart_promos_applied.map(function (p) {
2261
+ if (!!!p.free_shipping && !!!p.flatrate_shipping)
2262
+ return p;
2263
+ return __assign(__assign({}, p), { free_shipping: false, flatrate_shipping: undefined });
2264
+ })
2265
+ }
2266
+ : {})), { free_shipping: false });
2267
+ };
2268
+ _this._getCredz = function () { return __awaiter(_this, void 0, void 0, function () {
2269
+ var space, shippingServiceCredz, baseShippingCostDeterminedByTheOwner;
2270
+ return __generator(this, function (_b) {
2271
+ switch (_b.label) {
2272
+ case 0: return [4, Space_1.default.getCurrentSpaceWithRef(this._collection.path, this._user)];
2273
+ case 1:
2274
+ space = _b.sent();
2275
+ shippingServiceCredz = space.data().external_services.filter(function (es) { return !!es.is_active && es.type === 'shipping'; });
2276
+ if (!!!shippingServiceCredz) {
2277
+ baseShippingCostDeterminedByTheOwner = space.data().transport_preferences.override_shipping_with_cost;
2278
+ if (baseShippingCostDeterminedByTheOwner === undefined)
2279
+ throw new Error("Can't use shipping, pickup only. Admin must provide base shipping cost or set external services credentials like Shipstation.");
2280
+ return [2, baseShippingCostDeterminedByTheOwner];
2281
+ }
2282
+ return [2, { shippingServiceCredz: shippingServiceCredz, space: space }];
2283
+ }
2284
+ });
2285
+ }); };
2286
+ _this.calculateCartShippingPrice = function (fromServer, doNotPackage) {
2287
+ if (fromServer === void 0) { fromServer = false; }
2288
+ return __awaiter(_this, void 0, void 0, function () {
2289
+ var resCredz, shippingServiceCredz, space, shipment, departureAddress, selectedStore, quote, error_11;
2290
+ var _this = this;
2291
+ return __generator(this, function (_b) {
2292
+ switch (_b.label) {
2293
+ case 0: return [4, this._getCredz()];
2294
+ case 1:
2295
+ resCredz = _b.sent();
2296
+ if (typeof resCredz === 'number' || Array.isArray(resCredz))
2297
+ return [2, resCredz];
2298
+ shippingServiceCredz = resCredz.shippingServiceCredz, space = resCredz.space;
2299
+ (0, console_1.workingMessage)("Calling ".concat(shippingServiceCredz.map(function (e) { return e.external_service_name; }).join(', '), " for a quote.."));
2300
+ shipment = new Shipment_1.default(this, shippingServiceCredz);
2301
+ _b.label = 2;
2302
+ case 2:
2303
+ _b.trys.push([2, 4, , 5]);
2304
+ departureAddress = space.data().transport_preferences.default_departure_address;
2305
+ if (!!!departureAddress || (!!departureAddress && !!!departureAddress.line1)) {
2306
+ selectedStore = space.data().stores_warehouses.find(function (store) { return store.id === _this.data().current_store_id; });
2307
+ if (!!!selectedStore)
2308
+ throw new Error('Aucune adresse de départ, veuillez régler un magasin pour cette commande.');
2309
+ departureAddress = {
2310
+ line1: selectedStore.address.line1,
2311
+ app: selectedStore.address.app,
2312
+ line2: selectedStore.address.line2,
2313
+ city: selectedStore.address.city,
2314
+ state: selectedStore.address.state,
2315
+ postal_code: selectedStore.address.postal_code,
2316
+ country: 'CA',
2317
+ companyName: space.data().name,
2318
+ email: this._user,
2319
+ notify: true,
2320
+ residential: false,
2321
+ phone: departureAddress ? departureAddress.phone : ''
2322
+ };
2323
+ }
2324
+ return [4, shipment.getShippingQuotes(space, departureAddress, fromServer, doNotPackage)];
2325
+ case 3:
2326
+ quote = _b.sent();
2327
+ return [2, quote];
2328
+ case 4:
2329
+ error_11 = _b.sent();
2330
+ throw error_11;
2331
+ case 5: return [2];
2332
+ }
2333
+ });
2334
+ });
2335
+ };
2336
+ _this.getBoxOccupationByIndex = function (bIndex) {
2337
+ var box = _this.data().boxes[bIndex];
2338
+ if (!!!box)
2339
+ return 0;
2340
+ return ((0, sumBy_1.default)(box.item_ids.map(function (id) {
2341
+ return !!_this.data().items.find(function (i) { return i.sku === id; })
2342
+ ? _this._calculateItemVolume(_this.data().items.find(function (i) { return i.sku; }))
2343
+ : 0;
2344
+ })) / _this._calculateBoxItemVolume(box));
2345
+ };
2346
+ _this.selectShippingService = function (shipmentInfo) { return __awaiter(_this, void 0, void 0, function () {
2347
+ var space, cartPromo;
2348
+ return __generator(this, function (_b) {
2349
+ switch (_b.label) {
2350
+ case 0:
2351
+ if (!(typeof shipmentInfo === 'number')) return [3, 2];
2352
+ return [4, this.save({
2353
+ shipping: shipmentInfo || 0
2354
+ }, undefined)];
2355
+ case 1:
2356
+ _b.sent();
2357
+ return [2, shipmentInfo];
2358
+ case 2: return [4, Space_1.default.getCurrentSpaceWithRef(this._collection.path, this._user)];
2359
+ case 3:
2360
+ space = _b.sent();
2361
+ if (!!!space)
2362
+ return [2, new Error("Can't find space")];
2363
+ this.calculateSubtotal(space);
2364
+ cartPromo = this.getCartPromo();
2365
+ return [4, this.save({
2366
+ is_pickup: shipmentInfo.method === 'pickup',
2367
+ shipping: shipmentInfo.base_fee || 0,
2368
+ shipping_selected: shipmentInfo,
2369
+ free_shipping: !!cartPromo &&
2370
+ !!cartPromo.length &&
2371
+ !!cartPromo.find(function (p) { return p.free_shipping; }) &&
2372
+ typeof shipmentInfo !== 'number' &&
2373
+ !!shipmentInfo.is_lowest
2374
+ })];
2375
+ case 4:
2376
+ _b.sent();
2377
+ return [2, shipmentInfo.base_fee || 0];
2378
+ }
2379
+ });
2380
+ }); };
2381
+ _this.packageCartInOneBox = function (dontSaveToCart) {
2382
+ if (dontSaveToCart === void 0) { dontSaveToCart = false; }
2383
+ return __awaiter(_this, void 0, void 0, function () {
2384
+ var space, spaceData, boxes, boxTemplates, allItemsSplitted, _b, _c, item, i, itemsToBox, totalVolume, allItemsGoIn, _d, boxTemplates_1, box;
2385
+ var _this = this;
2386
+ return __generator(this, function (_e) {
2387
+ switch (_e.label) {
2388
+ case 0: return [4, Space_1.default.getCurrentSpaceWithRef(this._collection.path, this._user)];
2389
+ case 1:
2390
+ space = _e.sent();
2391
+ spaceData = space.data();
2392
+ boxes = [];
2393
+ if (!!!spaceData.transport_preferences.predefined_boxes ||
2394
+ !!!spaceData.transport_preferences.predefined_boxes.length) {
2395
+ return [2, [
2396
+ {
2397
+ height: this.getTotalHeight(),
2398
+ width: this.getTotalWidth(),
2399
+ length: this.getTotalLength(),
2400
+ weight: this.getTotalWeight(),
2401
+ item_ids: this.items.get().map(function (i) { return i.sku; }),
2402
+ name: 'Big custom box',
2403
+ occupied_volume: 100,
2404
+ slug: 'Big custom box'
2405
+ }
2406
+ ]];
2407
+ }
2408
+ boxTemplates = (0, orderBy_1.default)(spaceData.transport_preferences.predefined_boxes || [], function (b) { return _this._calculateBoxVolume(b); }, 'asc');
2409
+ allItemsSplitted = [];
2410
+ for (_b = 0, _c = this.items.get(); _b < _c.length; _b++) {
2411
+ item = _c[_b];
2412
+ if (item.qte === 0)
2413
+ continue;
2414
+ if (item.qte === 1) {
2415
+ allItemsSplitted.push(item);
2416
+ continue;
2417
+ }
2418
+ for (i = 0; i < item.qte; i++) {
2419
+ allItemsSplitted.push(item);
2420
+ }
2421
+ }
2422
+ allItemsSplitted = (0, orderBy_1.default)(allItemsSplitted, function (i) { return i.shipping_info.weight; }, 'desc');
2423
+ itemsToBox = allItemsSplitted;
2424
+ totalVolume = (0, sumBy_1.default)(itemsToBox, function (_item) { return _this._calculateItemVolume(_item); });
2425
+ allItemsGoIn = false;
2426
+ for (_d = 0, boxTemplates_1 = boxTemplates; _d < boxTemplates_1.length; _d++) {
2427
+ box = boxTemplates_1[_d];
2428
+ if (totalVolume < this._calculateBoxVolume(box) * 0.9) {
2429
+ boxes = __spreadArray(__spreadArray([], boxes, true), [
2430
+ __assign(__assign({}, box), { item_ids: itemsToBox.map(function (_item) { return _item.sku; }), occupied_volume: totalVolume / this._calculateBoxVolume(box), weight: (0, sumBy_1.default)(itemsToBox, function (_item) {
2431
+ return (0, weight_1.convertWeight)(_item.shipping_info.weight || 0, _item.shipping_info.unit_weight);
2432
+ }) })
2433
+ ], false);
2434
+ allItemsGoIn = true;
2435
+ break;
2436
+ }
2437
+ }
2438
+ if (dontSaveToCart)
2439
+ return [2, boxes];
2440
+ return [4, this.save({ boxes: boxes }, undefined, false)];
2441
+ case 2:
2442
+ _e.sent();
2443
+ return [2, boxes];
2444
+ }
2445
+ });
2446
+ });
2447
+ };
2448
+ _this.packageCart = function (dontSaveToCart) {
2449
+ if (dontSaveToCart === void 0) { dontSaveToCart = false; }
2450
+ return __awaiter(_this, void 0, void 0, function () {
2451
+ var space, spaceData, boxes, boxTemplates, allItemsSplitted, _b, _c, item, i, _d, allItemsSplitted_1, item, itemBoxed, _e, _f, existingBox, allItemsGoIn, itemsToBox, totalVolume, _g, boxTemplates_2, box, _h, boxTemplates_3, box;
2452
+ var _this = this;
2453
+ return __generator(this, function (_j) {
2454
+ switch (_j.label) {
2455
+ case 0: return [4, Space_1.default.getCurrentSpaceWithRef(this._collection.path, this._user)];
2456
+ case 1:
2457
+ space = _j.sent();
2458
+ spaceData = space.data();
2459
+ boxes = [];
2460
+ if (!!!spaceData.transport_preferences.predefined_boxes ||
2461
+ !!!spaceData.transport_preferences.predefined_boxes.length) {
2462
+ return [2, [
2463
+ {
2464
+ height: this.getTotalHeight(),
2465
+ width: this.getTotalWidth(),
2466
+ length: this.getTotalLength(),
2467
+ weight: this.getTotalWeight(),
2468
+ item_ids: this.items.get().map(function (i) { return i.sku; }),
2469
+ name: 'Big custom box',
2470
+ occupied_volume: 100,
2471
+ slug: 'Big custom box'
2472
+ }
2473
+ ]];
2474
+ }
2475
+ boxTemplates = (0, orderBy_1.default)(spaceData.transport_preferences.predefined_boxes || [], function (b) { return _this._calculateBoxVolume(b); }, 'asc');
2476
+ allItemsSplitted = [];
2477
+ for (_b = 0, _c = this.items.get(); _b < _c.length; _b++) {
2478
+ item = _c[_b];
2479
+ if (item.qte === 0)
2480
+ continue;
2481
+ if (item.qte === 1) {
2482
+ allItemsSplitted.push(item);
2483
+ continue;
2484
+ }
2485
+ for (i = 0; i < item.qte; i++) {
2486
+ allItemsSplitted.push(item);
2487
+ }
2488
+ }
2489
+ allItemsSplitted = (0, orderBy_1.default)(allItemsSplitted, function (i) { return i.shipping_info.weight; }, 'desc');
2490
+ for (_d = 0, allItemsSplitted_1 = allItemsSplitted; _d < allItemsSplitted_1.length; _d++) {
2491
+ item = allItemsSplitted_1[_d];
2492
+ itemBoxed = false;
2493
+ if (!!boxes.length) {
2494
+ for (_e = 0, _f = (0, orderBy_1.default)(boxes, function (b) { return b.occupied_volume || 0; }, 'asc'); _e < _f.length; _e++) {
2495
+ existingBox = _f[_e];
2496
+ if (this._doesGoIn(item, existingBox)) {
2497
+ boxes = __spreadArray(__spreadArray(__spreadArray([], boxes.slice(0, (0, indexOf_1.default)(boxes, existingBox)), true), [
2498
+ __assign(__assign({}, existingBox), { item_ids: __spreadArray(__spreadArray([], existingBox.item_ids, true), [item.sku], false), occupied_volume: existingBox.occupied_volume +
2499
+ this._calculateItemVolume(item) / this._calculateBoxItemVolume(existingBox), weight: existingBox.weight + (0, weight_1.convertWeight)(item.shipping_info.weight || 0, item.shipping_info.unit_weight) })
2500
+ ], false), boxes.slice((0, indexOf_1.default)(boxes, existingBox) + 1), true);
2501
+ itemBoxed = true;
2502
+ break;
2503
+ }
2504
+ }
2505
+ }
2506
+ if (itemBoxed)
2507
+ continue;
2508
+ allItemsGoIn = false;
2509
+ itemsToBox = allItemsSplitted.slice((0, indexOf_1.default)(allItemsSplitted, item));
2510
+ totalVolume = (0, sumBy_1.default)(itemsToBox, function (_item) { return _this._calculateItemVolume(_item); });
2511
+ for (_g = 0, boxTemplates_2 = boxTemplates; _g < boxTemplates_2.length; _g++) {
2512
+ box = boxTemplates_2[_g];
2513
+ if (totalVolume < this._calculateBoxVolume(box) * 0.9) {
2514
+ boxes = __spreadArray(__spreadArray([], boxes, true), [
2515
+ __assign(__assign({}, box), { item_ids: itemsToBox.map(function (_item) { return _item.sku; }), occupied_volume: totalVolume / this._calculateBoxVolume(box), weight: (0, sumBy_1.default)(itemsToBox, function (_item) {
2516
+ return (0, weight_1.convertWeight)(_item.shipping_info.weight || 0, _item.shipping_info.unit_weight);
2517
+ }) })
2518
+ ], false);
2519
+ allItemsGoIn = true;
2520
+ break;
2521
+ }
2522
+ }
2523
+ if (allItemsGoIn)
2524
+ break;
2525
+ for (_h = 0, boxTemplates_3 = boxTemplates; _h < boxTemplates_3.length; _h++) {
2526
+ box = boxTemplates_3[_h];
2527
+ if (this._doesGoIn(item, __assign(__assign({}, box), { item_ids: [], occupied_volume: 0, weight: 0 }))) {
2528
+ boxes = __spreadArray(__spreadArray([], boxes, true), [
2529
+ __assign(__assign({}, box), { item_ids: [item.sku], occupied_volume: this._calculateItemVolume(item) / this._calculateBoxVolume(box), weight: (0, weight_1.convertWeight)(item.shipping_info.weight || 0, item.shipping_info.unit_weight) })
2530
+ ], false);
2531
+ break;
2532
+ }
2533
+ boxes = __spreadArray(__spreadArray([], boxes, true), [
2534
+ {
2535
+ item_ids: [item.sku],
2536
+ height: (0, dimensions_1.convertDimension)(item.shipping_info.height || 0, item.shipping_info.unit_measurments),
2537
+ width: (0, dimensions_1.convertDimension)(item.shipping_info.width || 0, item.shipping_info.unit_measurments),
2538
+ length: (0, dimensions_1.convertDimension)(item.shipping_info.length || 0, item.shipping_info.unit_measurments),
2539
+ weight: (0, weight_1.convertWeight)(item.shipping_info.width || 0, item.shipping_info.unit_weight),
2540
+ occupied_volume: 1,
2541
+ name: "Custom box for item ".concat(item.sku),
2542
+ slug: "Custom box for item ".concat(item.sku)
2543
+ }
2544
+ ], false);
2545
+ }
2546
+ }
2547
+ if (dontSaveToCart)
2548
+ return [2, boxes];
2549
+ return [4, this.save({ boxes: boxes }, undefined, true)];
2550
+ case 2:
2551
+ _j.sent();
2552
+ return [2, boxes];
2553
+ }
2554
+ });
2555
+ });
2556
+ };
2557
+ _this.removeBoxAtIndex = function (boxIndex) { return __awaiter(_this, void 0, void 0, function () {
2558
+ return __generator(this, function (_b) {
2559
+ switch (_b.label) {
2560
+ case 0: return [4, this.save({
2561
+ boxes: __spreadArray(__spreadArray([], this._data.boxes.slice(0, boxIndex), true), this._data.boxes.slice(boxIndex + 1), true)
2562
+ })];
2563
+ case 1:
2564
+ _b.sent();
2565
+ return [2];
2566
+ }
2567
+ });
2568
+ }); };
2569
+ _this.addEmptyBox = function () { return __awaiter(_this, void 0, void 0, function () {
2570
+ var e_12;
2571
+ return __generator(this, function (_b) {
2572
+ switch (_b.label) {
2573
+ case 0:
2574
+ _b.trys.push([0, 2, , 3]);
2575
+ return [4, this.save({
2576
+ boxes: __spreadArray(__spreadArray([], this._data.boxes, true), [
2577
+ {
2578
+ height: 1,
2579
+ width: 1,
2580
+ length: 1,
2581
+ item_ids: [],
2582
+ weight: 0,
2583
+ name: 'Nouvelle boîte',
2584
+ occupied_volume: 0,
2585
+ slug: 'nouvelle-boîte'
2586
+ }
2587
+ ], false)
2588
+ })];
2589
+ case 1:
2590
+ _b.sent();
2591
+ return [3, 3];
2592
+ case 2:
2593
+ e_12 = _b.sent();
2594
+ throw new Error(e_12);
2595
+ case 3: return [2];
2596
+ }
2597
+ });
2598
+ }); };
2599
+ _this.removeItemFromBox = function (itemIndex, boxIndex) { return __awaiter(_this, void 0, void 0, function () {
2600
+ var _this = this;
2601
+ return __generator(this, function (_b) {
2602
+ switch (_b.label) {
2603
+ case 0:
2604
+ (0, console_1.workingMessage)("Updating box at index ".concat(boxIndex, " removing item ").concat(itemIndex));
2605
+ return [4, this.save({
2606
+ boxes: this._data.boxes
2607
+ .map(function (b, i) {
2608
+ if (i !== boxIndex)
2609
+ return b;
2610
+ var boxItemSKu = b.item_ids[itemIndex];
2611
+ if (!!!boxItemSKu)
2612
+ return b;
2613
+ var item = _this._data.items.find(function (i) { return i.sku === boxItemSKu; });
2614
+ if (!!!item)
2615
+ return b;
2616
+ var existing = __assign(__assign({}, b), { item_ids: b.item_ids.filter(function (_, _i) { return _i !== itemIndex; }), weight: (b.weight || 0) -
2617
+ (!!item.shipping_info.weight
2618
+ ? (0, weight_1.convertWeight)(item.shipping_info.weight, item.shipping_info.unit_weight, 'kilograms')
2619
+ : 0) });
2620
+ return __assign({}, existing);
2621
+ })
2622
+ .map(function (b) { return (__assign(__assign({}, b), { occupied_volume: (0, sumBy_1.default)(_this._data.items, function (item) {
2623
+ return !b.item_ids.includes(item.sku)
2624
+ ? 0
2625
+ : _this._calculateItemVolume(item) * (0, sumBy_1.default)(b.item_ids, function (id) { return (id === item.sku ? 1 : 0); });
2626
+ }) / _this._calculateBoxVolume(b) })); })
2627
+ }, undefined, true)];
2628
+ case 1:
2629
+ _b.sent();
2630
+ return [2];
2631
+ }
2632
+ });
2633
+ }); };
2634
+ _this.addItemToBox = function (itemId, boxIndex) { return __awaiter(_this, void 0, void 0, function () {
2635
+ var _this = this;
2636
+ return __generator(this, function (_b) {
2637
+ switch (_b.label) {
2638
+ case 0: return [4, this.save({
2639
+ boxes: this._data.boxes.map(function (b, i) {
2640
+ if (i !== boxIndex)
2641
+ return b;
2642
+ var item = _this.data().items.find(function (i) { return i.sku === itemId; });
2643
+ if (!!!item)
2644
+ return b;
2645
+ return __assign(__assign({}, b), { item_ids: __spreadArray(__spreadArray([], b.item_ids, true), [itemId], false), weight: (b.weight || 0) + (!!item.shipping_info.weight ? item.shipping_info.weight : 0) });
2646
+ })
2647
+ }, undefined, true)];
2648
+ case 1:
2649
+ _b.sent();
2650
+ return [2];
2651
+ }
2652
+ });
2653
+ }); };
2654
+ _this._calculateItemVolume = function (item) {
2655
+ return ((0, dimensions_1.convertDimension)(item.shipping_info.width || 0, item.shipping_info.unit_measurments) *
2656
+ (0, dimensions_1.convertDimension)(item.shipping_info.length || 0, item.shipping_info.unit_measurments) *
2657
+ (0, dimensions_1.convertDimension)(item.shipping_info.height || 0, item.shipping_info.unit_measurments));
2658
+ };
2659
+ _this._calculateBoxVolume = function (box) {
2660
+ return (box.width || 0) * (box.length || 0) * (box.height || 0);
2661
+ };
2662
+ _this._calculateBoxItemVolume = function (box, margin) {
2663
+ if (margin === void 0) { margin = 0.9; }
2664
+ return (box.width || 0) * (box.length || 0) * (box.height || 0) * margin;
2665
+ };
2666
+ _this._doesGoIn = function (item, box) {
2667
+ var itemVolume = _this._calculateItemVolume(item);
2668
+ var boxVolume = _this._calculateBoxItemVolume(box);
2669
+ return boxVolume - box.occupied_volume * boxVolume > itemVolume;
2670
+ };
2671
+ _this.addTrackingInfo = function (trackingInfo) {
2672
+ if (DatabaseService_1.default.getPathParent(_this._collection.path) == '/')
2673
+ throw new Error("Can't access invoices collection");
2674
+ _this.save({
2675
+ shipping_payload: trackingInfo
2676
+ });
2677
+ };
2678
+ _this._getItems = function () { return _this.data().items; };
2679
+ _this._getBoxes = function () { return _this.data().boxes; };
2680
+ _this._getFormatStringById = function (itemSku) {
2681
+ var item = _this.data().items.find(function (i) { return i.sku === itemSku; });
2682
+ if (!!!item)
2683
+ return '';
2684
+ return "".concat(item.shipping_info.height, " ").concat(item.shipping_info.unit_measurments, " (h) X ").concat(item.shipping_info.width, " ").concat(item.shipping_info.unit_measurments, " (w) X ").concat(item.shipping_info.length, " ").concat(item.shipping_info.unit_measurments, " (l) ").concat(item.shipping_info.weight, " ").concat(item.shipping_info.unit_weight);
2685
+ };
2686
+ _this._getWeight = function (index) {
2687
+ if (!!!_this.data().boxes[index])
2688
+ return 0;
2689
+ return _this.data().boxes[index].weight || 0;
2690
+ };
2691
+ _this._setWeight = function (index, weight) { return __awaiter(_this, void 0, void 0, function () {
2692
+ return __generator(this, function (_b) {
2693
+ if (!!!this.data().boxes[index])
2694
+ return [2, 0];
2695
+ return [2, this.save({
2696
+ boxes: this.data().boxes.map(function (b, bIndex) {
2697
+ if (bIndex !== index)
2698
+ return b;
2699
+ return __assign(__assign({}, b), { weight: weight });
2700
+ })
2701
+ }, undefined, true)];
2702
+ });
2703
+ }); };
2704
+ _this._getIfVerifiedWeight = function (index) {
2705
+ if (!!!_this.data().boxes[index])
2706
+ return false;
2707
+ return _this.data().boxes[index].confirm_weight;
2708
+ };
2709
+ _this._setIfVerifiedWeight = function (index, verified) { return __awaiter(_this, void 0, void 0, function () {
2710
+ return __generator(this, function (_b) {
2711
+ switch (_b.label) {
2712
+ case 0:
2713
+ if (!!!this.data().boxes[index])
2714
+ return [2, 0];
2715
+ return [4, this.save({
2716
+ boxes: this.data().boxes.map(function (box, bIndex) {
2717
+ if (bIndex !== index)
2718
+ return box;
2719
+ return __assign(__assign({}, box), { confirm_weight: verified });
2720
+ })
2721
+ }, undefined, true)];
2722
+ case 1: return [2, _b.sent()];
2723
+ }
2724
+ });
2725
+ }); };
2726
+ _this._getBoxDimension = function (index, type) {
2727
+ if (!!!_this.data().boxes[index])
2728
+ return 0;
2729
+ var box = _this.data().boxes[index];
2730
+ if (type === 'height')
2731
+ return box.height;
2732
+ if (type === 'width')
2733
+ return box.width;
2734
+ if (type === 'length')
2735
+ return box.length;
2736
+ };
2737
+ _this._setBoxDimension = function (index, type, value) { return __awaiter(_this, void 0, void 0, function () {
2738
+ return __generator(this, function (_b) {
2739
+ switch (_b.label) {
2740
+ case 0:
2741
+ if (!!!this.data().boxes[index])
2742
+ return [2, 0];
2743
+ if (!(type === 'height')) return [3, 2];
2744
+ return [4, this.save({
2745
+ boxes: this.data().boxes.map(function (b, bIndex) {
2746
+ if (bIndex !== index)
2747
+ return b;
2748
+ return __assign(__assign({}, b), { height: value });
2749
+ })
2750
+ }, undefined, true)];
2751
+ case 1: return [2, _b.sent()];
2752
+ case 2:
2753
+ if (!(type === 'width')) return [3, 4];
2754
+ return [4, this.save({
2755
+ boxes: this.data().boxes.map(function (b, bIndex) {
2756
+ if (bIndex !== index)
2757
+ return b;
2758
+ return __assign(__assign({}, b), { width: value });
2759
+ })
2760
+ }, undefined, true)];
2761
+ case 3: return [2, _b.sent()];
2762
+ case 4:
2763
+ if (!(type === 'length')) return [3, 6];
2764
+ return [4, this.save({
2765
+ boxes: this.data().boxes.map(function (b, bIndex) {
2766
+ if (bIndex !== index)
2767
+ return b;
2768
+ return __assign(__assign({}, b), { length: value });
2769
+ })
2770
+ }, undefined, true)];
2771
+ case 5: return [2, _b.sent()];
2772
+ case 6: return [2];
2773
+ }
2774
+ });
2775
+ }); };
2776
+ _this.getShipDate = function () {
2777
+ var shipping = _this.data().shipping_selected;
2778
+ if (!!!shipping)
2779
+ return false;
2780
+ if (!!!shipping.details)
2781
+ return false;
2782
+ return shipping.details.shipDate;
2783
+ };
2784
+ _this.setShipDate = function (shipDate) { return __awaiter(_this, void 0, void 0, function () {
2785
+ var shipping;
2786
+ return __generator(this, function (_b) {
2787
+ switch (_b.label) {
2788
+ case 0:
2789
+ shipping = this.data().shipping_selected;
2790
+ if (!!!!shipping) return [3, 2];
2791
+ return [4, this.save({
2792
+ shipping_selected: { details: { shipDate: shipDate } }
2793
+ })];
2794
+ case 1: return [2, _b.sent()];
2795
+ case 2:
2796
+ if (!!!!shipping.details) return [3, 4];
2797
+ return [4, this.save({
2798
+ shipping_selected: __assign(__assign({}, shipping), { details: { shipDate: shipDate } })
2799
+ })];
2800
+ case 3: return [2, _b.sent()];
2801
+ case 4: return [4, this.save({
2802
+ shipping_selected: __assign(__assign({}, shipping), { details: __assign(__assign({}, shipping.details), { shipDate: shipDate }) })
2803
+ })];
2804
+ case 5: return [2, _b.sent()];
2805
+ }
2806
+ });
2807
+ }); };
2808
+ _this.setBoxTypeAtIndex = function (boxType, boxIndex) { return __awaiter(_this, void 0, void 0, function () {
2809
+ var e_13;
2810
+ var _this = this;
2811
+ return __generator(this, function (_b) {
2812
+ switch (_b.label) {
2813
+ case 0:
2814
+ _b.trys.push([0, 2, , 3]);
2815
+ return [4, this.save({
2816
+ boxes: this._data.boxes.map(function (b, i) {
2817
+ if (i !== boxIndex)
2818
+ return b;
2819
+ return __assign(__assign({}, b), { slug: boxType.slug, height: boxType.height, width: boxType.width, length: boxType.length, name: boxType.name, occupied_volume: (0, sumBy_1.default)(_this._data.items, function (item) {
2820
+ return !b.item_ids.includes(item.sku)
2821
+ ? 0
2822
+ : _this._calculateItemVolume(item) * (0, sumBy_1.default)(b.item_ids, function (id) { return (id === item.sku ? 1 : 0); });
2823
+ }) / _this._calculateBoxVolume(boxType) });
2824
+ })
2825
+ })];
2826
+ case 1:
2827
+ _b.sent();
2828
+ return [2, true];
2829
+ case 2:
2830
+ e_13 = _b.sent();
2831
+ throw new Error(e_13);
2832
+ case 3: return [2];
2833
+ }
2834
+ });
2835
+ }); };
2836
+ _this.processShippingWithQuote = function (quote) { return __awaiter(_this, void 0, void 0, function () {
2837
+ var resCredz, shippingServiceCredz, shipment, space, quoteRes, error_12;
2838
+ return __generator(this, function (_b) {
2839
+ switch (_b.label) {
2840
+ case 0:
2841
+ if (!!!quote)
2842
+ throw new Error("No quote found");
2843
+ return [4, this._getCredz()];
2844
+ case 1:
2845
+ resCredz = _b.sent();
2846
+ if (typeof resCredz === 'number' || Array.isArray(resCredz))
2847
+ return [2, false];
2848
+ shippingServiceCredz = resCredz.shippingServiceCredz;
2849
+ shipment = new Shipment_1.default(this, shippingServiceCredz);
2850
+ return [4, Space_1.default.getCurrentSpaceWithRef(this._collection.path, this._user)];
2851
+ case 2:
2852
+ space = _b.sent();
2853
+ _b.label = 3;
2854
+ case 3:
2855
+ _b.trys.push([3, 6, , 7]);
2856
+ return [4, shipment.approveQuote(quote, false, {
2857
+ cartItem: this,
2858
+ fromAddress: space.data().transport_preferences.default_departure_address,
2859
+ serviceCode: quote.service_code,
2860
+ companyName: !!space.data().transport_preferences.default_departure_address
2861
+ ? space.data().transport_preferences.default_departure_address.companyName
2862
+ : '',
2863
+ companyPhone: !!space.data().transport_preferences.default_departure_address
2864
+ ? space.data().transport_preferences.default_departure_address.phone
2865
+ : ''
2866
+ })];
2867
+ case 4:
2868
+ quoteRes = _b.sent();
2869
+ if (!quoteRes.confirmed) {
2870
+ return [2, false];
2871
+ }
2872
+ return [4, this.save({
2873
+ shipping_payload: quoteRes.details,
2874
+ status: Cart_1.CartStatusEnum.SHIPPING_AWAITING_OR_PICKUP_READY
2875
+ })];
2876
+ case 5:
2877
+ _b.sent();
2878
+ return [2, true];
2879
+ case 6:
2880
+ error_12 = _b.sent();
2881
+ console.log("error while approving quote", error_12);
2882
+ throw error_12;
2883
+ case 7: return [2];
2884
+ }
2885
+ });
2886
+ }); };
2887
+ _this.getStatus = function () {
2888
+ return _this.data().status;
2889
+ };
2890
+ _this.cancelShipping = function () { return __awaiter(_this, void 0, void 0, function () {
2891
+ var resCredz, shippingPayload, shippingServiceCredz, shipment, quoteRes, error_13;
2892
+ return __generator(this, function (_b) {
2893
+ switch (_b.label) {
2894
+ case 0: return [4, this._getCredz()];
2895
+ case 1:
2896
+ resCredz = _b.sent();
2897
+ shippingPayload = this.data().shipping_payload;
2898
+ if (typeof resCredz === 'number' || Array.isArray(resCredz))
2899
+ return [2, false];
2900
+ shippingServiceCredz = resCredz.shippingServiceCredz;
2901
+ shipment = new Shipment_1.default(this, shippingServiceCredz);
2902
+ _b.label = 2;
2903
+ case 2:
2904
+ _b.trys.push([2, 5, , 6]);
2905
+ return [4, shipment.cancelShipping(shippingPayload.shipId, false, shippingPayload.deleteUrl)];
2906
+ case 3:
2907
+ quoteRes = _b.sent();
2908
+ if (!quoteRes.confirmed) {
2909
+ return [2, false];
2910
+ }
2911
+ return [4, this.save({
2912
+ status: Cart_1.CartStatusEnum.CART_READY_TO_PROCESS,
2913
+ shipping_payload: {},
2914
+ shipping_selected: {}
2915
+ })];
2916
+ case 4:
2917
+ _b.sent();
2918
+ return [2, true];
2919
+ case 5:
2920
+ error_13 = _b.sent();
2921
+ throw error_13;
2922
+ case 6: return [2];
2923
+ }
2924
+ });
2925
+ }); };
2926
+ _this.printLabel = function (spacePath) { return __awaiter(_this, void 0, void 0, function () {
2927
+ var resCredz, shippingPayload, shippingServiceCredz, shipment, quoteRes, label, defLabel, tempParsed, downloadUrl, error_14;
2928
+ return __generator(this, function (_b) {
2929
+ switch (_b.label) {
2930
+ case 0: return [4, this._getCredz()];
2931
+ case 1:
2932
+ resCredz = _b.sent();
2933
+ shippingPayload = this.data().shipping_payload;
2934
+ if (typeof resCredz === 'number' || Array.isArray(resCredz))
2935
+ return [2];
2936
+ shippingServiceCredz = resCredz.shippingServiceCredz;
2937
+ shipment = new Shipment_1.default(this, shippingServiceCredz);
2938
+ _b.label = 2;
2939
+ case 2:
2940
+ _b.trys.push([2, 4, , 5]);
2941
+ return [4, shipment.getLabel(shippingPayload.labelUrl)];
2942
+ case 3:
2943
+ quoteRes = _b.sent();
2944
+ if (!!!quoteRes || !quoteRes.confirmed)
2945
+ return [2];
2946
+ label = quoteRes.label;
2947
+ defLabel = void 0;
2948
+ if (typeof label === 'string') {
2949
+ try {
2950
+ tempParsed = JSON.parse(label);
2951
+ defLabel = tempParsed.data || tempParsed || '';
2952
+ }
2953
+ catch (error) {
2954
+ defLabel = label || '';
2955
+ }
2956
+ }
2957
+ else
2958
+ defLabel = label.data || '';
2959
+ if (!!__1.isTestEnv)
2960
+ console.log('def', defLabel);
2961
+ downloadUrl = (0, file_1.uploadStringToPath)(defLabel, spacePath, "order-".concat(this.data().ref), 'pdf', undefined, true);
2962
+ return [2, downloadUrl];
2963
+ case 4:
2964
+ error_14 = _b.sent();
2965
+ throw error_14;
2966
+ case 5: return [2];
2967
+ }
2968
+ });
2969
+ }); };
2970
+ _this.getCartRef = function (space) {
2971
+ return {
2972
+ order: "".concat(!!space.data().order_settings ? space.data().order_settings.prefix || '' : '').concat(_this.data().ref).concat(!!space.data().order_settings ? space.data().order_settings.suffix || '' : ''),
2973
+ invoice: "".concat(!!space.data().invoice_settings ? space.data().invoice_settings.prefix || '' : '').concat(_this.data().ref).concat(!!space.data().invoice_settings ? space.data().invoice_settings.suffix || '' : '')
2974
+ };
2975
+ };
2976
+ _this.getPossibleShipmentType = function (service) {
2977
+ if (service.external_service_name.toLowerCase() === 'shiptime') {
2978
+ var possible = [
2979
+ order_1.PackageTypeEnum.MY_ENVELOPE,
2980
+ order_1.PackageTypeEnum.PACKAGE
2981
+ ];
2982
+ if (_this.getTotalWeight('pounds') <= 1)
2983
+ possible.push(order_1.PackageTypeEnum.LETTER);
2984
+ if (_this.getTotalWeight('pounds') <= 3)
2985
+ possible.push(order_1.PackageTypeEnum.PAK);
2986
+ return possible;
2987
+ }
2988
+ if (service.external_service_name === 'Poste Canada') {
2989
+ return [order_1.PackageTypeEnum.PACKAGE, order_1.PackageTypeEnum.UNPACKAGED, order_1.PackageTypeEnum.TUBE, order_1.PackageTypeEnum.OVERSIZE];
2990
+ }
2991
+ return [];
2992
+ };
2993
+ _this.getPossibleShipmentService = function (service) {
2994
+ if (service.external_service_name.toLowerCase() === 'shiptime') {
2995
+ return (0, map_1.default)(order_1.ShipTimeServiceEnum, function (e) { return e; });
2996
+ }
2997
+ if (service.external_service_name === 'Poste Canada') {
2998
+ return (0, map_1.default)(order_1.CanadaPostServiceEnum, function (e) { return e; });
2999
+ }
3000
+ return [];
3001
+ };
3002
+ _this.postConstruct = function (currency, save, options) {
3003
+ if (options === void 0) { options = {}; }
3004
+ return __awaiter(_this, void 0, void 0, function () {
3005
+ var _this = this;
3006
+ return __generator(this, function (_b) {
3007
+ switch (_b.label) {
3008
+ case 0: return [4, this.setAllTaxes()];
3009
+ case 1:
3010
+ _b.sent();
3011
+ if (!!!!options.skipDiscountRules) return [3, 3];
3012
+ return [4, this.setDiscountRules()];
3013
+ case 2:
3014
+ _b.sent();
3015
+ _b.label = 3;
3016
+ case 3:
3017
+ if (!!!options.skipTierPricing) {
3018
+ this.data().items.map(function (item, iIndex) {
3019
+ if (!!item.tier_pricing) {
3020
+ _this.checkTierPricing(item, item.qte, iIndex);
3021
+ }
3022
+ });
3023
+ }
3024
+ return [4, this.calculateTotals(currency)];
3025
+ case 4:
3026
+ _b.sent();
3027
+ if (!!!save) return [3, 6];
3028
+ return [4, this.save()];
3029
+ case 5:
3030
+ _b.sent();
3031
+ _b.label = 6;
3032
+ case 6: return [2];
3033
+ }
3034
+ });
3035
+ });
3036
+ };
3037
+ _this.getTracking = function () {
3038
+ var shipSelected = _this.data().shipping_selected;
3039
+ var shipPayload = _this.data().shipping_payload;
3040
+ if (!!!shipPayload)
3041
+ return {
3042
+ error: 'Impossible de trouver le numéro de tracking',
3043
+ trackingPin: ''
3044
+ };
3045
+ if (!!!shipSelected || !!!shipSelected.carrier)
3046
+ return {
3047
+ error: '',
3048
+ trackingPin: shipPayload.trackingNumbers || shipPayload.tracking,
3049
+ trackingUrl: shipPayload.carrierTrackingUrl || shipPayload.trackingUrl
3050
+ };
3051
+ switch (shipSelected.carrier.toLowerCase()) {
3052
+ case 'poste canada':
3053
+ var elementParentWithTracking = shipPayload.elements.find(function (ele_firstLevel) {
3054
+ return ele_firstLevel.elements.find(function (ele_secondLevel) { return ele_secondLevel.name === 'tracking-pin'; });
3055
+ });
3056
+ if (!!!elementParentWithTracking)
3057
+ return {
3058
+ error: 'Impossible de trouver le numéro de tracking',
3059
+ trackingPin: ''
3060
+ };
3061
+ var elementChildWithTracking = elementParentWithTracking.elements.find(function (ele) { return ele.name === 'tracking-pin'; });
3062
+ var trackingPin = elementChildWithTracking.elements[0].text;
3063
+ if (!!!trackingPin)
3064
+ return {
3065
+ error: 'Impossible de trouver le numéro de tracking',
3066
+ trackingPin: ''
3067
+ };
3068
+ return { error: '', trackingPin: trackingPin };
3069
+ default:
3070
+ return {
3071
+ error: '',
3072
+ trackingPin: shipPayload.trackingNumbers,
3073
+ trackingUrl: shipPayload.carrierTrackingUrl
3074
+ };
3075
+ }
3076
+ };
3077
+ _this.items = {
3078
+ get: _this._getItems,
3079
+ getFormatStringById: _this._getFormatStringById
3080
+ };
3081
+ _this.boxes = {
3082
+ get: _this._getBoxes,
3083
+ getWeight: _this._getWeight,
3084
+ setWeight: _this._setWeight,
3085
+ getIfVerifiedWeight: _this._getIfVerifiedWeight,
3086
+ setIfVerifiedWeight: _this._setIfVerifiedWeight,
3087
+ getBoxDimension: _this._getBoxDimension,
3088
+ setBoxDimension: _this._setBoxDimension
3089
+ };
3090
+ _this.updateWithPromiseToPurchasePrices = function (escompteItems, customPriceList, banksUsedForCart) {
3091
+ if (customPriceList === void 0) { customPriceList = undefined; }
3092
+ return __awaiter(_this, void 0, void 0, function () {
3093
+ var updatedPriceProducts, associatedEscomptes, _loop_7, index;
3094
+ return __generator(this, function (_b) {
3095
+ switch (_b.label) {
3096
+ case 0:
3097
+ if (!!!customPriceList || typeof customPriceList == 'string')
3098
+ throw new Error('CustomPriceList is undefined!');
3099
+ if (!!this.data().status &&
3100
+ this.data().status >= Cart_1.CartStatusEnum.CHECKOUT_PAYMENT_SUCCESS &&
3101
+ !!this.data().paid_at) {
3102
+ console.log('cannot update a paid cart with a PA, returning');
3103
+ return [2];
3104
+ }
3105
+ updatedPriceProducts = this.data()
3106
+ .items.filter(function (item) { return !(0, g2_1.isEscompteSuppItem)(item.sku); })
3107
+ .map(function (item) {
3108
+ var shouldCheckPriceList = !!!banksUsedForCart ||
3109
+ (!!item.promise_to_purchase_association_ids &&
3110
+ !!item.promise_to_purchase_association_ids.some(function (id) { return !!banksUsedForCart.map(function (b) { return b.bank_type_id; }).includes(id); }));
3111
+ return (!!shouldCheckPriceList ? (0, g2_1.checkForCustomPriceEquivalent)(item, customPriceList) : item);
3112
+ });
3113
+ associatedEscomptes = new Array();
3114
+ _loop_7 = function (index) {
3115
+ var item = updatedPriceProducts[index];
3116
+ if (!!!item.promise_to_purchase_association_ids ||
3117
+ item.promise_to_purchase_association_ids.length == 0 ||
3118
+ (!!banksUsedForCart &&
3119
+ banksUsedForCart.every(function (b) { return !!!item.promise_to_purchase_association_ids.includes(b.bank_type_id); }))) {
3120
+ return "continue";
3121
+ }
3122
+ var associatedEscompte = (0, g2_1.getItemEscompteSupp)(customPriceList, item);
3123
+ if (!!!associatedEscompte)
3124
+ return "continue";
3125
+ var escompteSuppCartItem = (0, g2_1.buildEscompteSuppCartItem)(escompteItems, customPriceList, associatedEscompte, item);
3126
+ if (!!!escompteSuppCartItem)
3127
+ return "continue";
3128
+ associatedEscomptes.push(escompteSuppCartItem);
3129
+ };
3130
+ for (index = 0; index < updatedPriceProducts.length; index++) {
3131
+ _loop_7(index);
3132
+ }
3133
+ this._data = __assign(__assign({}, this._data), { items: __spreadArray(__spreadArray([], updatedPriceProducts, true), associatedEscomptes, true) });
3134
+ return [4, this.calculateTotals()];
3135
+ case 1:
3136
+ _b.sent();
3137
+ return [2];
3138
+ }
3139
+ });
3140
+ });
3141
+ };
3142
+ _this.canBePaidWithMyPromiseToPurchase = function (applicableBanks, applicableBanksHistory, customPriceList, contingency, forcedBankTypeId) {
3143
+ if (customPriceList === void 0) { customPriceList = undefined; }
3144
+ if (contingency === void 0) { contingency = 0; }
3145
+ return __awaiter(_this, void 0, void 0, function () {
3146
+ var space, remainingAmounts, potentialRemainingAmounts, e_14;
3147
+ return __generator(this, function (_b) {
3148
+ switch (_b.label) {
3149
+ case 0:
3150
+ if (!!!customPriceList || typeof customPriceList == 'string')
3151
+ throw new Error(PromiseToPurchase_2.ApplyBanksToCartErrorsEnum.CUSTOM_PRICE_LIST_UNDEFINED);
3152
+ return [4, this._savePromiseToPurchaseInCart(applicableBanks, false)];
3153
+ case 1:
3154
+ _b.sent();
3155
+ _b.label = 2;
3156
+ case 2:
3157
+ _b.trys.push([2, 5, , 6]);
3158
+ return [4, Space_1.default.getCurrentSpaceWithRef(this._collection.path, this._user)];
3159
+ case 3:
3160
+ space = _b.sent();
3161
+ return [4, PromiseToPurchase_1.default.calculateRemainingAmounts(this, applicableBanks, applicableBanksHistory, space)];
3162
+ case 4:
3163
+ remainingAmounts = _b.sent();
3164
+ potentialRemainingAmounts = this.calculatePotentialRemainingAmountsAndSetBanksUsedAmounts(remainingAmounts, applicableBanks, forcedBankTypeId);
3165
+ if (!!!potentialRemainingAmounts.length) {
3166
+ throw new Error(PromiseToPurchase_2.ApplyBanksToCartErrorsEnum.BANK_NOT_FOUND);
3167
+ }
3168
+ if (!!potentialRemainingAmounts.find(function (bank) { return bank.amount + contingency < 0; })) {
3169
+ throw new Error(PromiseToPurchase_2.ApplyBanksToCartErrorsEnum.NOT_ENOUGH_REMAINING);
3170
+ }
3171
+ return [2, true];
3172
+ case 5:
3173
+ e_14 = _b.sent();
3174
+ console.log('error on checking if pa can be used for cart: ', e_14.message);
3175
+ return [2, e_14.message];
3176
+ case 6: return [2];
3177
+ }
3178
+ });
3179
+ });
3180
+ };
3181
+ _this.calculatePotentialRemainingAmountsAndSetBanksUsedAmounts = function (remainingAmounts, applicableBanks, forcedBankTypeId) {
3182
+ var accountedForItems = new Array();
3183
+ var itemsToCheck = _this.data().items;
3184
+ var singleBankItems = itemsToCheck.filter(function (item) { return !!item.promise_to_purchase_association_ids && item.promise_to_purchase_association_ids.length == 1; });
3185
+ if (singleBankItems.length == 0) {
3186
+ throw new Error(PromiseToPurchase_2.ApplyBanksToCartErrorsEnum.ONLY_ITEMS_WITH_MULTI_ASSOCIATED_BANKS);
3187
+ }
3188
+ var multipleBankItems = itemsToCheck.filter(function (item) { return !!!item.promise_to_purchase_association_ids || item.promise_to_purchase_association_ids.length != 1; });
3189
+ if (!!forcedBankTypeId) {
3190
+ var bankToUse = remainingAmounts.find(function (bank) { return bank.bank_type_id == forcedBankTypeId; });
3191
+ if (!!!bankToUse)
3192
+ throw new Error(PromiseToPurchase_2.ApplyBanksToCartErrorsEnum.BANK_NOT_FOUND);
3193
+ remainingAmounts = new Array(bankToUse);
3194
+ }
3195
+ var bankTypesWithAmountsUsed = {};
3196
+ for (var _b = 0, singleBankItems_1 = singleBankItems; _b < singleBankItems_1.length; _b++) {
3197
+ var item = singleBankItems_1[_b];
3198
+ if (!!!item.promise_to_purchase_association_ids || !!!item.promise_to_purchase_association_ids.length)
3199
+ continue;
3200
+ var itemPrice = _this.getLowestPrice(item) * item.qte;
3201
+ var itemAssociatedId = item.promise_to_purchase_association_ids[0];
3202
+ bankTypesWithAmountsUsed["".concat(itemAssociatedId)] =
3203
+ (bankTypesWithAmountsUsed["".concat(itemAssociatedId)] || 0) + itemPrice;
3204
+ }
3205
+ var mostUsedBank = {
3206
+ id: '',
3207
+ amount: 0
3208
+ };
3209
+ for (var _c = 0, _d = Object.entries(bankTypesWithAmountsUsed); _c < _d.length; _c++) {
3210
+ var _e = _d[_c], key = _e[0], value = _e[1];
3211
+ if (value > mostUsedBank.amount) {
3212
+ mostUsedBank = {
3213
+ id: key,
3214
+ amount: value
3215
+ };
3216
+ }
3217
+ }
3218
+ if (!!remainingAmounts.length) {
3219
+ var banksToUse = remainingAmounts;
3220
+ var promiseBanksToUse = banksToUse
3221
+ .map(function (bankToUse) {
3222
+ var sameInApplicable = applicableBanks.find(function (b) { return b.bank.bank_type_id === bankToUse.bank_type_id; });
3223
+ return !!sameInApplicable ? sameInApplicable.bank : undefined;
3224
+ })
3225
+ .filter(function (bank) { return !!bank; });
3226
+ var allBanksAreInInactivePA = promiseBanksToUse.every(function (b) {
3227
+ var sameInApplicable = applicableBanks.find(function (ab) { return ab.bank.bank_type_id === b.bank_type_id; });
3228
+ return !!sameInApplicable && !!!sameInApplicable.pa_is_active;
3229
+ });
3230
+ if (!!allBanksAreInInactivePA) {
3231
+ throw new Error(PromiseToPurchase_2.ApplyBanksToCartErrorsEnum.PA_IS_INACTIVE);
3232
+ }
3233
+ var allBanksAreInactive = promiseBanksToUse.every(function (b) {
3234
+ var sameInApplicable = applicableBanks.find(function (ab) { return ab.bank.bank_type_id === b.bank_type_id; });
3235
+ return !!sameInApplicable && !!!sameInApplicable.bank.active;
3236
+ });
3237
+ if (!!allBanksAreInactive) {
3238
+ throw new Error(PromiseToPurchase_2.ApplyBanksToCartErrorsEnum.BANK_NOT_FOUND);
3239
+ }
3240
+ var _loop_8 = function (bankToUse) {
3241
+ var sameInApplicable = applicableBanks.find(function (ab) { return ab.bank.bank_type_id === bankToUse.bank_type_id; });
3242
+ if (!!sameInApplicable && (!!!sameInApplicable.pa_is_active || !!!sameInApplicable.bank.active)) {
3243
+ remainingAmounts = remainingAmounts
3244
+ .map(function (r) {
3245
+ if (r.bank_type_id !== sameInApplicable.bank.bank_type_id)
3246
+ return r;
3247
+ return undefined;
3248
+ })
3249
+ .filter(function (r) { return !!r; });
3250
+ }
3251
+ };
3252
+ for (var _f = 0, promiseBanksToUse_1 = promiseBanksToUse; _f < promiseBanksToUse_1.length; _f++) {
3253
+ var bankToUse = promiseBanksToUse_1[_f];
3254
+ _loop_8(bankToUse);
3255
+ }
3256
+ if (promiseBanksToUse.find(function (bankToUse) { return !!bankToUse && !!!bankToUse.initial_amount; })) {
3257
+ remainingAmounts = new Array();
3258
+ }
3259
+ }
3260
+ var banksUsed = new Array();
3261
+ var potentialRemainingAmounts = [];
3262
+ var _loop_9 = function (bank) {
3263
+ var amountToRemove = 0;
3264
+ var bank_type_id = bank.bank_type_id, amount = bank.amount, rest = __rest(bank, ["bank_type_id", "amount"]);
3265
+ if (!!forcedBankTypeId) {
3266
+ amountToRemove = _this.getSubtotal();
3267
+ }
3268
+ else {
3269
+ var itemsToAccount = _this.data().items.filter(function (item) {
3270
+ var bankIDInAssociatedPromises = !!item.promise_to_purchase_association_ids &&
3271
+ item.promise_to_purchase_association_ids.length == 1 &&
3272
+ item.promise_to_purchase_association_ids.includes(bank_type_id);
3273
+ var isEscSupp = false;
3274
+ var sameInApplicable = applicableBanks.find(function (ab) { return ab.bank.bank_type_id === bank_type_id; });
3275
+ if (!!sameInApplicable && !!sameInApplicable.bank.reductions.length) {
3276
+ for (var _b = 0, _c = sameInApplicable.bank.reductions; _b < _c.length; _b++) {
3277
+ var red = _c[_b];
3278
+ if (!!!red.external_service_association)
3279
+ continue;
3280
+ for (var _d = 0, _e = red.external_service_association; _d < _e.length; _d++) {
3281
+ var extService = _e[_d];
3282
+ if (!!item.sku.includes(extService.value))
3283
+ isEscSupp = true;
3284
+ }
3285
+ }
3286
+ }
3287
+ var isServiceOrMultiple = (!!item.promise_to_purchase_association_ids &&
3288
+ !!!item.promise_to_purchase_association_ids.length &&
3289
+ !!item.is_service &&
3290
+ !!item.sku &&
3291
+ !!!item.is_temp_prod) ||
3292
+ !!multipleBankItems.some(function (i) { return i.sku === item.sku; });
3293
+ return ((!!bankIDInAssociatedPromises ||
3294
+ !!isEscSupp ||
3295
+ (!!isServiceOrMultiple && bank.bank_type_id === mostUsedBank.id)) &&
3296
+ !!!accountedForItems.includes(item.sku));
3297
+ });
3298
+ amountToRemove = (0, sumBy_1.default)(itemsToAccount, function (item) {
3299
+ accountedForItems.push(item.sku);
3300
+ var priceToPay = _this.getLowestPrice(item);
3301
+ return priceToPay * item.qte;
3302
+ });
3303
+ }
3304
+ if (amountToRemove > 0 && amount < 1)
3305
+ throw new Error(PromiseToPurchase_2.ApplyBanksToCartErrorsEnum.EMPTY_BANK);
3306
+ if (amountToRemove > 0) {
3307
+ banksUsed.push(__assign(__assign({}, rest), { bank_type_id: bank_type_id, amount: amountToRemove }));
3308
+ potentialRemainingAmounts.push(__assign(__assign({}, rest), { bank_type_id: bank_type_id, amount: amount - amountToRemove }));
3309
+ }
3310
+ };
3311
+ for (var _g = 0, remainingAmounts_1 = remainingAmounts; _g < remainingAmounts_1.length; _g++) {
3312
+ var bank = remainingAmounts_1[_g];
3313
+ _loop_9(bank);
3314
+ }
3315
+ _this.setBankUsed(banksUsed);
3316
+ return potentialRemainingAmounts;
3317
+ };
3318
+ _this._savePromiseToPurchaseInCart = function (applicableBanks, saveToDatabase) {
3319
+ if (saveToDatabase === void 0) { saveToDatabase = true; }
3320
+ return __awaiter(_this, void 0, void 0, function () {
3321
+ return __generator(this, function (_b) {
3322
+ switch (_b.label) {
3323
+ case 0:
3324
+ this._data = __assign(__assign({}, this._data), { promise_to_purchase: {
3325
+ ids: (0, uniq_1.default)(applicableBanks.map(function (b) { return b.promise_id; })),
3326
+ banks_used: applicableBanks.map(function (b) {
3327
+ var bank = b.bank, rest = __rest(b, ["bank"]);
3328
+ return __assign(__assign({}, rest), { bank_type_id: bank.bank_type_id, amount: bank.initial_amount || 0 });
3329
+ })
3330
+ } });
3331
+ if (!saveToDatabase) return [3, 2];
3332
+ return [4, this.save()];
3333
+ case 1:
3334
+ _b.sent();
3335
+ _b.label = 2;
3336
+ case 2: return [2];
3337
+ }
3338
+ });
3339
+ });
3340
+ };
3341
+ _this.setBankUsed = function (bankAmountsUpdated) {
3342
+ _this._data = __assign(__assign({}, _this._data), { promise_to_purchase: {
3343
+ ids: (0, uniq_1.default)(bankAmountsUpdated.map(function (b) { return b.promise_id; })),
3344
+ banks_used: bankAmountsUpdated
3345
+ } });
3346
+ };
3347
+ _this.canBePaidWithPA = function (applicableBanks, customerID, customPriceList, space, forcedBankTypeId) { return __awaiter(_this, void 0, void 0, function () {
3348
+ var contingency, escomptesItems, applicableBanksHistory, _b, applicableBanks_1, applicable, promise_id, bank, bankHistory, e_15, filteredApplicableBanksHistory, possibleBanksToUse, canBePaidCheck, canBePaid;
3349
+ return __generator(this, function (_c) {
3350
+ switch (_c.label) {
3351
+ case 0:
3352
+ contingency = space.promisesToPurchase.getContingency();
3353
+ return [4, space.promisesToPurchase.getEscompteItems()];
3354
+ case 1:
3355
+ escomptesItems = _c.sent();
3356
+ applicableBanksHistory = [];
3357
+ _b = 0, applicableBanks_1 = applicableBanks;
3358
+ _c.label = 2;
3359
+ case 2:
3360
+ if (!(_b < applicableBanks_1.length)) return [3, 7];
3361
+ applicable = applicableBanks_1[_b];
3362
+ promise_id = applicable.promise_id, bank = applicable.bank;
3363
+ if (!!!bank.initial_amount)
3364
+ return [3, 6];
3365
+ _c.label = 3;
3366
+ case 3:
3367
+ _c.trys.push([3, 5, , 6]);
3368
+ return [4, space.promisesToPurchase.getBanksUsedHistory({ customerID: customerID, promiseID: promise_id, bankTypeID: bank.bank_type_id }, { hpp: 100000 })];
3369
+ case 4:
3370
+ bankHistory = _c.sent();
3371
+ if (!!bankHistory) {
3372
+ applicableBanksHistory = __spreadArray(__spreadArray([], applicableBanksHistory, true), bankHistory, true);
3373
+ }
3374
+ return [3, 6];
3375
+ case 5:
3376
+ e_15 = _c.sent();
3377
+ console.log('error on fetching bank history for bank ', bank.bank_type_id, ': ', e_15.toString());
3378
+ return [3, 6];
3379
+ case 6:
3380
+ _b++;
3381
+ return [3, 2];
3382
+ case 7:
3383
+ filteredApplicableBanksHistory = (0, flatten_1.default)(applicableBanksHistory).filter(function (b) { return !!b; });
3384
+ possibleBanksToUse = applicableBanks
3385
+ .filter(function (b) { return !!b.pa_is_active && !!b.bank.active && !!b.bank.initial_amount; })
3386
+ .map(function (b) { return ({
3387
+ promise_id: b.promise_id,
3388
+ promise_unique_id: b.promise_unique_id,
3389
+ bank_type_id: b.bank.bank_type_id,
3390
+ amount: 0
3391
+ }); });
3392
+ return [4, this.updateWithPromiseToPurchasePrices(escomptesItems, customPriceList, possibleBanksToUse)];
3393
+ case 8:
3394
+ _c.sent();
3395
+ return [4, this.canBePaidWithMyPromiseToPurchase(applicableBanks, filteredApplicableBanksHistory, customPriceList, contingency, forcedBankTypeId)];
3396
+ case 9:
3397
+ canBePaidCheck = _c.sent();
3398
+ if (!(!!this._data.promise_to_purchase &&
3399
+ applicableBanks.length !== this._data.promise_to_purchase.banks_used.length)) return [3, 11];
3400
+ return [4, this.updateWithPromiseToPurchasePrices(escomptesItems, customPriceList, this._data.promise_to_purchase.banks_used)];
3401
+ case 10:
3402
+ _c.sent();
3403
+ _c.label = 11;
3404
+ case 11:
3405
+ canBePaid = typeof canBePaidCheck === 'boolean';
3406
+ return [2, __assign(__assign({ canBePaid: canBePaid }, (!!!canBePaid ? { canBePaidReason: canBePaidCheck } : {})), { updatedCart: this.data() })];
3407
+ }
3408
+ });
3409
+ }); };
3410
+ _this.checkForEmptyBanksAfterPayment = function (space) { return __awaiter(_this, void 0, void 0, function () {
3411
+ var promisesInCart, banksToDeactivate, _loop_10, this_2, _b, _c, bank, e_16;
3412
+ var _this = this;
3413
+ return __generator(this, function (_d) {
3414
+ switch (_d.label) {
3415
+ case 0:
3416
+ promisesInCart = this._data.promise_to_purchase;
3417
+ if (!!!promisesInCart)
3418
+ return [2];
3419
+ banksToDeactivate = {};
3420
+ _loop_10 = function (bank) {
3421
+ var promiseQuery, promise, sameBankInPromise, bankUseHistory, historyQuery, e_17, remaining_amount, remainingAmount, promiseAlreadySetInObj, e_18;
3422
+ return __generator(this, function (_e) {
3423
+ switch (_e.label) {
3424
+ case 0:
3425
+ _e.trys.push([0, 6, , 7]);
3426
+ return [4, space.promisesToPurchase.get({
3427
+ query: [{ field: 'id', operator: '==', value: bank.promise_id }]
3428
+ })];
3429
+ case 1:
3430
+ promiseQuery = _e.sent();
3431
+ if (!!!promiseQuery || !!!promiseQuery.length)
3432
+ throw new Error('Could not find associated promise in DB');
3433
+ promise = promiseQuery[0];
3434
+ sameBankInPromise = promise.data().banks.find(function (b) { return b.bank_type_id === bank.bank_type_id; });
3435
+ if (!!!sameBankInPromise)
3436
+ throw new Error('Could not find same bank in promise');
3437
+ bankUseHistory = [];
3438
+ _e.label = 2;
3439
+ case 2:
3440
+ _e.trys.push([2, 4, , 5]);
3441
+ return [4, space.promisesToPurchase.getBanksUsedHistory({
3442
+ customerID: this_2._data.customer_id,
3443
+ promiseID: bank.promise_id,
3444
+ bankTypeID: bank.bank_type_id
3445
+ })];
3446
+ case 3:
3447
+ historyQuery = _e.sent();
3448
+ if (!!historyQuery) {
3449
+ bankUseHistory = historyQuery.filter(function (h) {
3450
+ return !!!h.associated_cart_ref ||
3451
+ h.associated_cart_ref !== _this._data.ref ||
3452
+ (!!_this._data.paid_at && h.date !== (0, moment_1.default)((0, data_1.formatDate)(_this._data.paid_at)).unix());
3453
+ });
3454
+ }
3455
+ return [3, 5];
3456
+ case 4:
3457
+ e_17 = _e.sent();
3458
+ console.log('error on fetching history for banks: ', e_17.toString());
3459
+ return [3, 5];
3460
+ case 5:
3461
+ remaining_amount = (0, promiseToPurchase_1.calculatedRemainingBankAmount)(sameBankInPromise.initial_amount, bankUseHistory).remaining_amount;
3462
+ if (typeof remaining_amount === 'number') {
3463
+ remainingAmount = remaining_amount - bank.amount;
3464
+ if ((0, round_1.default)(remainingAmount, 2) < 1) {
3465
+ promiseAlreadySetInObj = banksToDeactivate[bank.promise_id];
3466
+ banksToDeactivate[bank.promise_id] = {
3467
+ promiseObj: promise,
3468
+ bankIDs: __spreadArray(__spreadArray([], (!!promiseAlreadySetInObj ? promiseAlreadySetInObj.bankIDs : []), true), [bank.bank_type_id], false)
3469
+ };
3470
+ }
3471
+ }
3472
+ return [3, 7];
3473
+ case 6:
3474
+ e_18 = _e.sent();
3475
+ console.log('error on fetching promises for bank: ', e_18.toString());
3476
+ return [3, 7];
3477
+ case 7: return [2];
3478
+ }
3479
+ });
3480
+ };
3481
+ this_2 = this;
3482
+ _b = 0, _c = promisesInCart.banks_used;
3483
+ _d.label = 1;
3484
+ case 1:
3485
+ if (!(_b < _c.length)) return [3, 4];
3486
+ bank = _c[_b];
3487
+ return [5, _loop_10(bank)];
3488
+ case 2:
3489
+ _d.sent();
3490
+ _d.label = 3;
3491
+ case 3:
3492
+ _b++;
3493
+ return [3, 1];
3494
+ case 4:
3495
+ _d.trys.push([4, 6, , 7]);
3496
+ return [4, Promise.all(Object.values(banksToDeactivate).map(function (_b) {
3497
+ var promiseObj = _b.promiseObj, bankIDs = _b.bankIDs;
3498
+ return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_c) {
3499
+ switch (_c.label) {
3500
+ case 0: return [4, promiseObj.disableEmptyPABanks(bankIDs)];
3501
+ case 1: return [2, _c.sent()];
3502
+ }
3503
+ }); });
3504
+ }))];
3505
+ case 5:
3506
+ _d.sent();
3507
+ return [3, 7];
3508
+ case 6:
3509
+ e_16 = _d.sent();
3510
+ console.log('error on saving promises with empty banks: ', e_16.toString());
3511
+ return [3, 7];
3512
+ case 7: return [2];
3513
+ }
3514
+ });
3515
+ }); };
3516
+ _this.setCartAsProcessed = function (processedAtStore, currentUser) { return __awaiter(_this, void 0, void 0, function () {
3517
+ var newData, saved;
3518
+ return __generator(this, function (_b) {
3519
+ newData = __assign({}, this.data());
3520
+ newData = __assign(__assign({}, newData), { status: Cart_1.CartStatusEnum.CART_READY_TO_PROCESS });
3521
+ if (!!!newData.current_store_id && !!processedAtStore) {
3522
+ newData = __assign(__assign({}, newData), { current_store_id: processedAtStore.id });
3523
+ }
3524
+ if (!!currentUser) {
3525
+ newData = __assign(__assign({}, newData), { processed_by: this.getCartAssignedUserData(currentUser, processedAtStore) });
3526
+ }
3527
+ try {
3528
+ saved = this.save(newData, undefined, true);
3529
+ if (!!!saved) {
3530
+ throw new Error('could not save cart');
3531
+ }
3532
+ return [2, this.data().ref];
3533
+ }
3534
+ catch (e) {
3535
+ console.log('error on saving cart as processed: ', e.toString());
3536
+ }
3537
+ return [2];
3538
+ });
3539
+ }); };
3540
+ _this.setCartWithInvoiceRef = function (space, saveToDatabase) { return __awaiter(_this, void 0, void 0, function () {
3541
+ var invoiceRef, newData, e_19;
3542
+ return __generator(this, function (_b) {
3543
+ switch (_b.label) {
3544
+ case 0:
3545
+ invoiceRef = undefined;
3546
+ newData = __assign({}, this.data());
3547
+ _b.label = 1;
3548
+ case 1:
3549
+ _b.trys.push([1, 4, , 5]);
3550
+ return [4, space.invoices.incrementRef(newData)];
3551
+ case 2:
3552
+ invoiceRef = _b.sent();
3553
+ if (!!invoiceRef) {
3554
+ newData = __assign(__assign({}, newData), { invoice_ref: invoiceRef });
3555
+ }
3556
+ return [4, this.save(newData, undefined, !!saveToDatabase)];
3557
+ case 3:
3558
+ _b.sent();
3559
+ return [3, 5];
3560
+ case 4:
3561
+ e_19 = _b.sent();
3562
+ console.log('error on adding invoice_ref to cart: ', e_19.toString());
3563
+ return [2];
3564
+ case 5: return [2, invoiceRef];
3565
+ }
3566
+ });
3567
+ }); };
3568
+ _this.setCartAsRefunded = function () {
3569
+ var newData = __assign({}, _this.data());
3570
+ newData = __assign(__assign({}, newData), { status: Cart_1.CartStatusEnum.REFUND });
3571
+ try {
3572
+ var saved = _this.save(newData, undefined, true);
3573
+ if (!!!saved) {
3574
+ throw new Error('could not save cart');
3575
+ }
3576
+ return _this.data().ref;
3577
+ }
3578
+ catch (e) {
3579
+ console.log('error on saving cart as refunded: ', e.toString());
3580
+ }
3581
+ };
3582
+ if (!!resetErrors) {
3583
+ _this.clearErrors();
3584
+ }
3585
+ return _this;
3586
+ }
3587
+ var _a;
3588
+ _a = Cart;
3589
+ Cart.fetch = function (_b) {
3590
+ var app = _b.app, api = _b.api, _c = _b.hpp, hpp = _c === void 0 ? 10 : _c, _d = _b.page, page = _d === void 0 ? 0 : _d, _e = _b.query, query = _e === void 0 ? '' : _e, _f = _b.filters, filters = _f === void 0 ? '' : _f, _g = _b.indice, indice = _g === void 0 ? 'orders' : _g, _h = _b.f, f = _h === void 0 ? '' : _h, space = _b.space;
3591
+ return __awaiter(void 0, void 0, void 0, function () {
3592
+ var prosprSearch, prosprService, algolia, results, error_15;
3593
+ return __generator(_a, function (_j) {
3594
+ switch (_j.label) {
3595
+ case 0:
3596
+ _j.trys.push([0, 2, , 3]);
3597
+ prosprSearch = false;
3598
+ if (!!space) {
3599
+ prosprService = space
3600
+ .data()
3601
+ .external_services.find(function (es) { return es.external_service_name.toLowerCase().trim() === 'prosprsearch'; });
3602
+ prosprSearch = !!prosprService && prosprService.is_active;
3603
+ }
3604
+ algolia = (0, algolia_1.createClient)({
3605
+ app: app,
3606
+ indexId: "".concat(__1.isTestEnv ? 'test' : 'prod', "_").concat(indice),
3607
+ key: prosprSearch && !!space ? space.preferences.prosprsearch.app() : api,
3608
+ prospr: prosprSearch
3609
+ });
3610
+ return [4, algolia.search(query, {
3611
+ hitsPerPage: hpp,
3612
+ facetFilters: filters,
3613
+ filters: f,
3614
+ page: page,
3615
+ facets: ['*']
3616
+ })];
3617
+ case 1:
3618
+ results = _j.sent();
3619
+ return [2, results];
3620
+ case 2:
3621
+ error_15 = _j.sent();
3622
+ (0, console_1.errorMessage)(error_15);
3623
+ throw error_15;
3624
+ case 3: return [2];
3625
+ }
3626
+ });
3627
+ });
3628
+ };
3629
+ Cart.calculateMerchantShippingFee = function (shipping, space) {
3630
+ var merchantFee = !!space.transport_preferences
3631
+ ? !!space.transport_preferences.override_shipping_with_cost
3632
+ ? space.transport_preferences.override_shipping_with_cost
3633
+ : !!space.transport_preferences.add_percent_to_shipping_cost
3634
+ ? (space.transport_preferences.add_percent_to_shipping_cost / 100) * shipping
3635
+ : !!space.transport_preferences.add_amount_to_shipping_cost
3636
+ ? space.transport_preferences.add_amount_to_shipping_cost
3637
+ : 0
3638
+ : 0;
3639
+ return merchantFee;
3640
+ };
3641
+ return Cart;
3642
+ }(baseService_1.BaseServiceClass));
3643
+ exports.default = Cart;
3644
+ //# sourceMappingURL=index.js.map