addio-admin-sdk 1.7.196 → 1.7.197

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (589) hide show
  1. package/.babelrc +17 -17
  2. package/.env +14 -0
  3. package/.env.dev +14 -14
  4. package/.github/workflows/run_unit_test.yaml +48 -48
  5. package/.github/workflows/update_docs.yaml +32 -32
  6. package/addio-sdk-doc.md +1473 -1473
  7. package/changelog.md +582 -582
  8. package/dist/Interfaces/Address/index.d.ts +21 -21
  9. package/dist/Interfaces/Address/index.js +16 -16
  10. package/dist/Interfaces/Algolia/index.d.ts +183 -182
  11. package/dist/Interfaces/Algolia/index.js +2 -2
  12. package/dist/Interfaces/Attachement/index.d.ts +5 -5
  13. package/dist/Interfaces/Attachement/index.js +2 -2
  14. package/dist/Interfaces/Attribute/index.d.ts +53 -53
  15. package/dist/Interfaces/Attribute/index.js +10 -10
  16. package/dist/Interfaces/BGJob/index.d.ts +56 -56
  17. package/dist/Interfaces/BGJob/index.js +25 -25
  18. package/dist/Interfaces/BaseClass/index.d.ts +8 -8
  19. package/dist/Interfaces/BaseClass/index.js +2 -2
  20. package/dist/Interfaces/Blog/IBlogArticle.d.ts +18 -18
  21. package/dist/Interfaces/Blog/IBlogArticle.js +2 -2
  22. package/dist/Interfaces/Blog/IBlogAuthor.d.ts +7 -7
  23. package/dist/Interfaces/Blog/IBlogAuthor.js +2 -2
  24. package/dist/Interfaces/Blog/IBlogCategory.d.ts +9 -9
  25. package/dist/Interfaces/Blog/IBlogCategory.js +2 -2
  26. package/dist/Interfaces/Blog/IBlogComment.d.ts +13 -13
  27. package/dist/Interfaces/Blog/IBlogComment.js +2 -2
  28. package/dist/Interfaces/Blog/IBlogKeywords.d.ts +9 -9
  29. package/dist/Interfaces/Blog/IBlogKeywords.js +2 -2
  30. package/dist/Interfaces/Booking/index.d.ts +74 -74
  31. package/dist/Interfaces/Booking/index.js +17 -17
  32. package/dist/Interfaces/Brand/index.d.ts +15 -15
  33. package/dist/Interfaces/Brand/index.js +2 -2
  34. package/dist/Interfaces/Buylist/index.d.ts +19 -19
  35. package/dist/Interfaces/Buylist/index.js +2 -2
  36. package/dist/Interfaces/CMS/index.d.ts +28 -28
  37. package/dist/Interfaces/CMS/index.js +5 -5
  38. package/dist/Interfaces/Cart/IElavonPayload.d.ts +93 -93
  39. package/dist/Interfaces/Cart/IElavonPayload.js +17 -17
  40. package/dist/Interfaces/Cart/IMarketPayload.d.ts +12 -12
  41. package/dist/Interfaces/Cart/IMarketPayload.js +2 -2
  42. package/dist/Interfaces/Cart/IPandaPayload.d.ts +64 -64
  43. package/dist/Interfaces/Cart/IPandaPayload.js +18 -18
  44. package/dist/Interfaces/Cart/IPaymentCard.d.ts +22 -22
  45. package/dist/Interfaces/Cart/IPaymentCard.js +44 -44
  46. package/dist/Interfaces/Cart/IPaypalPayload.d.ts +9 -9
  47. package/dist/Interfaces/Cart/IPaypalPayload.js +2 -2
  48. package/dist/Interfaces/Cart/IPaysafePayload.d.ts +72 -72
  49. package/dist/Interfaces/Cart/IPaysafePayload.js +2 -2
  50. package/dist/Interfaces/Cart/IStripePayload.d.ts +66 -66
  51. package/dist/Interfaces/Cart/IStripePayload.js +2 -2
  52. package/dist/Interfaces/Cart/index.d.ts +478 -476
  53. package/dist/Interfaces/Cart/index.js +283 -283
  54. package/dist/Interfaces/Cart/index.js.map +1 -1
  55. package/dist/Interfaces/CartReservedQuantities/index.d.ts +10 -10
  56. package/dist/Interfaces/CartReservedQuantities/index.js +2 -2
  57. package/dist/Interfaces/CashDrawers/index.d.ts +38 -38
  58. package/dist/Interfaces/CashDrawers/index.js +19 -19
  59. package/dist/Interfaces/Catalogue/index.d.ts +68 -68
  60. package/dist/Interfaces/Catalogue/index.js +37 -37
  61. package/dist/Interfaces/Category/index.d.ts +33 -33
  62. package/dist/Interfaces/Category/index.js +2 -2
  63. package/dist/Interfaces/Chart/index.d.ts +11 -11
  64. package/dist/Interfaces/Chart/index.js +2 -2
  65. package/dist/Interfaces/Class/index.d.ts +8 -8
  66. package/dist/Interfaces/Class/index.js +2 -2
  67. package/dist/Interfaces/Consent/index.d.ts +6 -6
  68. package/dist/Interfaces/Consent/index.js +2 -2
  69. package/dist/Interfaces/Context/IContextProps.d.ts +4 -4
  70. package/dist/Interfaces/Context/IContextProps.js +2 -2
  71. package/dist/Interfaces/Context/IContextState.d.ts +15 -15
  72. package/dist/Interfaces/Context/IContextState.js +2 -2
  73. package/dist/Interfaces/Customer/ICustomerBadge.d.ts +2 -2
  74. package/dist/Interfaces/Customer/ICustomerBadge.js +2 -2
  75. package/dist/Interfaces/Customer/ICustomerRating.d.ts +10 -10
  76. package/dist/Interfaces/Customer/ICustomerRating.js +2 -2
  77. package/dist/Interfaces/Customer/IStoreCredit.d.ts +13 -13
  78. package/dist/Interfaces/Customer/IStoreCredit.js +2 -2
  79. package/dist/Interfaces/Customer/index.d.ts +104 -104
  80. package/dist/Interfaces/Customer/index.js +148 -148
  81. package/dist/Interfaces/Declination/index.d.ts +133 -117
  82. package/dist/Interfaces/Declination/index.js +83 -66
  83. package/dist/Interfaces/Declination/index.js.map +1 -1
  84. package/dist/Interfaces/Document/index.d.ts +8 -8
  85. package/dist/Interfaces/Document/index.js +2 -2
  86. package/dist/Interfaces/Elastic/index.d.ts +89 -89
  87. package/dist/Interfaces/Elastic/index.js +2 -2
  88. package/dist/Interfaces/Email/CustomGR/I3DPrintEmail.d.ts +11 -11
  89. package/dist/Interfaces/Email/CustomGR/I3DPrintEmail.js +2 -2
  90. package/dist/Interfaces/Email/CustomGR/IBorrowToolsEmail.d.ts +15 -15
  91. package/dist/Interfaces/Email/CustomGR/IBorrowToolsEmail.js +2 -2
  92. package/dist/Interfaces/Email/CustomGR/IPickupMaterialsEmail.d.ts +12 -12
  93. package/dist/Interfaces/Email/CustomGR/IPickupMaterialsEmail.js +2 -2
  94. package/dist/Interfaces/Email/CustomGR/IPreMeetingFormEmail.d.ts +36 -36
  95. package/dist/Interfaces/Email/CustomGR/IPreMeetingFormEmail.js +2 -2
  96. package/dist/Interfaces/Email/CustomGR/ISponsorRequestEmail.d.ts +12 -12
  97. package/dist/Interfaces/Email/CustomGR/ISponsorRequestEmail.js +2 -2
  98. package/dist/Interfaces/Email/CustomGR/ITransportEmail.d.ts +12 -12
  99. package/dist/Interfaces/Email/CustomGR/ITransportEmail.js +2 -2
  100. package/dist/Interfaces/Email/CustomGR/ITransportQuoteEmail.d.ts +12 -12
  101. package/dist/Interfaces/Email/CustomGR/ITransportQuoteEmail.js +2 -2
  102. package/dist/Interfaces/Email/CustomGR/IVegetalsEmail.d.ts +16 -16
  103. package/dist/Interfaces/Email/CustomGR/IVegetalsEmail.js +2 -2
  104. package/dist/Interfaces/Email/CustomGR/IWishlistEmail.d.ts +15 -15
  105. package/dist/Interfaces/Email/CustomGR/IWishlistEmail.js +2 -2
  106. package/dist/Interfaces/Email/IAbandonnedCartEmail.d.ts +29 -29
  107. package/dist/Interfaces/Email/IAbandonnedCartEmail.js +2 -2
  108. package/dist/Interfaces/Email/IAccountConfirmationEmail.d.ts +22 -22
  109. package/dist/Interfaces/Email/IAccountConfirmationEmail.js +2 -2
  110. package/dist/Interfaces/Email/IApplicationEmail.d.ts +19 -19
  111. package/dist/Interfaces/Email/IApplicationEmail.js +2 -2
  112. package/dist/Interfaces/Email/IBackInStockEmail.d.ts +21 -21
  113. package/dist/Interfaces/Email/IBackInStockEmail.js +2 -2
  114. package/dist/Interfaces/Email/IContactEmail.d.ts +20 -20
  115. package/dist/Interfaces/Email/IContactEmail.js +2 -2
  116. package/dist/Interfaces/Email/ICustomerBookingAdminEmail.d.ts +15 -15
  117. package/dist/Interfaces/Email/ICustomerBookingAdminEmail.js +2 -2
  118. package/dist/Interfaces/Email/ICustomerBookingEmail.d.ts +14 -14
  119. package/dist/Interfaces/Email/ICustomerBookingEmail.js +2 -2
  120. package/dist/Interfaces/Email/IEmail.d.ts +20 -20
  121. package/dist/Interfaces/Email/IEmail.js +46 -46
  122. package/dist/Interfaces/Email/IOrderConfirmationEmail.d.ts +47 -47
  123. package/dist/Interfaces/Email/IOrderConfirmationEmail.js +2 -2
  124. package/dist/Interfaces/Email/IPasswordResetEmail.d.ts +17 -17
  125. package/dist/Interfaces/Email/IPasswordResetEmail.js +2 -2
  126. package/dist/Interfaces/Email/IPhotoShootEmail.d.ts +14 -14
  127. package/dist/Interfaces/Email/IPhotoShootEmail.js +2 -2
  128. package/dist/Interfaces/Email/IPickupConfirmation.d.ts +23 -23
  129. package/dist/Interfaces/Email/IPickupConfirmation.js +2 -2
  130. package/dist/Interfaces/Email/IShippingConfirmation.d.ts +23 -23
  131. package/dist/Interfaces/Email/IShippingConfirmation.js +2 -2
  132. package/dist/Interfaces/Email/IWelcomeEmail.d.ts +19 -19
  133. package/dist/Interfaces/Email/IWelcomeEmail.js +2 -2
  134. package/dist/Interfaces/ExportSchema/index.d.ts +7 -7
  135. package/dist/Interfaces/ExportSchema/index.js +2 -2
  136. package/dist/Interfaces/ExternalService/BaseExternalService.d.ts +12 -12
  137. package/dist/Interfaces/ExternalService/BaseExternalService.js +2 -2
  138. package/dist/Interfaces/ExternalService/ExternalProductsService.d.ts +4 -4
  139. package/dist/Interfaces/ExternalService/ExternalProductsService.js +2 -2
  140. package/dist/Interfaces/ExternalService/index.d.ts +9 -9
  141. package/dist/Interfaces/ExternalService/index.js +2 -2
  142. package/dist/Interfaces/FirstOrderTracking/index.d.ts +5 -5
  143. package/dist/Interfaces/FirstOrderTracking/index.js +2 -2
  144. package/dist/Interfaces/G2/index.d.ts +557 -557
  145. package/dist/Interfaces/G2/index.js +39 -39
  146. package/dist/Interfaces/Indexed/Product/IIndexedLastSavedProduct.d.ts +20 -20
  147. package/dist/Interfaces/Indexed/Product/IIndexedLastSavedProduct.js +2 -2
  148. package/dist/Interfaces/Indexed/Product/index.d.ts +126 -111
  149. package/dist/Interfaces/Indexed/Product/index.js +372 -302
  150. package/dist/Interfaces/Indexed/Product/index.js.map +1 -1
  151. package/dist/Interfaces/Inventory/index.d.ts +19 -19
  152. package/dist/Interfaces/Inventory/index.js +8 -8
  153. package/dist/Interfaces/Invoice/index.d.ts +4 -4
  154. package/dist/Interfaces/Invoice/index.js +2 -2
  155. package/dist/Interfaces/MarketplacePublication/MarketplaceOrderData.d.ts +3 -3
  156. package/dist/Interfaces/MarketplacePublication/MarketplaceOrderData.js +2 -2
  157. package/dist/Interfaces/MarketplacePublication/index.d.ts +23 -23
  158. package/dist/Interfaces/MarketplacePublication/index.js +22 -22
  159. package/dist/Interfaces/Menu/index.d.ts +40 -40
  160. package/dist/Interfaces/Menu/index.js +16 -16
  161. package/dist/Interfaces/Note/index.d.ts +10 -10
  162. package/dist/Interfaces/Note/index.js +7 -7
  163. package/dist/Interfaces/Operations/ICreatedBy.d.ts +6 -6
  164. package/dist/Interfaces/Operations/ICreatedBy.js +2 -2
  165. package/dist/Interfaces/Operations/IUpdate.d.ts +5 -5
  166. package/dist/Interfaces/Operations/IUpdate.js +2 -2
  167. package/dist/Interfaces/Order/index.d.ts +4 -4
  168. package/dist/Interfaces/Order/index.js +2 -2
  169. package/dist/Interfaces/Org/IRelUser.d.ts +9 -9
  170. package/dist/Interfaces/Org/IRelUser.js +2 -2
  171. package/dist/Interfaces/Org/index.d.ts +29 -29
  172. package/dist/Interfaces/Org/index.js +12 -12
  173. package/dist/Interfaces/Payment/index.d.ts +26 -26
  174. package/dist/Interfaces/Payment/index.js +14 -14
  175. package/dist/Interfaces/Product/IAttributeFamily.d.ts +6 -6
  176. package/dist/Interfaces/Product/IAttributeFamily.js +2 -2
  177. package/dist/Interfaces/Product/IImportProduct.d.ts +42 -42
  178. package/dist/Interfaces/Product/IImportProduct.js +882 -882
  179. package/dist/Interfaces/Product/IInventoryItem.d.ts +74 -74
  180. package/dist/Interfaces/Product/IInventoryItem.js +38 -38
  181. package/dist/Interfaces/Product/IPricing.d.ts +177 -177
  182. package/dist/Interfaces/Product/IPricing.js +180 -180
  183. package/dist/Interfaces/Product/index.d.ts +137 -137
  184. package/dist/Interfaces/Product/index.js +64 -64
  185. package/dist/Interfaces/ProductAttribute/index.d.ts +11 -11
  186. package/dist/Interfaces/ProductAttribute/index.js +2 -2
  187. package/dist/Interfaces/PromiseToPurchase/BankType.d.ts +41 -41
  188. package/dist/Interfaces/PromiseToPurchase/BankType.js +41 -41
  189. package/dist/Interfaces/PromiseToPurchase/IIndexedBankUsed.d.ts +33 -33
  190. package/dist/Interfaces/PromiseToPurchase/IIndexedBankUsed.js +15 -15
  191. package/dist/Interfaces/PromiseToPurchase/IIndexedCustomerPromiseToPurchase.d.ts +19 -19
  192. package/dist/Interfaces/PromiseToPurchase/IIndexedCustomerPromiseToPurchase.js +2 -2
  193. package/dist/Interfaces/PromiseToPurchase/index.d.ts +50 -50
  194. package/dist/Interfaces/PromiseToPurchase/index.js +13 -13
  195. package/dist/Interfaces/PurchaseOrder/index.d.ts +17 -17
  196. package/dist/Interfaces/PurchaseOrder/index.js +2 -2
  197. package/dist/Interfaces/Query/IBrandQueryOptions.d.ts +11 -11
  198. package/dist/Interfaces/Query/IBrandQueryOptions.js +2 -2
  199. package/dist/Interfaces/Query/ICategoryQueryOptions.d.ts +11 -11
  200. package/dist/Interfaces/Query/ICategoryQueryOptions.js +2 -2
  201. package/dist/Interfaces/Query/IProductQueryOptions.d.ts +16 -16
  202. package/dist/Interfaces/Query/IProductQueryOptions.js +2 -2
  203. package/dist/Interfaces/Quote/index.d.ts +5 -5
  204. package/dist/Interfaces/Quote/index.js +2 -2
  205. package/dist/Interfaces/Refunds/index.d.ts +106 -106
  206. package/dist/Interfaces/Refunds/index.js +2 -2
  207. package/dist/Interfaces/Rules/IDiscountRule.d.ts +156 -156
  208. package/dist/Interfaces/Rules/IDiscountRule.js +114 -114
  209. package/dist/Interfaces/Schedule/index.d.ts +48 -48
  210. package/dist/Interfaces/Schedule/index.js +2 -2
  211. package/dist/Interfaces/Services/IAddServiceResponse.d.ts +4 -4
  212. package/dist/Interfaces/Services/IAddServiceResponse.js +2 -2
  213. package/dist/Interfaces/Services/IService.d.ts +16 -16
  214. package/dist/Interfaces/Services/IService.js +2 -2
  215. package/dist/Interfaces/Services/IServiceSecret.d.ts +8 -8
  216. package/dist/Interfaces/Services/IServiceSecret.js +2 -2
  217. package/dist/Interfaces/Shipping/Shipstation/carriers.d.ts +10 -10
  218. package/dist/Interfaces/Shipping/Shipstation/carriers.js +2 -2
  219. package/dist/Interfaces/Shipping/Shipstation/order.d.ts +227 -227
  220. package/dist/Interfaces/Shipping/Shipstation/order.js +2 -2
  221. package/dist/Interfaces/Shipping/Shipstation/quote.d.ts +31 -31
  222. package/dist/Interfaces/Shipping/Shipstation/quote.js +2 -2
  223. package/dist/Interfaces/Shipping/Shiptime/order.d.ts +54 -54
  224. package/dist/Interfaces/Shipping/Shiptime/order.js +71 -71
  225. package/dist/Interfaces/Shipping/Shiptime/quote.d.ts +111 -111
  226. package/dist/Interfaces/Shipping/Shiptime/quote.js +2 -2
  227. package/dist/Interfaces/Slider/GR.d.ts +114 -114
  228. package/dist/Interfaces/Slider/GR.js +271 -271
  229. package/dist/Interfaces/Slider/index.d.ts +30 -30
  230. package/dist/Interfaces/Slider/index.js +2 -2
  231. package/dist/Interfaces/Space/IExternalService.d.ts +54 -54
  232. package/dist/Interfaces/Space/IExternalService.js +45 -45
  233. package/dist/Interfaces/Space/IMember.d.ts +16 -16
  234. package/dist/Interfaces/Space/IMember.js +9 -9
  235. package/dist/Interfaces/Space/index.d.ts +414 -414
  236. package/dist/Interfaces/Space/index.js +176 -176
  237. package/dist/Interfaces/Specials/gr.d.ts +61 -61
  238. package/dist/Interfaces/Specials/gr.js +2 -2
  239. package/dist/Interfaces/StockNotification/index.d.ts +7 -7
  240. package/dist/Interfaces/StockNotification/index.js +2 -2
  241. package/dist/Interfaces/Store/index.d.ts +63 -63
  242. package/dist/Interfaces/Store/index.js +27 -27
  243. package/dist/Interfaces/Supplier/ICommand.d.ts +11 -11
  244. package/dist/Interfaces/Supplier/ICommand.js +2 -2
  245. package/dist/Interfaces/Supplier/index.d.ts +36 -36
  246. package/dist/Interfaces/Supplier/index.js +24 -24
  247. package/dist/Interfaces/TCG/index.d.ts +200 -200
  248. package/dist/Interfaces/TCG/index.js +59 -59
  249. package/dist/Interfaces/Tag/index.d.ts +18 -18
  250. package/dist/Interfaces/Tag/index.js +2 -2
  251. package/dist/Interfaces/Tax/index.d.ts +13 -13
  252. package/dist/Interfaces/Tax/index.js +2 -2
  253. package/dist/Interfaces/TransferRequest/index.d.ts +103 -103
  254. package/dist/Interfaces/TransferRequest/index.js +46 -46
  255. package/dist/Interfaces/Translation/index.d.ts +8 -8
  256. package/dist/Interfaces/Translation/index.js +5 -5
  257. package/dist/Interfaces/Update/index.d.ts +10 -10
  258. package/dist/Interfaces/Update/index.js +2 -2
  259. package/dist/Interfaces/User/IUser.d.ts +65 -65
  260. package/dist/Interfaces/User/IUser.js +8 -8
  261. package/dist/Interfaces/Version/index.d.ts +11 -11
  262. package/dist/Interfaces/Version/index.js +2 -2
  263. package/dist/Interfaces/Wishlist/index.d.ts +7 -7
  264. package/dist/Interfaces/Wishlist/index.js +2 -2
  265. package/dist/constants/Interfaces/IBaseApi.d.ts +15 -15
  266. package/dist/constants/Interfaces/IBaseApi.js +2 -2
  267. package/dist/constants/Interfaces/IEndpointResult.d.ts +9 -9
  268. package/dist/constants/Interfaces/IEndpointResult.js +2 -2
  269. package/dist/constants/enums.d.ts +6 -6
  270. package/dist/constants/enums.js +10 -10
  271. package/dist/constants/services.d.ts +2 -2
  272. package/dist/constants/services.js +122 -122
  273. package/dist/constants/version.d.ts +2 -2
  274. package/dist/constants/version.js +5 -5
  275. package/dist/index.d.ts +50 -50
  276. package/dist/index.js +266 -266
  277. package/dist/lib/Attribute/index.d.ts +14 -14
  278. package/dist/lib/Attribute/index.js +186 -186
  279. package/dist/lib/BGJob/index.d.ts +9 -9
  280. package/dist/lib/BGJob/index.js +216 -216
  281. package/dist/lib/BackgroundWorker/index.d.ts +34 -34
  282. package/dist/lib/BackgroundWorker/index.js +59 -59
  283. package/dist/lib/Blog/BlogArticle.d.ts +5 -5
  284. package/dist/lib/Blog/BlogArticle.js +10 -10
  285. package/dist/lib/Blog/BlogAuthor.d.ts +5 -5
  286. package/dist/lib/Blog/BlogAuthor.js +10 -10
  287. package/dist/lib/Blog/BlogCategory.d.ts +5 -5
  288. package/dist/lib/Blog/BlogCategory.js +10 -10
  289. package/dist/lib/Blog/BlogKeyword.d.ts +5 -5
  290. package/dist/lib/Blog/BlogKeyword.js +10 -10
  291. package/dist/lib/Booking/index.d.ts +85 -85
  292. package/dist/lib/Booking/index.js +596 -596
  293. package/dist/lib/Brand/index.d.ts +26 -26
  294. package/dist/lib/Brand/index.js +131 -131
  295. package/dist/lib/Cart/index.d.ts +357 -357
  296. package/dist/lib/Cart/index.js +4052 -4052
  297. package/dist/lib/CartReservedQuantities/index.d.ts +49 -49
  298. package/dist/lib/CartReservedQuantities/index.js +159 -159
  299. package/dist/lib/CashDrawerShift/index.d.ts +84 -84
  300. package/dist/lib/CashDrawerShift/index.js +206 -206
  301. package/dist/lib/Catalogue/index.d.ts +15 -15
  302. package/dist/lib/Catalogue/index.js +78 -78
  303. package/dist/lib/Category/index.d.ts +34 -34
  304. package/dist/lib/Category/index.js +230 -230
  305. package/dist/lib/Class/index.d.ts +16 -16
  306. package/dist/lib/Class/index.js +66 -66
  307. package/dist/lib/Consent/index.d.ts +4 -4
  308. package/dist/lib/Consent/index.js +29 -29
  309. package/dist/lib/Customer/index.d.ts +30 -30
  310. package/dist/lib/Customer/index.js +92 -92
  311. package/dist/lib/Declination/index.d.ts +9 -9
  312. package/dist/lib/Declination/index.js +26 -26
  313. package/dist/lib/Discount/index.d.ts +27 -27
  314. package/dist/lib/Discount/index.js +493 -493
  315. package/dist/lib/ElasticSearch/index.d.ts +13 -13
  316. package/dist/lib/ElasticSearch/index.js +50 -50
  317. package/dist/lib/Elavon/index.d.ts +18 -18
  318. package/dist/lib/Elavon/index.js +135 -135
  319. package/dist/lib/Email/AbandonedCartEmail.d.ts +16 -16
  320. package/dist/lib/Email/AbandonedCartEmail.js +24 -24
  321. package/dist/lib/Email/AccountConfirmationEmail.d.ts +19 -19
  322. package/dist/lib/Email/AccountConfirmationEmail.js +30 -30
  323. package/dist/lib/Email/AdminOrderConfirmationEmail.d.ts +16 -16
  324. package/dist/lib/Email/AdminOrderConfirmationEmail.js +24 -24
  325. package/dist/lib/Email/ApplicationEmail.d.ts +16 -16
  326. package/dist/lib/Email/ApplicationEmail.js +24 -24
  327. package/dist/lib/Email/BackInStockEmail.d.ts +16 -16
  328. package/dist/lib/Email/BackInStockEmail.js +24 -24
  329. package/dist/lib/Email/ContactEmail.d.ts +16 -16
  330. package/dist/lib/Email/ContactEmail.js +24 -24
  331. package/dist/lib/Email/CustomerBookingAdminEmail.d.ts +16 -16
  332. package/dist/lib/Email/CustomerBookingAdminEmail.js +24 -24
  333. package/dist/lib/Email/CustomerBookingEmail.d.ts +16 -16
  334. package/dist/lib/Email/CustomerBookingEmail.js +24 -24
  335. package/dist/lib/Email/OrderConfirmationEmail.d.ts +16 -16
  336. package/dist/lib/Email/OrderConfirmationEmail.js +24 -24
  337. package/dist/lib/Email/OrderDenounciationEmail.d.ts +16 -16
  338. package/dist/lib/Email/OrderDenounciationEmail.js +24 -24
  339. package/dist/lib/Email/OrderSampleEmail.d.ts +16 -16
  340. package/dist/lib/Email/OrderSampleEmail.js +24 -24
  341. package/dist/lib/Email/OtherTypeEmails.d.ts +16 -16
  342. package/dist/lib/Email/OtherTypeEmails.js +27 -27
  343. package/dist/lib/Email/PasswordResetEmail.d.ts +16 -16
  344. package/dist/lib/Email/PasswordResetEmail.js +24 -24
  345. package/dist/lib/Email/PhotoShootEmail.d.ts +16 -16
  346. package/dist/lib/Email/PhotoShootEmail.js +24 -24
  347. package/dist/lib/Email/PickUpConfirmation.d.ts +16 -16
  348. package/dist/lib/Email/PickUpConfirmation.js +24 -24
  349. package/dist/lib/Email/ShippingConfirmation.d.ts +16 -16
  350. package/dist/lib/Email/ShippingConfirmation.js +24 -24
  351. package/dist/lib/Email/WelcomeEmail.d.ts +16 -16
  352. package/dist/lib/Email/WelcomeEmail.js +24 -24
  353. package/dist/lib/Email/index.d.ts +16 -16
  354. package/dist/lib/Email/index.js +31 -31
  355. package/dist/lib/ExternalService/Ebay.d.ts +74 -74
  356. package/dist/lib/ExternalService/Ebay.js +124 -124
  357. package/dist/lib/ExternalService/index.d.ts +5 -5
  358. package/dist/lib/ExternalService/index.js +10 -10
  359. package/dist/lib/FirstOrderTracking/index.d.ts +5 -5
  360. package/dist/lib/FirstOrderTracking/index.js +10 -10
  361. package/dist/lib/Indexed/IndexedCart.d.ts +13 -13
  362. package/dist/lib/Indexed/IndexedCart.js +91 -91
  363. package/dist/lib/Indexed/Product.d.ts +17 -17
  364. package/dist/lib/Indexed/Product.js +98 -98
  365. package/dist/lib/Inventory/index.d.ts +131 -131
  366. package/dist/lib/Inventory/index.js +545 -545
  367. package/dist/lib/Invoice/index.d.ts +16 -16
  368. package/dist/lib/Invoice/index.js +21 -21
  369. package/dist/lib/MarketplacePublication/index.d.ts +9 -9
  370. package/dist/lib/MarketplacePublication/index.js +426 -426
  371. package/dist/lib/Menu/index.d.ts +11 -11
  372. package/dist/lib/Menu/index.js +107 -107
  373. package/dist/lib/MongoDB/BaseAPI.d.ts +18 -18
  374. package/dist/lib/MongoDB/BaseAPI.js +200 -200
  375. package/dist/lib/Note/index.d.ts +4 -4
  376. package/dist/lib/Note/index.js +6 -6
  377. package/dist/lib/Order/index.d.ts +27 -27
  378. package/dist/lib/Order/index.js +56 -56
  379. package/dist/lib/Org/index.d.ts +68 -68
  380. package/dist/lib/Org/index.js +216 -216
  381. package/dist/lib/PandaPay/index.d.ts +16 -16
  382. package/dist/lib/PandaPay/index.js +176 -176
  383. package/dist/lib/Paysafe/index.d.ts +11 -11
  384. package/dist/lib/Paysafe/index.js +41 -41
  385. package/dist/lib/Product/index.d.ts +182 -182
  386. package/dist/lib/Product/index.js +847 -847
  387. package/dist/lib/ProductAttribute/index.d.ts +15 -15
  388. package/dist/lib/ProductAttribute/index.js +45 -45
  389. package/dist/lib/PromiseToPurchase/index.d.ts +109 -109
  390. package/dist/lib/PromiseToPurchase/index.js +343 -343
  391. package/dist/lib/PurchaseOrder/index.d.ts +20 -20
  392. package/dist/lib/PurchaseOrder/index.js +28 -28
  393. package/dist/lib/Schedule/index.d.ts +5 -5
  394. package/dist/lib/Schedule/index.js +12 -12
  395. package/dist/lib/Service/Enum/ServiceEnum.d.ts +3 -3
  396. package/dist/lib/Service/Enum/ServiceEnum.js +7 -7
  397. package/dist/lib/Service/index.d.ts +13 -13
  398. package/dist/lib/Service/index.js +21 -21
  399. package/dist/lib/Shipment/index.d.ts +28 -28
  400. package/dist/lib/Shipment/index.js +370 -370
  401. package/dist/lib/Slider/index.d.ts +22 -22
  402. package/dist/lib/Slider/index.js +119 -119
  403. package/dist/lib/Space/index.d.ts +1181 -1181
  404. package/dist/lib/Space/index.js +5860 -5856
  405. package/dist/lib/Space/index.js.map +1 -1
  406. package/dist/lib/StockNotification/index.d.ts +4 -4
  407. package/dist/lib/StockNotification/index.js +6 -6
  408. package/dist/lib/Store/index.d.ts +5 -5
  409. package/dist/lib/Store/index.js +12 -12
  410. package/dist/lib/Supplier/Command.d.ts +5 -5
  411. package/dist/lib/Supplier/Command.js +10 -10
  412. package/dist/lib/Supplier/index.d.ts +25 -25
  413. package/dist/lib/Supplier/index.js +27 -27
  414. package/dist/lib/Tags/index.d.ts +6 -6
  415. package/dist/lib/Tags/index.js +26 -26
  416. package/dist/lib/Tax/index.d.ts +8 -8
  417. package/dist/lib/Tax/index.js +54 -54
  418. package/dist/lib/TransferRequest/index.d.ts +298 -298
  419. package/dist/lib/TransferRequest/index.js +1106 -1106
  420. package/dist/lib/Update/index.d.ts +10 -10
  421. package/dist/lib/Update/index.js +22 -22
  422. package/dist/lib/User/index.d.ts +89 -89
  423. package/dist/lib/User/index.js +328 -328
  424. package/dist/lib/Wishlist/index.d.ts +5 -5
  425. package/dist/lib/Wishlist/index.js +10 -10
  426. package/dist/lib/base.d.ts +14 -14
  427. package/dist/lib/base.js +62 -62
  428. package/dist/lib/baseService.d.ts +17 -17
  429. package/dist/lib/baseService.js +69 -69
  430. package/dist/rules/ADD/utils/buyback.d.ts +4 -4
  431. package/dist/rules/ADD/utils/buyback.js +135 -135
  432. package/dist/rules/GR/constants/data.d.ts +26 -26
  433. package/dist/rules/GR/constants/data.js +81 -81
  434. package/dist/rules/GR/constants/expedition.d.ts +4 -4
  435. package/dist/rules/GR/constants/expedition.js +9 -9
  436. package/dist/rules/GR/constants/products.d.ts +27 -22
  437. package/dist/rules/GR/constants/products.js +272 -263
  438. package/dist/rules/GR/constants/products.js.map +1 -1
  439. package/dist/rules/GR/interfaces/cart.d.ts +85 -84
  440. package/dist/rules/GR/interfaces/cart.js +42 -41
  441. package/dist/rules/GR/interfaces/cart.js.map +1 -1
  442. package/dist/rules/GR/interfaces/data.d.ts +101 -101
  443. package/dist/rules/GR/interfaces/data.js +114 -114
  444. package/dist/rules/GR/interfaces/products.d.ts +61 -61
  445. package/dist/rules/GR/interfaces/products.js +10 -10
  446. package/dist/rules/GR/utils/cart.d.ts +95 -95
  447. package/dist/rules/GR/utils/cart.js +879 -839
  448. package/dist/rules/GR/utils/cart.js.map +1 -1
  449. package/dist/rules/GR/utils/data.d.ts +3 -3
  450. package/dist/rules/GR/utils/data.js +28 -28
  451. package/dist/rules/GR/utils/expedition.d.ts +140 -140
  452. package/dist/rules/GR/utils/expedition.js +2098 -2017
  453. package/dist/rules/GR/utils/expedition.js.map +1 -1
  454. package/dist/rules/GR/utils/g2.d.ts +209 -209
  455. package/dist/rules/GR/utils/g2.js +1002 -1002
  456. package/dist/rules/GR/utils/invoices.d.ts +51 -51
  457. package/dist/rules/GR/utils/invoices.js +218 -215
  458. package/dist/rules/GR/utils/invoices.js.map +1 -1
  459. package/dist/rules/GR/utils/products.d.ts +277 -277
  460. package/dist/rules/GR/utils/products.js +1358 -1350
  461. package/dist/rules/GR/utils/products.js.map +1 -1
  462. package/dist/rules/GR/utils/upsells.d.ts +113 -111
  463. package/dist/rules/GR/utils/upsells.js +215 -215
  464. package/dist/services/database/BaseProvider.d.ts +29 -29
  465. package/dist/services/database/BaseProvider.js +28 -28
  466. package/dist/services/database/BatchUtils.d.ts +14 -14
  467. package/dist/services/database/BatchUtils.js +43 -43
  468. package/dist/services/database/Config.d.ts +2 -2
  469. package/dist/services/database/Config.js +5 -5
  470. package/dist/services/database/DatabaseService.d.ts +125 -125
  471. package/dist/services/database/DatabaseService.js +237 -237
  472. package/dist/services/database/FirebaseProvider.d.ts +17 -17
  473. package/dist/services/database/FirebaseProvider.js +235 -235
  474. package/dist/services/database/NotFirebaseProvider.d.ts +49 -49
  475. package/dist/services/database/NotFirebaseProvider.js +262 -262
  476. package/dist/services/g2/G2OrderSlip.d.ts +49 -49
  477. package/dist/services/g2/G2OrderSlip.js +228 -228
  478. package/dist/services/g2/utils.d.ts +19 -19
  479. package/dist/services/g2/utils.js +969 -968
  480. package/dist/services/g2/utils.js.map +1 -1
  481. package/dist/services/logs/index.d.ts +23 -23
  482. package/dist/services/logs/index.js +66 -66
  483. package/dist/services/marketplace/BaseMarketServiceClass.d.ts +78 -78
  484. package/dist/services/marketplace/BaseMarketServiceClass.js +141 -141
  485. package/dist/services/marketplace/CardtraderServiceClass.d.ts +38 -38
  486. package/dist/services/marketplace/CardtraderServiceClass.js +226 -226
  487. package/dist/services/marketplace/utils.d.ts +17 -17
  488. package/dist/services/marketplace/utils.js +32 -32
  489. package/dist/services/products/BaseClass.d.ts +79 -79
  490. package/dist/services/products/BaseClass.js +144 -144
  491. package/dist/services/products/TCGService.d.ts +29 -29
  492. package/dist/services/products/TCGService.js +503 -503
  493. package/dist/services/products/utils.d.ts +31 -31
  494. package/dist/services/products/utils.js +144 -144
  495. package/dist/utils/algolia.d.ts +46 -46
  496. package/dist/utils/algolia.js +21 -21
  497. package/dist/utils/anonymisation.d.ts +54 -54
  498. package/dist/utils/anonymisation.js +280 -280
  499. package/dist/utils/array.d.ts +5 -5
  500. package/dist/utils/array.js +14 -14
  501. package/dist/utils/aws.d.ts +36 -36
  502. package/dist/utils/aws.js +154 -154
  503. package/dist/utils/booking.d.ts +30 -30
  504. package/dist/utils/booking.js +127 -127
  505. package/dist/utils/cart.d.ts +279 -274
  506. package/dist/utils/cart.js +1152 -1143
  507. package/dist/utils/cart.js.map +1 -1
  508. package/dist/utils/categories.d.ts +2 -2
  509. package/dist/utils/categories.js +54 -54
  510. package/dist/utils/cmv.d.ts +12 -12
  511. package/dist/utils/cmv.js +108 -108
  512. package/dist/utils/console.d.ts +6 -6
  513. package/dist/utils/console.js +59 -59
  514. package/dist/utils/context.d.ts +20 -20
  515. package/dist/utils/context.js +61 -61
  516. package/dist/utils/currency.d.ts +6 -6
  517. package/dist/utils/currency.js +91 -91
  518. package/dist/utils/data.d.ts +31 -31
  519. package/dist/utils/data.js +302 -302
  520. package/dist/utils/date.d.ts +1 -1
  521. package/dist/utils/date.js +16 -16
  522. package/dist/utils/dimensions.d.ts +3 -3
  523. package/dist/utils/dimensions.js +16 -16
  524. package/dist/utils/discount.d.ts +192 -192
  525. package/dist/utils/discount.js +1180 -1180
  526. package/dist/utils/errors.d.ts +133 -133
  527. package/dist/utils/errors.js +171 -171
  528. package/dist/utils/file-admin.d.ts +8 -8
  529. package/dist/utils/file-admin.js +39 -39
  530. package/dist/utils/file.d.ts +39 -39
  531. package/dist/utils/file.js +208 -208
  532. package/dist/utils/firebase-admin.d.ts +11 -11
  533. package/dist/utils/firebase-admin.js +73 -73
  534. package/dist/utils/firebase.d.ts +58 -58
  535. package/dist/utils/firebase.js +148 -148
  536. package/dist/utils/import.d.ts +1 -1
  537. package/dist/utils/import.js +21 -21
  538. package/dist/utils/inventories.d.ts +101 -101
  539. package/dist/utils/inventories.js +467 -467
  540. package/dist/utils/locale.d.ts +24 -24
  541. package/dist/utils/locale.js +91 -91
  542. package/dist/utils/mailchimp.d.ts +58 -58
  543. package/dist/utils/mailchimp.js +531 -531
  544. package/dist/utils/mathUtils.d.ts +17 -17
  545. package/dist/utils/mathUtils.js +324 -324
  546. package/dist/utils/mongodb.d.ts +1 -1
  547. package/dist/utils/mongodb.js +22 -22
  548. package/dist/utils/object.d.ts +32 -32
  549. package/dist/utils/object.js +133 -133
  550. package/dist/utils/payment.d.ts +10 -10
  551. package/dist/utils/payment.js +23 -23
  552. package/dist/utils/products.d.ts +47 -47
  553. package/dist/utils/products.js +214 -214
  554. package/dist/utils/promiseToPurchase.d.ts +121 -121
  555. package/dist/utils/promiseToPurchase.js +329 -329
  556. package/dist/utils/prosprsearch.d.ts +42 -42
  557. package/dist/utils/prosprsearch.js +216 -216
  558. package/dist/utils/refunds.d.ts +2 -2
  559. package/dist/utils/refunds.js +21 -21
  560. package/dist/utils/sdc.d.ts +10 -10
  561. package/dist/utils/sdc.js +1309 -1309
  562. package/dist/utils/searchIndexes.d.ts +58 -58
  563. package/dist/utils/searchIndexes.js +247 -247
  564. package/dist/utils/services.d.ts +44 -44
  565. package/dist/utils/services.js +415 -415
  566. package/dist/utils/shipment.d.ts +110 -110
  567. package/dist/utils/shipment.js +341 -345
  568. package/dist/utils/shipment.js.map +1 -1
  569. package/dist/utils/simpletexting.d.ts +2 -2
  570. package/dist/utils/simpletexting.js +45 -45
  571. package/dist/utils/sliders.d.ts +4 -4
  572. package/dist/utils/sliders.js +24 -24
  573. package/dist/utils/string.d.ts +16 -16
  574. package/dist/utils/string.js +192 -192
  575. package/dist/utils/tcgService.d.ts +129 -129
  576. package/dist/utils/tcgService.js +494 -494
  577. package/dist/utils/tools.d.ts +5 -5
  578. package/dist/utils/tools.js +13 -13
  579. package/dist/utils/transferRequests.d.ts +43 -43
  580. package/dist/utils/transferRequests.js +67 -67
  581. package/dist/utils/update.d.ts +7 -7
  582. package/dist/utils/update.js +137 -137
  583. package/dist/utils/weight.d.ts +3 -3
  584. package/dist/utils/weight.js +16 -16
  585. package/dist/utils/zones.d.ts +11 -11
  586. package/dist/utils/zones.js +218 -218
  587. package/package.json +107 -107
  588. package/publish.sh +143 -143
  589. package/readme.md +182 -182
@@ -1,2018 +1,2099 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.checkIfNoDeliveryDateIsNormal = exports.checkIfCartExpired = exports.getStoresForVracProdShipping = exports.calculateShippingForVrac = exports.checkIfShouldRemoveSampleShippingFee = exports.applyFeesToCart = exports.installationFeePalletTier = exports.expeditionFeePalletTier = exports.checkForSameGrassDayFee = exports.checkIfShouldApplySameDayGrassFee = exports.getMinQteInstall = exports.getMinGrassQte = exports.calculatePalFeeForOtherThanGrass = exports.getPalletQtyPalletFee = exports.getGrassRoundedPickupPalletFees = exports.getPalletQty = exports.slugsToCheckFromExpeditionFees = exports.checkIfCartTypeHasBlockedDates = exports.dateIsClosedInSchedule = exports.shouldDisableDate = exports.getMinDateOffset = exports.getSamplesMinDateOffset = exports.getMinDatePicker = exports.getAvailableHours = exports.getDefaultTimeValues = void 0;
7
- const moment_1 = __importDefault(require("moment"));
8
- const ceil_1 = __importDefault(require("lodash/ceil"));
9
- const findIndex_1 = __importDefault(require("lodash/findIndex"));
10
- const floor_1 = __importDefault(require("lodash/floor"));
11
- const round_1 = __importDefault(require("lodash/round"));
12
- const sumBy_1 = __importDefault(require("lodash/sumBy"));
13
- const toNumber_1 = __importDefault(require("lodash/toNumber"));
14
- // Rule specific interfaces
15
- const products_1 = require("../interfaces/products");
16
- // Rule specific functions/constants
17
- const data_1 = require("./data");
18
- const products_2 = require("./products");
19
- const cart_1 = require("./cart");
20
- const g2_1 = require("./g2");
21
- const data_2 = require("../constants/data");
22
- const products_3 = require("../constants/products");
23
- // General interfaces
24
- const Cart_1 = require("../../../Interfaces/Cart");
25
- // General utils
26
- const data_3 = require("../../../utils/data");
27
- const products_4 = require("../../../utils/products");
28
- const cart_2 = require("../interfaces/cart");
29
- const data_4 = require("../interfaces/data");
30
- const object_1 = require("../../../utils/object");
31
- // ------------------------------------------------------------------------------------------
32
- // #region HOURS
33
- const getDefaultTimeValues = () => {
34
- let values = ['AM', 'PM'];
35
- return values.map((v) => ({ label: v, value: v }));
36
- };
37
- exports.getDefaultTimeValues = getDefaultTimeValues;
38
- const getAvailableHours = (minDeliveryDate, selectedDate, grassProduct, concreteOrder, expeditionMethod, selectedDeliveryTime, isPro, isSample, isAccessoriesOnly, testDate, keepHours) => {
39
- if (!!!minDeliveryDate)
40
- return { deliveryTimes: (0, exports.getDefaultTimeValues)() };
41
- let deliveryTimes = (0, exports.getDefaultTimeValues)().map((t) => t.value);
42
- const today = !!testDate
43
- ? !!keepHours
44
- ? (0, moment_1.default)(testDate).toDate()
45
- : (0, moment_1.default)(testDate).set('hours', (0, moment_1.default)().hours()).toDate()
46
- : (0, moment_1.default)().toDate();
47
- // If concreteOrder and product in stock and is pickup, can select 'now' (AM if before noon, PM if after)
48
- if (!!concreteOrder && !!concreteOrder.inStock && expeditionMethod === 'pickup') {
49
- const isPM = today.getHours() >= 12;
50
- if (!!isPM) {
51
- deliveryTimes = ['PM'];
52
- }
53
- return {
54
- deliveryTimes: deliveryTimes.map((t) => ({ label: t, value: t })),
55
- newSelectedDeliveryTime: !!isPM ? { label: 'PM', value: 'PM' } : undefined
56
- };
57
- }
58
- // ------------------------------------------------------------------------------------------------------
59
- // enable all hours in selection
60
- const resetHours = (d) => {
61
- d.setHours(0);
62
- d.setMinutes(0);
63
- d.setSeconds(0);
64
- d.setMilliseconds(0);
65
- };
66
- if (!!selectedDate)
67
- resetHours(selectedDate);
68
- resetHours(minDeliveryDate);
69
- let newSelectedDeliveryTime = undefined;
70
- const targetDateDay = minDeliveryDate.getDay();
71
- const selectedDateDay = !!selectedDate ? selectedDate.getDay() : targetDateDay;
72
- const isSelectedSameAsTarget = (0, moment_1.default)(minDeliveryDate).isSame(selectedDate) || !!!selectedDate;
73
- const todayDay = today.getDay();
74
- const isNonSpecialityGrass = !!grassProduct && (0, products_2.checkIfIsNonSpecialityGrass)(grassProduct.sku, grassProduct.slug);
75
- const onlyPm = () => {
76
- if (!!selectedDeliveryTime && selectedDeliveryTime === 'AM') {
77
- newSelectedDeliveryTime = { label: 'PM', value: 'PM' };
78
- }
79
- deliveryTimes = ['PM'];
80
- };
81
- // EDIT - Ajusted logic that excluded saturdays from time selection if not pro to make available if expeditionMethod = shipping [ 03-10-2022 ]
82
- if (selectedDateDay === 0 || (selectedDateDay === 6 && !!!isPro && expeditionMethod === 'pickup')) {
83
- deliveryTimes = [];
84
- newSelectedDeliveryTime = undefined;
85
- }
86
- else if (
87
- // Bug GR-I505 - AM / PM toujours disponnible pour Beton Vert en livraison
88
- // Bug GR-I511 - Pickup for concrete not in stock only change de available day
89
- !(!!concreteOrder && concreteOrder.type == 'green' && (!concreteOrder.inStock || expeditionMethod == 'delivery'))) {
90
- if (isSelectedSameAsTarget) {
91
- if (!!grassProduct || (!!concreteOrder && concreteOrder.type === 'green')) {
92
- let todayReset = !!testDate ? (0, moment_1.default)(testDate).toDate() : (0, moment_1.default)().toDate();
93
- resetHours(todayReset);
94
- // If today is either saturday of sunday
95
- if (!![6, 0].includes(todayReset.getDay())) {
96
- // Two options :
97
- // - is non-speciality grass OR [ concrete + type green + pickup + not in stock ] and target day is NOT a tuesday
98
- // - is any other kind of grass and target day is NOT a wednesday or thursday
99
- if ((![2].includes(targetDateDay) &&
100
- (!!isNonSpecialityGrass ||
101
- (!!concreteOrder && !concreteOrder.inStock && expeditionMethod === 'pickup'))) ||
102
- (![3, 4].includes(targetDateDay) && !!!isNonSpecialityGrass)) {
103
- // EDIT - Ajusted logic that excluded saturdays from time selection if not pro to make available if expeditionMethod = shipping [ 03-10-2022 ]
104
- if (targetDateDay === 6 && !!!isPro && expeditionMethod === 'pickup') {
105
- newSelectedDeliveryTime = undefined;
106
- deliveryTimes = [];
107
- }
108
- else {
109
- const amTimeToCheck = !!grassProduct && expeditionMethod == 'pickup' ? 12 : 10;
110
- // Logic ajusted on 08-05-2025 (task #GR-I377 in Sprint) - If grass & pickup, first check starts at noon. If not, at 10am.
111
- // Check if later than specific AM time
112
- if (today.getHours() >= amTimeToCheck) {
113
- onlyPm();
114
- }
115
- }
116
- }
117
- // If none of the above options are true, both time periods are available to the user
118
- }
119
- else {
120
- // Today is any other day than the weekend
121
- // Check if later than target hour
122
- // Logic updated on 08-05-2025, #GR-I377 in Sprint
123
- let targetHour = !!grassProduct && expeditionMethod == 'pickup' ? 12 : 10;
124
- // If grass or green concrete pickup, and today is Friday, AM stays available until after 16h
125
- // Logic updated on 17-02-2025, GR-I150 dans Zoho Sprint
126
- if (todayDay == 5 &&
127
- (!!grassProduct || (!!concreteOrder && concreteOrder.type == 'green' && expeditionMethod == 'pickup'))) {
128
- targetHour = 16;
129
- }
130
- if (today.getHours() >= targetHour) {
131
- onlyPm();
132
- }
133
- }
134
- }
135
- // If order contains samples or is of any other type than grass or concrete
136
- if ((!!!grassProduct && !!!concreteOrder) || !!isSample || !!isAccessoriesOnly) {
137
- // Check if later than 10 AM
138
- if (today.getHours() > 10) {
139
- onlyPm();
140
- }
141
- }
142
- }
143
- }
144
- return {
145
- deliveryTimes: deliveryTimes.map((t) => ({ label: t, value: t })),
146
- newSelectedDeliveryTime: newSelectedDeliveryTime ? newSelectedDeliveryTime : undefined
147
- };
148
- };
149
- exports.getAvailableHours = getAvailableHours;
150
- // Date de dégel (hardcodée, sera modifiée directement dans le code à la demande des clients)
151
- const isDegel = (dateToCheck) => {
152
- let date = !!dateToCheck ? (0, moment_1.default)(dateToCheck) : (0, moment_1.default)();
153
- return date.isBetween('2024-03-04 00:00:01', '2024-04-15 23:59:59', undefined, '[]');
154
- };
155
- /**
156
- * Function getMinDatePicker
157
- * @description Sets the minimum shipping day for delivery
158
- */
159
- const getMinDatePicker = (cartData, grassProduct, concreteOrder, expeditionMethod, isPro, testDate, blockedShippingDates, vracType, isPOS, spaceSchedule) => {
160
- const cartContainsInstallation = (0, cart_1.checkIfCartContainsType)(cart_2.CartGeneralTypeEnum.INSTALLATION, cartData);
161
- const cartContainsVrac = (0, cart_1.checkIfCartContainsType)(cart_2.CartGeneralTypeEnum.VRAC, cartData);
162
- const isAccessoriesOnly = (0, cart_1.checkIfCartContainsType)(cart_2.CartGeneralTypeEnum.ONLY_ACCESSORIES, cartData);
163
- let minDates = {};
164
- if (!!testDate && !isPOS) {
165
- testDate.setHours((0, moment_1.default)().hours());
166
- }
167
- let now = testDate || (0, moment_1.default)().toDate();
168
- let min_date = testDate || (0, moment_1.default)().toDate();
169
- // =======================================================================================
170
- // #region MIN DATE OFFSET
171
- const nbDaysOffset = (0, exports.getMinDateOffset)(now, cartContainsInstallation, cartContainsVrac, cartData, grassProduct, concreteOrder, isAccessoriesOnly, expeditionMethod, vracType);
172
- // #endregion
173
- // =======================================================================================
174
- // =======================================================================================
175
- // #region BLOCKED DAYS/DATES
176
- const typeToCheck = !!concreteOrder
177
- ? 'beton'
178
- : !!grassProduct
179
- ? 'gazon'
180
- : !!cartContainsVrac || (!!!isPro && !!vracType)
181
- ? 'vrac'
182
- : undefined;
183
- let dateToCheck = new Date(min_date);
184
- dateToCheck.setDate(min_date.getDate() + nbDaysOffset);
185
- let pickupDateSameAsNewDate = false;
186
- // ---------------------------------------------------------------------------------------
187
- // Check if space has blocked days
188
- // NEW!!! - For now, blocked days are hardcoded here. Will be moved to space eventually.
189
- const blockedDays = {
190
- vrac: [0],
191
- beton: [0],
192
- gazon: [0]
193
- };
194
- const getNextAvailableDay = (type) => {
195
- const dayToCheck = dateToCheck.getDay();
196
- if (!!blockedDays[type]) {
197
- // Right now we ignore blocked days on pickup because we check the schedules in the space. If days are added to the blockedDays dictionnary, validate that they still shouldn't apply on pickup
198
- if (blockedDays[type].includes(dayToCheck) && expeditionMethod !== 'pickup') {
199
- dateToCheck.setDate(dateToCheck.getDate() + 1);
200
- return getNextAvailableDay(type);
201
- }
202
- }
203
- if (!!spaceSchedule && expeditionMethod === 'pickup') {
204
- const storeId = (0, object_1.recursiveCheckObject)(cartData, 'shipping_payload.pickup_store.id');
205
- if (!!storeId && !!(0, exports.dateIsClosedInSchedule)(storeId, dateToCheck, spaceSchedule)) {
206
- dateToCheck.setDate(dateToCheck.getDate() + 1);
207
- return getNextAvailableDay(type);
208
- }
209
- }
210
- min_date = dateToCheck;
211
- min_date.setHours(0);
212
- min_date.setMinutes(0);
213
- min_date.setSeconds(0);
214
- };
215
- if (!!typeToCheck) {
216
- getNextAvailableDay(typeToCheck);
217
- if (typeToCheck === 'vrac') {
218
- pickupDateSameAsNewDate = true;
219
- }
220
- }
221
- // ---------------------------------------------------------------------------------------
222
- // Check if space has blocked dates
223
- if (!!blockedShippingDates && blockedShippingDates.length && !!typeToCheck && expeditionMethod === 'delivery') {
224
- const blockedDatesToCheck = blockedShippingDates.find((blockedDate) => blockedDate.cart_type === typeToCheck);
225
- if (!!blockedDatesToCheck && !!blockedDatesToCheck.dates && !!blockedDatesToCheck.dates.length) {
226
- const isInBlockedPeriod = blockedDatesToCheck.dates.find((blocked) => {
227
- return (!!blocked.start_date &&
228
- !!blocked.end_date &&
229
- (0, moment_1.default)(dateToCheck).isBetween((0, moment_1.default)((0, data_3.formatDate)(blocked.start_date)), (0, moment_1.default)((0, data_3.formatDate)(blocked.end_date)), 'date', '[]'));
230
- });
231
- if (!!isInBlockedPeriod) {
232
- dateToCheck = (0, moment_1.default)((0, data_3.formatDate)(isInBlockedPeriod.end_date)).add(1, 'days').toDate();
233
- getNextAvailableDay(typeToCheck);
234
- let pickup_date = !!pickupDateSameAsNewDate ? dateToCheck : (0, moment_1.default)(min_date).toDate();
235
- return {
236
- min_delivery: min_date,
237
- min_pickup: pickup_date
238
- };
239
- }
240
- }
241
- }
242
- // #endregion
243
- // =======================================================================================
244
- if (!!!concreteOrder || concreteOrder.type !== 'yellow') {
245
- min_date.setDate(dateToCheck.getDate());
246
- min_date.setHours(0);
247
- min_date.setMinutes(0);
248
- min_date.setSeconds(0);
249
- let pickup_date = (0, moment_1.default)(min_date).toDate();
250
- minDates = {
251
- min_delivery: min_date,
252
- min_pickup: pickup_date
253
- };
254
- }
255
- return minDates;
256
- };
257
- exports.getMinDatePicker = getMinDatePicker;
258
- const getSamplesMinDateOffset = () => {
259
- const now = new Date();
260
- const year = now.getFullYear();
261
- // December 1st
262
- const startWinterPeriod = new Date(year, 11, 1); // December == 11
263
- // March 1st
264
- const endWinterPeriod = new Date(year + 1, 2, 1); // March == 2
265
- const isWinterPeriod = (0, moment_1.default)().isBetween((0, moment_1.default)(startWinterPeriod), (0, moment_1.default)(endWinterPeriod), 'day', '[]');
266
- return isWinterPeriod ? 14 : 7;
267
- };
268
- exports.getSamplesMinDateOffset = getSamplesMinDateOffset;
269
- const getMinDateOffset = (now, cartContainsInstallation, cartContainsVrac, cartData, grassProduct, concreteOrder, isAccessoriesOnly, expeditionMethod, vracType) => {
270
- const current_hour = now.getHours();
271
- const current_day = now.getDay();
272
- let nb_days_offset = 1;
273
- // Variable to set all grass delays the same as non-speciality grasses (as of now, Kentucky and Prestige).
274
- // Use this instead of changing all values, in case our clients change their mind later!
275
- const allGrassDelaysSameAsNonSpecialityGrasses = true;
276
- // ========================
277
- // IF INSTALL
278
- // Install logic adjusted on 01-05-2024 (task #GR7-T429)
279
- if (!!cartContainsInstallation) {
280
- // --------------------
281
- // "Low staff" logic = 96hours delay for first available date
282
- // switch (current_day) {
283
- // case 3:
284
- // nb_days_offset = 5
285
- // break
286
- // default:
287
- // nb_days_offset = 4
288
- // break
289
- // }
290
- // --------------------
291
- // "Medium staff" logic = 48hours delay for first available date
292
- // CURRENT logic (active since 01-05-2024)
293
- switch (current_day) {
294
- case 5:
295
- nb_days_offset = 3;
296
- break;
297
- default:
298
- nb_days_offset = 2;
299
- break;
300
- }
301
- // --------------------
302
- // Regular logic (if fee applies for current year) = 24 hour delay for first available date
303
- // switch (current_day) {
304
- // case 5:
305
- // nb_days_offset = current_hour < 10 ? 1 : 3
306
- // break
307
- // case 6:
308
- // case 0:
309
- // nb_days_offset = 2
310
- // break
311
- // default:
312
- // nb_days_offset = 1
313
- // break
314
- // }
315
- }
316
- // ========================
317
- // IF SAMPLE OR ACCESSORIES ONLY
318
- else if (cartData.items.find((item) => item.is_sample) || !!isAccessoriesOnly) {
319
- if (expeditionMethod === 'delivery') {
320
- nb_days_offset = !!isAccessoriesOnly ? 7 : (0, exports.getSamplesMinDateOffset)();
321
- }
322
- else {
323
- switch (current_day) {
324
- case 4:
325
- nb_days_offset = 4;
326
- break;
327
- case 5:
328
- nb_days_offset = current_hour < 10 ? 3 : 4;
329
- break;
330
- case 6:
331
- nb_days_offset = 4;
332
- break;
333
- case 0:
334
- nb_days_offset = 3;
335
- break;
336
- default:
337
- nb_days_offset = 2;
338
- }
339
- }
340
- }
341
- // ========================
342
- // IF VRAC PRODUCTS WITH DELIVERY
343
- else if (expeditionMethod === 'delivery' &&
344
- !!cartContainsVrac &&
345
- !!(0, object_1.recursiveCheckObject)(vracType, 'vrac_type') &&
346
- [products_1.VracTypeEnum.AUTRE_TONNE, products_1.VracTypeEnum.NOBEL_TONNE].includes(vracType.vrac_type)) {
347
- nb_days_offset = 1;
348
- }
349
- // ========================
350
- // IF BASE GRASS / ALL GRASSES ARE SAME
351
- else if (!!grassProduct &&
352
- ((0, products_2.checkIfIsNonSpecialityGrass)(grassProduct.sku, grassProduct.slug) || !!allGrassDelaysSameAsNonSpecialityGrasses)) {
353
- const amTimeToCheck = !!grassProduct && expeditionMethod == 'pickup' ? 12 : 10;
354
- // Logic ajusted on 08-05-2025 (task #GR-I377 in Sprint) - If grass & pickup, first check starts at noon. If not, at 10am.
355
- switch (current_day) {
356
- case 5:
357
- nb_days_offset = current_hour < amTimeToCheck ? 1 : current_hour < 16 ? 3 : 3; // earliest is tomorrow if before 10AM, else after tomorrow, not counting the weekend (on fridays)
358
- // Logic ajusted on 14-02-2025 (task #GR-I151 in Sprint) - New check for between 10h (or 12h if grass&pickup) and 16h
359
- break;
360
- case 6:
361
- nb_days_offset = 3; // earliest is after tomorrow, not counting the weekend (on fridays or saturdays)
362
- break;
363
- case 0:
364
- nb_days_offset = 2; // earliest is after tomorrow, not counting the weekend (on sundays)
365
- break;
366
- default:
367
- nb_days_offset = 1; // earliest is tomorrow
368
- }
369
- }
370
- // ========================
371
- // IF CONCRETE WITH PICKUP | UNAVAILABLE PRODUCT
372
- else if (!!concreteOrder &&
373
- concreteOrder.type === 'green' &&
374
- !concreteOrder.inStock &&
375
- expeditionMethod === 'pickup') {
376
- // 13-08-2025 : Bug GR-I511 - Pickup for concrete not in stock only change the available day
377
- const amTimeToCheck = 10;
378
- switch (current_day) {
379
- case 0:
380
- nb_days_offset = 2;
381
- break;
382
- case 4:
383
- nb_days_offset = current_hour < amTimeToCheck ? 1 : 4;
384
- break;
385
- case 5:
386
- nb_days_offset = 3;
387
- break;
388
- case 6:
389
- nb_days_offset = current_hour < amTimeToCheck ? 2 : 3;
390
- break;
391
- default:
392
- nb_days_offset = current_hour < amTimeToCheck ? 1 : 2;
393
- }
394
- }
395
- // ========================
396
- // IF CONCRETE WITH PICKUP | ONLY AVAILABLE PRODUCTS
397
- else if (!!concreteOrder &&
398
- concreteOrder.type === 'green' &&
399
- concreteOrder.inStock &&
400
- expeditionMethod === 'pickup') {
401
- nb_days_offset = 0;
402
- }
403
- // ========================
404
- // IF SPECIALITY GRASS
405
- else if (!!grassProduct && !!!(0, products_2.checkIfIsNonSpecialityGrass)(grassProduct.sku, grassProduct.slug)) {
406
- switch (current_day) {
407
- case 5:
408
- case 6:
409
- case 0:
410
- nb_days_offset = 4; // if we are on friday and it's earlier than 10
411
- break;
412
- default:
413
- nb_days_offset = 2; // earliest is after tomorrow
414
- }
415
- }
416
- // ========================
417
- // IF CONCRETE WITH DELIVERY | ONLY AVAILABLE PRODUCTS
418
- else if (!!concreteOrder && concreteOrder.type === 'green' && expeditionMethod === 'delivery') {
419
- switch (current_day) {
420
- case 0:
421
- nb_days_offset = 3;
422
- break;
423
- case 1:
424
- case 2:
425
- case 3:
426
- nb_days_offset = current_hour < 10 ? 2 : 3;
427
- break;
428
- case 4:
429
- nb_days_offset = current_hour < 10 ? 2 : current_hour < 16 ? 4 : 5;
430
- // Logic ajusted on 14-02-2025 (task #GR-I151 in Sprint) - New check for between 10h and 16h
431
- break;
432
- case 5:
433
- nb_days_offset = current_hour < 16 ? 4 : 5;
434
- // Logic ajusted on 14-02-2025 (task #GR-I151 in Sprint) - New check for 16h instead of 10h
435
- break;
436
- case 6:
437
- nb_days_offset = 4;
438
- break;
439
- default:
440
- break;
441
- }
442
- }
443
- // ========================
444
- // IF ANY PRODUCT WITH DELIVERY THAT DID NOT FIT IN PREVIOUS CATEGORIES
445
- else if (expeditionMethod === 'delivery') {
446
- switch (current_day) {
447
- case 0:
448
- nb_days_offset = 4;
449
- break;
450
- case 1:
451
- case 2:
452
- nb_days_offset = current_hour < 10 ? 3 : 4;
453
- break;
454
- case 3:
455
- nb_days_offset = current_hour < 10 ? 3 : 6;
456
- break;
457
- case 4:
458
- case 5:
459
- nb_days_offset = current_hour < 10 ? 5 : 6;
460
- break;
461
- case 6:
462
- nb_days_offset = 5;
463
- break;
464
- default:
465
- break;
466
- }
467
- }
468
- return nb_days_offset;
469
- };
470
- exports.getMinDateOffset = getMinDateOffset;
471
- /**
472
- * Function shouldDisableDate
473
- * @description compares date with blockedDates from DB and blocked days (currently hardcoded in function)
474
- * @param date - Date to check
475
- * @param blockedDates - Blocked dates from DB
476
- * @param expeditionMethod - pickup or shipping
477
- * @param cartData
478
- */
479
- const shouldDisableDate = (date, blockedDates, expeditionMethod, cartData, schedule, selectedStore) => {
480
- if (!!!cartData)
481
- return false;
482
- const typeToCheck = (0, cart_1.getCartType)(cartData);
483
- // ---------------------------------------------------------------------------------------
484
- // Blocked days check
485
- // NEW!!! - For now, blocked days are hardcoded here. Will be moved to space eventually.
486
- const blockedDays = {
487
- vrac: [0],
488
- beton: [0],
489
- gazon: [0],
490
- only_accessories: [0],
491
- sample: [0]
492
- };
493
- if (!!!typeToCheck ||
494
- (!!blockedDays[typeToCheck] && !!blockedDays[typeToCheck].includes(date.getDay()) && expeditionMethod !== 'pickup')) {
495
- return true;
496
- }
497
- // ---------------------------------------------------------------------------------------
498
- // Blocked dates checks
499
- if (expeditionMethod !== 'pickup' && !!typeToCheck && !!blockedDates) {
500
- const sameType = blockedDates.find((blocked) => blocked.cart_type === typeToCheck);
501
- if (!!sameType && !!sameType.dates) {
502
- for (let dates of sameType.dates) {
503
- if (!!dates.start_date &&
504
- !!dates.end_date &&
505
- (0, moment_1.default)(date).isBetween((0, moment_1.default)((0, data_3.formatDate)(dates.start_date)), (0, moment_1.default)((0, data_3.formatDate)(dates.end_date)), 'date', '[]'))
506
- return true;
507
- }
508
- }
509
- }
510
- const storeId = (0, object_1.recursiveCheckObject)(cartData, 'shipping_payload.pickup_store.id');
511
- if ((!!storeId || !!selectedStore) && expeditionMethod === 'pickup' && !!schedule) {
512
- return !!(0, exports.dateIsClosedInSchedule)(!!selectedStore ? selectedStore : storeId, date, schedule);
513
- }
514
- return false;
515
- };
516
- exports.shouldDisableDate = shouldDisableDate;
517
- const dateIsClosedInSchedule = (storeId, dateToCheck, spaceSchedule) => {
518
- var _a;
519
- const weekdayIndex = dateToCheck.getDay();
520
- const storeSchedules = spaceSchedule.store_schedules[storeId];
521
- let isExternal = false;
522
- // If store schedule exists, check it, if not, set min date to dateToCheck.
523
- if (!!storeSchedules) {
524
- let selectedDaySchedule;
525
- // If periods are activated for the space, check the specific period schedule, if not check the general schedule
526
- if (!!spaceSchedule.space_periods_active) {
527
- const year = dateToCheck.getFullYear().toString();
528
- const periods = (_a = spaceSchedule.year_periods[year]) !== null && _a !== void 0 ? _a : [];
529
- const matchingPeriod = periods.find((p) => new Date(p.starts_at) <= dateToCheck && dateToCheck <= new Date(p.ends_at));
530
- if (!!matchingPeriod) {
531
- const periodSchedule = storeSchedules[matchingPeriod.id];
532
- if (!!periodSchedule) {
533
- if (!!periodSchedule.external) {
534
- isExternal = true;
535
- }
536
- const daySchedule = periodSchedule.weekly_schedule[weekdayIndex];
537
- if (!!daySchedule) {
538
- selectedDaySchedule = daySchedule;
539
- }
540
- }
541
- }
542
- }
543
- // If no schedule found for that day in active period, or periods aren't activated for that space, fall back to general schedule
544
- // A closed day should NOT enter this if
545
- // A period with an external schedule should NOT enter this if
546
- if (!!!isExternal &&
547
- (!!!selectedDaySchedule ||
548
- (!!selectedDaySchedule.schedule &&
549
- !!selectedDaySchedule.open &&
550
- !!!selectedDaySchedule.schedule.closing_time &&
551
- !!!selectedDaySchedule.schedule.opening_time))) {
552
- const generalSchedule = storeSchedules['general'];
553
- if (!!generalSchedule) {
554
- if (!!generalSchedule.external) {
555
- isExternal = true;
556
- }
557
- selectedDaySchedule = generalSchedule.weekly_schedule[weekdayIndex];
558
- }
559
- }
560
- // NEW - Returns true here even if isExternal
561
- if (!!selectedDaySchedule && selectedDaySchedule.open === false) {
562
- return true;
563
- }
564
- }
565
- let allClosedDays = spaceSchedule.common_closed_days;
566
- // If schedule for period is external, filter out all common dates since they do not apply
567
- if (!!isExternal)
568
- allClosedDays = allClosedDays.filter((d) => d.type != 'common');
569
- const isClosed = allClosedDays.some((c) => {
570
- const start = new Date(c.start_date);
571
- const end = c.end_date ? new Date(c.end_date) : start;
572
- start.setFullYear(dateToCheck.getFullYear());
573
- start.setHours(0, 0, 0, 0);
574
- end.setFullYear(dateToCheck.getFullYear());
575
- end.setHours(0, 0, 0, 0);
576
- dateToCheck.setHours(0, 0, 0, 0);
577
- return c.open === false && dateToCheck >= start && dateToCheck <= end && !!c.associated_stores.includes(storeId);
578
- });
579
- return isClosed;
580
- };
581
- exports.dateIsClosedInSchedule = dateIsClosedInSchedule;
582
- /**
583
- * Function checkIfCartTypeHasBlockedDates
584
- * @description checks if type of cart corresponds to a blockedDates array and if array has dates defined
585
- * @param cartData
586
- * @param blockedDates
587
- */
588
- const checkIfCartTypeHasBlockedDates = (cartData, blockedDates) => {
589
- if (!!!cartData || !!!blockedDates || !!!blockedDates.length)
590
- return false;
591
- const cartType = (0, cart_1.getCartType)(cartData);
592
- const sameType = blockedDates.find((blocked) => blocked.cart_type === cartType);
593
- if (!!!sameType)
594
- return false;
595
- return !!sameType.dates && !!sameType.dates.length;
596
- };
597
- exports.checkIfCartTypeHasBlockedDates = checkIfCartTypeHasBlockedDates;
598
- // #endregion
599
- // ------------------------------------------------------------------------------------------
600
- // ------------------------------------------------------------------------------------------
601
- // #region FEES
602
- exports.slugsToCheckFromExpeditionFees = {
603
- pickup: ['frais-preparation-general-beton', 'frais-palette', 'minimum-facturable-commande'],
604
- shipping: [
605
- 'livraison-echantillons',
606
- 'livraison-accessoires',
607
- 'livraison-beton-accessoires',
608
- 'livraison-gazon',
609
- 'frais-de-livraison-vrac',
610
- 'minimum-facturable-commande'
611
- ]
612
- };
613
- const getPalletQty = (items, orderType, minQteGrassOrder = 0) => {
614
- const total = (0, sumBy_1.default)(items.map((item) => {
615
- if (!!!item.other_units ||
616
- !!item.is_service ||
617
- !!item.is_sample ||
618
- (!!orderType &&
619
- !!['grass'].includes(orderType) &&
620
- (0, products_2.checkIfIsNonSpecialityGrass)(item.sku, item.parent_slug || '', true) &&
621
- !!item.is_upsell_of_sku)) {
622
- return 0;
623
- }
624
- const paletteUnit = item.other_units.find((u) => u.unit_slug === 'pal');
625
- const sellUnitCheck = item.other_units.find((u) => !!u.is_sale_unit);
626
- let sellUnit = 1;
627
- if (!!sellUnitCheck) {
628
- sellUnit = !!sellUnitCheck.fitting_unit ? sellUnitCheck.fitting_unit : 1;
629
- }
630
- if (!!!paletteUnit || !!!paletteUnit.fitting_unit) {
631
- return 0;
632
- }
633
- const typeAttr = item.attributes[data_4.AttributesIdEnumGR.TYPE];
634
- if (!!!typeAttr || !!!typeAttr.length) {
635
- return 0;
636
- }
637
- // If item is an accessory
638
- if (!!typeAttr && !typeAttr.includes('gazon') && !typeAttr.includes('beton')) {
639
- return (0, floor_1.default)((item.qte * sellUnit) / paletteUnit.fitting_unit);
640
- }
641
- // If is grass and minQteGrassOrder is defined
642
- if (!!typeAttr.includes('gazon') && !!minQteGrassOrder && item.qte < minQteGrassOrder) {
643
- return minQteGrassOrder / paletteUnit.fitting_unit;
644
- }
645
- return (item.qte * sellUnit) / paletteUnit.fitting_unit;
646
- }));
647
- if (orderType === 'concrete') {
648
- return (0, ceil_1.default)(total);
649
- }
650
- return total;
651
- };
652
- exports.getPalletQty = getPalletQty;
653
- // Retourne un nombre de frais de palettes à ajouter au panier selon la vraie quantité de palettes calculées pour les produits de gazon
654
- const getGrassRoundedPickupPalletFees = (realPalletNumber) => {
655
- // More than 400 square feet of grass needs another pallet
656
- const ratio = (0, round_1.default)(400 / 740, 3);
657
- // Get only the decimals from the real calculated pallet number, if the decimal is bigger than 400 / 740, round up
658
- const fraction = (0, round_1.default)(realPalletNumber % 1, 3);
659
- if (fraction >= ratio)
660
- return (0, ceil_1.default)(realPalletNumber);
661
- return (0, floor_1.default)(realPalletNumber);
662
- };
663
- exports.getGrassRoundedPickupPalletFees = getGrassRoundedPickupPalletFees;
664
- const getPalletQtyPalletFee = (items, expeditionMethod, isGrass, isMixed) => {
665
- let totalPalletGrass = 0;
666
- let totalPalletOther = 0;
667
- // For this fee specifically, remove all accessories before calculating palQty
668
- items = items.filter((i) => !(0, products_2.checkIfProductIsOfType)(i, 'accessoire'));
669
- if (!!isGrass) {
670
- const grassItemsToCheck = !!isMixed ? items.filter((i) => !!(0, products_2.checkIfProductIsOfType)(i, 'gazon', true)) : items;
671
- const calculatedPalletsGrass = (0, exports.getPalletQty)(grassItemsToCheck, 'grass');
672
- totalPalletGrass =
673
- expeditionMethod === 'pickup'
674
- ? (0, exports.getGrassRoundedPickupPalletFees)(calculatedPalletsGrass)
675
- : (0, ceil_1.default)(calculatedPalletsGrass);
676
- }
677
- if (!!!isGrass || !!isMixed) {
678
- const otherItemsToCheck = !!isMixed ? items.filter((i) => !!!(0, products_2.checkIfProductIsOfType)(i, 'gazon', true)) : items;
679
- totalPalletOther = (0, exports.calculatePalFeeForOtherThanGrass)(otherItemsToCheck);
680
- }
681
- const totalPallet = totalPalletGrass + totalPalletOther;
682
- return totalPallet;
683
- };
684
- exports.getPalletQtyPalletFee = getPalletQtyPalletFee;
685
- const calculatePalFeeForOtherThanGrass = (items) => {
686
- const total = (0, sumBy_1.default)(items.map((item) => {
687
- if (!!!item.other_units || !!item.is_service || !!item.is_sample) {
688
- return 0;
689
- }
690
- const exceptions = [
691
- 'muret-supra-citadin-180',
692
- 'muret-m-100-serie-moderne-double-face',
693
- 'muret-ora-double-face',
694
- 'pas-japonais-grand',
695
- 'marche-nueva',
696
- 'marche-aria',
697
- 'marche-t-200',
698
- 'marche-solino',
699
- 'marche-caralina',
700
- 'marche-rio-15',
701
- 'marche-appalaches',
702
- 'marche-citadin',
703
- 'marche-laurentien',
704
- 'marche-m-100-serie-moderne',
705
- 'marche-citadin-180',
706
- 'marche-ora',
707
- 'marche-t-100-serie-traditionnelle',
708
- 'marche-prestige-180'
709
- ];
710
- const itemIsException = item.parent_slug && exceptions.includes(item.parent_slug);
711
- const palUnit = item.other_units.find((u) => u.unit_slug === 'pal');
712
- const rgUnit = item.other_units.find((u) => u.unit_slug === 'rg');
713
- const unitUnit = item.other_units.find((u) => !!u.fitting_unit && u.fitting_unit === 1);
714
- const sellUnitCheck = item.other_units.find((u) => !!u.is_sale_unit);
715
- let sellUnit = 1;
716
- if (!!sellUnitCheck) {
717
- sellUnit = !!sellUnitCheck.fitting_unit ? sellUnitCheck.fitting_unit : 1;
718
- }
719
- const typeAttr = item.attributes[data_4.AttributesIdEnumGR.TYPE];
720
- // --------------------------------------------------
721
- // 1. If not all units are defined
722
- // if no palUnit or no typeAttr
723
- if (!!!palUnit || !!!palUnit.fitting_unit || !!!typeAttr || !!!typeAttr.length) {
724
- if (!!itemIsException)
725
- return 1;
726
- // if no rgUnit, can't calculate pallet amount
727
- if (!!!rgUnit || !!!rgUnit.fitting_unit) {
728
- return 0;
729
- }
730
- else {
731
- const nbRang = (item.qte * sellUnit) / rgUnit.fitting_unit;
732
- // if has quantities but rang amount is lower than 1, return 0
733
- if (nbRang > 0 && nbRang <= 1) {
734
- return 0;
735
- }
736
- else {
737
- return 1;
738
- }
739
- }
740
- }
741
- // --------------------------------------------------
742
- // 2. If is accessory
743
- if (!!typeAttr && !typeAttr.includes('gazon') && !typeAttr.includes('beton')) {
744
- return (0, floor_1.default)((item.qte * sellUnit) / palUnit.fitting_unit);
745
- }
746
- const palQty = (item.qte * sellUnit) / (palUnit.fitting_unit || 1);
747
- const rgQty = !!rgUnit ? (item.qte * sellUnit) / (rgUnit.fitting_unit || 1) : 0;
748
- const unitQty = !!unitUnit ? (item.qte * sellUnit) / (unitUnit.fitting_unit || 1) : !!sellUnit ? item.qte : 0;
749
- // --------------------------------------------------
750
- // 3. Calculate pal quantities
751
- // RULES:
752
- // - 1 pal = 1 pal
753
- // - 1 pal + 1 rang = 1 pal
754
- // - 1 pal + 2 rang = 2 pal
755
- // - 1 pal + 1 rang + 1 unité = 2 pals
756
- // - 1 pal + 1 unité = 1 pal
757
- // - 0 pal :
758
- // - If less than or equals 1 rang (or equivalent in units) = 0 pal (excluding exceptions)
759
- // - More thant 1 rang (or equivalent in units) = 1 pal
760
- let totalPal = (0, floor_1.default)(palQty);
761
- const unitsInRg = !!rgUnit ? rgUnit.fitting_unit || 0 : 0;
762
- const unitsInPal = palUnit.fitting_unit || 0;
763
- // if qte gives round number of pallets, return totalPal
764
- if (item.qte / unitsInPal === totalPal)
765
- return totalPal;
766
- // if rgQty and rgUnit are defined
767
- if (!!rgQty && !!rgUnit) {
768
- const rgInPal = (palUnit.fitting_unit || 1) / (rgUnit.fitting_unit || 1);
769
- // if palQty is higher than 1 and at least 2 rang extra
770
- if (palQty >= 1 && (0, ceil_1.default)(rgQty % rgInPal) >= 2) {
771
- totalPal += 1;
772
- }
773
- else {
774
- if (palQty < 1) {
775
- if (!!unitQty) {
776
- // if item is in exception list and at least 1 unit extra
777
- if (!!itemIsException && unitQty % unitsInPal !== 0) {
778
- totalPal += 1;
779
- }
780
- else if (!!unitsInRg && unitQty > unitsInRg && unitQty / unitsInRg > 1) {
781
- // if unit count does not equal rang count and total unit count is higher than rang count
782
- totalPal += 1;
783
- }
784
- }
785
- }
786
- }
787
- }
788
- else {
789
- if (!!unitQty && !!itemIsException) {
790
- if (unitQty % unitsInPal !== 0) {
791
- totalPal += 1;
792
- }
793
- }
794
- }
795
- return totalPal;
796
- }));
797
- return total;
798
- };
799
- exports.calculatePalFeeForOtherThanGrass = calculatePalFeeForOtherThanGrass;
800
- const getMinGrassQte = (_grassProduct, expeditionMethod, _isPro) => {
801
- let minQteGrassOrder = 0;
802
- // if (!![kentucky, prestige].includes(grassProduct.sku)) {
803
- // if (expeditionMethod !== 'pickup') {
804
- // minQteGrassOrder = !!isPro ? 1480 : 740
805
- // }
806
- // } else {
807
- // // Grass product is Speciality Grass
808
- // if (expeditionMethod === 'pickup') {
809
- // minQteGrassOrder = 740
810
- // } else {
811
- // minQteGrassOrder = !!isPro ? 1480 : 740
812
- // }
813
- // }
814
- // MODIF AVEC FRAIS 2024 - Même minimum facturable pour tous les gazons, et tous les clients
815
- // Toujours 0 pour la cueillette (pas de minimum), et 740 en livraison
816
- if (expeditionMethod != 'pickup') {
817
- minQteGrassOrder = 740; // 1 pallet
818
- }
819
- return minQteGrassOrder;
820
- };
821
- exports.getMinGrassQte = getMinGrassQte;
822
- const getMinQteInstall = (_isPro) => {
823
- // return !!isPro ? 2220 : 740
824
- // MODIF AVEC FRAIS 2024 - Même minimum facturable pour tous les clients pour l'installation
825
- return 740;
826
- };
827
- exports.getMinQteInstall = getMinQteInstall;
828
- const resetAllFeesIfAccessoriesOnly = (currentItems) => {
829
- const slugsToDelete = [
830
- 'livraison-gazon',
831
- 'minimum-facturable-commande',
832
- 'surcharge-jour-meme-gazon',
833
- 'livraison-beton-accessoires',
834
- 'frais-preparation-general-beton',
835
- 'frais-commande-beton-pas-en-ligne',
836
- 'frais-preparation',
837
- 'surcharges-installation-gazon',
838
- 'surcharges-commandes-gazon',
839
- 'surcharges-commandes-gazon-debut-fin-saison',
840
- 'surcharge-gazon-ramassage-hors-ferme',
841
- 'frais-commande-gazon-pas-en-ligne',
842
- ...products_3.fuelSurchargeSlugs
843
- ];
844
- let itemsToDelete = [];
845
- for (let i of currentItems) {
846
- if (!!i.parent_slug && !!slugsToDelete.includes(i.parent_slug))
847
- itemsToDelete.push(i.sku);
848
- }
849
- return itemsToDelete;
850
- };
851
- const checkIfShouldApplySameDayGrassFee = (firstDayForExpedition, expeditionMethod, selectedExpeditionDate, testDate // for unit test. To test holiday + hour after 4PM
852
- ) => {
853
- // a. Check min date for expedition type (for POS carts)
854
- const dateToCheck = expeditionMethod === 'pickup' ? firstDayForExpedition.min_pickup : firstDayForExpedition.min_delivery;
855
- const dateSelectedIsBeforeFirstCalculatedDay = !!dateToCheck && (0, moment_1.default)((0, data_3.formatDate)(selectedExpeditionDate)).isBefore((0, moment_1.default)(dateToCheck), 'date');
856
- // b. Check if current day is a holiday
857
- const isHoliday = (0, data_1.getHolidays)().some((h) => (0, moment_1.default)(h).isSame(testDate ? (0, moment_1.default)(testDate) : (0, moment_1.default)(), 'date'));
858
- // c. Check if current time is after 4PM
859
- const isAfter4PM = (!!testDate ? (0, moment_1.default)(testDate) : (0, moment_1.default)()).hour() >= 16;
860
- // d. Check if date selected is tomorrow
861
- const dateSelectedForExpeditionIsTomorrowOrToday = (0, moment_1.default)(selectedExpeditionDate).isSameOrBefore((0, moment_1.default)().add(1, 'day'), 'date');
862
- // If date selected is before first calculated date for expedition,
863
- // or order was created after 4PM/on a holiday and selected date for expedition is the next day,
864
- // apply fees
865
- return (!!dateSelectedIsBeforeFirstCalculatedDay ||
866
- ((!!isHoliday || !!isAfter4PM) && !!dateSelectedForExpeditionIsTomorrowOrToday));
867
- };
868
- exports.checkIfShouldApplySameDayGrassFee = checkIfShouldApplySameDayGrassFee;
869
- const checkForSameGrassDayFee = (isPOS, isPro, totalPallet, grassProduct, selectedExepeditionDate, isReserved) => {
870
- if (!!isReserved)
871
- return false;
872
- return !!selectedExepeditionDate && !!grassProduct && totalPallet >= 4 && (!!isPOS || !!isPro);
873
- };
874
- exports.checkForSameGrassDayFee = checkForSameGrassDayFee;
875
- // Correspond to the qte after which the expedition or installation fee should be reapplied
876
- // Eg. For each group of 24 pallets of a product, an expedition fee is added to the cart
877
- exports.expeditionFeePalletTier = 24;
878
- exports.installationFeePalletTier = 48;
879
- /**
880
- * Calculates fees that should be applied to provided cart, and fetches them from database or fee array if provided.
881
- * Returns the items to add, update and delete, as well as other cart info to set after fees.
882
- * ** Optimized version possible, where address zones and distance are calculated before and properties are sent directly to function
883
- * ** Optimized version reverted, logic found in commit here : [#2087b32]{@link https://github.com/ciaoqc/gng-tb-admin-sdk/commit/2087b3207df9e5916a979b8bb255abc2a4c1dac6}
884
- * @async
885
- * @param fetchProduct
886
- * @param getIfAddressIsInsideZones
887
- * @param getDistanceFromAddress
888
- * @param cart
889
- * @param expeditionMethod
890
- * @param grassProduct
891
- * @param concreteOrder
892
- * @param cartContainsInstallation
893
- * @param cartContainsVrac
894
- * @param availableVracStoreIDs
895
- * @param isPro
896
- * @param addOnePalletToPickup
897
- * @param cartContainsSample
898
- * @param saveToShippingPayload
899
- * @param deliveryAddress
900
- * @param locale
901
- * @param expeditionDate
902
- * @param equipmentPickupOnSite
903
- * @param cartContainsOnlyAccessories
904
- * @param pickupStore
905
- * @param allStores
906
- * @param customPriceList
907
- * @param useFeeArray
908
- */
909
- const applyFeesToCart = async (fetchProduct, getIfAddressIsInsideZones, getDistanceFromAddress, cart, expeditionMethod, grassProduct, concreteOrder, cartContainsInstallation, cartContainsVrac, availableVracStoreIDs, isPro, addOnePalletToPickup, cartContainsSample, saveToShippingPayload, deliveryAddress, locale, expeditionDate, equipmentPickupOnSite, cartContainsOnlyAccessories, pickupStore, allStores, customPriceList, useFeeArray) => {
910
- let itemsToAdd = [];
911
- let itemsToDelete = [];
912
- let itemsToUpdate = [];
913
- let newShippingPayload = cart.shipping_payload || {};
914
- // Pour le minimum facturable de la livraison
915
- let minQteGrassOrder = 0;
916
- if (!!grassProduct) {
917
- minQteGrassOrder = (0, exports.getMinGrassQte)(grassProduct, expeditionMethod, isPro);
918
- }
919
- // Vérification du type du cart
920
- const isPOS = [Cart_1.CartTypeEnum.POS, Cart_1.CartTypeEnum.POS_TRANSACTIONNAL].includes(cart.cart_type);
921
- const isMixed = cart.cart_content_type === Cart_1.CartContentTypeEnum.MIXED;
922
- let totalPalletOther = 0;
923
- let totalPalletGrass = 0;
924
- if (!!concreteOrder) {
925
- const concreteItemsToCheck = !!isMixed
926
- ? cart.items.filter((i) => !!!(0, products_2.checkIfProductIsOfType)(i, 'gazon', true))
927
- : cart.items;
928
- totalPalletOther = (0, exports.getPalletQty)(concreteItemsToCheck, 'concrete');
929
- }
930
- if (!!grassProduct) {
931
- const grassItemsToCheck = !!isMixed && !!concreteOrder ? cart.items.filter((i) => !!(0, products_2.checkIfProductIsOfType)(i, 'gazon', true)) : cart.items;
932
- totalPalletGrass = (0, exports.getPalletQty)(grassItemsToCheck, 'grass');
933
- }
934
- const totalPallet = totalPalletGrass + totalPalletOther;
935
- const totalPalletMinQte = (0, exports.getPalletQty)(cart.items, !!concreteOrder ? 'concrete' : !!grassProduct ? 'grass' : undefined, minQteGrassOrder);
936
- // Pour le minimum facturable de l'installation
937
- const minQteInstall = (0, exports.getMinQteInstall)(!!isPro);
938
- // Type de cart (en ligne, en magasin, avec un commis, etc...)
939
- const cartType = !!isPOS ? 'in_store' : !!cart.clerk_id ? 'with_clerk' : 'online';
940
- const installAllInclusiveActive = (0, products_2.isInstallAllInclusiveActive)(cartContainsInstallation, isPro, customPriceList);
941
- // --------------------------------------------------------------------------------------------------
942
- // #region FRAIS PALETTE
943
- // --------------------------------------------------------------------------------------------------
944
- const shouldAddPaletFees = !!!cartContainsInstallation && !!!cartContainsSample && !!!cartContainsVrac;
945
- if ((!!isMixed || !!shouldAddPaletFees) && (!!isPro || !!!grassProduct) && !!!cartContainsOnlyAccessories) {
946
- let qtyOfSkuNeeded = (0, exports.getPalletQtyPalletFee)(cart.items, expeditionMethod, !!(0, cart_1.checkIfCartContainsType)(cart_2.CartGeneralTypeEnum.GRASS, cart), isMixed);
947
- if (!!addOnePalletToPickup && expeditionMethod === 'pickup') {
948
- qtyOfSkuNeeded += 1;
949
- }
950
- if (!!addOnePalletToPickup && !!!useFeeArray && !!saveToShippingPayload) {
951
- newShippingPayload = Object.assign(Object.assign({}, newShippingPayload), { addOnePalletToPickup: true });
952
- }
953
- const productToAdd = await fetchProduct('frais-palette', locale, !!useFeeArray, true);
954
- if (!!productToAdd && !!productToAdd.declinations) {
955
- const palletFeeDecli = productToAdd.declinations[0];
956
- if (!!qtyOfSkuNeeded) {
957
- itemsToAdd.push(Object.assign(Object.assign({}, productToAdd.declinations[0]), { qte: qtyOfSkuNeeded, parent_slug: productToAdd.slug, is_upsell_of_sku: 'summary', categories: productToAdd.categories }));
958
- }
959
- else if (cart.items.some((i) => i.sku === palletFeeDecli.sku)) {
960
- itemsToDelete.push(palletFeeDecli.sku);
961
- }
962
- }
963
- }
964
- // #endregion FRAIS PALETTE
965
- // --------------------------------------------------------------------------------------------------
966
- // #region COMMANDE GAZON - FRAIS DE LIVRAISON
967
- // --------------------------------------------------------------------------------------------------
968
- if (!!grassProduct) {
969
- if (expeditionMethod === 'delivery') {
970
- const parentProduct = await fetchProduct('livraison-gazon', locale, !!useFeeArray, true);
971
- const product3 = parentProduct
972
- ? parentProduct.declinations.find((decli) => ['17000000T'].includes(decli.sku))
973
- : undefined;
974
- const product4_15 = parentProduct
975
- ? parentProduct.declinations.find((decli) => decli.sku === '170000000')
976
- : undefined;
977
- const product16 = parentProduct
978
- ? parentProduct.declinations.find((decli) => decli.sku === '170000160')
979
- : undefined;
980
- const add = (product, qty) => {
981
- if (!!product) {
982
- const alreadyToAdd = (0, findIndex_1.default)(itemsToAdd, (i) => i.sku === product.sku);
983
- if (alreadyToAdd === -1) {
984
- itemsToAdd.push(Object.assign(Object.assign({}, product), { is_upsell_of_sku: 'summary', qte: qty, parent_slug: 'livraison-gazon' }));
985
- }
986
- else {
987
- itemsToAdd[alreadyToAdd] = Object.assign(Object.assign(Object.assign({}, itemsToAdd[alreadyToAdd]), { is_upsell_of_sku: 'summary', qte: itemsToAdd[alreadyToAdd].qte + qty, parent_slug: 'livraison-gazon' }), (!!parentProduct ? { categories: parentProduct.categories } : {}));
988
- }
989
- }
990
- };
991
- const addRestQty = (pallets) => {
992
- if (pallets > 0 && pallets < 4) {
993
- add(product3, 1);
994
- }
995
- if (pallets >= 4 && pallets < 16) {
996
- add(product4_15, 1);
997
- }
998
- if (pallets >= 16) {
999
- add(product16, 1);
1000
- }
1001
- };
1002
- if (totalPalletMinQte <= exports.expeditionFeePalletTier) {
1003
- addRestQty(totalPalletMinQte);
1004
- }
1005
- else {
1006
- const qty4AndMore = (0, floor_1.default)(totalPalletMinQte / exports.expeditionFeePalletTier);
1007
- const rest = (0, ceil_1.default)(totalPalletMinQte % exports.expeditionFeePalletTier);
1008
- add(product16, qty4AndMore);
1009
- addRestQty(rest);
1010
- }
1011
- }
1012
- cart.items
1013
- .filter((i) => i.parent_slug === 'livraison-gazon')
1014
- .map((item) => {
1015
- if (!itemsToAdd.map((i) => i.sku).includes(item.sku) || expeditionMethod === 'pickup') {
1016
- itemsToDelete.push(item.sku);
1017
- }
1018
- return;
1019
- });
1020
- }
1021
- // #endregion COMMANDE GAZON - FRAIS DE LIVRAISON
1022
- // --------------------------------------------------------------------------------------------------
1023
- // #region COMMANDE BETON - FRAIS DE LIVRAISON
1024
- // --------------------------------------------------------------------------------------------------
1025
- if (!!!cartContainsVrac && !!!cartContainsSample && !!!grassProduct && !!!cartContainsOnlyAccessories) {
1026
- if (expeditionMethod === 'delivery') {
1027
- const parentProduct = await fetchProduct('livraison-beton-accessoires', locale, !!useFeeArray, true);
1028
- const product1To5 = parentProduct
1029
- ? parentProduct.declinations.find((decli) => decli.sku === '170060450')
1030
- : undefined;
1031
- const product6To11 = parentProduct
1032
- ? parentProduct.declinations.find((decli) => decli.sku === '170060650')
1033
- : undefined;
1034
- const product12AndMore = parentProduct
1035
- ? parentProduct.declinations.find((decli) => decli.sku === '170060000')
1036
- : undefined;
1037
- const add = (product, qty) => {
1038
- if (!!product) {
1039
- const alreadyToAdd = (0, findIndex_1.default)(itemsToAdd, (i) => i.sku === product.sku);
1040
- if (alreadyToAdd === -1) {
1041
- itemsToAdd.push(Object.assign(Object.assign({}, product), { is_upsell_of_sku: 'summary', parent_slug: 'livraison-beton-accessoires', qte: qty }));
1042
- }
1043
- else {
1044
- itemsToAdd[alreadyToAdd] = Object.assign(Object.assign(Object.assign({}, itemsToAdd[alreadyToAdd]), { is_upsell_of_sku: 'summary', qte: itemsToAdd[alreadyToAdd].qte + qty, parent_slug: 'livraison-beton-accessoires' }), (!!parentProduct ? { categories: parentProduct.categories } : {}));
1045
- }
1046
- }
1047
- };
1048
- const addRestQty = (pallets) => {
1049
- switch (true) {
1050
- case pallets > 0 && pallets <= 5:
1051
- add(product1To5, 1);
1052
- return;
1053
- case pallets > 5 && pallets < 12:
1054
- add(product6To11, 1);
1055
- return;
1056
- case pallets >= 12:
1057
- add(product12AndMore, 1);
1058
- return;
1059
- }
1060
- };
1061
- if (totalPalletOther <= exports.expeditionFeePalletTier) {
1062
- addRestQty(totalPalletOther);
1063
- }
1064
- else {
1065
- const qty4AndMore = (0, floor_1.default)(totalPalletMinQte / exports.expeditionFeePalletTier);
1066
- const rest = (0, ceil_1.default)(totalPalletOther) % exports.expeditionFeePalletTier;
1067
- add(product12AndMore, qty4AndMore);
1068
- addRestQty(rest);
1069
- }
1070
- }
1071
- cart.items
1072
- .filter((i) => i.parent_slug === 'livraison-beton-accessoires')
1073
- .map((item) => {
1074
- if (!itemsToAdd.map((i) => i.sku).includes(item.sku) || expeditionMethod === 'pickup') {
1075
- itemsToDelete.push(item.sku);
1076
- }
1077
- return;
1078
- });
1079
- }
1080
- // #endregion COMMANDE BETON - FRAIS DE LIVRAISON
1081
- // --------------------------------------------------------------------------------------------------
1082
- // #region COMMANDE GAZON - MINIMUM FACTURABLE
1083
- // --------------------------------------------------------------------------------------------------
1084
- if (!!grassProduct) {
1085
- // In this case, prestige is included in speciality grasses, since the fee must include kentucky price too
1086
- const isSpecialityGrass = !!grassProduct && !!!(0, products_2.checkIfIsNonSpecialityGrass)(grassProduct.sku, grassProduct.slug, true);
1087
- const qtyToAdd = minQteGrassOrder - grassProduct.qte;
1088
- if (qtyToAdd > 0) {
1089
- const product = await fetchProduct('minimum-facturable-commande', locale, !!useFeeArray, true);
1090
- if (!!product) {
1091
- const decli = product.declinations.find((d) => d.sku === '010010000-M');
1092
- if (!!decli) {
1093
- let price = grassProduct.price;
1094
- if (!!isSpecialityGrass) {
1095
- const isKentucky = cart.items.find((i) => (0, products_2.checkIfIsNonSpecialityGrass)(i.sku, i.parent_slug || '', true));
1096
- price = isKentucky ? price + (0, products_4.getLowestPrice)(isKentucky).price.amount : price;
1097
- }
1098
- let minGrassQteItem = Object.assign(Object.assign({}, decli), { regular_price: Object.assign(Object.assign({}, decli.regular_price), { amount: price }) });
1099
- if (!!isPro && !!customPriceList) {
1100
- minGrassQteItem = (0, g2_1.checkForCustomPriceEquivalent)(Object.assign(Object.assign({}, minGrassQteItem), { price_override: true }), customPriceList);
1101
- }
1102
- itemsToAdd.push(Object.assign(Object.assign({}, minGrassQteItem), { is_upsell_of_sku: 'summary', parent_slug: product.slug, price_override: true, qte: qtyToAdd, categories: product.categories }));
1103
- }
1104
- }
1105
- }
1106
- const minimumBillable = cart.items.find((i) => i.parent_slug === 'minimum-facturable-commande');
1107
- if (qtyToAdd <= 0 && !!minimumBillable) {
1108
- itemsToDelete.push(minimumBillable.sku);
1109
- }
1110
- }
1111
- // #endregion COMMANDE GAZON - MINIMUM FACTURABLE
1112
- // --------------------------------------------------------------------------------------------------
1113
- // #region COMMANDE GAZON - SURCHARGE JOUR MÊME
1114
- // --------------------------------------------------------------------------------------------------
1115
- const sameDayGrassFee = await fetchProduct('surcharge-jour-meme-gazon', locale, !!useFeeArray, true);
1116
- let decli;
1117
- if (!!sameDayGrassFee) {
1118
- decli = sameDayGrassFee.declinations.find((d) => d.sku === '000010990');
1119
- }
1120
- if (!!(0, exports.checkForSameGrassDayFee)(isPOS, isPro, totalPalletGrass, grassProduct, expeditionDate, (0, object_1.recursiveCheckObject)(cart.shipping_payload, 'is_reserved'))) {
1121
- // a. Fetch min date for expedition type (for POS carts)
1122
- const firstDayForExpedition = (0, exports.getMinDatePicker)(cart, grassProduct, undefined, expeditionMethod || 'delivery', !!isPro, !!cart.created_by ? (0, data_3.formatDate)(cart.created_by.date) : undefined, undefined, undefined, isPOS);
1123
- // b. Call function to get if fee should be applied
1124
- const shouldApplySameDayFee = (0, exports.checkIfShouldApplySameDayGrassFee)(firstDayForExpedition, expeditionMethod, expeditionDate);
1125
- if (!!sameDayGrassFee && !!decli) {
1126
- if (!!shouldApplySameDayFee) {
1127
- itemsToAdd.push(Object.assign(Object.assign({}, decli), { is_upsell_of_sku: 'summary', parent_slug: sameDayGrassFee.slug, price_override: true, qte: !!grassProduct ? grassProduct.qte : 1, categories: sameDayGrassFee.categories }));
1128
- }
1129
- }
1130
- }
1131
- if (!!sameDayGrassFee && !!decli) {
1132
- if (!!cart.items.some((i) => i.sku === decli.sku)) {
1133
- itemsToDelete.push(decli.sku);
1134
- }
1135
- }
1136
- // #endregion COMMANDE GAZON - SURCHARGE JOUR MÊME
1137
- // --------------------------------------------------------------------------------------------------
1138
- // #region LIVRAISON ÉCHANTILLONS
1139
- // --------------------------------------------------------------------------------------------------
1140
- if (!!cartContainsSample) {
1141
- let removeShippingFee = false;
1142
- if (expeditionMethod === 'delivery') {
1143
- let productToAdd = await fetchProduct('livraison-echantillons', locale, !!useFeeArray, true);
1144
- try {
1145
- removeShippingFee = await (0, exports.checkIfShouldRemoveSampleShippingFee)(fetchProduct, cart, locale, !!useFeeArray);
1146
- }
1147
- catch (e) {
1148
- console.log('error on checking if should remove sample shipping fee: ', e.toString());
1149
- }
1150
- if (!!removeShippingFee) {
1151
- productToAdd = undefined;
1152
- }
1153
- if (!!productToAdd && !!productToAdd.declinations) {
1154
- itemsToAdd.push(Object.assign(Object.assign({}, productToAdd.declinations[0]), { qte: 1, is_upsell_of_sku: 'summary', parent_slug: productToAdd.slug, categories: productToAdd.categories }));
1155
- }
1156
- }
1157
- const sampleDeliveryFee = cart.items.find((i) => i.parent_slug === 'livraison-echantillons');
1158
- if ((expeditionMethod === 'pickup' || !!removeShippingFee) && !!sampleDeliveryFee) {
1159
- itemsToDelete.push(sampleDeliveryFee.sku);
1160
- }
1161
- }
1162
- // #endregion LIVRAISON ÉCHANTILLONS
1163
- // --------------------------------------------------------------------------------------------------
1164
- // #region LIVRAISON ACCESSOIRES
1165
- // --------------------------------------------------------------------------------------------------
1166
- const cartAccessoriesDeliveryFee = cart.items.find((i) => i.parent_slug === 'livraison-accessoires');
1167
- if (!!cartContainsOnlyAccessories) {
1168
- // reset all service fees associated to grass or beton carts, if found
1169
- itemsToDelete = resetAllFeesIfAccessoriesOnly(cart.items);
1170
- // check to add delivery fee
1171
- if (expeditionMethod === 'delivery') {
1172
- const productToAdd = await fetchProduct('livraison-accessoires', locale, !!useFeeArray, true);
1173
- if (!!productToAdd && !!productToAdd.declinations) {
1174
- itemsToAdd.push(Object.assign(Object.assign({}, productToAdd.declinations[0]), { qte: 1, is_upsell_of_sku: 'summary', parent_slug: productToAdd.slug, categories: productToAdd.categories }));
1175
- }
1176
- }
1177
- if (expeditionMethod === 'pickup' && !!cartAccessoriesDeliveryFee) {
1178
- itemsToDelete.push(cartAccessoriesDeliveryFee.sku);
1179
- }
1180
- }
1181
- else {
1182
- if (!!cartAccessoriesDeliveryFee) {
1183
- itemsToDelete.push(cartAccessoriesDeliveryFee.sku);
1184
- }
1185
- }
1186
- // #endregion LIVRAISON ACCESSOIRES
1187
- // --------------------------------------------------------------------------------------------------
1188
- // #region COMMANDE GAZON - SURCHARGE DE PRIX DE GAZON
1189
- // --------------------------------------------------------------------------------------------------
1190
- // Les surcharges sur le gazon s'appliquent toujours pour les pros, ou juste dans le cas de commandes d'une palette ou plus pour les clients au détail
1191
- const shouldApplyFees = !!isPro || totalPalletGrass >= 1;
1192
- if (!!grassProduct) {
1193
- const feesToAdd = [];
1194
- let orderDate = expeditionDate;
1195
- let pickupStoreId = '';
1196
- if (!!pickupStore && !!pickupStore.id) {
1197
- pickupStoreId = pickupStore.id;
1198
- }
1199
- else {
1200
- const shipping_address = cart.shipping_address;
1201
- if (!!shipping_address) {
1202
- const pickupStore = allStores.find((store) => store.address.postal_code === shipping_address.address.postal_code);
1203
- if (!!pickupStore && !!pickupStore.id) {
1204
- pickupStoreId = pickupStore.id;
1205
- }
1206
- }
1207
- }
1208
- let surchargesCommandesGazon = undefined;
1209
- let surchargesCommandesGazonDebutFinSaison = undefined;
1210
- let surchargesInstallationGazon = undefined;
1211
- let surchargesInstallationGazonDebutFinSaison = undefined;
1212
- let surchargesGazonPickupHorsFerme = undefined;
1213
- let fraisSiCommandePasEnLigne = undefined;
1214
- try {
1215
- surchargesCommandesGazon = await fetchProduct('surcharges-commandes-gazon', locale, !!useFeeArray, true);
1216
- }
1217
- catch (e) {
1218
- console.log('error on fetching product: ', e.toString());
1219
- }
1220
- try {
1221
- surchargesCommandesGazonDebutFinSaison = await fetchProduct('surcharges-commandes-gazon-debut-fin-saison', locale, !!useFeeArray, true);
1222
- }
1223
- catch (e) {
1224
- console.log('error on fetching product: ', e.toString());
1225
- }
1226
- try {
1227
- surchargesInstallationGazon = await fetchProduct('surcharges-installation-gazon', locale, !!useFeeArray, true);
1228
- }
1229
- catch (e) {
1230
- console.log('error on fetching product: ', e.toString());
1231
- }
1232
- try {
1233
- surchargesInstallationGazonDebutFinSaison = await fetchProduct('surcharges-installation-gazon-debut-fin-saison', locale, useFeeArray, true);
1234
- }
1235
- catch (e) {
1236
- console.log('error on fetching product: ', e.toString());
1237
- }
1238
- try {
1239
- surchargesGazonPickupHorsFerme = await fetchProduct('surcharge-gazon-ramassage-hors-ferme', locale, !!useFeeArray, true);
1240
- }
1241
- catch (e) {
1242
- console.log('error on fetching product: ', e.toString());
1243
- }
1244
- try {
1245
- fraisSiCommandePasEnLigne =
1246
- cartType === 'online' || expeditionMethod === 'pickup'
1247
- ? undefined
1248
- : await fetchProduct('frais-commande-gazon-pas-en-ligne', locale, !!useFeeArray, true);
1249
- }
1250
- catch (e) {
1251
- console.log('error on fetching product: ', e.toString());
1252
- }
1253
- if (!!orderDate) {
1254
- const addSku = (sku, product) => {
1255
- const decli = product.declinations.find((i) => i.sku === sku);
1256
- if (!!decli) {
1257
- feesToAdd.push(Object.assign(Object.assign({}, decli), { qte: !!product.slug.includes('installation') && grassProduct.qte < minQteInstall
1258
- ? minQteInstall
1259
- : (!!product.slug.includes('commandes-gazon') ||
1260
- ['frais-commande-gazon-pas-en-ligne', 'surcharge-gazon-ramassage-hors-ferme'].includes(product.slug)) &&
1261
- grassProduct.qte < minQteGrassOrder
1262
- ? minQteGrassOrder
1263
- : grassProduct.qte, is_upsell_of_sku: 'summary', parent_slug: product.slug, other_units: decli.other_units }));
1264
- }
1265
- };
1266
- let allOrderFees = [];
1267
- let allInstallationFees = [];
1268
- if (!!shouldApplyFees) {
1269
- // ---------------------------------------------------
1270
- // #region Si la date de la commande est ...
1271
- if (!!surchargesCommandesGazon) {
1272
- // ... un samedi et que la commande est en livraison OU en pickup dans un magasin qui n'est pas rattaché à uen gazonnière
1273
- if (orderDate.getDay() === 6) {
1274
- if (expeditionMethod === 'delivery') {
1275
- allOrderFees.push(['000010400', surchargesCommandesGazon]);
1276
- }
1277
- else {
1278
- if (!!!data_2.grassFarmStores.includes(pickupStoreId)) {
1279
- allOrderFees.push(['000010400', surchargesCommandesGazon]);
1280
- }
1281
- }
1282
- }
1283
- // ... un dimanche ou jours fériés officiels
1284
- // NOTE: seulement pour le frais gazon, celui d'installation s'applique indépendemment plus bas dans la logique
1285
- if ((0, moment_1.default)(orderDate).day() === 0 ||
1286
- (0, data_1.getHolidays)().some((date) => (0, moment_1.default)(date).isSame((0, moment_1.default)(orderDate), 'day'))) {
1287
- allOrderFees = [...allOrderFees, ['000010850', surchargesCommandesGazon]];
1288
- }
1289
- // ... dans les vacances de construction
1290
- const cd = (0, data_1.getContructionHolidays)();
1291
- if ((0, moment_1.default)(orderDate).isBetween((0, moment_1.default)(cd[0]), (0, moment_1.default)(cd[1]), 'day', '[]')) {
1292
- allOrderFees = [...allOrderFees, ['000010860', surchargesCommandesGazon]];
1293
- }
1294
- // ... en été
1295
- const summer = (0, data_1.getSummerDate)();
1296
- if ((0, moment_1.default)(orderDate).isBetween((0, moment_1.default)(summer[0]), (0, moment_1.default)(summer[1]), 'day', '[]')) {
1297
- allOrderFees = [...allOrderFees, ['000010300', surchargesCommandesGazon]];
1298
- }
1299
- }
1300
- // #endregion
1301
- // ---------------------------------------------------
1302
- // ---------------------------------------------------
1303
- // #region Si la date de commande se trouve entre (inclusif)...
1304
- // NOTE : les frais d'installation ne doivent seulement s'appliquer pour les clients pros (POS et WEB)
1305
- const shouldAddGrassSeasonFee = !!surchargesCommandesGazonDebutFinSaison;
1306
- const shouldAddInstallSeasonFee = !!cartContainsInstallation && !!isPro && !!surchargesInstallationGazonDebutFinSaison;
1307
- // ...début de la saison au 30 avril
1308
- if ((0, moment_1.default)(orderDate).isBetween(`${(0, moment_1.default)().format('YYYY')}-03-01`, `${(0, moment_1.default)().format('YYYY')}-04-30`, 'day', '[]')) {
1309
- if (shouldAddGrassSeasonFee)
1310
- allOrderFees = [...allOrderFees, ['000010100', surchargesCommandesGazonDebutFinSaison]];
1311
- if (shouldAddInstallSeasonFee)
1312
- allInstallationFees.push(['000010600', surchargesInstallationGazonDebutFinSaison]);
1313
- }
1314
- // ...15 oct. au 31 oct.
1315
- if ((0, moment_1.default)(orderDate).isBetween(`${(0, moment_1.default)().format('YYYY')}-10-15`, `${(0, moment_1.default)().format('YYYY')}-10-31`, 'day', '[]')) {
1316
- if (shouldAddGrassSeasonFee)
1317
- allOrderFees = [...allOrderFees, ['000010840', surchargesCommandesGazonDebutFinSaison]];
1318
- if (shouldAddInstallSeasonFee)
1319
- allInstallationFees.push(['000010940', surchargesInstallationGazonDebutFinSaison]);
1320
- }
1321
- //...1er nov. au 14 nov.
1322
- if ((0, moment_1.default)(orderDate).isBetween(`${(0, moment_1.default)().format('YYYY')}-11-01`, `${(0, moment_1.default)().format('YYYY')}-11-14`, 'day', '[]')) {
1323
- if (shouldAddGrassSeasonFee)
1324
- allOrderFees = [...allOrderFees, ['000010700', surchargesCommandesGazonDebutFinSaison]];
1325
- if (shouldAddInstallSeasonFee)
1326
- allInstallationFees.push(['000010800', surchargesInstallationGazonDebutFinSaison]);
1327
- }
1328
- // ...15 nov. à la fin de la saison
1329
- if ((0, moment_1.default)(orderDate).isBetween(`${(0, moment_1.default)().format('YYYY')}-11-15`, `${(0, moment_1.default)().format('YYYY')}-12-31`, 'day', '[]')) {
1330
- if (shouldAddGrassSeasonFee)
1331
- allOrderFees = [...allOrderFees, ['000010900', surchargesCommandesGazonDebutFinSaison]];
1332
- if (shouldAddInstallSeasonFee)
1333
- allInstallationFees.push(['000010950', surchargesInstallationGazonDebutFinSaison]);
1334
- }
1335
- // #endregion
1336
- // ---------------------------------------------------
1337
- // Si la commande est en pick-up et le magazin n'est pas une gazonnière
1338
- if (expeditionMethod === 'pickup' && !!surchargesGazonPickupHorsFerme) {
1339
- if (!!!data_2.grassFarmStores.includes(pickupStoreId)) {
1340
- allOrderFees = [...allOrderFees, ['000012500', surchargesGazonPickupHorsFerme]];
1341
- }
1342
- }
1343
- }
1344
- // Si la commande a de l'installation et la date de la commande est un dimanche ou un jour férié
1345
- if (!!surchargesInstallationGazon &&
1346
- !!cartContainsInstallation &&
1347
- ((0, moment_1.default)(orderDate).day() === 0 ||
1348
- (0, data_1.getHolidays)().some((date) => (0, moment_1.default)(date).isSame((0, moment_1.default)(orderDate), 'day')))) {
1349
- allInstallationFees.push(['000010750', surchargesInstallationGazon]);
1350
- }
1351
- // Si la commande a été faite autrement qu'en ligne ET ne contient pas d'installation (PROS ONLY)
1352
- if (!!fraisSiCommandePasEnLigne && !!!cartContainsInstallation && !!isPro) {
1353
- allOrderFees = [...allOrderFees, ['FRSGAZON', fraisSiCommandePasEnLigne]];
1354
- }
1355
- allOrderFees.map((fee) => {
1356
- addSku(fee[0], fee[1]);
1357
- });
1358
- allInstallationFees.map((fee) => {
1359
- addSku(fee[0], fee[1]);
1360
- });
1361
- }
1362
- itemsToAdd = [...itemsToAdd, ...feesToAdd];
1363
- }
1364
- if (!!grassProduct || !!isMixed) {
1365
- cart.items.forEach((i) => {
1366
- if (!!i.parent_slug &&
1367
- [
1368
- 'surcharges-commandes-gazon',
1369
- 'surcharges-commandes-gazon-debut-fin-saison',
1370
- 'surcharges-installation-gazon',
1371
- 'surcharges-installation-gazon-debut-fin-saison',
1372
- 'surcharge-gazon-ramassage-hors-ferme',
1373
- 'frais-commande-gazon-pas-en-ligne'
1374
- ].includes(i.parent_slug)) {
1375
- itemsToDelete.push(i.sku);
1376
- }
1377
- });
1378
- }
1379
- // #endregion SURCHARGE DE PRIX DE GAZON
1380
- // --------------------------------------------------------------------------------------------------
1381
- // #region SURCHARGE CARBURANT TEMPORAIRE - COÛTS DE PRODUCTION GAZON
1382
- // 1¢/pi² sur gazon Kentucky, livraison ET cueillette, pro seulement
1383
- // La surcharge s'applique dès que du Kentucky est présent (directement ou comme gazon base)
1384
- const isGrassEligibleForFuelSurcharge = cart.items.some((i) => (0, products_2.checkIfIsNonSpecialityGrass)(i.sku, i.parent_slug || '', true));
1385
- // L'activation/désactivation est contrôlée par l'état draft du produit
1386
- const fuelGazonProd = !!grassProduct && isGrassEligibleForFuelSurcharge && isPro && !!!cart.is_booking
1387
- ? await fetchProduct(products_3.fuelSurchargeGazonSlug, locale, !!useFeeArray, true)
1388
- : undefined;
1389
- if (!!fuelGazonProd && !!grassProduct) {
1390
- let fuelGazonDecli = fuelGazonProd.declinations.find((d) => d.sku === products_3.fuelSurchargeGazonSku);
1391
- if (!!fuelGazonDecli) {
1392
- if (!!customPriceList) {
1393
- fuelGazonDecli = (0, g2_1.checkForCustomPriceEquivalent)(fuelGazonDecli, customPriceList);
1394
- }
1395
- if (!(0, products_2.shouldHideItemIfRegPriceIs0)(fuelGazonDecli, fuelGazonProd.slug, false)) {
1396
- itemsToAdd.push(Object.assign(Object.assign({}, fuelGazonDecli), { qte: grassProduct.qte < minQteGrassOrder ? minQteGrassOrder : grassProduct.qte, is_upsell_of_sku: 'summary', parent_slug: fuelGazonProd.slug, categories: fuelGazonProd.categories }));
1397
- }
1398
- }
1399
- }
1400
- else {
1401
- cart.items
1402
- .filter((i) => i.sku === products_3.fuelSurchargeGazonSku)
1403
- .forEach((i) => itemsToDelete.push(i.sku));
1404
- }
1405
- // #endregion SURCHARGE CARBURANT TEMPORAIRE - COÛTS DE PRODUCTION GAZON
1406
- // --------------------------------------------------------------------------------------------------
1407
- // #region COMMANDE BÉTON - FRAIS DE PRÉPARATION
1408
- // --------------------------------------------------------------------------------------------------
1409
- if (!!concreteOrder && !!!cartContainsSample && !!!cartContainsOnlyAccessories) {
1410
- // ----------------------------------------------------------------------------------------------
1411
- // Frais de préparation général
1412
- // MODIF FRAIS 2024 - Ajout du frais FP-1 seulement si le panier contient un minimum de 1 palette de produits de béton
1413
- // Vérifie vraiment que les produits de béton pour la quantité
1414
- const fraisPreparationGeneralBeton = await fetchProduct('frais-preparation-general-beton', locale, !!useFeeArray, true);
1415
- const onlyConcretePalQty = (0, exports.getPalletQty)(cart.items.filter((i) => (0, products_2.checkIfProductIsOfType)(i, 'beton', true)));
1416
- if (!!fraisPreparationGeneralBeton && onlyConcretePalQty >= 1) {
1417
- const decli = fraisPreparationGeneralBeton.declinations.find((i) => i.sku === 'FP-1');
1418
- if (!!decli) {
1419
- itemsToAdd.push(Object.assign(Object.assign({}, decli), { qte: 1, is_upsell_of_sku: 'summary', parent_slug: fraisPreparationGeneralBeton.slug, categories: fraisPreparationGeneralBeton.categories }));
1420
- }
1421
- }
1422
- // ----------------------------------------------------------------------------------------------
1423
- // Frais si commande pas en ligne/par un commis
1424
- if (expeditionMethod !== 'pickup' && cartType !== 'online' && !!isPro) {
1425
- const getFeeAmount = (decli) => {
1426
- // fee is a percentage of price for each item that isn't a service or fee
1427
- // percentage is determined by FRSBETON regular_price.value
1428
- const percent = (0, toNumber_1.default)(decli.regular_price.amount);
1429
- let amount = 0;
1430
- for (let item of cart.items) {
1431
- if (!!item.is_service)
1432
- continue;
1433
- if (!!customPriceList) {
1434
- item = (0, g2_1.checkForCustomPriceEquivalent)(item, customPriceList);
1435
- }
1436
- const itemPrice = (0, products_4.getLowestPrice)(item).price.amount;
1437
- amount += itemPrice * item.qte * percent;
1438
- }
1439
- return (0, round_1.default)(amount, 3);
1440
- };
1441
- const feeProd = await fetchProduct('frais-commande-beton-pas-en-ligne', locale, !!useFeeArray, true);
1442
- if (!!feeProd) {
1443
- const skuToAdd = (feeProd.declinations || []).find((d) => d.sku === 'FRSBETON');
1444
- if (!!skuToAdd) {
1445
- itemsToAdd.push(Object.assign(Object.assign({}, skuToAdd), { qte: 1, parent_slug: feeProd.slug, is_upsell_of_sku: 'summary', regular_price: Object.assign(Object.assign({}, skuToAdd.regular_price), { amount: getFeeAmount(skuToAdd), price_type: (0, round_1.default)((0, toNumber_1.default)(skuToAdd.regular_price.amount) * 100, 2).toString() }), price_override: true, categories: feeProd.categories }));
1446
- }
1447
- }
1448
- }
1449
- else {
1450
- if (cart.items.some((item) => item.sku === 'FRSBETON')) {
1451
- itemsToDelete.push('FRSBETON');
1452
- }
1453
- }
1454
- // ----------------------------------------------------------------------------------------------
1455
- // Frais de préparation si commande contient 4 palettes incomplètes
1456
- const concreteItems = cart.items.filter((i) => i.attributes[data_4.AttributesIdEnumGR.TYPE] && i.attributes[data_4.AttributesIdEnumGR.TYPE].includes('beton'));
1457
- let numberOfIncompletePallets = 0;
1458
- for (const item of concreteItems) {
1459
- if (!!!item.other_units)
1460
- continue;
1461
- const saleUnit = item.other_units.find((unit) => unit.is_sale_unit);
1462
- const palUnit = item.other_units.find((unit) => unit.unit_slug === 'pal');
1463
- if (!!!saleUnit || !!!saleUnit.fitting_unit || !!!palUnit || !!!palUnit.fitting_unit)
1464
- continue;
1465
- const calculatedPal = saleUnit.fitting_unit * item.qte;
1466
- const rest = (0, round_1.default)(calculatedPal, 3) % (0, round_1.default)(palUnit.fitting_unit, 3);
1467
- if (!!rest) {
1468
- numberOfIncompletePallets++;
1469
- }
1470
- }
1471
- if (numberOfIncompletePallets >= 4) {
1472
- const surchargesCommandesBeton = await fetchProduct('frais-preparation', locale, !!useFeeArray, true);
1473
- if (!!surchargesCommandesBeton) {
1474
- const decli = surchargesCommandesBeton.declinations.find((i) => i.sku === 'FP4');
1475
- if (!!decli) {
1476
- itemsToAdd.push(Object.assign(Object.assign({}, decli), { qte: 1, is_upsell_of_sku: 'summary', parent_slug: surchargesCommandesBeton.slug, categories: surchargesCommandesBeton.categories }));
1477
- }
1478
- }
1479
- }
1480
- else {
1481
- const prepItem = cart.items.find((item) => item.parent_slug === 'frais-preparation');
1482
- if (!!prepItem) {
1483
- itemsToDelete.push(prepItem.sku);
1484
- }
1485
- }
1486
- }
1487
- else {
1488
- if (cart.items.some((item) => item.sku === 'FP-1')) {
1489
- itemsToDelete.push('FP-1');
1490
- }
1491
- if (cart.items.some((item) => item.sku === 'FRSBETON')) {
1492
- itemsToDelete.push('FRSBETON');
1493
- }
1494
- }
1495
- // #endregion COMMANDE BÉTON - FRAIS DE PRÉPARATION
1496
- // --------------------------------------------------------------------------------------------------
1497
- // #region FRAIS LIVRAISON SELON L'EMPLACEMENT
1498
- // --------------------------------------------------------------------------------------------------
1499
- let isOutOfArea = false;
1500
- if (expeditionMethod === 'delivery' && !!deliveryAddress) {
1501
- let insideZones = undefined;
1502
- try {
1503
- insideZones = await getIfAddressIsInsideZones(deliveryAddress);
1504
- }
1505
- catch (e) {
1506
- console.log('error on fetching zones for address: ', e.toString());
1507
- }
1508
- if (!!insideZones && !!Array.isArray(insideZones)) {
1509
- if (!!insideZones.length && insideZones.includes('zone-gr')) {
1510
- // =============================================================================================
1511
- // TOUS TYPES DE COMMANDE
1512
- // Si une ou plusieurs zones correspondent
1513
- let productInstallToAdd;
1514
- if (!!grassProduct) {
1515
- productInstallToAdd = !!cartContainsInstallation
1516
- ? await fetchProduct('surcharges-installation-gazon', locale, !!useFeeArray, true)
1517
- : undefined;
1518
- }
1519
- const productToAdd = await fetchProduct('surcharges-commandes-gazon', locale, !!useFeeArray, true);
1520
- if (insideZones.includes('zone-mtl')) {
1521
- if (!!productToAdd) {
1522
- const mtl = productToAdd.declinations.find((i) => i.sku === '170050000');
1523
- if (!!mtl) {
1524
- itemsToAdd.push(Object.assign(Object.assign({}, mtl), { qte: (0, ceil_1.default)((0, ceil_1.default)(totalPallet) / exports.expeditionFeePalletTier), is_upsell_of_sku: 'summary', parent_slug: 'surcharges-commandes-gazon', categories: productToAdd.categories }));
1525
- }
1526
- }
1527
- // If Installation ...
1528
- if (!!grassProduct && !!productInstallToAdd) {
1529
- const mtlInstall = productInstallToAdd.declinations.find((i) => i.sku === '170055500');
1530
- if (!!mtlInstall) {
1531
- itemsToAdd.push(Object.assign(Object.assign({}, mtlInstall), { qte: (0, ceil_1.default)(totalPalletGrass / exports.installationFeePalletTier), is_upsell_of_sku: 'summary', parent_slug: 'surcharges-installation-gazon', categories: productInstallToAdd.categories }));
1532
- }
1533
- }
1534
- }
1535
- if (insideZones.includes('zone-ontario')) {
1536
- if (!!productToAdd) {
1537
- const ontario = productToAdd.declinations.find((i) => i.sku === '170000ONT');
1538
- if (!!ontario) {
1539
- itemsToAdd.push(Object.assign(Object.assign({}, ontario), { qte: (0, ceil_1.default)((0, ceil_1.default)(totalPallet) / exports.expeditionFeePalletTier), is_upsell_of_sku: 'summary', parent_slug: 'surcharges-commandes-gazon', categories: productToAdd.categories }));
1540
- }
1541
- }
1542
- // If Installation ...
1543
- if (!!grassProduct && !!productInstallToAdd) {
1544
- const ontarioInstall = productInstallToAdd.declinations.find((i) => i.sku === '170033ONT');
1545
- if (!!ontarioInstall) {
1546
- itemsToAdd.push(Object.assign(Object.assign({}, ontarioInstall), { qte: (0, ceil_1.default)(totalPalletGrass / exports.installationFeePalletTier), is_upsell_of_sku: 'summary', parent_slug: 'surcharges-installation-gazon', categories: productInstallToAdd.categories }));
1547
- }
1548
- }
1549
- }
1550
- if (insideZones.includes('zone-ile-orleans')) {
1551
- if (!!productToAdd) {
1552
- const ileOrleans = productToAdd.declinations.find((i) => i.sku === '170000418');
1553
- if (!!ileOrleans) {
1554
- itemsToAdd.push(Object.assign(Object.assign({}, ileOrleans), { qte: (0, ceil_1.default)((0, ceil_1.default)(totalPallet) / exports.expeditionFeePalletTier), is_upsell_of_sku: 'summary', parent_slug: 'surcharges-commandes-gazon', categories: productToAdd.categories }));
1555
- }
1556
- }
1557
- }
1558
- // }
1559
- // =============================================================================================
1560
- // COMMANDES VRAC
1561
- // Infos pour la livraison du vrac, vérification faite maintenant dans deux zones
1562
- if (!!cartContainsVrac) {
1563
- if (insideZones.includes('zone-vrac') || insideZones.includes('zone-vrac-les-coteaux')) {
1564
- const deliveryTruckProduct = await fetchProduct('frais-de-livraison-vrac', locale, !!useFeeArray, true);
1565
- // Fetch de l'adresse du magasin de la zone concernée, pour calculer le prix du frais de livraison
1566
- const storeIDToCheck = insideZones.includes('zone-vrac') ? 'sainte-julie-nobel' : 'default';
1567
- const storeAddress = getStoreAddressByID(allStores, storeIDToCheck);
1568
- // Si le magasin de la zone ne se trouve pas dans le array de magasins disponibles pour les produits de vrac de la commande,
1569
- // mettre la commande comme hors-zone automatiquement
1570
- if (!!availableVracStoreIDs && !availableVracStoreIDs.includes(storeIDToCheck)) {
1571
- isOutOfArea = true;
1572
- }
1573
- else if (!!deliveryTruckProduct && !!storeAddress) {
1574
- let distance = null;
1575
- try {
1576
- distance = await getDistanceFromAddress(storeAddress, deliveryAddress);
1577
- }
1578
- catch (_) {
1579
- console.log(_);
1580
- }
1581
- if (distance === null) {
1582
- isOutOfArea = true;
1583
- }
1584
- else {
1585
- itemsToAdd = [
1586
- ...itemsToAdd,
1587
- ...(0, exports.calculateShippingForVrac)(distance, cart.items, deliveryTruckProduct, itemsToAdd, expeditionDate)
1588
- ];
1589
- }
1590
- }
1591
- }
1592
- else {
1593
- isOutOfArea = true;
1594
- }
1595
- }
1596
- }
1597
- else {
1598
- isOutOfArea = true;
1599
- }
1600
- }
1601
- }
1602
- cart.items.forEach((i) => {
1603
- if (!!i.parent_slug && ['frais-de-livraison-vrac', 'surcharges-commandes-gazon'].includes(i.parent_slug)) {
1604
- itemsToDelete.push(i.sku);
1605
- }
1606
- });
1607
- // #endregion FRAIS LIVRAISON SELON L'EMPLACEMENT
1608
- // --------------------------------------------------------------------------------------------------
1609
- // #region RAMASSAGE D'ÉQUIPEMENT SUR LE CHANTIER
1610
- // --------------------------------------------------------------------------------------------------
1611
- if (!!equipmentPickupOnSite) {
1612
- // consoleLog({ equipmentPickupOnSite: 'true' })
1613
- }
1614
- // #endregion RAMASSAGE D'ÉQUIPEMENT SUR LE CHANTIER
1615
- // --------------------------------------------------------------------------------------------------
1616
- // #region FRAIS EXTRA LIVRAISON EN PÉRIODE DE DÉGEL
1617
- const degelFeeSku = '170000018';
1618
- if (!!isPro &&
1619
- expeditionMethod === 'delivery' &&
1620
- !!!cartContainsSample &&
1621
- !!!cartContainsVrac &&
1622
- !!expeditionDate &&
1623
- !!isDegel(expeditionDate)) {
1624
- const degelFeeProd = await fetchProduct('frais-livraison-periode-degel', locale, !!useFeeArray, true);
1625
- if (!!degelFeeProd) {
1626
- const degelFeeDecli = degelFeeProd.declinations.find((d) => d.sku === degelFeeSku);
1627
- if (!!degelFeeDecli) {
1628
- itemsToAdd.push(Object.assign(Object.assign({}, degelFeeDecli), { qte: 1, is_upsell_of_sku: 'summary', parent_slug: degelFeeProd.slug, categories: degelFeeProd.categories }));
1629
- }
1630
- }
1631
- }
1632
- else {
1633
- if (!!cart.items.some((i) => i.sku === degelFeeSku)) {
1634
- itemsToDelete.push(degelFeeSku);
1635
- }
1636
- }
1637
- // #endregion
1638
- // --------------------------------------------------------------------------------------------------
1639
- // #region SURCHARGE CARBURANT TEMPORAIRE - LIVRAISON
1640
- // 95$ par tranche de 24 palettes, pro seulement, pas de booking
1641
- const fuelLivraisonProd = isPro &&
1642
- !!!cart.is_booking &&
1643
- itemsToAdd.some((i) => !!i.parent_slug &&
1644
- ['livraison-gazon', 'livraison-beton-accessoires'].includes(i.parent_slug))
1645
- ? await fetchProduct(products_3.fuelSurchargeLivraisonSlug, locale, !!useFeeArray, true)
1646
- : undefined;
1647
- if (!!fuelLivraisonProd) {
1648
- let fuelLivraisonDecli = fuelLivraisonProd.declinations.find((d) => d.sku === products_3.fuelSurchargeLivraisonSku);
1649
- if (!!fuelLivraisonDecli) {
1650
- if (!!customPriceList) {
1651
- fuelLivraisonDecli = (0, g2_1.checkForCustomPriceEquivalent)(fuelLivraisonDecli, customPriceList);
1652
- }
1653
- if (!(0, products_2.shouldHideItemIfRegPriceIs0)(fuelLivraisonDecli, fuelLivraisonProd.slug, false)) {
1654
- itemsToAdd.push(Object.assign(Object.assign({}, fuelLivraisonDecli), { qte: (0, ceil_1.default)(totalPallet / exports.expeditionFeePalletTier) || 1, is_upsell_of_sku: 'summary', parent_slug: fuelLivraisonProd.slug, categories: fuelLivraisonProd.categories }));
1655
- }
1656
- }
1657
- }
1658
- else {
1659
- cart.items
1660
- .filter((i) => i.sku === products_3.fuelSurchargeLivraisonSku)
1661
- .forEach((i) => itemsToDelete.push(i.sku));
1662
- }
1663
- // #endregion SURCHARGE CARBURANT TEMPORAIRE - LIVRAISON
1664
- // --------------------------------------------------------------------------------------------------
1665
- // #region SURCHARGE CARBURANT TEMPORAIRE - MOBILISATION
1666
- // 95$ par tranche de 48 palettes, pro seulement
1667
- const fuelMobilisationProd = isPro &&
1668
- cartContainsInstallation &&
1669
- !!!cart.is_booking &&
1670
- cart.items.some((i) => i.parent_slug === 'frais-de-mobilisation')
1671
- ? await fetchProduct(products_3.fuelSurchargeMobilisationSlug, locale, !!useFeeArray, true)
1672
- : undefined;
1673
- if (!!fuelMobilisationProd) {
1674
- let fuelMobilisationDecli = fuelMobilisationProd.declinations.find((d) => d.sku === products_3.fuelSurchargeMobilisationSku);
1675
- if (!!fuelMobilisationDecli) {
1676
- if (!!customPriceList) {
1677
- fuelMobilisationDecli = (0, g2_1.checkForCustomPriceEquivalent)(fuelMobilisationDecli, customPriceList);
1678
- }
1679
- if (!(0, products_2.shouldHideItemIfRegPriceIs0)(fuelMobilisationDecli, fuelMobilisationProd.slug, false)) {
1680
- // Utiliser getPalletQtyPalletFee pour aligner sur le même calcul que les autres frais
1681
- // (gère l'arrondi spécifique livraison vs cueillette de gazon)
1682
- const palletQtyForFee = (0, exports.getPalletQtyPalletFee)(cart.items, expeditionMethod, true, isMixed);
1683
- itemsToAdd.push(Object.assign(Object.assign({}, fuelMobilisationDecli), { qte: (0, ceil_1.default)(Math.max(palletQtyForFee, 1) / exports.installationFeePalletTier) || 1, is_upsell_of_sku: 'summary', parent_slug: fuelMobilisationProd.slug, categories: fuelMobilisationProd.categories }));
1684
- }
1685
- }
1686
- }
1687
- else {
1688
- cart.items
1689
- .filter((i) => i.sku === products_3.fuelSurchargeMobilisationSku)
1690
- .forEach((i) => itemsToDelete.push(i.sku));
1691
- }
1692
- // #endregion SURCHARGE CARBURANT TEMPORAIRE - MOBILISATION
1693
- // --------------------------------------------------------------------------------------------------
1694
- // #region Gestion d'ajout / delete des frais
1695
- itemsToDelete = itemsToDelete.filter((i) => !itemsToAdd.map((add) => add.sku).includes(i));
1696
- itemsToAdd = itemsToAdd
1697
- .map((item) => {
1698
- const cartItem = cart.items.find((i) => i.sku === item.sku);
1699
- if (!!cartItem) {
1700
- if (cartItem.qte !== item.qte) {
1701
- itemsToUpdate.push({ sku: item.sku, qte: item.qte });
1702
- return;
1703
- }
1704
- else {
1705
- return;
1706
- }
1707
- }
1708
- else {
1709
- // If fee regular price is 0.00$ and item fits criteria, do not add to cart
1710
- if (!!item.parent_slug &&
1711
- (0, products_2.shouldHideItemIfRegPriceIs0)(item, item.parent_slug, !!item.is_upsell_of_sku && item.parent_slug.includes('installation'))) {
1712
- return;
1713
- }
1714
- }
1715
- // When installation all-inclusive, force frais de livraison to 0$
1716
- return installAllInclusiveActive ? (0, products_2.applyAllInclusiveOverrides)(item) : item;
1717
- })
1718
- .filter((i) => !!i);
1719
- // #endregion Gestion d'ajout / delete des frais
1720
- return {
1721
- newCart: Object.assign(Object.assign({}, cart), { shipping_payload: newShippingPayload }),
1722
- itemsToDelete,
1723
- itemsToUpdate,
1724
- itemsToAdd,
1725
- totalPallet,
1726
- isOutOfArea
1727
- };
1728
- };
1729
- exports.applyFeesToCart = applyFeesToCart;
1730
- // #endregion
1731
- // ------------------------------------------------------------------------------------------
1732
- // ------------------------------------------------------------------------------------------
1733
- // #region SHIPPING
1734
- /**
1735
- * Checks if sample shipping fee should be removed from cart depending on cart items found in cart.
1736
- * ** Optimized version possible using brand name instead of brand id, removing async check.
1737
- * ** Optimized version reverted, logic found in commit here : [#2087b32]{@link https://github.com/ciaoqc/gng-tb-admin-sdk/commit/2087b3207df9e5916a979b8bb255abc2a4c1dac6}
1738
- * @param fetchProduct
1739
- * @param cart
1740
- * @param locale
1741
- * @param useFeeArray
1742
- */
1743
- const checkIfShouldRemoveSampleShippingFee = async (fetchProduct, cart, locale, useFeeArray) => {
1744
- if (!!!cart.items)
1745
- return false;
1746
- const currentItems = cart.items.filter((i) => i.is_sample);
1747
- let currentItemsChecked = [];
1748
- for (let item of currentItems) {
1749
- if (!!!item.parent_slug)
1750
- continue;
1751
- // 1. Get parent product for brand ID
1752
- const parentProd = await fetchProduct(item.parent_slug, locale, !!useFeeArray, true);
1753
- if (!!!parentProd)
1754
- continue;
1755
- const brand = parentProd.brand;
1756
- // 2. Check if item.attributes contains FAMILY attribute with value Tena
1757
- const isTena = !!item.attributes &&
1758
- !!item.attributes[data_4.AttributesIdEnumGR.FAMILY] &&
1759
- !!item.attributes[data_4.AttributesIdEnumGR.FAMILY].includes('tena');
1760
- // 3. Check if item.attributes.TYPE is grass and is not Kentucky or Prestige (both non-speciality grasses)
1761
- // const excludedGrass = [`kentucky`, `prestige`]
1762
- const hasGrassType = (0, products_2.checkIfProductIsOfType)(item, 'gazon');
1763
- const isExcludedGrass = (0, products_2.checkIfIsNonSpecialityGrass)(item.sku, item.parent_slug);
1764
- const isGrass = !!hasGrassType && !!!isExcludedGrass;
1765
- const valuesToCheck = {
1766
- brand: !!brand ? brand : '',
1767
- isTena: isTena,
1768
- isGrass: isGrass
1769
- };
1770
- currentItemsChecked.push(valuesToCheck);
1771
- }
1772
- if (!!currentItemsChecked.length) {
1773
- const allIncludedBrandsNoTena = currentItemsChecked.filter((item) => !!item.brand && !!data_2.includedFreeShippingBrands.includes(item.brand) && !!!item.isTena);
1774
- const allGrass = currentItemsChecked.filter((item) => !!item.isGrass);
1775
- // 3. count all items with included brands and check if length === currentItems.length
1776
- // if true, remove shipping cost (set productToAdd undefined)
1777
- if (currentItems.length === allIncludedBrandsNoTena.length || currentItems.length === allGrass.length) {
1778
- return true;
1779
- }
1780
- else {
1781
- // 4. add IncludedBrandsNoTena + isGrass lengths and check if equals currentItems.length
1782
- // if true, remove shipping cost (set productToAdd undefined)
1783
- const added = allIncludedBrandsNoTena.length + allGrass.length;
1784
- if (added === currentItems.length) {
1785
- return true;
1786
- }
1787
- }
1788
- }
1789
- return false;
1790
- };
1791
- exports.checkIfShouldRemoveSampleShippingFee = checkIfShouldRemoveSampleShippingFee;
1792
- const calculateShippingForVrac = (distance = 0, cartItems, deliveryTruckProduct, currentItemsToAdd, deliveryDate) => {
1793
- let itemsToAdd = [...currentItemsToAdd];
1794
- const allVracItems = cartItems.filter((i) => (0, products_2.checkIfProductIsOfType)(i, 'vrac'));
1795
- for (const vracItem of allVracItems) {
1796
- const totalTons = vracItem.qte;
1797
- const isInDegelPeriod = !!isDegel(deliveryDate);
1798
- const volumeTons = [
1799
- {
1800
- min: 1,
1801
- max: 4
1802
- },
1803
- {
1804
- min: 4,
1805
- max: isInDegelPeriod ? 11 : 15
1806
- },
1807
- {
1808
- min: isInDegelPeriod ? 11 : 15,
1809
- max: isInDegelPeriod ? 16 : 20
1810
- },
1811
- {
1812
- min: isInDegelPeriod ? 16 : 20,
1813
- max: isInDegelPeriod ? 19 : 24
1814
- },
1815
- {
1816
- min: isInDegelPeriod ? 19 : 24,
1817
- max: isInDegelPeriod ? 24 : 30
1818
- }
1819
- ];
1820
- const checkTons = (tons) => {
1821
- let skuToAdd = '';
1822
- switch (true) {
1823
- case tons <= volumeTons[0].max:
1824
- switch (true) {
1825
- case distance >= 0 && distance < 15:
1826
- skuToAdd = '170000615';
1827
- break;
1828
- case distance >= 15 && distance < 30:
1829
- skuToAdd = '170000630';
1830
- break;
1831
- case distance >= 30:
1832
- skuToAdd = '170000660';
1833
- break;
1834
- }
1835
- tons = -1;
1836
- break;
1837
- case tons > volumeTons[1].min && tons <= volumeTons[1].max:
1838
- switch (true) {
1839
- case distance >= 0 && distance < 15:
1840
- skuToAdd = '170001015';
1841
- break;
1842
- case distance >= 15 && distance < 30:
1843
- skuToAdd = '170001030';
1844
- break;
1845
- case distance >= 30:
1846
- skuToAdd = '170001060';
1847
- break;
1848
- }
1849
- tons = -1;
1850
- break;
1851
- case tons > volumeTons[2].min && tons <= volumeTons[2].max:
1852
- switch (true) {
1853
- case distance >= 0 && distance < 15:
1854
- skuToAdd = '170001215';
1855
- break;
1856
- case distance >= 15 && distance < 30:
1857
- skuToAdd = '170001230';
1858
- break;
1859
- case distance >= 30:
1860
- skuToAdd = '170001260';
1861
- break;
1862
- }
1863
- tons = -1;
1864
- break;
1865
- case tons > volumeTons[3].min && tons <= volumeTons[3].max:
1866
- switch (true) {
1867
- case distance >= 0 && distance < 15:
1868
- skuToAdd = '170002015';
1869
- break;
1870
- case distance >= 15 && distance < 30:
1871
- skuToAdd = '170002030';
1872
- break;
1873
- case distance >= 30:
1874
- skuToAdd = '170002060';
1875
- break;
1876
- }
1877
- tons = -1;
1878
- break;
1879
- case tons > volumeTons[4].min:
1880
- switch (true) {
1881
- case distance >= 0 && distance < 15:
1882
- skuToAdd = '170003015';
1883
- break;
1884
- case distance >= 15 && distance < 30:
1885
- skuToAdd = '170003030';
1886
- break;
1887
- case distance >= 30:
1888
- skuToAdd = '170003060';
1889
- break;
1890
- }
1891
- tons = tons - volumeTons[4].max;
1892
- break;
1893
- default:
1894
- tons = -1;
1895
- }
1896
- const decliToAdd = deliveryTruckProduct.declinations.find((d) => d.sku === skuToAdd);
1897
- if (!!decliToAdd) {
1898
- if (!!itemsToAdd.find((item) => item.sku === decliToAdd.sku)) {
1899
- const index = itemsToAdd.findIndex((item) => item.sku === decliToAdd.sku);
1900
- itemsToAdd[index] = Object.assign(Object.assign({}, itemsToAdd[index]), { qte: itemsToAdd[index].qte + 1 });
1901
- }
1902
- else {
1903
- itemsToAdd.push(Object.assign(Object.assign({}, decliToAdd), { parent_slug: 'frais-de-livraison-vrac', qte: 1, is_upsell_of_sku: 'summary', categories: deliveryTruckProduct.categories }));
1904
- }
1905
- }
1906
- if (tons > 0) {
1907
- checkTons(tons);
1908
- }
1909
- };
1910
- checkTons(totalTons);
1911
- }
1912
- return itemsToAdd;
1913
- };
1914
- exports.calculateShippingForVrac = calculateShippingForVrac;
1915
- const getStoresForVracProdShipping = (inventoryItem) => {
1916
- let availability = {};
1917
- for (let vracStore of data_2.vracShippingStores) {
1918
- const sameInInventory = inventoryItem.inventories.find((i) => i.store_id == vracStore);
1919
- availability[vracStore] = !!sameInInventory && !!!sameInInventory.unavailable_in_store;
1920
- }
1921
- return availability;
1922
- };
1923
- exports.getStoresForVracProdShipping = getStoresForVracProdShipping;
1924
- const getStoreAddressByID = (allStores, storeID) => {
1925
- const sameStore = allStores.find((s) => s.id == storeID);
1926
- return !!sameStore ? sameStore.address : undefined;
1927
- };
1928
- // #endregion
1929
- // ------------------------------------------------------------------------------------------
1930
- // ------------------------------------------------------------------------------------------
1931
- // #region VALIDATION
1932
- /**
1933
- * Function checkIfCartExpired
1934
- * @description checks if cart expired using the updated_at date stored in the shipping_payload
1935
- * @param cartData
1936
- * @param grassProduct
1937
- * @param concreteOrder
1938
- * @param isPro
1939
- * @param options.blocked_shipping_dates
1940
- * @param options.vracType
1941
- * @param options.chosenPaymentType
1942
- * @param options.forceCheckForCartTypes
1943
- */
1944
- const checkIfCartExpired = (cartData, grassProduct, concreteOrder, isPro, options = {}) => {
1945
- // ######################################################################################
1946
- // #region TESTS
1947
- // ----------------------------------------------------------
1948
- // 1) Is same day after 10
1949
- // const test1 = {
1950
- // now: moment().set('hours', 11).toDate(),
1951
- // updated_last: moment().set('hours', 9).toDate(),
1952
- // time: 'AM',
1953
- // selected_date: moment().add(4, 'day').toDate()
1954
- // }
1955
- // 2) Is same day after 10 but with AM still possible
1956
- // const test2 = {
1957
- // now: moment().set({ day: 6, hours: 11 }).toDate(),
1958
- // updated_last: moment().set({ day: 6, hours: 9 }).toDate(),
1959
- // time: 'AM',
1960
- // selected_date: moment().set('day', 9).toDate()
1961
- // }
1962
- // const now = test2.now
1963
- // const updated_last = test2.updated_last
1964
- // const time = test2.time
1965
- // const selected_date = test2.selected_date
1966
- //
1967
- // #endregion
1968
- // ######################################################################################
1969
- const isPOS = Cart_1.CartTypeEnum.WEB != cartData.cart_type;
1970
- const isSample = (0, cart_1.checkIfCartContainsType)(cart_2.CartGeneralTypeEnum.SAMPLE, cartData);
1971
- const isAccessoriesOnly = (0, cart_1.checkIfCartContainsType)(cart_2.CartGeneralTypeEnum.ONLY_ACCESSORIES, cartData);
1972
- // const cartContainsInstallation = checkIfCartContainsType(CartGeneralTypeEnum.INSTALLATION, cartData)
1973
- // 1. Check if it is normal for selected date to be undefined / expired
1974
- const selectedDate = !!cartData.shipping_payload && !!cartData.shipping_payload.delivery_or_pickup_date
1975
- ? (0, data_3.formatDate)(cartData.shipping_payload.delivery_or_pickup_date)
1976
- : undefined;
1977
- const noDeliveryDateIsNormal = (0, exports.checkIfNoDeliveryDateIsNormal)(cartData, concreteOrder) ||
1978
- (!!options.chosenPaymentType && ['depot'].includes(options.chosenPaymentType));
1979
- const shouldForceCheck = (options.forceCheckForCartTypes || []).some((t) => (0, cart_1.checkIfCartContainsType)(t, cartData));
1980
- // If force check property sent, check event if !!noDeliveryDateIsNormal
1981
- if (!!noDeliveryDateIsNormal && !shouldForceCheck) {
1982
- return false;
1983
- }
1984
- else if (!!!selectedDate) {
1985
- return true;
1986
- }
1987
- // 2. Check date depending on when cart was last updated
1988
- const now = (0, moment_1.default)().toDate();
1989
- const updated_last = !!cartData.shipping_payload && !!cartData.shipping_payload.updated_at
1990
- ? (0, data_3.formatDate)(cartData.shipping_payload.updated_at)
1991
- : (0, moment_1.default)().toDate();
1992
- const time = !!cartData.shipping_payload && !!cartData.shipping_payload.delivery_period
1993
- ? cartData.shipping_payload.delivery_period
1994
- : 'PM';
1995
- const minDates = (0, exports.getMinDatePicker)(cartData, grassProduct, concreteOrder, !!cartData.is_pickup ? 'pickup' : 'delivery', !!isPro, updated_last, options.blocked_shipping_dates, options.vracType, isPOS);
1996
- const currentMinDate = !!cartData.is_pickup ? minDates.min_pickup : minDates.min_delivery;
1997
- const ok_hours = (0, exports.getAvailableHours)(currentMinDate, selectedDate, grassProduct, concreteOrder, (!!cartData.is_pickup ? 'pickup' : 'delivery'), time, isPro, isSample, isAccessoriesOnly, updated_last);
1998
- return (!!updated_last &&
1999
- (((0, moment_1.default)(selectedDate).isSameOrBefore(now, 'day') && !!!(0, moment_1.default)(currentMinDate).isSame(now, 'day')) ||
2000
- (0, moment_1.default)(now).isAfter(updated_last, 'day') ||
2001
- (0, moment_1.default)(currentMinDate).isAfter(selectedDate, 'day') ||
2002
- (updated_last.getHours() < 10 &&
2003
- now.getHours() >= 10 &&
2004
- time === 'AM' &&
2005
- !!ok_hours.deliveryTimes.every((d) => d.value == 'PM'))));
2006
- };
2007
- exports.checkIfCartExpired = checkIfCartExpired;
2008
- const checkIfNoDeliveryDateIsNormal = (cartData, concreteOrder, checkForInputShown) => {
2009
- const isAccessoriesOnly = (0, cart_1.checkIfCartContainsType)(cart_2.CartGeneralTypeEnum.ONLY_ACCESSORIES, cartData);
2010
- const isSample = (0, cart_1.checkIfCartContainsType)(cart_2.CartGeneralTypeEnum.SAMPLE, cartData);
2011
- return ((!!!checkForInputShown && !!cartData.shipping_payload && !!cartData.shipping_payload.isOutOfArea) ||
2012
- (!!concreteOrder && concreteOrder.type !== 'green') ||
2013
- ((!!isAccessoriesOnly || !!isSample) && !!!cartData.is_pickup));
2014
- };
2015
- exports.checkIfNoDeliveryDateIsNormal = checkIfNoDeliveryDateIsNormal;
2016
- // #endregion
2017
- // ------------------------------------------------------------------------------------------
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.checkIfNoDeliveryDateIsNormal = exports.checkIfCartExpired = exports.getStoresForVracProdShipping = exports.calculateShippingForVrac = exports.checkIfShouldRemoveSampleShippingFee = exports.applyFeesToCart = exports.installationFeePalletTier = exports.expeditionFeePalletTier = exports.checkForSameGrassDayFee = exports.checkIfShouldApplySameDayGrassFee = exports.getMinQteInstall = exports.getMinGrassQte = exports.calculatePalFeeForOtherThanGrass = exports.getPalletQtyPalletFee = exports.getGrassRoundedPickupPalletFees = exports.getPalletQty = exports.slugsToCheckFromExpeditionFees = exports.checkIfCartTypeHasBlockedDates = exports.dateIsClosedInSchedule = exports.shouldDisableDate = exports.getMinDateOffset = exports.getSamplesMinDateOffset = exports.getMinDatePicker = exports.getAvailableHours = exports.getDefaultTimeValues = void 0;
7
+ const moment_1 = __importDefault(require("moment"));
8
+ const ceil_1 = __importDefault(require("lodash/ceil"));
9
+ const findIndex_1 = __importDefault(require("lodash/findIndex"));
10
+ const floor_1 = __importDefault(require("lodash/floor"));
11
+ const round_1 = __importDefault(require("lodash/round"));
12
+ const sumBy_1 = __importDefault(require("lodash/sumBy"));
13
+ const toNumber_1 = __importDefault(require("lodash/toNumber"));
14
+ // Rule specific interfaces
15
+ const products_1 = require("../interfaces/products");
16
+ // Rule specific functions/constants
17
+ const data_1 = require("./data");
18
+ const products_2 = require("./products");
19
+ const cart_1 = require("./cart");
20
+ const g2_1 = require("./g2");
21
+ const data_2 = require("../constants/data");
22
+ const products_3 = require("../constants/products");
23
+ // General interfaces
24
+ const Cart_1 = require("../../../Interfaces/Cart");
25
+ // General utils
26
+ const data_3 = require("../../../utils/data");
27
+ const products_4 = require("../../../utils/products");
28
+ const cart_2 = require("../interfaces/cart");
29
+ const data_4 = require("../interfaces/data");
30
+ const object_1 = require("../../../utils/object");
31
+ // ------------------------------------------------------------------------------------------
32
+ // #region HOURS
33
+ const getDefaultTimeValues = () => {
34
+ let values = ['AM', 'PM'];
35
+ return values.map((v) => ({ label: v, value: v }));
36
+ };
37
+ exports.getDefaultTimeValues = getDefaultTimeValues;
38
+ const getAvailableHours = (minDeliveryDate, selectedDate, grassProduct, concreteOrder, expeditionMethod, selectedDeliveryTime, isPro, isSample, isAccessoriesOnly, testDate, keepHours) => {
39
+ if (!!!minDeliveryDate)
40
+ return { deliveryTimes: (0, exports.getDefaultTimeValues)() };
41
+ let deliveryTimes = (0, exports.getDefaultTimeValues)().map((t) => t.value);
42
+ const today = !!testDate
43
+ ? !!keepHours
44
+ ? (0, moment_1.default)(testDate).toDate()
45
+ : (0, moment_1.default)(testDate).set('hours', (0, moment_1.default)().hours()).toDate()
46
+ : (0, moment_1.default)().toDate();
47
+ // If concreteOrder and product in stock and is pickup, can select 'now' (AM if before noon, PM if after)
48
+ if (!!concreteOrder && !!concreteOrder.inStock && expeditionMethod === 'pickup') {
49
+ const isPM = today.getHours() >= 12;
50
+ if (!!isPM) {
51
+ deliveryTimes = ['PM'];
52
+ }
53
+ return {
54
+ deliveryTimes: deliveryTimes.map((t) => ({ label: t, value: t })),
55
+ newSelectedDeliveryTime: !!isPM ? { label: 'PM', value: 'PM' } : undefined
56
+ };
57
+ }
58
+ // ------------------------------------------------------------------------------------------------------
59
+ // enable all hours in selection
60
+ const resetHours = (d) => {
61
+ d.setHours(0);
62
+ d.setMinutes(0);
63
+ d.setSeconds(0);
64
+ d.setMilliseconds(0);
65
+ };
66
+ if (!!selectedDate)
67
+ resetHours(selectedDate);
68
+ resetHours(minDeliveryDate);
69
+ let newSelectedDeliveryTime = undefined;
70
+ const targetDateDay = minDeliveryDate.getDay();
71
+ const selectedDateDay = !!selectedDate ? selectedDate.getDay() : targetDateDay;
72
+ const isSelectedSameAsTarget = (0, moment_1.default)(minDeliveryDate).isSame(selectedDate) || !!!selectedDate;
73
+ const todayDay = today.getDay();
74
+ const isNonSpecialityGrass = !!grassProduct && (0, products_2.checkIfIsNonSpecialityGrass)(grassProduct.sku, grassProduct.slug);
75
+ const onlyPm = () => {
76
+ if (!!selectedDeliveryTime && selectedDeliveryTime === 'AM') {
77
+ newSelectedDeliveryTime = { label: 'PM', value: 'PM' };
78
+ }
79
+ deliveryTimes = ['PM'];
80
+ };
81
+ // EDIT - Ajusted logic that excluded saturdays from time selection if not pro to make available if expeditionMethod = shipping [ 03-10-2022 ]
82
+ if (selectedDateDay === 0 || (selectedDateDay === 6 && !!!isPro && expeditionMethod === 'pickup')) {
83
+ deliveryTimes = [];
84
+ newSelectedDeliveryTime = undefined;
85
+ }
86
+ else if (
87
+ // Bug GR-I505 - AM / PM toujours disponnible pour Beton Vert en livraison
88
+ // Bug GR-I511 - Pickup for concrete not in stock only change de available day
89
+ !(!!concreteOrder && concreteOrder.type == 'green' && (!concreteOrder.inStock || expeditionMethod == 'delivery'))) {
90
+ if (isSelectedSameAsTarget) {
91
+ if (!!grassProduct || (!!concreteOrder && concreteOrder.type === 'green')) {
92
+ let todayReset = !!testDate ? (0, moment_1.default)(testDate).toDate() : (0, moment_1.default)().toDate();
93
+ resetHours(todayReset);
94
+ // If today is either saturday of sunday
95
+ if (!![6, 0].includes(todayReset.getDay())) {
96
+ // Two options :
97
+ // - is non-speciality grass OR [ concrete + type green + pickup + not in stock ] and target day is NOT a tuesday
98
+ // - is any other kind of grass and target day is NOT a wednesday or thursday
99
+ if ((![2].includes(targetDateDay) &&
100
+ (!!isNonSpecialityGrass ||
101
+ (!!concreteOrder && !concreteOrder.inStock && expeditionMethod === 'pickup'))) ||
102
+ (![3, 4].includes(targetDateDay) && !!!isNonSpecialityGrass)) {
103
+ // EDIT - Ajusted logic that excluded saturdays from time selection if not pro to make available if expeditionMethod = shipping [ 03-10-2022 ]
104
+ if (targetDateDay === 6 && !!!isPro && expeditionMethod === 'pickup') {
105
+ newSelectedDeliveryTime = undefined;
106
+ deliveryTimes = [];
107
+ }
108
+ else {
109
+ const amTimeToCheck = !!grassProduct && expeditionMethod == 'pickup' ? 12 : 10;
110
+ // Logic ajusted on 08-05-2025 (task #GR-I377 in Sprint) - If grass & pickup, first check starts at noon. If not, at 10am.
111
+ // Check if later than specific AM time
112
+ if (today.getHours() >= amTimeToCheck) {
113
+ onlyPm();
114
+ }
115
+ }
116
+ }
117
+ // If none of the above options are true, both time periods are available to the user
118
+ }
119
+ else {
120
+ // Today is any other day than the weekend
121
+ // Check if later than target hour
122
+ // Logic updated on 08-05-2025, #GR-I377 in Sprint
123
+ let targetHour = !!grassProduct && expeditionMethod == 'pickup' ? 12 : 10;
124
+ // If grass or green concrete pickup, and today is Friday, AM stays available until after 16h
125
+ // Logic updated on 17-02-2025, GR-I150 dans Zoho Sprint
126
+ if (todayDay == 5 &&
127
+ (!!grassProduct || (!!concreteOrder && concreteOrder.type == 'green' && expeditionMethod == 'pickup'))) {
128
+ targetHour = 16;
129
+ }
130
+ if (today.getHours() >= targetHour) {
131
+ onlyPm();
132
+ }
133
+ }
134
+ }
135
+ // If order contains samples or is of any other type than grass or concrete
136
+ if ((!!!grassProduct && !!!concreteOrder) || !!isSample || !!isAccessoriesOnly) {
137
+ // Check if later than 10 AM
138
+ if (today.getHours() > 10) {
139
+ onlyPm();
140
+ }
141
+ }
142
+ }
143
+ }
144
+ return {
145
+ deliveryTimes: deliveryTimes.map((t) => ({ label: t, value: t })),
146
+ newSelectedDeliveryTime: newSelectedDeliveryTime ? newSelectedDeliveryTime : undefined
147
+ };
148
+ };
149
+ exports.getAvailableHours = getAvailableHours;
150
+ // Date de dégel (hardcodée, sera modifiée directement dans le code à la demande des clients)
151
+ const isDegel = (dateToCheck) => {
152
+ let date = !!dateToCheck ? (0, moment_1.default)(dateToCheck) : (0, moment_1.default)();
153
+ return date.isBetween('2024-03-04 00:00:01', '2024-04-15 23:59:59', undefined, '[]');
154
+ };
155
+ /**
156
+ * Function getMinDatePicker
157
+ * @description Sets the minimum shipping day for delivery
158
+ */
159
+ const getMinDatePicker = (cartData, grassProduct, concreteOrder, expeditionMethod, isPro, testDate, blockedShippingDates, vracType, isPOS, spaceSchedule) => {
160
+ const cartContainsInstallation = (0, cart_1.checkIfCartContainsType)(cart_2.CartGeneralTypeEnum.INSTALLATION, cartData);
161
+ const cartContainsVrac = (0, cart_1.checkIfCartContainsType)(cart_2.CartGeneralTypeEnum.VRAC, cartData);
162
+ const isAccessoriesOnly = (0, cart_1.checkIfCartContainsType)(cart_2.CartGeneralTypeEnum.ONLY_ACCESSORIES, cartData);
163
+ let minDates = {};
164
+ if (!!testDate && !isPOS) {
165
+ testDate.setHours((0, moment_1.default)().hours());
166
+ }
167
+ let now = testDate || (0, moment_1.default)().toDate();
168
+ let min_date = new Date(now);
169
+ // =======================================================================================
170
+ // #region MIN DATE OFFSET
171
+ const nbDaysOffset = (0, exports.getMinDateOffset)(now, cartContainsInstallation, cartContainsVrac, cartData, grassProduct, concreteOrder, isAccessoriesOnly, expeditionMethod, vracType);
172
+ // #endregion
173
+ // =======================================================================================
174
+ // =======================================================================================
175
+ // #region BLOCKED DAYS/DATES
176
+ const typeToCheck = !!concreteOrder
177
+ ? 'beton'
178
+ : !!grassProduct
179
+ ? 'gazon'
180
+ : !!cartContainsVrac || (!!!isPro && !!vracType)
181
+ ? 'vrac'
182
+ : undefined;
183
+ let dateToCheck = new Date(min_date);
184
+ dateToCheck.setDate(min_date.getDate() + nbDaysOffset);
185
+ let pickupDateSameAsNewDate = false;
186
+ // ---------------------------------------------------------------------------------------
187
+ // Check if space has blocked days
188
+ // NEW!!! - For now, blocked days are hardcoded here. Will be moved to space eventually.
189
+ const blockedDays = {
190
+ vrac: [0],
191
+ beton: [0],
192
+ gazon: [0]
193
+ };
194
+ const getNextAvailableDay = (type) => {
195
+ const dayToCheck = dateToCheck.getDay();
196
+ if (!!blockedDays[type]) {
197
+ // Right now we ignore blocked days on pickup because we check the schedules in the space. If days are added to the blockedDays dictionnary, validate that they still shouldn't apply on pickup
198
+ if (blockedDays[type].includes(dayToCheck) && expeditionMethod !== 'pickup') {
199
+ dateToCheck.setDate(dateToCheck.getDate() + 1);
200
+ return getNextAvailableDay(type);
201
+ }
202
+ }
203
+ if (!!spaceSchedule && expeditionMethod === 'pickup') {
204
+ const storeId = (0, object_1.recursiveCheckObject)(cartData, 'shipping_payload.pickup_store.id');
205
+ if (!!storeId && !!(0, exports.dateIsClosedInSchedule)(storeId, dateToCheck, spaceSchedule)) {
206
+ dateToCheck.setDate(dateToCheck.getDate() + 1);
207
+ return getNextAvailableDay(type);
208
+ }
209
+ }
210
+ min_date = dateToCheck;
211
+ min_date.setHours(0);
212
+ min_date.setMinutes(0);
213
+ min_date.setSeconds(0);
214
+ };
215
+ if (!!typeToCheck) {
216
+ getNextAvailableDay(typeToCheck);
217
+ if (typeToCheck === 'vrac') {
218
+ pickupDateSameAsNewDate = true;
219
+ }
220
+ }
221
+ // ---------------------------------------------------------------------------------------
222
+ // Check if space has blocked dates
223
+ if (!!blockedShippingDates && blockedShippingDates.length && !!typeToCheck && expeditionMethod === 'delivery') {
224
+ const blockedDatesToCheck = blockedShippingDates.find((blockedDate) => blockedDate.cart_type === typeToCheck);
225
+ if (!!blockedDatesToCheck && !!blockedDatesToCheck.dates && !!blockedDatesToCheck.dates.length) {
226
+ const isInBlockedPeriod = blockedDatesToCheck.dates.find((blocked) => {
227
+ return (!!blocked.start_date &&
228
+ !!blocked.end_date &&
229
+ (0, moment_1.default)(dateToCheck).isBetween((0, moment_1.default)((0, data_3.formatDate)(blocked.start_date)), (0, moment_1.default)((0, data_3.formatDate)(blocked.end_date)), 'date', '[]'));
230
+ });
231
+ if (!!isInBlockedPeriod) {
232
+ dateToCheck = (0, moment_1.default)((0, data_3.formatDate)(isInBlockedPeriod.end_date)).add(1, 'days').toDate();
233
+ getNextAvailableDay(typeToCheck);
234
+ let pickup_date = !!pickupDateSameAsNewDate ? dateToCheck : (0, moment_1.default)(min_date).toDate();
235
+ return {
236
+ min_delivery: min_date,
237
+ min_pickup: pickup_date
238
+ };
239
+ }
240
+ }
241
+ }
242
+ // #endregion
243
+ // =======================================================================================
244
+ if (!!!concreteOrder || concreteOrder.type !== 'yellow') {
245
+ min_date = new Date(dateToCheck);
246
+ min_date.setHours(0);
247
+ min_date.setMinutes(0);
248
+ min_date.setSeconds(0);
249
+ let pickup_date = (0, moment_1.default)(min_date).toDate();
250
+ minDates = {
251
+ min_delivery: min_date,
252
+ min_pickup: pickup_date
253
+ };
254
+ }
255
+ return minDates;
256
+ };
257
+ exports.getMinDatePicker = getMinDatePicker;
258
+ const getSamplesMinDateOffset = () => {
259
+ const now = new Date();
260
+ const year = now.getFullYear();
261
+ // December 1st
262
+ const startWinterPeriod = new Date(year, 11, 1); // December == 11
263
+ // March 1st
264
+ const endWinterPeriod = new Date(year + 1, 2, 1); // March == 2
265
+ const isWinterPeriod = (0, moment_1.default)().isBetween((0, moment_1.default)(startWinterPeriod), (0, moment_1.default)(endWinterPeriod), 'day', '[]');
266
+ return isWinterPeriod ? 14 : 7;
267
+ };
268
+ exports.getSamplesMinDateOffset = getSamplesMinDateOffset;
269
+ const getMinDateOffset = (now, cartContainsInstallation, cartContainsVrac, cartData, grassProduct, concreteOrder, isAccessoriesOnly, expeditionMethod, vracType) => {
270
+ const current_hour = now.getHours();
271
+ const current_day = now.getDay();
272
+ let nb_days_offset = 1;
273
+ // Variable to set all grass delays the same as non-speciality grasses (as of now, Kentucky and Prestige).
274
+ // Use this instead of changing all values, in case our clients change their mind later!
275
+ const allGrassDelaysSameAsNonSpecialityGrasses = true;
276
+ // ========================
277
+ // IF INSTALL
278
+ // Install logic adjusted on 01-05-2024 (task #GR7-T429)
279
+ if (!!cartContainsInstallation) {
280
+ // --------------------
281
+ // "Low staff" logic = 96hours delay for first available date
282
+ // switch (current_day) {
283
+ // case 3:
284
+ // nb_days_offset = 5
285
+ // break
286
+ // default:
287
+ // nb_days_offset = 4
288
+ // break
289
+ // }
290
+ // --------------------
291
+ // "Medium staff" logic = 48hours delay for first available date
292
+ // CURRENT logic (active since 01-05-2024)
293
+ switch (current_day) {
294
+ case 5:
295
+ nb_days_offset = 3;
296
+ break;
297
+ default:
298
+ nb_days_offset = 2;
299
+ break;
300
+ }
301
+ // --------------------
302
+ // Regular logic (if fee applies for current year) = 24 hour delay for first available date
303
+ // switch (current_day) {
304
+ // case 5:
305
+ // nb_days_offset = current_hour < 10 ? 1 : 3
306
+ // break
307
+ // case 6:
308
+ // case 0:
309
+ // nb_days_offset = 2
310
+ // break
311
+ // default:
312
+ // nb_days_offset = 1
313
+ // break
314
+ // }
315
+ }
316
+ // ========================
317
+ // IF SAMPLE OR ACCESSORIES ONLY
318
+ else if (cartData.items.find((item) => item.is_sample) || !!isAccessoriesOnly) {
319
+ if (expeditionMethod === 'delivery') {
320
+ nb_days_offset = !!isAccessoriesOnly ? 7 : (0, exports.getSamplesMinDateOffset)();
321
+ }
322
+ else {
323
+ switch (current_day) {
324
+ case 4:
325
+ nb_days_offset = 4;
326
+ break;
327
+ case 5:
328
+ nb_days_offset = current_hour < 10 ? 3 : 4;
329
+ break;
330
+ case 6:
331
+ nb_days_offset = 4;
332
+ break;
333
+ case 0:
334
+ nb_days_offset = 3;
335
+ break;
336
+ default:
337
+ nb_days_offset = 2;
338
+ }
339
+ }
340
+ }
341
+ // ========================
342
+ // IF VRAC PRODUCTS WITH DELIVERY
343
+ else if (expeditionMethod === 'delivery' &&
344
+ !!cartContainsVrac &&
345
+ !!(0, object_1.recursiveCheckObject)(vracType, 'vrac_type') &&
346
+ [products_1.VracTypeEnum.AUTRE_TONNE, products_1.VracTypeEnum.NOBEL_TONNE].includes(vracType.vrac_type)) {
347
+ nb_days_offset = 1;
348
+ }
349
+ // ========================
350
+ // IF BASE GRASS / ALL GRASSES ARE SAME
351
+ else if (!!grassProduct &&
352
+ ((0, products_2.checkIfIsNonSpecialityGrass)(grassProduct.sku, grassProduct.slug) || !!allGrassDelaysSameAsNonSpecialityGrasses)) {
353
+ const amTimeToCheck = !!grassProduct && expeditionMethod == 'pickup' ? 12 : 10;
354
+ // Logic ajusted on 08-05-2025 (task #GR-I377 in Sprint) - If grass & pickup, first check starts at noon. If not, at 10am.
355
+ switch (current_day) {
356
+ case 5:
357
+ nb_days_offset = current_hour < amTimeToCheck ? 1 : current_hour < 16 ? 3 : 3; // earliest is tomorrow if before 10AM, else after tomorrow, not counting the weekend (on fridays)
358
+ // Logic ajusted on 14-02-2025 (task #GR-I151 in Sprint) - New check for between 10h (or 12h if grass&pickup) and 16h
359
+ break;
360
+ case 6:
361
+ nb_days_offset = 3; // earliest is after tomorrow, not counting the weekend (on fridays or saturdays)
362
+ break;
363
+ case 0:
364
+ nb_days_offset = 2; // earliest is after tomorrow, not counting the weekend (on sundays)
365
+ break;
366
+ default:
367
+ nb_days_offset = 1; // earliest is tomorrow
368
+ }
369
+ }
370
+ // ========================
371
+ // IF CONCRETE WITH PICKUP | UNAVAILABLE PRODUCT
372
+ else if (!!concreteOrder &&
373
+ concreteOrder.type === 'green' &&
374
+ !concreteOrder.inStock &&
375
+ expeditionMethod === 'pickup') {
376
+ // 13-08-2025 : Bug GR-I511 - Pickup for concrete not in stock only change the available day
377
+ const amTimeToCheck = 10;
378
+ switch (current_day) {
379
+ case 0:
380
+ nb_days_offset = 2;
381
+ break;
382
+ case 4:
383
+ nb_days_offset = current_hour < amTimeToCheck ? 1 : 4;
384
+ break;
385
+ case 5:
386
+ nb_days_offset = 3;
387
+ break;
388
+ case 6:
389
+ nb_days_offset = current_hour < amTimeToCheck ? 2 : 3;
390
+ break;
391
+ default:
392
+ nb_days_offset = current_hour < amTimeToCheck ? 1 : 2;
393
+ }
394
+ }
395
+ // ========================
396
+ // IF CONCRETE WITH PICKUP | ONLY AVAILABLE PRODUCTS
397
+ else if (!!concreteOrder &&
398
+ concreteOrder.type === 'green' &&
399
+ concreteOrder.inStock &&
400
+ expeditionMethod === 'pickup') {
401
+ nb_days_offset = 0;
402
+ }
403
+ // ========================
404
+ // IF SPECIALITY GRASS
405
+ else if (!!grassProduct && !!!(0, products_2.checkIfIsNonSpecialityGrass)(grassProduct.sku, grassProduct.slug)) {
406
+ switch (current_day) {
407
+ case 5:
408
+ case 6:
409
+ case 0:
410
+ nb_days_offset = 4; // if we are on friday and it's earlier than 10
411
+ break;
412
+ default:
413
+ nb_days_offset = 2; // earliest is after tomorrow
414
+ }
415
+ }
416
+ // ========================
417
+ // IF CONCRETE WITH DELIVERY | ONLY AVAILABLE PRODUCTS
418
+ else if (!!concreteOrder && concreteOrder.type === 'green' && expeditionMethod === 'delivery') {
419
+ switch (current_day) {
420
+ case 0:
421
+ nb_days_offset = 3;
422
+ break;
423
+ case 1:
424
+ case 2:
425
+ case 3:
426
+ nb_days_offset = current_hour < 10 ? 2 : 3;
427
+ break;
428
+ case 4:
429
+ nb_days_offset = current_hour < 10 ? 2 : current_hour < 16 ? 4 : 5;
430
+ // Logic ajusted on 14-02-2025 (task #GR-I151 in Sprint) - New check for between 10h and 16h
431
+ break;
432
+ case 5:
433
+ nb_days_offset = current_hour < 16 ? 4 : 5;
434
+ // Logic ajusted on 14-02-2025 (task #GR-I151 in Sprint) - New check for 16h instead of 10h
435
+ break;
436
+ case 6:
437
+ nb_days_offset = 4;
438
+ break;
439
+ default:
440
+ break;
441
+ }
442
+ }
443
+ // ========================
444
+ // IF ANY PRODUCT WITH DELIVERY THAT DID NOT FIT IN PREVIOUS CATEGORIES
445
+ else if (expeditionMethod === 'delivery') {
446
+ switch (current_day) {
447
+ case 0:
448
+ nb_days_offset = 4;
449
+ break;
450
+ case 1:
451
+ case 2:
452
+ nb_days_offset = current_hour < 10 ? 3 : 4;
453
+ break;
454
+ case 3:
455
+ nb_days_offset = current_hour < 10 ? 3 : 6;
456
+ break;
457
+ case 4:
458
+ case 5:
459
+ nb_days_offset = current_hour < 10 ? 5 : 6;
460
+ break;
461
+ case 6:
462
+ nb_days_offset = 5;
463
+ break;
464
+ default:
465
+ break;
466
+ }
467
+ }
468
+ return nb_days_offset;
469
+ };
470
+ exports.getMinDateOffset = getMinDateOffset;
471
+ /**
472
+ * Function shouldDisableDate
473
+ * @description compares date with blockedDates from DB and blocked days (currently hardcoded in function)
474
+ * @param date - Date to check
475
+ * @param blockedDates - Blocked dates from DB
476
+ * @param expeditionMethod - pickup or shipping
477
+ * @param cartData
478
+ */
479
+ const shouldDisableDate = (date, blockedDates, expeditionMethod, cartData, schedule, selectedStore) => {
480
+ if (!!!cartData)
481
+ return false;
482
+ const typeToCheck = (0, cart_1.getCartType)(cartData);
483
+ // ---------------------------------------------------------------------------------------
484
+ // Blocked days check
485
+ // NEW!!! - For now, blocked days are hardcoded here. Will be moved to space eventually.
486
+ const blockedDays = {
487
+ vrac: [0],
488
+ beton: [0],
489
+ gazon: [0],
490
+ only_accessories: [0],
491
+ sample: [0]
492
+ };
493
+ if (!!!typeToCheck ||
494
+ (!!blockedDays[typeToCheck] && !!blockedDays[typeToCheck].includes(date.getDay()) && expeditionMethod !== 'pickup')) {
495
+ return true;
496
+ }
497
+ // ---------------------------------------------------------------------------------------
498
+ // Blocked dates checks
499
+ if (expeditionMethod !== 'pickup' && !!typeToCheck && !!blockedDates) {
500
+ const sameType = blockedDates.find((blocked) => blocked.cart_type === typeToCheck);
501
+ if (!!sameType && !!sameType.dates) {
502
+ for (let dates of sameType.dates) {
503
+ if (!!dates.start_date &&
504
+ !!dates.end_date &&
505
+ (0, moment_1.default)(date).isBetween((0, moment_1.default)((0, data_3.formatDate)(dates.start_date)), (0, moment_1.default)((0, data_3.formatDate)(dates.end_date)), 'date', '[]'))
506
+ return true;
507
+ }
508
+ }
509
+ }
510
+ const storeId = (0, object_1.recursiveCheckObject)(cartData, 'shipping_payload.pickup_store.id');
511
+ if ((!!storeId || !!selectedStore) && expeditionMethod === 'pickup' && !!schedule) {
512
+ return !!(0, exports.dateIsClosedInSchedule)(!!selectedStore ? selectedStore : storeId, date, schedule);
513
+ }
514
+ return false;
515
+ };
516
+ exports.shouldDisableDate = shouldDisableDate;
517
+ const dateIsClosedInSchedule = (storeId, dateToCheck, spaceSchedule) => {
518
+ var _a;
519
+ const weekdayIndex = dateToCheck.getDay();
520
+ const storeSchedules = spaceSchedule.store_schedules[storeId];
521
+ let isExternal = false;
522
+ // If store schedule exists, check it, if not, set min date to dateToCheck.
523
+ if (!!storeSchedules) {
524
+ let selectedDaySchedule;
525
+ // If periods are activated for the space, check the specific period schedule, if not check the general schedule
526
+ if (!!spaceSchedule.space_periods_active) {
527
+ const year = dateToCheck.getFullYear().toString();
528
+ const periods = (_a = spaceSchedule.year_periods[year]) !== null && _a !== void 0 ? _a : [];
529
+ const matchingPeriod = periods.find((p) => new Date(p.starts_at) <= dateToCheck && dateToCheck <= new Date(p.ends_at));
530
+ if (!!matchingPeriod) {
531
+ const periodSchedule = storeSchedules[matchingPeriod.id];
532
+ if (!!periodSchedule) {
533
+ if (!!periodSchedule.external) {
534
+ isExternal = true;
535
+ }
536
+ const daySchedule = periodSchedule.weekly_schedule[weekdayIndex];
537
+ if (!!daySchedule) {
538
+ selectedDaySchedule = daySchedule;
539
+ }
540
+ }
541
+ }
542
+ }
543
+ // If no schedule found for that day in active period, or periods aren't activated for that space, fall back to general schedule
544
+ // A closed day should NOT enter this if
545
+ // A period with an external schedule should NOT enter this if
546
+ if (!!!isExternal &&
547
+ (!!!selectedDaySchedule ||
548
+ (!!selectedDaySchedule.schedule &&
549
+ !!selectedDaySchedule.open &&
550
+ !!!selectedDaySchedule.schedule.closing_time &&
551
+ !!!selectedDaySchedule.schedule.opening_time))) {
552
+ const generalSchedule = storeSchedules['general'];
553
+ if (!!generalSchedule) {
554
+ if (!!generalSchedule.external) {
555
+ isExternal = true;
556
+ }
557
+ selectedDaySchedule = generalSchedule.weekly_schedule[weekdayIndex];
558
+ }
559
+ }
560
+ // NEW - Returns true here even if isExternal
561
+ if (!!selectedDaySchedule && selectedDaySchedule.open === false) {
562
+ return true;
563
+ }
564
+ }
565
+ let allClosedDays = spaceSchedule.common_closed_days;
566
+ // If schedule for period is external, filter out all common dates since they do not apply
567
+ if (!!isExternal)
568
+ allClosedDays = allClosedDays.filter((d) => d.type != 'common');
569
+ const isClosed = allClosedDays.some((c) => {
570
+ const start = new Date(c.start_date);
571
+ const end = c.end_date ? new Date(c.end_date) : start;
572
+ start.setFullYear(dateToCheck.getFullYear());
573
+ start.setHours(0, 0, 0, 0);
574
+ end.setFullYear(dateToCheck.getFullYear());
575
+ end.setHours(0, 0, 0, 0);
576
+ dateToCheck.setHours(0, 0, 0, 0);
577
+ return c.open === false && dateToCheck >= start && dateToCheck <= end && !!c.associated_stores.includes(storeId);
578
+ });
579
+ return isClosed;
580
+ };
581
+ exports.dateIsClosedInSchedule = dateIsClosedInSchedule;
582
+ /**
583
+ * Function checkIfCartTypeHasBlockedDates
584
+ * @description checks if type of cart corresponds to a blockedDates array and if array has dates defined
585
+ * @param cartData
586
+ * @param blockedDates
587
+ */
588
+ const checkIfCartTypeHasBlockedDates = (cartData, blockedDates) => {
589
+ if (!!!cartData || !!!blockedDates || !!!blockedDates.length)
590
+ return false;
591
+ const cartType = (0, cart_1.getCartType)(cartData);
592
+ const sameType = blockedDates.find((blocked) => blocked.cart_type === cartType);
593
+ if (!!!sameType)
594
+ return false;
595
+ return !!sameType.dates && !!sameType.dates.length;
596
+ };
597
+ exports.checkIfCartTypeHasBlockedDates = checkIfCartTypeHasBlockedDates;
598
+ // #endregion
599
+ // ------------------------------------------------------------------------------------------
600
+ // ------------------------------------------------------------------------------------------
601
+ // #region FEES
602
+ exports.slugsToCheckFromExpeditionFees = {
603
+ pickup: ['frais-preparation-general-beton', 'frais-palette', 'minimum-facturable-commande'],
604
+ shipping: [
605
+ 'livraison-echantillons',
606
+ 'livraison-accessoires',
607
+ 'livraison-beton-accessoires',
608
+ 'livraison-gazon',
609
+ 'frais-de-livraison-vrac',
610
+ 'minimum-facturable-commande',
611
+ products_3.liquidationDeliveryFeeSlug
612
+ ]
613
+ };
614
+ const getPalletQty = (items, orderType, minQteGrassOrder = 0) => {
615
+ const total = (0, sumBy_1.default)(items.map((item) => {
616
+ if (!!!item.other_units ||
617
+ !!item.is_service ||
618
+ !!item.is_sample ||
619
+ (!!orderType &&
620
+ !!['grass'].includes(orderType) &&
621
+ (0, products_2.checkIfIsNonSpecialityGrass)(item.sku, item.parent_slug || '', true) &&
622
+ !!item.is_upsell_of_sku)) {
623
+ return 0;
624
+ }
625
+ const paletteUnit = item.other_units.find((u) => u.unit_slug === 'pal');
626
+ const sellUnitCheck = item.other_units.find((u) => !!u.is_sale_unit);
627
+ let sellUnit = 1;
628
+ if (!!sellUnitCheck) {
629
+ sellUnit = !!sellUnitCheck.fitting_unit ? sellUnitCheck.fitting_unit : 1;
630
+ }
631
+ if (!!!paletteUnit || !!!paletteUnit.fitting_unit) {
632
+ return 0;
633
+ }
634
+ const typeAttr = item.attributes[data_4.AttributesIdEnumGR.TYPE];
635
+ if (!!!typeAttr || !!!typeAttr.length) {
636
+ return 0;
637
+ }
638
+ // If item is an accessory
639
+ if (!!typeAttr && !typeAttr.includes('gazon') && !typeAttr.includes('beton')) {
640
+ return (0, floor_1.default)((item.qte * sellUnit) / paletteUnit.fitting_unit);
641
+ }
642
+ // If is grass and minQteGrassOrder is defined
643
+ if (!!typeAttr.includes('gazon') && !!minQteGrassOrder && item.qte < minQteGrassOrder) {
644
+ return minQteGrassOrder / paletteUnit.fitting_unit;
645
+ }
646
+ return (item.qte * sellUnit) / paletteUnit.fitting_unit;
647
+ }));
648
+ if (orderType === 'concrete') {
649
+ return (0, ceil_1.default)(total);
650
+ }
651
+ return total;
652
+ };
653
+ exports.getPalletQty = getPalletQty;
654
+ // Retourne un nombre de frais de palettes à ajouter au panier selon la vraie quantité de palettes calculées pour les produits de gazon
655
+ const getGrassRoundedPickupPalletFees = (realPalletNumber) => {
656
+ // More than 400 square feet of grass needs another pallet
657
+ const ratio = (0, round_1.default)(400 / 740, 3);
658
+ // Get only the decimals from the real calculated pallet number, if the decimal is bigger than 400 / 740, round up
659
+ const fraction = (0, round_1.default)(realPalletNumber % 1, 3);
660
+ if (fraction >= ratio)
661
+ return (0, ceil_1.default)(realPalletNumber);
662
+ return (0, floor_1.default)(realPalletNumber);
663
+ };
664
+ exports.getGrassRoundedPickupPalletFees = getGrassRoundedPickupPalletFees;
665
+ const getPalletQtyPalletFee = (items, expeditionMethod, isGrass, isMixed) => {
666
+ let totalPalletGrass = 0;
667
+ let totalPalletOther = 0;
668
+ // For this fee specifically, remove all accessories before calculating palQty
669
+ items = items.filter((i) => !(0, products_2.checkIfProductIsOfType)(i, 'accessoire'));
670
+ if (!!isGrass) {
671
+ const grassItemsToCheck = !!isMixed ? items.filter((i) => !!(0, products_2.checkIfProductIsOfType)(i, 'gazon', true)) : items;
672
+ const calculatedPalletsGrass = (0, exports.getPalletQty)(grassItemsToCheck, 'grass');
673
+ totalPalletGrass =
674
+ expeditionMethod === 'pickup'
675
+ ? (0, exports.getGrassRoundedPickupPalletFees)(calculatedPalletsGrass)
676
+ : (0, ceil_1.default)(calculatedPalletsGrass);
677
+ }
678
+ if (!!!isGrass || !!isMixed) {
679
+ const otherItemsToCheck = !!isMixed ? items.filter((i) => !!!(0, products_2.checkIfProductIsOfType)(i, 'gazon', true)) : items;
680
+ totalPalletOther = (0, exports.calculatePalFeeForOtherThanGrass)(otherItemsToCheck);
681
+ }
682
+ const totalPallet = totalPalletGrass + totalPalletOther;
683
+ return totalPallet;
684
+ };
685
+ exports.getPalletQtyPalletFee = getPalletQtyPalletFee;
686
+ const calculatePalFeeForOtherThanGrass = (items) => {
687
+ const total = (0, sumBy_1.default)(items.map((item) => {
688
+ if (!!!item.other_units || !!item.is_service || !!item.is_sample) {
689
+ return 0;
690
+ }
691
+ const exceptions = [
692
+ 'muret-supra-citadin-180',
693
+ 'muret-m-100-serie-moderne-double-face',
694
+ 'muret-ora-double-face',
695
+ 'pas-japonais-grand',
696
+ 'marche-nueva',
697
+ 'marche-aria',
698
+ 'marche-t-200',
699
+ 'marche-solino',
700
+ 'marche-caralina',
701
+ 'marche-rio-15',
702
+ 'marche-appalaches',
703
+ 'marche-citadin',
704
+ 'marche-laurentien',
705
+ 'marche-m-100-serie-moderne',
706
+ 'marche-citadin-180',
707
+ 'marche-ora',
708
+ 'marche-t-100-serie-traditionnelle',
709
+ 'marche-prestige-180'
710
+ ];
711
+ const itemIsException = item.parent_slug && exceptions.includes(item.parent_slug);
712
+ const palUnit = item.other_units.find((u) => u.unit_slug === 'pal');
713
+ const rgUnit = item.other_units.find((u) => u.unit_slug === 'rg');
714
+ const unitUnit = item.other_units.find((u) => !!u.fitting_unit && u.fitting_unit === 1);
715
+ const sellUnitCheck = item.other_units.find((u) => !!u.is_sale_unit);
716
+ let sellUnit = 1;
717
+ if (!!sellUnitCheck) {
718
+ sellUnit = !!sellUnitCheck.fitting_unit ? sellUnitCheck.fitting_unit : 1;
719
+ }
720
+ const typeAttr = item.attributes[data_4.AttributesIdEnumGR.TYPE];
721
+ // --------------------------------------------------
722
+ // 1. If not all units are defined
723
+ // if no palUnit or no typeAttr
724
+ if (!!!palUnit || !!!palUnit.fitting_unit || !!!typeAttr || !!!typeAttr.length) {
725
+ if (!!itemIsException)
726
+ return 1;
727
+ // if no rgUnit, can't calculate pallet amount
728
+ if (!!!rgUnit || !!!rgUnit.fitting_unit) {
729
+ return 0;
730
+ }
731
+ else {
732
+ const nbRang = (item.qte * sellUnit) / rgUnit.fitting_unit;
733
+ // if has quantities but rang amount is lower than 1, return 0
734
+ if (nbRang > 0 && nbRang <= 1) {
735
+ return 0;
736
+ }
737
+ else {
738
+ return 1;
739
+ }
740
+ }
741
+ }
742
+ // --------------------------------------------------
743
+ // 2. If is accessory
744
+ if (!!typeAttr && !typeAttr.includes('gazon') && !typeAttr.includes('beton')) {
745
+ return (0, floor_1.default)((item.qte * sellUnit) / palUnit.fitting_unit);
746
+ }
747
+ const palQty = (item.qte * sellUnit) / (palUnit.fitting_unit || 1);
748
+ const rgQty = !!rgUnit ? (item.qte * sellUnit) / (rgUnit.fitting_unit || 1) : 0;
749
+ const unitQty = !!unitUnit ? (item.qte * sellUnit) / (unitUnit.fitting_unit || 1) : !!sellUnit ? item.qte : 0;
750
+ // --------------------------------------------------
751
+ // 3. Calculate pal quantities
752
+ // RULES:
753
+ // - 1 pal = 1 pal
754
+ // - 1 pal + 1 rang = 1 pal
755
+ // - 1 pal + 2 rang = 2 pal
756
+ // - 1 pal + 1 rang + 1 unité = 2 pals
757
+ // - 1 pal + 1 unité = 1 pal
758
+ // - 0 pal :
759
+ // - If less than or equals 1 rang (or equivalent in units) = 0 pal (excluding exceptions)
760
+ // - More thant 1 rang (or equivalent in units) = 1 pal
761
+ let totalPal = (0, floor_1.default)(palQty);
762
+ const unitsInRg = !!rgUnit ? rgUnit.fitting_unit || 0 : 0;
763
+ const unitsInPal = palUnit.fitting_unit || 0;
764
+ // if qte gives round number of pallets, return totalPal
765
+ if (item.qte / unitsInPal === totalPal)
766
+ return totalPal;
767
+ // if rgQty and rgUnit are defined
768
+ if (!!rgQty && !!rgUnit) {
769
+ const rgInPal = (palUnit.fitting_unit || 1) / (rgUnit.fitting_unit || 1);
770
+ // if palQty is higher than 1 and at least 2 rang extra
771
+ if (palQty >= 1 && (0, ceil_1.default)(rgQty % rgInPal) >= 2) {
772
+ totalPal += 1;
773
+ }
774
+ else {
775
+ if (palQty < 1) {
776
+ if (!!unitQty) {
777
+ // if item is in exception list and at least 1 unit extra
778
+ if (!!itemIsException && unitQty % unitsInPal !== 0) {
779
+ totalPal += 1;
780
+ }
781
+ else if (!!unitsInRg && unitQty > unitsInRg && unitQty / unitsInRg > 1) {
782
+ // if unit count does not equal rang count and total unit count is higher than rang count
783
+ totalPal += 1;
784
+ }
785
+ }
786
+ }
787
+ }
788
+ }
789
+ else {
790
+ if (!!unitQty && !!itemIsException) {
791
+ if (unitQty % unitsInPal !== 0) {
792
+ totalPal += 1;
793
+ }
794
+ }
795
+ }
796
+ return totalPal;
797
+ }));
798
+ return total;
799
+ };
800
+ exports.calculatePalFeeForOtherThanGrass = calculatePalFeeForOtherThanGrass;
801
+ const getMinGrassQte = (_grassProduct, expeditionMethod, _isPro) => {
802
+ let minQteGrassOrder = 0;
803
+ // if (!![kentucky, prestige].includes(grassProduct.sku)) {
804
+ // if (expeditionMethod !== 'pickup') {
805
+ // minQteGrassOrder = !!isPro ? 1480 : 740
806
+ // }
807
+ // } else {
808
+ // // Grass product is Speciality Grass
809
+ // if (expeditionMethod === 'pickup') {
810
+ // minQteGrassOrder = 740
811
+ // } else {
812
+ // minQteGrassOrder = !!isPro ? 1480 : 740
813
+ // }
814
+ // }
815
+ // MODIF AVEC FRAIS 2024 - Même minimum facturable pour tous les gazons, et tous les clients
816
+ // Toujours 0 pour la cueillette (pas de minimum), et 740 en livraison
817
+ if (expeditionMethod != 'pickup') {
818
+ minQteGrassOrder = 740; // 1 pallet
819
+ }
820
+ return minQteGrassOrder;
821
+ };
822
+ exports.getMinGrassQte = getMinGrassQte;
823
+ const getMinQteInstall = (_isPro) => {
824
+ // return !!isPro ? 2220 : 740
825
+ // MODIF AVEC FRAIS 2024 - Même minimum facturable pour tous les clients pour l'installation
826
+ return 740;
827
+ };
828
+ exports.getMinQteInstall = getMinQteInstall;
829
+ const resetAllFeesIfAccessoriesOnly = (currentItems) => {
830
+ const slugsToDelete = [
831
+ 'livraison-gazon',
832
+ 'minimum-facturable-commande',
833
+ 'surcharge-jour-meme-gazon',
834
+ 'livraison-beton-accessoires',
835
+ 'frais-preparation-general-beton',
836
+ 'frais-commande-beton-pas-en-ligne',
837
+ 'frais-preparation',
838
+ 'surcharges-installation-gazon',
839
+ 'surcharges-commandes-gazon',
840
+ 'surcharges-commandes-gazon-debut-fin-saison',
841
+ 'surcharge-gazon-ramassage-hors-ferme',
842
+ 'frais-commande-gazon-pas-en-ligne',
843
+ ...products_3.fuelSurchargeSlugs
844
+ ];
845
+ let itemsToDelete = [];
846
+ for (let i of currentItems) {
847
+ if (!!i.parent_slug && !!slugsToDelete.includes(i.parent_slug))
848
+ itemsToDelete.push(i.sku);
849
+ }
850
+ return itemsToDelete;
851
+ };
852
+ const checkIfShouldApplySameDayGrassFee = (firstDayForExpedition, expeditionMethod, selectedExpeditionDate, testDate // for unit test. To test holiday + hour after 4PM
853
+ ) => {
854
+ // a. Check min date for expedition type (for POS carts)
855
+ const dateToCheck = expeditionMethod === 'pickup' ? firstDayForExpedition.min_pickup : firstDayForExpedition.min_delivery;
856
+ const dateSelectedIsBeforeFirstCalculatedDay = !!dateToCheck && (0, moment_1.default)((0, data_3.formatDate)(selectedExpeditionDate)).isBefore((0, moment_1.default)(dateToCheck), 'date');
857
+ // b. Check if current day is a holiday
858
+ const isHoliday = (0, data_1.getHolidays)().some((h) => (0, moment_1.default)(h).isSame(testDate ? (0, moment_1.default)(testDate) : (0, moment_1.default)(), 'date'));
859
+ // c. Check if current time is after 4PM
860
+ const isAfter4PM = (!!testDate ? (0, moment_1.default)(testDate) : (0, moment_1.default)()).hour() >= 16;
861
+ // d. Check if date selected is tomorrow
862
+ const dateSelectedForExpeditionIsTomorrowOrToday = (0, moment_1.default)(selectedExpeditionDate).isSameOrBefore((0, moment_1.default)().add(1, 'day'), 'date');
863
+ // If date selected is before first calculated date for expedition,
864
+ // or order was created after 4PM/on a holiday and selected date for expedition is the next day,
865
+ // apply fees
866
+ return (!!dateSelectedIsBeforeFirstCalculatedDay ||
867
+ ((!!isHoliday || !!isAfter4PM) && !!dateSelectedForExpeditionIsTomorrowOrToday));
868
+ };
869
+ exports.checkIfShouldApplySameDayGrassFee = checkIfShouldApplySameDayGrassFee;
870
+ const checkForSameGrassDayFee = (isPOS, isPro, totalPallet, grassProduct, selectedExepeditionDate, isReserved) => {
871
+ if (!!isReserved)
872
+ return false;
873
+ return !!selectedExepeditionDate && !!grassProduct && totalPallet >= 4 && (!!isPOS || !!isPro);
874
+ };
875
+ exports.checkForSameGrassDayFee = checkForSameGrassDayFee;
876
+ // Correspond to the qte after which the expedition or installation fee should be reapplied
877
+ // Eg. For each group of 24 pallets of a product, an expedition fee is added to the cart
878
+ exports.expeditionFeePalletTier = 24;
879
+ exports.installationFeePalletTier = 48;
880
+ /**
881
+ * Calculates fees that should be applied to provided cart, and fetches them from database or fee array if provided.
882
+ * Returns the items to add, update and delete, as well as other cart info to set after fees.
883
+ * ** Optimized version possible, where address zones and distance are calculated before and properties are sent directly to function
884
+ * ** Optimized version reverted, logic found in commit here : [#2087b32]{@link https://github.com/ciaoqc/gng-tb-admin-sdk/commit/2087b3207df9e5916a979b8bb255abc2a4c1dac6}
885
+ * @async
886
+ * @param fetchProduct
887
+ * @param getIfAddressIsInsideZones
888
+ * @param getDistanceFromAddress
889
+ * @param cart
890
+ * @param expeditionMethod
891
+ * @param grassProduct
892
+ * @param concreteOrder
893
+ * @param cartContainsInstallation
894
+ * @param cartContainsVrac
895
+ * @param availableVracStoreIDs
896
+ * @param isPro
897
+ * @param addOnePalletToPickup
898
+ * @param cartContainsSample
899
+ * @param saveToShippingPayload
900
+ * @param deliveryAddress
901
+ * @param locale
902
+ * @param expeditionDate
903
+ * @param equipmentPickupOnSite
904
+ * @param cartContainsOnlyAccessories
905
+ * @param pickupStore
906
+ * @param allStores
907
+ * @param customPriceList
908
+ * @param useFeeArray
909
+ */
910
+ const applyFeesToCart = async (fetchProduct, getIfAddressIsInsideZones, getDistanceFromAddress, cart, expeditionMethod, grassProduct, concreteOrder, cartContainsInstallation, cartContainsVrac, availableVracStoreIDs, isPro, addOnePalletToPickup, cartContainsSample, saveToShippingPayload, deliveryAddress, locale, expeditionDate, equipmentPickupOnSite, cartContainsOnlyAccessories, pickupStore, allStores, customPriceList, useFeeArray) => {
911
+ let itemsToAdd = [];
912
+ let itemsToDelete = [];
913
+ let itemsToUpdate = [];
914
+ let newShippingPayload = cart.shipping_payload || {};
915
+ // Pour le minimum facturable de la livraison
916
+ let minQteGrassOrder = 0;
917
+ if (!!grassProduct) {
918
+ minQteGrassOrder = (0, exports.getMinGrassQte)(grassProduct, expeditionMethod, isPro);
919
+ }
920
+ // Vérification du type du cart
921
+ const isPOS = [Cart_1.CartTypeEnum.POS, Cart_1.CartTypeEnum.POS_TRANSACTIONNAL].includes(cart.cart_type);
922
+ // Liquidation cart has its own delivery and preparation fees
923
+ const cartContainsLiquidation = (0, cart_1.checkIfCartContainsType)(cart_2.CartGeneralTypeEnum.LIQUIDATION, cart);
924
+ const isMixed = cart.cart_content_type === Cart_1.CartContentTypeEnum.MIXED;
925
+ let totalPalletOther = 0;
926
+ let totalPalletGrass = 0;
927
+ if (!!concreteOrder) {
928
+ const concreteItemsToCheck = !!isMixed
929
+ ? cart.items.filter((i) => !!!(0, products_2.checkIfProductIsOfType)(i, 'gazon', true))
930
+ : cart.items;
931
+ totalPalletOther = (0, exports.getPalletQty)(concreteItemsToCheck, 'concrete');
932
+ }
933
+ else if (cartContainsLiquidation) {
934
+ // Un panier surplus n'a pas de concreteOrder mais ses palettes doivent compter pour les surcharges de zone
935
+ totalPalletOther = (0, exports.getPalletQty)(cart.items, 'concrete');
936
+ }
937
+ if (!!grassProduct) {
938
+ const grassItemsToCheck = !!isMixed && !!concreteOrder ? cart.items.filter((i) => !!(0, products_2.checkIfProductIsOfType)(i, 'gazon', true)) : cart.items;
939
+ totalPalletGrass = (0, exports.getPalletQty)(grassItemsToCheck, 'grass');
940
+ }
941
+ const totalPallet = totalPalletGrass + totalPalletOther;
942
+ const totalPalletMinQte = (0, exports.getPalletQty)(cart.items, !!concreteOrder ? 'concrete' : !!grassProduct ? 'grass' : undefined, minQteGrassOrder);
943
+ // Pour le minimum facturable de l'installation
944
+ const minQteInstall = (0, exports.getMinQteInstall)(!!isPro);
945
+ // Type de cart (en ligne, en magasin, avec un commis, etc...)
946
+ const cartType = !!isPOS ? 'in_store' : !!cart.clerk_id ? 'with_clerk' : 'online';
947
+ const installAllInclusiveActive = (0, products_2.isInstallAllInclusiveActive)(cartContainsInstallation, isPro, customPriceList);
948
+ // --------------------------------------------------------------------------------------------------
949
+ // #region FRAIS PALETTE
950
+ // --------------------------------------------------------------------------------------------------
951
+ const shouldAddPaletFees = !!!cartContainsInstallation && !!!cartContainsSample && !!!cartContainsVrac;
952
+ if ((!!isMixed || !!shouldAddPaletFees) && (!!isPro || !!!grassProduct) && !!!cartContainsOnlyAccessories) {
953
+ let qtyOfSkuNeeded = (0, exports.getPalletQtyPalletFee)(cart.items, expeditionMethod, !!(0, cart_1.checkIfCartContainsType)(cart_2.CartGeneralTypeEnum.GRASS, cart), isMixed);
954
+ if (!!addOnePalletToPickup && expeditionMethod === 'pickup') {
955
+ qtyOfSkuNeeded += 1;
956
+ }
957
+ if (!!addOnePalletToPickup && !!!useFeeArray && !!saveToShippingPayload) {
958
+ newShippingPayload = Object.assign(Object.assign({}, newShippingPayload), { addOnePalletToPickup: true });
959
+ }
960
+ const productToAdd = await fetchProduct('frais-palette', locale, !!useFeeArray, true);
961
+ if (!!productToAdd && !!productToAdd.declinations) {
962
+ const palletFeeDecli = productToAdd.declinations[0];
963
+ if (!!qtyOfSkuNeeded) {
964
+ itemsToAdd.push(Object.assign(Object.assign({}, productToAdd.declinations[0]), { qte: qtyOfSkuNeeded, parent_slug: productToAdd.slug, is_upsell_of_sku: 'summary', categories: productToAdd.categories }));
965
+ }
966
+ else if (cart.items.some((i) => i.sku === palletFeeDecli.sku)) {
967
+ itemsToDelete.push(palletFeeDecli.sku);
968
+ }
969
+ }
970
+ }
971
+ // #endregion FRAIS PALETTE
972
+ // --------------------------------------------------------------------------------------------------
973
+ // #region COMMANDE GAZON - FRAIS DE LIVRAISON
974
+ // --------------------------------------------------------------------------------------------------
975
+ if (!!grassProduct && !cartContainsLiquidation) {
976
+ if (expeditionMethod === 'delivery') {
977
+ const parentProduct = await fetchProduct('livraison-gazon', locale, !!useFeeArray, true);
978
+ const product3 = parentProduct
979
+ ? parentProduct.declinations.find((decli) => ['17000000T'].includes(decli.sku))
980
+ : undefined;
981
+ const product4_15 = parentProduct
982
+ ? parentProduct.declinations.find((decli) => decli.sku === '170000000')
983
+ : undefined;
984
+ const product16 = parentProduct
985
+ ? parentProduct.declinations.find((decli) => decli.sku === '170000160')
986
+ : undefined;
987
+ const add = (product, qty) => {
988
+ if (!!product) {
989
+ const alreadyToAdd = (0, findIndex_1.default)(itemsToAdd, (i) => i.sku === product.sku);
990
+ if (alreadyToAdd === -1) {
991
+ itemsToAdd.push(Object.assign(Object.assign({}, product), { is_upsell_of_sku: 'summary', qte: qty, parent_slug: 'livraison-gazon' }));
992
+ }
993
+ else {
994
+ itemsToAdd[alreadyToAdd] = Object.assign(Object.assign(Object.assign({}, itemsToAdd[alreadyToAdd]), { is_upsell_of_sku: 'summary', qte: itemsToAdd[alreadyToAdd].qte + qty, parent_slug: 'livraison-gazon' }), (!!parentProduct ? { categories: parentProduct.categories } : {}));
995
+ }
996
+ }
997
+ };
998
+ const addRestQty = (pallets) => {
999
+ if (pallets > 0 && pallets < 4) {
1000
+ add(product3, 1);
1001
+ }
1002
+ if (pallets >= 4 && pallets < 16) {
1003
+ add(product4_15, 1);
1004
+ }
1005
+ if (pallets >= 16) {
1006
+ add(product16, 1);
1007
+ }
1008
+ };
1009
+ if (totalPalletMinQte <= exports.expeditionFeePalletTier) {
1010
+ addRestQty(totalPalletMinQte);
1011
+ }
1012
+ else {
1013
+ const qty4AndMore = (0, floor_1.default)(totalPalletMinQte / exports.expeditionFeePalletTier);
1014
+ const rest = (0, ceil_1.default)(totalPalletMinQte % exports.expeditionFeePalletTier);
1015
+ add(product16, qty4AndMore);
1016
+ addRestQty(rest);
1017
+ }
1018
+ }
1019
+ cart.items
1020
+ .filter((i) => i.parent_slug === 'livraison-gazon')
1021
+ .map((item) => {
1022
+ if (!itemsToAdd.map((i) => i.sku).includes(item.sku) || expeditionMethod === 'pickup') {
1023
+ itemsToDelete.push(item.sku);
1024
+ }
1025
+ return;
1026
+ });
1027
+ }
1028
+ // #endregion COMMANDE GAZON - FRAIS DE LIVRAISON
1029
+ // --------------------------------------------------------------------------------------------------
1030
+ // #region COMMANDE BETON - FRAIS DE LIVRAISON
1031
+ // --------------------------------------------------------------------------------------------------
1032
+ if (!!!cartContainsVrac &&
1033
+ !!!cartContainsSample &&
1034
+ !cartContainsLiquidation &&
1035
+ !!!grassProduct &&
1036
+ !!!cartContainsOnlyAccessories) {
1037
+ if (expeditionMethod === 'delivery') {
1038
+ const parentProduct = await fetchProduct('livraison-beton-accessoires', locale, !!useFeeArray, true);
1039
+ const product1To5 = parentProduct
1040
+ ? parentProduct.declinations.find((decli) => decli.sku === '170060450')
1041
+ : undefined;
1042
+ const product6To11 = parentProduct
1043
+ ? parentProduct.declinations.find((decli) => decli.sku === '170060650')
1044
+ : undefined;
1045
+ const product12AndMore = parentProduct
1046
+ ? parentProduct.declinations.find((decli) => decli.sku === '170060000')
1047
+ : undefined;
1048
+ const add = (product, qty) => {
1049
+ if (!!product) {
1050
+ const alreadyToAdd = (0, findIndex_1.default)(itemsToAdd, (i) => i.sku === product.sku);
1051
+ if (alreadyToAdd === -1) {
1052
+ itemsToAdd.push(Object.assign(Object.assign({}, product), { is_upsell_of_sku: 'summary', parent_slug: 'livraison-beton-accessoires', qte: qty }));
1053
+ }
1054
+ else {
1055
+ itemsToAdd[alreadyToAdd] = Object.assign(Object.assign(Object.assign({}, itemsToAdd[alreadyToAdd]), { is_upsell_of_sku: 'summary', qte: itemsToAdd[alreadyToAdd].qte + qty, parent_slug: 'livraison-beton-accessoires' }), (!!parentProduct ? { categories: parentProduct.categories } : {}));
1056
+ }
1057
+ }
1058
+ };
1059
+ const addRestQty = (pallets) => {
1060
+ switch (true) {
1061
+ case pallets > 0 && pallets <= 5:
1062
+ add(product1To5, 1);
1063
+ return;
1064
+ case pallets > 5 && pallets < 12:
1065
+ add(product6To11, 1);
1066
+ return;
1067
+ case pallets >= 12:
1068
+ add(product12AndMore, 1);
1069
+ return;
1070
+ }
1071
+ };
1072
+ if (totalPalletOther <= exports.expeditionFeePalletTier) {
1073
+ addRestQty(totalPalletOther);
1074
+ }
1075
+ else {
1076
+ const qty4AndMore = (0, floor_1.default)(totalPalletMinQte / exports.expeditionFeePalletTier);
1077
+ const rest = (0, ceil_1.default)(totalPalletOther) % exports.expeditionFeePalletTier;
1078
+ add(product12AndMore, qty4AndMore);
1079
+ addRestQty(rest);
1080
+ }
1081
+ }
1082
+ cart.items
1083
+ .filter((i) => i.parent_slug === 'livraison-beton-accessoires')
1084
+ .map((item) => {
1085
+ if (!itemsToAdd.map((i) => i.sku).includes(item.sku) || expeditionMethod === 'pickup') {
1086
+ itemsToDelete.push(item.sku);
1087
+ }
1088
+ return;
1089
+ });
1090
+ }
1091
+ // #endregion COMMANDE BETON - FRAIS DE LIVRAISON
1092
+ // --------------------------------------------------------------------------------------------------
1093
+ // #region COMMANDE GAZON - MINIMUM FACTURABLE
1094
+ // --------------------------------------------------------------------------------------------------
1095
+ if (!!grassProduct) {
1096
+ // In this case, prestige is included in speciality grasses, since the fee must include kentucky price too
1097
+ const isSpecialityGrass = !!grassProduct && !!!(0, products_2.checkIfIsNonSpecialityGrass)(grassProduct.sku, grassProduct.slug, true);
1098
+ const qtyToAdd = minQteGrassOrder - grassProduct.qte;
1099
+ if (qtyToAdd > 0) {
1100
+ const product = await fetchProduct('minimum-facturable-commande', locale, !!useFeeArray, true);
1101
+ if (!!product) {
1102
+ const decli = product.declinations.find((d) => d.sku === '010010000-M');
1103
+ if (!!decli) {
1104
+ let price = grassProduct.price;
1105
+ if (!!isSpecialityGrass) {
1106
+ const isKentucky = cart.items.find((i) => (0, products_2.checkIfIsNonSpecialityGrass)(i.sku, i.parent_slug || '', true));
1107
+ price = isKentucky ? price + (0, products_4.getLowestPrice)(isKentucky).price.amount : price;
1108
+ }
1109
+ let minGrassQteItem = Object.assign(Object.assign({}, decli), { regular_price: Object.assign(Object.assign({}, decli.regular_price), { amount: price }) });
1110
+ if (!!isPro && !!customPriceList) {
1111
+ minGrassQteItem = (0, g2_1.checkForCustomPriceEquivalent)(Object.assign(Object.assign({}, minGrassQteItem), { price_override: true }), customPriceList);
1112
+ }
1113
+ itemsToAdd.push(Object.assign(Object.assign({}, minGrassQteItem), { is_upsell_of_sku: 'summary', parent_slug: product.slug, price_override: true, qte: qtyToAdd, categories: product.categories }));
1114
+ }
1115
+ }
1116
+ }
1117
+ const minimumBillable = cart.items.find((i) => i.parent_slug === 'minimum-facturable-commande');
1118
+ if (qtyToAdd <= 0 && !!minimumBillable) {
1119
+ itemsToDelete.push(minimumBillable.sku);
1120
+ }
1121
+ }
1122
+ // #endregion COMMANDE GAZON - MINIMUM FACTURABLE
1123
+ // --------------------------------------------------------------------------------------------------
1124
+ // #region COMMANDE GAZON - SURCHARGE JOUR MÊME
1125
+ // --------------------------------------------------------------------------------------------------
1126
+ const sameDayGrassFee = await fetchProduct('surcharge-jour-meme-gazon', locale, !!useFeeArray, true);
1127
+ let decli;
1128
+ if (!!sameDayGrassFee) {
1129
+ decli = sameDayGrassFee.declinations.find((d) => d.sku === '000010990');
1130
+ }
1131
+ if (!!(0, exports.checkForSameGrassDayFee)(isPOS, isPro, totalPalletGrass, grassProduct, expeditionDate, (0, object_1.recursiveCheckObject)(cart.shipping_payload, 'is_reserved'))) {
1132
+ // a. Fetch min date for expedition type (for POS carts)
1133
+ const firstDayForExpedition = (0, exports.getMinDatePicker)(cart, grassProduct, undefined, expeditionMethod || 'delivery', !!isPro, !!cart.created_by ? (0, data_3.formatDate)(cart.created_by.date) : undefined, undefined, undefined, isPOS);
1134
+ // b. Call function to get if fee should be applied
1135
+ const shouldApplySameDayFee = (0, exports.checkIfShouldApplySameDayGrassFee)(firstDayForExpedition, expeditionMethod, expeditionDate);
1136
+ if (!!sameDayGrassFee && !!decli) {
1137
+ if (!!shouldApplySameDayFee) {
1138
+ itemsToAdd.push(Object.assign(Object.assign({}, decli), { is_upsell_of_sku: 'summary', parent_slug: sameDayGrassFee.slug, price_override: true, qte: !!grassProduct ? grassProduct.qte : 1, categories: sameDayGrassFee.categories }));
1139
+ }
1140
+ }
1141
+ }
1142
+ if (!!sameDayGrassFee && !!decli) {
1143
+ if (!!cart.items.some((i) => i.sku === decli.sku)) {
1144
+ itemsToDelete.push(decli.sku);
1145
+ }
1146
+ }
1147
+ // #endregion COMMANDE GAZON - SURCHARGE JOUR MÊME
1148
+ // --------------------------------------------------------------------------------------------------
1149
+ // #region LIVRAISON ÉCHANTILLONS
1150
+ // --------------------------------------------------------------------------------------------------
1151
+ if (!!cartContainsSample) {
1152
+ let removeShippingFee = false;
1153
+ if (expeditionMethod === 'delivery') {
1154
+ let productToAdd = await fetchProduct('livraison-echantillons', locale, !!useFeeArray, true);
1155
+ try {
1156
+ removeShippingFee = await (0, exports.checkIfShouldRemoveSampleShippingFee)(fetchProduct, cart, locale, !!useFeeArray);
1157
+ }
1158
+ catch (e) {
1159
+ console.log('error on checking if should remove sample shipping fee: ', e.toString());
1160
+ }
1161
+ if (!!removeShippingFee) {
1162
+ productToAdd = undefined;
1163
+ }
1164
+ if (!!productToAdd && !!productToAdd.declinations) {
1165
+ itemsToAdd.push(Object.assign(Object.assign({}, productToAdd.declinations[0]), { qte: 1, is_upsell_of_sku: 'summary', parent_slug: productToAdd.slug, categories: productToAdd.categories }));
1166
+ }
1167
+ }
1168
+ const sampleDeliveryFee = cart.items.find((i) => i.parent_slug === 'livraison-echantillons');
1169
+ if ((expeditionMethod === 'pickup' || !!removeShippingFee) && !!sampleDeliveryFee) {
1170
+ itemsToDelete.push(sampleDeliveryFee.sku);
1171
+ }
1172
+ }
1173
+ // #endregion LIVRAISON ÉCHANTILLONS
1174
+ // --------------------------------------------------------------------------------------------------
1175
+ // #region LIVRAISON ACCESSOIRES
1176
+ // --------------------------------------------------------------------------------------------------
1177
+ const cartAccessoriesDeliveryFee = cart.items.find((i) => i.parent_slug === 'livraison-accessoires');
1178
+ if (!!cartContainsOnlyAccessories && !cartContainsLiquidation) {
1179
+ // reset all service fees associated to grass or beton carts, if found
1180
+ itemsToDelete = resetAllFeesIfAccessoriesOnly(cart.items);
1181
+ // check to add delivery fee
1182
+ if (expeditionMethod === 'delivery') {
1183
+ const productToAdd = await fetchProduct('livraison-accessoires', locale, !!useFeeArray, true);
1184
+ if (!!productToAdd && !!productToAdd.declinations) {
1185
+ itemsToAdd.push(Object.assign(Object.assign({}, productToAdd.declinations[0]), { qte: 1, is_upsell_of_sku: 'summary', parent_slug: productToAdd.slug, categories: productToAdd.categories }));
1186
+ }
1187
+ }
1188
+ if (expeditionMethod === 'pickup' && !!cartAccessoriesDeliveryFee) {
1189
+ itemsToDelete.push(cartAccessoriesDeliveryFee.sku);
1190
+ }
1191
+ }
1192
+ else {
1193
+ if (!!cartAccessoriesDeliveryFee) {
1194
+ itemsToDelete.push(cartAccessoriesDeliveryFee.sku);
1195
+ }
1196
+ }
1197
+ // #endregion LIVRAISON ACCESSOIRES
1198
+ // --------------------------------------------------------------------------------------------------
1199
+ // #region SURPLUS D'INVENTAIRE (LIQUIDATION) - FRAIS DE LIVRAISON
1200
+ // --------------------------------------------------------------------------------------------------
1201
+ if (cartContainsLiquidation) {
1202
+ const liquidationPalletQty = (0, exports.getPalletQty)(cart.items, 'concrete');
1203
+ if (expeditionMethod === 'delivery') {
1204
+ const parentProduct = await fetchProduct(products_3.liquidationDeliveryFeeSlug, locale, !!useFeeArray, true);
1205
+ const product1To11 = parentProduct
1206
+ ? parentProduct.declinations.find((decli) => decli.sku === products_3.liquidationDeliveryFeeSku1To11)
1207
+ : undefined;
1208
+ const product12To24 = parentProduct
1209
+ ? parentProduct.declinations.find((decli) => decli.sku === products_3.liquidationDeliveryFeeSku12To24)
1210
+ : undefined;
1211
+ const add = (product, qty) => {
1212
+ if (!!product) {
1213
+ const alreadyToAdd = (0, findIndex_1.default)(itemsToAdd, (i) => i.sku === product.sku);
1214
+ if (alreadyToAdd === -1) {
1215
+ itemsToAdd.push(Object.assign(Object.assign(Object.assign({}, product), { is_upsell_of_sku: 'summary', parent_slug: products_3.liquidationDeliveryFeeSlug, qte: qty }), (!!parentProduct ? { categories: parentProduct.categories } : {})));
1216
+ }
1217
+ else {
1218
+ itemsToAdd[alreadyToAdd] = Object.assign(Object.assign({}, itemsToAdd[alreadyToAdd]), { qte: itemsToAdd[alreadyToAdd].qte + qty });
1219
+ }
1220
+ }
1221
+ };
1222
+ const addRestQty = (pallets) => {
1223
+ switch (true) {
1224
+ case pallets > 0 && pallets < 12:
1225
+ add(product1To11, 1);
1226
+ return;
1227
+ case pallets >= 12:
1228
+ add(product12To24, 1);
1229
+ return;
1230
+ }
1231
+ };
1232
+ if (liquidationPalletQty <= exports.expeditionFeePalletTier) {
1233
+ addRestQty(liquidationPalletQty);
1234
+ }
1235
+ else {
1236
+ add(product12To24, (0, floor_1.default)(liquidationPalletQty / exports.expeditionFeePalletTier));
1237
+ addRestQty(liquidationPalletQty % exports.expeditionFeePalletTier);
1238
+ }
1239
+ }
1240
+ }
1241
+ cart.items
1242
+ .filter((i) => i.parent_slug === products_3.liquidationDeliveryFeeSlug)
1243
+ .forEach((i) => itemsToDelete.push(i.sku));
1244
+ // #endregion SURPLUS D'INVENTAIRE - FRAIS DE LIVRAISON / PRÉPARATION
1245
+ // --------------------------------------------------------------------------------------------------
1246
+ // #region COMMANDE GAZON - SURCHARGE DE PRIX DE GAZON
1247
+ // --------------------------------------------------------------------------------------------------
1248
+ // Les surcharges sur le gazon s'appliquent toujours pour les pros, ou juste dans le cas de commandes d'une palette ou plus pour les clients au détail
1249
+ const shouldApplyFees = !!isPro || totalPalletGrass >= 1;
1250
+ if (!!grassProduct && !cartContainsLiquidation) {
1251
+ const feesToAdd = [];
1252
+ let orderDate = expeditionDate;
1253
+ let pickupStoreId = '';
1254
+ if (!!pickupStore && !!pickupStore.id) {
1255
+ pickupStoreId = pickupStore.id;
1256
+ }
1257
+ else {
1258
+ const shipping_address = cart.shipping_address;
1259
+ if (!!shipping_address) {
1260
+ const pickupStore = allStores.find((store) => store.address.postal_code === shipping_address.address.postal_code);
1261
+ if (!!pickupStore && !!pickupStore.id) {
1262
+ pickupStoreId = pickupStore.id;
1263
+ }
1264
+ }
1265
+ }
1266
+ let surchargesCommandesGazon = undefined;
1267
+ let surchargesCommandesGazonDebutFinSaison = undefined;
1268
+ let surchargesInstallationGazon = undefined;
1269
+ let surchargesInstallationGazonDebutFinSaison = undefined;
1270
+ let surchargesGazonPickupHorsFerme = undefined;
1271
+ let fraisSiCommandePasEnLigne = undefined;
1272
+ try {
1273
+ surchargesCommandesGazon = await fetchProduct('surcharges-commandes-gazon', locale, !!useFeeArray, true);
1274
+ }
1275
+ catch (e) {
1276
+ console.log('error on fetching product: ', e.toString());
1277
+ }
1278
+ try {
1279
+ surchargesCommandesGazonDebutFinSaison = await fetchProduct('surcharges-commandes-gazon-debut-fin-saison', locale, !!useFeeArray, true);
1280
+ }
1281
+ catch (e) {
1282
+ console.log('error on fetching product: ', e.toString());
1283
+ }
1284
+ try {
1285
+ surchargesInstallationGazon = await fetchProduct('surcharges-installation-gazon', locale, !!useFeeArray, true);
1286
+ }
1287
+ catch (e) {
1288
+ console.log('error on fetching product: ', e.toString());
1289
+ }
1290
+ try {
1291
+ surchargesInstallationGazonDebutFinSaison = await fetchProduct('surcharges-installation-gazon-debut-fin-saison', locale, useFeeArray, true);
1292
+ }
1293
+ catch (e) {
1294
+ console.log('error on fetching product: ', e.toString());
1295
+ }
1296
+ try {
1297
+ surchargesGazonPickupHorsFerme = await fetchProduct('surcharge-gazon-ramassage-hors-ferme', locale, !!useFeeArray, true);
1298
+ }
1299
+ catch (e) {
1300
+ console.log('error on fetching product: ', e.toString());
1301
+ }
1302
+ try {
1303
+ fraisSiCommandePasEnLigne =
1304
+ cartType === 'online' || expeditionMethod === 'pickup'
1305
+ ? undefined
1306
+ : await fetchProduct('frais-commande-gazon-pas-en-ligne', locale, !!useFeeArray, true);
1307
+ }
1308
+ catch (e) {
1309
+ console.log('error on fetching product: ', e.toString());
1310
+ }
1311
+ if (!!orderDate) {
1312
+ const addSku = (sku, product) => {
1313
+ const decli = product.declinations.find((i) => i.sku === sku);
1314
+ if (!!decli) {
1315
+ feesToAdd.push(Object.assign(Object.assign({}, decli), { qte: !!product.slug.includes('installation') && grassProduct.qte < minQteInstall
1316
+ ? minQteInstall
1317
+ : (!!product.slug.includes('commandes-gazon') ||
1318
+ ['frais-commande-gazon-pas-en-ligne', 'surcharge-gazon-ramassage-hors-ferme'].includes(product.slug)) &&
1319
+ grassProduct.qte < minQteGrassOrder
1320
+ ? minQteGrassOrder
1321
+ : grassProduct.qte, is_upsell_of_sku: 'summary', parent_slug: product.slug, other_units: decli.other_units }));
1322
+ }
1323
+ };
1324
+ let allOrderFees = [];
1325
+ let allInstallationFees = [];
1326
+ if (!!shouldApplyFees) {
1327
+ // ---------------------------------------------------
1328
+ // #region Si la date de la commande est ...
1329
+ if (!!surchargesCommandesGazon) {
1330
+ // ... un samedi et que la commande est en livraison OU en pickup dans un magasin qui n'est pas rattaché à uen gazonnière
1331
+ if (orderDate.getDay() === 6) {
1332
+ if (expeditionMethod === 'delivery') {
1333
+ allOrderFees.push(['000010400', surchargesCommandesGazon]);
1334
+ }
1335
+ else {
1336
+ if (!!!data_2.grassFarmStores.includes(pickupStoreId)) {
1337
+ allOrderFees.push(['000010400', surchargesCommandesGazon]);
1338
+ }
1339
+ }
1340
+ }
1341
+ // ... un dimanche ou jours fériés officiels
1342
+ // NOTE: seulement pour le frais gazon, celui d'installation s'applique indépendemment plus bas dans la logique
1343
+ if ((0, moment_1.default)(orderDate).day() === 0 ||
1344
+ (0, data_1.getHolidays)().some((date) => (0, moment_1.default)(date).isSame((0, moment_1.default)(orderDate), 'day'))) {
1345
+ allOrderFees = [...allOrderFees, ['000010850', surchargesCommandesGazon]];
1346
+ }
1347
+ // ... dans les vacances de construction
1348
+ const cd = (0, data_1.getContructionHolidays)();
1349
+ if ((0, moment_1.default)(orderDate).isBetween((0, moment_1.default)(cd[0]), (0, moment_1.default)(cd[1]), 'day', '[]')) {
1350
+ allOrderFees = [...allOrderFees, ['000010860', surchargesCommandesGazon]];
1351
+ }
1352
+ // ... en été
1353
+ const summer = (0, data_1.getSummerDate)();
1354
+ if ((0, moment_1.default)(orderDate).isBetween((0, moment_1.default)(summer[0]), (0, moment_1.default)(summer[1]), 'day', '[]')) {
1355
+ allOrderFees = [...allOrderFees, ['000010300', surchargesCommandesGazon]];
1356
+ }
1357
+ }
1358
+ // #endregion
1359
+ // ---------------------------------------------------
1360
+ // ---------------------------------------------------
1361
+ // #region Si la date de commande se trouve entre (inclusif)...
1362
+ // NOTE : les frais d'installation ne doivent seulement s'appliquer pour les clients pros (POS et WEB)
1363
+ const shouldAddGrassSeasonFee = !!surchargesCommandesGazonDebutFinSaison;
1364
+ const shouldAddInstallSeasonFee = !!cartContainsInstallation && !!isPro && !!surchargesInstallationGazonDebutFinSaison;
1365
+ // ...début de la saison au 30 avril
1366
+ if ((0, moment_1.default)(orderDate).isBetween(`${(0, moment_1.default)().format('YYYY')}-03-01`, `${(0, moment_1.default)().format('YYYY')}-04-30`, 'day', '[]')) {
1367
+ if (shouldAddGrassSeasonFee)
1368
+ allOrderFees = [...allOrderFees, ['000010100', surchargesCommandesGazonDebutFinSaison]];
1369
+ if (shouldAddInstallSeasonFee)
1370
+ allInstallationFees.push(['000010600', surchargesInstallationGazonDebutFinSaison]);
1371
+ }
1372
+ // ...15 oct. au 31 oct.
1373
+ if ((0, moment_1.default)(orderDate).isBetween(`${(0, moment_1.default)().format('YYYY')}-10-15`, `${(0, moment_1.default)().format('YYYY')}-10-31`, 'day', '[]')) {
1374
+ if (shouldAddGrassSeasonFee)
1375
+ allOrderFees = [...allOrderFees, ['000010840', surchargesCommandesGazonDebutFinSaison]];
1376
+ if (shouldAddInstallSeasonFee)
1377
+ allInstallationFees.push(['000010940', surchargesInstallationGazonDebutFinSaison]);
1378
+ }
1379
+ //...1er nov. au 14 nov.
1380
+ if ((0, moment_1.default)(orderDate).isBetween(`${(0, moment_1.default)().format('YYYY')}-11-01`, `${(0, moment_1.default)().format('YYYY')}-11-14`, 'day', '[]')) {
1381
+ if (shouldAddGrassSeasonFee)
1382
+ allOrderFees = [...allOrderFees, ['000010700', surchargesCommandesGazonDebutFinSaison]];
1383
+ if (shouldAddInstallSeasonFee)
1384
+ allInstallationFees.push(['000010800', surchargesInstallationGazonDebutFinSaison]);
1385
+ }
1386
+ // ...15 nov. à la fin de la saison
1387
+ if ((0, moment_1.default)(orderDate).isBetween(`${(0, moment_1.default)().format('YYYY')}-11-15`, `${(0, moment_1.default)().format('YYYY')}-12-31`, 'day', '[]')) {
1388
+ if (shouldAddGrassSeasonFee)
1389
+ allOrderFees = [...allOrderFees, ['000010900', surchargesCommandesGazonDebutFinSaison]];
1390
+ if (shouldAddInstallSeasonFee)
1391
+ allInstallationFees.push(['000010950', surchargesInstallationGazonDebutFinSaison]);
1392
+ }
1393
+ // #endregion
1394
+ // ---------------------------------------------------
1395
+ // Si la commande est en pick-up et le magazin n'est pas une gazonnière
1396
+ if (expeditionMethod === 'pickup' && !!surchargesGazonPickupHorsFerme) {
1397
+ if (!!!data_2.grassFarmStores.includes(pickupStoreId)) {
1398
+ allOrderFees = [...allOrderFees, ['000012500', surchargesGazonPickupHorsFerme]];
1399
+ }
1400
+ }
1401
+ }
1402
+ // Si la commande a de l'installation et la date de la commande est un dimanche ou un jour férié
1403
+ if (!!surchargesInstallationGazon &&
1404
+ !!cartContainsInstallation &&
1405
+ ((0, moment_1.default)(orderDate).day() === 0 ||
1406
+ (0, data_1.getHolidays)().some((date) => (0, moment_1.default)(date).isSame((0, moment_1.default)(orderDate), 'day')))) {
1407
+ allInstallationFees.push(['000010750', surchargesInstallationGazon]);
1408
+ }
1409
+ // Si la commande a été faite autrement qu'en ligne ET ne contient pas d'installation (PROS ONLY)
1410
+ if (!!fraisSiCommandePasEnLigne && !!!cartContainsInstallation && !!isPro) {
1411
+ allOrderFees = [...allOrderFees, ['FRSGAZON', fraisSiCommandePasEnLigne]];
1412
+ }
1413
+ allOrderFees.map((fee) => {
1414
+ addSku(fee[0], fee[1]);
1415
+ });
1416
+ allInstallationFees.map((fee) => {
1417
+ addSku(fee[0], fee[1]);
1418
+ });
1419
+ }
1420
+ itemsToAdd = [...itemsToAdd, ...feesToAdd];
1421
+ }
1422
+ if (!!grassProduct || !!isMixed) {
1423
+ cart.items.forEach((i) => {
1424
+ if (!!i.parent_slug &&
1425
+ [
1426
+ 'surcharges-commandes-gazon',
1427
+ 'surcharges-commandes-gazon-debut-fin-saison',
1428
+ 'surcharges-installation-gazon',
1429
+ 'surcharges-installation-gazon-debut-fin-saison',
1430
+ 'surcharge-gazon-ramassage-hors-ferme',
1431
+ 'frais-commande-gazon-pas-en-ligne'
1432
+ ].includes(i.parent_slug)) {
1433
+ itemsToDelete.push(i.sku);
1434
+ }
1435
+ });
1436
+ }
1437
+ // #endregion SURCHARGE DE PRIX DE GAZON
1438
+ // --------------------------------------------------------------------------------------------------
1439
+ // #region SURCHARGE CARBURANT TEMPORAIRE - COÛTS DE PRODUCTION GAZON
1440
+ // 1¢/pi² sur gazon Kentucky, livraison ET cueillette, pro seulement
1441
+ // La surcharge s'applique dès que du Kentucky est présent (directement ou comme gazon base)
1442
+ const isGrassEligibleForFuelSurcharge = cart.items.some((i) => (0, products_2.checkIfIsNonSpecialityGrass)(i.sku, i.parent_slug || '', true));
1443
+ // L'activation/désactivation est contrôlée par l'état draft du produit
1444
+ const fuelGazonProd = !!grassProduct && isGrassEligibleForFuelSurcharge && isPro && !!!cart.is_booking && !cartContainsLiquidation
1445
+ ? await fetchProduct(products_3.fuelSurchargeGazonSlug, locale, !!useFeeArray, true)
1446
+ : undefined;
1447
+ if (!!fuelGazonProd && !!grassProduct) {
1448
+ let fuelGazonDecli = fuelGazonProd.declinations.find((d) => d.sku === products_3.fuelSurchargeGazonSku);
1449
+ if (!!fuelGazonDecli) {
1450
+ if (!!customPriceList) {
1451
+ fuelGazonDecli = (0, g2_1.checkForCustomPriceEquivalent)(fuelGazonDecli, customPriceList);
1452
+ }
1453
+ if (!(0, products_2.shouldHideItemIfRegPriceIs0)(fuelGazonDecli, fuelGazonProd.slug, false)) {
1454
+ itemsToAdd.push(Object.assign(Object.assign({}, fuelGazonDecli), { qte: grassProduct.qte < minQteGrassOrder ? minQteGrassOrder : grassProduct.qte, is_upsell_of_sku: 'summary', parent_slug: fuelGazonProd.slug, categories: fuelGazonProd.categories }));
1455
+ }
1456
+ }
1457
+ }
1458
+ else {
1459
+ cart.items
1460
+ .filter((i) => i.sku === products_3.fuelSurchargeGazonSku)
1461
+ .forEach((i) => itemsToDelete.push(i.sku));
1462
+ }
1463
+ // #endregion SURCHARGE CARBURANT TEMPORAIRE - COÛTS DE PRODUCTION GAZON
1464
+ // --------------------------------------------------------------------------------------------------
1465
+ // #region COMMANDE BÉTON - FRAIS DE PRÉPARATION
1466
+ // --------------------------------------------------------------------------------------------------
1467
+ // Un panier surplus n'a pas de frais de préparation (décision GR du 31 août 2026)
1468
+ if (!!concreteOrder && !cartContainsLiquidation && !!!cartContainsSample && !!!cartContainsOnlyAccessories) {
1469
+ // ----------------------------------------------------------------------------------------------
1470
+ // Frais de préparation général
1471
+ // MODIF FRAIS 2024 - Ajout du frais FP-1 seulement si le panier contient un minimum de 1 palette de produits de béton
1472
+ // Vérifie vraiment que les produits de béton pour la quantité
1473
+ const fraisPreparationGeneralBeton = await fetchProduct('frais-preparation-general-beton', locale, !!useFeeArray, true);
1474
+ const onlyConcretePalQty = (0, exports.getPalletQty)(cart.items.filter((i) => (0, products_2.checkIfProductIsOfType)(i, 'beton', true)));
1475
+ if (!!fraisPreparationGeneralBeton && onlyConcretePalQty >= 1) {
1476
+ const decli = fraisPreparationGeneralBeton.declinations.find((i) => i.sku === 'FP-1');
1477
+ if (!!decli) {
1478
+ itemsToAdd.push(Object.assign(Object.assign({}, decli), { qte: 1, is_upsell_of_sku: 'summary', parent_slug: fraisPreparationGeneralBeton.slug, categories: fraisPreparationGeneralBeton.categories }));
1479
+ }
1480
+ }
1481
+ // ----------------------------------------------------------------------------------------------
1482
+ // Frais si commande pas en ligne/par un commis
1483
+ if (expeditionMethod !== 'pickup' && cartType !== 'online' && !!isPro && !cartContainsLiquidation) {
1484
+ const getFeeAmount = (decli) => {
1485
+ // fee is a percentage of price for each item that isn't a service or fee
1486
+ // percentage is determined by FRSBETON regular_price.value
1487
+ const percent = (0, toNumber_1.default)(decli.regular_price.amount);
1488
+ let amount = 0;
1489
+ for (let item of cart.items) {
1490
+ if (!!item.is_service)
1491
+ continue;
1492
+ if (!!customPriceList) {
1493
+ item = (0, g2_1.checkForCustomPriceEquivalent)(item, customPriceList);
1494
+ }
1495
+ const itemPrice = (0, products_4.getLowestPrice)(item).price.amount;
1496
+ amount += itemPrice * item.qte * percent;
1497
+ }
1498
+ return (0, round_1.default)(amount, 3);
1499
+ };
1500
+ const feeProd = await fetchProduct('frais-commande-beton-pas-en-ligne', locale, !!useFeeArray, true);
1501
+ if (!!feeProd) {
1502
+ const skuToAdd = (feeProd.declinations || []).find((d) => d.sku === 'FRSBETON');
1503
+ if (!!skuToAdd) {
1504
+ itemsToAdd.push(Object.assign(Object.assign({}, skuToAdd), { qte: 1, parent_slug: feeProd.slug, is_upsell_of_sku: 'summary', regular_price: Object.assign(Object.assign({}, skuToAdd.regular_price), { amount: getFeeAmount(skuToAdd), price_type: (0, round_1.default)((0, toNumber_1.default)(skuToAdd.regular_price.amount) * 100, 2).toString() }), price_override: true, categories: feeProd.categories }));
1505
+ }
1506
+ }
1507
+ }
1508
+ else {
1509
+ if (cart.items.some((item) => item.sku === 'FRSBETON')) {
1510
+ itemsToDelete.push('FRSBETON');
1511
+ }
1512
+ }
1513
+ // ----------------------------------------------------------------------------------------------
1514
+ // Frais de préparation si commande contient 4 palettes incomplètes
1515
+ const concreteItems = cart.items.filter((i) => i.attributes[data_4.AttributesIdEnumGR.TYPE] && i.attributes[data_4.AttributesIdEnumGR.TYPE].includes('beton'));
1516
+ let numberOfIncompletePallets = 0;
1517
+ for (const item of concreteItems) {
1518
+ if (!!!item.other_units)
1519
+ continue;
1520
+ const saleUnit = item.other_units.find((unit) => unit.is_sale_unit);
1521
+ const palUnit = item.other_units.find((unit) => unit.unit_slug === 'pal');
1522
+ if (!!!saleUnit || !!!saleUnit.fitting_unit || !!!palUnit || !!!palUnit.fitting_unit)
1523
+ continue;
1524
+ const calculatedPal = saleUnit.fitting_unit * item.qte;
1525
+ const rest = (0, round_1.default)(calculatedPal, 3) % (0, round_1.default)(palUnit.fitting_unit, 3);
1526
+ if (!!rest) {
1527
+ numberOfIncompletePallets++;
1528
+ }
1529
+ }
1530
+ if (numberOfIncompletePallets >= 4) {
1531
+ const surchargesCommandesBeton = await fetchProduct('frais-preparation', locale, !!useFeeArray, true);
1532
+ if (!!surchargesCommandesBeton) {
1533
+ const decli = surchargesCommandesBeton.declinations.find((i) => i.sku === 'FP4');
1534
+ if (!!decli) {
1535
+ itemsToAdd.push(Object.assign(Object.assign({}, decli), { qte: 1, is_upsell_of_sku: 'summary', parent_slug: surchargesCommandesBeton.slug, categories: surchargesCommandesBeton.categories }));
1536
+ }
1537
+ }
1538
+ }
1539
+ else {
1540
+ const prepItem = cart.items.find((item) => item.parent_slug === 'frais-preparation');
1541
+ if (!!prepItem) {
1542
+ itemsToDelete.push(prepItem.sku);
1543
+ }
1544
+ }
1545
+ }
1546
+ else {
1547
+ if (cart.items.some((item) => item.sku === 'FP-1')) {
1548
+ itemsToDelete.push('FP-1');
1549
+ }
1550
+ if (cart.items.some((item) => item.sku === 'FRSBETON')) {
1551
+ itemsToDelete.push('FRSBETON');
1552
+ }
1553
+ const prepItem = cart.items.find((item) => item.parent_slug === 'frais-preparation');
1554
+ if (!!prepItem) {
1555
+ itemsToDelete.push(prepItem.sku);
1556
+ }
1557
+ }
1558
+ // #endregion COMMANDE BÉTON - FRAIS DE PRÉPARATION
1559
+ // --------------------------------------------------------------------------------------------------
1560
+ // #region FRAIS LIVRAISON SELON L'EMPLACEMENT
1561
+ // --------------------------------------------------------------------------------------------------
1562
+ let isOutOfArea = false;
1563
+ if (expeditionMethod === 'delivery' && !!deliveryAddress) {
1564
+ let insideZones = undefined;
1565
+ try {
1566
+ insideZones = await getIfAddressIsInsideZones(deliveryAddress);
1567
+ }
1568
+ catch (e) {
1569
+ console.log('error on fetching zones for address: ', e.toString());
1570
+ }
1571
+ if (!!insideZones && !!Array.isArray(insideZones)) {
1572
+ if (!!insideZones.length && insideZones.includes('zone-gr')) {
1573
+ // =============================================================================================
1574
+ // TOUS TYPES DE COMMANDE
1575
+ // Si une ou plusieurs zones correspondent
1576
+ let productInstallToAdd;
1577
+ if (!!grassProduct) {
1578
+ productInstallToAdd = !!cartContainsInstallation
1579
+ ? await fetchProduct('surcharges-installation-gazon', locale, !!useFeeArray, true)
1580
+ : undefined;
1581
+ }
1582
+ const productToAdd = await fetchProduct('surcharges-commandes-gazon', locale, !!useFeeArray, true);
1583
+ if (insideZones.includes('zone-mtl')) {
1584
+ if (!!productToAdd) {
1585
+ const mtl = productToAdd.declinations.find((i) => i.sku === '170050000');
1586
+ if (!!mtl) {
1587
+ itemsToAdd.push(Object.assign(Object.assign({}, mtl), { qte: (0, ceil_1.default)((0, ceil_1.default)(totalPallet) / exports.expeditionFeePalletTier), is_upsell_of_sku: 'summary', parent_slug: 'surcharges-commandes-gazon', categories: productToAdd.categories }));
1588
+ }
1589
+ }
1590
+ // If Installation ...
1591
+ if (!!grassProduct && !!productInstallToAdd) {
1592
+ const mtlInstall = productInstallToAdd.declinations.find((i) => i.sku === '170055500');
1593
+ if (!!mtlInstall) {
1594
+ itemsToAdd.push(Object.assign(Object.assign({}, mtlInstall), { qte: (0, ceil_1.default)(totalPalletGrass / exports.installationFeePalletTier), is_upsell_of_sku: 'summary', parent_slug: 'surcharges-installation-gazon', categories: productInstallToAdd.categories }));
1595
+ }
1596
+ }
1597
+ }
1598
+ if (insideZones.includes('zone-ontario')) {
1599
+ if (!!productToAdd) {
1600
+ const ontario = productToAdd.declinations.find((i) => i.sku === '170000ONT');
1601
+ if (!!ontario) {
1602
+ itemsToAdd.push(Object.assign(Object.assign({}, ontario), { qte: (0, ceil_1.default)((0, ceil_1.default)(totalPallet) / exports.expeditionFeePalletTier), is_upsell_of_sku: 'summary', parent_slug: 'surcharges-commandes-gazon', categories: productToAdd.categories }));
1603
+ }
1604
+ }
1605
+ // If Installation ...
1606
+ if (!!grassProduct && !!productInstallToAdd) {
1607
+ const ontarioInstall = productInstallToAdd.declinations.find((i) => i.sku === '170033ONT');
1608
+ if (!!ontarioInstall) {
1609
+ itemsToAdd.push(Object.assign(Object.assign({}, ontarioInstall), { qte: (0, ceil_1.default)(totalPalletGrass / exports.installationFeePalletTier), is_upsell_of_sku: 'summary', parent_slug: 'surcharges-installation-gazon', categories: productInstallToAdd.categories }));
1610
+ }
1611
+ }
1612
+ }
1613
+ if (insideZones.includes('zone-ile-orleans')) {
1614
+ if (!!productToAdd) {
1615
+ const ileOrleans = productToAdd.declinations.find((i) => i.sku === '170000418');
1616
+ if (!!ileOrleans) {
1617
+ itemsToAdd.push(Object.assign(Object.assign({}, ileOrleans), { qte: (0, ceil_1.default)((0, ceil_1.default)(totalPallet) / exports.expeditionFeePalletTier), is_upsell_of_sku: 'summary', parent_slug: 'surcharges-commandes-gazon', categories: productToAdd.categories }));
1618
+ }
1619
+ }
1620
+ }
1621
+ // }
1622
+ // =============================================================================================
1623
+ // COMMANDES VRAC
1624
+ // Infos pour la livraison du vrac, vérification faite maintenant dans deux zones
1625
+ if (!!cartContainsVrac) {
1626
+ if (insideZones.includes('zone-vrac') || insideZones.includes('zone-vrac-les-coteaux')) {
1627
+ const deliveryTruckProduct = await fetchProduct('frais-de-livraison-vrac', locale, !!useFeeArray, true);
1628
+ // Fetch de l'adresse du magasin de la zone concernée, pour calculer le prix du frais de livraison
1629
+ const storeIDToCheck = insideZones.includes('zone-vrac') ? 'sainte-julie-nobel' : 'default';
1630
+ const storeAddress = getStoreAddressByID(allStores, storeIDToCheck);
1631
+ // Si le magasin de la zone ne se trouve pas dans le array de magasins disponibles pour les produits de vrac de la commande,
1632
+ // mettre la commande comme hors-zone automatiquement
1633
+ if (!!availableVracStoreIDs && !availableVracStoreIDs.includes(storeIDToCheck)) {
1634
+ isOutOfArea = true;
1635
+ }
1636
+ else if (!!deliveryTruckProduct && !!storeAddress) {
1637
+ let distance = null;
1638
+ try {
1639
+ distance = await getDistanceFromAddress(storeAddress, deliveryAddress);
1640
+ }
1641
+ catch (_) {
1642
+ console.log(_);
1643
+ }
1644
+ if (distance === null) {
1645
+ isOutOfArea = true;
1646
+ }
1647
+ else if (!cartContainsLiquidation) {
1648
+ itemsToAdd = [
1649
+ ...itemsToAdd,
1650
+ ...(0, exports.calculateShippingForVrac)(distance, cart.items, deliveryTruckProduct, itemsToAdd, expeditionDate)
1651
+ ];
1652
+ }
1653
+ }
1654
+ }
1655
+ else {
1656
+ isOutOfArea = true;
1657
+ }
1658
+ }
1659
+ }
1660
+ else {
1661
+ isOutOfArea = true;
1662
+ }
1663
+ }
1664
+ }
1665
+ cart.items.forEach((i) => {
1666
+ if (!!i.parent_slug && ['frais-de-livraison-vrac', 'surcharges-commandes-gazon'].includes(i.parent_slug)) {
1667
+ itemsToDelete.push(i.sku);
1668
+ }
1669
+ });
1670
+ // #endregion FRAIS LIVRAISON SELON L'EMPLACEMENT
1671
+ // --------------------------------------------------------------------------------------------------
1672
+ // #region RAMASSAGE D'ÉQUIPEMENT SUR LE CHANTIER
1673
+ // --------------------------------------------------------------------------------------------------
1674
+ if (!!equipmentPickupOnSite) {
1675
+ // consoleLog({ equipmentPickupOnSite: 'true' })
1676
+ }
1677
+ // #endregion RAMASSAGE D'ÉQUIPEMENT SUR LE CHANTIER
1678
+ // --------------------------------------------------------------------------------------------------
1679
+ // #region FRAIS EXTRA LIVRAISON EN PÉRIODE DE DÉGEL
1680
+ const degelFeeSku = '170000018';
1681
+ if (!!isPro &&
1682
+ expeditionMethod === 'delivery' &&
1683
+ !!!cartContainsSample &&
1684
+ !!!cartContainsVrac &&
1685
+ !!expeditionDate &&
1686
+ !!isDegel(expeditionDate)) {
1687
+ const degelFeeProd = await fetchProduct('frais-livraison-periode-degel', locale, !!useFeeArray, true);
1688
+ if (!!degelFeeProd) {
1689
+ const degelFeeDecli = degelFeeProd.declinations.find((d) => d.sku === degelFeeSku);
1690
+ if (!!degelFeeDecli) {
1691
+ itemsToAdd.push(Object.assign(Object.assign({}, degelFeeDecli), { qte: 1, is_upsell_of_sku: 'summary', parent_slug: degelFeeProd.slug, categories: degelFeeProd.categories }));
1692
+ }
1693
+ }
1694
+ }
1695
+ else {
1696
+ if (!!cart.items.some((i) => i.sku === degelFeeSku)) {
1697
+ itemsToDelete.push(degelFeeSku);
1698
+ }
1699
+ }
1700
+ // #endregion
1701
+ // --------------------------------------------------------------------------------------------------
1702
+ // #region SURCHARGE CARBURANT TEMPORAIRE - LIVRAISON
1703
+ // 95$ par tranche de 24 palettes, pro seulement, pas de booking
1704
+ const fuelLivraisonProd = isPro &&
1705
+ !!!cart.is_booking &&
1706
+ !cartContainsLiquidation &&
1707
+ itemsToAdd.some((i) => !!i.parent_slug &&
1708
+ ['livraison-gazon', 'livraison-beton-accessoires'].includes(i.parent_slug))
1709
+ ? await fetchProduct(products_3.fuelSurchargeLivraisonSlug, locale, !!useFeeArray, true)
1710
+ : undefined;
1711
+ if (!!fuelLivraisonProd) {
1712
+ let fuelLivraisonDecli = fuelLivraisonProd.declinations.find((d) => d.sku === products_3.fuelSurchargeLivraisonSku);
1713
+ if (!!fuelLivraisonDecli) {
1714
+ if (!!customPriceList) {
1715
+ fuelLivraisonDecli = (0, g2_1.checkForCustomPriceEquivalent)(fuelLivraisonDecli, customPriceList);
1716
+ }
1717
+ if (!(0, products_2.shouldHideItemIfRegPriceIs0)(fuelLivraisonDecli, fuelLivraisonProd.slug, false)) {
1718
+ itemsToAdd.push(Object.assign(Object.assign({}, fuelLivraisonDecli), { qte: (0, ceil_1.default)(totalPallet / exports.expeditionFeePalletTier) || 1, is_upsell_of_sku: 'summary', parent_slug: fuelLivraisonProd.slug, categories: fuelLivraisonProd.categories }));
1719
+ }
1720
+ }
1721
+ }
1722
+ else {
1723
+ cart.items
1724
+ .filter((i) => i.sku === products_3.fuelSurchargeLivraisonSku)
1725
+ .forEach((i) => itemsToDelete.push(i.sku));
1726
+ }
1727
+ // #endregion SURCHARGE CARBURANT TEMPORAIRE - LIVRAISON
1728
+ // --------------------------------------------------------------------------------------------------
1729
+ // #region SURCHARGE CARBURANT TEMPORAIRE - MOBILISATION
1730
+ // 95$ par tranche de 48 palettes, pro seulement
1731
+ const fuelMobilisationProd = isPro &&
1732
+ cartContainsInstallation &&
1733
+ !!!cart.is_booking &&
1734
+ !cartContainsLiquidation &&
1735
+ cart.items.some((i) => i.parent_slug === 'frais-de-mobilisation')
1736
+ ? await fetchProduct(products_3.fuelSurchargeMobilisationSlug, locale, !!useFeeArray, true)
1737
+ : undefined;
1738
+ if (!!fuelMobilisationProd) {
1739
+ let fuelMobilisationDecli = fuelMobilisationProd.declinations.find((d) => d.sku === products_3.fuelSurchargeMobilisationSku);
1740
+ if (!!fuelMobilisationDecli) {
1741
+ if (!!customPriceList) {
1742
+ fuelMobilisationDecli = (0, g2_1.checkForCustomPriceEquivalent)(fuelMobilisationDecli, customPriceList);
1743
+ }
1744
+ if (!(0, products_2.shouldHideItemIfRegPriceIs0)(fuelMobilisationDecli, fuelMobilisationProd.slug, false)) {
1745
+ // Utiliser getPalletQtyPalletFee pour aligner sur le même calcul que les autres frais
1746
+ // (gère l'arrondi spécifique livraison vs cueillette de gazon)
1747
+ const palletQtyForFee = (0, exports.getPalletQtyPalletFee)(cart.items, expeditionMethod, true, isMixed);
1748
+ itemsToAdd.push(Object.assign(Object.assign({}, fuelMobilisationDecli), { qte: (0, ceil_1.default)(Math.max(palletQtyForFee, 1) / exports.installationFeePalletTier) || 1, is_upsell_of_sku: 'summary', parent_slug: fuelMobilisationProd.slug, categories: fuelMobilisationProd.categories }));
1749
+ }
1750
+ }
1751
+ }
1752
+ else {
1753
+ cart.items
1754
+ .filter((i) => i.sku === products_3.fuelSurchargeMobilisationSku)
1755
+ .forEach((i) => itemsToDelete.push(i.sku));
1756
+ }
1757
+ // #endregion SURCHARGE CARBURANT TEMPORAIRE - MOBILISATION
1758
+ // --------------------------------------------------------------------------------------------------
1759
+ // #region Gestion d'ajout / delete des frais
1760
+ itemsToDelete = itemsToDelete.filter((i) => !itemsToAdd.map((add) => add.sku).includes(i));
1761
+ itemsToAdd = itemsToAdd
1762
+ .map((item) => {
1763
+ const cartItem = cart.items.find((i) => i.sku === item.sku);
1764
+ if (!!cartItem) {
1765
+ if (cartItem.qte !== item.qte) {
1766
+ itemsToUpdate.push({ sku: item.sku, qte: item.qte });
1767
+ return;
1768
+ }
1769
+ else {
1770
+ return;
1771
+ }
1772
+ }
1773
+ else {
1774
+ // If fee regular price is 0.00$ and item fits criteria, do not add to cart
1775
+ if (!!item.parent_slug &&
1776
+ (0, products_2.shouldHideItemIfRegPriceIs0)(item, item.parent_slug, !!item.is_upsell_of_sku && item.parent_slug.includes('installation'))) {
1777
+ return;
1778
+ }
1779
+ }
1780
+ // When installation all-inclusive, force frais de livraison to 0$
1781
+ return installAllInclusiveActive ? (0, products_2.applyAllInclusiveOverrides)(item) : item;
1782
+ })
1783
+ .filter((i) => !!i);
1784
+ // #endregion Gestion d'ajout / delete des frais
1785
+ // --------------------------------------------------------------------------------------------------
1786
+ // #region SURPLUS D'INVENTAIRE (LIQUIDATION) - LIGNE « VENTE FINALE »
1787
+ const finalSaleInCart = cart.items.find((i) => i.sku === products_3.liquidationFinalSaleSku);
1788
+ if (cartContainsLiquidation && !!!finalSaleInCart) {
1789
+ const finalSaleProduct = await fetchProduct(products_3.liquidationFinalSaleSlug, locale, !!useFeeArray, true);
1790
+ const finalSaleDecli = !!finalSaleProduct
1791
+ ? finalSaleProduct.declinations.find((decli) => decli.sku === products_3.liquidationFinalSaleSku)
1792
+ : undefined;
1793
+ if (!!finalSaleProduct && !!finalSaleDecli) {
1794
+ itemsToAdd.push(Object.assign(Object.assign({}, finalSaleDecli), { qte: 1, is_upsell_of_sku: 'summary', parent_slug: finalSaleProduct.slug, categories: finalSaleProduct.categories }));
1795
+ }
1796
+ }
1797
+ else if (!cartContainsLiquidation && !!finalSaleInCart) {
1798
+ itemsToDelete.push(finalSaleInCart.sku);
1799
+ }
1800
+ // #endregion SURPLUS D'INVENTAIRE (LIQUIDATION) - LIGNE « VENTE FINALE »
1801
+ return {
1802
+ newCart: Object.assign(Object.assign({}, cart), { shipping_payload: newShippingPayload }),
1803
+ itemsToDelete,
1804
+ itemsToUpdate,
1805
+ itemsToAdd,
1806
+ totalPallet,
1807
+ isOutOfArea
1808
+ };
1809
+ };
1810
+ exports.applyFeesToCart = applyFeesToCart;
1811
+ // #endregion
1812
+ // ------------------------------------------------------------------------------------------
1813
+ // ------------------------------------------------------------------------------------------
1814
+ // #region SHIPPING
1815
+ /**
1816
+ * Checks if sample shipping fee should be removed from cart depending on cart items found in cart.
1817
+ * ** Optimized version possible using brand name instead of brand id, removing async check.
1818
+ * ** Optimized version reverted, logic found in commit here : [#2087b32]{@link https://github.com/ciaoqc/gng-tb-admin-sdk/commit/2087b3207df9e5916a979b8bb255abc2a4c1dac6}
1819
+ * @param fetchProduct
1820
+ * @param cart
1821
+ * @param locale
1822
+ * @param useFeeArray
1823
+ */
1824
+ const checkIfShouldRemoveSampleShippingFee = async (fetchProduct, cart, locale, useFeeArray) => {
1825
+ if (!!!cart.items)
1826
+ return false;
1827
+ const currentItems = cart.items.filter((i) => i.is_sample);
1828
+ let currentItemsChecked = [];
1829
+ for (let item of currentItems) {
1830
+ if (!!!item.parent_slug)
1831
+ continue;
1832
+ // 1. Get parent product for brand ID
1833
+ const parentProd = await fetchProduct(item.parent_slug, locale, !!useFeeArray, true);
1834
+ if (!!!parentProd)
1835
+ continue;
1836
+ const brand = parentProd.brand;
1837
+ // 2. Check if item.attributes contains FAMILY attribute with value Tena
1838
+ const isTena = !!item.attributes &&
1839
+ !!item.attributes[data_4.AttributesIdEnumGR.FAMILY] &&
1840
+ !!item.attributes[data_4.AttributesIdEnumGR.FAMILY].includes('tena');
1841
+ // 3. Check if item.attributes.TYPE is grass and is not Kentucky or Prestige (both non-speciality grasses)
1842
+ // const excludedGrass = [`kentucky`, `prestige`]
1843
+ const hasGrassType = (0, products_2.checkIfProductIsOfType)(item, 'gazon');
1844
+ const isExcludedGrass = (0, products_2.checkIfIsNonSpecialityGrass)(item.sku, item.parent_slug);
1845
+ const isGrass = !!hasGrassType && !!!isExcludedGrass;
1846
+ const valuesToCheck = {
1847
+ brand: !!brand ? brand : '',
1848
+ isTena: isTena,
1849
+ isGrass: isGrass
1850
+ };
1851
+ currentItemsChecked.push(valuesToCheck);
1852
+ }
1853
+ if (!!currentItemsChecked.length) {
1854
+ const allIncludedBrandsNoTena = currentItemsChecked.filter((item) => !!item.brand && !!data_2.includedFreeShippingBrands.includes(item.brand) && !!!item.isTena);
1855
+ const allGrass = currentItemsChecked.filter((item) => !!item.isGrass);
1856
+ // 3. count all items with included brands and check if length === currentItems.length
1857
+ // if true, remove shipping cost (set productToAdd undefined)
1858
+ if (currentItems.length === allIncludedBrandsNoTena.length || currentItems.length === allGrass.length) {
1859
+ return true;
1860
+ }
1861
+ else {
1862
+ // 4. add IncludedBrandsNoTena + isGrass lengths and check if equals currentItems.length
1863
+ // if true, remove shipping cost (set productToAdd undefined)
1864
+ const added = allIncludedBrandsNoTena.length + allGrass.length;
1865
+ if (added === currentItems.length) {
1866
+ return true;
1867
+ }
1868
+ }
1869
+ }
1870
+ return false;
1871
+ };
1872
+ exports.checkIfShouldRemoveSampleShippingFee = checkIfShouldRemoveSampleShippingFee;
1873
+ const calculateShippingForVrac = (distance = 0, cartItems, deliveryTruckProduct, currentItemsToAdd, deliveryDate) => {
1874
+ let itemsToAdd = [...currentItemsToAdd];
1875
+ const allVracItems = cartItems.filter((i) => (0, products_2.checkIfProductIsOfType)(i, 'vrac'));
1876
+ for (const vracItem of allVracItems) {
1877
+ const totalTons = vracItem.qte;
1878
+ const isInDegelPeriod = !!isDegel(deliveryDate);
1879
+ const volumeTons = [
1880
+ {
1881
+ min: 1,
1882
+ max: 4
1883
+ },
1884
+ {
1885
+ min: 4,
1886
+ max: isInDegelPeriod ? 11 : 15
1887
+ },
1888
+ {
1889
+ min: isInDegelPeriod ? 11 : 15,
1890
+ max: isInDegelPeriod ? 16 : 20
1891
+ },
1892
+ {
1893
+ min: isInDegelPeriod ? 16 : 20,
1894
+ max: isInDegelPeriod ? 19 : 24
1895
+ },
1896
+ {
1897
+ min: isInDegelPeriod ? 19 : 24,
1898
+ max: isInDegelPeriod ? 24 : 30
1899
+ }
1900
+ ];
1901
+ const checkTons = (tons) => {
1902
+ let skuToAdd = '';
1903
+ switch (true) {
1904
+ case tons <= volumeTons[0].max:
1905
+ switch (true) {
1906
+ case distance >= 0 && distance < 15:
1907
+ skuToAdd = '170000615';
1908
+ break;
1909
+ case distance >= 15 && distance < 30:
1910
+ skuToAdd = '170000630';
1911
+ break;
1912
+ case distance >= 30:
1913
+ skuToAdd = '170000660';
1914
+ break;
1915
+ }
1916
+ tons = -1;
1917
+ break;
1918
+ case tons > volumeTons[1].min && tons <= volumeTons[1].max:
1919
+ switch (true) {
1920
+ case distance >= 0 && distance < 15:
1921
+ skuToAdd = '170001015';
1922
+ break;
1923
+ case distance >= 15 && distance < 30:
1924
+ skuToAdd = '170001030';
1925
+ break;
1926
+ case distance >= 30:
1927
+ skuToAdd = '170001060';
1928
+ break;
1929
+ }
1930
+ tons = -1;
1931
+ break;
1932
+ case tons > volumeTons[2].min && tons <= volumeTons[2].max:
1933
+ switch (true) {
1934
+ case distance >= 0 && distance < 15:
1935
+ skuToAdd = '170001215';
1936
+ break;
1937
+ case distance >= 15 && distance < 30:
1938
+ skuToAdd = '170001230';
1939
+ break;
1940
+ case distance >= 30:
1941
+ skuToAdd = '170001260';
1942
+ break;
1943
+ }
1944
+ tons = -1;
1945
+ break;
1946
+ case tons > volumeTons[3].min && tons <= volumeTons[3].max:
1947
+ switch (true) {
1948
+ case distance >= 0 && distance < 15:
1949
+ skuToAdd = '170002015';
1950
+ break;
1951
+ case distance >= 15 && distance < 30:
1952
+ skuToAdd = '170002030';
1953
+ break;
1954
+ case distance >= 30:
1955
+ skuToAdd = '170002060';
1956
+ break;
1957
+ }
1958
+ tons = -1;
1959
+ break;
1960
+ case tons > volumeTons[4].min:
1961
+ switch (true) {
1962
+ case distance >= 0 && distance < 15:
1963
+ skuToAdd = '170003015';
1964
+ break;
1965
+ case distance >= 15 && distance < 30:
1966
+ skuToAdd = '170003030';
1967
+ break;
1968
+ case distance >= 30:
1969
+ skuToAdd = '170003060';
1970
+ break;
1971
+ }
1972
+ tons = tons - volumeTons[4].max;
1973
+ break;
1974
+ default:
1975
+ tons = -1;
1976
+ }
1977
+ const decliToAdd = deliveryTruckProduct.declinations.find((d) => d.sku === skuToAdd);
1978
+ if (!!decliToAdd) {
1979
+ if (!!itemsToAdd.find((item) => item.sku === decliToAdd.sku)) {
1980
+ const index = itemsToAdd.findIndex((item) => item.sku === decliToAdd.sku);
1981
+ itemsToAdd[index] = Object.assign(Object.assign({}, itemsToAdd[index]), { qte: itemsToAdd[index].qte + 1 });
1982
+ }
1983
+ else {
1984
+ itemsToAdd.push(Object.assign(Object.assign({}, decliToAdd), { parent_slug: 'frais-de-livraison-vrac', qte: 1, is_upsell_of_sku: 'summary', categories: deliveryTruckProduct.categories }));
1985
+ }
1986
+ }
1987
+ if (tons > 0) {
1988
+ checkTons(tons);
1989
+ }
1990
+ };
1991
+ checkTons(totalTons);
1992
+ }
1993
+ return itemsToAdd;
1994
+ };
1995
+ exports.calculateShippingForVrac = calculateShippingForVrac;
1996
+ const getStoresForVracProdShipping = (inventoryItem) => {
1997
+ let availability = {};
1998
+ for (let vracStore of data_2.vracShippingStores) {
1999
+ const sameInInventory = inventoryItem.inventories.find((i) => i.store_id == vracStore);
2000
+ availability[vracStore] = !!sameInInventory && !!!sameInInventory.unavailable_in_store;
2001
+ }
2002
+ return availability;
2003
+ };
2004
+ exports.getStoresForVracProdShipping = getStoresForVracProdShipping;
2005
+ const getStoreAddressByID = (allStores, storeID) => {
2006
+ const sameStore = allStores.find((s) => s.id == storeID);
2007
+ return !!sameStore ? sameStore.address : undefined;
2008
+ };
2009
+ // #endregion
2010
+ // ------------------------------------------------------------------------------------------
2011
+ // ------------------------------------------------------------------------------------------
2012
+ // #region VALIDATION
2013
+ /**
2014
+ * Function checkIfCartExpired
2015
+ * @description checks if cart expired using the updated_at date stored in the shipping_payload
2016
+ * @param cartData
2017
+ * @param grassProduct
2018
+ * @param concreteOrder
2019
+ * @param isPro
2020
+ * @param options.blocked_shipping_dates
2021
+ * @param options.vracType
2022
+ * @param options.chosenPaymentType
2023
+ * @param options.forceCheckForCartTypes
2024
+ */
2025
+ const checkIfCartExpired = (cartData, grassProduct, concreteOrder, isPro, options = {}) => {
2026
+ // ######################################################################################
2027
+ // #region TESTS
2028
+ // ----------------------------------------------------------
2029
+ // 1) Is same day after 10
2030
+ // const test1 = {
2031
+ // now: moment().set('hours', 11).toDate(),
2032
+ // updated_last: moment().set('hours', 9).toDate(),
2033
+ // time: 'AM',
2034
+ // selected_date: moment().add(4, 'day').toDate()
2035
+ // }
2036
+ // 2) Is same day after 10 but with AM still possible
2037
+ // const test2 = {
2038
+ // now: moment().set({ day: 6, hours: 11 }).toDate(),
2039
+ // updated_last: moment().set({ day: 6, hours: 9 }).toDate(),
2040
+ // time: 'AM',
2041
+ // selected_date: moment().set('day', 9).toDate()
2042
+ // }
2043
+ // const now = test2.now
2044
+ // const updated_last = test2.updated_last
2045
+ // const time = test2.time
2046
+ // const selected_date = test2.selected_date
2047
+ //
2048
+ // #endregion
2049
+ // ######################################################################################
2050
+ const isPOS = Cart_1.CartTypeEnum.WEB != cartData.cart_type;
2051
+ const isSample = (0, cart_1.checkIfCartContainsType)(cart_2.CartGeneralTypeEnum.SAMPLE, cartData);
2052
+ const isAccessoriesOnly = (0, cart_1.checkIfCartContainsType)(cart_2.CartGeneralTypeEnum.ONLY_ACCESSORIES, cartData);
2053
+ // const cartContainsInstallation = checkIfCartContainsType(CartGeneralTypeEnum.INSTALLATION, cartData)
2054
+ // 1. Check if it is normal for selected date to be undefined / expired
2055
+ const selectedDate = !!cartData.shipping_payload && !!cartData.shipping_payload.delivery_or_pickup_date
2056
+ ? (0, data_3.formatDate)(cartData.shipping_payload.delivery_or_pickup_date)
2057
+ : undefined;
2058
+ const noDeliveryDateIsNormal = (0, exports.checkIfNoDeliveryDateIsNormal)(cartData, concreteOrder) ||
2059
+ (!!options.chosenPaymentType && ['depot'].includes(options.chosenPaymentType));
2060
+ const shouldForceCheck = (options.forceCheckForCartTypes || []).some((t) => (0, cart_1.checkIfCartContainsType)(t, cartData));
2061
+ // If force check property sent, check event if !!noDeliveryDateIsNormal
2062
+ if (!!noDeliveryDateIsNormal && !shouldForceCheck) {
2063
+ return false;
2064
+ }
2065
+ else if (!!!selectedDate) {
2066
+ return true;
2067
+ }
2068
+ // 2. Check date depending on when cart was last updated
2069
+ const now = (0, moment_1.default)().toDate();
2070
+ const updated_last = !!cartData.shipping_payload && !!cartData.shipping_payload.updated_at
2071
+ ? (0, data_3.formatDate)(cartData.shipping_payload.updated_at)
2072
+ : (0, moment_1.default)().toDate();
2073
+ const time = !!cartData.shipping_payload && !!cartData.shipping_payload.delivery_period
2074
+ ? cartData.shipping_payload.delivery_period
2075
+ : 'PM';
2076
+ const minDates = (0, exports.getMinDatePicker)(cartData, grassProduct, concreteOrder, !!cartData.is_pickup ? 'pickup' : 'delivery', !!isPro, updated_last, options.blocked_shipping_dates, options.vracType, isPOS);
2077
+ const currentMinDate = !!cartData.is_pickup ? minDates.min_pickup : minDates.min_delivery;
2078
+ const ok_hours = (0, exports.getAvailableHours)(currentMinDate, selectedDate, grassProduct, concreteOrder, (!!cartData.is_pickup ? 'pickup' : 'delivery'), time, isPro, isSample, isAccessoriesOnly, updated_last);
2079
+ return (!!updated_last &&
2080
+ (((0, moment_1.default)(selectedDate).isSameOrBefore(now, 'day') && !!!(0, moment_1.default)(currentMinDate).isSame(now, 'day')) ||
2081
+ (0, moment_1.default)(now).isAfter(updated_last, 'day') ||
2082
+ (0, moment_1.default)(currentMinDate).isAfter(selectedDate, 'day') ||
2083
+ (updated_last.getHours() < 10 &&
2084
+ now.getHours() >= 10 &&
2085
+ time === 'AM' &&
2086
+ !!ok_hours.deliveryTimes.every((d) => d.value == 'PM'))));
2087
+ };
2088
+ exports.checkIfCartExpired = checkIfCartExpired;
2089
+ const checkIfNoDeliveryDateIsNormal = (cartData, concreteOrder, checkForInputShown) => {
2090
+ const isAccessoriesOnly = (0, cart_1.checkIfCartContainsType)(cart_2.CartGeneralTypeEnum.ONLY_ACCESSORIES, cartData);
2091
+ const isSample = (0, cart_1.checkIfCartContainsType)(cart_2.CartGeneralTypeEnum.SAMPLE, cartData);
2092
+ return ((!!!checkForInputShown && !!cartData.shipping_payload && !!cartData.shipping_payload.isOutOfArea) ||
2093
+ (!!concreteOrder && concreteOrder.type !== 'green') ||
2094
+ ((!!isAccessoriesOnly || !!isSample) && !!!cartData.is_pickup));
2095
+ };
2096
+ exports.checkIfNoDeliveryDateIsNormal = checkIfNoDeliveryDateIsNormal;
2097
+ // #endregion
2098
+ // ------------------------------------------------------------------------------------------
2018
2099
  //# sourceMappingURL=expedition.js.map