addio-admin-sdk 1.7.103 → 1.7.104

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 (323) hide show
  1. package/dist/Interfaces/Attribute/index.d.ts +1 -0
  2. package/dist/Interfaces/CMS/index.d.ts +3 -0
  3. package/dist/Interfaces/CMS/index.js +3 -0
  4. package/dist/Interfaces/CMS/index.js.map +1 -1
  5. package/dist/Interfaces/Cart/index.js +6 -2
  6. package/dist/Interfaces/Cart/index.js.map +1 -1
  7. package/dist/Interfaces/CartReservedQuantities/index.d.ts +2 -0
  8. package/dist/Interfaces/Customer/IStoreCredit.d.ts +1 -0
  9. package/dist/Interfaces/Customer/index.d.ts +7 -0
  10. package/dist/Interfaces/Customer/index.js +7 -0
  11. package/dist/Interfaces/Customer/index.js.map +1 -1
  12. package/dist/Interfaces/Declination/index.js +8 -2
  13. package/dist/Interfaces/Declination/index.js.map +1 -1
  14. package/dist/Interfaces/Email/IEmail.js +7 -3
  15. package/dist/Interfaces/Email/IEmail.js.map +1 -1
  16. package/dist/Interfaces/G2/index.js +2 -0
  17. package/dist/Interfaces/G2/index.js.map +1 -1
  18. package/dist/Interfaces/Indexed/Product/index.d.ts +3 -0
  19. package/dist/Interfaces/Indexed/Product/index.js +43 -2
  20. package/dist/Interfaces/Indexed/Product/index.js.map +1 -1
  21. package/dist/Interfaces/Menu/index.d.ts +11 -0
  22. package/dist/Interfaces/Product/IImportProduct.js +94 -3
  23. package/dist/Interfaces/Product/IImportProduct.js.map +1 -1
  24. package/dist/Interfaces/Product/IInventoryItem.d.ts +11 -27
  25. package/dist/Interfaces/Product/IInventoryItem.js +13 -4
  26. package/dist/Interfaces/Product/IInventoryItem.js.map +1 -1
  27. package/dist/Interfaces/Product/IPricing.js +6 -0
  28. package/dist/Interfaces/Product/IPricing.js.map +1 -1
  29. package/dist/Interfaces/Product/index.d.ts +8 -0
  30. package/dist/Interfaces/Product/index.js +8 -0
  31. package/dist/Interfaces/Product/index.js.map +1 -1
  32. package/dist/Interfaces/PromiseToPurchase/IIndexedBankUsed.js +1 -1
  33. package/dist/Interfaces/PromiseToPurchase/IIndexedBankUsed.js.map +1 -1
  34. package/dist/Interfaces/Rules/IDiscountRule.d.ts +18 -0
  35. package/dist/Interfaces/Rules/IDiscountRule.js +19 -0
  36. package/dist/Interfaces/Rules/IDiscountRule.js.map +1 -1
  37. package/dist/Interfaces/Services/IService.d.ts +4 -0
  38. package/dist/Interfaces/Shipping/Shiptime/order.js +23 -0
  39. package/dist/Interfaces/Shipping/Shiptime/order.js.map +1 -1
  40. package/dist/Interfaces/Space/index.d.ts +8 -0
  41. package/dist/Interfaces/Space/index.js +9 -0
  42. package/dist/Interfaces/Space/index.js.map +1 -1
  43. package/dist/Interfaces/TCG/index.d.ts +12 -1
  44. package/dist/Interfaces/TCG/index.js +11 -0
  45. package/dist/Interfaces/TCG/index.js.map +1 -1
  46. package/dist/Interfaces/TransferRequest/index.js +3 -0
  47. package/dist/Interfaces/TransferRequest/index.js.map +1 -1
  48. package/dist/constants/services.js +1 -0
  49. package/dist/constants/services.js.map +1 -1
  50. package/dist/index.d.ts +18 -0
  51. package/dist/index.js +24 -0
  52. package/dist/index.js.map +1 -1
  53. package/dist/lib/Attribute/index.js +43 -0
  54. package/dist/lib/Attribute/index.js.map +1 -1
  55. package/dist/lib/BGJob/index.js +5 -1
  56. package/dist/lib/BGJob/index.js.map +1 -1
  57. package/dist/lib/Booking/index.d.ts +15 -0
  58. package/dist/lib/Booking/index.js +20 -0
  59. package/dist/lib/Booking/index.js.map +1 -1
  60. package/dist/lib/Brand/index.d.ts +9 -0
  61. package/dist/lib/Brand/index.js +18 -0
  62. package/dist/lib/Brand/index.js.map +1 -1
  63. package/dist/lib/Cart/index.d.ts +99 -0
  64. package/dist/lib/Cart/index.js +498 -9
  65. package/dist/lib/Cart/index.js.map +1 -1
  66. package/dist/lib/CartReservedQuantities/index.d.ts +29 -0
  67. package/dist/lib/CartReservedQuantities/index.js +41 -0
  68. package/dist/lib/CartReservedQuantities/index.js.map +1 -1
  69. package/dist/lib/Catalogue/index.d.ts +6 -0
  70. package/dist/lib/Catalogue/index.js +9 -0
  71. package/dist/lib/Catalogue/index.js.map +1 -1
  72. package/dist/lib/Category/index.d.ts +6 -0
  73. package/dist/lib/Category/index.js +15 -0
  74. package/dist/lib/Category/index.js.map +1 -1
  75. package/dist/lib/Class/index.d.ts +4 -0
  76. package/dist/lib/Class/index.js +8 -0
  77. package/dist/lib/Class/index.js.map +1 -1
  78. package/dist/lib/Customer/index.d.ts +12 -0
  79. package/dist/lib/Customer/index.js +13 -0
  80. package/dist/lib/Customer/index.js.map +1 -1
  81. package/dist/lib/Declination/index.js +2 -0
  82. package/dist/lib/Declination/index.js.map +1 -1
  83. package/dist/lib/Discount/index.d.ts +9 -0
  84. package/dist/lib/Discount/index.js +23 -0
  85. package/dist/lib/Discount/index.js.map +1 -1
  86. package/dist/lib/ElasticSearch/index.d.ts +5 -0
  87. package/dist/lib/ElasticSearch/index.js +5 -0
  88. package/dist/lib/ElasticSearch/index.js.map +1 -1
  89. package/dist/lib/Elavon/index.js +5 -0
  90. package/dist/lib/Elavon/index.js.map +1 -1
  91. package/dist/lib/Email/AbandonedCartEmail.d.ts +8 -0
  92. package/dist/lib/Email/AbandonedCartEmail.js +8 -0
  93. package/dist/lib/Email/AbandonedCartEmail.js.map +1 -1
  94. package/dist/lib/Email/AccountConfirmationEmail.d.ts +8 -0
  95. package/dist/lib/Email/AccountConfirmationEmail.js +8 -0
  96. package/dist/lib/Email/AccountConfirmationEmail.js.map +1 -1
  97. package/dist/lib/Email/AdminOrderConfirmationEmail.d.ts +8 -0
  98. package/dist/lib/Email/AdminOrderConfirmationEmail.js +8 -0
  99. package/dist/lib/Email/AdminOrderConfirmationEmail.js.map +1 -1
  100. package/dist/lib/Email/ApplicationEmail.d.ts +8 -0
  101. package/dist/lib/Email/ApplicationEmail.js +8 -0
  102. package/dist/lib/Email/ApplicationEmail.js.map +1 -1
  103. package/dist/lib/Email/BackInStockEmail.d.ts +8 -0
  104. package/dist/lib/Email/BackInStockEmail.js +8 -0
  105. package/dist/lib/Email/BackInStockEmail.js.map +1 -1
  106. package/dist/lib/Email/ContactEmail.d.ts +8 -0
  107. package/dist/lib/Email/ContactEmail.js +8 -0
  108. package/dist/lib/Email/ContactEmail.js.map +1 -1
  109. package/dist/lib/Email/CustomerBookingAdminEmail.d.ts +8 -0
  110. package/dist/lib/Email/CustomerBookingAdminEmail.js +8 -0
  111. package/dist/lib/Email/CustomerBookingAdminEmail.js.map +1 -1
  112. package/dist/lib/Email/CustomerBookingEmail.d.ts +8 -0
  113. package/dist/lib/Email/CustomerBookingEmail.js +8 -0
  114. package/dist/lib/Email/CustomerBookingEmail.js.map +1 -1
  115. package/dist/lib/Email/OrderConfirmationEmail.d.ts +8 -0
  116. package/dist/lib/Email/OrderConfirmationEmail.js +8 -0
  117. package/dist/lib/Email/OrderConfirmationEmail.js.map +1 -1
  118. package/dist/lib/Email/OrderDenounciationEmail.d.ts +8 -0
  119. package/dist/lib/Email/OrderDenounciationEmail.js +8 -0
  120. package/dist/lib/Email/OrderDenounciationEmail.js.map +1 -1
  121. package/dist/lib/Email/OrderSampleEmail.d.ts +8 -0
  122. package/dist/lib/Email/OrderSampleEmail.js +8 -0
  123. package/dist/lib/Email/OrderSampleEmail.js.map +1 -1
  124. package/dist/lib/Email/OtherTypeEmails.d.ts +8 -0
  125. package/dist/lib/Email/OtherTypeEmails.js +8 -0
  126. package/dist/lib/Email/OtherTypeEmails.js.map +1 -1
  127. package/dist/lib/Email/PasswordResetEmail.d.ts +8 -0
  128. package/dist/lib/Email/PasswordResetEmail.js +8 -0
  129. package/dist/lib/Email/PasswordResetEmail.js.map +1 -1
  130. package/dist/lib/Email/PhotoShootEmail.d.ts +8 -0
  131. package/dist/lib/Email/PhotoShootEmail.js +8 -0
  132. package/dist/lib/Email/PhotoShootEmail.js.map +1 -1
  133. package/dist/lib/Email/PickUpConfirmation.d.ts +8 -0
  134. package/dist/lib/Email/PickUpConfirmation.js +8 -0
  135. package/dist/lib/Email/PickUpConfirmation.js.map +1 -1
  136. package/dist/lib/Email/ShippingConfirmation.d.ts +8 -0
  137. package/dist/lib/Email/ShippingConfirmation.js +8 -0
  138. package/dist/lib/Email/ShippingConfirmation.js.map +1 -1
  139. package/dist/lib/Email/WelcomeEmail.d.ts +8 -0
  140. package/dist/lib/Email/WelcomeEmail.js +8 -0
  141. package/dist/lib/Email/WelcomeEmail.js.map +1 -1
  142. package/dist/lib/Email/index.d.ts +8 -0
  143. package/dist/lib/Email/index.js +8 -0
  144. package/dist/lib/Email/index.js.map +1 -1
  145. package/dist/lib/ExternalService/Ebay.d.ts +12 -0
  146. package/dist/lib/ExternalService/Ebay.js +22 -0
  147. package/dist/lib/ExternalService/Ebay.js.map +1 -1
  148. package/dist/lib/Indexed/IndexedCart.js +5 -0
  149. package/dist/lib/Indexed/IndexedCart.js.map +1 -1
  150. package/dist/lib/Indexed/Product.js +50 -0
  151. package/dist/lib/Indexed/Product.js.map +1 -1
  152. package/dist/lib/Inventory/index.d.ts +59 -0
  153. package/dist/lib/Inventory/index.js +157 -9
  154. package/dist/lib/Inventory/index.js.map +1 -1
  155. package/dist/lib/Invoice/index.d.ts +11 -0
  156. package/dist/lib/Invoice/index.js +11 -0
  157. package/dist/lib/Invoice/index.js.map +1 -1
  158. package/dist/lib/MarketplacePublication/index.js +308 -0
  159. package/dist/lib/MarketplacePublication/index.js.map +1 -1
  160. package/dist/lib/Menu/index.js +2 -0
  161. package/dist/lib/Menu/index.js.map +1 -1
  162. package/dist/lib/Order/index.d.ts +20 -0
  163. package/dist/lib/Order/index.js +23 -0
  164. package/dist/lib/Order/index.js.map +1 -1
  165. package/dist/lib/Org/index.d.ts +41 -0
  166. package/dist/lib/Org/index.js +41 -0
  167. package/dist/lib/Org/index.js.map +1 -1
  168. package/dist/lib/PandaPay/index.js +6 -0
  169. package/dist/lib/PandaPay/index.js.map +1 -1
  170. package/dist/lib/Paysafe/index.js +1 -0
  171. package/dist/lib/Paysafe/index.js.map +1 -1
  172. package/dist/lib/Product/index.d.ts +25 -0
  173. package/dist/lib/Product/index.js +55 -1
  174. package/dist/lib/Product/index.js.map +1 -1
  175. package/dist/lib/PromiseToPurchase/index.d.ts +72 -0
  176. package/dist/lib/PromiseToPurchase/index.js +79 -0
  177. package/dist/lib/PromiseToPurchase/index.js.map +1 -1
  178. package/dist/lib/PurchaseOrder/index.d.ts +11 -0
  179. package/dist/lib/PurchaseOrder/index.js +12 -0
  180. package/dist/lib/PurchaseOrder/index.js.map +1 -1
  181. package/dist/lib/Service/index.d.ts +8 -0
  182. package/dist/lib/Service/index.js +8 -0
  183. package/dist/lib/Service/index.js.map +1 -1
  184. package/dist/lib/Shipment/index.js +13 -0
  185. package/dist/lib/Shipment/index.js.map +1 -1
  186. package/dist/lib/Slider/index.d.ts +6 -0
  187. package/dist/lib/Slider/index.js +6 -0
  188. package/dist/lib/Slider/index.js.map +1 -1
  189. package/dist/lib/Space/index.d.ts +178 -0
  190. package/dist/lib/Space/index.js +495 -6
  191. package/dist/lib/Space/index.js.map +1 -1
  192. package/dist/lib/Supplier/index.js +5 -0
  193. package/dist/lib/Supplier/index.js.map +1 -1
  194. package/dist/lib/Tags/index.js +5 -0
  195. package/dist/lib/Tags/index.js.map +1 -1
  196. package/dist/lib/TransferRequest/index.d.ts +178 -0
  197. package/dist/lib/TransferRequest/index.js +236 -4
  198. package/dist/lib/TransferRequest/index.js.map +1 -1
  199. package/dist/lib/User/index.d.ts +54 -0
  200. package/dist/lib/User/index.js +101 -21
  201. package/dist/lib/User/index.js.map +1 -1
  202. package/dist/lib/baseService.js +26 -0
  203. package/dist/lib/baseService.js.map +1 -1
  204. package/dist/rules/GR/constants/data.js +22 -0
  205. package/dist/rules/GR/constants/data.js.map +1 -1
  206. package/dist/rules/GR/constants/products.d.ts +3 -0
  207. package/dist/rules/GR/constants/products.js +16 -0
  208. package/dist/rules/GR/constants/products.js.map +1 -1
  209. package/dist/rules/GR/interfaces/data.js +7 -1
  210. package/dist/rules/GR/interfaces/data.js.map +1 -1
  211. package/dist/rules/GR/utils/cart.d.ts +41 -0
  212. package/dist/rules/GR/utils/cart.js +107 -1
  213. package/dist/rules/GR/utils/cart.js.map +1 -1
  214. package/dist/rules/GR/utils/data.js +4 -1
  215. package/dist/rules/GR/utils/data.js.map +1 -1
  216. package/dist/rules/GR/utils/expedition.d.ts +69 -0
  217. package/dist/rules/GR/utils/expedition.js +399 -11
  218. package/dist/rules/GR/utils/expedition.js.map +1 -1
  219. package/dist/rules/GR/utils/g2.d.ts +33 -0
  220. package/dist/rules/GR/utils/g2.js +135 -3
  221. package/dist/rules/GR/utils/g2.js.map +1 -1
  222. package/dist/rules/GR/utils/invoices.d.ts +27 -0
  223. package/dist/rules/GR/utils/invoices.js +41 -0
  224. package/dist/rules/GR/utils/invoices.js.map +1 -1
  225. package/dist/rules/GR/utils/products.d.ts +161 -0
  226. package/dist/rules/GR/utils/products.js +272 -1
  227. package/dist/rules/GR/utils/products.js.map +1 -1
  228. package/dist/rules/GR/utils/upsells.d.ts +32 -0
  229. package/dist/rules/GR/utils/upsells.js +32 -0
  230. package/dist/rules/GR/utils/upsells.js.map +1 -1
  231. package/dist/services/database/DatabaseService.d.ts +84 -0
  232. package/dist/services/database/DatabaseService.js +85 -0
  233. package/dist/services/database/DatabaseService.js.map +1 -1
  234. package/dist/services/database/FirebaseProvider.js +17 -0
  235. package/dist/services/database/FirebaseProvider.js.map +1 -1
  236. package/dist/services/database/NotFirebaseProvider.d.ts +14 -0
  237. package/dist/services/database/NotFirebaseProvider.js +19 -0
  238. package/dist/services/database/NotFirebaseProvider.js.map +1 -1
  239. package/dist/services/g2/G2OrderSlip.d.ts +7 -0
  240. package/dist/services/g2/G2OrderSlip.js +18 -0
  241. package/dist/services/g2/G2OrderSlip.js.map +1 -1
  242. package/dist/services/g2/utils.d.ts +10 -0
  243. package/dist/services/g2/utils.js +189 -3
  244. package/dist/services/g2/utils.js.map +1 -1
  245. package/dist/services/logs/index.d.ts +3 -0
  246. package/dist/services/logs/index.js +6 -1
  247. package/dist/services/logs/index.js.map +1 -1
  248. package/dist/services/products/BaseClass.js +2 -0
  249. package/dist/services/products/BaseClass.js.map +1 -1
  250. package/dist/services/products/TCGService.js +17 -1
  251. package/dist/services/products/TCGService.js.map +1 -1
  252. package/dist/services/products/utils.d.ts +22 -0
  253. package/dist/services/products/utils.js +50 -0
  254. package/dist/services/products/utils.js.map +1 -1
  255. package/dist/utils/anonymisation.d.ts +24 -0
  256. package/dist/utils/anonymisation.js +30 -0
  257. package/dist/utils/anonymisation.js.map +1 -1
  258. package/dist/utils/aws.d.ts +22 -0
  259. package/dist/utils/aws.js +28 -0
  260. package/dist/utils/aws.js.map +1 -1
  261. package/dist/utils/booking.d.ts +8 -0
  262. package/dist/utils/booking.js +9 -0
  263. package/dist/utils/booking.js.map +1 -1
  264. package/dist/utils/cart.d.ts +81 -0
  265. package/dist/utils/cart.js +172 -9
  266. package/dist/utils/cart.js.map +1 -1
  267. package/dist/utils/context.js +2 -2
  268. package/dist/utils/context.js.map +1 -1
  269. package/dist/utils/currency.js +31 -1
  270. package/dist/utils/currency.js.map +1 -1
  271. package/dist/utils/data.js +2 -0
  272. package/dist/utils/data.js.map +1 -1
  273. package/dist/utils/discount.d.ts +118 -0
  274. package/dist/utils/discount.js +178 -1
  275. package/dist/utils/discount.js.map +1 -1
  276. package/dist/utils/file-admin.js +1 -0
  277. package/dist/utils/file-admin.js.map +1 -1
  278. package/dist/utils/file.js +9 -1
  279. package/dist/utils/file.js.map +1 -1
  280. package/dist/utils/firebase-admin.d.ts +9 -0
  281. package/dist/utils/firebase-admin.js +12 -0
  282. package/dist/utils/firebase-admin.js.map +1 -1
  283. package/dist/utils/firebase.d.ts +17 -0
  284. package/dist/utils/firebase.js +17 -0
  285. package/dist/utils/firebase.js.map +1 -1
  286. package/dist/utils/inventories.d.ts +52 -0
  287. package/dist/utils/inventories.js +77 -2
  288. package/dist/utils/inventories.js.map +1 -1
  289. package/dist/utils/locale.d.ts +9 -0
  290. package/dist/utils/locale.js +9 -0
  291. package/dist/utils/locale.js.map +1 -1
  292. package/dist/utils/mailchimp.js +36 -0
  293. package/dist/utils/mailchimp.js.map +1 -1
  294. package/dist/utils/mathUtils.js +9 -0
  295. package/dist/utils/mathUtils.js.map +1 -1
  296. package/dist/utils/object.d.ts +19 -0
  297. package/dist/utils/object.js +21 -3
  298. package/dist/utils/object.js.map +1 -1
  299. package/dist/utils/products.d.ts +7 -0
  300. package/dist/utils/products.js +9 -0
  301. package/dist/utils/products.js.map +1 -1
  302. package/dist/utils/promiseToPurchase.d.ts +32 -0
  303. package/dist/utils/promiseToPurchase.js +34 -0
  304. package/dist/utils/promiseToPurchase.js.map +1 -1
  305. package/dist/utils/prosprsearch.d.ts +15 -0
  306. package/dist/utils/prosprsearch.js +15 -0
  307. package/dist/utils/prosprsearch.js.map +1 -1
  308. package/dist/utils/sdc.js +7 -0
  309. package/dist/utils/sdc.js.map +1 -1
  310. package/dist/utils/searchIndexes.d.ts +37 -0
  311. package/dist/utils/searchIndexes.js +37 -0
  312. package/dist/utils/searchIndexes.js.map +1 -1
  313. package/dist/utils/string.js +7 -6
  314. package/dist/utils/string.js.map +1 -1
  315. package/dist/utils/tools.d.ts +4 -0
  316. package/dist/utils/tools.js +4 -0
  317. package/dist/utils/tools.js.map +1 -1
  318. package/dist/utils/transferRequests.d.ts +24 -0
  319. package/dist/utils/transferRequests.js +24 -0
  320. package/dist/utils/transferRequests.js.map +1 -1
  321. package/dist/utils/update.js +12 -0
  322. package/dist/utils/update.js.map +1 -1
  323. package/package.json +1 -1
@@ -1,4 +1,5 @@
1
1
  "use strict";
2
+ //#region IMPORTS
2
3
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
4
  if (k2 === undefined) k2 = k;
4
5
  var desc = Object.getOwnPropertyDescriptor(m, k);
@@ -107,7 +108,14 @@ const IExternalService_1 = require("../../Interfaces/Space/IExternalService");
107
108
  const utils_1 = require("../../services/products/utils");
108
109
  const Menu_1 = __importDefault(require("../../lib/Menu"));
109
110
  const Note_1 = __importDefault(require("../Note"));
111
+ //#endregion
112
+ /**
113
+ * Class Space
114
+ * A Space represent a company.
115
+ */
110
116
  class Space {
117
+ //#endregion
118
+ //#region CONSTRUCTOR
111
119
  constructor(space, user, space_ref) {
112
120
  this.getRef = () => this._space_ref;
113
121
  this.initCurrencies = async () => {
@@ -125,6 +133,11 @@ class Space {
125
133
  throw _e;
126
134
  }
127
135
  };
136
+ //#endregion
137
+ //#region SPACE
138
+ /**
139
+ * Create the actual space
140
+ */
128
141
  this.create = async () => {
129
142
  try {
130
143
  const newSpaceDoc = await DatabaseService_1.default.addDocument(this._space_ref.path, Object.assign({}, this._space));
@@ -136,6 +149,10 @@ class Space {
136
149
  throw `Error while creating the new space: ${error}`;
137
150
  }
138
151
  };
152
+ /**
153
+ * Update current space with a partial space pass as parameters.
154
+ * @param updates Updates to be made on the space - Partial<Space>
155
+ */
139
156
  this.update = async (updates) => {
140
157
  try {
141
158
  this._space = Object.assign(Object.assign({}, this._space), updates);
@@ -199,9 +216,13 @@ class Space {
199
216
  this.listenOnChange = (callback) => {
200
217
  return DatabaseService_1.default.registerListener((values) => callback(values), DatabaseService_1.default.addToPath(this._space_ref.path, this._space_ref.id));
201
218
  };
219
+ //#endregion
220
+ //#region SPACE - PREFERENCES - CUSTOMERS
202
221
  this._getAllCustomerGroups = () => {
203
222
  return !!this.data().customer_groups ? this.data().customer_groups : [];
204
223
  };
224
+ //#endregion
225
+ //#region SPACE - PREFERENCES - SHIPPING
205
226
  this._updateShippingFee = async (forProps, value) => {
206
227
  this._space = Object.assign(Object.assign({}, this._space), { transport_preferences: Object.assign(Object.assign({}, this._space.transport_preferences), { [forProps]: value }) });
207
228
  return await DatabaseService_1.default.saveDocument(this._space_ref.path, this._space_ref.id, 0, {
@@ -241,6 +262,8 @@ class Space {
241
262
  };
242
263
  this._setShippingAsProduct = async (value) => {
243
264
  this._space = Object.assign(Object.assign({}, this._space), { transport_preferences: Object.assign(Object.assign({}, this._space.transport_preferences), { shipping_as_product: value }) });
265
+ // If shipping_as_product is set to true,
266
+ // save all discounts applied to shipping with draft: true
244
267
  if (!!value) {
245
268
  try {
246
269
  const allDiscounts = await this.discountRules.get();
@@ -500,9 +523,13 @@ class Space {
500
523
  return [];
501
524
  return transport_preferences.predefined_envelops;
502
525
  };
526
+ //#endregion
527
+ //#region SPACE - PREFERENCES - PRODUCTS
503
528
  this._getAllProductPreferences = () => {
504
529
  return this.data().product_preferences;
505
530
  };
531
+ //#endregion
532
+ //#region SPACE - OPTIONS
506
533
  this._getOptions = () => {
507
534
  const options = this.data().space_options || (0, Space_1.getDefaultSpaceOptions)();
508
535
  return options;
@@ -521,6 +548,8 @@ class Space {
521
548
  const allOptions = this._getOptions();
522
549
  return (0, object_1.recursiveCheckObject)(allOptions, path);
523
550
  };
551
+ //#endregion
552
+ //#region SPACE - STORES
524
553
  this._getAllStores = () => {
525
554
  return this.data().stores_warehouses;
526
555
  };
@@ -545,7 +574,10 @@ class Space {
545
574
  ]
546
575
  });
547
576
  };
577
+ //#endregion
578
+ //#region SPACE - EXTERNAL SERVICES
548
579
  this._getExternalServices = async () => {
580
+ //const servicesSnap = await this._space_ref.collection('external_services').get()
549
581
  const servicesSnap = await DatabaseService_1.default.getDocuments(DatabaseService_1.default.addToPath(this._space_ref.path, this._space_ref.id + '/external_services'));
550
582
  if (servicesSnap.length)
551
583
  return [];
@@ -587,6 +619,11 @@ class Space {
587
619
  const currentExternalServices = (_c = this.data().external_services) !== null && _c !== void 0 ? _c : [];
588
620
  return currentExternalServices.filter((s) => (!!s.is_active || !!returnIfInactive) && !!s[query.field] && s[query.field] === query.value);
589
621
  };
622
+ /**
623
+ * Fetch the external service for the name provided
624
+ * @param serviceName
625
+ * @param returnInactiveService Optionnal, defaults to false. Must be set if service should be returned even if it is inactive
626
+ */
590
627
  this._getSpecificServiceByName = (serviceName, returnInactiveService = false) => {
591
628
  const serviceQuery = this._fetchServices({ field: 'external_service_name', operator: '==', value: serviceName });
592
629
  if (!!!serviceQuery.length)
@@ -621,6 +658,9 @@ class Space {
621
658
  return false;
622
659
  }
623
660
  };
661
+ /**
662
+ * Check if external_value fields should be shown for space
663
+ */
624
664
  this._showExternalValueFieldsForSpace = () => {
625
665
  const spaceID = this._space.id;
626
666
  switch (true) {
@@ -638,6 +678,10 @@ class Space {
638
678
  return;
639
679
  }
640
680
  };
681
+ /**
682
+ * Get array of field data nesessary to show space's external_values per objet type
683
+ * @param objType The object type to check for external_values
684
+ */
641
685
  this._getExternalFieldsToShowForPageType = (objType) => {
642
686
  const allTypesForSpace = this._showExternalValueFieldsForSpace();
643
687
  if (!!!allTypesForSpace || allTypesForSpace.pages.every((t) => t !== objType))
@@ -714,6 +758,8 @@ class Space {
714
758
  return [];
715
759
  }
716
760
  };
761
+ //#endregion
762
+ //#region TAXES
717
763
  this._getAllTaxes = async () => {
718
764
  return await Tax_1.default.getAllTaxes();
719
765
  };
@@ -726,9 +772,13 @@ class Space {
726
772
  throw new Error(`Can't find tax for code ${taxCode}`);
727
773
  return Object.assign(Object.assign({}, tax), { id: taxReq.id });
728
774
  };
775
+ //#endregion
776
+ //#region CONSENT
729
777
  this._getMostRecentConsentForm = async () => {
730
778
  return await Consent_1.default.getMostRecentConsent();
731
779
  };
780
+ //#endregion
781
+ //#region BRANDS
732
782
  this._brandsListener = (callback, _options) => {
733
783
  if (!!!this._user)
734
784
  throw 'Invalid or unauthenticated user';
@@ -804,6 +854,8 @@ class Space {
804
854
  (0, console_1.errorMessage)(`Error while creating new brand: ${error}`);
805
855
  }
806
856
  };
857
+ //#endregion
858
+ //#region BLOG ARTICLES
807
859
  this._getBlogArticles = async () => {
808
860
  if (!!!this._user)
809
861
  throw 'Invalid or unauthenticated user';
@@ -821,6 +873,8 @@ class Space {
821
873
  return [];
822
874
  }
823
875
  };
876
+ //#endregion
877
+ //#region BLOG AUTHORS
824
878
  this._getBlogAuthors = async () => {
825
879
  if (!!!this._user)
826
880
  throw 'Invalid or unauthenticated user';
@@ -838,6 +892,8 @@ class Space {
838
892
  return [];
839
893
  }
840
894
  };
895
+ //#endregion
896
+ //#region BLOG CATEGORIES
841
897
  this._getBlogCategories = async () => {
842
898
  if (!!!this._user)
843
899
  throw 'Invalid or unauthenticated user';
@@ -874,6 +930,8 @@ class Space {
874
930
  return '';
875
931
  }
876
932
  };
933
+ //#endregion
934
+ //#region BLOG KEYWORDS
877
935
  this._getBlogKeywords = async () => {
878
936
  if (!!!this._user)
879
937
  throw 'Invalid or unauthenticated user';
@@ -891,6 +949,8 @@ class Space {
891
949
  return [];
892
950
  }
893
951
  };
952
+ //#endregion
953
+ //#region CATALOGUES
894
954
  this._getCatalogues = async () => {
895
955
  if (!!!this._user)
896
956
  throw 'Invalid or unauthenticated user';
@@ -943,10 +1003,13 @@ class Space {
943
1003
  }
944
1004
  ]
945
1005
  });
1006
+ // If no docs returned, return true
946
1007
  if (!!!query || !!!query.length)
947
1008
  return true;
1009
+ // If only one doc returned, and is same ID as current catalogue, return true
948
1010
  if (query.length === 1 && query[0].id === id)
949
1011
  return true;
1012
+ // Else, slug already exists
950
1013
  return false;
951
1014
  }
952
1015
  catch (e) {
@@ -993,6 +1056,8 @@ class Space {
993
1056
  return false;
994
1057
  }
995
1058
  };
1059
+ //#endregion
1060
+ //#region CATEGORIES
996
1061
  this._categoriesListener = (callback, options) => {
997
1062
  if (!!!this._user)
998
1063
  throw 'Invalid or unauthenticated user';
@@ -1016,6 +1081,12 @@ class Space {
1016
1081
  if (this._user === undefined)
1017
1082
  throw 'Invalid or unauthenticated user';
1018
1083
  try {
1084
+ /*let call = this._space_ref.collection('categories')
1085
+ if (!!options) {
1086
+ call = constructFirebaseCallWithOptions(call, options)
1087
+ }
1088
+
1089
+ let categoriesCollection = await call.get()*/
1019
1090
  let categoriesCollection = await DatabaseService_1.default.getDocuments(DatabaseService_1.default.addToPath(this._space_ref.path, this._space_ref.id + '/categories'), options);
1020
1091
  if (categoriesCollection.length == 0)
1021
1092
  return [];
@@ -1026,6 +1097,13 @@ class Space {
1026
1097
  return [];
1027
1098
  }
1028
1099
  };
1100
+ /**
1101
+ * Get full category tree
1102
+ * @deprecated use new _getTreeNew function instead
1103
+ * @param categories
1104
+ * @param level
1105
+ * @param parent
1106
+ */
1029
1107
  this._getTree = (categories, level = 0, parent) => {
1030
1108
  const _categories = categories.filter((c) => c.getHierarchicalOrderBasedOnCategories(categories) === level);
1031
1109
  if (_categories.length === 0)
@@ -1035,6 +1113,11 @@ class Space {
1035
1113
  }
1036
1114
  return (0, orderBy_1.default)(_categories.filter((c) => !!c.data().parent && c.data().parent === parent), (c) => c.data().order).map((c) => (Object.assign(Object.assign({}, c.data()), { children: this._getTree(categories, level + 1, c.data().id), items_count: 2 })));
1037
1115
  };
1116
+ /**
1117
+ * Get array of ordered categories
1118
+ * @param categories
1119
+ * @param parentID
1120
+ */
1038
1121
  this._getTreeNew = (categories, parentID) => {
1039
1122
  return (0, categories_1.buildTree)(categories.map((c) => c.data()), parentID);
1040
1123
  };
@@ -1048,6 +1131,7 @@ class Space {
1048
1131
  };
1049
1132
  this._resetInventories = async (categoryId) => {
1050
1133
  try {
1134
+ // Fetch les produits (inventaires) de la catégories
1051
1135
  const inventorieToUpdateFromCategoryId = await this.inventoryItems.get({
1052
1136
  query: [
1053
1137
  {
@@ -1058,6 +1142,7 @@ class Space {
1058
1142
  ]
1059
1143
  });
1060
1144
  (0, console_1.workingMessage)(`${inventorieToUpdateFromCategoryId.length} inventaires trouvés. Processing...`, true);
1145
+ // Mettre les inventaires à 0
1061
1146
  for (const inventoryGroup of (0, chunk_1.default)(inventorieToUpdateFromCategoryId, 250)) {
1062
1147
  (0, console_1.workingMessage)(`Exécution d'une batch de 250...`, true);
1063
1148
  const inventoryBatch = new BatchUtils_1.default();
@@ -1065,6 +1150,7 @@ class Space {
1065
1150
  try {
1066
1151
  if (!!!inventory.id)
1067
1152
  continue;
1153
+ // Mettre les valeurs d'inventaire à 0
1068
1154
  inventoryBatch.set(DatabaseService_1.default.addToPath(this._space_ref.path, this._space_ref.id + '/inventories'), inventory.id, {
1069
1155
  web_inventory: {
1070
1156
  available: 0,
@@ -1093,6 +1179,12 @@ class Space {
1093
1179
  (0, console_1.errorMessage)(error.toString(), true);
1094
1180
  }
1095
1181
  };
1182
+ /**
1183
+ * Private function to save a bulk of document to a collection
1184
+ * @param obj an array of documents
1185
+ * @param collection the collection name where to save
1186
+ * @returns the amount of save vs errors
1187
+ */
1096
1188
  this._batchSaveCollection = async (obj, collection) => {
1097
1189
  let errorsOccured = 0;
1098
1190
  let totalSaves = 0;
@@ -1183,6 +1275,8 @@ class Space {
1183
1275
  throw `Failed to update category ${category.id}: ${error}`;
1184
1276
  }
1185
1277
  };
1278
+ //#endregion
1279
+ //#region ATTRIBUTES
1186
1280
  this.addAttribute = async (attribute) => {
1187
1281
  if (!!!this._user) {
1188
1282
  (0, console_1.errorMessage)(`A user must be authenticated to create a new attribute`);
@@ -1236,11 +1330,15 @@ class Space {
1236
1330
  const productAttributeObj = new Attribute_1.default(attribute, DatabaseService_1.default.asCollectionObject(this._space_ref.path, this._space_ref.id + '/attributes'), this._user);
1237
1331
  await productAttributeObj.save();
1238
1332
  };
1333
+ //#endregion
1334
+ //#region PRODUCTS
1239
1335
  this._saveAllActiveProducts = async () => {
1240
1336
  try {
1241
1337
  const products = await this.products.get();
1338
+ // let _pIndex = 1
1242
1339
  for (const p of products.filter((p) => !!!p.data().draft && !!p.data().declinations && !!p.data().declinations.length)) {
1243
1340
  await p.save(undefined, { index: true });
1341
+ // _pIndex++
1244
1342
  }
1245
1343
  }
1246
1344
  catch (error) {
@@ -1540,12 +1638,17 @@ class Space {
1540
1638
  for (const service of services) {
1541
1639
  const serviceClass = (0, utils_1.getInstanceToUseForProductService)(service.external_service_slug, pathInfo.space, pathInfo.org);
1542
1640
  if (serviceClass) {
1641
+ // try to get the product from this provider
1543
1642
  const prod = await serviceClass.getProduct(slug, this._space);
1544
1643
  if (prod)
1545
1644
  return prod;
1546
1645
  }
1547
1646
  }
1548
1647
  };
1648
+ /**
1649
+ * Fetch all options with - optionnal - query
1650
+ * @param options Query options - optionnal
1651
+ */
1549
1652
  this._getProducts = async (options) => {
1550
1653
  if (!!!this._user)
1551
1654
  throw 'Invalid or unauthenticated user';
@@ -1553,6 +1656,7 @@ class Space {
1553
1656
  let call = DatabaseService_1.default.addToPath(this._space_ref.path, this._space_ref.id + '/products');
1554
1657
  const productsCollection = await DatabaseService_1.default.getDocuments(call, options);
1555
1658
  if (productsCollection.length == 0) {
1659
+ // Search in external products too
1556
1660
  const slug = this._getExternalProductsSlugToTry(options);
1557
1661
  if (slug) {
1558
1662
  const productFound = await this._getExternalProductBySlug(slug);
@@ -1570,6 +1674,12 @@ class Space {
1570
1674
  return [];
1571
1675
  }
1572
1676
  };
1677
+ /**
1678
+ * Obtenir une partie des produits à partir de l'indentifiant fournis
1679
+ * @param from le id du dernier document ou continuer ou undefine si on veut le premier
1680
+ * @param limit la taille max à lire, idéalement 500 ou moins
1681
+ * @returns la liste de produits récupéré
1682
+ */
1573
1683
  this._getProductsPage = async (from, limit) => {
1574
1684
  const productsCollection = await DatabaseService_1.default.getDocuments(DatabaseService_1.default.addToPath(this._space_ref.path, this._space_ref.id + '/products'), { orderBy: '__id', limit: limit, startAfter: !!from ? from : undefined });
1575
1685
  if (productsCollection.length == 0)
@@ -1702,6 +1812,29 @@ class Space {
1702
1812
  ? undefined
1703
1813
  : (0, currency_1.calculateAmountByCurrencyAllDetails)(this, this.preferences.default.currency(), d.price.discountPrice.amount);
1704
1814
  let regular = (0, currency_1.calculateAmountByCurrencyAllDetails)(this, this.preferences.default.currency(), d.price.regular.amount);
1815
+ // const tierPricing = flatten(
1816
+ // d.discount_rules
1817
+ // .filter((d) => d.discountRule_type === 'tier-pricing')
1818
+ // .map((discount) =>
1819
+ // applyTierPricing(
1820
+ // discount,
1821
+ // Number(
1822
+ // !!discount.result.apply_on_discounted_price && !!d.price.discountPrice
1823
+ // ? d.price.discountPrice.amount
1824
+ // : d.price.regular.amount
1825
+ // ),
1826
+ // this
1827
+ // )
1828
+ // )
1829
+ // )
1830
+ // if (!!tierPricing && !!tierPricing.length) {
1831
+ // const lowestTier = minBy(tierPricing, (t) => t.price.amount)
1832
+ // if (!!lowestTier) {
1833
+ // if (lowestTier.price.amount < regular.amount) {
1834
+ // regular = lowestTier.price
1835
+ // }
1836
+ // }
1837
+ // }
1705
1838
  if (!!promo) {
1706
1839
  if (!!discount && promo.amount <= discount.amount && promo.amount !== 0)
1707
1840
  return promo;
@@ -1757,10 +1890,12 @@ class Space {
1757
1890
  let call = DatabaseService_1.default.addToPath(this._space_ref.path, this._space_ref.id + '/indexes/products/public');
1758
1891
  const indexedProducts = await DatabaseService_1.default.getDocuments(call, options);
1759
1892
  if (indexedProducts.length == 0) {
1893
+ // search in external products too
1760
1894
  const slug = this._getExternalProductsSlugToTry(options);
1761
1895
  if (slug) {
1762
1896
  const productFound = await this._getExternalProductBySlug(slug);
1763
1897
  if (productFound) {
1898
+ // get the category and brand
1764
1899
  return [await this._getIndexedProductFromProduct(productFound)];
1765
1900
  }
1766
1901
  }
@@ -1781,10 +1916,12 @@ class Space {
1781
1916
  let call = DatabaseService_1.default.addToPath(this._space_ref.path, this._space_ref.id + '/indexes/products/public');
1782
1917
  const allExistingIndexes = await DatabaseService_1.default.getDocuments(call, options);
1783
1918
  if (allExistingIndexes.length == 0) {
1919
+ // search in external products too
1784
1920
  const slug = this._getExternalProductsSlugToTry(options);
1785
1921
  if (slug) {
1786
1922
  const productFound = await this._getExternalProductBySlug(slug);
1787
1923
  if (productFound) {
1924
+ // get the category and brand
1788
1925
  return [
1789
1926
  new Product_2.default(await this._getIndexedProductFromProduct(productFound), DatabaseService_1.default.asCollectionObject(this._space_ref.path, this._space_ref.id + '/indexes/products/public'), this._user)
1790
1927
  ];
@@ -1803,6 +1940,7 @@ class Space {
1803
1940
  };
1804
1941
  this._saveAllIndexedCategories = async (tree) => {
1805
1942
  try {
1943
+ //TODO- check with Christian if this is okay: this._space_ref.collection('indexes').doc('categories').set({ data: tree })
1806
1944
  DatabaseService_1.default.saveDocument(DatabaseService_1.default.addToPath(this._space_ref.path, this._space_ref.id + '/indexes'), 'categories', 0, tree, { merge: false });
1807
1945
  }
1808
1946
  catch (error) {
@@ -1838,6 +1976,13 @@ class Space {
1838
1976
  throw error;
1839
1977
  }
1840
1978
  };
1979
+ /**
1980
+ * Finds indexed declination corresponding to parent slug and sku provided
1981
+ * @param space
1982
+ * @param parentSlug - The parent product slug (to search space indexed products)
1983
+ * @param sku - The specific sku for the declination
1984
+ * @param customPriceList - Optionnal. If provided, indexed decli is returned with adjusted prices from price list
1985
+ */
1841
1986
  this._fetchIndexedDecliBySlugAndSku = async (parentSlug, sku, customPriceList) => {
1842
1987
  try {
1843
1988
  let indexedDecli = undefined;
@@ -1865,6 +2010,8 @@ class Space {
1865
2010
  return;
1866
2011
  }
1867
2012
  };
2013
+ //#endregion
2014
+ //#region INVENTORY ITEMS
1868
2015
  this._getAllInventoryItems = async (options) => {
1869
2016
  let call = DatabaseService_1.default.addToPath(this._space_ref.path, this._space_ref.id + '/inventories');
1870
2017
  const allExistingInventoryItemsQuery = await DatabaseService_1.default.getDocuments(call, options);
@@ -1882,6 +2029,12 @@ class Space {
1882
2029
  });
1883
2030
  return allExistingInventoryItems;
1884
2031
  };
2032
+ /**
2033
+ * Obtenir une partie des inventaires à partir de l'indentifiant fournis
2034
+ * @param from le id du dernier document ou continuer ou undefine si on veut le premier
2035
+ * @param limit la taille max à lire, idéalement 500 ou moins
2036
+ * @returns la liste de l'inventaires récupéré
2037
+ */
1885
2038
  this._getInventoryPage = async (from, limit) => {
1886
2039
  let productsCollection = await DatabaseService_1.default.getDocuments(DatabaseService_1.default.addToPath(this._space_ref.path, this._space_ref.id + '/inventories'), {
1887
2040
  order: 'asc',
@@ -1983,6 +2136,8 @@ class Space {
1983
2136
  this._setIsSaving = async (user_email) => {
1984
2137
  await this.save({ is_saving_inventory: user_email });
1985
2138
  };
2139
+ //#endregion
2140
+ //#region TRANSFER REQUESTS
1986
2141
  this._getAllTransfertRequests = async () => {
1987
2142
  const collRef = DatabaseService_1.default.asCollectionObject(this._space_ref.path, this._space_ref.id + '/transfer_requests');
1988
2143
  const allTransferRequests = await DatabaseService_1.default.getDocuments(collRef.path);
@@ -2036,6 +2191,8 @@ class Space {
2036
2191
  console.log('error on fetching transfer for ref: ', e.toString());
2037
2192
  }
2038
2193
  };
2194
+ //#endregion
2195
+ //#region DISCOUNT RULES
2039
2196
  this._discountRulesListener = (callback, options) => {
2040
2197
  if (!!!this._user)
2041
2198
  throw 'Invalid or unauthenticated user';
@@ -2124,6 +2281,8 @@ class Space {
2124
2281
  return [];
2125
2282
  }
2126
2283
  };
2284
+ //#endregion
2285
+ //#region PURCHASE ORDERS
2127
2286
  this._getPurchaseOrders = async (options) => {
2128
2287
  if (!!!this._user)
2129
2288
  throw 'Invalid or unauthenticated user';
@@ -2163,11 +2322,13 @@ class Space {
2163
2322
  orderState: 'draft'
2164
2323
  }, DatabaseService_1.default.asCollectionObject(this._space_ref.path, this._space_ref.id + '/purchaseOrders'), this._user);
2165
2324
  this.generatePurchaseOrders = async (declinationsToAdd) => {
2325
+ // const suppliers = await this._getSuppliers()
2166
2326
  const products = await this._getProducts();
2167
2327
  const purchaseOrders = [];
2168
2328
  declinationsToAdd.forEach((declinationData) => {
2169
2329
  const productOfDeclination = products.filter((product) => product.declinations.get().some((decli) => decli.data().slug == declinationData.declination.slug))[0];
2170
2330
  const supplier_id = productOfDeclination.getDefaultSupplier();
2331
+ // Si la purchase order existe déjà
2171
2332
  if (purchaseOrders.some((purchaseOrder) => purchaseOrder.supplier_id === supplier_id)) {
2172
2333
  const purchaseOrderIndex = (0, findIndex_1.default)(purchaseOrders, (order) => order.supplier_id == supplier_id);
2173
2334
  purchaseOrders[purchaseOrderIndex] = Object.assign(Object.assign({}, purchaseOrders[purchaseOrderIndex]), { items: [
@@ -2204,7 +2365,9 @@ class Space {
2204
2365
  if (this._user === undefined)
2205
2366
  throw 'Invalid or unauthenticated user';
2206
2367
  try {
2368
+ //TODO- check with Christian if this is okay
2207
2369
  return DatabaseService_1.default.registerListener((dataSnap) => {
2370
+ // tslint:disable-next-line: no-null-keyword
2208
2371
  if (dataSnap.length == 0)
2209
2372
  callback(null);
2210
2373
  (0, console_1.workingMessage)(`Purchase order list has been udpated. Refreshing...`);
@@ -2213,6 +2376,7 @@ class Space {
2213
2376
  }
2214
2377
  catch (err) {
2215
2378
  (0, console_1.errorMessage)(JSON.stringify(err));
2379
+ // tslint:disable-next-line: no-null-keyword
2216
2380
  callback(null);
2217
2381
  return '';
2218
2382
  }
@@ -2238,6 +2402,8 @@ class Space {
2238
2402
  return '';
2239
2403
  }
2240
2404
  };
2405
+ //#endregion
2406
+ //#region CLASSES
2241
2407
  this._getClasses = async (options) => {
2242
2408
  try {
2243
2409
  let call = DatabaseService_1.default.addToPath(this._space_ref.path, this._space_ref.id + '/classes');
@@ -2286,6 +2452,8 @@ class Space {
2286
2452
  (0, console_1.errorMessage)(`Error while creating new class: ${error}`);
2287
2453
  }
2288
2454
  };
2455
+ //#endregion
2456
+ //#region SUPPLIERS
2289
2457
  this._getSuppliers = async (options) => {
2290
2458
  try {
2291
2459
  let call = DatabaseService_1.default.addToPath(this._space_ref.path, this._space_ref.id + '/suppliers');
@@ -2326,6 +2494,8 @@ class Space {
2326
2494
  return '';
2327
2495
  }
2328
2496
  };
2497
+ //#endregion
2498
+ //#region CART
2329
2499
  this.createEmptyCart = async (save = false, cartType = Cart_1.CartTypeEnum.WEB, defaultPickup = false) => {
2330
2500
  const cart = new Cart_2.default(Object.assign(Object.assign({}, (0, Cart_1.getDefaultCart)(cartType)), (!!defaultPickup ? { is_pickup: true } : {})), DatabaseService_1.default.asCollectionObject(this._space_ref.path, this._space_ref.id + '/carts'), this._user);
2331
2501
  await cart.save({}, undefined, save);
@@ -2346,7 +2516,7 @@ class Space {
2346
2516
  const data = d.data;
2347
2517
  const paid_at = !!!data.paid_at
2348
2518
  ? undefined
2349
- : data.paid_at instanceof app_1.default.firestore.Timestamp
2519
+ : data.paid_at instanceof app_1.default.firestore.Timestamp // TODO - remplacer par formatDate
2350
2520
  ? data.paid_at.toDate()
2351
2521
  : data.paid_at;
2352
2522
  return new Cart_2.default(Object.assign(Object.assign({}, data), { id: d.id, paid_at }), DatabaseService_1.default.asCollectionObject(this._space_ref.path, this._space_ref.id + '/carts'), this._user);
@@ -2417,6 +2587,8 @@ class Space {
2417
2587
  store: (0, sumBy_1.default)(inventories.filter((i) => !!i), (i) => (0, sumBy_1.default)(i.inventories, (inventory) => inventory.qty.available || 0))
2418
2588
  };
2419
2589
  };
2590
+ //#endregion
2591
+ //#region ALL ORDER TYPES
2420
2592
  this._getAllOrderTypes = async (id = '') => {
2421
2593
  if (!!!this._user)
2422
2594
  throw 'Invalid or unauthenticated user';
@@ -2448,6 +2620,71 @@ class Space {
2448
2620
  throw new Error(`Error while getting invoices: ${err}`);
2449
2621
  }
2450
2622
  };
2623
+ // private _listenOrder = async (id: string = '', callback: any) => {
2624
+ // if (!!!this._user) throw 'Invalid or unauthenticated user'
2625
+ // if (this._user === undefined) throw 'Invalid or unauthenticated user'
2626
+ // try {
2627
+ // let invoicesDocs
2628
+ // let ordersDocs
2629
+ // let cartsDocs
2630
+ // invoicesDocs = await DatabaseService.getDocuments(
2631
+ // DatabaseService.addToPath(this._space_ref.path, this._space_ref.id + '/invoices')
2632
+ // )
2633
+ // ordersDocs = await DatabaseService.getDocuments(
2634
+ // DatabaseService.addToPath(this._space_ref.path, this._space_ref.id + '/orders')
2635
+ // )
2636
+ // cartsDocs = await DatabaseService.getDocuments(
2637
+ // DatabaseService.addToPath(this._space_ref.path, this._space_ref.id + '/carts')
2638
+ // )
2639
+ // let allOrderTypes: any[] = []
2640
+ // allOrderTypes.push(
2641
+ // invoicesDocs
2642
+ // .filter((d) => d.exists && !!d.data)
2643
+ // .map(
2644
+ // (d) =>
2645
+ // new Invoice(
2646
+ // { ...d.data, id: d.id } as IInvoice,
2647
+ // DatabaseService.asCollectionObject(this._space_ref.path, this._space_ref.id + '/invoices'),
2648
+ // this._user
2649
+ // )
2650
+ // )
2651
+ // )
2652
+ // allOrderTypes.push(
2653
+ // ordersDocs
2654
+ // .filter((d) => d.exists && !!d.data)
2655
+ // .map(
2656
+ // (d) =>
2657
+ // new Order(
2658
+ // { ...d.data, id: d.id } as IOrder,
2659
+ // DatabaseService.asCollectionObject(this._space_ref.path, this._space_ref.id + '/orders'),
2660
+ // this._user
2661
+ // )
2662
+ // )
2663
+ // )
2664
+ // allOrderTypes.push(
2665
+ // cartsDocs
2666
+ // .filter((d) => d.exists && !!d.data)
2667
+ // .map(
2668
+ // (d) =>
2669
+ // new Cart(
2670
+ // { ...d.data, id: d.id } as ICart,
2671
+ // DatabaseService.asCollectionObject(this._space_ref.path, this._space_ref.id + '/carts'),
2672
+ // this._user
2673
+ // )
2674
+ // )
2675
+ // )
2676
+ // if (!!!id) {
2677
+ // return flatten(allOrderTypes)
2678
+ // }
2679
+ // return flatten(allOrderTypes).filter((orderType: any) => orderType.data().id === id)[0]
2680
+ // } catch (err) {
2681
+ // throw new Error(`Error while getting invoices: ${err}`)
2682
+ // }
2683
+ // }
2684
+ //#endregion
2685
+ //#region INVOICE
2686
+ // public createEmptyInvoice = () =>
2687
+ // new Invoice(getDefaultInvoice(), this._space_ref.collection('invoices'), this._user)
2451
2688
  this._getInvoices = async (options) => {
2452
2689
  try {
2453
2690
  let call = DatabaseService_1.default.addToPath(this._space_ref.path, this._space_ref.id + '/invoices');
@@ -2480,6 +2717,8 @@ class Space {
2480
2717
  }
2481
2718
  };
2482
2719
  this._getUnknownCartItem = (cartItem, product, orderImport) => {
2720
+ // METTRE LE TABLEAU DE LANGUES DU SPACE DYNAMIQUE
2721
+ // *** type cause problème présement....
2483
2722
  return Object.assign(Object.assign({}, cartItem), { sku: 'UNK-000000-00000', slug: 'unknown', parent_product_id: product.split('*')[0], name: (0, locale_1.getLanguageDictFromString)('unknown', ['fr', 'en']), description: (0, locale_1.getLanguageDictFromString)("Produit venant de l'ancien site", ['fr', 'en']), regular_price: {
2484
2723
  currency: orderImport.currency,
2485
2724
  amount: Number(product.split('*')[2])
@@ -2489,6 +2728,7 @@ class Space {
2489
2728
  let allCarts = [];
2490
2729
  const fileData = fileImport.data;
2491
2730
  allCarts = await Promise.all(fileData.map(async (orderImport) => {
2731
+ // 1. Get customer
2492
2732
  const customerQuery = await this.customers.get({
2493
2733
  query: [{ field: 'id', operator: '==', value: orderImport.customer_id }]
2494
2734
  });
@@ -2496,6 +2736,7 @@ class Space {
2496
2736
  if (!!customerQuery && !!customerQuery.length) {
2497
2737
  customer = customerQuery[0].data();
2498
2738
  }
2739
+ // 2. Get products
2499
2740
  const orderImportProducts = orderImport.products.split(';');
2500
2741
  const cartItems = [];
2501
2742
  if (!!orderImportProducts && !!orderImportProducts.length) {
@@ -2541,7 +2782,9 @@ class Space {
2541
2782
  .reduce((map, obj) => {
2542
2783
  map[obj.key] = obj.value;
2543
2784
  return map;
2544
- }, {}), description: closestDeclination.description, images_path: closestDeclination.image_files, tax_family_id: 'QC', parent_product_id: !!parentProduct.id ? parentProduct.id : '', shipping_info: closestDeclination.shipping_info, regular_price: {
2785
+ }, {}), description: closestDeclination.description, images_path: closestDeclination.image_files, tax_family_id: 'QC', parent_product_id: !!parentProduct.id ? parentProduct.id : '', shipping_info: closestDeclination.shipping_info,
2786
+ // stock_level: closestDeclination.stock_level,
2787
+ regular_price: {
2545
2788
  currency: orderImport.currency,
2546
2789
  amount: Number(product.split('*')[2])
2547
2790
  }, discount_price: null, promo_price: null, qte: Number(product.split('*')[1]), parent_slug: parentProduct.slug });
@@ -2550,6 +2793,7 @@ class Space {
2550
2793
  cartItems.push(cartItem);
2551
2794
  }
2552
2795
  }
2796
+ // 3. Construct cart
2553
2797
  let cart = (0, Cart_1.getDefaultCart)();
2554
2798
  cart = Object.assign(Object.assign({}, cart), { customer_id: !!customer ? customer.id : 'unknown', customer_info: !!customer
2555
2799
  ? {
@@ -2635,10 +2879,19 @@ class Space {
2635
2879
  }));
2636
2880
  return allCarts.filter((cart) => !!cart);
2637
2881
  };
2882
+ /**
2883
+ * Generate the next unique ID for a customers new promise to purchase. Recursive function : always checks if ID exists in database before returning ID.
2884
+ * @param customerId - The customer for whom we're creating a new promise
2885
+ * @param useNextSeason - If we should check the values for next season instead of current one
2886
+ * @param idToIncrement - Optionnal. Only set when calling the function recursively.
2887
+ */
2638
2888
  this._generateNewPromiseId = async (customerId, useNextSeason, idToIncrement) => {
2639
2889
  const yearToUse = useNextSeason ? (0, moment_1.default)().add(1, 'year').format('YY') : (0, moment_1.default)().format('YY');
2640
2890
  let existingPAs;
2641
2891
  try {
2892
+ // NOTE - Pour firebase, si le champ est une string, le [ > et >= ] ou [ < et <= ] veullent dire "commence par" et "termine par", respectivement.
2893
+ // Par contre, la vérification continue de foncitonner comme si c'était des number. Il faut donc même une close >= ET < ici pour pas que le code retourne
2894
+ // celles de l'année en cours ET des années prochaines aussi!!
2642
2895
  existingPAs = await this.promisesToPurchase.get({
2643
2896
  query: [
2644
2897
  { field: 'customer_id', operator: '==', value: customerId },
@@ -2683,6 +2936,7 @@ class Space {
2683
2936
  throw new Error('invoice data not set in space');
2684
2937
  }
2685
2938
  let newInvoiceRef = '';
2939
+ // if should be same as cart ref
2686
2940
  if (!!invoiceData.inherit_order_number && !!cartData.ref) {
2687
2941
  try {
2688
2942
  await this.save({
@@ -2695,9 +2949,12 @@ class Space {
2695
2949
  }
2696
2950
  }
2697
2951
  else {
2952
+ // invoice ref by store variables
2698
2953
  let wasPaidAtStore = false;
2699
2954
  let storeToUse;
2700
2955
  if (!!cartData.current_store_id) {
2956
+ // Get store where payment was taken (invoice should be associated to that store)
2957
+ // If not found, use current_store_id (which should be store where order was processed)
2701
2958
  const createdAtStore = (0, object_1.recursiveCheckObject)(cartData, 'created_by.at_store_id');
2702
2959
  const processedAtStore = (0, object_1.recursiveCheckObject)(cartData, 'processed_by.at_store_id');
2703
2960
  const paidAtStore = !!(0, object_1.recursiveCheckObject)(cartData, 'created_by.took_payment')
@@ -2732,7 +2989,7 @@ class Space {
2732
2989
  catch (e) {
2733
2990
  console.log('Error fetching invoice number', e);
2734
2991
  }
2735
- await (0, tools_1.waitFor)(1000);
2992
+ await (0, tools_1.waitFor)(1000); // whait a second before trying again, server need to recover
2736
2993
  triesLeft--;
2737
2994
  }
2738
2995
  if (triesLeft == 0)
@@ -2744,6 +3001,7 @@ class Space {
2744
3001
  if (!!!invoiceData) {
2745
3002
  throw new Error('invoice data not set in space');
2746
3003
  }
3004
+ // get min invoice ref number length
2747
3005
  const newInvoiceRef = this._constructNewRefForInvoice(invoiceData);
2748
3006
  try {
2749
3007
  await this.save({
@@ -2842,6 +3100,8 @@ class Space {
2842
3100
  return;
2843
3101
  }
2844
3102
  };
3103
+ //#endregion
3104
+ //#region ORDERS
2845
3105
  this._getOrders = async (options) => {
2846
3106
  try {
2847
3107
  let call = DatabaseService_1.default.addToPath(this._space_ref.path, this._space_ref.id + '/orders');
@@ -2873,6 +3133,8 @@ class Space {
2873
3133
  return '';
2874
3134
  }
2875
3135
  };
3136
+ //#endregion
3137
+ //#region CUSTOMERS
2876
3138
  this._customersListener = (callback, _options) => {
2877
3139
  if (!!!this._user)
2878
3140
  throw 'Invalid or unauthenticated user';
@@ -3172,6 +3434,11 @@ class Space {
3172
3434
  throw error;
3173
3435
  }
3174
3436
  };
3437
+ /**
3438
+ * Fetches and returns all promises to purchase associated with a customer ID.
3439
+ * @param customerID - The customer ID to check
3440
+ * @param onlyActive - Optionnal. If true, function only returns currently active promises
3441
+ */
3175
3442
  this._getCustomerPromisesToPurchase = async (customerID, onlyActive) => {
3176
3443
  try {
3177
3444
  const customerPromisesToPurchase = await this.promisesToPurchase.get({
@@ -3179,9 +3446,11 @@ class Space {
3179
3446
  });
3180
3447
  if (!!!customerPromisesToPurchase)
3181
3448
  throw new Error(`Error while getting promises to purchase for customer: ${customerID}`);
3449
+ // If onlyActive is false, return all found promises to purchase
3182
3450
  if (!!!onlyActive) {
3183
3451
  return customerPromisesToPurchase;
3184
3452
  }
3453
+ // Filter to keep only active promises
3185
3454
  const allActive = customerPromisesToPurchase.filter((promise) => !!(0, promiseToPurchase_1.isPromiseActive)(promise.data()));
3186
3455
  return allActive;
3187
3456
  }
@@ -3189,6 +3458,11 @@ class Space {
3189
3458
  throw new Error(`Error while getting PAs: ${err}`);
3190
3459
  }
3191
3460
  };
3461
+ /**
3462
+ * For all possible bank types for space, checks all active promises for customer and returns an object containing currently active bank applicable.
3463
+ * @param customerID - The customer ID to check
3464
+ * @param promisesToCheck - Optionnal. If defined, uses provided array of promises instead of calling DB.
3465
+ */
3192
3466
  this._getPossibleActiveBanksForCustomer = async (customerID, promisesToCheck) => {
3193
3467
  try {
3194
3468
  let promisesForCustomer = promisesToCheck;
@@ -3198,7 +3472,9 @@ class Space {
3198
3472
  }
3199
3473
  if (!!!promisesForCustomer)
3200
3474
  return [];
3475
+ // Order promises data by promise_unique_id
3201
3476
  const promisesData = (0, promiseToPurchase_1.getOrderedPromises)(promisesForCustomer.map((p) => p.data()), 'promise_unique_id');
3477
+ // Loop through all possible banks to find applicable options in active promises for customer
3202
3478
  const possibleBanks = this.bankTypes.get(undefined, true);
3203
3479
  return (0, promiseToPurchase_1.checkForApplicableBanks)(promisesData, possibleBanks);
3204
3480
  }
@@ -3225,10 +3501,26 @@ class Space {
3225
3501
  console.log(`Could not set last_activity prop for customer: ${customerId}, ${e}`);
3226
3502
  }
3227
3503
  };
3504
+ //#endregion
3505
+ //#region INVENTORY
3506
+ /**
3507
+ * Function that adjusts store and / or web inventories for a cart depending on it's state
3508
+ * @param items an array of ICartItem objects through which we will loop to adjust their inventories
3509
+ * @param cartState the state of the cart for which we are adjusting the inventory, this affects what inventory actions will be made
3510
+ * @param cartType type of the cart
3511
+ * @param options.currentStoreId the store at which we are doing the inventory manipulation
3512
+ * @param options.onlyWeb if the inventory should only be adjusted for WEB or also for the current store
3513
+ * @param options.fromStoreId the store at which the inventories were initially modified, it is only used in the context of a refund, where we might return items to a different store than where they were taken.
3514
+ * @param options.associatedTransferForCart Optionnal. Array of TransferRequest objects associated to order (used in 'cancelled' cart state)
3515
+ * @param options.previousItems Optionnal. Array of ICartItem corresponding to prevState in cart
3516
+ * @param options.inventoryItemsDataToUse Optionnal. Array of inventoryItem data to use instead of calling Db twice.
3517
+ * @param options.shouldCheckReservedQte Optionnal. If reserved quantities should be check for inventory or not
3518
+ */
3228
3519
  this._ajustInventoryWithCart = async (items, cartState, cartType, options = {}) => {
3229
3520
  var _c;
3230
3521
  if (!!!this._space.stores_warehouses.length)
3231
3522
  return;
3523
+ // Check for stores that either sell online, or offer immediate pickup. Will be used as "possible" stores for inventory ajustment
3232
3524
  const canShipStores = this._space.stores_warehouses.filter((store) => !store.no_inventory_for_store && (store.can_sell_online || store.allow_immediate_pickup));
3233
3525
  if (!!!canShipStores.length)
3234
3526
  return;
@@ -3283,6 +3575,7 @@ class Space {
3283
3575
  result = await inventoryObj.handleProductSold(options.currentStoreId, inventoryToRemove, cartType, cartType !== Cart_1.CartTypeEnum.POS_TRANSACTIONNAL);
3284
3576
  }
3285
3577
  else if (cartState === 'cancelled' || cartState === 'refunded') {
3578
+ //TODO Add logic for item should be deleted on cancel inventory
3286
3579
  result = await inventoryObj.handleOrderCancelled(options.currentStoreId, (_c = options.fromStoreId) !== null && _c !== void 0 ? _c : options.currentStoreId, inventoryToRemove, cartState, cartType, {
3287
3580
  deleteItem: false,
3288
3581
  onlyWeb: options.onlyWeb,
@@ -3324,6 +3617,8 @@ class Space {
3324
3617
  const spaceOptions = this.options.get();
3325
3618
  return !!(0, object_1.recursiveCheckObject)(spaceOptions, 'inventory.minimum_inventory_per_sku');
3326
3619
  };
3620
+ //#endregion
3621
+ //#region TAGS
3327
3622
  this._addTag = async (declination, product, category_slug, inventory, currentStoreId, maxQte, isOtherCategory) => {
3328
3623
  try {
3329
3624
  if (!!!declination)
@@ -3384,7 +3679,9 @@ class Space {
3384
3679
  const _d = d;
3385
3680
  if (!!_d.upc)
3386
3681
  continue;
3682
+ // Fetch last UPC that can be use
3387
3683
  const lastUpc = this.data().product_preferences.barcode_next || '0';
3684
+ // Assign the last UPC to the declination
3388
3685
  await productObj.save({
3389
3686
  declinations: (_p.declinations || []).map((__d) => {
3390
3687
  if (__d.sku !== _d.sku)
@@ -3392,10 +3689,13 @@ class Space {
3392
3689
  return Object.assign(Object.assign({}, __d), { upc: lastUpc });
3393
3690
  })
3394
3691
  });
3692
+ // Check if we should change current declination UPC
3395
3693
  if (declination.sku === _d.sku) {
3396
3694
  declination = Object.assign(Object.assign({}, declination), { upc: lastUpc });
3397
3695
  }
3696
+ // Increment the UPC
3398
3697
  const newUpc = parseInt(lastUpc) + 1;
3698
+ // Save it to the Space
3399
3699
  await this.save({
3400
3700
  product_preferences: Object.assign(Object.assign({}, this.data().product_preferences), { barcode_next: newUpc.toString() })
3401
3701
  });
@@ -3414,6 +3714,7 @@ class Space {
3414
3714
  catch (error) {
3415
3715
  console.log(error);
3416
3716
  throw error;
3717
+ // return
3417
3718
  }
3418
3719
  };
3419
3720
  this._getAllTags = async (options) => {
@@ -3440,6 +3741,12 @@ class Space {
3440
3741
  throw error;
3441
3742
  }
3442
3743
  };
3744
+ //#endregion
3745
+ //#region USERS
3746
+ /**
3747
+ * Fetches user from database by unique ID.
3748
+ * @param uid - The users unique ID (same as the email)
3749
+ */
3443
3750
  this._getUser = async (uid) => {
3444
3751
  if (this._space_ref === undefined)
3445
3752
  throw new Error(`Space ref is undefined`);
@@ -3447,6 +3754,11 @@ class Space {
3447
3754
  throw new Error(`User ID must be defined and not empty. Value received: ${uid}`);
3448
3755
  return await User_1.default.FetchUser({ email: uid });
3449
3756
  };
3757
+ /**
3758
+ * Fetches user from database by external ID
3759
+ * @param externalID - The user's external ID
3760
+ * @param userEmail - The user's email
3761
+ */
3450
3762
  this._getUserByExternalID = async (externalID) => {
3451
3763
  if (this._space_ref === undefined)
3452
3764
  throw new Error(`Space ref is undefined`);
@@ -3540,7 +3852,11 @@ class Space {
3540
3852
  const orgRef = DatabaseService_1.default.getPathParent(this._space_ref.path);
3541
3853
  if (!!!orgRef)
3542
3854
  throw new Error(`Can't access org ref`);
3855
+ // --------------------------------------------------------------------
3856
+ // STEP 1 - Delete user from Users collection in Org
3543
3857
  try {
3858
+ // Since not all users have props id set in document,
3859
+ // fetch using FB doc id instead
3544
3860
  const userDoc = await DatabaseService_1.default.getDocument(DatabaseService_1.default.addToPath(orgRef, 'users'), userId);
3545
3861
  if (!!!userDoc || !!!userDoc.exists)
3546
3862
  throw new Error(`Can't retreive user with ID ${userId}`);
@@ -3553,6 +3869,8 @@ class Space {
3553
3869
  console.log('---- in catch for STEP 1 ----');
3554
3870
  throw error;
3555
3871
  }
3872
+ // --------------------------------------------------------------------
3873
+ // STEP 2 - Delete user relation to org in collection rel_orgs_users
3556
3874
  try {
3557
3875
  if (!!!DatabaseService_1.default.getPathParent(DatabaseService_1.default.getPathParent(orgRef)))
3558
3876
  throw new Error(`can't access base DB to delete relation to org of user. Please check manually in Firestore`);
@@ -3577,6 +3895,8 @@ class Space {
3577
3895
  console.log('---- in catch for STEP 2 ----');
3578
3896
  throw error;
3579
3897
  }
3898
+ // --------------------------------------------------------------------
3899
+ // STEP 3 - Delete user from FirebaseAuth
3580
3900
  if (!!!credentials)
3581
3901
  throw new Error(`Admin Firebase must be passed`);
3582
3902
  try {
@@ -3593,6 +3913,8 @@ class Space {
3593
3913
  throw error;
3594
3914
  }
3595
3915
  };
3916
+ //#endregion
3917
+ //#region UTILS
3596
3918
  this.translateToDefault = (dict) => {
3597
3919
  if (!!!dict.length)
3598
3920
  return '';
@@ -3671,6 +3993,8 @@ class Space {
3671
3993
  return false;
3672
3994
  }
3673
3995
  };
3996
+ //#endregion
3997
+ //#region BOOKINGS
3674
3998
  this._getBookings = async (options) => {
3675
3999
  if (!!!this._user)
3676
4000
  throw 'Invalid or unauthenticated user';
@@ -3730,6 +4054,8 @@ class Space {
3730
4054
  return { saved: false, booking: undefined };
3731
4055
  }
3732
4056
  };
4057
+ //#endregion
4058
+ //#region G2 CALLS (GR ONLY)
3733
4059
  this._updateG2Calls = async (optionsToUpdate) => {
3734
4060
  try {
3735
4061
  await this.save({
@@ -3742,6 +4068,8 @@ class Space {
3742
4068
  return false;
3743
4069
  }
3744
4070
  };
4071
+ //#endregion
4072
+ //#region GETTERS
3745
4073
  this.publicToken = () => {
3746
4074
  if (!!!DatabaseService_1.default.getPathParent(this._space_ref.path + this._space_ref.id))
3747
4075
  return '';
@@ -3811,6 +4139,9 @@ class Space {
3811
4139
  const storageSettings = this.preferences.storage.getServiceConfig();
3812
4140
  return { name: storageService, config: storageSettings };
3813
4141
  };
4142
+ // #endregion
4143
+ // -------------------------------------------------------------------------------
4144
+ // #region UPDATES
3814
4145
  this._getUpdateByObjectID = async (objectID) => {
3815
4146
  const query = await DatabaseService_1.default.getDocuments(DatabaseService_1.default.addToPath(this._space_ref.path, this._space_ref.id + '/updates'), { query: [{ field: 'object_id', operator: '==', value: objectID }] });
3816
4147
  if (!!!query || !!!query.length)
@@ -3823,6 +4154,9 @@ class Space {
3823
4154
  return;
3824
4155
  return query.map((doc) => doc.data);
3825
4156
  };
4157
+ // #endregion
4158
+ // -------------------------------------------------------------------------------
4159
+ // #region BANK TYPES
3826
4160
  this._getBankTypes = (id, returnInactive) => {
3827
4161
  const allBankTypes = this.data().bank_types || [];
3828
4162
  if (!!id) {
@@ -3892,6 +4226,13 @@ class Space {
3892
4226
  const onlyMostRecent = (0, promiseToPurchase_1.getMostRecentVersionOfRules)(typeToCheck);
3893
4227
  return onlyMostRecent;
3894
4228
  };
4229
+ // #endregion
4230
+ // -------------------------------------------------------------------------------
4231
+ // #region PROMISES TO PURCHASE
4232
+ /**
4233
+ * Synchronizes the customers with the list of promise to purchase.
4234
+ * @param associations - Record dont la clé est l'id d'un customer et la valeur est un record de promesses d'achats avec leur id et leurs infos
4235
+ */
3895
4236
  this._syncCustomerPromiseToPurchaseAssoc = async (associations) => {
3896
4237
  const prospr = new prosprsearch_1.ProsprSearch({
3897
4238
  app: this.preferences.prosprsearch.app(),
@@ -3959,6 +4300,9 @@ class Space {
3959
4300
  }
3960
4301
  return sync.every((r) => !!r);
3961
4302
  };
4303
+ /**
4304
+ * Retrieves and returns only the customers who have a PA.
4305
+ */
3962
4306
  this._getAllWithActivePromises = async () => {
3963
4307
  const prosprResult = await PromiseToPurchase_1.default.fetch({
3964
4308
  app: this.preferences.prosprsearch.app(),
@@ -3969,7 +4313,7 @@ class Space {
3969
4313
  space: this,
3970
4314
  filters: '',
3971
4315
  f: `(has_active_promise:true)`,
3972
- hpp: 100000
4316
+ hpp: 100000 // gimme gimme
3973
4317
  });
3974
4318
  const { customers, error } = await (async () => {
3975
4319
  try {
@@ -4001,6 +4345,10 @@ class Space {
4001
4345
  return;
4002
4346
  }
4003
4347
  };
4348
+ /**
4349
+ * Checks for currently active banks, and returns their available amount, as well as the ones for all previous PAs with same bank type.
4350
+ * @param customerID
4351
+ */
4004
4352
  this._getAvailableBankAmountsByBankType = async (customerID, filterToApply = 'active-and-before') => {
4005
4353
  var _c;
4006
4354
  try {
@@ -4013,6 +4361,8 @@ class Space {
4013
4361
  });
4014
4362
  if (!!!historyForCustomer)
4015
4363
  throw new Error('Error on fetching history for customer');
4364
+ // Get currently active banks in PAs
4365
+ // We will use info to check if PA should be considered in history shown
4016
4366
  let currentlyActiveBanksInPAs = [];
4017
4367
  let allCustomerBanks = [];
4018
4368
  for (let pa of (0, orderBy_1.default)(allCustomerPAsData, (pa) => (0, toNumber_1.default)(pa.promise_unique_id), 'desc')) {
@@ -4024,16 +4374,22 @@ class Space {
4024
4374
  currentlyActiveBanksInPAs.push({ bankID: bank.bank_type_id, promiseUniqueID: pa.promise_unique_id });
4025
4375
  }
4026
4376
  }
4377
+ // ** TODO - Check what to do if history array is empty for customer?
4378
+ // ** should we only return values for currently active banks?
4379
+ // Group history entries by promise_id
4027
4380
  let orderedHistoryById = (0, groupBy_1.default)(historyForCustomer, 'promise_id');
4381
+ // Save remaining amounts by grouping them by bank_type
4028
4382
  let orderedByBankType = {};
4029
4383
  for (const bank of allCustomerBanks) {
4030
4384
  const bankInfo = bank.data;
4031
4385
  const currentActivePaForBank = currentlyActiveBanksInPAs.find((b) => b.bankID === bankInfo.bank_type_id);
4032
4386
  if (!!currentActivePaForBank) {
4033
4387
  const mostRecentlyEmptiedBankOfType = (0, promiseToPurchase_1.getLatestEmptiedBankOfType)(allCustomerPAsData, bankInfo.bank_type_id, currentActivePaForBank.promiseUniqueID);
4388
+ // Set cutoff id to check for filterToApply
4034
4389
  let cutoffPromiseUniqueID = (0, toNumber_1.default)(currentActivePaForBank.promiseUniqueID);
4035
4390
  if (!!mostRecentlyEmptiedBankOfType && filterToApply === 'last-emptied-active-and-after')
4036
4391
  cutoffPromiseUniqueID = mostRecentlyEmptiedBankOfType.promise_unique_id;
4392
+ // Ignore all entries that do not correspond
4037
4393
  if (['active-and-before'].includes(filterToApply) && (0, toNumber_1.default)(bank.promiseUniqueID) > cutoffPromiseUniqueID)
4038
4394
  continue;
4039
4395
  if (['active-and-after', 'last-emptied-active-and-after'].includes(filterToApply) &&
@@ -4053,6 +4409,7 @@ class Space {
4053
4409
  Object.assign({ promise_id: (_c = bank.promiseId) !== null && _c !== void 0 ? _c : '', promise_unique_id: bank.promiseUniqueID, bank_type_id: bankInfo.bank_type_id }, amounts)
4054
4410
  ];
4055
4411
  }
4412
+ // Order values by promise_unique_id (from most recent to oldest)
4056
4413
  for (let [bankID, values] of Object.entries(orderedByBankType)) {
4057
4414
  orderedByBankType[bankID] = (0, orderBy_1.default)(values, (v) => (0, toNumber_1.default)(v.promise_unique_id), 'desc');
4058
4415
  }
@@ -4152,9 +4509,11 @@ class Space {
4152
4509
  this._closeSeasonPromisesToPurchase = async (yearToClose, userClosingID) => {
4153
4510
  const currentClosed = this.promisesToPurchase.getPromiseSeasons('closed');
4154
4511
  const yearAlreadyClosed = currentClosed.find((c) => c.season_year === yearToClose);
4512
+ // Si l'année est déjà fermée, return
4155
4513
  if (!!yearAlreadyClosed)
4156
4514
  return false;
4157
4515
  const currentValues = this.data().promise_to_purchase_seasons;
4516
+ // Si il n'y a aucune saison dans la space, on ne peut pas la fermer
4158
4517
  if (!!!currentValues)
4159
4518
  return false;
4160
4519
  currentValues[yearToClose.toString()] = Object.assign(Object.assign({}, currentValues[yearToClose.toString()]), { closed: {
@@ -4181,6 +4540,7 @@ class Space {
4181
4540
  const currentValues = this.data().promise_to_purchase_seasons;
4182
4541
  let newRecord = {};
4183
4542
  if (!!!currentValues) {
4543
+ // If there are no current seasons saved, create a new record and populate it with the new season to open
4184
4544
  newRecord[yearToOpen.toString()] = {
4185
4545
  opened: {
4186
4546
  date: new Date(),
@@ -4215,9 +4575,11 @@ class Space {
4215
4575
  this._endSeasonPromisesToPurchase = async (yearToEnd, userEndingId) => {
4216
4576
  const currentEnded = this.promisesToPurchase.getPromiseSeasons('ended');
4217
4577
  const yearAlreadyEnded = currentEnded.find((c) => c.season_year === yearToEnd);
4578
+ // Si l'année est déjà terminée, return
4218
4579
  if (!!yearAlreadyEnded)
4219
4580
  return false;
4220
4581
  const currentValues = this.data().promise_to_purchase_seasons;
4582
+ // Si il n'y a aucune saison dans la space, on ne peut pas en end
4221
4583
  if (!!!currentValues)
4222
4584
  return false;
4223
4585
  currentValues[yearToEnd.toString()] = Object.assign(Object.assign({}, currentValues[yearToEnd.toString()]), { ended: {
@@ -4241,6 +4603,11 @@ class Space {
4241
4603
  });
4242
4604
  return escompteSuppProduct;
4243
4605
  };
4606
+ /**
4607
+ * Retrieves and returns all the carts containing a specific promise ID.
4608
+ * @param promiseID - The ID to check
4609
+ * @param options - Optionnal. Additionnal query options
4610
+ */
4244
4611
  this._getPromiseAssociatedCarts = async (promiseID, options) => {
4245
4612
  const carts = await this.carts.get(Object.assign({ query: [
4246
4613
  {
@@ -4249,9 +4616,11 @@ class Space {
4249
4616
  value: promiseID
4250
4617
  }
4251
4618
  ] }, (!!options ? options : {})));
4619
+ // Only return paid carts
4252
4620
  return carts.filter((f) => !!f.data().paid_at && f.data().status >= Cart_1.CartStatusEnum.CHECKOUT_PAYMENT_SUCCESS);
4253
4621
  };
4254
4622
  this._getBanksUsedHistory = async (filterOptions, searchOptions) => {
4623
+ // Construct filters
4255
4624
  let filtersToSet = [];
4256
4625
  if (!!filterOptions.customerID) {
4257
4626
  filtersToSet.push(`customer_id:${filterOptions.customerID}`);
@@ -4269,6 +4638,7 @@ class Space {
4269
4638
  filtersToSet.push(`date:${filterOptions.unixDateRange.start} TO ${filterOptions.unixDateRange.end}`);
4270
4639
  }
4271
4640
  const filters = !!filtersToSet.length ? filtersToSet.join(' AND ') : '';
4641
+ // Fetch history
4272
4642
  try {
4273
4643
  const basicSearchInfo = (0, searchIndexes_1.getFetchInfoAlgoliaAddioSearch)(this);
4274
4644
  const results = await PromiseToPurchase_1.default.fetchHistory(Object.assign(Object.assign(Object.assign({}, basicSearchInfo), (!!filters ? { f: filters } : {})), (searchOptions || {})));
@@ -4282,6 +4652,7 @@ class Space {
4282
4652
  }
4283
4653
  };
4284
4654
  this._getAvailableBankAmountForApplicableBanks = (applicableBanks, applicableBanksHistory) => {
4655
+ // No need to query promises here, since initialAmount can be found in applicableBank.bank!
4285
4656
  let remainingAmounts = {};
4286
4657
  for (let applicable of applicableBanks) {
4287
4658
  const { bank, promise_id } = applicable;
@@ -4300,6 +4671,11 @@ class Space {
4300
4671
  }
4301
4672
  return remainingAmounts;
4302
4673
  };
4674
+ /**
4675
+ * Returns all available amounts for banks found in specific promise.
4676
+ * @param promiseID The ID of the promise to check
4677
+ * @param promiseObj Optionnal. If provided, saves a call to the DB.
4678
+ */
4303
4679
  this._getAvailableBankAmountsForPromise = async (promiseID, promiseObj) => {
4304
4680
  try {
4305
4681
  let promiseToCheck = promiseObj;
@@ -4344,6 +4720,12 @@ class Space {
4344
4720
  return;
4345
4721
  }
4346
4722
  };
4723
+ /**
4724
+ * Returns remaining amount and other info for a specific bank of a specific PA.
4725
+ * @param promiseID - The promise to purchase ID
4726
+ * @param bankID - The bank type ID
4727
+ * @param promiseObj - Optionnal. If provided, removes one fetch from database
4728
+ */
4347
4729
  this._getSpecificAvailableBankAmount = async (promiseID, bankID, promiseObj) => {
4348
4730
  try {
4349
4731
  let promiseToCheck = promiseObj;
@@ -4378,6 +4760,9 @@ class Space {
4378
4760
  return;
4379
4761
  }
4380
4762
  };
4763
+ // #endregion
4764
+ // -------------------------------------------------------------------------------
4765
+ // #region JOBS
4381
4766
  this._getJobs = async (options) => {
4382
4767
  if (!!!this._user)
4383
4768
  throw 'Invalid or unauthenticated user';
@@ -4395,6 +4780,30 @@ class Space {
4395
4780
  throw 'Invalid or unauthenticated user';
4396
4781
  if (this._user === undefined)
4397
4782
  throw 'Invalid or unauthenticated user';
4783
+ // TODO- modify to use DatabaseService.getDocumentsListener
4784
+ // try {
4785
+ // let call = DatabaseService.addToPath(this._space_ref.path, this._space_ref.id + '/bg_jobs')
4786
+ // if (!!options) {
4787
+ // call = constructFirebaseCallWithOptions(call, options)
4788
+ // }
4789
+ // return call.withConverter(BgJobConverter).onSnapshot((dataSnap) => {
4790
+ // if (dataSnap.empty) callback([])
4791
+ // workingMessage(`Jobs list has been udpated. Refreshing...`)
4792
+ // callback(
4793
+ // dataSnap.docs.map(
4794
+ // (jobDoc) =>
4795
+ // new BGJob(
4796
+ // { ...jobDoc.data(), id: jobDoc.id } as IBGJob,
4797
+ // DatabaseService.asCollectionObject(this._space_ref.path, this._space_ref.id + '/bg_jobs'),
4798
+ // this._user
4799
+ // )
4800
+ // )
4801
+ // )
4802
+ // })
4803
+ // } catch (error) {
4804
+ // errorMessage(JSON.stringify(error))
4805
+ // callback([])
4806
+ // }
4398
4807
  return '';
4399
4808
  };
4400
4809
  this._startJob = async (jobToStart) => {
@@ -4430,6 +4839,9 @@ class Space {
4430
4839
  (0, console_1.errorMessage)(JSON.stringify(error));
4431
4840
  }
4432
4841
  };
4842
+ //#endregion
4843
+ // -------------------------------------------------------------------------------
4844
+ // #region SLIDERS
4433
4845
  this._getSliders = async (options) => {
4434
4846
  if (!!!this._user)
4435
4847
  throw 'Invalid or unauthenticated user';
@@ -4442,6 +4854,9 @@ class Space {
4442
4854
  }
4443
4855
  catch (error) { }
4444
4856
  };
4857
+ //#endregion
4858
+ // -------------------------------------------------------------------------------
4859
+ // #region FIRST ORDER TRACKING
4445
4860
  this._getFirstOrders = async (options) => {
4446
4861
  if (!!!this._user)
4447
4862
  throw 'Invalid or unauthenticated user';
@@ -4454,6 +4869,9 @@ class Space {
4454
4869
  }
4455
4870
  catch (error) { }
4456
4871
  };
4872
+ //#endregion
4873
+ // -------------------------------------------------------------------------------
4874
+ // #region DOCUMENTS
4457
4875
  this._getAllDocuments = async (specificPath) => {
4458
4876
  if (!!!this._user)
4459
4877
  throw 'Invalid or unauthenticated user';
@@ -4505,6 +4923,18 @@ class Space {
4505
4923
  console.log('Error while updating document in firebase bucket: ', e);
4506
4924
  }
4507
4925
  };
4926
+ //#endregion
4927
+ // -------------------------------------------------------------------------------
4928
+ // #region STORE CREDITS
4929
+ /**
4930
+ * Apply a credit change, the value is negative for a purchasse
4931
+ * @param customerId The id of the customer
4932
+ * @param creditSlug The credit *slug name as configured in the space
4933
+ * @param amount The amount to add or remove
4934
+ * @param comment The reason for this change
4935
+ * @param user The user doing the action
4936
+ * @returns
4937
+ */
4508
4938
  this._modifyStoreCredit = async (customerId, creditSlug, amount, comment, user) => {
4509
4939
  if (!customerId)
4510
4940
  throw new Error('Customer ID is required');
@@ -4515,15 +4945,18 @@ class Space {
4515
4945
  if (!user)
4516
4946
  throw new Error('The user doing the action is required');
4517
4947
  if (amount == 0)
4518
- return true;
4948
+ return true; // do nothing if amount is 0
4519
4949
  const customerPath = DatabaseService_1.default.addToPath(this._space_ref.path, this._space_ref.id + '/customers');
4520
4950
  const historyPath = DatabaseService_1.default.addToPath(this._space_ref.path, this._space_ref.id + '/store_credit_history');
4951
+ // fetch the user document
4521
4952
  const customer = await DatabaseService_1.default.getDocument(customerPath, customerId);
4522
4953
  if (!customer.exists)
4523
4954
  new Error('Could not find customer');
4955
+ // add the amount
4524
4956
  const credits = customer.data.store_credits || [];
4525
4957
  const index = credits.findIndex((x) => x.credit_slug == creditSlug);
4526
4958
  if (index == -1) {
4959
+ // first time, add a new entry
4527
4960
  credits.push({
4528
4961
  amount: amount,
4529
4962
  credit_slug: creditSlug
@@ -4532,6 +4965,7 @@ class Space {
4532
4965
  else {
4533
4966
  credits[index] = Object.assign(Object.assign({}, credits[index]), { amount: credits[index].amount + amount });
4534
4967
  }
4968
+ // create history
4535
4969
  const history = {
4536
4970
  amount: amount,
4537
4971
  comment: comment,
@@ -4543,16 +4977,24 @@ class Space {
4543
4977
  const newDoc = await DatabaseService_1.default.addDocument(historyPath, history);
4544
4978
  if (!newDoc)
4545
4979
  throw new Error('Unable to create the credit history');
4980
+ // save the new amount
4546
4981
  if (!(await DatabaseService_1.default.saveDocument(customerPath, customerId, 0, { store_credits: credits }, { merge: true })))
4547
4982
  throw new Error('Unable to save new credit value');
4548
4983
  return true;
4549
4984
  };
4985
+ /**
4986
+ * Get the latess credit amount for a customer
4987
+ * @param customerId The customer ID
4988
+ * @param creditSlug The slug of the credit to get
4989
+ * @returns The amount
4990
+ */
4550
4991
  this._getStoreCredit = async (customerId, creditSlug) => {
4551
4992
  if (!customerId)
4552
4993
  throw new Error('Customer ID is required');
4553
4994
  if (!creditSlug)
4554
4995
  throw new Error('The credit slug is required');
4555
4996
  const customerPath = DatabaseService_1.default.addToPath(this._space_ref.path, this._space_ref.id + '/customers');
4997
+ // fetch the user document
4556
4998
  const customer = await DatabaseService_1.default.getDocument(customerPath, customerId);
4557
4999
  if (!customer.exists)
4558
5000
  new Error('Could not find customer');
@@ -4561,6 +5003,12 @@ class Space {
4561
5003
  return 0;
4562
5004
  return credit.amount;
4563
5005
  };
5006
+ /**
5007
+ * Get the full history of credit for a customer
5008
+ * @param customerId The customer ID
5009
+ * @param creditSlug The slug of the credit to get
5010
+ * @returns A list of IStoreCreditHistory
5011
+ */
4564
5012
  this._getStoreCreditHistory = async (customerId, creditSlug) => {
4565
5013
  if (!customerId)
4566
5014
  throw new Error('Customer ID is required');
@@ -4577,6 +5025,13 @@ class Space {
4577
5025
  });
4578
5026
  return histories.map((x) => x.data);
4579
5027
  };
5028
+ /**
5029
+ * Validate if an amount can be deducted from the credit of a customer
5030
+ * @param customerId The customer ID
5031
+ * @param creditSlug The credit slug to verify
5032
+ * @param amount The amount to deduct
5033
+ * @returns True if the amount is less or equal to the customer credit
5034
+ */
4580
5035
  this._validateCredit = async (customerId, creditSlug, amount) => {
4581
5036
  if (!customerId)
4582
5037
  throw new Error('Customer ID is required');
@@ -4587,9 +5042,13 @@ class Space {
4587
5042
  const current = await this._getStoreCredit(customerId, creditSlug);
4588
5043
  return amount <= current;
4589
5044
  };
5045
+ /**
5046
+ * Get the space available credits
5047
+ */
4590
5048
  this._getSpaceCredits = () => {
4591
5049
  const credits = [...(this._space.store_credits || [])];
4592
5050
  if (!credits.some((x) => x.credit_slug == 'default')) {
5051
+ // add the default one if not present
4593
5052
  credits.push({
4594
5053
  credit_slug: 'default',
4595
5054
  name: [
@@ -4600,6 +5059,11 @@ class Space {
4600
5059
  }
4601
5060
  return credits;
4602
5061
  };
5062
+ //#
5063
+ //#region MENUS
5064
+ /**
5065
+ * Retourne tous les menus du space
5066
+ */
4603
5067
  this._getMenus = async (options) => {
4604
5068
  if (!this._user)
4605
5069
  throw new Error('Invalid or unauthenticated user');
@@ -4623,6 +5087,9 @@ class Space {
4623
5087
  return [];
4624
5088
  }
4625
5089
  };
5090
+ /**
5091
+ * Retourne le menu actif pour un slug
5092
+ */
4626
5093
  this._getActiveMenuBySlug = async (slug) => {
4627
5094
  if (!slug)
4628
5095
  return undefined;
@@ -4635,12 +5102,16 @@ class Space {
4635
5102
  });
4636
5103
  return results.length ? results[0] : undefined;
4637
5104
  };
5105
+ /**
5106
+ * Retourne tous les menus actifs
5107
+ */
4638
5108
  this._getAllActiveMenus = async () => {
4639
5109
  const results = await this._getMenus({
4640
5110
  query: [{ field: 'active', operator: '==', value: true }]
4641
5111
  });
4642
5112
  return results;
4643
5113
  };
5114
+ //#endregion
4644
5115
  this.attributes = {
4645
5116
  get: this._getAttributes,
4646
5117
  add: this._addAttribute,
@@ -4685,6 +5156,10 @@ class Space {
4685
5156
  getPage: this._getProductsPage,
4686
5157
  getAll: this._getAllProducts,
4687
5158
  listener: this._productsListener,
5159
+ // Automatic declinations
5160
+ // generate: {
5161
+ // declinations: this._generateProductDeclinations
5162
+ // },
4688
5163
  batch: {
4689
5164
  create: this._batchProductsCreate,
4690
5165
  set: this._batchProductsSet
@@ -5019,8 +5494,17 @@ class Space {
5019
5494
  return await this._getAllActiveMenus();
5020
5495
  }
5021
5496
  };
5497
+ /**
5498
+ * Get all space properties
5499
+ */
5022
5500
  this.data = () => this._space;
5501
+ /**
5502
+ * Get the space name
5503
+ */
5023
5504
  this.getName = () => this._space.name;
5505
+ /**
5506
+ * Get the space ID
5507
+ */
5024
5508
  this.getId = () => {
5025
5509
  if (!!!this._space.id) {
5026
5510
  throw 'Id not yet set';
@@ -5030,6 +5514,8 @@ class Space {
5030
5514
  this.isMultiPromo = () => {
5031
5515
  return !!this._space.multipromo_aware ? this._space.multipromo_aware : false;
5032
5516
  };
5517
+ //#endregion
5518
+ //#region NOTES
5033
5519
  this._getNotes = async (parentId, type) => {
5034
5520
  try {
5035
5521
  const path = DatabaseService_1.default.addToPath(this._space_ref.path, this._space_ref.id + '/notes');
@@ -5069,6 +5555,7 @@ class Space {
5069
5555
  add: this._addNote,
5070
5556
  delete: this._deleteNote
5071
5557
  };
5558
+ // Console.log if space ref has less or more path elements than expected
5072
5559
  const lengthToCheck = space_ref.path.startsWith('/') ? 6 : 5;
5073
5560
  if (space_ref.path.split('/').length != lengthToCheck) {
5074
5561
  try {
@@ -5089,13 +5576,15 @@ class Space {
5089
5576
  if (!options)
5090
5577
  return undefined;
5091
5578
  if (options.id)
5092
- return options.id;
5579
+ return options.id; // request a specific id
5093
5580
  if (options.query && options.query.length == 1 && options.query[0].operator == '==') {
5094
5581
  if (options.query[0].field == 'id' || options.query[0].field == 'slug')
5095
5582
  return options.query[0].value;
5096
5583
  }
5097
5584
  return undefined;
5098
5585
  }
5586
+ //#endregion
5587
+ //#region INDEXED PRODUCTS
5099
5588
  async _getIndexedProductFromProduct(product) {
5100
5589
  const categories = product.category ? await this.categories.get({ id: product.category }) : undefined;
5101
5590
  const brands = product.brand ? await this.brands.get({ id: product.brand }) : undefined;