thm-p3-configurator 0.0.94 → 0.0.95

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.
@@ -1,11 +1,14 @@
1
1
  "use strict";
2
2
 
3
+ require("core-js/modules/es.promise.js");
3
4
  Object.defineProperty(exports, "__esModule", {
4
5
  value: true
5
6
  });
6
7
  exports.authenticatedProxyApi = void 0;
8
+ require("core-js/modules/es.promise.js");
7
9
  var _axios = _interopRequireDefault(require("axios"));
8
10
  var _constants__ = require("../__constants__");
11
+ var _cookieManager = require("../__helpers__/cookieManager");
9
12
  var _LocalStorageWorker = require("../__services__/LocalStorageWorker");
10
13
  function _interopRequireDefault(e) {
11
14
  return e && e.__esModule ? e : {
@@ -15,16 +18,36 @@ function _interopRequireDefault(e) {
15
18
  const authenticateClient = _axios.default.create({
16
19
  baseURL: APP_CONFIG.proxyUrl
17
20
  });
21
+ const refreshClient = _axios.default.create({
22
+ baseURL: APP_CONFIG.proxyUrl
23
+ });
24
+ refreshClient.interceptors.request.use(config => {
25
+ const refreshToken = (0, _cookieManager.getRefreshToken)();
26
+ config.headers.Authorization = "Bearer ".concat(refreshToken);
27
+ return config;
28
+ });
18
29
 
19
30
  /**
20
31
  * @description This interceptor:
21
32
  * - Appends the bearer token (For authentication)
22
33
  * - Appends the currently active branch Id (For authorization)
23
34
  */
24
- authenticateClient.interceptors.request.use(config => {
35
+ authenticateClient.interceptors.request.use(async config => {
25
36
  var _authSession$branch;
26
37
  const authSession = _LocalStorageWorker.lsw.getJson(_constants__.AUTH_SESSION_KEY);
27
- config.headers.Authorization = "Bearer ".concat(authSession === null || authSession === void 0 ? void 0 : authSession.accessToken);
38
+ let accessToken = (0, _cookieManager.getAccessToken)();
39
+ if (!accessToken) {
40
+ try {
41
+ const refreshResponse = await refreshClient('api/v1/auth', {
42
+ method: 'PUT'
43
+ });
44
+ accessToken = refreshResponse.data.accessToken;
45
+ (0, _cookieManager.setAccessToken)(accessToken);
46
+ } catch (error) {
47
+ console.log('error', error);
48
+ }
49
+ }
50
+ config.headers.Authorization = "Bearer ".concat(accessToken);
28
51
  config.headers['active-branch-id'] = authSession === null || authSession === void 0 || (_authSession$branch = authSession.branch) === null || _authSession$branch === void 0 ? void 0 : _authSession$branch.entityId;
29
52
  return config;
30
53
  });
@@ -32,6 +55,9 @@ const authenticatedProxyApi = exports.authenticatedProxyApi = {
32
55
  getArticleTypes: () => authenticateClient("api/v1/articles/types", {
33
56
  method: 'GET'
34
57
  }),
58
+ putRefreshToken: () => refreshClient('api/v1/auth', {
59
+ method: 'PUT'
60
+ }),
35
61
  getArticleGroups: articleTypeId => authenticateClient("api/v1/articles/groups/".concat(articleTypeId), {
36
62
  method: 'GET'
37
63
  }),
@@ -133,5 +159,17 @@ const authenticatedProxyApi = exports.authenticatedProxyApi = {
133
159
  'Content-Type': 'application/json'
134
160
  }
135
161
  });
162
+ },
163
+ getOrder: orderParameters => {
164
+ const basePath = APP_CONFIG.internal ? 'api/v1' : 'api/public/v1';
165
+ return authenticateClient("".concat(basePath, "/configurator/order?").concat(orderParameters), {
166
+ method: 'GET'
167
+ });
168
+ },
169
+ getArticlePrices: partsQueryString => {
170
+ const basePath = APP_CONFIG.internal ? 'api/v1' : 'api/public/v1';
171
+ return authenticateClient("".concat(basePath, "/configurator/prices?").concat(partsQueryString), {
172
+ method: 'GET'
173
+ });
136
174
  }
137
175
  };
@@ -30,9 +30,6 @@ orderClient.interceptors.request.use(config => {
30
30
  return config;
31
31
  });
32
32
  const orderApi = exports.orderApi = {
33
- getOrder: orderParameters => orderClient("api".concat(APP_CONFIG.internal ? '' : '/public', "/order?").concat(orderParameters) // Remove the `/public` param if the configurator is internal,
34
- ),
35
- getArticlePrices: partsQueryString => orderClient("api".concat(APP_CONFIG.internal ? '' : '/public', "/prices?").concat(partsQueryString)),
36
33
  getArticles: filters => orderClient("api/public/articles?".concat(filters)),
37
34
  getBrands: () => orderClient('api/public/makes'),
38
35
  getBuildYears: brand => orderClient("api/public/makes/".concat(brand, "/years")),
@@ -318,7 +318,7 @@ const useSingleOrderCart = () => {
318
318
  totals: []
319
319
  };
320
320
  }
321
- const orderResults = await _orderApi.orderApi.getOrder(cartOrderQuery).then(res => res.data);
321
+ const orderResults = await _authenticatedProxyApi.authenticatedProxyApi.getOrder(cartOrderQuery).then(res => res.data);
322
322
  if (!orderResults.data.cart) {
323
323
  return {
324
324
  cart: []
@@ -364,8 +364,8 @@ const useProductsQuery = orderParameters => {
364
364
  enabled: (licensePlate === null || licensePlate === void 0 ? void 0 : licensePlate.length) > 5 || !!(model !== null && model !== void 0 && model.length),
365
365
  keepPreviousData: true,
366
366
  queryFn: async () => {
367
- var _response$data, _JSON$parse, _data$articles, _data$articles2, _data$articles3, _data$articles4, _data$articles5, _data$articles6, _data$articles7, _data$articles8, _data$articles9, _data$articles10, _data$articles11;
368
- const response = await _orderApi.orderApi.getOrder(productsSearchParams);
367
+ var _response$data, _JSON$parse, _data$articles, _data$articles2, _data$articles3, _data$articles4, _data$articles5, _data$articles6;
368
+ const response = await _authenticatedProxyApi.authenticatedProxyApi.getOrder(productsSearchParams);
369
369
  const data = (_response$data = response.data) === null || _response$data === void 0 ? void 0 : _response$data.data;
370
370
  if (!data) return data;
371
371
  const authSession = _LocalStorageWorker.lsw.get(_constants__.AUTH_SESSION_KEY);
@@ -377,23 +377,30 @@ const useProductsQuery = orderParameters => {
377
377
  }
378
378
  // Get all products to enrich
379
379
  const allProducts = [...(((_data$articles = data.articles) === null || _data$articles === void 0 ? void 0 : _data$articles.towbars) || []), ...(((_data$articles2 = data.articles) === null || _data$articles2 === void 0 ? void 0 : _data$articles2.cablesets) || []), ...(((_data$articles3 = data.articles) === null || _data$articles3 === void 0 ? void 0 : _data$articles3.combisets) || []), ...((_data$articles4 = data.articles) !== null && _data$articles4 !== void 0 && _data$articles4.boardComputerUpdate ? [(_data$articles5 = data.articles) === null || _data$articles5 === void 0 ? void 0 : _data$articles5.boardComputerUpdate] : []), ...(((_data$articles6 = data.articles) === null || _data$articles6 === void 0 ? void 0 : _data$articles6.extras) || [])];
380
+ // NOTE: the API to enrich the products with extra data is only available when the configurator has an authenticated user, so on in the PP.
381
+ // If we need this also for the public version than Hyper needs to implement this.
380
382
 
381
- // Enrich all products with brands and prices
382
- const enrichedProducts = await (0, _singleOrderArticles.enrichArticlesWithBrandsAndPrices)(allProducts, branchId, formula);
383
+ if (APP_CONFIG.internal) {
384
+ var _data$articles7, _data$articles8, _data$articles9, _data$articles10, _data$articles11;
385
+ // Enrich all products with brands and prices
386
+ const enrichedProducts = await (0, _singleOrderArticles.enrichArticlesWithBrandsAndPrices)(allProducts, branchId, formula);
383
387
 
384
- // Create a lookup map for the enriched products
385
- const enrichedProductsMap = Object.fromEntries(enrichedProducts.map(product => [product.articleNumber, product]));
388
+ // Create a lookup map for the enriched products
389
+ const enrichedProductsMap = Object.fromEntries(enrichedProducts.map(product => [product.articleNumber, product]));
386
390
 
387
- // Update the products in the response with the enriched data
388
- return _objectSpread(_objectSpread({}, data), {}, {
389
- articles: _objectSpread(_objectSpread({}, data.articles), {}, {
390
- towbars: ((_data$articles7 = data.articles) === null || _data$articles7 === void 0 || (_data$articles7 = _data$articles7.towbars) === null || _data$articles7 === void 0 ? void 0 : _data$articles7.map(product => _objectSpread(_objectSpread({}, product), enrichedProductsMap[product.articleNumber]))) || [],
391
- cablesets: ((_data$articles8 = data.articles) === null || _data$articles8 === void 0 || (_data$articles8 = _data$articles8.cablesets) === null || _data$articles8 === void 0 ? void 0 : _data$articles8.map(product => _objectSpread(_objectSpread({}, product), enrichedProductsMap[product.articleNumber]))) || [],
392
- combisets: ((_data$articles9 = data.articles) === null || _data$articles9 === void 0 || (_data$articles9 = _data$articles9.combisets) === null || _data$articles9 === void 0 ? void 0 : _data$articles9.map(product => _objectSpread(_objectSpread({}, product), enrichedProductsMap[product.articleNumber]))) || [],
393
- boardComputerUpdate: (_data$articles10 = data.articles) !== null && _data$articles10 !== void 0 && _data$articles10.boardComputerUpdate ? _objectSpread(_objectSpread({}, data.articles.boardComputerUpdate), enrichedProductsMap[data.articles.boardComputerUpdate.articleNumber]) : null,
394
- extras: ((_data$articles11 = data.articles) === null || _data$articles11 === void 0 || (_data$articles11 = _data$articles11.extras) === null || _data$articles11 === void 0 ? void 0 : _data$articles11.map(product => _objectSpread(_objectSpread({}, product), enrichedProductsMap[product.articleNumber]))) || []
395
- })
396
- });
391
+ // Update the products in the response with the enriched data
392
+ return _objectSpread(_objectSpread({}, data), {}, {
393
+ articles: _objectSpread(_objectSpread({}, data.articles), {}, {
394
+ towbars: ((_data$articles7 = data.articles) === null || _data$articles7 === void 0 || (_data$articles7 = _data$articles7.towbars) === null || _data$articles7 === void 0 ? void 0 : _data$articles7.map(product => _objectSpread(_objectSpread({}, product), enrichedProductsMap[product.articleNumber]))) || [],
395
+ cablesets: ((_data$articles8 = data.articles) === null || _data$articles8 === void 0 || (_data$articles8 = _data$articles8.cablesets) === null || _data$articles8 === void 0 ? void 0 : _data$articles8.map(product => _objectSpread(_objectSpread({}, product), enrichedProductsMap[product.articleNumber]))) || [],
396
+ combisets: ((_data$articles9 = data.articles) === null || _data$articles9 === void 0 || (_data$articles9 = _data$articles9.combisets) === null || _data$articles9 === void 0 ? void 0 : _data$articles9.map(product => _objectSpread(_objectSpread({}, product), enrichedProductsMap[product.articleNumber]))) || [],
397
+ boardComputerUpdate: (_data$articles10 = data.articles) !== null && _data$articles10 !== void 0 && _data$articles10.boardComputerUpdate ? _objectSpread(_objectSpread({}, data.articles.boardComputerUpdate), enrichedProductsMap[data.articles.boardComputerUpdate.articleNumber]) : null,
398
+ extras: ((_data$articles11 = data.articles) === null || _data$articles11 === void 0 || (_data$articles11 = _data$articles11.extras) === null || _data$articles11 === void 0 ? void 0 : _data$articles11.map(product => _objectSpread(_objectSpread({}, product), enrichedProductsMap[product.articleNumber]))) || []
399
+ })
400
+ });
401
+ } else {
402
+ return data;
403
+ }
397
404
  }
398
405
  });
399
406
  return {
@@ -436,7 +443,7 @@ const useQuestionsQuery = questionParams => {
436
443
  const questionsParamsString = new URLSearchParams((0, _helpers__.removeNullishProps)(questionParams)).toString();
437
444
  const questionsQuery = (0, _reactQuery.useQuery)(['questions', questionsParamsString], {
438
445
  enabled: (licensePlate === null || licensePlate === void 0 ? void 0 : licensePlate.length) > 5 || !!(model !== null && model !== void 0 && model.length),
439
- queryFn: () => _orderApi.orderApi.getOrder(questionsParamsString).then(res => {
446
+ queryFn: () => _authenticatedProxyApi.authenticatedProxyApi.getOrder(questionsParamsString).then(res => {
440
447
  var _res$data4, _res$data5, _res$data6, _res$data7, _res$data8, _res$data9;
441
448
  return {
442
449
  execution1Answer: res === null || res === void 0 || (_res$data4 = res.data) === null || _res$data4 === void 0 || (_res$data4 = _res$data4.data) === null || _res$data4 === void 0 || (_res$data4 = _res$data4.answers) === null || _res$data4 === void 0 ? void 0 : _res$data4.execution1,
@@ -0,0 +1,104 @@
1
+ "use strict";
2
+
3
+ require("core-js/modules/es.string.starts-with.js");
4
+ require("core-js/modules/es.string.trim.js");
5
+ Object.defineProperty(exports, "__esModule", {
6
+ value: true
7
+ });
8
+ exports.setRefreshToken = exports.setAuthCookies = exports.setAccessToken = exports.isAuthenticated = exports.getRefreshToken = exports.getCookie = exports.getAccessToken = exports.clearAuthCookies = void 0;
9
+ require("core-js/modules/es.string.starts-with.js");
10
+ require("core-js/modules/es.string.trim.js");
11
+ /**
12
+ * Sets authentication cookies with security attributes
13
+ * @param {string} accessToken - JWT access token
14
+ * @param {string} refreshToken - JWT refresh token
15
+ */
16
+ const setAuthCookies = (accessToken, refreshToken) => {
17
+ setAccessToken(accessToken);
18
+ setRefreshToken(refreshToken);
19
+ };
20
+ exports.setAuthCookies = setAuthCookies;
21
+ const setAccessToken = accessToken => {
22
+ const accessExpiry = getTokenExpiry(accessToken) || 60 * 60;
23
+ document.cookie = "access_token=".concat(accessToken, "; max-age=").concat(accessExpiry, "; path=/; SameSite=Strict; Secure;");
24
+ };
25
+ exports.setAccessToken = setAccessToken;
26
+ const setRefreshToken = refreshToken => {
27
+ const refreshExpiry = getTokenExpiry(refreshToken) || 7 * 24 * 60 * 60;
28
+ document.cookie = "refresh_token=".concat(refreshToken, "; max-age=").concat(refreshExpiry, "; path=/; SameSite=Strict; Secure;");
29
+ };
30
+
31
+ /**
32
+ * Gets a cookie by name
33
+ * @param {string} name - The name of the cookie to retrieve
34
+ * @returns {string|null} The cookie value or null if not found
35
+ */
36
+ exports.setRefreshToken = setRefreshToken;
37
+ const getCookie = name => {
38
+ const cookies = document.cookie.split(';');
39
+ for (let i = 0; i < cookies.length; i++) {
40
+ const cookie = cookies[i].trim();
41
+ if (cookie.startsWith(name + '=')) {
42
+ return cookie.substring(name.length + 1);
43
+ }
44
+ }
45
+ return null;
46
+ };
47
+
48
+ /**
49
+ * Gets the access token from cookies
50
+ * @returns {string|null} The access token or null
51
+ */
52
+ exports.getCookie = getCookie;
53
+ const getAccessToken = () => {
54
+ return getCookie('access_token');
55
+ };
56
+
57
+ /**
58
+ * Gets the refresh token from cookies
59
+ * @returns {string|null} The refresh token or null
60
+ */
61
+ exports.getAccessToken = getAccessToken;
62
+ const getRefreshToken = () => {
63
+ return getCookie('refresh_token');
64
+ };
65
+
66
+ /**
67
+ * Clears authentication cookies
68
+ */
69
+ exports.getRefreshToken = getRefreshToken;
70
+ const clearAuthCookies = () => {
71
+ document.cookie = 'access_token=; max-age=0; path=/; SameSite=Strict; Secure;';
72
+ document.cookie = 'refresh_token=; max-age=0; path=/; SameSite=Strict; Secure;';
73
+ };
74
+
75
+ /**
76
+ * Checks if the user is authenticated based on cookie presence
77
+ * @returns {boolean} True if authenticated
78
+ */
79
+ exports.clearAuthCookies = clearAuthCookies;
80
+ const isAuthenticated = () => {
81
+ return !!getAccessToken();
82
+ };
83
+
84
+ /**
85
+ * Extracts expiration time from a JWT token
86
+ * @param {string} token - JWT token
87
+ * @returns {number|null} Expiration time in seconds or null if can't be determined
88
+ */
89
+ exports.isAuthenticated = isAuthenticated;
90
+ const getTokenExpiry = token => {
91
+ try {
92
+ const parts = token.split('.');
93
+ if (parts.length !== 3) return null;
94
+ const payload = JSON.parse(atob(parts[1]));
95
+ if (payload.exp) {
96
+ const currentTimeInSeconds = Math.floor(Date.now() / 1000);
97
+ return Math.max(0, payload.exp - currentTimeInSeconds);
98
+ }
99
+ return null;
100
+ } catch (error) {
101
+ console.error('Error parsing JWT token:', error);
102
+ return null;
103
+ }
104
+ };
@@ -127,7 +127,7 @@ const fetchArticlesByLicensePlateAndModel = async (filters, formula, branchId) =
127
127
  executionAnswer2: filters.executionAnswer2,
128
128
  skipFilters: (_filters$showAllArtic = filters === null || filters === void 0 ? void 0 : filters.showAllArticles) !== null && _filters$showAllArtic !== void 0 ? _filters$showAllArtic : false
129
129
  })).toString();
130
- const orderData = await _orderApi.orderApi.getOrder(queryString);
130
+ const orderData = await _authenticatedProxyApi.authenticatedProxyApi.getOrder(queryString);
131
131
  if (!(orderData !== null && orderData !== void 0 && (_orderData$data = orderData.data) !== null && _orderData$data !== void 0 && (_orderData$data = _orderData$data.data) !== null && _orderData$data !== void 0 && _orderData$data.articles)) {
132
132
  return {
133
133
  articles: [],
@@ -193,7 +193,7 @@ const enrichArticlesWithBrandsAndPrices = async (articles, branchId, formula) =>
193
193
  brandNumber: (_article$brand = article.brand) !== null && _article$brand !== void 0 ? _article$brand : _index2.DEFAULT_ARTICLE_BRAND
194
194
  };
195
195
  });
196
- const pricesResponse = await _orderApi.orderApi.getArticlePrices(new URLSearchParams({
196
+ const pricesResponse = await _authenticatedProxyApi.authenticatedProxyApi.getArticlePrices(new URLSearchParams({
197
197
  branchId,
198
198
  formula,
199
199
  parts: JSON.stringify(parts)
@@ -35,6 +35,7 @@ var _OrderSessionContext = require("../../__context__/OrderSessionContext");
35
35
  var _helpers__ = require("../../__helpers__");
36
36
  var _dossier = require("../../__helpers__/dossier");
37
37
  var _useSearchParam = _interopRequireDefault(require("../../__hooks__/useSearchParam"));
38
+ var _authenticatedProxyApi = require("../../__api__/authenticatedProxyApi");
38
39
  function _interopRequireDefault(e) {
39
40
  return e && e.__esModule ? e : {
40
41
  default: e
@@ -127,7 +128,7 @@ const InternalSessionEditPage = props => {
127
128
  var _dossierById$akkoordO, _orderRes$data, _orderRes$data2;
128
129
  let session = (0, _dossier.parseDossierToOrderSession)(dossierById);
129
130
  session.customerAgreed = (_dossierById$akkoordO = dossierById === null || dossierById === void 0 ? void 0 : dossierById.akkoordOpmerkingen) !== null && _dossierById$akkoordO !== void 0 ? _dossierById$akkoordO : false;
130
- const orderRes = await _orderApi.orderApi.getOrder(new URLSearchParams((0, _helpers__.removeNullishProps)(_objectSpread(_objectSpread({}, session), {}, {
131
+ const orderRes = await _authenticatedProxyApi.authenticatedProxyApi.getOrder(new URLSearchParams((0, _helpers__.removeNullishProps)(_objectSpread(_objectSpread({}, session), {}, {
131
132
  formula
132
133
  }))).toString());
133
134
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "thm-p3-configurator",
3
- "version": "0.0.94",
3
+ "version": "0.0.95",
4
4
  "main": "dist/index.js",
5
5
  "module": "dist/index.js",
6
6
  "author": "EnoRm.",