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,437 @@
1
+ const DynamoAWS = require("aws-sdk/clients/dynamodb");
2
+ const Logger = require("../../common/utils/logger");
3
+
4
+ const ACCOUNT_ERRORS_TABLE = process.env.ACCOUNT_ERRORS_TABLE;
5
+
6
+ class AccountErrorManager {
7
+
8
+ /**
9
+ * Crea una respuesta de error con formato estándar
10
+ * @param {string} errorCode - Código de error (ej: 'ACCOUNT_001')
11
+ * @param {Object} replacements - Valores para reemplazar en el mensaje (opcional)
12
+ * @returns {Promise<Object>} Respuesta de error formateada
13
+ */
14
+ static async createResponse(errorCode, replacements = {}) {
15
+ try {
16
+ const errorInfo = await this.getError(errorCode);
17
+
18
+ if (!errorInfo) {
19
+ // ✅ MEJORADO: Fallback más robusto con logging
20
+ Logger.warn(`Error code ${errorCode} not found in database, using fallback`);
21
+
22
+ // Categorías conocidas de errores para fallback inteligente
23
+ const errorCategories = {
24
+ 'ACCOUNT_': { status: 400, category: 'Account Management' },
25
+ 'VTEX_': { status: 500, category: 'VTEX Integration' },
26
+ 'AUTH_': { status: 401, category: 'Authentication' },
27
+ 'PERM_': { status: 403, category: 'Permissions' },
28
+ 'VALID_': { status: 400, category: 'Validation' }
29
+ };
30
+
31
+ // Determinar status code basado en el prefijo del código
32
+ let httpStatus = 500;
33
+ let category = 'Unknown';
34
+
35
+ for (const [prefix, config] of Object.entries(errorCategories)) {
36
+ if (errorCode.startsWith(prefix)) {
37
+ httpStatus = config.status;
38
+ category = config.category;
39
+ break;
40
+ }
41
+ }
42
+
43
+ return {
44
+ statusCode: httpStatus,
45
+ body: JSON.stringify({
46
+ error: errorCode,
47
+ message: `Error ${errorCode}: Operation failed. Please contact support if this issue persists.`,
48
+ category: category,
49
+ fallback: true // Flag para indicar que es fallback
50
+ }, null, 2),
51
+ headers: {
52
+ "Content-Type": "application/json"
53
+ }
54
+ };
55
+ }
56
+
57
+ // Reemplazar variables en el mensaje si se proporcionan
58
+ let message = errorInfo.Message;
59
+ Object.keys(replacements).forEach(key => {
60
+ const placeholder = `{${key}}`;
61
+ message = message.replace(new RegExp(placeholder.replace(/[{}]/g, '\\$&'), 'g'), replacements[key]);
62
+ });
63
+
64
+ return {
65
+ statusCode: errorInfo.HttpStatus,
66
+ body: JSON.stringify({
67
+ error: errorCode,
68
+ message: message,
69
+ category: errorInfo.Category,
70
+ severity: errorInfo.Severity
71
+ }, null, 2),
72
+ headers: {
73
+ "Content-Type": "application/json"
74
+ }
75
+ };
76
+
77
+ } catch (error) {
78
+ Logger.error("Error creating response:", error);
79
+
80
+ // ✅ MEJORADO: Fallback de emergencia más informativo
81
+ return {
82
+ statusCode: 500,
83
+ body: JSON.stringify({
84
+ error: errorCode || 'SYSTEM_ERROR',
85
+ message: "A system error occurred while processing your request. Please contact support.",
86
+ category: "System Error",
87
+ emergency_fallback: true,
88
+ timestamp: new Date().toISOString()
89
+ }, null, 2),
90
+ headers: {
91
+ "Content-Type": "application/json"
92
+ }
93
+ };
94
+ }
95
+ }
96
+
97
+ /**
98
+ * Obtiene un error específico por código
99
+ * @param {string} errorCode - Código del error
100
+ * @returns {Promise<Object|null>} Información del error
101
+ */
102
+ static async getError(errorCode) {
103
+ try {
104
+ if (!ACCOUNT_ERRORS_TABLE) {
105
+ Logger.error("ACCOUNT_ERRORS_TABLE environment variable not set");
106
+ return null;
107
+ }
108
+
109
+ const dynamodb = new DynamoAWS.DocumentClient();
110
+ const params = {
111
+ TableName: ACCOUNT_ERRORS_TABLE,
112
+ Key: { ErrorCode: errorCode }
113
+ };
114
+
115
+ const result = await dynamodb.get(params).promise();
116
+ return result.Item || null;
117
+ } catch (error) {
118
+ Logger.error(`Error getting error ${errorCode}:`, error);
119
+ return null;
120
+ }
121
+ }
122
+
123
+ /**
124
+ * Lista todos los errores con filtros opcionales
125
+ * @param {Object} filters - Filtros para la consulta
126
+ * @returns {Promise<Object>} Lista de errores
127
+ */
128
+ static async listErrors(filters = {}) {
129
+ try {
130
+ if (!ACCOUNT_ERRORS_TABLE) {
131
+ throw new Error("ACCOUNT_ERRORS_TABLE environment variable not set");
132
+ }
133
+
134
+ const dynamodb = new DynamoAWS.DocumentClient();
135
+ let params = {
136
+ TableName: ACCOUNT_ERRORS_TABLE,
137
+ Limit: filters.limit || 100
138
+ };
139
+
140
+ // Filtrar por categoría si se especifica
141
+ if (filters.category) {
142
+ params.IndexName = "CategoryIndex";
143
+ params.KeyConditionExpression = "Category = :category";
144
+ params.ExpressionAttributeValues = {
145
+ ":category": filters.category
146
+ };
147
+
148
+ const result = await dynamodb.query(params).promise();
149
+ return {
150
+ items: result.Items,
151
+ lastEvaluatedKey: result.LastEvaluatedKey,
152
+ count: result.Count
153
+ };
154
+ }
155
+
156
+ // Filtrar por severidad si se especifica
157
+ if (filters.severity) {
158
+ params.IndexName = "SeverityIndex";
159
+ params.KeyConditionExpression = "Severity = :severity";
160
+ params.ExpressionAttributeValues = {
161
+ ":severity": filters.severity
162
+ };
163
+
164
+ const result = await dynamodb.query(params).promise();
165
+ return {
166
+ items: result.Items,
167
+ lastEvaluatedKey: result.LastEvaluatedKey,
168
+ count: result.Count
169
+ };
170
+ }
171
+
172
+ // Scan completo si no hay filtros específicos
173
+ if (filters.lastEvaluatedKey) {
174
+ params.ExclusiveStartKey = JSON.parse(filters.lastEvaluatedKey);
175
+ }
176
+
177
+ const result = await dynamodb.scan(params).promise();
178
+ return {
179
+ items: result.Items,
180
+ lastEvaluatedKey: result.LastEvaluatedKey,
181
+ count: result.Count
182
+ };
183
+
184
+ } catch (error) {
185
+ Logger.error("Error listing errors:", error);
186
+ throw error;
187
+ }
188
+ }
189
+
190
+ /**
191
+ * Crea un nuevo error
192
+ * @param {Object} errorData - Datos del error
193
+ * @returns {Promise<Object>} Error creado
194
+ */
195
+ static async createError(errorData) {
196
+ try {
197
+ if (!ACCOUNT_ERRORS_TABLE) {
198
+ throw new Error("ACCOUNT_ERRORS_TABLE environment variable not set");
199
+ }
200
+
201
+ const dynamodb = new DynamoAWS.DocumentClient();
202
+
203
+ // Validar campos requeridos
204
+ const requiredFields = ['ErrorCode', 'HttpStatus', 'Message', 'Category', 'Severity'];
205
+ for (const field of requiredFields) {
206
+ if (!errorData[field]) {
207
+ throw new Error(`${field} is required`);
208
+ }
209
+ }
210
+
211
+ // Verificar que el error no exista
212
+ const existingError = await this.getError(errorData.ErrorCode);
213
+ if (existingError) {
214
+ throw new Error(`Error code ${errorData.ErrorCode} already exists`);
215
+ }
216
+
217
+ const params = {
218
+ TableName: ACCOUNT_ERRORS_TABLE,
219
+ Item: {
220
+ ErrorCode: errorData.ErrorCode,
221
+ HttpStatus: errorData.HttpStatus,
222
+ Message: errorData.Message,
223
+ Description: errorData.Description || '',
224
+ Category: errorData.Category,
225
+ Severity: errorData.Severity,
226
+ PossibleCauses: errorData.PossibleCauses || [],
227
+ Solutions: errorData.Solutions || [],
228
+ RelatedFields: errorData.RelatedFields || [],
229
+ RelatedTables: errorData.RelatedTables || [],
230
+ RelatedEndpoints: errorData.RelatedEndpoints || [],
231
+ CreatedAt: new Date().toISOString(),
232
+ UpdatedAt: new Date().toISOString()
233
+ }
234
+ };
235
+
236
+ await dynamodb.put(params).promise();
237
+ return params.Item;
238
+
239
+ } catch (error) {
240
+ Logger.error("Error creating error:", error);
241
+ throw error;
242
+ }
243
+ }
244
+
245
+ /**
246
+ * Actualiza un error existente
247
+ * @param {string} errorCode - Código del error
248
+ * @param {Object} errorData - Nuevos datos del error
249
+ * @returns {Promise<Object>} Error actualizado
250
+ */
251
+ static async updateError(errorCode, errorData) {
252
+ try {
253
+ if (!ACCOUNT_ERRORS_TABLE) {
254
+ throw new Error("ACCOUNT_ERRORS_TABLE environment variable not set");
255
+ }
256
+
257
+ const dynamodb = new DynamoAWS.DocumentClient();
258
+
259
+ // Verificar que el error existe
260
+ const existingError = await this.getError(errorCode);
261
+ if (!existingError) {
262
+ throw new Error(`Error code ${errorCode} not found`);
263
+ }
264
+
265
+ // Construir UpdateExpression dinámicamente
266
+ const updateFields = ['HttpStatus', 'Message', 'Description', 'Category', 'Severity',
267
+ 'PossibleCauses', 'Solutions', 'RelatedFields', 'RelatedTables', 'RelatedEndpoints'];
268
+
269
+ let updateExpression = 'SET UpdatedAt = :updatedAt';
270
+ const expressionAttributeNames = {};
271
+ const expressionAttributeValues = {
272
+ ':updatedAt': new Date().toISOString()
273
+ };
274
+ const updates = [];
275
+
276
+ updateFields.forEach(field => {
277
+ if (errorData[field] !== undefined) {
278
+ const attributeName = `#${field}`;
279
+ const attributeValue = `:${field}`;
280
+ updates.push(`${attributeName} = ${attributeValue}`);
281
+ expressionAttributeNames[attributeName] = field;
282
+ expressionAttributeValues[attributeValue] = errorData[field];
283
+ }
284
+ });
285
+
286
+ if (updates.length > 0) {
287
+ updateExpression += ', ' + updates.join(', ');
288
+ }
289
+
290
+ const params = {
291
+ TableName: ACCOUNT_ERRORS_TABLE,
292
+ Key: { ErrorCode: errorCode },
293
+ UpdateExpression: updateExpression,
294
+ ExpressionAttributeNames: Object.keys(expressionAttributeNames).length > 0 ? expressionAttributeNames : undefined,
295
+ ExpressionAttributeValues: expressionAttributeValues,
296
+ ReturnValues: 'ALL_NEW'
297
+ };
298
+
299
+ const result = await dynamodb.update(params).promise();
300
+ return result.Attributes;
301
+
302
+ } catch (error) {
303
+ Logger.error(`Error updating error ${errorCode}:`, error);
304
+ throw error;
305
+ }
306
+ }
307
+
308
+ /**
309
+ * Elimina un error
310
+ * @param {string} errorCode - Código del error
311
+ * @returns {Promise<boolean>} Éxito de la eliminación
312
+ */
313
+ static async deleteError(errorCode) {
314
+ try {
315
+ if (!ACCOUNT_ERRORS_TABLE) {
316
+ throw new Error("ACCOUNT_ERRORS_TABLE environment variable not set");
317
+ }
318
+
319
+ const dynamodb = new DynamoAWS.DocumentClient();
320
+
321
+ // Verificar que el error existe
322
+ const existingError = await this.getError(errorCode);
323
+ if (!existingError) {
324
+ throw new Error(`Error code ${errorCode} not found`);
325
+ }
326
+
327
+ const params = {
328
+ TableName: ACCOUNT_ERRORS_TABLE,
329
+ Key: { ErrorCode: errorCode }
330
+ };
331
+
332
+ await dynamodb.delete(params).promise();
333
+ return true;
334
+
335
+ } catch (error) {
336
+ Logger.error(`Error deleting error ${errorCode}:`, error);
337
+ throw error;
338
+ }
339
+ }
340
+
341
+ /**
342
+ * ✅ NUEVO: Inicializar errores básicos del sistema
343
+ * @returns {Promise<Array>} Resultados de la inicialización
344
+ */
345
+ static async initializeBasicErrors() {
346
+ const basicErrors = [
347
+ {
348
+ ErrorCode: 'ACCOUNT_001',
349
+ HttpStatus: 400,
350
+ Message: 'Request body is required',
351
+ Category: 'Validation',
352
+ Severity: 'Medium',
353
+ Description: 'The request body is missing or empty'
354
+ },
355
+ {
356
+ ErrorCode: 'ACCOUNT_026',
357
+ HttpStatus: 500,
358
+ Message: 'Internal server error occurred',
359
+ Category: 'System',
360
+ Severity: 'High',
361
+ Description: 'An unexpected system error occurred'
362
+ },
363
+ {
364
+ ErrorCode: 'SYSTEM_ERROR',
365
+ HttpStatus: 500,
366
+ Message: 'System error occurred',
367
+ Category: 'System',
368
+ Severity: 'Critical',
369
+ Description: 'Emergency fallback error'
370
+ }
371
+ ];
372
+
373
+ const results = [];
374
+ for (const errorData of basicErrors) {
375
+ try {
376
+ // Solo crear si no existe
377
+ const existing = await this.getError(errorData.ErrorCode);
378
+ if (!existing) {
379
+ await this.createError(errorData);
380
+ results.push({ errorCode: errorData.ErrorCode, status: 'created' });
381
+ } else {
382
+ results.push({ errorCode: errorData.ErrorCode, status: 'exists' });
383
+ }
384
+ } catch (error) {
385
+ results.push({
386
+ errorCode: errorData.ErrorCode,
387
+ status: 'failed',
388
+ error: error.message
389
+ });
390
+ }
391
+ }
392
+
393
+ return results;
394
+ }
395
+
396
+ /**
397
+ * Migra errores desde JSON a DynamoDB (para uso inicial)
398
+ * @param {Object} jsonErrors - Errores del JSON original
399
+ * @returns {Promise<Array>} Resultados de la migración
400
+ */
401
+ static async migrateFromJson(jsonErrors) {
402
+ try {
403
+ const results = [];
404
+ const errors = jsonErrors.accountErrorCodes.errors;
405
+
406
+ for (const [errorCode, errorInfo] of Object.entries(errors)) {
407
+ try {
408
+ const errorData = {
409
+ ErrorCode: errorCode,
410
+ HttpStatus: errorInfo.httpStatus,
411
+ Message: errorInfo.message,
412
+ Description: errorInfo.description || '',
413
+ Category: errorInfo.category,
414
+ Severity: errorInfo.severity,
415
+ PossibleCauses: errorInfo.possibleCauses || [],
416
+ Solutions: errorInfo.solutions || [],
417
+ RelatedFields: errorInfo.relatedFields || [],
418
+ RelatedTables: errorInfo.relatedTables || [],
419
+ RelatedEndpoints: errorInfo.relatedEndpoints || []
420
+ };
421
+
422
+ await this.createError(errorData);
423
+ results.push({ errorCode, status: 'success' });
424
+ } catch (error) {
425
+ results.push({ errorCode, status: 'failed', error: error.message });
426
+ }
427
+ }
428
+
429
+ return results;
430
+ } catch (error) {
431
+ Logger.error("Error migrating from JSON:", error);
432
+ throw error;
433
+ }
434
+ }
435
+ }
436
+
437
+ module.exports = AccountErrorManager;
@@ -0,0 +1,70 @@
1
+ const VtexApi = require("../../vtex/clients/VtexApi");
2
+ const Logger = require("../../common/utils/logger");
3
+
4
+ class AudiencePrice {
5
+ constructor(AccountName, Key, Token) {
6
+ this.AccountName = AccountName;
7
+ this.Key = Key;
8
+ this.Token = Token;
9
+ }
10
+
11
+ async getAudiencePriceById(audienceId) {
12
+ try {
13
+ const vtexApi = new VtexApi(this.AccountName, this.Key, this.Token);
14
+ const response = await vtexApi.fetch(`/price-table-mapper/pvt/mapping/${audienceId}`, {
15
+ method: "GET",
16
+ });
17
+
18
+ return response.data;
19
+ } catch (error) {
20
+ Logger.error("Error getting audience price: ", error);
21
+ return error;
22
+ }
23
+ }
24
+
25
+ async deleteAudiencePriceById(audienceId) {
26
+ try {
27
+ const vtexApi = new VtexApi(this.AccountName, this.Key, this.Token);
28
+ const response = await vtexApi.fetch(`/price-table-mapper/pvt/mapping/${audienceId}`, {
29
+ method: "DELETE",
30
+ });
31
+
32
+ return response.data;
33
+ } catch (error) {
34
+ Logger.error("Error deleting audience price: ", error);
35
+ return error;
36
+ }
37
+ }
38
+
39
+ async updateAudiencePriceById(audienceId, data) {
40
+ try {
41
+ const vtexApi = new VtexApi(this.AccountName, this.Key, this.Token);
42
+ await vtexApi.fetch(`/price-table-mapper/pvt/mapping/${audienceId}`, {
43
+ method: "PUT",
44
+ data,
45
+ });
46
+
47
+ return true;
48
+ } catch (error) {
49
+ Logger.error(error);
50
+ return false;
51
+ }
52
+ }
53
+
54
+ async createAudiencePrice(email) {
55
+ try {
56
+ const vtexApi = new VtexApi(this.AccountName, this.Key, this.Token);
57
+ const audienceResponse = await vtexApi.fetch(`/audience-manager/pvt/audience`, {
58
+ method: "POST",
59
+ data: { email: email },
60
+ });
61
+
62
+ return audienceResponse.data[0] ?? null;
63
+ } catch (error) {
64
+ Logger.error("Error creating audience: ", error);
65
+ return error;
66
+ }
67
+ }
68
+ }
69
+
70
+ module.exports = AudiencePrice;