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,648 @@
1
+ const VtexApi = require("../../vtex/clients/VtexApi");
2
+ const AWSServices = require("../../common/utils/aws-services");
3
+ const AccountData = require("../../entities/account");
4
+ const AudiencePrice = require("../../integrations/audience/Audience");
5
+ const Logger = require("../../common/utils/logger");
6
+
7
+ const SQS_CLIENT_DQL_QUEUE_URL = process.env.SQS_CLIENT_DQL_QUEUE_URL;
8
+ const SQS_CLIENT_QUEUE_URL = process.env.SQS_CLIENT_QUEUE_URL;
9
+ const MAX_ATTEMPS = process.env.MAX_ATTEMPS || 3;
10
+ const DATA_ENTITY_CLIENT_ACRONYM = process.env.DATA_ENTITY_CLIENT_ACRONYM;
11
+
12
+ /**
13
+ *
14
+ * @param {import("aws-lambda").APIGatewayProxyEvent} event
15
+ * @returns
16
+ */
17
+ const consumer = async (event) => {
18
+
19
+ for (const record of event.Records) {
20
+ const body = JSON.parse(record.body);
21
+ if (body) {
22
+ const {
23
+ an,
24
+ parentAccount,
25
+ key,
26
+ token,
27
+ email,
28
+ firstName,
29
+ lastName,
30
+ documentType,
31
+ document,
32
+ status,
33
+ homePhone,
34
+ phone,
35
+ phoneTwo,
36
+ customerClass,
37
+ customerClassTwo,
38
+ customerClassDist,
39
+ customerClassDistTwo,
40
+ customerClassDistThree,
41
+ approved,
42
+ address,
43
+ additional_information
44
+ } = JSON.parse(record.body);
45
+
46
+ let clientVtextBody = {
47
+ an: an,
48
+ approved: approved ?? true,
49
+ city: address?.city,
50
+ complement: address?.complement,
51
+ country: address?.country,
52
+ customerClass: customerClass,
53
+ customerClassTwo: customerClassTwo,
54
+ customerID: additional_information?.clientCode || '',
55
+ priceTables: additional_information?.priceTable,
56
+ diaEntrega: additional_information?.deliveryDay,
57
+ diaVisita: additional_information?.visitDay,
58
+ distribuitorName: additional_information?.distributorName ?? null,
59
+ distribuitorCode: additional_information?.distributorCode ?? null,
60
+ document: document,
61
+ documentType: documentType,
62
+ email: email,
63
+ firstName: firstName,
64
+ frecuencia: additional_information?.frequency,
65
+ lastName: lastName,
66
+ latitud: address?.geoCoordinates?.latitude,
67
+ longitud: address?.geoCoordinates?.longitude,
68
+ neighborhood: address?.neighborhood,
69
+ number: address?.number ?? null,
70
+ pdvname: additional_information?.pdvname,
71
+ pdv: additional_information?.pdv,
72
+ phone: phone || homePhone,
73
+ postalCode: address?.postalCode,
74
+ reference: address?.reference,
75
+ salesmanName: additional_information?.salesmanName ?? null,
76
+ state: address?.state,
77
+ status: status || "new",
78
+ street: address?.street,
79
+ supervisorName: additional_information?.supervisorName ?? null
80
+ };
81
+
82
+ if(additional_information?.sellerId){
83
+ clientVtextBody.sellerId= additional_information?.sellerId;
84
+ }
85
+ if(additional_information?.routeMirror){
86
+ clientVtextBody.routeMirror= additional_information?.routeMirror;
87
+ }
88
+ if(additional_information?.catalogueName){
89
+ clientVtextBody.catalogueName= additional_information?.catalogueName;
90
+ }
91
+ if(additional_information?.catalogueId){
92
+ clientVtextBody.catalogueId= additional_information?.catalogueId;
93
+ }
94
+ if(additional_information?.routeName){
95
+ clientVtextBody.routeName= additional_information?.routeName;
96
+ }
97
+ if(additional_information?.routeId){
98
+ clientVtextBody.routeId= additional_information?.routeId;
99
+ }
100
+ if(customerClassDist){
101
+ clientVtextBody.customerClassDist= customerClassDist;
102
+ }
103
+ if(customerClassDistTwo){
104
+ clientVtextBody.customerClassDistTwo= customerClassDistTwo;
105
+ }
106
+ if(customerClassDistThree){
107
+ clientVtextBody.customerClassDistThree= customerClassDistThree;
108
+ }
109
+ if(phoneTwo){
110
+ clientVtextBody.phoneTwo= phoneTwo;
111
+ }
112
+
113
+ //campos politicas financieras
114
+ if(additional_information?.withCredit || additional_information?.withCredit === false){
115
+ clientVtextBody.withCredit= additional_information?.withCredit;
116
+ }
117
+ if(additional_information?.paymentTerm){
118
+ clientVtextBody.paymentTerm= additional_information?.paymentTerm;
119
+ }
120
+ if(additional_information?.paymentMethodCode){
121
+ clientVtextBody.paymentMethodCode= additional_information?.paymentMethodCode;
122
+ }
123
+
124
+ const account = await AccountData.getAccountDataByAccountName(an);
125
+ Logger.setAccount(account);
126
+ Logger.debug("Message Event: ", event);
127
+ Logger.debug("Account Data: ", account);
128
+ // Se realiza proceso para ignorar campos que no prodran ser actualizados por la distribuidora
129
+ const ParametersRequiredForCustomerApproved= account?.ParametersRequiredForCustomerApproved ?? ['an'];
130
+ if(ParametersRequiredForCustomerApproved){
131
+ let clientAproved=true;
132
+ for (var i = 0; i < ParametersRequiredForCustomerApproved.length; i++) {
133
+ let keyClientApro= ParametersRequiredForCustomerApproved[i] ?? null;
134
+ if(keyClientApro && keyClientApro != ''){
135
+ if(!clientVtextBody[keyClientApro] || clientVtextBody[keyClientApro] == ''){
136
+ clientAproved= false;
137
+ }
138
+ }
139
+ }
140
+
141
+ if(clientAproved===false){
142
+ clientVtextBody.approved=false;
143
+ }
144
+ }
145
+ // Asignacion seller default y validacion geoenviadas
146
+ if(account && account?.ConditionsGeoCoordinates && account?.ConditionsGeoCoordinates?.default && account?.ConditionsGeoCoordinates?.default?.latitude && account?.ConditionsGeoCoordinates?.default?.longitude && account?.SetGeoCoordinatesGlobal === true){
147
+ const validSeller= await validSellerAccountVTEX({country: clientVtextBody.country, latitud: clientVtextBody.latitud, longitud: clientVtextBody.longitud, an:account?.AccountName, token: account?.Credentials?.token, key: account?.Credentials.key});
148
+ if(validSeller === false){
149
+ let options= account?.ConditionsGeoCoordinates ?? null;
150
+ if(options?.keyLatitudeSend && options?.keyLongitudeSend && options?.keyLatitudeSend != '' && options?.keyLongitudeSend != ''){
151
+ clientVtextBody[options.keyLatitudeSend]= clientVtextBody?.latitud;
152
+ clientVtextBody[options.keyLongitudeSend]= clientVtextBody?.longitud;
153
+ }
154
+
155
+ clientVtextBody.latitud= account?.ConditionsGeoCoordinates?.default?.latitude;
156
+ clientVtextBody.longitud= account?.ConditionsGeoCoordinates?.default?.longitude;
157
+
158
+ }
159
+ }
160
+
161
+ //Limpiar campos que ignorados a ditribuidora
162
+ if(account && account?.IgnoreParameters && account?.ParameterListIgnore && typeof account?.ParameterListIgnore == 'object' && account?.IgnoreParameters== true ){
163
+ for (let i = 0; i < account?.ParameterListIgnore.length; i++) {
164
+ if(account?.ParameterListIgnore[i] && account?.ParameterListIgnore[i] != ''){
165
+ delete clientVtextBody[account.ParameterListIgnore[i]];
166
+ }
167
+ }
168
+ }
169
+
170
+ //recorrer todo AdditionalFieldsClientMD para asignar valores a clientVtextBody
171
+ if(account && account?.AdditionalFieldsClientMD && typeof account?.AdditionalFieldsClientMD == 'object'){
172
+ for (let key in account?.AdditionalFieldsClientMD) {
173
+ if(account?.AdditionalFieldsClientMD[key] && account?.AdditionalFieldsClientMD[key] != ''){
174
+ try {
175
+ eval(`clientVtextBody.${key}= ${account?.AdditionalFieldsClientMD[key]}`)
176
+ } catch (error) {
177
+ Logger.error(error);
178
+ }
179
+ }
180
+ }
181
+ }
182
+
183
+ // Asignacion de valores por defecto de cliente siendo account?.valuesDefaultClient un objeto que contiene key y value, siendo key el nombre del campo y value el valor a asignar
184
+ // este key puede ya existir en el objeto clientVtextBody, si es asi se debe verificar si el valor es diferente de null para no sobreescribirlo
185
+ if(account && account?.ValuesDefaultClient && typeof account?.ValuesDefaultClient == 'object'){
186
+ for (let key in account?.ValuesDefaultClient) {
187
+ if(!clientVtextBody[key] || clientVtextBody[key] == ''){
188
+ clientVtextBody[key]= account?.ValuesDefaultClient[key];
189
+ }
190
+ }
191
+ }
192
+
193
+ // limpieza caracteres campos clientes
194
+ clientVtextBody= cleanerCharactersFields({data:clientVtextBody, regExpFieldsClients: account?.RegExpFieldsClients});
195
+
196
+ // Asignacion de geocoordenadas de manera dinamica por monaliza siguiendo parametros configurados dentro de la cuenta.
197
+ if(account && account?.SetGeoCoordinatesApp){
198
+ let setGeoCoordinatesApp= account.SetGeoCoordinatesApp ?? false;
199
+ if(setGeoCoordinatesApp===true){
200
+ let conditionsGeoCoordinates= account?.ConditionsGeoCoordinates;
201
+ if(conditionsGeoCoordinates){
202
+ clientVtextBody= await validGeoClientPerProperties({client:clientVtextBody, options: conditionsGeoCoordinates});
203
+ }
204
+ }
205
+ }
206
+
207
+ // asignacion de id de entidad de datos de manura dinamica y configurable
208
+ let idClient= account?.IndexClientRegister ? SetIdClient({indexes: account?.IndexClientRegister, dataClient: clientVtextBody}) : SetIdClient({dataClient: clientVtextBody});
209
+ if(idClient){
210
+ clientVtextBody.id= idClient;
211
+ try {
212
+ const vtexApi = new VtexApi(parentAccount, key, token);
213
+ let AcronymClientVtex= account?.AcronymClientVtex ?? DATA_ENTITY_CLIENT_ACRONYM;
214
+
215
+ const response = await vtexApi.fetch(`/dataentities/${AcronymClientVtex}/documents`, {
216
+ method: "PATCH",
217
+ data: clientVtextBody,
218
+ });
219
+ Logger.debug("Response: ", response);
220
+
221
+ // proceso para actualizar cliente dentro de entidad de datos seller vtex
222
+ if(account?.SavePriceTableCLWL===true){
223
+ const responseCL = await saveListPriceWhitelabel({
224
+ accountConfig: account,
225
+ data: {
226
+ email: `${account?.Startemail}+${idClient}@${account?.Domainemail}`,
227
+ priceTables: additional_information?.priceTable
228
+ }
229
+ });
230
+ Logger.debug("Response save priceTable CL whitelabel: ", responseCL);
231
+ }
232
+ // fin del proceso
233
+
234
+ // proceso para actualizar audience dentro de entidad de datos seller vtex
235
+ if(account?.SavePriceAudience===true){
236
+ const responsePriceAudienceCL = await saveListPriceAudience({
237
+ accountConfig: account,
238
+ email: `${account?.Startemail}+${idClient}@${account?.Domainemail}`,
239
+ priceTable: additional_information?.priceTable
240
+ });
241
+ Logger.debug("Response save Audience CL: ", responsePriceAudienceCL);
242
+ }
243
+ // fin del proceso
244
+
245
+ if (response.status >= 200 && response.status < 300) {
246
+ Logger.debug("Client updated successfully.");
247
+ } else {
248
+ const attemps = JSON.parse(record.body)?.attemps || 0;
249
+ Logger.error(
250
+ "Error updating client. Status: ",
251
+ response.status,
252
+ ". Message: ",
253
+ response?.data?.message,
254
+ " - Try: ",
255
+ attemps
256
+ );
257
+
258
+ if (attemps < MAX_ATTEMPS) {
259
+ await AWSServices.sendSQSMessage(
260
+ SQS_CLIENT_QUEUE_URL,
261
+ JSON.stringify({
262
+ key,
263
+ token,
264
+ attemps: attemps + 1,
265
+ ...clientVtextBody,
266
+ })
267
+ );
268
+ } else {
269
+ throw new Error("Max attemps reached.");
270
+ }
271
+ }
272
+ } catch (error) {
273
+ Logger.error("Register Client Consumer: ", error);
274
+ try {
275
+ let attempsSqs= record?.attempsSqs ?? 1;
276
+ if(attempsSqs < MAX_ATTEMPS){
277
+ attempsSqs++;
278
+ await AWSServices.sendSQSMessage(SQS_CLIENT_QUEUE_URL, {...record, attempsSqs});
279
+ }else{
280
+ await AWSServices.sendSQSMessage(
281
+ SQS_CLIENT_DQL_QUEUE_URL,
282
+ JSON.stringify({
283
+ body: record.body,
284
+ error: error?.message,
285
+ })
286
+ );
287
+ }
288
+ } catch (error) {
289
+ Logger.error("Sending message to DQL Queue: ", error);
290
+ }
291
+ }
292
+ }else{
293
+ Logger.error("Error per id client valid IndexClientRegister in settings!")
294
+ }
295
+
296
+ }
297
+ }
298
+ };
299
+
300
+
301
+ /**
302
+ * Guardar datos de clientes dentro del seller audience
303
+ * @param accountConfig datos de configuracion seller dentro de monalisa
304
+ * @param email email del cliente
305
+ * @param priceTable lista de precios a asociar
306
+ * @returns {Promise}
307
+ **/
308
+ const saveListPriceAudience = async ({ accountConfig = null, email = null, priceTable = null }) => {
309
+ if (!accountConfig || !email || !priceTable) {
310
+ return null;
311
+ }
312
+ return new Promise(async (res, err) => {
313
+ try {
314
+ const priceAudience = new AudiencePrice(accountConfig?.AccountName, accountConfig?.Credentials?.key, accountConfig?.Credentials?.token);
315
+ // 1. POST - Fetch audience (Obtén el audienceId usando el email del comprador)
316
+ const audienceResponse = await priceAudience.createAudiencePrice(email) ?? null;
317
+ if (!audienceResponse) {
318
+ return err("Error fetching audience or no audience found.");
319
+ }
320
+ const priceTableResponse = await priceAudience.updateAudiencePriceById(audienceResponse, [priceTable]);
321
+ if (!priceTableResponse) {
322
+ return err("Error setting price table mapping.");
323
+ }
324
+ // Devuelve el resultado exitoso
325
+ res({
326
+ audienceId: audienceResponse,
327
+ message: "Price table mapping successful.",
328
+ });
329
+ } catch (error) {
330
+ err(error);
331
+ }
332
+ });
333
+ };
334
+
335
+ /**
336
+ * Guardar datos de clientes dentro del seller white label
337
+ * @param accountConfig datos de configuracion seller dentro de monalisa
338
+ * @param data datos almacenar en CL wl VTEX
339
+ **/
340
+ const saveListPriceWhitelabel= async ({accountConfig=null, data=null})=>{
341
+ if(!accountConfig || !data){
342
+ return null;
343
+ }
344
+
345
+ return new Promise(async(res, err)=>{
346
+ const vtexApi = new VtexApi(accountConfig?.AccountName, accountConfig?.Credentials?.key, accountConfig?.Credentials?.token);
347
+
348
+ const response = await vtexApi.fetch(`/dataentities/CL/documents`, {
349
+ method: "PATCH",
350
+ data: data,
351
+ });
352
+
353
+ res(response);
354
+ });
355
+ };
356
+
357
+ /**
358
+ * Funcion para limpieza de caracteres especiales en campos
359
+ *@param data -- datos que del cliente
360
+ *@param regExpFieldsClients -- expresion regular de los valores permitidos por filed
361
+ **/
362
+ const cleanerCharactersFields= ({data=null, regExpFieldsClients= {"firstName": "^[a-zA-Z0-9 ñÑáéíóúÁÉÍÓÚ]+$"} })=>{
363
+ if(!data || !regExpFieldsClients){
364
+ return data;
365
+ }
366
+
367
+ let listReplace={
368
+ "Ã": "A",
369
+ "É": "E",
370
+ "Ü": "U",
371
+ "Ã'": "N",
372
+ "°": " ",
373
+ "´" : " ",
374
+ "'" : " ",
375
+ "," : " ",
376
+ "-": " ",
377
+ ".": "",
378
+ "º": "",
379
+ "ª": "",
380
+ "/": " ",
381
+ "°": "",
382
+ "+": " ",
383
+ "Ì": "I",
384
+ ":": "",
385
+ "?": "",
386
+ "@": "",
387
+ "¥": "",
388
+ "*": "",
389
+ "ä": "a",
390
+ "&": " ",
391
+ "#": " ",
392
+ "¦": "",
393
+ "Ü": "U",
394
+ "È": "E",
395
+ "À": "A",
396
+ "Ø": "O",
397
+ "{": "",
398
+ "}": "",
399
+ "ü": "u",
400
+ "©": "",
401
+ "`": "",
402
+ "±": "",
403
+ "¬": "",
404
+ "|": "",
405
+ ";": "",
406
+ "!": "",
407
+ "<": " ",
408
+ "³": "",
409
+ "": "",
410
+ "§": "",
411
+ "~": "",
412
+ "­": "",
413
+ "_": "",
414
+ "¡": "",
415
+ "„": "",
416
+ "%": "",
417
+ "Ð": "",
418
+ "à": "a",
419
+ "Ù": "U",
420
+ "Â": "A",
421
+ "": "",
422
+ "(": "",
423
+ ")": "",
424
+ "‰": "",
425
+ "š": "s",
426
+ "‘": "",
427
+ "[": "",
428
+ "]": "",
429
+ "€": "",
430
+ "Œ": ""
431
+ };
432
+
433
+ let registerClient= data;
434
+
435
+ // Validador de caracteres
436
+ if(regExpFieldsClients && typeof regExpFieldsClients === 'object'){
437
+ let listCharacter= [];
438
+ for (let strRegex in regExpFieldsClients) {
439
+ if(strRegex && regExpFieldsClients[strRegex] && regExpFieldsClients[strRegex] != '' && registerClient[strRegex] && registerClient[strRegex] != '' ){
440
+ if( validStringRegExp({string: registerClient[strRegex], regEx: regExpFieldsClients[strRegex]}) === false ){
441
+ for (let iStr = 0; iStr < registerClient[strRegex].length; iStr++) {
442
+ let strLetter= registerClient[strRegex].charAt(iStr);
443
+ if(strLetter != '' && validStringRegExp({string: strLetter, regEx: regExpFieldsClients[strRegex]}) === false){
444
+ if(!listCharacter.includes(strLetter) && strLetter != '' && strLetter != ' '){
445
+ listCharacter=[...listCharacter, strLetter];
446
+ }
447
+ }
448
+ }
449
+ registerClient[strRegex]= fixStringValues({string: registerClient[strRegex], listReplace:listReplace, charactersFound: listCharacter });
450
+ }
451
+ }
452
+ }
453
+
454
+ }
455
+
456
+ return registerClient;
457
+ };
458
+
459
+ /**
460
+ * Funcion validador de textos
461
+ **/
462
+ function validStringRegExp({string=null, regEx= "^[a-zA-Z ñÑáéíóúÁÉÍÓÚ]+$"}){
463
+ if(typeof string != 'string' || !string || !regEx){
464
+ return true;
465
+ }
466
+
467
+ if (string.match(regEx)!=null) {
468
+ return true;
469
+ } else {
470
+ return false;
471
+ }
472
+ }
473
+
474
+ /***
475
+ * Funcion de limpiieza string
476
+ **/
477
+ function fixStringValues({
478
+ string=null,
479
+ listReplace={
480
+ "%": ""
481
+ },
482
+ charactersFound= []
483
+ }) {
484
+ if(!string){
485
+ return "";
486
+ }
487
+
488
+ let listCharacterReplace={};
489
+
490
+ for (let i = 0; i < charactersFound.length; i++) {
491
+ let charac= charactersFound[i];
492
+ listCharacterReplace[`${charac}`]= listReplace.hasOwnProperty(charac) ? listReplace[charac] : "";
493
+
494
+ }
495
+
496
+ for (let caracter in listCharacterReplace) {
497
+ if (listCharacterReplace.hasOwnProperty(caracter) && caracter != '.' && caracter != '(' && caracter != ')' && caracter != '[' && caracter != ']' && caracter != '{' && caracter != '}' && caracter != '?' && caracter != '+' && caracter != '*' && caracter != '\\') {
498
+ string = string.replace(new RegExp(`${caracter}`, 'g'), listCharacterReplace[`${caracter}`]);
499
+ }else if (listCharacterReplace.hasOwnProperty(caracter) && caracter == '.'){
500
+ string = string.replace(/\./g, listCharacterReplace[`${caracter}`]);
501
+ }else if (listCharacterReplace.hasOwnProperty(caracter) && caracter == '('){
502
+ string = string.replace(/\(/g, listCharacterReplace[`${caracter}`]);
503
+ }else if (listCharacterReplace.hasOwnProperty(caracter) && caracter == ')'){
504
+ string = string.replace(/\)/g, listCharacterReplace[`${caracter}`]);
505
+ }else if (listCharacterReplace.hasOwnProperty(caracter) && caracter == '['){
506
+ string = string.replace(/\[/g, listCharacterReplace[`${caracter}`]);
507
+ }else if (listCharacterReplace.hasOwnProperty(caracter) && caracter == ']'){
508
+ string = string.replace(/\]/g, listCharacterReplace[`${caracter}`]);
509
+ }else if (listCharacterReplace.hasOwnProperty(caracter) && caracter == '{'){
510
+ string = string.replace(/\{/g, listCharacterReplace[`${caracter}`]);
511
+ }else if (listCharacterReplace.hasOwnProperty(caracter) && caracter == '}'){
512
+ string = string.replace(/\}/g, listCharacterReplace[`${caracter}`]);
513
+ }else if (listCharacterReplace.hasOwnProperty(caracter) && caracter == '?'){
514
+ string = string.replace(/\?/g, listCharacterReplace[`${caracter}`]);
515
+ }else if (listCharacterReplace.hasOwnProperty(caracter) && caracter == '+'){
516
+ string = string.replace(/\+/g, listCharacterReplace[`${caracter}`]);
517
+ }else if (listCharacterReplace.hasOwnProperty(caracter) && caracter == '*'){
518
+ string = string.replace(/\*/g, listCharacterReplace[`${caracter}`]);
519
+ }else if (listCharacterReplace.hasOwnProperty(caracter) && caracter == '\\'){
520
+ string = string.replace(/\\/g, '');
521
+ }
522
+ }
523
+
524
+ return string;
525
+ }
526
+
527
+ /**
528
+ * Funcion para validar geo coordenadas seller
529
+ * @param country
530
+ * @param latitud
531
+ * @param longitud
532
+ * @param an
533
+ * @param token
534
+ * @param key
535
+ **/
536
+ const validSellerAccountVTEX= async ({
537
+ country= null,
538
+ latitud= null,
539
+ longitud= null,
540
+ an= null,
541
+ token= null,
542
+ key= null
543
+ })=>{
544
+ if(!country || !latitud || !longitud || !an || !token || !key){
545
+ return false;
546
+ }
547
+
548
+ return new Promise(async (res, err)=>{
549
+
550
+ const vtexApiV = new VtexApi(an, key, token);
551
+ const response = await vtexApiV.fetch(`/checkout/pub/regions?country=${country}&geoCoordinates=${longitud};${latitud}`, {
552
+ method: "GET"
553
+ });
554
+
555
+ if(response?.status === 200 && response?.data && response?.data?.length > 0){
556
+ let exitSellerVtex= false;
557
+ for (let i = 0; i < response?.data?.length; i++) {
558
+ let lisSellerApi= response?.data[i]?.sellers ?? [];
559
+ for (let j = 0; j < lisSellerApi?.length; j++) {
560
+ if(lisSellerApi[j]?.id == an){
561
+ exitSellerVtex= true;
562
+ }
563
+ }
564
+ }
565
+
566
+ if(exitSellerVtex === true){
567
+ res(true);
568
+ }else{
569
+ res(false);
570
+ }
571
+ }else{
572
+ res(false);
573
+ }
574
+ });
575
+ };
576
+
577
+ /**
578
+ * Funcion para realizar la asignacion de id de registro de cliente
579
+ **/
580
+ const SetIdClient= ({indexes= ['an', 'document'], dataClient=null})=>{
581
+ if(indexes && dataClient && typeof indexes === 'object'){
582
+ let idT= null;
583
+ let listValues=[];
584
+ for (let i = 0; i < indexes.length; i++) {
585
+ let indexCl=indexes[i];
586
+ if(indexCl && dataClient[indexCl]){
587
+ listValues= [...listValues, dataClient[indexCl]];
588
+ }
589
+ }
590
+
591
+ return listValues.length > 0 ? listValues.join('') : null;
592
+ }else{
593
+ return null;
594
+ }
595
+ }
596
+
597
+ /**
598
+ * Funcion que realiza asignacion de geocoordenadas desde el lado de monaliza con propiedades del cliente
599
+ * @param client {object} .son las propiedades que se guardan para un cliente
600
+ * @param options {object} .Son los parametros de configuracion para las condiciones para asignacion de geocoordenadas
601
+ **/
602
+ const validGeoClientPerProperties= async ({client={}, options=null})=>{
603
+ if(client && options){
604
+ let latitude= options?.default?.latitude,
605
+ longitude= options?.default?.longitude;
606
+
607
+ if(options?.keyLatitudeSend && options?.keyLongitudeSend && options?.keyLatitudeSend != '' && options?.keyLongitudeSend != ''){
608
+ client[options.keyLatitudeSend]= client?.latitud;
609
+ client[options.keyLongitudeSend]= client?.longitud;
610
+ }
611
+
612
+ if(options?.listOptions){
613
+ for (let i = 0; i < options?.listOptions.length; i++) {
614
+ let conditions= options?.listOptions[i]?.conditioins;
615
+ if(conditions){
616
+ let totalConditions= Object.keys(conditions).length;
617
+ let countConditions= 0;
618
+ for (let key in conditions) {
619
+ let keyS= key ?? null;
620
+ let valueS= conditions[keyS] ?? null;
621
+ if(keyS && valueS){
622
+ if(client[keyS] && client[keyS] == valueS){
623
+ countConditions++;
624
+ }
625
+ }
626
+ }
627
+ if(totalConditions==countConditions){
628
+ latitude= options?.listOptions[i]?.geoCoordinates?.latitude;
629
+ longitude= options?.listOptions[i]?.geoCoordinates?.longitude;
630
+ }
631
+ }
632
+ }
633
+ }
634
+
635
+ client.latitud= latitude;
636
+ client.longitud= longitude;
637
+
638
+ return client;
639
+ }else if(client){
640
+ return client;
641
+ }else{
642
+ return null;
643
+ }
644
+ }
645
+
646
+ module.exports = {
647
+ consumer,
648
+ };