dcos-core-monalisav2-latam 1.0.0

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 (129) hide show
  1. package/README.md +130 -0
  2. package/index.js +350 -0
  3. package/package.json +52 -0
  4. package/src/auth/handler.js +3 -0
  5. package/src/common/MondelezCastOrder.js +449 -0
  6. package/src/common/utils/AuthSecurity.js +46 -0
  7. package/src/common/utils/account-error-handler.js +279 -0
  8. package/src/common/utils/account-error-helper.js +231 -0
  9. package/src/common/utils/account-properties-handler.js +355 -0
  10. package/src/common/utils/api-response.js +62 -0
  11. package/src/common/utils/aws-services.js +186 -0
  12. package/src/common/utils/constants/account-error-codes.json +801 -0
  13. package/src/common/utils/constants.js +37 -0
  14. package/src/common/utils/convert/MondelezClientsItemsCast.js +52 -0
  15. package/src/common/utils/convert/MondelezInventoryItemsCast.js +15 -0
  16. package/src/common/utils/convert/MondelezOrderStatusCast.js +34 -0
  17. package/src/common/utils/convert/MondelezPricesItemsCast.js +37 -0
  18. package/src/common/utils/cron-ftp-get.js +143 -0
  19. package/src/common/utils/data-tables-helper.js +213 -0
  20. package/src/common/utils/date-range-calculator.js +113 -0
  21. package/src/common/utils/delay.js +17 -0
  22. package/src/common/utils/ftp-sftp.js +320 -0
  23. package/src/common/utils/logger.js +126 -0
  24. package/src/common/utils/nodemailerLib.js +61 -0
  25. package/src/common/utils/product-unit-converter.js +168 -0
  26. package/src/common/utils/schemas-utils.js +101 -0
  27. package/src/common/utils/seller-email-sharing-service.js +441 -0
  28. package/src/common/utils/sftp-utils.js +202 -0
  29. package/src/common/utils/status.js +15 -0
  30. package/src/common/utils/util.js +236 -0
  31. package/src/common/utils/validate-state-order.js +35 -0
  32. package/src/common/utils/validateProviders.js +67 -0
  33. package/src/common/utils/validation-data.js +45 -0
  34. package/src/common/utils/vtex/save-hooks.js +65 -0
  35. package/src/common/utils/vtex/save-schemas.js +65 -0
  36. package/src/common/utils/vtex-hook-handler.js +71 -0
  37. package/src/common/validation/AccountCoordinatesValidation.js +350 -0
  38. package/src/common/validation/GeneralErrorValidation.js +11 -0
  39. package/src/common/validation/MainErrorValidation.js +8 -0
  40. package/src/entities/account.js +639 -0
  41. package/src/entities/clients.js +104 -0
  42. package/src/entities/controlprice.js +196 -0
  43. package/src/entities/controlstock.js +206 -0
  44. package/src/entities/cron.js +77 -0
  45. package/src/entities/cronjob.js +71 -0
  46. package/src/entities/orders.js +195 -0
  47. package/src/entities/sftp-inbound.js +88 -0
  48. package/src/entities/sku.js +220 -0
  49. package/src/entities/taxpromotion.js +249 -0
  50. package/src/functions/account/account-get.js +262 -0
  51. package/src/functions/account/account-handler.js +299 -0
  52. package/src/functions/account/clients.js +10 -0
  53. package/src/functions/account/index.js +208 -0
  54. package/src/functions/actions/save-promotions-order-history.js +324 -0
  55. package/src/functions/affiliates/affiliates-hook-consumer.js +87 -0
  56. package/src/functions/affiliates/affiliates-hook-producer.js +45 -0
  57. package/src/functions/clients/clients-audience.js +62 -0
  58. package/src/functions/clients/clients-consumer.js +648 -0
  59. package/src/functions/clients/clients-producer.js +362 -0
  60. package/src/functions/clients/clients-suggested-product-consumer.js +166 -0
  61. package/src/functions/clients/helpers/suggested-product-mdlz.js +233 -0
  62. package/src/functions/clients_peru/email.html +129 -0
  63. package/src/functions/clients_peru/splitfile.js +357 -0
  64. package/src/functions/clients_peru/updateClients.js +1334 -0
  65. package/src/functions/clients_peru/utils.js +243 -0
  66. package/src/functions/cronjobs/cron-jobs-manager.js +40 -0
  67. package/src/functions/cronjobs/cron-jobs.js +171 -0
  68. package/src/functions/crons/cron.js +39 -0
  69. package/src/functions/distributors/distributor-handler.js +81 -0
  70. package/src/functions/distributors/distributor.js +535 -0
  71. package/src/functions/distributors/index.js +60 -0
  72. package/src/functions/financialpolicy/assign-financialpolicy.js +111 -0
  73. package/src/functions/financialpolicy/get-financialpolicy.js +91 -0
  74. package/src/functions/financialpolicy/index.js +28 -0
  75. package/src/functions/inventory/catalog-sync-consumer.js +17 -0
  76. package/src/functions/inventory/catalog-sync-handler.js +311 -0
  77. package/src/functions/inventory/inventory-consumer.js +119 -0
  78. package/src/functions/inventory/inventory-producer.js +197 -0
  79. package/src/functions/multiPresentation/multipre-queue.js +155 -0
  80. package/src/functions/multiPresentation/multipres.js +459 -0
  81. package/src/functions/nodeflow/index.js +83 -0
  82. package/src/functions/nodeflow/nodeflow-cron.js +200 -0
  83. package/src/functions/nodeflow/nodeflow-pub.js +203 -0
  84. package/src/functions/nodeflow/nodeflow-pvt.js +266 -0
  85. package/src/functions/notifications/download-leads-handler.js +67 -0
  86. package/src/functions/notifications/new-leads-notification-consumer.js +17 -0
  87. package/src/functions/notifications/new-leads-notification-handler.js +359 -0
  88. package/src/functions/notifications/order-status-notification-handler.js +482 -0
  89. package/src/functions/notifications/promotion-notification-handler.js +193 -0
  90. package/src/functions/orders/index.js +32 -0
  91. package/src/functions/orders/orders-cancel-handler.js +74 -0
  92. package/src/functions/orders/orders-handler.js +280 -0
  93. package/src/functions/orders/orders-hook-consumer.js +137 -0
  94. package/src/functions/orders/orders-hook-producer.js +170 -0
  95. package/src/functions/orders/orders-notifications-handler.js +137 -0
  96. package/src/functions/orders/orders-status-consumer.js +461 -0
  97. package/src/functions/orders/orders-status-producer.js +443 -0
  98. package/src/functions/prices/index.js +75 -0
  99. package/src/functions/prices/prices-consumer.js +236 -0
  100. package/src/functions/prices/prices-producer.js +323 -0
  101. package/src/functions/prices/promotion-and-tax.js +1284 -0
  102. package/src/functions/routesflow/assign-routeflow-queue.js +77 -0
  103. package/src/functions/schemas/vtex/handle-schemas.js +102 -0
  104. package/src/functions/security/process_gas.js +221 -0
  105. package/src/functions/security/security-handler.js +950 -0
  106. package/src/functions/sftp/sftp-consumer.js +453 -0
  107. package/src/functions/sftpIntegrations/processes/redirectServices.js +184 -0
  108. package/src/functions/sftpIntegrations/processes/validateFileSchema.js +226 -0
  109. package/src/functions/sftpIntegrations/schemas/credential-schema.js +123 -0
  110. package/src/functions/sftpIntegrations/schemas/record-schema.js +131 -0
  111. package/src/functions/sftpIntegrations/schemas/sftp_required_fields.json +3 -0
  112. package/src/functions/sftpIntegrations/sftp-config-producer.js +112 -0
  113. package/src/functions/sftpIntegrations/sftp-consumer.js +700 -0
  114. package/src/functions/sftpIntegrations/test/validateFile.test.js +122 -0
  115. package/src/functions/sftpIntegrations/utils/connect-dynamo.js +29 -0
  116. package/src/functions/sftpIntegrations/utils/split-data.js +25 -0
  117. package/src/functions/utils/index.js +130 -0
  118. package/src/functions/vtex/vtex-helpers.js +694 -0
  119. package/src/integrations/accountErrors/AccountErrorManager.js +437 -0
  120. package/src/integrations/audience/Audience.js +70 -0
  121. package/src/integrations/financialPolicy/FinancialPolicyApi.js +377 -0
  122. package/src/integrations/index.js +0 -0
  123. package/src/integrations/mobilvendor/MobilvendorApi.js +405 -0
  124. package/src/integrations/productmultipresentation/ProductMultiPresentation.js +200 -0
  125. package/src/mdlz/auth/SecretManagerApi.js +77 -0
  126. package/src/mdlz/client/MdlzApi.js +70 -0
  127. package/src/vtex/clients/ProvidersApi.js +51 -0
  128. package/src/vtex/clients/VtexApi.js +511 -0
  129. package/src/vtex/models/VtexOrder.js +87 -0
@@ -0,0 +1,535 @@
1
+ const ApiResponse = require("../../common/utils/api-response");
2
+ const { DynamoDB } = require("aws-sdk");
3
+ const ClientData = require("../../entities/clients");
4
+ const Logger = require("../../common/utils/logger");
5
+
6
+ const dynamoDb = new DynamoDB.DocumentClient();
7
+ const SKU_DATA_DISTRIBUTOR_TABLE = process?.env?.SKU_DATA_DISTRIBUTOR_TABLE;
8
+
9
+ /**
10
+ * Function to validate input data manually.
11
+ * @param {Object} data
12
+ * @returns {Object|null} Returns an error object if validation fails, otherwise null.
13
+ */
14
+ function validateInputData(data) {
15
+ const errors = [];
16
+ if (typeof data.ERPCode !== 'string') {
17
+ errors.push('ERPCode debe ser una cadena');
18
+ }
19
+ if (typeof data.Name !== 'string' || data.Name.length < 1 || data.Name.length > 50) {
20
+ errors.push('Name debe ser una cadena entre 1 y 50 caracteres');
21
+ }
22
+ if (typeof data.Sku !== 'string') {
23
+ errors.push('Sku debe ser una cadena');
24
+ }
25
+ if (typeof data.Active !== 'boolean') {
26
+ errors.push('Active debe ser un booleano');
27
+ }
28
+
29
+ if (errors.length > 0) {
30
+ Logger.error('Errores de validación:', errors);
31
+ return { message: 'Datos de entrada inválidos', errors: errors };
32
+ }
33
+ return null;
34
+ }
35
+
36
+ /**
37
+ * Function to create a new distributor code.
38
+ * @param {string} accountNameAndSkuDis
39
+ * @param {string} accountName
40
+ * @param {Object} data
41
+ * @returns {Promise<Object|null>}
42
+ * @throws {Error}
43
+ */
44
+ async function createDistributorCodeTemplate(accountNameAndSkuDis, accountName, data) {
45
+ try {
46
+ const item = {
47
+ AccountNameAndSkuDis: accountNameAndSkuDis,
48
+ AccountName: accountName,
49
+ ERPCode: data.ERPCode,
50
+ Name: data.Name,
51
+ Sku: data.Sku,
52
+ Active: data.Active,
53
+ };
54
+
55
+ const params = {
56
+ TableName: SKU_DATA_DISTRIBUTOR_TABLE,
57
+ Item: item,
58
+ };
59
+
60
+ await dynamoDb.put(params).promise();
61
+
62
+ return item;
63
+ } catch (error) {
64
+ Logger.error('Error al crear distribuidor:', error);
65
+ return null;
66
+ }
67
+ }
68
+
69
+ /**
70
+ * Handler function for creating a new distributor code.
71
+ * @param {import("aws-lambda").APIGatewayProxyEvent} event
72
+ * @returns {Promise<any>}
73
+ */
74
+ async function createDistributorCode(event) {
75
+ try {
76
+ const request = JSON.parse(event.body);
77
+ const clientId = event?.requestContext?.authorizer?.claims?.client_id;
78
+ const requestDataArray = Array.isArray(request) ? request : [request];
79
+
80
+ for (const requestData of requestDataArray) {
81
+ const accountName = requestData?.AccountName;
82
+ const isValid = await ClientData.validateAccount(clientId, accountName);
83
+
84
+ if (!isValid) {
85
+ Logger.error("Account not found: ", accountName, ". ClientId: ", clientId);
86
+ return ApiResponse.responseNoCors(404, "Account not found");
87
+ }
88
+
89
+ // Generate AccountNameAndSkuDis by concatenating AccountName and ERPCode
90
+ requestData.AccountNameAndSkuDis = `${requestData.AccountName}-${requestData.ERPCode.toString()}`;
91
+
92
+ const result = await createDistributorCodeTemplate(requestData.AccountNameAndSkuDis, requestData.AccountName, requestData);
93
+ if (!result) {
94
+ return ApiResponse.responseNoCors(500, 'Error interno al crear distributor');
95
+ }
96
+ }
97
+
98
+ return ApiResponse.responseNoCors(200, { message: 'Distribuidor creado correctamente' });
99
+ } catch (error) {
100
+ Logger.error('Error al crear distribuidor:', error);
101
+ return ApiResponse.responseNoCors(500, 'Error interno al crear distribuidor');
102
+ }
103
+ }
104
+
105
+ /**
106
+ * Handler function for create or update a list of distributor codes.
107
+ * @param {import("aws-lambda").APIGatewayProxyEvent} event
108
+ * @returns {Promise<any>}
109
+ */
110
+ async function createOrUpdateDistributorCodes(event) {
111
+ try {
112
+ const request = JSON.parse(event.body);
113
+ const clientId = event?.requestContext?.authorizer?.claims?.client_id;
114
+
115
+ // Array to store the log messages
116
+ const logMessages = [];
117
+
118
+ // Validate input
119
+ if (!Array.isArray(request.ErpData)) {
120
+ return ApiResponse.responseNoCors(400, "Invalid input data");
121
+ }
122
+
123
+ // Obtener todos los accountName únicos del ErpData
124
+ const accountNames = [...new Set(request.ErpData.map(erpData => erpData.AccountName))];
125
+
126
+ // Mapa para almacenar todos los items existentes por accountName
127
+ const allExistingItemsMap = {};
128
+
129
+ // Obtener los distribuidores para cada accountName
130
+ for (const accountName of accountNames) {
131
+ allExistingItemsMap[accountName] = await getAllItemsByAccountName(accountName);
132
+ }
133
+
134
+ for (const erpData of request.ErpData) {
135
+ // Validar la cuenta
136
+ const isValid = await ClientData.validateAccount(clientId, erpData.AccountName);
137
+ if (!isValid) {
138
+ logMessages.push(`Error: Account not found for ${erpData.AccountName}`);
139
+ continue;
140
+ }
141
+
142
+ // Obtener los distribuidores existentes para el accountName actual
143
+ const existingItems = allExistingItemsMap[erpData.AccountName] || [];
144
+
145
+ const accountNameAndSkuDis = erpData?.AccountNameAndSkuDis ?? `${erpData.AccountName}-${erpData.ERPCode.toString()}`;
146
+ const existingItem = existingItems.find(item => item.AccountNameAndSkuDis === accountNameAndSkuDis);
147
+
148
+ if (erpData.Delete === true) {
149
+ if (existingItem) {
150
+ if (await deleteDistributorByTemplate(accountNameAndSkuDis, erpData.AccountName)) {
151
+ logMessages.push(`Distribuidor eliminado correctamente: ${accountNameAndSkuDis}`);
152
+ } else {
153
+ logMessages.push(`Error al eliminar distribuidor: ${accountNameAndSkuDis}`);
154
+ }
155
+ } else {
156
+ logMessages.push(`Distribuidor no encontrado para eliminación: ${accountNameAndSkuDis}`);
157
+ }
158
+ } else {
159
+ if (existingItem) {
160
+ // Actualizar el item existente
161
+ const result = await updateDistributorCodeTemplate(accountNameAndSkuDis, erpData.AccountName, erpData);
162
+ logMessages.push(`Distribuidor actualizado correctamente: ${result}`);
163
+ } else {
164
+ // Crear un nuevo item
165
+ const result = await createDistributorCodeTemplate(accountNameAndSkuDis, erpData.AccountName, erpData);
166
+ logMessages.push(`Distribuidor creado correctamente: ${result}`);
167
+ }
168
+ }
169
+ }
170
+
171
+ return ApiResponse.responseNoCors(200, { message: 'Operación completada', logs: logMessages });
172
+ } catch (error) {
173
+ Logger.error('Error al crear distribuidor:', error);
174
+ return ApiResponse.responseNoCors(500, 'Error interno al crear distribuidor');
175
+ }
176
+ }
177
+
178
+ /**
179
+ * Function to update an existing distributor code.
180
+ * @param {string} accountNameAndSkuDis
181
+ * @param {string} accountName
182
+ * @param {Object} data
183
+ * @returns {Promise<Object|null>}
184
+ * @throws {Error}
185
+ */
186
+ async function updateDistributorCodeTemplate(accountNameAndSkuDis, accountName, data) {
187
+ try {
188
+ //for update we need to delete the existing item and create a new one
189
+ const isDeleted = await deleteDistributorByTemplate(accountNameAndSkuDis, accountName);
190
+ if (!isDeleted) {
191
+ return null;
192
+ }
193
+ const newAccountNameAndSkuDis = `${accountName}-${data?.ERPCode.toString()}`;
194
+ const result = await createDistributorCodeTemplate(newAccountNameAndSkuDis, accountName, data);
195
+ return result;
196
+ } catch (error) {
197
+ Logger.error('Error al actualizar distribuidor:', error);
198
+ return null;
199
+ }
200
+ }
201
+
202
+ /**
203
+ * Handler function for updating an existing distributor code.
204
+ * @param {import("aws-lambda").APIGatewayProxyEvent} event
205
+ * @returns {Promise<any>}
206
+ */
207
+ async function updateDistributorCode(event) {
208
+ try {
209
+ const clientId = event?.requestContext?.authorizer?.claims?.client_id;
210
+ const distributorCode = event?.pathParameters?.id;
211
+ const accountName = distributorCode.split('-')[0];
212
+ const isValid = await ClientData.validateAccount(clientId, accountName);
213
+
214
+ if (!isValid) {
215
+ Logger.error("Account not found: ", accountName, ". ClientId: ", clientId);
216
+ return ApiResponse.responseNoCors(404, "Account not found");
217
+ }
218
+
219
+ if (!distributorCode || !accountName) {
220
+ return ApiResponse.responseNoCors(400, { message: 'Distributor code and AccountName required' });
221
+ }
222
+
223
+ const data = JSON.parse(event.body);
224
+
225
+ const validationError = validateInputData(data);
226
+ if (validationError) {
227
+ return ApiResponse.responseNoCors(400, validationError);
228
+ };
229
+
230
+ const result = await updateDistributorCodeTemplate(distributorCode, data.AccountName, data);
231
+
232
+ return ApiResponse.responseNoCors(200, { message: 'Distribuidor actualizado correctamente', attributes: result });
233
+ } catch (error) {
234
+ Logger.error('Error al actualizar distribuidor:', error);
235
+ return ApiResponse.responseNoCors(500, 'Error interno al actualizar distribuidor');
236
+ }
237
+ }
238
+
239
+ /**
240
+ * Handler function for deleting a distributor code.
241
+ * @param {import("aws-lambda").APIGatewayProxyEvent} event
242
+ * @returns {Promise<any>}
243
+ */
244
+ async function deleteDistributorCode(event) {
245
+ try {
246
+ const clientId = event?.requestContext?.authorizer?.claims?.client_id;
247
+ const distributorCode = event?.pathParameters?.id;
248
+ const accountName = distributorCode.split('-')[0];
249
+ const isValid = await ClientData.validateAccount(clientId, accountName);
250
+
251
+ if (!isValid) {
252
+ Logger.error("Account not found: ", accountName, ". ClientId: ", clientId);
253
+ return ApiResponse.responseNoCors(404, "Account not found");
254
+ }
255
+
256
+ if (!distributorCode || !accountName) {
257
+ return ApiResponse.responseNoCors(400, { message: 'Distributor code and AccountName required' });
258
+ }
259
+
260
+ await deleteDistributorByTemplate(distributorCode, accountName);
261
+
262
+ return ApiResponse.responseNoCors(200, { message: 'Distribuidor eliminado correctamente' });
263
+ } catch (error) {
264
+ Logger.error('Error al eliminar distribuidor:', error);
265
+ return ApiResponse.responseNoCors(500, 'Error interno al eliminar distribuidor');
266
+ }
267
+ }
268
+
269
+ /**
270
+ * Handler function for deleting a distributor code.
271
+ * @param {string} distributorCode
272
+ * @param {string} accountName
273
+ * @returns {Promise<boolean>}
274
+ */
275
+ async function deleteDistributorByTemplate(distributorCode, accountName) {
276
+ try {
277
+ const params = {
278
+ TableName: SKU_DATA_DISTRIBUTOR_TABLE,
279
+ Key: {
280
+ AccountNameAndSkuDis: distributorCode,
281
+ AccountName: accountName,
282
+ },
283
+ };
284
+ await dynamoDb.delete(params).promise();
285
+ return true;
286
+ } catch (error) {
287
+ Logger.error('Error al eliminar distribuidor:', error);
288
+ return false;
289
+ }
290
+ }
291
+
292
+ /**
293
+ * Function to get all items by account name.
294
+ * @param {string} accountName
295
+ * @returns {Promise<any>}
296
+ * @throws {Error}
297
+ */
298
+ async function getAllItemsByAccountName(accountName) {
299
+ try {
300
+ const params = {
301
+ TableName: SKU_DATA_DISTRIBUTOR_TABLE,
302
+ IndexName: 'AccountNameIndex',
303
+ KeyConditionExpression: '#AccountName = :AccountName',
304
+ ExpressionAttributeNames: {
305
+ '#AccountName': 'AccountName',
306
+ },
307
+ ExpressionAttributeValues: {
308
+ ':AccountName': accountName,
309
+ },
310
+ };
311
+ let result = await dynamoDb.query(params).promise();
312
+ let items = result.Items;
313
+
314
+ while (result.LastEvaluatedKey) {
315
+ params.ExclusiveStartKey = result.LastEvaluatedKey;
316
+ result = await dynamoDb.query(params).promise();
317
+ items = items.concat(result.Items);
318
+ }
319
+
320
+ return items;
321
+ } catch (error) {
322
+ Logger.error('Error al obtener items por accountName:', error);
323
+ return [];
324
+ }
325
+ }
326
+
327
+ /**
328
+ * Handler function for retrieving all distributors.
329
+ * @param {import("aws-lambda").APIGatewayProxyEvent} event
330
+ * @returns {Promise<any>}
331
+ * @throws {Error}
332
+ */
333
+ async function getAllDistributorsCodes(event) {
334
+ try {
335
+ const clientId = event?.requestContext?.authorizer?.claims?.client_id;
336
+ const accountName = event?.queryStringParameters?.accountName;
337
+
338
+ let params = {
339
+ TableName: SKU_DATA_DISTRIBUTOR_TABLE,
340
+ Limit: 300,
341
+ Select: !accountName ? "ALL_ATTRIBUTES" : "ALL_PROJECTED_ATTRIBUTES",
342
+ ReturnConsumedCapacity: "TOTAL",
343
+ };
344
+
345
+ let result = null;
346
+ // Verificamos si el accountName fue pasado como query param
347
+ if (accountName) {
348
+ const isValid = await ClientData.validateAccount(clientId, accountName);
349
+ if (!isValid) {
350
+ Logger.error("Account not found: ", accountName, ". ClientId: ", clientId);
351
+ return ApiResponse.responseNoCors(404, "Account not found");
352
+ }
353
+ params.IndexName = 'AccountNameIndex';
354
+ params.KeyConditionExpression = '#AccountName = :AccountName';
355
+ params.ExpressionAttributeNames = {
356
+ '#AccountName': 'AccountName',
357
+ };
358
+ params.ExpressionAttributeValues = {
359
+ ':AccountName': accountName,
360
+ };
361
+ result = await dynamoDb.query(params).promise();
362
+
363
+ } else {
364
+ // Si no se proporciona el accountName, hacemos la consulta total
365
+ result = await dynamoDb.scan(params).promise();
366
+ }
367
+ let items = result.Items;
368
+ while (result.LastEvaluatedKey) {
369
+ params.ExclusiveStartKey = result.LastEvaluatedKey;
370
+ result = await dynamoDb.query(params).promise();
371
+ items = items.concat(result.Items);
372
+ }
373
+ return ApiResponse.responseNoCors(200, items);
374
+ } catch (error) {
375
+ Logger.error('Error al obtener distribuidores:', error);
376
+ return ApiResponse.responseNoCors(500, 'Error interno al obtener distribuidores');
377
+ }
378
+ }
379
+
380
+ /**
381
+ * Handler function for retrieving a distributor by code.
382
+ * @param {import("aws-lambda").APIGatewayProxyEvent} event
383
+ * @returns {Promise<any>}
384
+ */
385
+ async function getDistributorByCode(event) {
386
+ try {
387
+ const clientId = event?.requestContext?.authorizer?.claims?.client_id;
388
+ const distributorCode = event?.pathParameters?.id;
389
+ const accountName = distributorCode.split('-')[0];
390
+ const isValid = await ClientData.validateAccount(clientId, accountName);
391
+
392
+ if (!isValid) {
393
+ Logger.error("Account not found: ", accountName, ". ClientId: ", clientId);
394
+ return ApiResponse.responseNoCors(404, "Account not found");
395
+ }
396
+
397
+ if (!distributorCode || !accountName) {
398
+ return ApiResponse.responseNoCors(400, { message: 'Código de distribuidor y AccountName requeridos' });
399
+ }
400
+
401
+ const params = {
402
+ TableName: SKU_DATA_DISTRIBUTOR_TABLE,
403
+ Key: {
404
+ AccountNameAndSkuDis: distributorCode,
405
+ AccountName: accountName,
406
+ },
407
+ };
408
+ const result = await dynamoDb.get(params).promise();
409
+
410
+ if (!result.Item) {
411
+ return ApiResponse.responseNoCors(404, { message: 'Distribuidor no encontrado' });
412
+ }
413
+
414
+ return ApiResponse.responseNoCors(200, result.Item);
415
+ } catch (error) {
416
+ Logger.error('Error al obtener distribuidor por código:', error);
417
+ return ApiResponse.responseNoCors(500, 'Error interno al obtener distribuidor por código');
418
+ }
419
+ }
420
+
421
+ /**
422
+ * Handler function for retrieving a distributor by sku.
423
+ * @param {string} accountName Name of the account
424
+ * @param {string} sku Sku of the product
425
+ * @param {boolean} skuDistributorManagement Flag to manage distributor by sku
426
+ * @returns {Promise<any>}
427
+ */
428
+ async function getDistributorByErpCode(accountName, erpCode, skuDistributorManagement) {
429
+ try {
430
+ if (!skuDistributorManagement || skuDistributorManagement === false) {
431
+ return erpCode;
432
+ }
433
+
434
+ if (!accountName || !erpCode) {
435
+ Logger.error('Error al obtener distribuidor por erpCode');
436
+ throw new Error('Error al obtener distribuidor por erpCode');
437
+ }
438
+
439
+ const AccountNameAndSkuDis = `${accountName}-${erpCode?.toString()}`;
440
+ const params = {
441
+ TableName: SKU_DATA_DISTRIBUTOR_TABLE,
442
+ Key: {
443
+ AccountNameAndSkuDis: AccountNameAndSkuDis,
444
+ AccountName: accountName,
445
+ },
446
+ };
447
+ const result = await dynamoDb.get(params).promise();
448
+
449
+ if (!result.Item) {
450
+ Logger.error('Item no encontrado por código de distribuidor');
451
+ throw new Error('Item no encontrado por código de distribuidor');
452
+ }
453
+
454
+ if (!result?.Item?.Active || result?.Item?.Active === false) {
455
+ Logger.error('Sku inactivo en distribuidor');
456
+ throw new Error('Sku inactivo en distribuidor');
457
+ }
458
+
459
+ return result?.Item?.Sku ?? erpCode;
460
+
461
+ } catch (error) {
462
+ Logger.error('Error al obtener distribuidor por erpCode:', error);
463
+ throw error;
464
+ }
465
+ }
466
+
467
+ /**
468
+ * Handler function for retrieving a distributor by ean.
469
+ * @param {string} accountName Name of the account
470
+ * @param {string} ean Ean of the product
471
+ * @param {boolean} skuDistributorManagement Flag to manage distributor by sku
472
+ * @returns {Promise<any>}
473
+ */
474
+ async function getDistributorByRefId(accountName, sku, skuDistributorManagement) {
475
+ try {
476
+ if (!skuDistributorManagement || skuDistributorManagement === false) {
477
+ Logger.error('No se gestiona distribuidor por sku');
478
+ return sku;
479
+ }
480
+
481
+ if (!accountName || !sku) {
482
+ Logger.error('Error al obtener distribuidor por sku');
483
+ throw new Error('Error al obtener distribuidor por sku');
484
+ }
485
+
486
+ const params = {
487
+ TableName: SKU_DATA_DISTRIBUTOR_TABLE,
488
+ IndexName: 'SkuIndex',
489
+ KeyConditionExpression: '#AccountName = :AccountName AND #Sku = :Sku',
490
+ ExpressionAttributeNames: {
491
+ '#AccountName': 'AccountName',
492
+ '#Sku': 'Sku',
493
+ '#Active': 'Active'
494
+ },
495
+ ExpressionAttributeValues: {
496
+ ':AccountName': accountName,
497
+ ':Sku': sku,
498
+ ':Active': true
499
+ },
500
+ FilterExpression: '#Active = :Active',
501
+ Limit: 300,
502
+ Select: "ALL_PROJECTED_ATTRIBUTES",
503
+ };
504
+ let result = await dynamoDb.query(params).promise();
505
+ let items = result.Items;
506
+
507
+ while (result.LastEvaluatedKey) {
508
+ params.ExclusiveStartKey = result.LastEvaluatedKey;
509
+ result = await dynamoDb.query(params).promise();
510
+ items = items.concat(result.Items);
511
+ }
512
+
513
+ if (!items || items.length === 0) {
514
+ Logger.error('Item no encontrado por código de distribuidor');
515
+ throw new Error('Item no encontrado por código de distribuidor');
516
+ }
517
+
518
+ return items[0]?.ERPCode ?? sku;
519
+
520
+ } catch (error) {
521
+ Logger.error('Error al obtener distribuidor por sku:', error);
522
+ throw error;
523
+ }
524
+ }
525
+
526
+ module.exports = {
527
+ createDistributorCode,
528
+ createOrUpdateDistributorCodes,
529
+ updateDistributorCode,
530
+ deleteDistributorCode,
531
+ getAllDistributorsCodes,
532
+ getDistributorByCode,
533
+ getDistributorByErpCode,
534
+ getDistributorByRefId,
535
+ };
@@ -0,0 +1,60 @@
1
+
2
+ const ApiResponse = require("../../common/utils/api-response");
3
+ const distributor = require("./distributor");
4
+
5
+ module.exports.handler= async (req,res)=>{
6
+ const resource= req?.resource ?? null;
7
+ const method= req?.httpMethod ? String(req?.httpMethod).toUpperCase() : null;
8
+
9
+ if(resource && method){
10
+ switch(resource){
11
+ case "/distributors":
12
+ switch(method){
13
+ case "POST":
14
+ return await distributor?.createDistributorCode(req,res);
15
+ case "GET":
16
+ return await distributor?.getAllDistributorsCodes(req,res);
17
+ default:
18
+ return ApiResponse.response(400, {error: "error method!."});
19
+ }
20
+ break;
21
+ case "/distributors/import":
22
+ switch(method){
23
+ case "POST":
24
+ return await distributor?.createOrUpdateDistributorCodes(req,res);
25
+ default:
26
+ return ApiResponse.response(400, {error: "error method!."});
27
+ }
28
+ break;
29
+ case "/distributors/get/{id}":
30
+ switch(method){
31
+ case "GET":
32
+ return await distributor?.getDistributorByCode(req,res);
33
+ default:
34
+ return ApiResponse.response(400, {error: "error method!."});
35
+ }
36
+ break;
37
+ case "/distributors/update/{id}":
38
+ switch(method){
39
+ case "PUT":
40
+ return await distributor?.updateDistributorCode(req,res);
41
+ default:
42
+ return ApiResponse.response(400, {error: "error method!."});
43
+ }
44
+ break;
45
+ case "/distributors/delete/{id}":
46
+ switch(method){
47
+ case "DELETE":
48
+ return await distributor?.deleteDistributorCode(req,res);
49
+ default:
50
+ return ApiResponse.response(400, {error: "error method!."});
51
+ }
52
+ break;
53
+
54
+ default:
55
+ return ApiResponse.response(400, {error: "error resource!."});
56
+ }
57
+ }else{
58
+ return ApiResponse.response(400, {error: "error resource!."});
59
+ }
60
+ }