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,70 @@
1
+ const axios = require("axios");
2
+ const MDLZ_BASE_URL = process.env.MDLZ_BASE_URL;
3
+ const Logger = require("../../common/utils/logger");
4
+
5
+ class MdlzApi {
6
+ constructor(authorization, grantType, scope) {
7
+ if (!authorization || !grantType || !scope) {
8
+ Logger.error("Invalid MDLZ API Credentials");
9
+ throw new Error("Invalid MDLZ API Credentials");
10
+ }
11
+ this.authorization = authorization;
12
+ this.grantType = grantType;
13
+ this.scope = scope;
14
+ }
15
+
16
+ get baseURL() {
17
+ return MDLZ_BASE_URL;
18
+ }
19
+
20
+ /**
21
+ * Excute a request to MDLZ API
22
+ * @param {string} url
23
+ * @param {import("axios").AxiosRequestConfig} options
24
+ * @returns {Promise<import("axios").AxiosResponse>}
25
+ */
26
+ fetch(url, options) {
27
+ const params = {
28
+ url: `${this.baseURL}${url}`,
29
+ ...options,
30
+ headers: {
31
+ "Content-Type": "application/json",
32
+ Authorization: this.authorization,
33
+ grant_type: this.grantType,
34
+ scope: this.scope,
35
+ ...options.headers,
36
+ },
37
+ };
38
+ return axios.request(params).catch((error) => {
39
+ // error is handled in catch block
40
+ if (error.response) {
41
+ // status code out of the range of 2xx
42
+ Logger.error("Data MDLZ response: ", error.response.data);
43
+ Logger.error("Status MDLZ response : ", error.response.status);
44
+ const errorResponse = {
45
+ status: error.response.status,
46
+ data: error.response.data,
47
+ };
48
+ return errorResponse;
49
+ } else if (error.request) {
50
+ // The request was made but no response was received
51
+ Logger.error("Error MDLZ no response: ", error.request);
52
+ const errorResponse = {
53
+ status: 500,
54
+ data: error.request,
55
+ };
56
+ return errorResponse;
57
+ } else {
58
+ // Error on setting up the request
59
+ Logger.error("Error MDLZ api response: ", error.message);
60
+ const errorResponse = {
61
+ status: 500,
62
+ data: error.message,
63
+ };
64
+ return errorResponse;
65
+ }
66
+ });
67
+ }
68
+ }
69
+
70
+ module.exports = MdlzApi;
@@ -0,0 +1,51 @@
1
+ const axios = require("axios");
2
+ const Logger = require("../../common/utils/logger");
3
+
4
+ /**
5
+ * Class providers api.
6
+ **/
7
+
8
+ class ProviderApi {
9
+
10
+ /**
11
+ * Method that processes the fetch request to the supplier once the necessary data has been assembled.
12
+ * @param url -- url to request
13
+ * @param options -- object that contains the parameters necessary to perform the query, path, query or body.
14
+ **/
15
+
16
+ fetch(url, options = {}){
17
+ if (typeof options.body === 'string') {
18
+ try {
19
+ options.body = JSON.parse(options.body);
20
+ } catch (error) {
21
+ Logger.error('Error parsing body:', error.message);
22
+ return Promise.reject(new Error('Invalid JSON body format'));
23
+ }
24
+ }
25
+
26
+ return axios
27
+ .request({
28
+ url: url,
29
+ method: options.method || 'POST',
30
+ headers: {
31
+ 'Content-Type': 'application/json',
32
+ ...options.headers,
33
+ },
34
+ data: options.body
35
+ })
36
+ .then(response => {
37
+ Logger.debug('Response data:', response.data);
38
+ return response;
39
+ })
40
+ .catch(error => {
41
+ if (error.response) {
42
+ Logger.error('Error response:', error.response.data);
43
+ } else {
44
+ Logger.error('Error', error.message);
45
+ }
46
+ throw error;
47
+ });
48
+ }
49
+ }
50
+
51
+ module.exports = ProviderApi
@@ -0,0 +1,511 @@
1
+ const axios = require("axios");
2
+ const VTEX_BASE_URL = process.env.VTEX_BASE_URL;
3
+ const Logger = require("../../common/utils/logger");
4
+
5
+ class VtexApi {
6
+ constructor(accountName, authKey, authToken, environment) {
7
+ if (!accountName || !authKey || !authToken) {
8
+ throw new Error("Invalid VTEX API Credentials");
9
+ }
10
+ this.accountName = accountName;
11
+ this.authKey = authKey;
12
+ this.authToken = authToken;
13
+ this.environment = environment || "vtexcommercestable";
14
+ }
15
+
16
+ get baseURL() {
17
+ return VTEX_BASE_URL.replace("{accountName}", this.accountName)
18
+ .replace("{environment}", this.environment);
19
+ }
20
+
21
+ /**
22
+ * Execute a request to VTEX API
23
+ * @param {string} url
24
+ * @param {import("axios").AxiosRequestConfig} options
25
+ * @returns {Promise<import("axios").AxiosResponse>}
26
+ */
27
+ fetch(url, options = {}, printLog = true) {
28
+ const { headers = {}, ...optionsRemain } = options;
29
+ const data = {
30
+ url: `${this.baseURL}${url}`,
31
+ ...optionsRemain,
32
+ headers: {
33
+ "X-VTEX-API-AppKey": this.authKey,
34
+ "X-VTEX-API-AppToken": this.authToken,
35
+ "Content-Type": "application/json",
36
+ ...headers,
37
+ },
38
+ };
39
+ return axios
40
+ .request(data)
41
+ .catch(error => {
42
+ if (printLog) {
43
+ // error is handled in catch block
44
+ if (error.response) {
45
+ // status code out of the range of 2xx
46
+ Logger.error("Data :", error.response.data);
47
+ Logger.error("Status :" + error.response.status);
48
+ } else if (error.request) {
49
+ // The request was made but no response was received
50
+ Logger.error(error.request);
51
+ } else {
52
+ // Error on setting up the request
53
+ Logger.error("Error", error.message);
54
+ }
55
+ }
56
+ if (error?.response?.status >= 400) {
57
+ throw error;
58
+ } else {
59
+ return null;
60
+ }
61
+ });
62
+ }
63
+
64
+ fetchPub(url, options, data) {
65
+ return axios
66
+ .request({
67
+ url: `${this.baseURL}${url}`,
68
+ ...options,
69
+ data,
70
+ headers: {
71
+ "Content-Type": "application/json",
72
+ ...options.headers,
73
+ },
74
+ })
75
+ .catch((error) => {
76
+ // error is handled in catch block
77
+ if (error.response) {
78
+ // status code out of the range of 2xx
79
+ Logger.error("Data :", error.response.data);
80
+ Logger.error("Status :" + error.response.status);
81
+ } else if (error.request) {
82
+ // The request was made but no response was received
83
+ Logger.error(error.request);
84
+ } else {
85
+ // Error on setting up the request
86
+ Logger.error("Error", error.message);
87
+ }
88
+ throw error;
89
+ });
90
+ }
91
+
92
+ fetchOrderMail(aliasMail) {
93
+ return axios.request({
94
+ url: `http://conversationtracker.vtex.com.br/api/pvt/emailMapping?alias=${aliasMail}&an=${this.accountName}`,
95
+ headers: {
96
+ "Content-Type": "application/json",
97
+ "X-VTEX-API-AppKey": this.authKey,
98
+ "X-VTEX-API-AppToken": this.authToken,
99
+ },
100
+ });
101
+ }
102
+
103
+ /**
104
+ * Execute a request to VTEX API
105
+ * @param {string} url
106
+ * @param {import("axios").AxiosRequestConfig} options
107
+ * @returns {Promise<import("axios").AxiosResponse>}
108
+ */
109
+ fetchApiURL(url, options) {
110
+ return axios.request({
111
+ url: `https://api.vtex.com/${this.accountName}${url}`,
112
+ ...options,
113
+ headers: {
114
+ "Content-Type": "application/json",
115
+ ...options.headers,
116
+ "X-VTEX-API-AppKey": this.authKey,
117
+ "X-VTEX-API-AppToken": this.authToken,
118
+ },
119
+ });
120
+ }
121
+ /**
122
+ * Metdo para obtener token de autenticacion
123
+ * @returns
124
+ */
125
+ async getVtexIdclientAutCookie(){
126
+ const _this= this;
127
+ return new Promise(async (resp,err)=>{
128
+ let data = JSON.stringify({
129
+ "appkey": _this.authKey,
130
+ "apptoken": _this.authToken
131
+ });
132
+
133
+ let config = {
134
+ method: 'post',
135
+ maxBodyLength: Infinity,
136
+ url: `https://api.vtexcommercestable.com.br/api/vtexid/apptoken/login?an=${_this.accountName}`,
137
+ headers: {
138
+ 'X-VTEX-API-AppKey': _this.authKey,
139
+ 'X-VTEX-API-AppToken': _this.authToken,
140
+ 'Content-Type': 'application/json'
141
+ },
142
+ data : data
143
+ };
144
+
145
+ axios.request(config)
146
+ .then((response) => {
147
+ resp((response?.data?.token ?? null));
148
+ })
149
+ .catch((error) => {
150
+ Logger.error(error);
151
+ resp(null);
152
+ });
153
+ });
154
+ }
155
+
156
+ convertDefaultProductSearch(dataP=null, isActive=true){
157
+ dataP.Skus= dataP?.Skus?.filter(it=> it?.IsActive===isActive) ?? [];
158
+ let dataTransform= {
159
+ "productId": dataP?.ProductId ? String(dataP?.ProductId) : dataP?.ProductId,
160
+ "productName": dataP?.Name,
161
+ "noVisible": true,
162
+ "brand": dataP?.BrandName,
163
+ "brandId": dataP?.BrandId,
164
+ "brandImageUrl": null,
165
+ "linkText": dataP?.LinkId,
166
+ "productReference": dataP?.RefId,
167
+ "productReferenceCode": dataP?.RefId,
168
+ "categoryId": dataP?.CategoryId ? String(dataP?.CategoryId) : dataP?.CategoryId,
169
+ "productTitle": dataP?.Title,
170
+ "metaTagDescription": dataP?.MetaTagDescription,
171
+ "releaseDate": dataP?.ReleaseDate,
172
+ "clusterHighlights": {},
173
+ "productClusters": {},
174
+ "searchableClusters": {},
175
+ "categories": [
176
+ `/${dataP?.CategoryName}/`
177
+ ],
178
+ "categoriesIds": [
179
+ `/${String(dataP?.CategoryId)}/`
180
+ ],
181
+ "link": null,
182
+ "allSpecifications": dataP?.Specifications?.map(it=>(it?.MainFieldName)),
183
+ "allSpecificationsGroups": [],
184
+ "description": dataP?.Description,
185
+ "items": dataP?.Skus?.map(it=>({
186
+ "itemId": it?.Id ? String(it?.Id) : it?.Id,
187
+ "name": it?.Name,
188
+ "nameComplete": `${dataP?.Name} ${it?.Name}`,
189
+ "complementName": dataP?.Name,
190
+ "ean": it?.Eans?.length > 0 ? it?.Eans[0] : "",
191
+ "referenceId": [
192
+ {
193
+ "Key": "RefId",
194
+ "Value": it?.RefId
195
+ }
196
+ ],
197
+ "measurementUnit": it?.MeasurementUnit,
198
+ "unitMultiplier": it?.UnitMultiplier,
199
+ "modalType": it?.ModalType,
200
+ "isKit": it?.IsKit,
201
+ "kitItems": it?.Components?.map(itK =>({
202
+ "itemId": itK?.SkuId ? String(itK?.SkuId) : itK?.SkuId,
203
+ "amount": itK?.Quantity
204
+ })),
205
+ "images": it?.Images?.map(itI=>({
206
+ "imageId": itI?.Id,
207
+ "imageLabel": itI?.Label,
208
+ "imageTag": itI?.Tag,
209
+ "imageUrl": itI?.Url,
210
+ "imageText": itI?.ArchiveText,
211
+ "imageLastModified": null
212
+ })),
213
+ "sellers": [],
214
+ "Videos": it?.Videos ?? [],
215
+ "estimatedDateArrival": it?.EstimatedDateArrival
216
+ }))
217
+ };
218
+
219
+ for(let i = 0; i < dataP?.Specifications?.length; i++){
220
+ let spec= dataP?.Specifications[i];
221
+ let keyS=spec.MainFieldName, valS=spec.ProductFieldValueText;
222
+ dataTransform[keyS]= [valS];
223
+ }
224
+
225
+ return dataTransform;
226
+ }
227
+
228
+ getProductsUnique(data=[]){
229
+ return data.filter((objeto, index) => {
230
+ return data.findIndex(obj => JSON.stringify(obj) === JSON.stringify(objeto)) === index;
231
+ });
232
+ };
233
+
234
+ async getProductsVisiblesDetails(data=[], authPrev, isActive=true){
235
+ const _this= this;
236
+ const dataUnique= _this.getProductsUnique(data);
237
+
238
+ if(dataUnique?.length === 0){
239
+ return [];
240
+ }
241
+
242
+ return new Promise(async(resp, err)=>{
243
+ const urls = dataUnique?.map(it=>(`https://admin-catalog-facelift.vercel.app/api/proxy/catalog/pvt/admin/form/product/${it?.ProductId}?an=${_this.accountName}`));
244
+
245
+ axios.all(urls.map(url => axios.request({
246
+ method: 'get',
247
+ maxBodyLength: Infinity,
248
+ url: url,
249
+ headers: {
250
+ 'accept': 'application/json',
251
+ 'token': authPrev
252
+ }
253
+ })))
254
+ .then((responses) => {
255
+ const dataRes= responses.map((resp) => {
256
+ return _this.convertDefaultProductSearch(resp?.data, isActive);
257
+ });
258
+ resp(dataRes);
259
+ })
260
+ .catch(error => {
261
+ // Manejar errores
262
+ Logger.error('Error:', error);
263
+ resp([]);
264
+ });
265
+ });
266
+ }
267
+
268
+ /**
269
+ * Metodo para obtener registros no visibles en tienda
270
+ * @param {*} isVisible
271
+ * @param {*} isActive
272
+ * @param {*} sc
273
+ * @returns
274
+ */
275
+ async getProductsVisibles(isVisible=true, isActive=true, sc="1", lengthData= 2000){
276
+ const _this=this;
277
+ return new Promise(async (resp, err)=>{
278
+ let data = `Filters[SkuId]=&Filters[IsVisible]=${(isVisible === true ? "True" : "False")}&Filters[ProductName]=&Filters[BrandId]=&Filters[CategoryIds]=&Filters[StoreId]=${sc}&Filters[IsActive]=${(isActive === true ? "True" : "False")}&Filters[SellerId]=&Fields[]=ProductId&Rows=${lengthData}`;
279
+ const tokenAuth= await _this.getVtexIdclientAutCookie();
280
+
281
+ if(!tokenAuth){
282
+ resp([]);
283
+ }
284
+
285
+ let config = {
286
+ method: 'post',
287
+ maxBodyLength: Infinity,
288
+ url: `https://${_this.accountName}.${_this.environment}.com.br/admin/API/StockKeepingUnitReport/LoadContent/`,
289
+ headers: {
290
+ 'accept': 'application/json',
291
+ 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
292
+ 'Cookie': `VtexIdclientAutCookie=${tokenAuth}`
293
+ },
294
+ data : data
295
+ };
296
+
297
+ axios.request(config).then(async (response) => {
298
+ const dataRes= await _this.getProductsVisiblesDetails((response?.data["Data"] ?? []), tokenAuth, isActive);
299
+ resp(dataRes);
300
+ }).catch((error) => {
301
+ Logger.error(error);
302
+ resp([]);
303
+ });
304
+ });
305
+ }
306
+ /**
307
+ * Metodo para obtener todos los productos de catalogo VTEX
308
+ * @param {*} isVisible
309
+ * @param {*} isActive
310
+ * @param {*} sc
311
+ * @returns
312
+ */
313
+ async getProductsAll(isActive=null, isVisible=null, sc="1", lengthData=2000){
314
+ let _this=this;
315
+ return new Promise(async (res, err) => {
316
+ let listProductSkus = [];
317
+ try {
318
+ const listTradePolicy = sc ? [sc] : ["1"];
319
+ for (let i = 0; i < listTradePolicy.length; i++) {
320
+ let stop = false, _from = 0, _to = 49;
321
+ while (stop === false) {
322
+ try {
323
+ const products = await _this.fetch(`/catalog_system/pub/products/search/?sc=${listTradePolicy[i]}&_to=${_to}&_from=${_from}&O=OrderByNameASC`, {
324
+ method: "GET",
325
+ });
326
+
327
+ if (products?.data?.length > 0) {
328
+ for (let j = 0; j < products.data.length; j++) {
329
+ listProductSkus=[...listProductSkus, products.data[j]];
330
+ }
331
+ } else {
332
+ stop = true;
333
+ }
334
+ } catch (error) {
335
+ Logger.error("error getAllProductsVTEX while", error);
336
+ stop = true;
337
+ }
338
+
339
+ _from += 50;
340
+ _to += 50;
341
+ }
342
+ }
343
+
344
+ if(typeof isActive === "string"){
345
+ isActive= isActive.toLowerCase();
346
+ if(isActive && (isActive===true || isActive==="true")){
347
+ isActive= true;
348
+ }else{
349
+ isActive= false;
350
+ }
351
+ }else if(!isActive){
352
+ isActive=true;
353
+ }
354
+
355
+ if(typeof isVisible === "string"){
356
+ isVisible= isVisible.toLowerCase();
357
+ if(isVisible && (isVisible===true || isVisible==="true")){
358
+ isVisible= true;
359
+ }else{
360
+ isVisible= false;
361
+ }
362
+ }else if(!isVisible){
363
+ isVisible=false;
364
+ }
365
+
366
+ const productsVisible= await _this.getProductsVisibles(isVisible, isActive, sc, lengthData);
367
+ const productsVisibleFilter= productsVisible?.filter(itV=>itV?.items?.length > 0);
368
+ listProductSkus= [...listProductSkus, ...productsVisibleFilter];
369
+
370
+ } catch (error) {
371
+ Logger.error("error getAllProductsVTEX", error);
372
+ }
373
+
374
+ res(listProductSkus);
375
+ });
376
+ }
377
+ /**
378
+ * Metodo para obtener productos de catalogo VTEX
379
+ * @param {*} isVisible
380
+ * @param {*} isActive
381
+ * @param {*} sc
382
+ * @returns
383
+ */
384
+ async getProducts(event, isActive=null, isVisible=null, sc="1", lengthData=2000){
385
+ let _this=this;
386
+ let noVisible= event?.queryStringParameters?.noVisible;
387
+
388
+ let responseService= [];
389
+
390
+ if(typeof noVisible === "string"){
391
+ noVisible= noVisible.toLowerCase();
392
+ }
393
+ if(typeof isActive === "string"){
394
+ isActive= isActive.toLowerCase();
395
+ if(isActive && (isActive===true || isActive==="true")){
396
+ isActive= true;
397
+ }else{
398
+ isActive= false;
399
+ }
400
+ }else if(!isActive){
401
+ isActive=true;
402
+ }
403
+
404
+ if(typeof isVisible === "string"){
405
+ isVisible= isVisible.toLowerCase();
406
+ if(isVisible && (isVisible===true || isVisible==="true")){
407
+ isVisible= true;
408
+ }else{
409
+ isVisible= false;
410
+ }
411
+ }else if(!isVisible){
412
+ isVisible=false;
413
+ }
414
+
415
+ if((noVisible && (noVisible===true || noVisible==="true")) || isActive===false){
416
+ const productsVisible= await _this.getProductsVisibles(isVisible, isActive, sc, lengthData);
417
+ const productsVisibleFilter= productsVisible?.filter(itV=>itV?.items?.length > 0);
418
+ responseService= [...responseService, ...productsVisibleFilter];
419
+ }else{
420
+ const response = await _this.fetch(`/catalog_system/pub/products/search`, {
421
+ method: "GET",
422
+ params: event?.queryStringParameters
423
+ });
424
+
425
+ if (response?.data) {
426
+ responseService = response?.data ?? [];
427
+ }
428
+ }
429
+
430
+ return responseService;
431
+ }
432
+
433
+ async getDetailSkuPerSkuRef(relationSkuRef){
434
+ const _this = this;
435
+
436
+ try {
437
+ if (Array.isArray(relationSkuRef) === false || relationSkuRef.length === 0) {
438
+ relationSkuRef = [relationSkuRef];
439
+ }
440
+
441
+ const skusRefsIds = await _this.fetch(`/catalog_system/pub/sku/stockkeepingunitidsbyrefids`, {
442
+ method: "POST",
443
+ data: relationSkuRef
444
+ });
445
+
446
+ if (!skusRefsIds || !skusRefsIds.data) {
447
+ return [];
448
+ }
449
+
450
+ let filteredSkusRefsIds = [];
451
+ Object.entries(skusRefsIds.data).forEach(([key, value]) => {
452
+ if(value !== "null" && value !== null && value !== undefined){
453
+ filteredSkusRefsIds.push(value);
454
+ }
455
+ });
456
+
457
+ if (filteredSkusRefsIds.length === 0) {
458
+ return [];
459
+ }
460
+
461
+ const detailedProducts = await this.getDetailSkuById(filteredSkusRefsIds);
462
+ return detailedProducts;
463
+
464
+ } catch (error) {
465
+ Logger.error("error getDetailSkuPerSkuRef", error);
466
+ return [];
467
+ }
468
+ }
469
+
470
+ async getDetailSkuById(skuIds){
471
+ const _this = this;
472
+
473
+ if (Array.isArray(skuIds) === false || skuIds.length === 0) {
474
+ skuIds = [skuIds];
475
+ }
476
+
477
+ return new Promise(async(resp, err)=>{
478
+ const urls = skuIds?.map(skuId =>(`${_this.baseURL}/catalog_system/pvt/sku/stockkeepingunitbyid/${skuId}`));
479
+
480
+ axios.all(urls.map(url => axios.request({
481
+ method: 'get',
482
+ maxBodyLength: Infinity,
483
+ url: url,
484
+ headers: {
485
+ 'Accept': 'application/json',
486
+ 'Content-Type': 'application/json',
487
+ 'X-VTEX-API-AppKey': _this.authKey,
488
+ 'X-VTEX-API-AppToken': _this.authToken
489
+ }
490
+ }).catch(error => {
491
+ Logger.error(`Error for URL ${url}:`, error.message);
492
+ return null;
493
+ })))
494
+ .then((responses) => {
495
+ const dataRes = responses
496
+ .filter(resp => resp && resp.data) // Filtrar respuestas válidas
497
+ .map((resp) => resp.data);
498
+ resp(dataRes);
499
+ })
500
+ .catch(error => {
501
+ Logger.error('General error in getDetailSkuById:', error);
502
+ resp([]);
503
+ });
504
+ });
505
+
506
+ }
507
+
508
+ }
509
+
510
+ module.exports = VtexApi;
511
+