dcos-core-monalisav2-latam 1.1.5 → 1.1.6

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.6",
4
4
  "scripts": {
5
5
  "test": "echo \"Error: no test specified\" && exit 1"
6
6
  },
@@ -23,15 +23,29 @@ const consumer = async (event) => {
23
23
  // Referencia a la API de VTEX sobre el marketplace asociado
24
24
  const vtexApi = new VtexApi(parentAccount, key, token);
25
25
 
26
- const { clientId, productsRegular, productsIncremental } = client;
26
+ const {
27
+ clientId,
28
+ productsRegular, productsIncremental,
29
+ productsRegularFinal, productsIncrementalFinal
30
+ } = client;
31
+
32
+ // Insertar datos en Clientes Totales
33
+ await vtexApi.fetch(`/dataentities/${DATA_ENTITY_CLIENT_ACRONYM}/documents`, {
34
+ method: 'PATCH',
35
+ data: {
36
+ id: clientId,
37
+ productsRegular: JSON.stringify(productsRegular),
38
+ productsIncremental: JSON.stringify(productsIncremental),
39
+ }
40
+ });
27
41
 
28
42
  // Objeto de datos para el producto sugerido
29
43
  const suggestedProductData = {
30
44
  orderDate: new Date().toISOString(),
31
45
  clientId,
32
46
  type: 'SUGGESTED_ORDER',
33
- productsRegular,
34
- productsIncremental,
47
+ productsRegular: productsRegularFinal,
48
+ productsIncremental: productsIncrementalFinal,
35
49
  };
36
50
  const email = `${Startemail}+${clientId}@${Domainemail}`;
37
51
  // Consulta del userProfileId
@@ -43,16 +57,6 @@ const consumer = async (event) => {
43
57
  data: suggestedProductData
44
58
  });
45
59
 
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
60
  Logger.log("Suggested products processed successfully", { an, clientId });
57
61
  }
58
62
  } 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,17 @@ function validateClientsData(clients, minProductsCount, indexClientRegister, an,
127
122
  continue;
128
123
  }
129
124
 
125
+ client.clientId = clientId;
126
+ client.productsRegularFinal = [];
127
+ client.productsIncrementalFinal = [];
128
+ setItemInformation(client.productsRegular, 'REGULAR', skusList, client.productsRegularFinal);
129
+ setItemInformation(client.productsIncremental, 'INCREMENTAL', skusList, client.productsIncrementalFinal);
130
+
130
131
  // 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) {
132
+ if (client.productsRegularFinal.length < minProductsCount || client.productsIncrementalFinal.length < minProductsCount) {
132
133
  client.error = `Validate the following properties productsRegular and productsIncremental minimum ${minProductsCount} elements`;
133
134
  notProcessedItems.push(client);
134
- continue;
135
135
  }
136
-
137
- client.clientId = clientId;
138
- setItemInformation(client.productsRegular, 'REGULAR', skusList);
139
- setItemInformation(client.productsIncremental, 'INCREMENTAL', skusList);
140
136
  }
141
137
 
142
138
  // Si hay ítems no procesados, se retorna el mensaje de error
@@ -173,21 +169,33 @@ async function getSkuData(skusList, account) {
173
169
  do {
174
170
  // Se extrae las primeras filas de la lista para ejecutar las Promises
175
171
  let rowsData = items.splice(0, 10);
172
+ const skus = {};
176
173
  await Promise.allSettled(rowsData.map(sku => {
177
174
  return new Promise((resolve, reject) => {
178
175
  // Se consulta el SKU en MonalisaV2
179
176
  getSkuInformation(sku, account, skuRefUsed).then(skuId => {
180
- // Se consulta en VTEX información del producto
177
+ // Se establece el skuId del producto, para luego consultar en VTEX
181
178
  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);
179
+ skus[skuId] = sku;
180
+ resolve(sku);
188
181
  }).catch(reject);
189
182
  });
190
183
  })).catch(Logger.error);
184
+
185
+ // Se consulta el detalle de los SKU en VTEX
186
+ if (Object.keys(skus).length) {
187
+ const skusData = await vtexApi.getDetailSkuById(Object.keys(skus)).catch(Logger.error);
188
+ if (skusData?.length) {
189
+ for (let skuInfo of skusData) {
190
+ const { Id, IsActive, ProductIsVisible } = skuInfo;
191
+ if (skus.hasOwnProperty(Id)) {
192
+ const { [Id]: sku } = skus;
193
+ skusList[sku].IsActive = IsActive;
194
+ skusList[sku].ProductIsVisible = ProductIsVisible;
195
+ }
196
+ }
197
+ }
198
+ }
191
199
  } while (items.length);
192
200
  }
193
201
 
@@ -249,27 +257,35 @@ function removeDuplicatesSku(items, skusList) {
249
257
 
250
258
  /**
251
259
  * 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.
260
+ * @param {Object[]} list Lista de ítems enviados en la petición.
261
+ * @param {String} productType Tipo de producto ('REGULAR' o 'INCREMENTAL').
254
262
  * @param {Object} skusList Objeto donde se consolida la información de los SKU que no fueron encontrados.
255
263
  */
256
- function setItemInformation(list, productType, skusList) {
264
+ function setItemInformation(list, productType, skusList, finalList) {
257
265
  for (let item of list) {
258
- item.type = productType;
259
- const { sku } = item;
260
- // Se elimina la propiedad "sku", para luego insertar este valor en la entidad de productos sugeridos
261
- delete item.sku;
262
- if (skusList?.[sku]) {
266
+ const { sku, quantity, priority } = item;
267
+ const finalItem = {
268
+ refId: sku,
269
+ quantity,
270
+ type: productType,
271
+ priority
272
+ };
273
+
274
+ if (skusList?.[sku]?.hasOwnProperty('SkuId')) {
263
275
  const { SkuId, IsActive, ProductIsVisible } = skusList[sku];
264
- item.refId = sku;
265
- item.skuId = SkuId;
276
+ finalItem.skuId = SkuId;
266
277
  if (IsActive) {
267
- item.status = ProductIsVisible ? 'active' : 'not_visible';
278
+ if (ProductIsVisible) {
279
+ finalItem.status = 'active';
280
+ finalList.push(finalItem);
281
+ } else {
282
+ finalItem.status = 'not_visible';
283
+ }
268
284
  } else {
269
- item.status = 'inactive';
285
+ finalItem.status = 'inactive';
270
286
  }
271
287
  } else {
272
- item.status = 'invalid';
288
+ finalItem.status = 'invalid';
273
289
  }
274
290
  }
275
291
  }