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
@@ -1,314 +1,314 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- var __importDefault = (this && this.__importDefault) || function (mod) {
26
- return (mod && mod.__esModule) ? mod : { "default": mod };
27
- };
28
- Object.defineProperty(exports, "__esModule", { value: true });
29
- const jsx_runtime_1 = require("react/jsx-runtime");
30
- const react_1 = require("react");
31
- const index_1 = __importStar(require("./index"));
32
- const useSDK_1 = __importDefault(require("../../hooks/useSDK"));
33
- const moment_1 = __importDefault(require("moment"));
34
- const functions_1 = require("../../../../utils/functions");
35
- const UserContextProvider = ({ children }) => {
36
- const sdk = (0, useSDK_1.default)();
37
- const setUserLoggedIn = async (userData) => {
38
- const isPro = !!userData.basic_info.customer_professionnal_info &&
39
- !!userData.basic_info.customer_professionnal_info.proof_doc_value;
40
- localStorage.setItem('userLogged', 'true');
41
- if (!!isPro) {
42
- localStorage.setItem('isPro', 'true');
43
- }
44
- const isClerk = localStorage.getItem('isClerk');
45
- if (typeof window !== 'undefined' && !!isClerk) {
46
- window.addEventListener('beforeunload', async (e) => {
47
- if (!!!userData.temp_hash)
48
- return;
49
- e.preventDefault();
50
- const dialogText = '';
51
- e.returnValue = dialogText;
52
- return dialogText;
53
- });
54
- }
55
- setState((prevState) => (Object.assign(Object.assign({}, prevState), { isUserLoggedIn: true, userData: userData })));
56
- };
57
- const setUserLoggedOut = async (keepRepCart) => {
58
- if (!!!sdk)
59
- return;
60
- if (!!state.userData && state.userData.temp_hash && !!!keepRepCart) {
61
- await sdk.user.killRepCart(state.userData.temp_hash);
62
- }
63
- sdk.user.logout();
64
- setState((prevState) => (Object.assign(Object.assign({}, prevState), { isUserLoggedIn: false, isPro: false, customPriceList: undefined, userData: null, resetUserData: true })));
65
- };
66
- const setUserPreferedStore = async (storeId) => {
67
- if (!!!state.userData)
68
- return;
69
- await saveUser(Object.assign(Object.assign({}, state.userData), { prefered_store: storeId }));
70
- };
71
- const saveUser = async (customer) => {
72
- if (!!!sdk)
73
- return false;
74
- setState((prevState) => (Object.assign(Object.assign({}, prevState), { userData: customer, isPro: !!customer.basic_info.customer_professionnal_info &&
75
- !!customer.basic_info.customer_professionnal_info.professionnal_title })));
76
- return await sdk.user.saveUser(customer);
77
- };
78
- const deleteUser = async () => {
79
- if (!!!sdk)
80
- return false;
81
- return await sdk.user.deleteUser();
82
- };
83
- const getOrder = async (orderID, token) => {
84
- if (!!!sdk)
85
- return 'sdk_not_defined';
86
- try {
87
- const order = await sdk.user.getOrder(orderID, token);
88
- return order;
89
- }
90
- catch (err) {
91
- return 'error';
92
- }
93
- };
94
- const changePassword = async (currentPassword, newPassword) => {
95
- if (!!!sdk)
96
- return 'sdk_not_defined';
97
- try {
98
- return await sdk.user.changePassword(currentPassword, newPassword);
99
- }
100
- catch (err) {
101
- return err;
102
- }
103
- };
104
- const changeProfilePicture = async (base64) => {
105
- if (!!!sdk)
106
- return 'sdk_not_defined';
107
- try {
108
- const upload = await sdk.user.changeProfilePicture(base64);
109
- setState((prevState) => {
110
- if (prevState.userData) {
111
- return Object.assign(Object.assign({}, prevState), { userData: Object.assign(Object.assign({}, prevState.userData), { basic_info: Object.assign(Object.assign({}, prevState.userData.basic_info), { customer_image: upload === "Can't upload image." || upload === 'done' ? undefined : upload }) }) });
112
- }
113
- return prevState;
114
- });
115
- return upload;
116
- }
117
- catch (err) {
118
- return err;
119
- }
120
- };
121
- const setCustomPriceList = (list) => {
122
- setState((prevState) => (Object.assign(Object.assign({}, prevState), { customPriceList: list, fetchCustomPrices: false })));
123
- localStorage.setItem('customPriceList', JSON.stringify(list));
124
- localStorage.setItem('lastCustomPriceFetch', (0, moment_1.default)().format('YYYY-MM-DD'));
125
- };
126
- const setLoaded = (value) => {
127
- setState((prevState) => (Object.assign(Object.assign({}, prevState), { loaded: value })));
128
- };
129
- const [state, setState] = (0, react_1.useState)((0, index_1.getDefaultUserContext)());
130
- (0, react_1.useEffect)(() => {
131
- if (!!!sdk)
132
- return;
133
- const userLoggedData = localStorage.getItem('userLogged');
134
- const userIsPro = localStorage.getItem('isPro');
135
- const isClerk = localStorage.getItem('isClerk');
136
- const isLoggedIn = !!userLoggedData && JSON.parse(userLoggedData);
137
- const isPro = !!userLoggedData && !!userIsPro && JSON.parse(userIsPro);
138
- let newState = Object.assign({ isUserLoggedIn: !!!isClerk && !!isLoggedIn, isPro: !!!isClerk && !!isPro }, checkForCustomPriceList(!!userIsPro));
139
- if (!!isClerk) {
140
- localStorage.removeItem('isClerk');
141
- }
142
- return setState((prevState) => (Object.assign(Object.assign(Object.assign({}, prevState), newState), { loaded: true })));
143
- }, [sdk]);
144
- (0, react_1.useEffect)(() => {
145
- if (!!!state.fetchCustomPrices || !!!state.isPro || !!!state.userData || !!!sdk)
146
- return;
147
- const fetchCustomPrices = async () => {
148
- const proUser = !!state.userData && !!state.isPro ? state.userData.id : '';
149
- if (!!!proUser)
150
- return;
151
- try {
152
- const newList = await sdk.user.fetchCustomPriceList(proUser);
153
- if (!!newList) {
154
- setCustomPriceList(newList);
155
- }
156
- }
157
- catch (e) {
158
- console.log('error on fetching customPrices from G2: ', e.toString());
159
- setState((prevState) => (Object.assign(Object.assign({}, prevState), { fetchCustomPrices: false, customPriceList: undefined })));
160
- }
161
- };
162
- fetchCustomPrices();
163
- }, [sdk, state.fetchCustomPrices, state.isPro, state.userData]);
164
- (0, react_1.useEffect)(() => {
165
- if (!!!sdk)
166
- return;
167
- if (!state.isUserLoggedIn) {
168
- return;
169
- }
170
- const getContent = async () => {
171
- let user;
172
- try {
173
- user = (await sdk.user.getUser(!!localStorage.getItem('isClerk')));
174
- if (!!!user) {
175
- localStorage.setItem('isPro', JSON.stringify(false));
176
- localStorage.removeItem('foundInG2');
177
- if (!!localStorage.getItem('customPriceList')) {
178
- localStorage.removeItem('customPriceList');
179
- localStorage.removeItem('lastCustomPriceFetch');
180
- }
181
- return setState((prevState) => (Object.assign(Object.assign(Object.assign({}, prevState), { userData: null, isPro: false }), (!!prevState.customPriceList
182
- ? {
183
- customPriceList: undefined
184
- }
185
- : {}))));
186
- }
187
- const checkIsPro = !!user.basic_info.customer_professionnal_info &&
188
- !!user.basic_info.customer_professionnal_info.professionnal_title;
189
- setState((prevState) => (Object.assign(Object.assign(Object.assign({}, prevState), { userData: user, isPro: checkIsPro }), checkForCustomPriceList(checkIsPro))));
190
- localStorage.setItem('isPro', JSON.stringify(checkIsPro));
191
- if (!!!checkIsPro) {
192
- localStorage.removeItem('foundInG2');
193
- if (!!localStorage.getItem('customPriceList')) {
194
- localStorage.removeItem('customPriceList');
195
- localStorage.removeItem('lastCustomPriceFetch');
196
- }
197
- }
198
- }
199
- catch (err) {
200
- if (!!err.message) {
201
- const error = JSON.parse(err.message);
202
- if (!!error && !!error.error) {
203
- await setUserLoggedOut();
204
- }
205
- }
206
- }
207
- };
208
- getContent();
209
- }, [sdk, state.isUserLoggedIn]);
210
- (0, react_1.useEffect)(() => {
211
- return () => {
212
- if (typeof window !== 'undefined') {
213
- window.removeEventListener('onbeforeunload', async () => { });
214
- }
215
- };
216
- }, []);
217
- const checkForCustomPriceList = (userIsPro) => {
218
- const hasCustomPriceList = !!userIsPro && localStorage.getItem('customPriceList');
219
- const lastCustomPriceFetch = !!userIsPro && localStorage.getItem('lastCustomPriceFetch');
220
- const foundProInG2 = !!userIsPro && localStorage.getItem('foundInG2');
221
- const lastFetchWasBefore = !!userIsPro &&
222
- (!!!lastCustomPriceFetch || (!!lastCustomPriceFetch && (0, moment_1.default)().isAfter((0, moment_1.default)(lastCustomPriceFetch), 'day')));
223
- let parsedJSONCustomPrices = [];
224
- if (!!hasCustomPriceList) {
225
- try {
226
- parsedJSONCustomPrices = JSON.parse(hasCustomPriceList);
227
- }
228
- catch (e) {
229
- console.log(e.toString());
230
- }
231
- }
232
- return Object.assign(Object.assign({}, (!!!lastFetchWasBefore && !!foundProInG2
233
- ? { customPriceList: parsedJSONCustomPrices }
234
- : { customPriceList: undefined })), (!!lastFetchWasBefore && !!foundProInG2 ? { fetchCustomPrices: true } : {}));
235
- };
236
- const getPromiseToPurchaseHistory = async (userId, filters) => {
237
- if (!state.isPro)
238
- throw new Error('Only the PRO users have a promise to purchase');
239
- const api = !!sdk ? sdk.getAPIInfos() : null;
240
- if (!!!api)
241
- return;
242
- if (!!!userId) {
243
- if (!!state.userData && !!state.userData.id)
244
- userId = state.userData.id;
245
- else
246
- throw new Error("Can't get user promise to purchase without userId");
247
- }
248
- let body = undefined;
249
- if (!!filters) {
250
- body = Object.assign(Object.assign({}, (!!filters.bankTypeId
251
- ? {
252
- bank_type_id: filters.bankTypeId
253
- }
254
- : {})), (!!filters.unixDateRange
255
- ? {
256
- unix_date_range: filters.unixDateRange
257
- }
258
- : {}));
259
- }
260
- const requestHistory = await fetch(`${api.api}/users/${userId}/promisestopurchase/history`, {
261
- method: 'POST',
262
- headers: {
263
- Authorization: `Bearer ${api.token}`,
264
- 'Content-Type': 'application/json',
265
- 'x-gng-ecomm-token': api.userToken
266
- },
267
- body: !!body ? JSON.stringify(body) : undefined
268
- });
269
- const responseData = await requestHistory.json();
270
- if (responseData.status !== 200) {
271
- const errorStr = !!!responseData.error
272
- ? ''
273
- : typeof responseData.error === 'string'
274
- ? responseData.error
275
- : (0, functions_1.getStringByLang)(responseData.error, 'fr');
276
- throw new Error('Error on history fetch: ' + errorStr);
277
- }
278
- return responseData.data.history;
279
- };
280
- const getPromiseToPurchaseRemainingAmounts = async (userId) => {
281
- if (!state.isPro)
282
- throw new Error('Only the PRO users have a promise to purchase');
283
- const api = !!sdk ? sdk.getAPIInfos() : null;
284
- if (!!!api)
285
- return;
286
- if (!!!userId) {
287
- if (!!state.userData && !!state.userData.id)
288
- userId = state.userData.id;
289
- else
290
- throw new Error("Can't get remaining amounts for user without userId");
291
- }
292
- const requestHistory = await fetch(`${api.api}/users/${userId}/promisestopurchase/remainingAmounts`, {
293
- method: 'GET',
294
- headers: {
295
- Authorization: `Bearer ${api.token}`,
296
- 'Content-Type': 'application/json',
297
- 'x-gng-ecomm-token': api.userToken
298
- }
299
- });
300
- const responseData = await requestHistory.json();
301
- if (responseData.status !== 200) {
302
- const errorStr = !!!responseData.error
303
- ? ''
304
- : typeof responseData.error === 'string'
305
- ? responseData.error
306
- : (0, functions_1.getStringByLang)(responseData.error, 'fr');
307
- throw new Error('Error on remainingAmounts fetch: ' + errorStr);
308
- }
309
- return responseData.data.availableAmountsForBanks;
310
- };
311
- return ((0, jsx_runtime_1.jsx)(index_1.default.Provider, Object.assign({ value: Object.assign(Object.assign({}, state), { setLoaded: setLoaded, setUserLoggedIn: setUserLoggedIn, setUserLoggedOut: setUserLoggedOut, saveUser: saveUser, deleteUser: deleteUser, getOrder: getOrder, changePassword: changePassword, changeProfilePicture: changeProfilePicture, setUserPreferedStore: setUserPreferedStore, setCustomPriceList: setCustomPriceList, getPromiseToPurchaseHistory: getPromiseToPurchaseHistory, getPromiseToPurchaseRemainingAmounts: getPromiseToPurchaseRemainingAmounts }) }, { children: children })));
312
- };
313
- exports.default = UserContextProvider;
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ const jsx_runtime_1 = require("react/jsx-runtime");
30
+ const react_1 = require("react");
31
+ const index_1 = __importStar(require("./index"));
32
+ const useSDK_1 = __importDefault(require("../../hooks/useSDK"));
33
+ const moment_1 = __importDefault(require("moment"));
34
+ const functions_1 = require("../../../../utils/functions");
35
+ const UserContextProvider = ({ children }) => {
36
+ const sdk = (0, useSDK_1.default)();
37
+ const setUserLoggedIn = async (userData) => {
38
+ const isPro = !!userData.basic_info.customer_professionnal_info &&
39
+ !!userData.basic_info.customer_professionnal_info.proof_doc_value;
40
+ localStorage.setItem('userLogged', 'true');
41
+ if (!!isPro) {
42
+ localStorage.setItem('isPro', 'true');
43
+ }
44
+ const isClerk = localStorage.getItem('isClerk');
45
+ if (typeof window !== 'undefined' && !!isClerk) {
46
+ window.addEventListener('beforeunload', async (e) => {
47
+ if (!!!userData.temp_hash)
48
+ return;
49
+ e.preventDefault();
50
+ const dialogText = '';
51
+ e.returnValue = dialogText;
52
+ return dialogText;
53
+ });
54
+ }
55
+ setState((prevState) => (Object.assign(Object.assign({}, prevState), { isUserLoggedIn: true, userData: userData })));
56
+ };
57
+ const setUserLoggedOut = async (keepRepCart) => {
58
+ if (!!!sdk)
59
+ return;
60
+ if (!!state.userData && state.userData.temp_hash && !!!keepRepCart) {
61
+ await sdk.user.killRepCart(state.userData.temp_hash);
62
+ }
63
+ sdk.user.logout();
64
+ setState((prevState) => (Object.assign(Object.assign({}, prevState), { isUserLoggedIn: false, isPro: false, customPriceList: undefined, userData: null, resetUserData: true })));
65
+ };
66
+ const setUserPreferedStore = async (storeId) => {
67
+ if (!!!state.userData)
68
+ return;
69
+ await saveUser(Object.assign(Object.assign({}, state.userData), { prefered_store: storeId }));
70
+ };
71
+ const saveUser = async (customer) => {
72
+ if (!!!sdk)
73
+ return false;
74
+ setState((prevState) => (Object.assign(Object.assign({}, prevState), { userData: customer, isPro: !!customer.basic_info.customer_professionnal_info &&
75
+ !!customer.basic_info.customer_professionnal_info.professionnal_title })));
76
+ return await sdk.user.saveUser(customer);
77
+ };
78
+ const deleteUser = async () => {
79
+ if (!!!sdk)
80
+ return false;
81
+ return await sdk.user.deleteUser();
82
+ };
83
+ const getOrder = async (orderID, token) => {
84
+ if (!!!sdk)
85
+ return 'sdk_not_defined';
86
+ try {
87
+ const order = await sdk.user.getOrder(orderID, token);
88
+ return order;
89
+ }
90
+ catch (err) {
91
+ return 'error';
92
+ }
93
+ };
94
+ const changePassword = async (currentPassword, newPassword) => {
95
+ if (!!!sdk)
96
+ return 'sdk_not_defined';
97
+ try {
98
+ return await sdk.user.changePassword(currentPassword, newPassword);
99
+ }
100
+ catch (err) {
101
+ return err;
102
+ }
103
+ };
104
+ const changeProfilePicture = async (base64) => {
105
+ if (!!!sdk)
106
+ return 'sdk_not_defined';
107
+ try {
108
+ const upload = await sdk.user.changeProfilePicture(base64);
109
+ setState((prevState) => {
110
+ if (prevState.userData) {
111
+ return Object.assign(Object.assign({}, prevState), { userData: Object.assign(Object.assign({}, prevState.userData), { basic_info: Object.assign(Object.assign({}, prevState.userData.basic_info), { customer_image: upload === "Can't upload image." || upload === 'done' ? undefined : upload }) }) });
112
+ }
113
+ return prevState;
114
+ });
115
+ return upload;
116
+ }
117
+ catch (err) {
118
+ return err;
119
+ }
120
+ };
121
+ const setCustomPriceList = (list) => {
122
+ setState((prevState) => (Object.assign(Object.assign({}, prevState), { customPriceList: list, fetchCustomPrices: false })));
123
+ localStorage.setItem('customPriceList', JSON.stringify(list));
124
+ localStorage.setItem('lastCustomPriceFetch', (0, moment_1.default)().format('YYYY-MM-DD'));
125
+ };
126
+ const setLoaded = (value) => {
127
+ setState((prevState) => (Object.assign(Object.assign({}, prevState), { loaded: value })));
128
+ };
129
+ const [state, setState] = (0, react_1.useState)((0, index_1.getDefaultUserContext)());
130
+ (0, react_1.useEffect)(() => {
131
+ if (!!!sdk)
132
+ return;
133
+ const userLoggedData = localStorage.getItem('userLogged');
134
+ const userIsPro = localStorage.getItem('isPro');
135
+ const isClerk = localStorage.getItem('isClerk');
136
+ const isLoggedIn = !!userLoggedData && JSON.parse(userLoggedData);
137
+ const isPro = !!userLoggedData && !!userIsPro && JSON.parse(userIsPro);
138
+ let newState = Object.assign({ isUserLoggedIn: !!!isClerk && !!isLoggedIn, isPro: !!!isClerk && !!isPro }, checkForCustomPriceList(!!userIsPro));
139
+ if (!!isClerk) {
140
+ localStorage.removeItem('isClerk');
141
+ }
142
+ return setState((prevState) => (Object.assign(Object.assign(Object.assign({}, prevState), newState), { loaded: true })));
143
+ }, [sdk]);
144
+ (0, react_1.useEffect)(() => {
145
+ if (!!!state.fetchCustomPrices || !!!state.isPro || !!!state.userData || !!!sdk)
146
+ return;
147
+ const fetchCustomPrices = async () => {
148
+ const proUser = !!state.userData && !!state.isPro ? state.userData.id : '';
149
+ if (!!!proUser)
150
+ return;
151
+ try {
152
+ const newList = await sdk.user.fetchCustomPriceList(proUser);
153
+ if (!!newList) {
154
+ setCustomPriceList(newList);
155
+ }
156
+ }
157
+ catch (e) {
158
+ console.log('error on fetching customPrices from G2: ', e.toString());
159
+ setState((prevState) => (Object.assign(Object.assign({}, prevState), { fetchCustomPrices: false, customPriceList: undefined })));
160
+ }
161
+ };
162
+ fetchCustomPrices();
163
+ }, [sdk, state.fetchCustomPrices, state.isPro, state.userData]);
164
+ (0, react_1.useEffect)(() => {
165
+ if (!!!sdk)
166
+ return;
167
+ if (!state.isUserLoggedIn) {
168
+ return;
169
+ }
170
+ const getContent = async () => {
171
+ let user;
172
+ try {
173
+ user = (await sdk.user.getUser(!!localStorage.getItem('isClerk')));
174
+ if (!!!user) {
175
+ localStorage.setItem('isPro', JSON.stringify(false));
176
+ localStorage.removeItem('foundInG2');
177
+ if (!!localStorage.getItem('customPriceList')) {
178
+ localStorage.removeItem('customPriceList');
179
+ localStorage.removeItem('lastCustomPriceFetch');
180
+ }
181
+ return setState((prevState) => (Object.assign(Object.assign(Object.assign({}, prevState), { userData: null, isPro: false }), (!!prevState.customPriceList
182
+ ? {
183
+ customPriceList: undefined
184
+ }
185
+ : {}))));
186
+ }
187
+ const checkIsPro = !!user.basic_info.customer_professionnal_info &&
188
+ !!user.basic_info.customer_professionnal_info.professionnal_title;
189
+ setState((prevState) => (Object.assign(Object.assign(Object.assign({}, prevState), { userData: user, isPro: checkIsPro }), checkForCustomPriceList(checkIsPro))));
190
+ localStorage.setItem('isPro', JSON.stringify(checkIsPro));
191
+ if (!!!checkIsPro) {
192
+ localStorage.removeItem('foundInG2');
193
+ if (!!localStorage.getItem('customPriceList')) {
194
+ localStorage.removeItem('customPriceList');
195
+ localStorage.removeItem('lastCustomPriceFetch');
196
+ }
197
+ }
198
+ }
199
+ catch (err) {
200
+ if (!!err.message) {
201
+ const error = JSON.parse(err.message);
202
+ if (!!error && !!error.error) {
203
+ await setUserLoggedOut();
204
+ }
205
+ }
206
+ }
207
+ };
208
+ getContent();
209
+ }, [sdk, state.isUserLoggedIn]);
210
+ (0, react_1.useEffect)(() => {
211
+ return () => {
212
+ if (typeof window !== 'undefined') {
213
+ window.removeEventListener('onbeforeunload', async () => { });
214
+ }
215
+ };
216
+ }, []);
217
+ const checkForCustomPriceList = (userIsPro) => {
218
+ const hasCustomPriceList = !!userIsPro && localStorage.getItem('customPriceList');
219
+ const lastCustomPriceFetch = !!userIsPro && localStorage.getItem('lastCustomPriceFetch');
220
+ const foundProInG2 = !!userIsPro && localStorage.getItem('foundInG2');
221
+ const lastFetchWasBefore = !!userIsPro &&
222
+ (!!!lastCustomPriceFetch || (!!lastCustomPriceFetch && (0, moment_1.default)().isAfter((0, moment_1.default)(lastCustomPriceFetch), 'day')));
223
+ let parsedJSONCustomPrices = [];
224
+ if (!!hasCustomPriceList) {
225
+ try {
226
+ parsedJSONCustomPrices = JSON.parse(hasCustomPriceList);
227
+ }
228
+ catch (e) {
229
+ console.log(e.toString());
230
+ }
231
+ }
232
+ return Object.assign(Object.assign({}, (!!!lastFetchWasBefore && !!foundProInG2
233
+ ? { customPriceList: parsedJSONCustomPrices }
234
+ : { customPriceList: undefined })), (!!lastFetchWasBefore && !!foundProInG2 ? { fetchCustomPrices: true } : {}));
235
+ };
236
+ const getPromiseToPurchaseHistory = async (userId, filters) => {
237
+ if (!state.isPro)
238
+ throw new Error('Only the PRO users have a promise to purchase');
239
+ const api = !!sdk ? sdk.getAPIInfos() : null;
240
+ if (!!!api)
241
+ return;
242
+ if (!!!userId) {
243
+ if (!!state.userData && !!state.userData.id)
244
+ userId = state.userData.id;
245
+ else
246
+ throw new Error("Can't get user promise to purchase without userId");
247
+ }
248
+ let body = undefined;
249
+ if (!!filters) {
250
+ body = Object.assign(Object.assign({}, (!!filters.bankTypeId
251
+ ? {
252
+ bank_type_id: filters.bankTypeId
253
+ }
254
+ : {})), (!!filters.unixDateRange
255
+ ? {
256
+ unix_date_range: filters.unixDateRange
257
+ }
258
+ : {}));
259
+ }
260
+ const requestHistory = await fetch(`${api.api}/users/${userId}/promisestopurchase/history`, {
261
+ method: 'POST',
262
+ headers: {
263
+ Authorization: `Bearer ${api.token}`,
264
+ 'Content-Type': 'application/json',
265
+ 'x-gng-ecomm-token': api.userToken
266
+ },
267
+ body: !!body ? JSON.stringify(body) : undefined
268
+ });
269
+ const responseData = await requestHistory.json();
270
+ if (responseData.status !== 200) {
271
+ const errorStr = !!!responseData.error
272
+ ? ''
273
+ : typeof responseData.error === 'string'
274
+ ? responseData.error
275
+ : (0, functions_1.getStringByLang)(responseData.error, 'fr');
276
+ throw new Error('Error on history fetch: ' + errorStr);
277
+ }
278
+ return responseData.data.history;
279
+ };
280
+ const getPromiseToPurchaseRemainingAmounts = async (userId) => {
281
+ if (!state.isPro)
282
+ throw new Error('Only the PRO users have a promise to purchase');
283
+ const api = !!sdk ? sdk.getAPIInfos() : null;
284
+ if (!!!api)
285
+ return;
286
+ if (!!!userId) {
287
+ if (!!state.userData && !!state.userData.id)
288
+ userId = state.userData.id;
289
+ else
290
+ throw new Error("Can't get remaining amounts for user without userId");
291
+ }
292
+ const requestHistory = await fetch(`${api.api}/users/${userId}/promisestopurchase/remainingAmounts`, {
293
+ method: 'GET',
294
+ headers: {
295
+ Authorization: `Bearer ${api.token}`,
296
+ 'Content-Type': 'application/json',
297
+ 'x-gng-ecomm-token': api.userToken
298
+ }
299
+ });
300
+ const responseData = await requestHistory.json();
301
+ if (responseData.status !== 200) {
302
+ const errorStr = !!!responseData.error
303
+ ? ''
304
+ : typeof responseData.error === 'string'
305
+ ? responseData.error
306
+ : (0, functions_1.getStringByLang)(responseData.error, 'fr');
307
+ throw new Error('Error on remainingAmounts fetch: ' + errorStr);
308
+ }
309
+ return responseData.data.availableAmountsForBanks;
310
+ };
311
+ return ((0, jsx_runtime_1.jsx)(index_1.default.Provider, Object.assign({ value: Object.assign(Object.assign({}, state), { setLoaded: setLoaded, setUserLoggedIn: setUserLoggedIn, setUserLoggedOut: setUserLoggedOut, saveUser: saveUser, deleteUser: deleteUser, getOrder: getOrder, changePassword: changePassword, changeProfilePicture: changeProfilePicture, setUserPreferedStore: setUserPreferedStore, setCustomPriceList: setCustomPriceList, getPromiseToPurchaseHistory: getPromiseToPurchaseHistory, getPromiseToPurchaseRemainingAmounts: getPromiseToPurchaseRemainingAmounts }) }, { children: children })));
312
+ };
313
+ exports.default = UserContextProvider;
314
314
  //# sourceMappingURL=UserContextProvider.js.map