addio-admin-sdk 1.7.131 → 1.7.132

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