dcos-core-monalisav2-latam 1.1.5 → 1.1.7

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dcos-core-monalisav2-latam",
3
- "version": "1.1.5",
3
+ "version": "1.1.7",
4
4
  "scripts": {
5
5
  "test": "echo \"Error: no test specified\" && exit 1"
6
6
  },
@@ -25,6 +25,16 @@ const consumer = async (event) => {
25
25
 
26
26
  const { clientId, productsRegular, productsIncremental } = client;
27
27
 
28
+ // Insertar datos en Clientes Totales
29
+ await vtexApi.fetch(`/dataentities/${DATA_ENTITY_CLIENT_ACRONYM}/documents`, {
30
+ method: 'PATCH',
31
+ data: {
32
+ id: clientId,
33
+ productsRegular: JSON.stringify(productsRegular),
34
+ productsIncremental: JSON.stringify(productsIncremental),
35
+ }
36
+ });
37
+
28
38
  // Objeto de datos para el producto sugerido
29
39
  const suggestedProductData = {
30
40
  orderDate: new Date().toISOString(),
@@ -33,8 +43,8 @@ const consumer = async (event) => {
33
43
  productsRegular,
34
44
  productsIncremental,
35
45
  };
36
- const email = `${Startemail}+${clientId}@${Domainemail}`;
37
46
  // Consulta del userProfileId
47
+ const email = `${Startemail}+${clientId}@${Domainemail}`;
38
48
  await findUserProfileId(vtexApi, email, suggestedProductData);
39
49
 
40
50
  // Insertar datos en entidad de Productos Sugeridos
@@ -43,16 +53,6 @@ const consumer = async (event) => {
43
53
  data: suggestedProductData
44
54
  });
45
55
 
46
- // Insertar datos en Clientes Totales
47
- await vtexApi.fetch(`/dataentities/${DATA_ENTITY_CLIENT_ACRONYM}/documents`, {
48
- method: 'PATCH',
49
- data: {
50
- id: clientId,
51
- productsRegular: JSON.stringify(productsRegular),
52
- productsIncremental: JSON.stringify(productsIncremental),
53
- }
54
- });
55
-
56
56
  Logger.log("Suggested products processed successfully", { an, clientId });
57
57
  }
58
58
  } catch (error) {
@@ -13,7 +13,6 @@ const {
13
13
  const suggestedProductMdlz = async (event) => {
14
14
  try {
15
15
  const { an, clients } = JSON.parse(event.body);
16
- // return ApiResponse.response(200, { an, clients });
17
16
 
18
17
  const account = await AccountData.getAccountDataByAccountName(an);
19
18
  if (!account) {
@@ -33,10 +32,6 @@ const suggestedProductMdlz = async (event) => {
33
32
  if (!IndexClientRegister?.length) {
34
33
  return ApiResponse.response(400, "IndexClientRegister not configured for account");
35
34
  }
36
- // Se valida que exista el índice 'an'
37
- if (!IndexClientRegister.includes('an')) {
38
- return ApiResponse.response(400, "IndexClientRegister must have a 'an' property");
39
- }
40
35
 
41
36
  // Se obtiene las propiedades de la configuración de ProductSuggestedConfig
42
37
  const {
@@ -103,17 +98,17 @@ function validateClientsData(clients, minProductsCount, indexClientRegister, an,
103
98
 
104
99
  for (const client of clients) {
105
100
  let remain = [], clientId = '';
101
+ // Se recorre la lista para definir el clientId del usuario asociado
106
102
  for (let prop of indexClientRegister) {
107
103
  if (prop == 'an') {
108
104
  clientId += an;
105
+ } else if (client.hasOwnProperty(prop)) {
106
+ clientId += client[prop] ?? '';
109
107
  } else {
110
- if (client.hasOwnProperty(prop)) {
111
- clientId += client[prop] ?? '';
112
- } else {
113
- remain.push(prop);
114
- }
108
+ remain.push(prop);
115
109
  }
116
110
  }
111
+ // Si no se encontró propiedades, se genera el mensaje de error
117
112
  if (remain.length) {
118
113
  client.error = `The properties ${remain.join(',')} are required`;
119
114
  notProcessedItems.push(client);
@@ -127,16 +122,16 @@ function validateClientsData(clients, minProductsCount, indexClientRegister, an,
127
122
  continue;
128
123
  }
129
124
 
130
- // Se valida si la longitud de alguno de los ítems del cliente es menos al número mínimo de productos
131
- if (client.productsRegular?.length < minProductsCount || client.productsIncremental?.length < minProductsCount) {
125
+ client.clientId = clientId;
126
+ const productsCounter = { 'REGULAR': 0, 'INCREMENTAL': 0 };
127
+ setItemInformation(client.productsRegular, 'REGULAR', skusList, productsCounter);
128
+ setItemInformation(client.productsIncremental, 'INCREMENTAL', skusList, productsCounter);
129
+
130
+ // Se valida si la longitud de alguno de la lista de ítems válidos del cliente es menos al número mínimo de productos
131
+ if (productsCounter.REGULAR.length < minProductsCount || productsCounter.INCREMENTAL.length < minProductsCount) {
132
132
  client.error = `Validate the following properties productsRegular and productsIncremental minimum ${minProductsCount} elements`;
133
133
  notProcessedItems.push(client);
134
- continue;
135
134
  }
136
-
137
- client.clientId = clientId;
138
- setItemInformation(client.productsRegular, 'REGULAR', skusList);
139
- setItemInformation(client.productsIncremental, 'INCREMENTAL', skusList);
140
135
  }
141
136
 
142
137
  // Si hay ítems no procesados, se retorna el mensaje de error
@@ -173,21 +168,33 @@ async function getSkuData(skusList, account) {
173
168
  do {
174
169
  // Se extrae las primeras filas de la lista para ejecutar las Promises
175
170
  let rowsData = items.splice(0, 10);
171
+ const skus = {};
176
172
  await Promise.allSettled(rowsData.map(sku => {
177
173
  return new Promise((resolve, reject) => {
178
174
  // Se consulta el SKU en MonalisaV2
179
175
  getSkuInformation(sku, account, skuRefUsed).then(skuId => {
180
- // Se consulta en VTEX información del producto
176
+ // Se establece el skuId del producto, para luego consultar en VTEX
181
177
  skusList[sku].SkuId = skuId;
182
- vtexApi.getDetailSkuById([skuId]).then(res => {
183
- const { IsActive, ProductIsVisible } = res[0];
184
- skusList[sku].IsActive = IsActive;
185
- skusList[sku].ProductIsVisible = ProductIsVisible;
186
- resolve(sku);
187
- }).catch(reject);
178
+ skus[skuId] = sku;
179
+ resolve(sku);
188
180
  }).catch(reject);
189
181
  });
190
182
  })).catch(Logger.error);
183
+
184
+ // Se consulta el detalle de los SKU en VTEX
185
+ if (Object.keys(skus).length) {
186
+ const skusData = await vtexApi.getDetailSkuById(Object.keys(skus)).catch(Logger.error);
187
+ if (skusData?.length) {
188
+ for (let skuInfo of skusData) {
189
+ const { Id, IsActive, ProductIsVisible } = skuInfo;
190
+ if (skus.hasOwnProperty(Id)) {
191
+ const { [Id]: sku } = skus;
192
+ skusList[sku].IsActive = IsActive;
193
+ skusList[sku].ProductIsVisible = ProductIsVisible;
194
+ }
195
+ }
196
+ }
197
+ }
191
198
  } while (items.length);
192
199
  }
193
200
 
@@ -249,22 +256,27 @@ function removeDuplicatesSku(items, skusList) {
249
256
 
250
257
  /**
251
258
  * Organiza la información de los SKU en cada una de las listas de productos del cliente.
252
- * @param {Object[]} list Lista de ítems de producto sugerido.
253
- * @param {Object} skusList Objeto donde se consolida la información de los SKU.
259
+ * @param {Object[]} list Lista de ítems enviados en la petición.
260
+ * @param {String} productType Tipo de producto ('REGULAR' o 'INCREMENTAL').
254
261
  * @param {Object} skusList Objeto donde se consolida la información de los SKU que no fueron encontrados.
262
+ * @param {Object} productsCounter Objeto donde se consolida el conteo de productos válidos por el tipo de producto `productType`.
255
263
  */
256
- function setItemInformation(list, productType, skusList) {
264
+ function setItemInformation(list, productType, skusList, productsCounter) {
257
265
  for (let item of list) {
258
- item.type = productType;
259
266
  const { sku } = item;
260
- // Se elimina la propiedad "sku", para luego insertar este valor en la entidad de productos sugeridos
267
+ item.type = productType;
268
+
269
+ // Se elimina la propiedad "sku" del ítem de la lista, ya que su valor se estableció en la propiedad "refId"
270
+ item.refId = sku;
261
271
  delete item.sku;
262
- if (skusList?.[sku]) {
272
+
273
+ if (skusList?.[sku]?.hasOwnProperty('SkuId')) {
263
274
  const { SkuId, IsActive, ProductIsVisible } = skusList[sku];
264
- item.refId = sku;
265
275
  item.skuId = SkuId;
266
276
  if (IsActive) {
267
277
  item.status = ProductIsVisible ? 'active' : 'not_visible';
278
+ // Se incrementa el contador de productos válidos asociados al tipo "productType"
279
+ productsCounter[productType] += 1;
268
280
  } else {
269
281
  item.status = 'inactive';
270
282
  }