addio-ecomm-sdk 1.3.77 → 1.3.78

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 (106) hide show
  1. package/.vscode/settings.json +34 -34
  2. package/README.md +79 -79
  3. package/dist/index.d.ts +203 -203
  4. package/dist/index.js +1237 -1237
  5. package/dist/lib/constants/components/CreditCardInput.d.ts +11 -11
  6. package/dist/lib/constants/components/CreditCardInput.js +65 -65
  7. package/dist/lib/constants/components/Snackbar.d.ts +11 -11
  8. package/dist/lib/constants/components/Snackbar.js +29 -29
  9. package/dist/lib/constants/contexts/CartContext/CartContextProvider.d.ts +7 -7
  10. package/dist/lib/constants/contexts/CartContext/CartContextProvider.js +640 -640
  11. package/dist/lib/constants/contexts/CartContext/index.d.ts +79 -79
  12. package/dist/lib/constants/contexts/CartContext/index.js +47 -47
  13. package/dist/lib/constants/contexts/DataContext/DataContextProvider.d.ts +15 -15
  14. package/dist/lib/constants/contexts/DataContext/DataContextProvider.js +173 -173
  15. package/dist/lib/constants/contexts/DataContext/index.d.ts +47 -47
  16. package/dist/lib/constants/contexts/DataContext/index.js +27 -27
  17. package/dist/lib/constants/contexts/LogContext/LogContextProvider.d.ts +6 -6
  18. package/dist/lib/constants/contexts/LogContext/LogContextProvider.js +40 -40
  19. package/dist/lib/constants/contexts/LogContext/index.d.ts +7 -7
  20. package/dist/lib/constants/contexts/LogContext/index.js +7 -7
  21. package/dist/lib/constants/contexts/ModalContext/ModalContextProvider.d.ts +7 -7
  22. package/dist/lib/constants/contexts/ModalContext/ModalContextProvider.js +61 -61
  23. package/dist/lib/constants/contexts/ModalContext/index.d.ts +14 -14
  24. package/dist/lib/constants/contexts/ModalContext/index.js +16 -16
  25. package/dist/lib/constants/contexts/SDKContext/SDKProvider.d.ts +8 -8
  26. package/dist/lib/constants/contexts/SDKContext/SDKProvider.js +23 -23
  27. package/dist/lib/constants/contexts/SDKContext/index.d.ts +4 -4
  28. package/dist/lib/constants/contexts/SDKContext/index.js +4 -4
  29. package/dist/lib/constants/contexts/SnackbarContext/SnackbarContext.d.ts +4 -4
  30. package/dist/lib/constants/contexts/SnackbarContext/SnackbarContext.js +6 -6
  31. package/dist/lib/constants/contexts/SnackbarContext/SnackbarContextProvider.d.ts +12 -12
  32. package/dist/lib/constants/contexts/SnackbarContext/SnackbarContextProvider.js +38 -38
  33. package/dist/lib/constants/contexts/SnackbarContext/interfaces/ISnackbarContext.d.ts +19 -19
  34. package/dist/lib/constants/contexts/SnackbarContext/interfaces/ISnackbarContext.js +21 -21
  35. package/dist/lib/constants/contexts/StockNotifContext/StockNotifContextProvider.d.ts +7 -7
  36. package/dist/lib/constants/contexts/StockNotifContext/StockNotifContextProvider.js +112 -112
  37. package/dist/lib/constants/contexts/StockNotifContext/index.d.ts +10 -10
  38. package/dist/lib/constants/contexts/StockNotifContext/index.js +10 -10
  39. package/dist/lib/constants/contexts/UserContext/UserContextProvider.d.ts +5 -5
  40. package/dist/lib/constants/contexts/UserContext/UserContextProvider.js +313 -313
  41. package/dist/lib/constants/contexts/UserContext/index.d.ts +54 -54
  42. package/dist/lib/constants/contexts/UserContext/index.js +28 -28
  43. package/dist/lib/constants/contexts/WishlistContext/WishlistContextProvider.d.ts +6 -6
  44. package/dist/lib/constants/contexts/WishlistContext/WishlistContextProvider.js +231 -231
  45. package/dist/lib/constants/contexts/WishlistContext/index.d.ts +12 -12
  46. package/dist/lib/constants/contexts/WishlistContext/index.js +12 -12
  47. package/dist/lib/constants/hooks/useCart.d.ts +2 -2
  48. package/dist/lib/constants/hooks/useCart.js +11 -11
  49. package/dist/lib/constants/hooks/useData.d.ts +2 -2
  50. package/dist/lib/constants/hooks/useData.js +11 -11
  51. package/dist/lib/constants/hooks/useLogs.d.ts +2 -2
  52. package/dist/lib/constants/hooks/useLogs.js +11 -11
  53. package/dist/lib/constants/hooks/useModal.d.ts +2 -2
  54. package/dist/lib/constants/hooks/useModal.js +11 -11
  55. package/dist/lib/constants/hooks/useSDK.d.ts +2 -2
  56. package/dist/lib/constants/hooks/useSDK.js +11 -11
  57. package/dist/lib/constants/hooks/useSnackbar.d.ts +2 -2
  58. package/dist/lib/constants/hooks/useSnackbar.js +11 -11
  59. package/dist/lib/constants/hooks/useStockNotif.d.ts +2 -2
  60. package/dist/lib/constants/hooks/useStockNotif.js +11 -11
  61. package/dist/lib/constants/hooks/useUser.d.ts +2 -2
  62. package/dist/lib/constants/hooks/useUser.js +11 -11
  63. package/dist/lib/constants/hooks/useWishlist.d.ts +2 -2
  64. package/dist/lib/constants/hooks/useWishlist.js +11 -11
  65. package/dist/lib/models/image/index.d.ts +6 -6
  66. package/dist/lib/models/image/index.js +10 -10
  67. package/dist/lib/models/stockNotification/index.d.ts +13 -13
  68. package/dist/lib/models/stockNotification/index.js +70 -70
  69. package/dist/lib/models/wishlist/index.d.ts +14 -14
  70. package/dist/lib/models/wishlist/index.js +86 -86
  71. package/dist/utils/StripeErrors.d.ts +24 -24
  72. package/dist/utils/StripeErrors.js +55 -55
  73. package/dist/utils/algolia.d.ts +3 -3
  74. package/dist/utils/algolia.js +35 -35
  75. package/dist/utils/analytics.d.ts +71 -71
  76. package/dist/utils/analytics.js +246 -246
  77. package/dist/utils/cart.d.ts +3 -3
  78. package/dist/utils/cart.js +65 -65
  79. package/dist/utils/contentful.d.ts +10 -10
  80. package/dist/utils/contentful.js +63 -63
  81. package/dist/utils/functions.d.ts +21 -21
  82. package/dist/utils/functions.js +183 -183
  83. package/dist/utils/getSDK.d.ts +4 -4
  84. package/dist/utils/getSDK.js +19 -19
  85. package/dist/utils/initStoreData.d.ts +3 -3
  86. package/dist/utils/initStoreData.js +17 -17
  87. package/dist/utils/interfaces/IClientCMSData.d.ts +132 -132
  88. package/dist/utils/interfaces/IClientCMSData.js +2 -2
  89. package/dist/utils/interfaces/IEndpointResult.d.ts +10 -10
  90. package/dist/utils/interfaces/IEndpointResult.js +2 -2
  91. package/dist/utils/interfaces/IFacebookUserProfile.d.ts +10 -10
  92. package/dist/utils/interfaces/IFacebookUserProfile.js +2 -2
  93. package/dist/utils/interfaces/IFilter.d.ts +23 -23
  94. package/dist/utils/interfaces/IFilter.js +2 -2
  95. package/dist/utils/interfaces/IGoogleUserProfile.d.ts +7 -7
  96. package/dist/utils/interfaces/IGoogleUserProfile.js +2 -2
  97. package/dist/utils/interfaces/ISDKConfig.d.ts +7 -7
  98. package/dist/utils/interfaces/ISDKConfig.js +2 -2
  99. package/dist/utils/interfaces/ISpaceData.d.ts +18 -18
  100. package/dist/utils/interfaces/ISpaceData.js +2 -2
  101. package/dist/utils/larivieremeunier.d.ts +3 -3
  102. package/dist/utils/larivieremeunier.js +156 -156
  103. package/dist/utils/technosupply.d.ts +3 -3
  104. package/dist/utils/technosupply.js +155 -155
  105. package/package.json +61 -61
  106. package/publish.sh +132 -132
package/dist/index.js CHANGED
@@ -1,1238 +1,1238 @@
1
- "use strict";
2
- var __rest = (this && this.__rest) || function (s, e) {
3
- var t = {};
4
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
5
- t[p] = s[p];
6
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
7
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
8
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
9
- t[p[i]] = s[p[i]];
10
- }
11
- return t;
12
- };
13
- var __importDefault = (this && this.__importDefault) || function (mod) {
14
- return (mod && mod.__esModule) ? mod : { "default": mod };
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- const isomorphic_unfetch_1 = __importDefault(require("isomorphic-unfetch"));
18
- const image_1 = __importDefault(require("./lib/models/image"));
19
- const wishlist_1 = __importDefault(require("./lib/models/wishlist"));
20
- const stockNotification_1 = __importDefault(require("./lib/models/stockNotification"));
21
- const Product_1 = __importDefault(require("addio-admin-sdk/dist/lib/Product"));
22
- const js_cookie_1 = __importDefault(require("js-cookie"));
23
- const g2_1 = require("addio-admin-sdk/dist/rules/GR/utils/g2");
24
- const anonymisation_1 = require("addio-admin-sdk/dist/utils/anonymisation");
25
- const functions_1 = require("./utils/functions");
26
- const zones_1 = require("addio-admin-sdk/dist/utils/zones");
27
- const lodash_1 = require("lodash");
28
- const functions_2 = require("./utils/functions");
29
- const data_1 = require("addio-admin-sdk/dist/utils/data");
30
- const moment_1 = __importDefault(require("moment"));
31
- const object_1 = require("addio-admin-sdk/dist/utils/object");
32
- const services_1 = require("addio-admin-sdk/dist/utils/services");
33
- const logs_1 = require("addio-admin-sdk/dist/services/logs");
34
- class SDK {
35
- constructor() {
36
- this.init = async (sdk_config) => {
37
- this._api = sdk_config.api;
38
- this._token = sdk_config.token;
39
- this._url = sdk_config.url;
40
- this._org = sdk_config.org;
41
- this._userToken = !!sdk_config.userToken ? sdk_config.userToken : '';
42
- this._storeData = null;
43
- };
44
- this.getAPIInfos = () => ({
45
- api: this._api,
46
- token: this._token,
47
- userToken: this._userToken,
48
- org: this._org
49
- });
50
- this.getSDKOrgInitials = () => {
51
- const orgID = this.getAPIInfos().org;
52
- if (!!!orgID)
53
- return '';
54
- if (orgID.length <= 3)
55
- return orgID.toUpperCase();
56
- return (0, services_1.getOrgInitialsByID)(orgID);
57
- };
58
- this.initWishlist = async (wishlist) => {
59
- this._wishlist = new wishlist_1.default(wishlist, this._api, this._token, this._userToken, this.setUserToken);
60
- return await this._wishlist.getFromDatabase(wishlist);
61
- };
62
- this.initStockNotif = async (stockNotif) => {
63
- this._stockNotif = new stockNotification_1.default(stockNotif, this._api, this._token, this._userToken, this.setUserToken);
64
- return await this._stockNotif.getFromDatabase(stockNotif);
65
- };
66
- this.initStoreData = async (defaultData) => {
67
- if (!!defaultData) {
68
- this._storeData = defaultData;
69
- return;
70
- }
71
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/store`, {
72
- method: 'GET',
73
- headers: {
74
- authorization: `Bearer ${this._token}`,
75
- 'Content-Type': 'application/json'
76
- }
77
- });
78
- const responseData = await fetchData.json();
79
- if (responseData.status !== 200) {
80
- throw new Error(JSON.stringify({ status: responseData.status, error: responseData.error }));
81
- }
82
- this._storeData = responseData.data;
83
- return this._storeData;
84
- };
85
- this.shouldShowFixedPromoBanner = (fixedPromoBannerData) => {
86
- if (!!!fixedPromoBannerData.is_active) {
87
- return false;
88
- }
89
- if (!!fixedPromoBannerData.active_between_dates && !!fixedPromoBannerData.active_between_dates.length) {
90
- const date = fixedPromoBannerData.active_between_dates.some((date) => {
91
- return (0, moment_1.default)().isBetween((0, moment_1.default)((0, data_1.formatDate)(date.start)), (0, moment_1.default)((0, data_1.formatDate)(date.end)), 'days', '[]');
92
- });
93
- return !!date;
94
- }
95
- return true;
96
- };
97
- this.getInventoryItem = async (sku, locale) => {
98
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/inventory/${encodeURIComponent(sku)}`, {
99
- method: 'GET',
100
- headers: {
101
- Authorization: `Bearer ${this._token}`,
102
- 'x-gng-ecomm-locale': locale
103
- }
104
- });
105
- const responseData = await fetchData.json();
106
- if (responseData.status !== 200)
107
- throw new Error(JSON.stringify({ status: responseData.status, error: responseData.error }));
108
- return responseData.data;
109
- };
110
- this.getFullInventory = async (locale) => {
111
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/inventory`, {
112
- method: 'GET',
113
- headers: {
114
- Authorization: `Bearer ${this._token}`,
115
- 'x-gng-ecomm-locale': locale
116
- }
117
- });
118
- const responseData = await fetchData.json();
119
- if (responseData.status !== 200)
120
- throw new Error(JSON.stringify({ status: responseData.status, error: responseData.error }));
121
- return responseData.data;
122
- };
123
- this.inventory = {
124
- getFullInventory: this.getFullInventory,
125
- getInventoryItem: this.getInventoryItem
126
- };
127
- this.setUserToken = (token) => {
128
- this._userToken = token;
129
- localStorage.setItem('userToken', token);
130
- js_cookie_1.default.set('userToken', token, { sameSite: 'strict', secure: true });
131
- };
132
- this.loginUserWithFacebook = async (fb) => {
133
- const { email, id, name } = fb;
134
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/signinwithfacebook`, {
135
- method: 'POST',
136
- headers: {
137
- authorization: `Bearer ${this._token}`,
138
- 'Content-Type': 'application/json'
139
- },
140
- body: JSON.stringify({ email, userID: id, name })
141
- });
142
- const responseData = await fetchData.json();
143
- if (responseData.status !== 200) {
144
- throw { status: responseData.status, error: responseData.error };
145
- }
146
- try {
147
- if (!!!responseData.data.userData) {
148
- throw {
149
- status: responseData.status,
150
- error: 'user_not_found'
151
- };
152
- }
153
- if (!!responseData.data.cartData) {
154
- localStorage.setItem(`${this._org}__cart`, responseData.data.cartData.id);
155
- }
156
- if (responseData.token)
157
- this.setUserToken(responseData.token);
158
- return { userData: responseData.data.userData, cart: responseData.data.cartData };
159
- }
160
- catch (err) {
161
- return err.toString();
162
- }
163
- };
164
- this.anonymousResetPassword = async (locale, id, oldPassword, newPassword, confirmPassword) => {
165
- try {
166
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/anonymousResetPassword`, {
167
- method: 'POST',
168
- headers: {
169
- authorization: `Bearer ${this._token}`,
170
- 'Content-Type': 'application/json',
171
- 'x-gng-ecomm-locale': locale
172
- },
173
- body: JSON.stringify({
174
- id,
175
- oldPassword,
176
- newPassword,
177
- confirmPassword
178
- })
179
- });
180
- const responseData = await fetchData.json();
181
- if (responseData.status !== 200) {
182
- return { status: responseData.status, error: responseData.error };
183
- }
184
- return { status: responseData.status, data: { done: true } };
185
- }
186
- catch (error) {
187
- console.log('error dans le catch du sdk: ', typeof error, error);
188
- return {
189
- status: 400,
190
- error: typeof error === 'string' ? error : error.toString()
191
- };
192
- }
193
- };
194
- this.loginUser = async (locale, email, password, keepCart = false, isClerk = false) => {
195
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/signin`, {
196
- method: 'POST',
197
- headers: {
198
- authorization: `Bearer ${this._token}`,
199
- 'Content-Type': 'application/json',
200
- 'x-gng-ecomm-locale': locale
201
- },
202
- body: JSON.stringify({ email, password, isClerk })
203
- });
204
- const responseData = await fetchData.json();
205
- if (responseData.status !== 200) {
206
- throw { status: responseData.status, error: responseData.error };
207
- }
208
- try {
209
- if (!!!responseData.data.userData) {
210
- throw {
211
- status: responseData.status,
212
- error: 'user_not_found'
213
- };
214
- }
215
- const cartData = responseData.data.cartData;
216
- const shouldResetCartData = !!cartData && !!cartData.clerk_id && !!!isClerk;
217
- const currentCartInLocalStorage = !!shouldResetCartData || !!!keepCart ? false : localStorage.getItem(`${this._org}__cart`);
218
- if (!!cartData && !!!currentCartInLocalStorage) {
219
- localStorage.setItem(`${this._org}__cart`, responseData.data.cartData.id);
220
- }
221
- if (responseData.token)
222
- this.setUserToken(responseData.token);
223
- return {
224
- userData: responseData.data.userData,
225
- cart: shouldResetCartData ? null : cartData
226
- };
227
- }
228
- catch (err) {
229
- return err.toString();
230
- }
231
- };
232
- this.loginUserWithID = async (locale, id, password, keepCart = false, isClerk = false) => {
233
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/signinwithid`, {
234
- method: 'POST',
235
- headers: {
236
- authorization: `Bearer ${this._token}`,
237
- 'Content-Type': 'application/json',
238
- 'x-gng-ecomm-locale': locale
239
- },
240
- body: JSON.stringify({ id, password, isClerk })
241
- });
242
- const responseData = await fetchData.json();
243
- if (responseData.status !== 200) {
244
- throw { status: responseData.status, error: responseData.error };
245
- }
246
- if (!!!responseData.data.userData) {
247
- throw {
248
- status: responseData.status,
249
- error: 'user_not_found'
250
- };
251
- }
252
- const currentCartInLocalStorage = !!!keepCart ? false : localStorage.getItem(`${this._org}__cart`);
253
- if (!!responseData.data.cartData && !!!currentCartInLocalStorage) {
254
- localStorage.setItem(`${this._org}__cart`, responseData.data.cartData.id);
255
- }
256
- if (responseData.token)
257
- this.setUserToken(responseData.token);
258
- return { userData: responseData.data.userData, cart: responseData.data.cartData };
259
- };
260
- this.checkG2ForCustomer = async (id, currentCustomer, customerGroups) => {
261
- try {
262
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/services/g2/customers/${id}`, {
263
- method: 'GET',
264
- headers: {
265
- authorization: `Bearer ${this._token}`,
266
- 'Content-Type': 'application/json'
267
- }
268
- });
269
- const G2RequestRes = await fetchData.json();
270
- if (!!fetchData.status && fetchData.status !== 200)
271
- throw `${fetchData.status}`;
272
- if (!!!G2RequestRes || !!!G2RequestRes.length)
273
- throw 'no data';
274
- const allG2Customers = G2RequestRes;
275
- const customerToCheck = allG2Customers[0];
276
- if (!!(0, object_1.recursiveCheckObject)(customerToCheck, 'client.noClient') &&
277
- customerToCheck.client.noClient.toUpperCase() !== id.toUpperCase())
278
- throw 'no data';
279
- const customerToCreate = (0, g2_1.transformG2CustomerToCustomer)(customerToCheck, currentCustomer, customerGroups);
280
- const anonymizedCustomer = (0, anonymisation_1.hideG2CustomerInfoIfNeeded)(customerToCreate);
281
- return (anonymizedCustomer !== null && anonymizedCustomer !== void 0 ? anonymizedCustomer : customerToCreate);
282
- }
283
- catch (e) {
284
- console.log('error on fetching G2 customer: ', e.toString());
285
- return;
286
- }
287
- };
288
- this.createProCustomer = async (customer) => {
289
- try {
290
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/user/createProWithId`, {
291
- method: 'POST',
292
- headers: {
293
- authorization: `Bearer ${this._token}`,
294
- 'Content-Type': 'application/json'
295
- },
296
- body: JSON.stringify({ customer })
297
- });
298
- const result = await fetchData.json();
299
- if (!!fetchData.status && fetchData.status !== 200)
300
- throw `${result.data}`;
301
- return true;
302
- }
303
- catch (e) {
304
- console.log('error on creating G2 customer: ', e.toString());
305
- return e.toString();
306
- }
307
- };
308
- this.fetchCustomPriceList = async (customerID, isPA = false) => {
309
- try {
310
- const id = !!isPA ? `${customerID}PA` : customerID;
311
- const g2PriceListQuery = await (0, isomorphic_unfetch_1.default)(`${this._api}/services/g2/customers/${id}/customPrices`, {
312
- method: 'POST',
313
- headers: {
314
- authorization: `Bearer ${this._token}`,
315
- 'Content-Type': 'application/json'
316
- }
317
- });
318
- const prices = await g2PriceListQuery.json();
319
- if (!!g2PriceListQuery.status && g2PriceListQuery.status !== 200)
320
- throw `Error - ${g2PriceListQuery.status}`;
321
- if (!!!prices || !!!prices.length)
322
- throw 'Error - no data';
323
- return prices;
324
- }
325
- catch (e) {
326
- console.log('error on fetching customer from G2: ', e);
327
- return;
328
- }
329
- };
330
- this.validateAccount = async (code) => {
331
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/user/validateEmail`, {
332
- method: 'POST',
333
- headers: {
334
- authorization: `Bearer ${this._token}`,
335
- 'Content-Type': 'application/json',
336
- 'x-gng-ecomm-token': this._userToken
337
- },
338
- body: JSON.stringify({ code: code })
339
- });
340
- const responseData = await fetchData.json();
341
- if (responseData.status !== 200) {
342
- throw new Error(JSON.stringify({ status: responseData.status, error: responseData.error }));
343
- }
344
- if (!!!responseData.data.userData) {
345
- throw new Error(JSON.stringify({ status: responseData.status, error: 'User not sent in request.' }));
346
- }
347
- if (responseData.token)
348
- this.setUserToken(responseData.token);
349
- return responseData.data.userData;
350
- };
351
- this.logout = () => {
352
- this.setUserToken('');
353
- localStorage.removeItem(`${this._org}__cart`);
354
- localStorage.removeItem('userLogged');
355
- localStorage.removeItem('isPro');
356
- localStorage.removeItem('foundInG2');
357
- localStorage.removeItem('customPriceList');
358
- localStorage.removeItem('lastCustomPriceFetch');
359
- localStorage.removeItem('userToken');
360
- localStorage.removeItem('wishlist');
361
- localStorage.removeItem('stockNotification');
362
- js_cookie_1.default.remove('userToken', { expires: new Date(0) });
363
- };
364
- this.registerUser = async (locale, userData, password) => {
365
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/register`, {
366
- method: 'PUT',
367
- headers: {
368
- Authorization: `Bearer ${this._token}`,
369
- 'Content-Type': 'application/json',
370
- 'x-gng-ecomm-locale': locale
371
- },
372
- body: JSON.stringify({ userData: userData, password: password })
373
- });
374
- if (fetchData.status == 200)
375
- return { status: 200, error: '' };
376
- const responseData = await fetchData.json();
377
- return { status: responseData.status, error: responseData.error };
378
- };
379
- this.getUser = async (keepTempHash) => {
380
- let token = this._userToken;
381
- if (!!!token) {
382
- const localToken = localStorage.getItem('userToken');
383
- if (!!localToken) {
384
- token = localToken;
385
- }
386
- }
387
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/user/get`, {
388
- method: 'GET',
389
- headers: {
390
- authorization: `Bearer ${this._token}`,
391
- 'Content-Type': 'application/json',
392
- 'x-gng-ecomm-token': token
393
- }
394
- });
395
- const responseData = await fetchData.json();
396
- if (responseData.status !== 200) {
397
- throw new Error(JSON.stringify({ status: responseData.status, error: responseData.error }));
398
- }
399
- if (!!!responseData.data.userData) {
400
- throw new Error(JSON.stringify({ status: responseData.status, error: 'User not sent in request.' }));
401
- }
402
- if (responseData.token)
403
- this.setUserToken(responseData.token);
404
- const _a = responseData.data.userData, { temp_hash } = _a, rest = __rest(_a, ["temp_hash"]);
405
- return Object.assign(Object.assign({}, rest), (!!keepTempHash ? { temp_hash: temp_hash } : {}));
406
- };
407
- this.saveUser = async (userData) => {
408
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/user/save`, {
409
- method: 'POST',
410
- headers: {
411
- authorization: `Bearer ${this._token}`,
412
- 'Content-Type': 'application/json',
413
- 'x-gng-ecomm-token': this._userToken
414
- },
415
- body: JSON.stringify({ userData: userData })
416
- });
417
- const responseData = await fetchData.json();
418
- if (responseData.status !== 200) {
419
- throw new Error(JSON.stringify({ status: responseData.status, error: responseData.error }));
420
- }
421
- if (responseData.data !== 'done') {
422
- throw new Error(JSON.stringify({ status: responseData.status, error: 'User not sent in response.' }));
423
- }
424
- if (responseData.token)
425
- this.setUserToken(responseData.token);
426
- return true;
427
- };
428
- this.deleteUser = async () => {
429
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/user/delete`, {
430
- method: 'GET',
431
- headers: {
432
- authorization: `Bearer ${this._token}`,
433
- 'x-gng-ecomm-token': this._userToken
434
- }
435
- });
436
- const responseData = await fetchData.json();
437
- if (responseData.status !== 200) {
438
- return false;
439
- }
440
- return true;
441
- };
442
- this.getOrders = async (lastID, iteration) => {
443
- let queryString = `?fromLastID=${lastID !== null && lastID !== void 0 ? lastID : ''}&skip=${iteration !== null && iteration !== void 0 ? iteration : ''}`;
444
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/user/orders${queryString}`, {
445
- method: 'GET',
446
- headers: {
447
- authorization: `Bearer ${this._token}`,
448
- 'Content-Type': 'application/json',
449
- 'x-gng-ecomm-token': this._userToken
450
- }
451
- });
452
- const responseData = (await fetchData.json());
453
- if (responseData.status !== 200) {
454
- return responseData.data;
455
- }
456
- return responseData.data;
457
- };
458
- this.killRepCart = async (hashed_cart_id) => {
459
- try {
460
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/user/killRepCart/${encodeURIComponent(hashed_cart_id)}`, {
461
- method: 'GET',
462
- headers: {
463
- authorization: `Bearer ${this._token}`,
464
- 'Content-Type': 'application/json',
465
- 'x-gng-ecomm-token': this._userToken
466
- }
467
- });
468
- const responseData = (await fetchData.json());
469
- if (responseData.status !== 200) {
470
- return responseData.data;
471
- }
472
- return responseData.data;
473
- }
474
- catch (error) {
475
- console.log(error);
476
- return '';
477
- }
478
- };
479
- this.getOrder = async (orderID, token) => {
480
- try {
481
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/user/order/${orderID}`, {
482
- method: 'POST',
483
- headers: {
484
- authorization: `Bearer ${this._token}`,
485
- 'Content-Type': 'application/json',
486
- 'x-gng-ecomm-token': this._userToken
487
- },
488
- body: JSON.stringify({ orderToken: token })
489
- });
490
- const responseData = (await fetchData.json());
491
- if (responseData.status !== 200) {
492
- return responseData.data;
493
- }
494
- return responseData.data;
495
- }
496
- catch (error) {
497
- console.log(error);
498
- return '';
499
- }
500
- };
501
- this.changeProfilePicture = async (file) => {
502
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/user/changeProfilePicture`, {
503
- method: 'POST',
504
- headers: {
505
- authorization: `Bearer ${this._token}`,
506
- 'Content-Type': 'application/json',
507
- 'x-gng-ecomm-token': this._userToken
508
- },
509
- body: JSON.stringify({
510
- file: file
511
- })
512
- });
513
- const responseData = (await fetchData.json());
514
- return responseData.data;
515
- };
516
- this.changePassword = async (currentPassword, newPassword) => {
517
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/user/changePassword`, {
518
- method: 'POST',
519
- headers: {
520
- authorization: `Bearer ${this._token}`,
521
- 'Content-Type': 'application/json',
522
- 'x-gng-ecomm-token': this._userToken
523
- },
524
- body: JSON.stringify({ currentPassword, newPassword })
525
- });
526
- const responseData = (await fetchData.json());
527
- if (responseData.status === 200)
528
- return responseData.data;
529
- return responseData.error;
530
- };
531
- this.sendResetPasswordEmail = async (locale, userEmail, forPro, withEmail, isTest) => {
532
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/user/sentForgotPasswordEmail`, {
533
- method: 'POST',
534
- headers: {
535
- authorization: `Bearer ${this._token}`,
536
- 'Content-Type': 'application/json',
537
- 'x-gng-ecomm-token': this._userToken,
538
- 'x-gng-ecomm-locale': locale
539
- },
540
- body: JSON.stringify({ userEmail, forPro, withEmail, isTest })
541
- });
542
- const responseData = (await fetchData.json());
543
- if (responseData.status === 200)
544
- return responseData.data;
545
- if (responseData.status === 403)
546
- return {
547
- fr: `Plus d\'un compte a été trouvé avec ${withEmail ? 'ce courriel' : 'ce ID client'}. Veuillez contacter un administrateur pour procéder.`,
548
- en: `More than one account was found with ${withEmail ? 'this email' : 'this client ID'}. Please contact an administrator to proceed.`
549
- };
550
- return responseData.error;
551
- };
552
- this.sendApplicationEmail = async (locale, form) => {
553
- try {
554
- if (!!!form.cv)
555
- return {
556
- error: "Couldn't find cv"
557
- };
558
- const cvBase64 = await (0, functions_2.toBase64)(form.cv);
559
- if (typeof cvBase64 !== 'string') {
560
- return {
561
- error: "Couldn't convert file to base64"
562
- };
563
- }
564
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/email/sendApplicationEmail`, {
565
- method: 'POST',
566
- headers: {
567
- authorization: `Bearer ${this._token}`,
568
- 'Content-Type': 'application/json',
569
- 'x-gng-ecomm-token': this._userToken,
570
- 'x-gng-ecomm-locale': locale
571
- },
572
- body: JSON.stringify(Object.assign(Object.assign({}, form), { cv: cvBase64 }))
573
- });
574
- const responseData = (await fetchData.json());
575
- if (responseData.status === 200)
576
- return responseData.data;
577
- return responseData.error;
578
- }
579
- catch (error) {
580
- return 'error';
581
- }
582
- };
583
- this.sendContactEmail = async (locale, form) => {
584
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/email/sendContactEmail`, {
585
- method: 'POST',
586
- headers: {
587
- authorization: `Bearer ${this._token}`,
588
- 'Content-Type': 'application/json',
589
- 'x-gng-ecomm-token': this._userToken,
590
- 'x-gng-ecomm-locale': locale
591
- },
592
- body: JSON.stringify(form)
593
- });
594
- const responseData = (await fetchData.json());
595
- if (responseData.status === 200)
596
- return responseData.data;
597
- return responseData.error;
598
- };
599
- this.sendGenericOtherEmail = async (locale, form, templateId, to, replyTo) => {
600
- const getSubjectByType = (type) => {
601
- switch (type) {
602
- case 'confirmation_lawn_submission':
603
- return { fr: 'Soumission gazon - Confirmation de réception', en: 'Lawn submission - Confirmation' };
604
- default:
605
- return undefined;
606
- }
607
- };
608
- try {
609
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/email/sendGenericOtherEmail`, {
610
- method: 'POST',
611
- headers: {
612
- authorization: `Bearer ${this._token}`,
613
- 'Content-Type': 'application/json',
614
- 'x-gng-ecomm-token': this._userToken,
615
- 'x-gng-ecomm-locale': locale
616
- },
617
- body: JSON.stringify(Object.assign(Object.assign({}, (!!form ? { content: form } : {})), { subject: getSubjectByType(templateId), templateId,
618
- to,
619
- replyTo }))
620
- });
621
- const responseData = (await fetchData.json());
622
- if (responseData.status === 200)
623
- return responseData.data;
624
- return responseData.error;
625
- }
626
- catch (error) {
627
- console.log('error on sendGenericOtherEmail: ', error);
628
- }
629
- };
630
- this.sendServicePageEmail = async (locale, form, type, testEmail) => {
631
- const { attachments } = form, rest = __rest(form, ["attachments"]);
632
- const updatedAttachments = [];
633
- if (!!attachments) {
634
- for (let att of attachments) {
635
- try {
636
- const cvBase64 = await (0, functions_2.toBase64)(att);
637
- updatedAttachments.push({ name: att.name, content: cvBase64 });
638
- }
639
- catch (e) {
640
- console.log('error on converting to base64: ', e);
641
- }
642
- }
643
- }
644
- const getSubjectByType = () => {
645
- switch (type) {
646
- case 'admin_3D_plans':
647
- if (!!form.project_type && form.project_type === 'conception') {
648
- return { fr: 'Conception de plans - Nouvelle demande', en: 'Project design - new request' };
649
- }
650
- else {
651
- return { fr: 'Images 3D - Nouvelle demande', en: '3D plans - new request' };
652
- }
653
- case 'admin_vegetals':
654
- return { fr: 'Commande de végétaux - nouvelle soumission', en: 'Vegetals - new quotation' };
655
- case 'admin_pickup_on_site':
656
- return { fr: 'Ramassage sur chantier - nouvelle demande', en: 'Pickup on site - new request' };
657
- case 'admin_borrow_tools':
658
- return { fr: "Location d'outils - nouvelle demande", en: 'Rent tools - new request' };
659
- case 'admin_sales_info':
660
- return {
661
- fr: 'Produits en solde - Information demandée',
662
- en: 'On sale products - Information request'
663
- };
664
- case 'admin_credit_info':
665
- return {
666
- fr: 'Département de crédit - Information demandée',
667
- en: 'Credit department - Information request'
668
- };
669
- case 'admin_transport_quote':
670
- return {
671
- fr: 'Location de camion - nouvelle soumission',
672
- en: 'Transport truck rental - new quotation'
673
- };
674
- case 'admin_special_order':
675
- return { fr: 'Commande spéciale - nouvelle demande', en: 'Special order - new request' };
676
- case 'admin_installation':
677
- return { fr: 'Installation - nouvelle soumission', en: 'Installation - new quotation' };
678
- case 'admin_find_landscaper':
679
- return { fr: 'Trouver un paysagiste - nouvelle demande', en: 'Find a landscaper - new request' };
680
- case 'admin_lawn_submission':
681
- return { fr: 'Soumission gazon - nouvelle demande', en: 'Lawn submission - new request' };
682
- case 'confirmation_find_landsacper':
683
- return { fr: 'Trouver un paysagiste - Confirmation', en: 'Find a landscaper - Confirmation' };
684
- default:
685
- return { fr: 'Demande de service - nouvelle soumission', en: 'Service request - new quotation' };
686
- }
687
- };
688
- try {
689
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/email/sendServiceStaticPageEmail`, {
690
- method: 'POST',
691
- headers: {
692
- authorization: `Bearer ${this._token}`,
693
- 'Content-Type': 'application/json',
694
- 'x-gng-ecomm-token': this._userToken,
695
- 'x-gng-ecomm-locale': locale
696
- },
697
- body: JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign({}, rest), (!!updatedAttachments && !!updatedAttachments.length ? { attachments: updatedAttachments } : {})), { subject: getSubjectByType(), title: getSubjectByType(), type: type }), (!!testEmail ? { test_email: testEmail } : {})))
698
- });
699
- const responseData = (await fetchData.json());
700
- if (responseData.status === 200)
701
- return true;
702
- return responseData.error;
703
- }
704
- catch (e) {
705
- console.log('error on calling api: ', e);
706
- if (!!updatedAttachments) {
707
- return {
708
- status: 413,
709
- error: {
710
- fr: "Vos pièces jointes n'ont pas pu être envoyées. Veuillez réessayer.",
711
- en: 'Your attachments could not be sent. Please try again.'
712
- }
713
- };
714
- }
715
- return '';
716
- }
717
- };
718
- this.sendSponsorRequestEmail = async (locale, form, template_name) => {
719
- const { plan } = form, rest = __rest(form, ["plan"]);
720
- let updatedPlan;
721
- if (!!plan) {
722
- try {
723
- const planBase64 = await (0, functions_2.toBase64)(plan);
724
- if (typeof planBase64 === 'string') {
725
- const splitString = planBase64.split(';base64,');
726
- if (!!splitString.length && !!splitString[1]) {
727
- updatedPlan = {
728
- name: plan.name,
729
- content: splitString[1]
730
- };
731
- }
732
- }
733
- }
734
- catch (e) {
735
- console.log('error on converting to base64: ', e);
736
- }
737
- }
738
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/email/sendSponsorRequestEmail`, {
739
- method: 'POST',
740
- headers: {
741
- authorization: `Bearer ${this._token}`,
742
- 'Content-Type': 'application/json',
743
- 'x-gng-ecomm-token': this._userToken,
744
- 'x-gng-ecomm-locale': locale
745
- },
746
- body: JSON.stringify({
747
- contenu: Object.assign(Object.assign(Object.assign({}, rest), { admin: true, has_plan: !!updatedPlan }), (!!updatedPlan
748
- ? {
749
- plan: updatedPlan
750
- }
751
- : {})),
752
- template_name: template_name
753
- })
754
- });
755
- const responseData = (await fetchData.json());
756
- if (responseData.status === 200)
757
- return true;
758
- return responseData.error;
759
- };
760
- this.sendPreMeetingFormEmail = async (locale, form, proId) => {
761
- const { attachments } = form, rest = __rest(form, ["attachments"]);
762
- const _a = rest.pro_infos, { pro_logo } = _a, restProInfos = __rest(_a, ["pro_logo"]);
763
- const updatedAttachments = [];
764
- let updatedLogo = '';
765
- if (!!attachments) {
766
- for (let att of attachments) {
767
- try {
768
- const cvBase64 = await (0, functions_2.toBase64)(att);
769
- updatedAttachments.push({ name: att.name, content: cvBase64 });
770
- }
771
- catch (e) {
772
- console.log('error on converting to base64: ', e);
773
- }
774
- }
775
- }
776
- if (!!pro_logo) {
777
- try {
778
- const logoBase64 = await (0, functions_2.toBase64)(pro_logo);
779
- updatedLogo = { name: pro_logo.name, content: logoBase64 };
780
- }
781
- catch (e) {
782
- console.log('error on converting logo to base64: ', e);
783
- }
784
- }
785
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/email/sendPreMeetingFormEmail`, {
786
- method: 'POST',
787
- headers: {
788
- authorization: `Bearer ${this._token}`,
789
- 'Content-Type': 'application/json',
790
- 'x-gng-ecomm-token': this._userToken,
791
- 'x-gng-ecomm-locale': locale
792
- },
793
- body: JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign({}, rest), { pro_infos: Object.assign(Object.assign({}, restProInfos), (!!updatedLogo ? { pro_logo: updatedLogo } : {})) }), (!!updatedAttachments && !!updatedAttachments.length ? { attachments: updatedAttachments } : {})), (!!proId ? { pro_id: proId } : {})))
794
- });
795
- const responseData = (await fetchData.json());
796
- if (responseData.status === 200)
797
- return true;
798
- return responseData.error;
799
- };
800
- this.sendWishlistByEmail = async (locale, contenu, template_name) => {
801
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/email/sendWishlistEmail`, {
802
- method: 'POST',
803
- headers: {
804
- authorization: `Bearer ${this._token}`,
805
- 'Content-Type': 'application/json',
806
- 'x-gng-ecomm-token': this._userToken,
807
- 'x-gng-ecomm-locale': locale
808
- },
809
- body: JSON.stringify({ contenu: contenu, template_name: template_name })
810
- });
811
- const responseData = (await fetchData.json());
812
- if (responseData.status === 200)
813
- return true;
814
- return responseData.error;
815
- };
816
- this.resetPassword = async (token, newPassword, withEmail) => {
817
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/user/resetPassword`, {
818
- method: 'POST',
819
- headers: {
820
- authorization: `Bearer ${this._token}`,
821
- 'Content-Type': 'application/json',
822
- 'x-gng-ecomm-token': this._userToken
823
- },
824
- body: JSON.stringify({ validationCode: token, newPassword, withEmail })
825
- });
826
- const responseData = (await fetchData.json());
827
- if (responseData.status === 200)
828
- return responseData.data;
829
- if (responseData.status === 403)
830
- return {
831
- fr: `Plus d\'un compte a été trouvé avec ${withEmail ? 'ce courriel' : 'ce ID client'}. Veuillez contacter un administrateur pour procéder.`,
832
- en: `More than one account was found with ${withEmail ? 'this email' : 'this client ID'}. Please contact an administrator to proceed.`
833
- };
834
- return responseData.error;
835
- };
836
- this.user = {
837
- getUser: this.getUser,
838
- saveUser: this.saveUser,
839
- deleteUser: this.deleteUser,
840
- loginUser: this.loginUser,
841
- loginUserWithID: this.loginUserWithID,
842
- loginUserWithFacebook: this.loginUserWithFacebook,
843
- logout: this.logout,
844
- registerUser: this.registerUser,
845
- killRepCart: this.killRepCart,
846
- getOrder: this.getOrder,
847
- getOrders: this.getOrders,
848
- changePassword: this.changePassword,
849
- changeProfilePicture: this.changeProfilePicture,
850
- validateAccount: this.validateAccount,
851
- sendResetPasswordEmail: this.sendResetPasswordEmail,
852
- resetPassword: this.resetPassword,
853
- sendApplicationEmail: this.sendApplicationEmail,
854
- sendContactEmail: this.sendContactEmail,
855
- sendServiceEmail: this.sendServicePageEmail,
856
- anonymousResetPassword: this.anonymousResetPassword,
857
- checkG2: this.checkG2ForCustomer,
858
- createPro: this.createProCustomer,
859
- fetchCustomPriceList: this.fetchCustomPriceList
860
- };
861
- this.getImage = (imgName, formatQuery, addImgPath = false) => {
862
- const img = new image_1.default(`${addImgPath ? this._imgPath : ''}${this._imgPath}/${imgName}`);
863
- return img.getFileDownloadUrl(formatQuery);
864
- };
865
- this.getProducts = async (page = 0, hpp = 10, query = '', filters = '', indice = 'products', f = '', useProspr = false) => {
866
- try {
867
- return await Product_1.default.fetch({
868
- app: process.env.NEXT_PUBLIC_ALGOLIA_APP,
869
- api: process.env.NEXT_PUBLIC_ALGOLIA_TOKEN,
870
- page: page,
871
- hpp: hpp,
872
- query: query,
873
- filters,
874
- indice: indice || 'products',
875
- f,
876
- useProspr,
877
- space: undefined
878
- });
879
- }
880
- catch (error) {
881
- throw error;
882
- }
883
- };
884
- this.getProduct = async (parentSlug, locale, useProdArray, noDrafts) => {
885
- let prod = undefined;
886
- if (!!useProdArray && !!useProdArray.length) {
887
- prod = useProdArray.find((fee) => fee.slug === parentSlug);
888
- }
889
- if (!!!prod) {
890
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/products/${encodeURIComponent(parentSlug)}`, {
891
- method: 'GET',
892
- headers: {
893
- Authorization: `Bearer ${this._token}`,
894
- 'x-gng-ecomm-locale': locale,
895
- 'x-gng-ecomm-token': this._userToken
896
- }
897
- });
898
- const responseData = await fetchData.json();
899
- if (responseData.status !== 200)
900
- throw new Error(JSON.stringify({ status: responseData.status, error: responseData.error }));
901
- prod = responseData.data;
902
- }
903
- if (!!noDrafts && prod.draft)
904
- return undefined;
905
- return prod;
906
- };
907
- this.getUpsellOfProducts = async (slugs, customPriceList) => {
908
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/products/getUpsellOfProductsWithProducts`, {
909
- method: 'POST',
910
- headers: {
911
- Authorization: `Bearer ${this._token}`,
912
- 'Content-Type': 'application/json'
913
- },
914
- body: JSON.stringify(Object.assign({ slugs: slugs }, (!!customPriceList ? { customPriceList: customPriceList } : {})))
915
- });
916
- const responseData = await fetchData.json();
917
- if (responseData.status !== 200)
918
- throw new Error(JSON.stringify({ status: responseData.status, error: responseData.error }));
919
- return responseData.data;
920
- };
921
- this.getAttributes = async () => {
922
- try {
923
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/attributes`, {
924
- method: 'GET',
925
- headers: {
926
- authorization: `Bearer ${this._token}`,
927
- 'Content-Type': 'application/json'
928
- }
929
- });
930
- const resJson = await fetchData.json();
931
- return resJson.data.map((a) => (Object.assign(Object.assign({}, a), { slug: !!a.slug ? a.slug : (0, functions_1.string_to_slug)((0, functions_1.translate)('fr', a.name)) })));
932
- }
933
- catch (error) {
934
- console.log('error fetch attributes: ', error);
935
- }
936
- };
937
- this.getCategories = async () => {
938
- try {
939
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/categories`, {
940
- method: 'GET',
941
- headers: {
942
- authorization: `Bearer ${this._token}`,
943
- 'Content-Type': 'application/json'
944
- }
945
- });
946
- const resJson = (await fetchData.json());
947
- return resJson.data;
948
- }
949
- catch (error) {
950
- console.log('error fetch categories: ', error);
951
- }
952
- };
953
- this.getBrands = async () => {
954
- try {
955
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/brands`, {
956
- method: 'GET',
957
- headers: {
958
- authorization: `Bearer ${this._token}`,
959
- 'Content-Type': 'application/json'
960
- }
961
- });
962
- const resJson = (await fetchData.json());
963
- return resJson.data;
964
- }
965
- catch (error) {
966
- console.log('error fetch brands: ', error);
967
- }
968
- };
969
- this.getInventoryItems = async (parentSlug) => {
970
- try {
971
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/inventories${!!parentSlug ? `/${encodeURIComponent(parentSlug)}` : ''}`, {
972
- method: 'GET',
973
- headers: {
974
- authorization: `Bearer ${this._token}`,
975
- 'Content-Type': 'application/json'
976
- }
977
- });
978
- const resJson = (await fetchData.json());
979
- return resJson.data;
980
- }
981
- catch (error) {
982
- console.log(`error fetch inventory items${!!parentSlug ? 'for parentSlug ' + parentSlug : ''}: `, error);
983
- }
984
- };
985
- this.getOneInventoryItem = async (sku) => {
986
- try {
987
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/inventory/${encodeURIComponent(sku)}`, {
988
- method: 'GET',
989
- headers: {
990
- authorization: `Bearer ${this._token}`,
991
- 'Content-Type': 'application/json'
992
- }
993
- });
994
- const resJson = (await fetchData.json());
995
- return resJson.data;
996
- }
997
- catch (error) {
998
- console.log(`error fetch inventory item for sku: ${sku}`, error);
999
- return undefined;
1000
- }
1001
- };
1002
- this.getLatestProducts = async () => {
1003
- try {
1004
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/latest_products`, {
1005
- method: 'GET',
1006
- headers: {
1007
- authorization: `Bearer ${this._token}`,
1008
- 'Content-Type': 'application/json'
1009
- }
1010
- });
1011
- const resJson = (await fetchData.json());
1012
- return resJson.data;
1013
- }
1014
- catch (error) {
1015
- console.log(`error fetching latest products`, error);
1016
- }
1017
- };
1018
- this._getFees = async () => {
1019
- try {
1020
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/products/getFees`, {
1021
- method: 'GET',
1022
- headers: {
1023
- authorization: `Bearer ${this._token}`,
1024
- 'x-gng-ecomm-token': this._userToken
1025
- }
1026
- });
1027
- const resJson = (await fetchData.json());
1028
- if (resJson.status !== 200) {
1029
- console.log('error on fetching fees: ', !!resJson.error ? resJson.error.toString() : '');
1030
- return [];
1031
- }
1032
- return resJson.data;
1033
- }
1034
- catch (error) {
1035
- console.log(`error fetching fees`, error);
1036
- }
1037
- };
1038
- this.products = {
1039
- getProducts: this.getProducts,
1040
- getProduct: this.getProduct,
1041
- getUpsellOfProducts: this.getUpsellOfProducts,
1042
- getAttributes: this.getAttributes,
1043
- getCategories: this.getCategories,
1044
- getBrands: this.getBrands,
1045
- getInventoryItems: this.getInventoryItems,
1046
- getOneInventoryItem: this.getOneInventoryItem,
1047
- getLatestProducts: this.getLatestProducts,
1048
- getFees: this._getFees
1049
- };
1050
- this.getIfAddressIsInsideZones = async (address) => {
1051
- try {
1052
- const userPos = await (0, zones_1.getPositionFromAddress)(address);
1053
- if (!!!userPos)
1054
- return [];
1055
- const { lat, lng } = userPos;
1056
- const zone = await (0, isomorphic_unfetch_1.default)(`${this._api}/shipping/zones`, {
1057
- method: 'POST',
1058
- headers: {
1059
- authorization: `Bearer ${this._token}`,
1060
- 'Content-Type': 'application/json'
1061
- },
1062
- body: JSON.stringify({ address })
1063
- });
1064
- if (zone.status !== 200)
1065
- return [];
1066
- const { zones } = (await zone.json()).data;
1067
- const google = window.google;
1068
- const insideZones = [];
1069
- for (const zone of zones) {
1070
- const polygon = new google.maps.Polygon({
1071
- paths: zone.polygon.split(';').map((coords) => ({
1072
- lat: (0, lodash_1.toNumber)(coords.split(',')[1]),
1073
- lng: (0, lodash_1.toNumber)(coords.split(',')[0])
1074
- }))
1075
- });
1076
- if (google.maps.geometry.poly.containsLocation({ lat: Number(lat), lng: Number(lng) }, polygon)) {
1077
- insideZones.push(zone.slug);
1078
- }
1079
- }
1080
- return insideZones;
1081
- }
1082
- catch (error) {
1083
- if (!!window && !!window.RemoteLog) {
1084
- ;
1085
- window.RemoteLog(`error while fetching zones - ${error.toString()}`, logs_1.LogType.ERROR);
1086
- }
1087
- console.log('error while fetching zones', error.toString());
1088
- return [];
1089
- }
1090
- };
1091
- this._pricingByQuery = async (query) => {
1092
- try {
1093
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/services/pricing/byQuery`, {
1094
- method: 'POST',
1095
- headers: {
1096
- authorization: `Bearer ${this._token}`,
1097
- 'Content-Type': 'application/json'
1098
- },
1099
- body: JSON.stringify({ query })
1100
- });
1101
- const resJson = await fetchData.json();
1102
- return resJson.data;
1103
- }
1104
- catch (error) {
1105
- throw error;
1106
- }
1107
- };
1108
- this._buyFromForm = async (form) => {
1109
- try {
1110
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/services/buy/fromForm`, {
1111
- method: 'POST',
1112
- headers: {
1113
- authorization: `Bearer ${this._token}`,
1114
- 'Content-Type': 'application/json'
1115
- },
1116
- body: JSON.stringify(form)
1117
- });
1118
- const resJson = await fetchData.json();
1119
- if (!!resJson.error) {
1120
- return false;
1121
- }
1122
- return true;
1123
- }
1124
- catch (error) {
1125
- throw error;
1126
- }
1127
- };
1128
- this._getSearchServices = async () => {
1129
- try {
1130
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/space`, {
1131
- method: 'GET',
1132
- headers: {
1133
- authorization: `Bearer ${this._token}`,
1134
- 'Content-Type': 'application/json'
1135
- }
1136
- });
1137
- const resJson = await fetchData.json();
1138
- if (!!resJson.error) {
1139
- return [];
1140
- }
1141
- const space = resJson.data;
1142
- if (!!!space || !!!space._space)
1143
- return [];
1144
- return space._space.external_services.filter((s) => s.type === 'index');
1145
- }
1146
- catch (error) {
1147
- throw error;
1148
- }
1149
- };
1150
- this.services = {
1151
- pricingByQuery: this._pricingByQuery,
1152
- buy: {
1153
- fromForm: this._buyFromForm
1154
- },
1155
- searchServices: this._getSearchServices
1156
- };
1157
- this._getAllCatalogues = async (locale) => {
1158
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/catalogues`, {
1159
- method: 'GET',
1160
- headers: {
1161
- Authorization: `Bearer ${this._token}`,
1162
- 'x-gng-ecomm-locale': locale
1163
- }
1164
- });
1165
- const responseData = await fetchData.json();
1166
- if (responseData.status !== 200)
1167
- throw new Error(JSON.stringify({ status: responseData.status, error: responseData.error }));
1168
- return responseData.data.filter((catalogue) => !!!catalogue.draft);
1169
- };
1170
- this._getCatalogueBySlug = async (slug, locale) => {
1171
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/catalogues/${slug}`, {
1172
- method: 'GET',
1173
- headers: {
1174
- Authorization: `Bearer ${this._token}`,
1175
- 'x-gng-ecomm-locale': locale
1176
- }
1177
- });
1178
- const responseData = await fetchData.json();
1179
- if (responseData.status !== 200)
1180
- throw new Error(JSON.stringify({ status: responseData.status, error: responseData.error }));
1181
- return responseData.data;
1182
- };
1183
- this.catalogues = {
1184
- getAll: this._getAllCatalogues,
1185
- getOne: this._getCatalogueBySlug
1186
- };
1187
- this.saveCustomerToMailchimpList = async (customerEmail, listID, mergeFields, tags) => {
1188
- try {
1189
- const saved = await (0, isomorphic_unfetch_1.default)(`${this._api}/marketing/mailchimp/updateOrCreateCustomer`, {
1190
- method: 'POST',
1191
- headers: {
1192
- Authorization: `Bearer ${this._token}`,
1193
- 'Content-Type': 'application/json'
1194
- },
1195
- body: JSON.stringify(Object.assign(Object.assign({ email: customerEmail, listID: listID }, (!!mergeFields ? { mergeFields: mergeFields } : {})), (!!tags ? { tags: tags } : {})))
1196
- });
1197
- const responseData = await saved.json();
1198
- if (responseData.status !== 200)
1199
- throw new Error(JSON.stringify({ status: responseData.status, error: responseData.error }));
1200
- return true;
1201
- }
1202
- catch (e) {
1203
- console.log('error on saving customer to mailchimp list: ', e.toString());
1204
- return false;
1205
- }
1206
- };
1207
- this.getProductListForSitemap = async () => {
1208
- try {
1209
- const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/analytics/sitmap_data`, {
1210
- method: 'GET',
1211
- headers: {
1212
- authorization: `Bearer ${this._token}`,
1213
- 'Content-Type': 'application/json'
1214
- }
1215
- });
1216
- const result = await fetchData.json();
1217
- if (!!fetchData.status && fetchData.status !== 200)
1218
- throw `${result.data}`;
1219
- return result.data;
1220
- }
1221
- catch (e) {
1222
- console.log('error fetching sitemap data: ', e.toString());
1223
- return e.toString();
1224
- }
1225
- };
1226
- this._api = '';
1227
- this._imgPath = '';
1228
- this._token = '';
1229
- this._userToken = '';
1230
- this._url = '';
1231
- this._org = '';
1232
- this._storeData = null;
1233
- this._wishlist = null;
1234
- this._stockNotif = null;
1235
- }
1236
- }
1237
- exports.default = SDK;
1
+ "use strict";
2
+ var __rest = (this && this.__rest) || function (s, e) {
3
+ var t = {};
4
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
5
+ t[p] = s[p];
6
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
7
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
8
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
9
+ t[p[i]] = s[p[i]];
10
+ }
11
+ return t;
12
+ };
13
+ var __importDefault = (this && this.__importDefault) || function (mod) {
14
+ return (mod && mod.__esModule) ? mod : { "default": mod };
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ const isomorphic_unfetch_1 = __importDefault(require("isomorphic-unfetch"));
18
+ const image_1 = __importDefault(require("./lib/models/image"));
19
+ const wishlist_1 = __importDefault(require("./lib/models/wishlist"));
20
+ const stockNotification_1 = __importDefault(require("./lib/models/stockNotification"));
21
+ const Product_1 = __importDefault(require("addio-admin-sdk/dist/lib/Product"));
22
+ const js_cookie_1 = __importDefault(require("js-cookie"));
23
+ const g2_1 = require("addio-admin-sdk/dist/rules/GR/utils/g2");
24
+ const anonymisation_1 = require("addio-admin-sdk/dist/utils/anonymisation");
25
+ const functions_1 = require("./utils/functions");
26
+ const zones_1 = require("addio-admin-sdk/dist/utils/zones");
27
+ const lodash_1 = require("lodash");
28
+ const functions_2 = require("./utils/functions");
29
+ const data_1 = require("addio-admin-sdk/dist/utils/data");
30
+ const moment_1 = __importDefault(require("moment"));
31
+ const object_1 = require("addio-admin-sdk/dist/utils/object");
32
+ const services_1 = require("addio-admin-sdk/dist/utils/services");
33
+ const logs_1 = require("addio-admin-sdk/dist/services/logs");
34
+ class SDK {
35
+ constructor() {
36
+ this.init = async (sdk_config) => {
37
+ this._api = sdk_config.api;
38
+ this._token = sdk_config.token;
39
+ this._url = sdk_config.url;
40
+ this._org = sdk_config.org;
41
+ this._userToken = !!sdk_config.userToken ? sdk_config.userToken : '';
42
+ this._storeData = null;
43
+ };
44
+ this.getAPIInfos = () => ({
45
+ api: this._api,
46
+ token: this._token,
47
+ userToken: this._userToken,
48
+ org: this._org
49
+ });
50
+ this.getSDKOrgInitials = () => {
51
+ const orgID = this.getAPIInfos().org;
52
+ if (!!!orgID)
53
+ return '';
54
+ if (orgID.length <= 3)
55
+ return orgID.toUpperCase();
56
+ return (0, services_1.getOrgInitialsByID)(orgID);
57
+ };
58
+ this.initWishlist = async (wishlist) => {
59
+ this._wishlist = new wishlist_1.default(wishlist, this._api, this._token, this._userToken, this.setUserToken);
60
+ return await this._wishlist.getFromDatabase(wishlist);
61
+ };
62
+ this.initStockNotif = async (stockNotif) => {
63
+ this._stockNotif = new stockNotification_1.default(stockNotif, this._api, this._token, this._userToken, this.setUserToken);
64
+ return await this._stockNotif.getFromDatabase(stockNotif);
65
+ };
66
+ this.initStoreData = async (defaultData) => {
67
+ if (!!defaultData) {
68
+ this._storeData = defaultData;
69
+ return;
70
+ }
71
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/store`, {
72
+ method: 'GET',
73
+ headers: {
74
+ authorization: `Bearer ${this._token}`,
75
+ 'Content-Type': 'application/json'
76
+ }
77
+ });
78
+ const responseData = await fetchData.json();
79
+ if (responseData.status !== 200) {
80
+ throw new Error(JSON.stringify({ status: responseData.status, error: responseData.error }));
81
+ }
82
+ this._storeData = responseData.data;
83
+ return this._storeData;
84
+ };
85
+ this.shouldShowFixedPromoBanner = (fixedPromoBannerData) => {
86
+ if (!!!fixedPromoBannerData.is_active) {
87
+ return false;
88
+ }
89
+ if (!!fixedPromoBannerData.active_between_dates && !!fixedPromoBannerData.active_between_dates.length) {
90
+ const date = fixedPromoBannerData.active_between_dates.some((date) => {
91
+ return (0, moment_1.default)().isBetween((0, moment_1.default)((0, data_1.formatDate)(date.start)), (0, moment_1.default)((0, data_1.formatDate)(date.end)), 'days', '[]');
92
+ });
93
+ return !!date;
94
+ }
95
+ return true;
96
+ };
97
+ this.getInventoryItem = async (sku, locale) => {
98
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/inventory/${encodeURIComponent(sku)}`, {
99
+ method: 'GET',
100
+ headers: {
101
+ Authorization: `Bearer ${this._token}`,
102
+ 'x-gng-ecomm-locale': locale
103
+ }
104
+ });
105
+ const responseData = await fetchData.json();
106
+ if (responseData.status !== 200)
107
+ throw new Error(JSON.stringify({ status: responseData.status, error: responseData.error }));
108
+ return responseData.data;
109
+ };
110
+ this.getFullInventory = async (locale) => {
111
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/inventory`, {
112
+ method: 'GET',
113
+ headers: {
114
+ Authorization: `Bearer ${this._token}`,
115
+ 'x-gng-ecomm-locale': locale
116
+ }
117
+ });
118
+ const responseData = await fetchData.json();
119
+ if (responseData.status !== 200)
120
+ throw new Error(JSON.stringify({ status: responseData.status, error: responseData.error }));
121
+ return responseData.data;
122
+ };
123
+ this.inventory = {
124
+ getFullInventory: this.getFullInventory,
125
+ getInventoryItem: this.getInventoryItem
126
+ };
127
+ this.setUserToken = (token) => {
128
+ this._userToken = token;
129
+ localStorage.setItem('userToken', token);
130
+ js_cookie_1.default.set('userToken', token, { sameSite: 'strict', secure: true });
131
+ };
132
+ this.loginUserWithFacebook = async (fb) => {
133
+ const { email, id, name } = fb;
134
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/signinwithfacebook`, {
135
+ method: 'POST',
136
+ headers: {
137
+ authorization: `Bearer ${this._token}`,
138
+ 'Content-Type': 'application/json'
139
+ },
140
+ body: JSON.stringify({ email, userID: id, name })
141
+ });
142
+ const responseData = await fetchData.json();
143
+ if (responseData.status !== 200) {
144
+ throw { status: responseData.status, error: responseData.error };
145
+ }
146
+ try {
147
+ if (!!!responseData.data.userData) {
148
+ throw {
149
+ status: responseData.status,
150
+ error: 'user_not_found'
151
+ };
152
+ }
153
+ if (!!responseData.data.cartData) {
154
+ localStorage.setItem(`${this._org}__cart`, responseData.data.cartData.id);
155
+ }
156
+ if (responseData.token)
157
+ this.setUserToken(responseData.token);
158
+ return { userData: responseData.data.userData, cart: responseData.data.cartData };
159
+ }
160
+ catch (err) {
161
+ return err.toString();
162
+ }
163
+ };
164
+ this.anonymousResetPassword = async (locale, id, oldPassword, newPassword, confirmPassword) => {
165
+ try {
166
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/anonymousResetPassword`, {
167
+ method: 'POST',
168
+ headers: {
169
+ authorization: `Bearer ${this._token}`,
170
+ 'Content-Type': 'application/json',
171
+ 'x-gng-ecomm-locale': locale
172
+ },
173
+ body: JSON.stringify({
174
+ id,
175
+ oldPassword,
176
+ newPassword,
177
+ confirmPassword
178
+ })
179
+ });
180
+ const responseData = await fetchData.json();
181
+ if (responseData.status !== 200) {
182
+ return { status: responseData.status, error: responseData.error };
183
+ }
184
+ return { status: responseData.status, data: { done: true } };
185
+ }
186
+ catch (error) {
187
+ console.log('error dans le catch du sdk: ', typeof error, error);
188
+ return {
189
+ status: 400,
190
+ error: typeof error === 'string' ? error : error.toString()
191
+ };
192
+ }
193
+ };
194
+ this.loginUser = async (locale, email, password, keepCart = false, isClerk = false) => {
195
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/signin`, {
196
+ method: 'POST',
197
+ headers: {
198
+ authorization: `Bearer ${this._token}`,
199
+ 'Content-Type': 'application/json',
200
+ 'x-gng-ecomm-locale': locale
201
+ },
202
+ body: JSON.stringify({ email, password, isClerk })
203
+ });
204
+ const responseData = await fetchData.json();
205
+ if (responseData.status !== 200) {
206
+ throw { status: responseData.status, error: responseData.error };
207
+ }
208
+ try {
209
+ if (!!!responseData.data.userData) {
210
+ throw {
211
+ status: responseData.status,
212
+ error: 'user_not_found'
213
+ };
214
+ }
215
+ const cartData = responseData.data.cartData;
216
+ const shouldResetCartData = !!cartData && !!cartData.clerk_id && !!!isClerk;
217
+ const currentCartInLocalStorage = !!shouldResetCartData || !!!keepCart ? false : localStorage.getItem(`${this._org}__cart`);
218
+ if (!!cartData && !!!currentCartInLocalStorage) {
219
+ localStorage.setItem(`${this._org}__cart`, responseData.data.cartData.id);
220
+ }
221
+ if (responseData.token)
222
+ this.setUserToken(responseData.token);
223
+ return {
224
+ userData: responseData.data.userData,
225
+ cart: shouldResetCartData ? null : cartData
226
+ };
227
+ }
228
+ catch (err) {
229
+ return err.toString();
230
+ }
231
+ };
232
+ this.loginUserWithID = async (locale, id, password, keepCart = false, isClerk = false) => {
233
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/signinwithid`, {
234
+ method: 'POST',
235
+ headers: {
236
+ authorization: `Bearer ${this._token}`,
237
+ 'Content-Type': 'application/json',
238
+ 'x-gng-ecomm-locale': locale
239
+ },
240
+ body: JSON.stringify({ id, password, isClerk })
241
+ });
242
+ const responseData = await fetchData.json();
243
+ if (responseData.status !== 200) {
244
+ throw { status: responseData.status, error: responseData.error };
245
+ }
246
+ if (!!!responseData.data.userData) {
247
+ throw {
248
+ status: responseData.status,
249
+ error: 'user_not_found'
250
+ };
251
+ }
252
+ const currentCartInLocalStorage = !!!keepCart ? false : localStorage.getItem(`${this._org}__cart`);
253
+ if (!!responseData.data.cartData && !!!currentCartInLocalStorage) {
254
+ localStorage.setItem(`${this._org}__cart`, responseData.data.cartData.id);
255
+ }
256
+ if (responseData.token)
257
+ this.setUserToken(responseData.token);
258
+ return { userData: responseData.data.userData, cart: responseData.data.cartData };
259
+ };
260
+ this.checkG2ForCustomer = async (id, currentCustomer, customerGroups) => {
261
+ try {
262
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/services/g2/customers/${id}`, {
263
+ method: 'GET',
264
+ headers: {
265
+ authorization: `Bearer ${this._token}`,
266
+ 'Content-Type': 'application/json'
267
+ }
268
+ });
269
+ const G2RequestRes = await fetchData.json();
270
+ if (!!fetchData.status && fetchData.status !== 200)
271
+ throw `${fetchData.status}`;
272
+ if (!!!G2RequestRes || !!!G2RequestRes.length)
273
+ throw 'no data';
274
+ const allG2Customers = G2RequestRes;
275
+ const customerToCheck = allG2Customers[0];
276
+ if (!!(0, object_1.recursiveCheckObject)(customerToCheck, 'client.noClient') &&
277
+ customerToCheck.client.noClient.toUpperCase() !== id.toUpperCase())
278
+ throw 'no data';
279
+ const customerToCreate = (0, g2_1.transformG2CustomerToCustomer)(customerToCheck, currentCustomer, customerGroups);
280
+ const anonymizedCustomer = (0, anonymisation_1.hideG2CustomerInfoIfNeeded)(customerToCreate);
281
+ return (anonymizedCustomer !== null && anonymizedCustomer !== void 0 ? anonymizedCustomer : customerToCreate);
282
+ }
283
+ catch (e) {
284
+ console.log('error on fetching G2 customer: ', e.toString());
285
+ return;
286
+ }
287
+ };
288
+ this.createProCustomer = async (customer) => {
289
+ try {
290
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/user/createProWithId`, {
291
+ method: 'POST',
292
+ headers: {
293
+ authorization: `Bearer ${this._token}`,
294
+ 'Content-Type': 'application/json'
295
+ },
296
+ body: JSON.stringify({ customer })
297
+ });
298
+ const result = await fetchData.json();
299
+ if (!!fetchData.status && fetchData.status !== 200)
300
+ throw `${result.data}`;
301
+ return true;
302
+ }
303
+ catch (e) {
304
+ console.log('error on creating G2 customer: ', e.toString());
305
+ return e.toString();
306
+ }
307
+ };
308
+ this.fetchCustomPriceList = async (customerID, isPA = false) => {
309
+ try {
310
+ const id = !!isPA ? `${customerID}PA` : customerID;
311
+ const g2PriceListQuery = await (0, isomorphic_unfetch_1.default)(`${this._api}/services/g2/customers/${id}/customPrices`, {
312
+ method: 'POST',
313
+ headers: {
314
+ authorization: `Bearer ${this._token}`,
315
+ 'Content-Type': 'application/json'
316
+ }
317
+ });
318
+ const prices = await g2PriceListQuery.json();
319
+ if (!!g2PriceListQuery.status && g2PriceListQuery.status !== 200)
320
+ throw `Error - ${g2PriceListQuery.status}`;
321
+ if (!!!prices || !!!prices.length)
322
+ throw 'Error - no data';
323
+ return prices;
324
+ }
325
+ catch (e) {
326
+ console.log('error on fetching customer from G2: ', e);
327
+ return;
328
+ }
329
+ };
330
+ this.validateAccount = async (code) => {
331
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/user/validateEmail`, {
332
+ method: 'POST',
333
+ headers: {
334
+ authorization: `Bearer ${this._token}`,
335
+ 'Content-Type': 'application/json',
336
+ 'x-gng-ecomm-token': this._userToken
337
+ },
338
+ body: JSON.stringify({ code: code })
339
+ });
340
+ const responseData = await fetchData.json();
341
+ if (responseData.status !== 200) {
342
+ throw new Error(JSON.stringify({ status: responseData.status, error: responseData.error }));
343
+ }
344
+ if (!!!responseData.data.userData) {
345
+ throw new Error(JSON.stringify({ status: responseData.status, error: 'User not sent in request.' }));
346
+ }
347
+ if (responseData.token)
348
+ this.setUserToken(responseData.token);
349
+ return responseData.data.userData;
350
+ };
351
+ this.logout = () => {
352
+ this.setUserToken('');
353
+ localStorage.removeItem(`${this._org}__cart`);
354
+ localStorage.removeItem('userLogged');
355
+ localStorage.removeItem('isPro');
356
+ localStorage.removeItem('foundInG2');
357
+ localStorage.removeItem('customPriceList');
358
+ localStorage.removeItem('lastCustomPriceFetch');
359
+ localStorage.removeItem('userToken');
360
+ localStorage.removeItem('wishlist');
361
+ localStorage.removeItem('stockNotification');
362
+ js_cookie_1.default.remove('userToken', { expires: new Date(0) });
363
+ };
364
+ this.registerUser = async (locale, userData, password) => {
365
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/register`, {
366
+ method: 'PUT',
367
+ headers: {
368
+ Authorization: `Bearer ${this._token}`,
369
+ 'Content-Type': 'application/json',
370
+ 'x-gng-ecomm-locale': locale
371
+ },
372
+ body: JSON.stringify({ userData: userData, password: password })
373
+ });
374
+ if (fetchData.status == 200)
375
+ return { status: 200, error: '' };
376
+ const responseData = await fetchData.json();
377
+ return { status: responseData.status, error: responseData.error };
378
+ };
379
+ this.getUser = async (keepTempHash) => {
380
+ let token = this._userToken;
381
+ if (!!!token) {
382
+ const localToken = localStorage.getItem('userToken');
383
+ if (!!localToken) {
384
+ token = localToken;
385
+ }
386
+ }
387
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/user/get`, {
388
+ method: 'GET',
389
+ headers: {
390
+ authorization: `Bearer ${this._token}`,
391
+ 'Content-Type': 'application/json',
392
+ 'x-gng-ecomm-token': token
393
+ }
394
+ });
395
+ const responseData = await fetchData.json();
396
+ if (responseData.status !== 200) {
397
+ throw new Error(JSON.stringify({ status: responseData.status, error: responseData.error }));
398
+ }
399
+ if (!!!responseData.data.userData) {
400
+ throw new Error(JSON.stringify({ status: responseData.status, error: 'User not sent in request.' }));
401
+ }
402
+ if (responseData.token)
403
+ this.setUserToken(responseData.token);
404
+ const _a = responseData.data.userData, { temp_hash } = _a, rest = __rest(_a, ["temp_hash"]);
405
+ return Object.assign(Object.assign({}, rest), (!!keepTempHash ? { temp_hash: temp_hash } : {}));
406
+ };
407
+ this.saveUser = async (userData) => {
408
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/user/save`, {
409
+ method: 'POST',
410
+ headers: {
411
+ authorization: `Bearer ${this._token}`,
412
+ 'Content-Type': 'application/json',
413
+ 'x-gng-ecomm-token': this._userToken
414
+ },
415
+ body: JSON.stringify({ userData: userData })
416
+ });
417
+ const responseData = await fetchData.json();
418
+ if (responseData.status !== 200) {
419
+ throw new Error(JSON.stringify({ status: responseData.status, error: responseData.error }));
420
+ }
421
+ if (responseData.data !== 'done') {
422
+ throw new Error(JSON.stringify({ status: responseData.status, error: 'User not sent in response.' }));
423
+ }
424
+ if (responseData.token)
425
+ this.setUserToken(responseData.token);
426
+ return true;
427
+ };
428
+ this.deleteUser = async () => {
429
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/user/delete`, {
430
+ method: 'GET',
431
+ headers: {
432
+ authorization: `Bearer ${this._token}`,
433
+ 'x-gng-ecomm-token': this._userToken
434
+ }
435
+ });
436
+ const responseData = await fetchData.json();
437
+ if (responseData.status !== 200) {
438
+ return false;
439
+ }
440
+ return true;
441
+ };
442
+ this.getOrders = async (lastID, iteration) => {
443
+ let queryString = `?fromLastID=${lastID !== null && lastID !== void 0 ? lastID : ''}&skip=${iteration !== null && iteration !== void 0 ? iteration : ''}`;
444
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/user/orders${queryString}`, {
445
+ method: 'GET',
446
+ headers: {
447
+ authorization: `Bearer ${this._token}`,
448
+ 'Content-Type': 'application/json',
449
+ 'x-gng-ecomm-token': this._userToken
450
+ }
451
+ });
452
+ const responseData = (await fetchData.json());
453
+ if (responseData.status !== 200) {
454
+ return responseData.data;
455
+ }
456
+ return responseData.data;
457
+ };
458
+ this.killRepCart = async (hashed_cart_id) => {
459
+ try {
460
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/user/killRepCart/${encodeURIComponent(hashed_cart_id)}`, {
461
+ method: 'GET',
462
+ headers: {
463
+ authorization: `Bearer ${this._token}`,
464
+ 'Content-Type': 'application/json',
465
+ 'x-gng-ecomm-token': this._userToken
466
+ }
467
+ });
468
+ const responseData = (await fetchData.json());
469
+ if (responseData.status !== 200) {
470
+ return responseData.data;
471
+ }
472
+ return responseData.data;
473
+ }
474
+ catch (error) {
475
+ console.log(error);
476
+ return '';
477
+ }
478
+ };
479
+ this.getOrder = async (orderID, token) => {
480
+ try {
481
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/user/order/${orderID}`, {
482
+ method: 'POST',
483
+ headers: {
484
+ authorization: `Bearer ${this._token}`,
485
+ 'Content-Type': 'application/json',
486
+ 'x-gng-ecomm-token': this._userToken
487
+ },
488
+ body: JSON.stringify({ orderToken: token })
489
+ });
490
+ const responseData = (await fetchData.json());
491
+ if (responseData.status !== 200) {
492
+ return responseData.data;
493
+ }
494
+ return responseData.data;
495
+ }
496
+ catch (error) {
497
+ console.log(error);
498
+ return '';
499
+ }
500
+ };
501
+ this.changeProfilePicture = async (file) => {
502
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/user/changeProfilePicture`, {
503
+ method: 'POST',
504
+ headers: {
505
+ authorization: `Bearer ${this._token}`,
506
+ 'Content-Type': 'application/json',
507
+ 'x-gng-ecomm-token': this._userToken
508
+ },
509
+ body: JSON.stringify({
510
+ file: file
511
+ })
512
+ });
513
+ const responseData = (await fetchData.json());
514
+ return responseData.data;
515
+ };
516
+ this.changePassword = async (currentPassword, newPassword) => {
517
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/user/changePassword`, {
518
+ method: 'POST',
519
+ headers: {
520
+ authorization: `Bearer ${this._token}`,
521
+ 'Content-Type': 'application/json',
522
+ 'x-gng-ecomm-token': this._userToken
523
+ },
524
+ body: JSON.stringify({ currentPassword, newPassword })
525
+ });
526
+ const responseData = (await fetchData.json());
527
+ if (responseData.status === 200)
528
+ return responseData.data;
529
+ return responseData.error;
530
+ };
531
+ this.sendResetPasswordEmail = async (locale, userEmail, forPro, withEmail, isTest) => {
532
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/user/sentForgotPasswordEmail`, {
533
+ method: 'POST',
534
+ headers: {
535
+ authorization: `Bearer ${this._token}`,
536
+ 'Content-Type': 'application/json',
537
+ 'x-gng-ecomm-token': this._userToken,
538
+ 'x-gng-ecomm-locale': locale
539
+ },
540
+ body: JSON.stringify({ userEmail, forPro, withEmail, isTest })
541
+ });
542
+ const responseData = (await fetchData.json());
543
+ if (responseData.status === 200)
544
+ return responseData.data;
545
+ if (responseData.status === 403)
546
+ return {
547
+ fr: `Plus d\'un compte a été trouvé avec ${withEmail ? 'ce courriel' : 'ce ID client'}. Veuillez contacter un administrateur pour procéder.`,
548
+ en: `More than one account was found with ${withEmail ? 'this email' : 'this client ID'}. Please contact an administrator to proceed.`
549
+ };
550
+ return responseData.error;
551
+ };
552
+ this.sendApplicationEmail = async (locale, form) => {
553
+ try {
554
+ if (!!!form.cv)
555
+ return {
556
+ error: "Couldn't find cv"
557
+ };
558
+ const cvBase64 = await (0, functions_2.toBase64)(form.cv);
559
+ if (typeof cvBase64 !== 'string') {
560
+ return {
561
+ error: "Couldn't convert file to base64"
562
+ };
563
+ }
564
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/email/sendApplicationEmail`, {
565
+ method: 'POST',
566
+ headers: {
567
+ authorization: `Bearer ${this._token}`,
568
+ 'Content-Type': 'application/json',
569
+ 'x-gng-ecomm-token': this._userToken,
570
+ 'x-gng-ecomm-locale': locale
571
+ },
572
+ body: JSON.stringify(Object.assign(Object.assign({}, form), { cv: cvBase64 }))
573
+ });
574
+ const responseData = (await fetchData.json());
575
+ if (responseData.status === 200)
576
+ return responseData.data;
577
+ return responseData.error;
578
+ }
579
+ catch (error) {
580
+ return 'error';
581
+ }
582
+ };
583
+ this.sendContactEmail = async (locale, form) => {
584
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/email/sendContactEmail`, {
585
+ method: 'POST',
586
+ headers: {
587
+ authorization: `Bearer ${this._token}`,
588
+ 'Content-Type': 'application/json',
589
+ 'x-gng-ecomm-token': this._userToken,
590
+ 'x-gng-ecomm-locale': locale
591
+ },
592
+ body: JSON.stringify(form)
593
+ });
594
+ const responseData = (await fetchData.json());
595
+ if (responseData.status === 200)
596
+ return responseData.data;
597
+ return responseData.error;
598
+ };
599
+ this.sendGenericOtherEmail = async (locale, form, templateId, to, replyTo) => {
600
+ const getSubjectByType = (type) => {
601
+ switch (type) {
602
+ case 'confirmation_lawn_submission':
603
+ return { fr: 'Soumission gazon - Confirmation de réception', en: 'Lawn submission - Confirmation' };
604
+ default:
605
+ return undefined;
606
+ }
607
+ };
608
+ try {
609
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/email/sendGenericOtherEmail`, {
610
+ method: 'POST',
611
+ headers: {
612
+ authorization: `Bearer ${this._token}`,
613
+ 'Content-Type': 'application/json',
614
+ 'x-gng-ecomm-token': this._userToken,
615
+ 'x-gng-ecomm-locale': locale
616
+ },
617
+ body: JSON.stringify(Object.assign(Object.assign({}, (!!form ? { content: form } : {})), { subject: getSubjectByType(templateId), templateId,
618
+ to,
619
+ replyTo }))
620
+ });
621
+ const responseData = (await fetchData.json());
622
+ if (responseData.status === 200)
623
+ return responseData.data;
624
+ return responseData.error;
625
+ }
626
+ catch (error) {
627
+ console.log('error on sendGenericOtherEmail: ', error);
628
+ }
629
+ };
630
+ this.sendServicePageEmail = async (locale, form, type, testEmail) => {
631
+ const { attachments } = form, rest = __rest(form, ["attachments"]);
632
+ const updatedAttachments = [];
633
+ if (!!attachments) {
634
+ for (let att of attachments) {
635
+ try {
636
+ const cvBase64 = await (0, functions_2.toBase64)(att);
637
+ updatedAttachments.push({ name: att.name, content: cvBase64 });
638
+ }
639
+ catch (e) {
640
+ console.log('error on converting to base64: ', e);
641
+ }
642
+ }
643
+ }
644
+ const getSubjectByType = () => {
645
+ switch (type) {
646
+ case 'admin_3D_plans':
647
+ if (!!form.project_type && form.project_type === 'conception') {
648
+ return { fr: 'Conception de plans - Nouvelle demande', en: 'Project design - new request' };
649
+ }
650
+ else {
651
+ return { fr: 'Images 3D - Nouvelle demande', en: '3D plans - new request' };
652
+ }
653
+ case 'admin_vegetals':
654
+ return { fr: 'Commande de végétaux - nouvelle soumission', en: 'Vegetals - new quotation' };
655
+ case 'admin_pickup_on_site':
656
+ return { fr: 'Ramassage sur chantier - nouvelle demande', en: 'Pickup on site - new request' };
657
+ case 'admin_borrow_tools':
658
+ return { fr: "Location d'outils - nouvelle demande", en: 'Rent tools - new request' };
659
+ case 'admin_sales_info':
660
+ return {
661
+ fr: 'Produits en solde - Information demandée',
662
+ en: 'On sale products - Information request'
663
+ };
664
+ case 'admin_credit_info':
665
+ return {
666
+ fr: 'Département de crédit - Information demandée',
667
+ en: 'Credit department - Information request'
668
+ };
669
+ case 'admin_transport_quote':
670
+ return {
671
+ fr: 'Location de camion - nouvelle soumission',
672
+ en: 'Transport truck rental - new quotation'
673
+ };
674
+ case 'admin_special_order':
675
+ return { fr: 'Commande spéciale - nouvelle demande', en: 'Special order - new request' };
676
+ case 'admin_installation':
677
+ return { fr: 'Installation - nouvelle soumission', en: 'Installation - new quotation' };
678
+ case 'admin_find_landscaper':
679
+ return { fr: 'Trouver un paysagiste - nouvelle demande', en: 'Find a landscaper - new request' };
680
+ case 'admin_lawn_submission':
681
+ return { fr: 'Soumission gazon - nouvelle demande', en: 'Lawn submission - new request' };
682
+ case 'confirmation_find_landsacper':
683
+ return { fr: 'Trouver un paysagiste - Confirmation', en: 'Find a landscaper - Confirmation' };
684
+ default:
685
+ return { fr: 'Demande de service - nouvelle soumission', en: 'Service request - new quotation' };
686
+ }
687
+ };
688
+ try {
689
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/email/sendServiceStaticPageEmail`, {
690
+ method: 'POST',
691
+ headers: {
692
+ authorization: `Bearer ${this._token}`,
693
+ 'Content-Type': 'application/json',
694
+ 'x-gng-ecomm-token': this._userToken,
695
+ 'x-gng-ecomm-locale': locale
696
+ },
697
+ body: JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign({}, rest), (!!updatedAttachments && !!updatedAttachments.length ? { attachments: updatedAttachments } : {})), { subject: getSubjectByType(), title: getSubjectByType(), type: type }), (!!testEmail ? { test_email: testEmail } : {})))
698
+ });
699
+ const responseData = (await fetchData.json());
700
+ if (responseData.status === 200)
701
+ return true;
702
+ return responseData.error;
703
+ }
704
+ catch (e) {
705
+ console.log('error on calling api: ', e);
706
+ if (!!updatedAttachments) {
707
+ return {
708
+ status: 413,
709
+ error: {
710
+ fr: "Vos pièces jointes n'ont pas pu être envoyées. Veuillez réessayer.",
711
+ en: 'Your attachments could not be sent. Please try again.'
712
+ }
713
+ };
714
+ }
715
+ return '';
716
+ }
717
+ };
718
+ this.sendSponsorRequestEmail = async (locale, form, template_name) => {
719
+ const { plan } = form, rest = __rest(form, ["plan"]);
720
+ let updatedPlan;
721
+ if (!!plan) {
722
+ try {
723
+ const planBase64 = await (0, functions_2.toBase64)(plan);
724
+ if (typeof planBase64 === 'string') {
725
+ const splitString = planBase64.split(';base64,');
726
+ if (!!splitString.length && !!splitString[1]) {
727
+ updatedPlan = {
728
+ name: plan.name,
729
+ content: splitString[1]
730
+ };
731
+ }
732
+ }
733
+ }
734
+ catch (e) {
735
+ console.log('error on converting to base64: ', e);
736
+ }
737
+ }
738
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/email/sendSponsorRequestEmail`, {
739
+ method: 'POST',
740
+ headers: {
741
+ authorization: `Bearer ${this._token}`,
742
+ 'Content-Type': 'application/json',
743
+ 'x-gng-ecomm-token': this._userToken,
744
+ 'x-gng-ecomm-locale': locale
745
+ },
746
+ body: JSON.stringify({
747
+ contenu: Object.assign(Object.assign(Object.assign({}, rest), { admin: true, has_plan: !!updatedPlan }), (!!updatedPlan
748
+ ? {
749
+ plan: updatedPlan
750
+ }
751
+ : {})),
752
+ template_name: template_name
753
+ })
754
+ });
755
+ const responseData = (await fetchData.json());
756
+ if (responseData.status === 200)
757
+ return true;
758
+ return responseData.error;
759
+ };
760
+ this.sendPreMeetingFormEmail = async (locale, form, proId) => {
761
+ const { attachments } = form, rest = __rest(form, ["attachments"]);
762
+ const _a = rest.pro_infos, { pro_logo } = _a, restProInfos = __rest(_a, ["pro_logo"]);
763
+ const updatedAttachments = [];
764
+ let updatedLogo = '';
765
+ if (!!attachments) {
766
+ for (let att of attachments) {
767
+ try {
768
+ const cvBase64 = await (0, functions_2.toBase64)(att);
769
+ updatedAttachments.push({ name: att.name, content: cvBase64 });
770
+ }
771
+ catch (e) {
772
+ console.log('error on converting to base64: ', e);
773
+ }
774
+ }
775
+ }
776
+ if (!!pro_logo) {
777
+ try {
778
+ const logoBase64 = await (0, functions_2.toBase64)(pro_logo);
779
+ updatedLogo = { name: pro_logo.name, content: logoBase64 };
780
+ }
781
+ catch (e) {
782
+ console.log('error on converting logo to base64: ', e);
783
+ }
784
+ }
785
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/email/sendPreMeetingFormEmail`, {
786
+ method: 'POST',
787
+ headers: {
788
+ authorization: `Bearer ${this._token}`,
789
+ 'Content-Type': 'application/json',
790
+ 'x-gng-ecomm-token': this._userToken,
791
+ 'x-gng-ecomm-locale': locale
792
+ },
793
+ body: JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign({}, rest), { pro_infos: Object.assign(Object.assign({}, restProInfos), (!!updatedLogo ? { pro_logo: updatedLogo } : {})) }), (!!updatedAttachments && !!updatedAttachments.length ? { attachments: updatedAttachments } : {})), (!!proId ? { pro_id: proId } : {})))
794
+ });
795
+ const responseData = (await fetchData.json());
796
+ if (responseData.status === 200)
797
+ return true;
798
+ return responseData.error;
799
+ };
800
+ this.sendWishlistByEmail = async (locale, contenu, template_name) => {
801
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/email/sendWishlistEmail`, {
802
+ method: 'POST',
803
+ headers: {
804
+ authorization: `Bearer ${this._token}`,
805
+ 'Content-Type': 'application/json',
806
+ 'x-gng-ecomm-token': this._userToken,
807
+ 'x-gng-ecomm-locale': locale
808
+ },
809
+ body: JSON.stringify({ contenu: contenu, template_name: template_name })
810
+ });
811
+ const responseData = (await fetchData.json());
812
+ if (responseData.status === 200)
813
+ return true;
814
+ return responseData.error;
815
+ };
816
+ this.resetPassword = async (token, newPassword, withEmail) => {
817
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/user/resetPassword`, {
818
+ method: 'POST',
819
+ headers: {
820
+ authorization: `Bearer ${this._token}`,
821
+ 'Content-Type': 'application/json',
822
+ 'x-gng-ecomm-token': this._userToken
823
+ },
824
+ body: JSON.stringify({ validationCode: token, newPassword, withEmail })
825
+ });
826
+ const responseData = (await fetchData.json());
827
+ if (responseData.status === 200)
828
+ return responseData.data;
829
+ if (responseData.status === 403)
830
+ return {
831
+ fr: `Plus d\'un compte a été trouvé avec ${withEmail ? 'ce courriel' : 'ce ID client'}. Veuillez contacter un administrateur pour procéder.`,
832
+ en: `More than one account was found with ${withEmail ? 'this email' : 'this client ID'}. Please contact an administrator to proceed.`
833
+ };
834
+ return responseData.error;
835
+ };
836
+ this.user = {
837
+ getUser: this.getUser,
838
+ saveUser: this.saveUser,
839
+ deleteUser: this.deleteUser,
840
+ loginUser: this.loginUser,
841
+ loginUserWithID: this.loginUserWithID,
842
+ loginUserWithFacebook: this.loginUserWithFacebook,
843
+ logout: this.logout,
844
+ registerUser: this.registerUser,
845
+ killRepCart: this.killRepCart,
846
+ getOrder: this.getOrder,
847
+ getOrders: this.getOrders,
848
+ changePassword: this.changePassword,
849
+ changeProfilePicture: this.changeProfilePicture,
850
+ validateAccount: this.validateAccount,
851
+ sendResetPasswordEmail: this.sendResetPasswordEmail,
852
+ resetPassword: this.resetPassword,
853
+ sendApplicationEmail: this.sendApplicationEmail,
854
+ sendContactEmail: this.sendContactEmail,
855
+ sendServiceEmail: this.sendServicePageEmail,
856
+ anonymousResetPassword: this.anonymousResetPassword,
857
+ checkG2: this.checkG2ForCustomer,
858
+ createPro: this.createProCustomer,
859
+ fetchCustomPriceList: this.fetchCustomPriceList
860
+ };
861
+ this.getImage = (imgName, formatQuery, addImgPath = false) => {
862
+ const img = new image_1.default(`${addImgPath ? this._imgPath : ''}${this._imgPath}/${imgName}`);
863
+ return img.getFileDownloadUrl(formatQuery);
864
+ };
865
+ this.getProducts = async (page = 0, hpp = 10, query = '', filters = '', indice = 'products', f = '', useProspr = false) => {
866
+ try {
867
+ return await Product_1.default.fetch({
868
+ app: process.env.NEXT_PUBLIC_ALGOLIA_APP,
869
+ api: process.env.NEXT_PUBLIC_ALGOLIA_TOKEN,
870
+ page: page,
871
+ hpp: hpp,
872
+ query: query,
873
+ filters,
874
+ indice: indice || 'products',
875
+ f,
876
+ useProspr,
877
+ space: undefined
878
+ });
879
+ }
880
+ catch (error) {
881
+ throw error;
882
+ }
883
+ };
884
+ this.getProduct = async (parentSlug, locale, useProdArray, noDrafts) => {
885
+ let prod = undefined;
886
+ if (!!useProdArray && !!useProdArray.length) {
887
+ prod = useProdArray.find((fee) => fee.slug === parentSlug);
888
+ }
889
+ if (!!!prod) {
890
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/products/${encodeURIComponent(parentSlug)}`, {
891
+ method: 'GET',
892
+ headers: {
893
+ Authorization: `Bearer ${this._token}`,
894
+ 'x-gng-ecomm-locale': locale,
895
+ 'x-gng-ecomm-token': this._userToken
896
+ }
897
+ });
898
+ const responseData = await fetchData.json();
899
+ if (responseData.status !== 200)
900
+ throw new Error(JSON.stringify({ status: responseData.status, error: responseData.error }));
901
+ prod = responseData.data;
902
+ }
903
+ if (!!noDrafts && prod.draft)
904
+ return undefined;
905
+ return prod;
906
+ };
907
+ this.getUpsellOfProducts = async (slugs, customPriceList) => {
908
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/products/getUpsellOfProductsWithProducts`, {
909
+ method: 'POST',
910
+ headers: {
911
+ Authorization: `Bearer ${this._token}`,
912
+ 'Content-Type': 'application/json'
913
+ },
914
+ body: JSON.stringify(Object.assign({ slugs: slugs }, (!!customPriceList ? { customPriceList: customPriceList } : {})))
915
+ });
916
+ const responseData = await fetchData.json();
917
+ if (responseData.status !== 200)
918
+ throw new Error(JSON.stringify({ status: responseData.status, error: responseData.error }));
919
+ return responseData.data;
920
+ };
921
+ this.getAttributes = async () => {
922
+ try {
923
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/attributes`, {
924
+ method: 'GET',
925
+ headers: {
926
+ authorization: `Bearer ${this._token}`,
927
+ 'Content-Type': 'application/json'
928
+ }
929
+ });
930
+ const resJson = await fetchData.json();
931
+ return resJson.data.map((a) => (Object.assign(Object.assign({}, a), { slug: !!a.slug ? a.slug : (0, functions_1.string_to_slug)((0, functions_1.translate)('fr', a.name)) })));
932
+ }
933
+ catch (error) {
934
+ console.log('error fetch attributes: ', error);
935
+ }
936
+ };
937
+ this.getCategories = async () => {
938
+ try {
939
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/categories`, {
940
+ method: 'GET',
941
+ headers: {
942
+ authorization: `Bearer ${this._token}`,
943
+ 'Content-Type': 'application/json'
944
+ }
945
+ });
946
+ const resJson = (await fetchData.json());
947
+ return resJson.data;
948
+ }
949
+ catch (error) {
950
+ console.log('error fetch categories: ', error);
951
+ }
952
+ };
953
+ this.getBrands = async () => {
954
+ try {
955
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/brands`, {
956
+ method: 'GET',
957
+ headers: {
958
+ authorization: `Bearer ${this._token}`,
959
+ 'Content-Type': 'application/json'
960
+ }
961
+ });
962
+ const resJson = (await fetchData.json());
963
+ return resJson.data;
964
+ }
965
+ catch (error) {
966
+ console.log('error fetch brands: ', error);
967
+ }
968
+ };
969
+ this.getInventoryItems = async (parentSlug) => {
970
+ try {
971
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/inventories${!!parentSlug ? `/${encodeURIComponent(parentSlug)}` : ''}`, {
972
+ method: 'GET',
973
+ headers: {
974
+ authorization: `Bearer ${this._token}`,
975
+ 'Content-Type': 'application/json'
976
+ }
977
+ });
978
+ const resJson = (await fetchData.json());
979
+ return resJson.data;
980
+ }
981
+ catch (error) {
982
+ console.log(`error fetch inventory items${!!parentSlug ? 'for parentSlug ' + parentSlug : ''}: `, error);
983
+ }
984
+ };
985
+ this.getOneInventoryItem = async (sku) => {
986
+ try {
987
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/inventory/${encodeURIComponent(sku)}`, {
988
+ method: 'GET',
989
+ headers: {
990
+ authorization: `Bearer ${this._token}`,
991
+ 'Content-Type': 'application/json'
992
+ }
993
+ });
994
+ const resJson = (await fetchData.json());
995
+ return resJson.data;
996
+ }
997
+ catch (error) {
998
+ console.log(`error fetch inventory item for sku: ${sku}`, error);
999
+ return undefined;
1000
+ }
1001
+ };
1002
+ this.getLatestProducts = async () => {
1003
+ try {
1004
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/latest_products`, {
1005
+ method: 'GET',
1006
+ headers: {
1007
+ authorization: `Bearer ${this._token}`,
1008
+ 'Content-Type': 'application/json'
1009
+ }
1010
+ });
1011
+ const resJson = (await fetchData.json());
1012
+ return resJson.data;
1013
+ }
1014
+ catch (error) {
1015
+ console.log(`error fetching latest products`, error);
1016
+ }
1017
+ };
1018
+ this._getFees = async () => {
1019
+ try {
1020
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/products/getFees`, {
1021
+ method: 'GET',
1022
+ headers: {
1023
+ authorization: `Bearer ${this._token}`,
1024
+ 'x-gng-ecomm-token': this._userToken
1025
+ }
1026
+ });
1027
+ const resJson = (await fetchData.json());
1028
+ if (resJson.status !== 200) {
1029
+ console.log('error on fetching fees: ', !!resJson.error ? resJson.error.toString() : '');
1030
+ return [];
1031
+ }
1032
+ return resJson.data;
1033
+ }
1034
+ catch (error) {
1035
+ console.log(`error fetching fees`, error);
1036
+ }
1037
+ };
1038
+ this.products = {
1039
+ getProducts: this.getProducts,
1040
+ getProduct: this.getProduct,
1041
+ getUpsellOfProducts: this.getUpsellOfProducts,
1042
+ getAttributes: this.getAttributes,
1043
+ getCategories: this.getCategories,
1044
+ getBrands: this.getBrands,
1045
+ getInventoryItems: this.getInventoryItems,
1046
+ getOneInventoryItem: this.getOneInventoryItem,
1047
+ getLatestProducts: this.getLatestProducts,
1048
+ getFees: this._getFees
1049
+ };
1050
+ this.getIfAddressIsInsideZones = async (address) => {
1051
+ try {
1052
+ const userPos = await (0, zones_1.getPositionFromAddress)(address);
1053
+ if (!!!userPos)
1054
+ return [];
1055
+ const { lat, lng } = userPos;
1056
+ const zone = await (0, isomorphic_unfetch_1.default)(`${this._api}/shipping/zones`, {
1057
+ method: 'POST',
1058
+ headers: {
1059
+ authorization: `Bearer ${this._token}`,
1060
+ 'Content-Type': 'application/json'
1061
+ },
1062
+ body: JSON.stringify({ address })
1063
+ });
1064
+ if (zone.status !== 200)
1065
+ return [];
1066
+ const { zones } = (await zone.json()).data;
1067
+ const google = window.google;
1068
+ const insideZones = [];
1069
+ for (const zone of zones) {
1070
+ const polygon = new google.maps.Polygon({
1071
+ paths: zone.polygon.split(';').map((coords) => ({
1072
+ lat: (0, lodash_1.toNumber)(coords.split(',')[1]),
1073
+ lng: (0, lodash_1.toNumber)(coords.split(',')[0])
1074
+ }))
1075
+ });
1076
+ if (google.maps.geometry.poly.containsLocation({ lat: Number(lat), lng: Number(lng) }, polygon)) {
1077
+ insideZones.push(zone.slug);
1078
+ }
1079
+ }
1080
+ return insideZones;
1081
+ }
1082
+ catch (error) {
1083
+ if (!!window && !!window.RemoteLog) {
1084
+ ;
1085
+ window.RemoteLog(`error while fetching zones - ${error.toString()}`, logs_1.LogType.ERROR);
1086
+ }
1087
+ console.log('error while fetching zones', error.toString());
1088
+ return [];
1089
+ }
1090
+ };
1091
+ this._pricingByQuery = async (query) => {
1092
+ try {
1093
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/services/pricing/byQuery`, {
1094
+ method: 'POST',
1095
+ headers: {
1096
+ authorization: `Bearer ${this._token}`,
1097
+ 'Content-Type': 'application/json'
1098
+ },
1099
+ body: JSON.stringify({ query })
1100
+ });
1101
+ const resJson = await fetchData.json();
1102
+ return resJson.data;
1103
+ }
1104
+ catch (error) {
1105
+ throw error;
1106
+ }
1107
+ };
1108
+ this._buyFromForm = async (form) => {
1109
+ try {
1110
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/services/buy/fromForm`, {
1111
+ method: 'POST',
1112
+ headers: {
1113
+ authorization: `Bearer ${this._token}`,
1114
+ 'Content-Type': 'application/json'
1115
+ },
1116
+ body: JSON.stringify(form)
1117
+ });
1118
+ const resJson = await fetchData.json();
1119
+ if (!!resJson.error) {
1120
+ return false;
1121
+ }
1122
+ return true;
1123
+ }
1124
+ catch (error) {
1125
+ throw error;
1126
+ }
1127
+ };
1128
+ this._getSearchServices = async () => {
1129
+ try {
1130
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/space`, {
1131
+ method: 'GET',
1132
+ headers: {
1133
+ authorization: `Bearer ${this._token}`,
1134
+ 'Content-Type': 'application/json'
1135
+ }
1136
+ });
1137
+ const resJson = await fetchData.json();
1138
+ if (!!resJson.error) {
1139
+ return [];
1140
+ }
1141
+ const space = resJson.data;
1142
+ if (!!!space || !!!space._space)
1143
+ return [];
1144
+ return space._space.external_services.filter((s) => s.type === 'index');
1145
+ }
1146
+ catch (error) {
1147
+ throw error;
1148
+ }
1149
+ };
1150
+ this.services = {
1151
+ pricingByQuery: this._pricingByQuery,
1152
+ buy: {
1153
+ fromForm: this._buyFromForm
1154
+ },
1155
+ searchServices: this._getSearchServices
1156
+ };
1157
+ this._getAllCatalogues = async (locale) => {
1158
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/catalogues`, {
1159
+ method: 'GET',
1160
+ headers: {
1161
+ Authorization: `Bearer ${this._token}`,
1162
+ 'x-gng-ecomm-locale': locale
1163
+ }
1164
+ });
1165
+ const responseData = await fetchData.json();
1166
+ if (responseData.status !== 200)
1167
+ throw new Error(JSON.stringify({ status: responseData.status, error: responseData.error }));
1168
+ return responseData.data.filter((catalogue) => !!!catalogue.draft);
1169
+ };
1170
+ this._getCatalogueBySlug = async (slug, locale) => {
1171
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/catalogues/${slug}`, {
1172
+ method: 'GET',
1173
+ headers: {
1174
+ Authorization: `Bearer ${this._token}`,
1175
+ 'x-gng-ecomm-locale': locale
1176
+ }
1177
+ });
1178
+ const responseData = await fetchData.json();
1179
+ if (responseData.status !== 200)
1180
+ throw new Error(JSON.stringify({ status: responseData.status, error: responseData.error }));
1181
+ return responseData.data;
1182
+ };
1183
+ this.catalogues = {
1184
+ getAll: this._getAllCatalogues,
1185
+ getOne: this._getCatalogueBySlug
1186
+ };
1187
+ this.saveCustomerToMailchimpList = async (customerEmail, listID, mergeFields, tags) => {
1188
+ try {
1189
+ const saved = await (0, isomorphic_unfetch_1.default)(`${this._api}/marketing/mailchimp/updateOrCreateCustomer`, {
1190
+ method: 'POST',
1191
+ headers: {
1192
+ Authorization: `Bearer ${this._token}`,
1193
+ 'Content-Type': 'application/json'
1194
+ },
1195
+ body: JSON.stringify(Object.assign(Object.assign({ email: customerEmail, listID: listID }, (!!mergeFields ? { mergeFields: mergeFields } : {})), (!!tags ? { tags: tags } : {})))
1196
+ });
1197
+ const responseData = await saved.json();
1198
+ if (responseData.status !== 200)
1199
+ throw new Error(JSON.stringify({ status: responseData.status, error: responseData.error }));
1200
+ return true;
1201
+ }
1202
+ catch (e) {
1203
+ console.log('error on saving customer to mailchimp list: ', e.toString());
1204
+ return false;
1205
+ }
1206
+ };
1207
+ this.getProductListForSitemap = async () => {
1208
+ try {
1209
+ const fetchData = await (0, isomorphic_unfetch_1.default)(`${this._api}/analytics/sitmap_data`, {
1210
+ method: 'GET',
1211
+ headers: {
1212
+ authorization: `Bearer ${this._token}`,
1213
+ 'Content-Type': 'application/json'
1214
+ }
1215
+ });
1216
+ const result = await fetchData.json();
1217
+ if (!!fetchData.status && fetchData.status !== 200)
1218
+ throw `${result.data}`;
1219
+ return result.data;
1220
+ }
1221
+ catch (e) {
1222
+ console.log('error fetching sitemap data: ', e.toString());
1223
+ return e.toString();
1224
+ }
1225
+ };
1226
+ this._api = '';
1227
+ this._imgPath = '';
1228
+ this._token = '';
1229
+ this._userToken = '';
1230
+ this._url = '';
1231
+ this._org = '';
1232
+ this._storeData = null;
1233
+ this._wishlist = null;
1234
+ this._stockNotif = null;
1235
+ }
1236
+ }
1237
+ exports.default = SDK;
1238
1238
  //# sourceMappingURL=index.js.map