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,377 @@
1
+ const axios = require('axios');
2
+ const VtexHelper = require('../../functions/vtex/vtex-helpers');
3
+ const Logger = require("../../common/utils/logger");
4
+
5
+ /**
6
+ * Financial Policy API Class for handling client financial operations
7
+ * @class
8
+ */
9
+ class FinancialPolicyApi {
10
+ /**
11
+ * Constructor for Financial Policy API
12
+ * @param {string} AccountName - VTEX account name
13
+ * @param {string} Key - Authentication key
14
+ * @param {string} Token - Authentication token
15
+ * @param {string} AcronymClientVtex - Client acronym in VTEX
16
+ * @param {Object} FinancialPolicyConfig - Configuration for financial policy
17
+ */
18
+ constructor(AccountName, Key, Token, AcronymClientVtex, FinancialPolicyConfig) {
19
+ this.AccountName = AccountName;
20
+ this.Key = Key;
21
+ this.Token = Token;
22
+ this.AcronymClientVtex = AcronymClientVtex;
23
+ this.config = FinancialPolicyConfig;
24
+ }
25
+
26
+ setConfig(config) {
27
+ this.config = config;
28
+ }
29
+
30
+ /**
31
+ * Authenticate with external service
32
+ * @returns {Promise<string|null>} Authentication token or null
33
+ * @throws {Error} If authentication fails
34
+ */
35
+ async authenticate() {
36
+ try {
37
+ const authConfig = this.config?.configService?.serviceAuth;
38
+ if (!authConfig?.url) return null;
39
+
40
+ const { url, method = 'post', headers = {}, body } = authConfig;
41
+ const response = await axios({
42
+ url,
43
+ method: method.toLowerCase(),
44
+ headers,
45
+ data: body
46
+ });
47
+
48
+ const tokenPath = authConfig.tokenPath || 'Token';
49
+ const token = this.getValueByPath(response.data, tokenPath);
50
+
51
+ if (!token) throw new Error(`Authentication failed - token not found at path: ${tokenPath}`);
52
+ return token;
53
+ } catch (error) {
54
+ Logger.error("Authentication error:", error);
55
+ throw error;
56
+ }
57
+ }
58
+
59
+ getValueByPath(obj, path) {
60
+ return path.split('.').reduce((current, key) => current?.[key], obj);
61
+ }
62
+
63
+ applyTransform(value, transformType) {
64
+ if (!transformType) return value;
65
+
66
+ try {
67
+ const customTransform = this.config?.transforms?.[transformType];
68
+ if (customTransform) {
69
+ return new Function('value', `return ${customTransform}`)(value);
70
+ }
71
+
72
+ // Usa VtexHelper para transformaciones base
73
+ return VtexHelper.applyTransform(value, transformType);
74
+ } catch (error) {
75
+ Logger.error(`Transform error (${transformType}):`, error);
76
+ return value;
77
+ }
78
+ }
79
+
80
+ async getBalanceByClient(params) {
81
+ try {
82
+ const token = await this.authenticate();
83
+ const { url, method = 'post', headers = {}, headerMapping = {}, parameterMapping = {} } = this.config.configService;
84
+
85
+ if (!url) throw new Error("Invalid service configuration - URL required");
86
+
87
+ const processedHeaders = {
88
+ 'Content-Type': 'application/json',
89
+ ...headers,
90
+ ...this.processHeaderMapping(headerMapping, params, token)
91
+ };
92
+ const data = this.processParameterMapping(parameterMapping, params, token);
93
+ const response = await axios({
94
+ method: method.toLowerCase(),
95
+ url,
96
+ headers: processedHeaders,
97
+ data
98
+ });
99
+
100
+ return response.data;
101
+ } catch (error) {
102
+ Logger.error("Balance error:", error);
103
+ throw error;
104
+ }
105
+ }
106
+
107
+ processHeaderMapping(headerMapping, params, token) {
108
+ return Object.entries(headerMapping).reduce((acc, [key, path]) => {
109
+ if (key === 'Authorization' && token) {
110
+ acc[key] = `Bearer ${token}`;
111
+ } else {
112
+ const value = this.getValueByPath(params, path);
113
+ if (value !== undefined) acc[key] = value;
114
+ }
115
+ return acc;
116
+ }, {});
117
+ }
118
+
119
+ processParameterMapping(parameterMapping, params, token) {
120
+ const mappedData = { Token: token };
121
+ for (const [key, mappingPath] of Object.entries(parameterMapping)) {
122
+ if (key === 'Token') continue;
123
+ // Obtener el path del extractor correspondiente
124
+ const extractorPath = this.config.parameterExtractors[mappingPath];
125
+ if (!extractorPath) {
126
+ continue;
127
+ }
128
+ const value = this.getValueByPath(params, extractorPath);
129
+
130
+ if (value !== undefined) {
131
+ mappedData[key] = value;
132
+ }
133
+ }
134
+ return mappedData;
135
+ }
136
+
137
+ /**
138
+ * Get client balance information
139
+ * @param {Object} params - Parameters for balance retrieval
140
+ * @param {Object} params.orderForm - Order form details
141
+ * @param {number|null} params.creditDaysParam - Credit days parameter
142
+ * @param {Object} params.responseMasterDataCT - Master data response
143
+ * @returns {Promise<Object>} Balance response object
144
+ * @example
145
+ * // Expected input
146
+ * {
147
+ * orderForm: { value: 10000 },
148
+ * creditDaysParam: 30,
149
+ * responseMasterDataCT: {}
150
+ * }
151
+ *
152
+ * // Expected output
153
+ * {
154
+ * approved: boolean,
155
+ * customerWithCredit: boolean,
156
+ * paymentTerm: number,
157
+ * creditDays: number
158
+ * }
159
+ */
160
+ async getCustomerBalance(orderForm, creditDaysParam, responseMasterDataCT) {
161
+ try {
162
+ const params = { orderForm, creditDaysParam, responseMasterDataCT };
163
+ const requiredParams = this.validateRequiredParams(params);
164
+ if (!requiredParams.valid) {
165
+ Logger.error('Missing required params:', requiredParams.missing);
166
+ return this.getDefaultResponse(false);
167
+ }
168
+
169
+ const balanceData = await this.getBalanceByClient(params);
170
+ if (this.hasError(balanceData)) return this.getDefaultResponse(false);
171
+
172
+ const extractedData = this.extractResponseData(balanceData);
173
+ const isValid = this.validateExtractedFields(extractedData);
174
+ if (!isValid) return this.getDefaultResponse(false);
175
+
176
+ const isApproved = this.validateResponse(extractedData, params);
177
+ const formattedResponse = this.formatResponse(extractedData, isApproved, creditDaysParam);
178
+ return formattedResponse;
179
+ } catch (error) {
180
+ Logger.error('Customer balance error:', error);
181
+ return this.getDefaultResponse(false);
182
+ }
183
+ }
184
+
185
+ validateRequiredParams(params) {
186
+ const required = this.config.requiredParameters || [];
187
+ const missing = required.filter(param =>
188
+ !this.getValueByPath(params, this.config.parameterExtractors[param])
189
+ );
190
+ return { valid: missing.length === 0, missing };
191
+ }
192
+
193
+ hasError(response) {
194
+ return this.config.errorPath ?
195
+ Boolean(this.getValueByPath(response, this.config.errorPath)) :
196
+ false;
197
+ }
198
+
199
+ extractResponseData(response) {
200
+ const { responsePaths, fieldTransforms = {} } = this.config;
201
+ if (!response || !responsePaths) return this.getDefaultResponse(false);
202
+
203
+ try {
204
+ return Object.entries(responsePaths).reduce((acc, [field, path]) => {
205
+ const rawValue = this.getValueByPath(response, path);
206
+ const transform = fieldTransforms[field];
207
+ acc[field] = rawValue !== undefined ?
208
+ (transform ? this.applyTransform(rawValue, transform) : rawValue) :
209
+ this.getDefaultValueForField(field);
210
+ return acc;
211
+ }, {});
212
+ } catch (error) {
213
+ Logger.error('Data extraction error:', error);
214
+ return this.getDefaultResponse(false);
215
+ }
216
+ }
217
+
218
+ validateExtractedFields(data) {
219
+ if (!data || typeof data !== 'object') return false;
220
+ const { fieldValidations = {} } = this.config;
221
+
222
+ return Object.entries(fieldValidations).every(([field, validation]) => {
223
+ if (!(field in data)) return true;
224
+ try {
225
+ const validationFunction = new Function('value', `return ${validation}`);
226
+ return validationFunction(data[field]);
227
+ } catch (error) {
228
+ Logger.error(`Validation error for ${field}:`, error);
229
+ return false;
230
+ }
231
+ });
232
+ }
233
+
234
+ validateResponse(data, context) {
235
+ const { validationTransforms = {} } = this.config;
236
+ const format = context.creditDaysParam === null ? 'get' : 'assign';
237
+ const validationData = this.config.responseFormats[format].validationData;
238
+
239
+ if (!validationData) return false;
240
+
241
+ try {
242
+ const validationContext = this.prepareValidationContext(data, context, validationTransforms);
243
+ const validationFunction = new Function(
244
+ ...Object.keys(validationContext),
245
+ `return ${validationData}`
246
+ );
247
+ return validationFunction(...Object.values(validationContext)) ?? false;
248
+ } catch (error) {
249
+ Logger.error('Validation error:', error);
250
+ return false;
251
+ }
252
+ }
253
+
254
+ prepareValidationContext(data, context, transforms) {
255
+ const transformedData = {};
256
+ const baseTransforms = {
257
+ toString: value => String(value || ''),
258
+ toNumber: value => Number(value || 0),
259
+ toBoolean: value => Boolean(value),
260
+ toOrderValue: value => Number(value || 0) / 100
261
+ };
262
+
263
+ // Transforma datos de respuesta API
264
+ Object.entries(data).forEach(([key, value]) => {
265
+ const transform = transforms[key];
266
+ transformedData[key] = transform ?
267
+ baseTransforms[transform](value) :
268
+ value;
269
+ });
270
+
271
+ // Extrae y transforma orderValue
272
+ const orderValue = baseTransforms.toOrderValue(context.orderForm?.value);
273
+
274
+ return {
275
+ ...transformedData,
276
+ orderValue,
277
+ creditDaysParam: context.creditDaysParam !== null ?
278
+ baseTransforms.toNumber(context.creditDaysParam) :
279
+ null
280
+ };
281
+ }
282
+
283
+ transformFields(data, transforms) {
284
+ return Object.entries(data).reduce((acc, [key, value]) => {
285
+ acc[key] = transforms[key] ? this.applyTransform(value, transforms[key]) : value;
286
+ return acc;
287
+ }, {});
288
+ }
289
+
290
+ getDefaultValueForField(field) {
291
+ const defaultValue = this.config?.jsonDefault?.fields?.[field];
292
+ if (defaultValue === undefined) return null;
293
+
294
+ // Manejo especial para booleanos y números
295
+ if (field === 'approved' || field === 'withCredit') return Boolean(defaultValue === 'true');
296
+ if (field === 'paymentTerm' || field === 'creditDays' || field === 'maximumCreditAmount') {
297
+ return Number(defaultValue) || 0;
298
+ }
299
+
300
+ return defaultValue;
301
+ }
302
+
303
+ getDefaultResponse(approved = false) {
304
+ const defaultFields = this.config?.jsonDefault?.fields || {};
305
+
306
+ return Object.entries(defaultFields).reduce((response, [field, defaultValue]) => {
307
+ response[field] = field === 'approved' || field === 'withCredit' ?
308
+ Boolean(approved) :
309
+ this.getDefaultValueForField(field);
310
+ return response;
311
+ }, {});
312
+ }
313
+
314
+ formatResponse(data, isApproved, creditDaysParam) {
315
+ const format = creditDaysParam === null ?
316
+ this.config.responseFormats.get :
317
+ this.config.responseFormats.assign;
318
+
319
+ return Object.entries(format.mapping).reduce((acc, [key, config]) => {
320
+ if (creditDaysParam === null && key === 'withCredit') {
321
+ // Solo retorna customerWithCredit como true si pasa todas las validaciones
322
+ acc['customerWithCredit'] = isApproved && this.applyTransform(data[config.field], config.type);
323
+ } else {
324
+ const value = config.field === 'approved' ? isApproved : data[config.field];
325
+ acc[key] = this.applyTransform(value, config.type);
326
+ }
327
+ return acc;
328
+ }, {});
329
+ }
330
+
331
+ // VTEX Helper Methods
332
+ /**
333
+ * Retrieve order form by ID from VTEX
334
+ * @param {string} orderFormId - Unique identifier for order form
335
+ * @returns {Promise<Object>} Order form details
336
+ */
337
+ async getOrderFormById(orderFormId) {
338
+ return VtexHelper.getOrderFormById(orderFormId, this.AccountName, this.Key, this.Token);
339
+ }
340
+
341
+ /**
342
+ * Retrieve client information by email
343
+ * @param {string} email - Client email address
344
+ * @returns {Promise<Object>} Client details
345
+ */
346
+ async getClientById(email) {
347
+ return VtexHelper.getClientById(email, this.AccountName, this.Key, this.Token, this.AcronymClientVtex);
348
+ }
349
+
350
+ /**
351
+ * Delete custom data from order form
352
+ * @param {string} orderFormId - Order form identifier
353
+ * @param {Object} customData - Custom data to delete
354
+ * @returns {Promise<Object>} Deletion result
355
+ */
356
+ async deleteCustomData(orderFormId, customData) {
357
+ return VtexHelper.deleteCustomData(
358
+ orderFormId, this.AccountName, this.Key, this.Token,
359
+ this.config?.configVtex, this.config?.attachmentCredit, customData
360
+ );
361
+ }
362
+
363
+ /**
364
+ * Update order form custom data
365
+ * @param {string} orderFormId - Order form identifier
366
+ * @param {string} idConfigVtex - VTEX configuration ID
367
+ * @param {Object} customData - Custom data to update
368
+ * @returns {Promise<Object>} Update result
369
+ */
370
+ async updateOrderFormCustomData(orderFormId, idConfigVtex, customData) {
371
+ return VtexHelper.updateOrderFormCustomData(
372
+ orderFormId, this.AccountName, this.Key, this.Token, idConfigVtex, customData, this.config.attachmentCredit
373
+ );
374
+ }
375
+ }
376
+
377
+ module.exports = FinancialPolicyApi;
File without changes