n8n-nodes-centum 0.2.12 → 0.2.14

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.
@@ -38,43 +38,7 @@ class Centum {
38
38
  };
39
39
  const resource = this.getNodeParameter('resource', 0);
40
40
  switch (resource) {
41
- case 'generarToken':
42
- try {
43
- const tokenGenerado = (0, functions_1.createHash)(headers.publicAccessKey);
44
- return [this.helpers.returnJsonArray(tokenGenerado)];
45
- }
46
- catch (error) {
47
- console.log(error);
48
- const errorMessage = error?.response?.data?.Message || error.message || 'Error desconocido';
49
- throw new n8n_workflow_1.NodeOperationError(this.getNode(), errorMessage);
50
- }
51
- case 'pedidoVentaActividad':
52
- const pedidoID = this.getNodeParameter('id', 0);
53
- try {
54
- const dataActividad = await (0, functions_1.apiRequest)(`${centumUrl}/PedidosVenta/${pedidoID}`, { ...headers });
55
- return [this.helpers.returnJsonArray(dataActividad)];
56
- }
57
- catch (error) {
58
- console.log(error);
59
- const errorMessage = error?.response?.data?.Message || error.message || 'Error desconocido';
60
- throw new n8n_workflow_1.NodeOperationError(this.getNode(), errorMessage);
61
- }
62
- case 'articulosDatosGenerales':
63
- try {
64
- const response = await (0, functions_1.apiRequest)(`${centumUrl}/Articulos/DatosGenerales`, {
65
- method: 'POST',
66
- headers,
67
- body: {},
68
- queryParams: { tipoOrdenArticulos: 'Nombre' }
69
- });
70
- return [this.helpers.returnJsonArray(response)];
71
- }
72
- catch (error) {
73
- console.log('Error en solicitud de artículos', error);
74
- const errorMessage = error?.response?.data?.Message || error.message || 'Error desconocido';
75
- throw new n8n_workflow_1.NodeOperationError(this.getNode(), errorMessage);
76
- }
77
- case 'articulo':
41
+ case 'articulo': {
78
42
  const clientId = this.getNodeParameter('clienteId', 0);
79
43
  const documentDate = this.getNodeParameter('documentDate', 0);
80
44
  const IdsRubro = this.getNodeParameter('idsRubros', 0);
@@ -84,6 +48,8 @@ class Centum {
84
48
  const dateModified = this.getNodeParameter('dateModified', 0);
85
49
  const dateModifiedImage = this.getNodeParameter('dateModifiedImage', 0);
86
50
  const priceDateModified = this.getNodeParameter('priceDateModified', 0);
51
+ const numeroPagina = this.getNodeParameter('numeroPagina', 0);
52
+ const cantidadPorPagina = this.getNodeParameter('cantidadPorPagina', 0);
87
53
  const bodyToSend = {
88
54
  idCliente: clientId,
89
55
  FechaDocumento: formattedDocumentDate,
@@ -93,13 +59,15 @@ class Centum {
93
59
  fechaModificacionDesde: dateModified ? dateModified : '',
94
60
  fechaModificacionImagenesDesde: dateModifiedImage ? dateModifiedImage : '',
95
61
  fechaPrecioActualizadoDesde: priceDateModified,
62
+ numeroPagina,
63
+ cantidadPorPagina,
96
64
  };
97
65
  try {
98
66
  const response = await (0, functions_1.apiRequest)(`${centumUrl}/Articulos/Venta`, {
99
67
  method: 'POST',
100
68
  body: bodyToSend,
101
69
  headers,
102
- queryParams: { tipoOrdenArticulos: 'Codigo' }
70
+ queryParams: { tipoOrdenArticulos: 'Codigo' },
103
71
  });
104
72
  if (response.Articulos.Items.length > 0) {
105
73
  const items = response.Articulos.Items;
@@ -136,7 +104,7 @@ class Centum {
136
104
  }
137
105
  }
138
106
  const combinedArrays = [...acc, ...items];
139
- const filteredArray = Array.from(new Map(combinedArrays.map(obj => [obj.IdArticulo, obj])).values());
107
+ const filteredArray = Array.from(new Map(combinedArrays.map((obj) => [obj.IdArticulo, obj])).values());
140
108
  const itemsArray = filteredArray.map((item) => ({
141
109
  ...item,
142
110
  AtributosArticulo: item.Habilitado && item.ActivoWeb ? item.AtributosArticulo : [],
@@ -154,69 +122,69 @@ class Centum {
154
122
  const errorMessage = error?.response?.data?.Message || error.message || 'Error desconocido';
155
123
  throw new n8n_workflow_1.NodeOperationError(this.getNode(), errorMessage);
156
124
  }
157
- case 'articulosExistencia':
158
- const branchOfficeIds = String(this.getNodeParameter('branchOfficeIds', 0));
125
+ }
126
+ case 'articuloPorId': {
127
+ const codigo = this.getNodeParameter('codigo', 0);
128
+ const articleId = this.getNodeParameter('articleId', 0);
129
+ if (!codigo && !articleId) {
130
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'El id o codigo del articulo es obligatorio');
131
+ }
159
132
  try {
160
- const dataArticulosExistencia = await (0, functions_1.apiRequest)(`${centumUrl}/ArticulosExistencias`, {
133
+ const articulo = await (0, functions_1.apiRequest)(`${centumUrl}/Articulos/DatosGenerales`, {
134
+ method: 'POST',
161
135
  headers,
162
- queryParams: {
163
- idsSucursalesFisicas: branchOfficeIds,
164
- },
136
+ body: { CodigoExacto: codigo, Ids: articleId },
165
137
  });
166
- return [this.helpers.returnJsonArray(dataArticulosExistencia.Items)];
138
+ return [this.helpers.returnJsonArray(articulo)];
167
139
  }
168
140
  catch (error) {
169
- console.log('ArticulosExistencias error: ', error);
141
+ console.log('Error en solicitud de artículo por ID:', error);
170
142
  const errorMessage = error?.response?.data?.Message || error.message || 'Error desconocido';
171
143
  throw new n8n_workflow_1.NodeOperationError(this.getNode(), errorMessage);
172
144
  }
173
- case 'articulosSucursalesFisicas':
174
- const IdSucursalFisica = this.getNodeParameter('IdSucursalFisica', 0);
175
- const queryParams = {
176
- Codigo: 'R06SR0601P00010007',
177
- };
178
- if (IdSucursalFisica) {
179
- queryParams.idsSucursalesFisicas = IdSucursalFisica;
180
- }
145
+ }
146
+ case 'articulosDatosGenerales': {
181
147
  try {
182
- const dataArticulosExistencias = await (0, functions_1.apiRequest)(`${centumUrl}/ArticulosSucursalesFisicas`, {
148
+ const ajustesHTTP = functions_1.getHttpSettings.call(this);
149
+ const articulosURL = `${centumUrl}/Articulos/DatosGenerales`;
150
+ const fetchOptions = {
151
+ method: 'POST',
183
152
  headers,
184
- queryParams,
185
- });
186
- return [this.helpers.returnJsonArray(dataArticulosExistencias.Items)];
153
+ body: {},
154
+ queryParams: { tipoOrdenArticulos: 'Nombre' },
155
+ pagination: ajustesHTTP.pagination,
156
+ cantidadItemsPorPagina: ajustesHTTP.cantidadItemsPorPagina,
157
+ intervaloPagina: ajustesHTTP.intervaloPagina,
158
+ itemsField: 'Items',
159
+ context: this,
160
+ };
161
+ const paginated = await (0, functions_1.apiPostRequestPaginated)(articulosURL, fetchOptions);
162
+ return [this.helpers.returnJsonArray(paginated)];
187
163
  }
188
164
  catch (error) {
189
- console.log(error);
165
+ console.log('Error en solicitud de artículos', error);
190
166
  const errorMessage = error?.response?.data?.Message || error.message || 'Error desconocido';
191
167
  throw new n8n_workflow_1.NodeOperationError(this.getNode(), errorMessage);
192
168
  }
193
- case 'precioArticulo':
194
- const paramsPrice = {
195
- Cantidad: this.getNodeParameter('articuloCantidad', 0),
196
- FechaDocumento: this.getNodeParameter('documentDate', 0),
197
- };
169
+ }
170
+ case 'articulosExistencia': {
171
+ const branchOfficeIds = String(this.getNodeParameter('branchOfficeIds', 0));
198
172
  try {
199
- const dataArticulosPrecios = await (0, functions_1.apiRequest)(`${centumUrl}/Articulos/PrecioArticulo`, {
200
- method: 'POST',
173
+ const dataArticulosExistencia = await (0, functions_1.apiRequest)(`${centumUrl}/ArticulosExistencias`, {
201
174
  headers,
202
- queryParams: paramsPrice,
203
- body: {
204
- IdArticulo: 1507,
205
- Codigo: 'R02SR0206P00070007',
206
- CodigoAuxiliar: '',
207
- CodigoPropioProveedor: '',
208
- Nombre: 'ADHESIVO ACRILICO KEKOL K-645 1 KG',
209
- NombreFantasia: '',
175
+ queryParams: {
176
+ idsSucursalesFisicas: branchOfficeIds,
210
177
  },
211
178
  });
212
- return [this.helpers.returnJsonArray(dataArticulosPrecios)];
179
+ return [this.helpers.returnJsonArray(dataArticulosExistencia.Items)];
213
180
  }
214
181
  catch (error) {
215
- console.log(error);
182
+ console.log('ArticulosExistencias error: ', error);
216
183
  const errorMessage = error?.response?.data?.Message || error.message || 'Error desconocido';
217
184
  throw new n8n_workflow_1.NodeOperationError(this.getNode(), errorMessage);
218
185
  }
219
- case 'articulosImagenes':
186
+ }
187
+ case 'articulosImagenes': {
220
188
  const arrResult = [];
221
189
  const inputData = this.getInputData();
222
190
  const requestUrl = `${centumUrl}/ArticulosImagenes`;
@@ -227,7 +195,10 @@ class Centum {
227
195
  images: [],
228
196
  infoImages: [],
229
197
  };
230
- const allArticleImages = await (0, functions_1.centumGetArticleImages)(1, element.json.IdArticulo, { consumerApiPublicId, publicAccessKey: String(centumApiCredentials.publicAccessKey) }, requestUrl);
198
+ const allArticleImages = await (0, functions_1.centumGetArticleImages)(1, element.json.IdArticulo, {
199
+ consumerApiPublicId,
200
+ publicAccessKey: String(centumApiCredentials.publicAccessKey),
201
+ }, requestUrl);
231
202
  if (allArticleImages instanceof Error) {
232
203
  console.error(`Failed to download images for article ${element.json.IdArticulo}`, allArticleImages);
233
204
  continue;
@@ -256,87 +227,113 @@ class Centum {
256
227
  }
257
228
  }
258
229
  return [this.helpers.returnJsonArray(arrResult)];
259
- case 'procesarImagenes':
260
- const dataImages = this.getNodeParameter('dataImg', 0);
261
- const db = this.getNodeParameter('lastModifiedImg', 0);
262
- const result = [];
263
- for (let i = 0; i < dataImages.length; i++) {
264
- const element = dataImages[i];
265
- for (let j = 0; j < element.json.images?.length; j++) {
266
- const currentData = element.json.images[j];
267
- const currentInfoImage = element.json.infoImages[j];
268
- const articleInDB = db.find((dbData) => dbData.articleId === element.json.idArticulo);
269
- if (!articleInDB) {
270
- result.push({ json: {}, binary: currentData });
271
- }
272
- else {
273
- const currentImageInDB = articleInDB.dataImage.find((dataImageDB) => dataImageDB.orderNumber === currentInfoImage.orderNumber);
274
- if (currentImageInDB?.lastModified !== currentInfoImage.lastModified) {
275
- result.push({ json: {}, binary: currentData });
276
- }
277
- }
278
- }
230
+ }
231
+ case 'articulosPrecioPorLista': {
232
+ const idArticulos = this.getNodeParameter('codigo', 0);
233
+ const idLista = this.getNodeParameter('idList', 0);
234
+ if (!idLista || !idArticulos) {
235
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'El id de la lista y el artículo son obligatorios.');
279
236
  }
280
- if (result.length === 0) {
281
- result.push([]);
237
+ try {
238
+ const articulo = await (0, functions_1.apiRequest)(`${centumUrl}/Articulos/FiltrosPrecios`, {
239
+ method: 'POST',
240
+ headers,
241
+ body: { IdsArticulos: idArticulos, IdLista: idLista },
242
+ });
243
+ return [this.helpers.returnJsonArray(articulo)];
244
+ }
245
+ catch (error) {
246
+ console.log('Error en solicitud de artículo por ID:', error);
247
+ }
248
+ }
249
+ case 'articulosSucursalesFisicas': {
250
+ const IdSucursalFisica = this.getNodeParameter('IdSucursalFisica', 0);
251
+ const queryParams = {
252
+ idsSucursalesFisicas: IdSucursalFisica,
253
+ };
254
+ if (!IdSucursalFisica) {
255
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'El id de la sucursal fisica es obligatorio');
282
256
  }
283
- return [this.helpers.returnJsonArray(result)];
284
- case 'clientes':
285
257
  try {
286
- const ajustesHTTP = functions_1.getHttpSettings.call(this);
287
- const clientesURL = `${centumUrl}/Clientes`;
288
- const fetchOptions = {
289
- method: 'GET',
290
- pagination: ajustesHTTP.pagination,
291
- cantidadItemsPorPagina: ajustesHTTP.cantidadItemsPorPagina,
292
- intervaloPagina: ajustesHTTP.intervaloPagina,
293
- itemsField: 'Items',
294
- context: this,
258
+ const dataArticulosExistencias = await (0, functions_1.apiRequest)(`${centumUrl}/ArticulosSucursalesFisicas`, {
295
259
  headers,
296
- };
297
- let clientes = [];
298
- const paginated = await (0, functions_1.apiGetRequest)(clientesURL, fetchOptions);
299
- clientes = paginated;
300
- return [this.helpers.returnJsonArray(clientes)];
260
+ queryParams,
261
+ });
262
+ return [this.helpers.returnJsonArray(dataArticulosExistencias.Items)];
301
263
  }
302
264
  catch (error) {
265
+ console.log(error);
303
266
  const errorMessage = error?.response?.data?.Message || error.message || 'Error desconocido';
304
267
  throw new n8n_workflow_1.NodeOperationError(this.getNode(), errorMessage);
305
268
  }
306
- case 'nuevoContribuyente': {
307
- const bodyJson = this.getNodeParameter('cuerpoHTTP', 0);
308
- const cuit = this.getNodeParameter('cuit', 0);
309
- console.log(bodyJson);
310
- if (typeof cuit !== 'string' || !/^\d{11}$/.test(cuit)) {
311
- throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'El CUIT debe ser una cadena de 11 dígitos numéricos.');
269
+ }
270
+ case 'articuloSucursalFisica': {
271
+ const IdSucursalFisica = this.getNodeParameter('idSucursalFisica', 0);
272
+ const idArticulo = this.getNodeParameter('articleId', 0);
273
+ const codigo = this.getNodeParameter('codigo', 0);
274
+ const queryParams = {
275
+ IdSucursalFisica: IdSucursalFisica,
276
+ codigoExacto: codigo,
277
+ idsArticulos: idArticulo
278
+ };
279
+ if (!IdSucursalFisica || (!idArticulo && !codigo)) {
280
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'El id de la sucursal fisica y el id del articulo o el codigo son obligatorios');
312
281
  }
313
- const contribuyenteJSON = (0, functions_1.createContribuyenteJson)(bodyJson, cuit);
314
282
  try {
315
- const crearCliente = await (0, functions_1.apiRequest)(`${centumUrl}/Clientes`, {
316
- method: 'POST',
317
- body: contribuyenteJSON,
283
+ const dataArticulosExistencias = await (0, functions_1.apiRequest)(`${centumUrl}/ArticulosSucursalesFisicas`, {
318
284
  headers,
285
+ queryParams,
319
286
  });
320
- console.log('Contribuyente creado:', crearCliente);
321
- return [this.helpers.returnJsonArray([crearCliente])];
287
+ return [this.helpers.returnJsonArray(dataArticulosExistencias.Items)];
322
288
  }
323
289
  catch (error) {
324
- console.error('Error al crear contribuyente:', error);
325
- const statusCode = error?.response?.status;
326
- const responseData = error?.response?.data;
327
- const errorMessage = responseData?.Message ||
328
- responseData?.message ||
329
- error?.message ||
330
- 'Error desconocido al crear el contribuyente.';
331
- const fullMessage = statusCode
332
- ? `Error ${statusCode}: ${errorMessage}`
333
- : errorMessage;
334
- throw new n8n_workflow_1.NodeOperationError(this.getNode(), fullMessage, {
335
- description: responseData?.Detail || 'Ocurrió un error inesperado al llamar a la API de Centum.',
290
+ console.log(error);
291
+ const errorMessage = error?.response?.data?.Message || error.message || 'Error desconocido';
292
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), errorMessage);
293
+ }
294
+ }
295
+ case 'buscarContribuyente': {
296
+ const cuit = this.getNodeParameter('cuit', 0, '');
297
+ const razonSocial = this.getNodeParameter('razonSocial', 0, '');
298
+ if (!cuit && !razonSocial) {
299
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Debe proporcionar al menos CUIT o Razón Social para buscar contribuyentes.');
300
+ }
301
+ let url = `${centumUrl}/Clientes/BuscarContribuyente`;
302
+ const queryParams = {};
303
+ if (cuit && !razonSocial) {
304
+ url += `/${cuit}`;
305
+ }
306
+ else {
307
+ if (cuit)
308
+ queryParams.Cuit = cuit;
309
+ if (razonSocial)
310
+ queryParams.razonSocial = razonSocial;
311
+ }
312
+ const requestDetails = {
313
+ url,
314
+ headers,
315
+ queryParams,
316
+ };
317
+ try {
318
+ console.log(`[BuscarContribuyente] Request:`, JSON.stringify(requestDetails, null, 2));
319
+ const response = await (0, functions_1.apiRequest)(requestDetails.url, {
320
+ method: 'GET',
321
+ headers: requestDetails.headers,
322
+ queryParams: requestDetails.queryParams,
336
323
  });
324
+ console.log(`[BuscarContribuyente] Response:`, JSON.stringify(response, null, 2));
325
+ if (response.CantidadTotalItems === 1) {
326
+ return [this.helpers.returnJsonArray(response.Items)];
327
+ }
328
+ return [this.helpers.returnJsonArray(response)];
329
+ }
330
+ catch (error) {
331
+ console.log(`[BuscarContribuyente] Error:`, error);
332
+ const errorMessage = error?.response?.data?.Message || error.message || 'Error desconocido';
333
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), errorMessage);
337
334
  }
338
335
  }
339
- case 'clienteNuevo':
336
+ case 'clienteNuevo': {
340
337
  const datosCliente = this.getNodeParameter('cuerpoHTTP', 0);
341
338
  const clienteDNI = this.getNodeParameter('dni', 0);
342
339
  const datosJSON = (0, functions_1.createCustomerJson)(datosCliente, clienteDNI);
@@ -356,7 +353,31 @@ class Centum {
356
353
  };
357
354
  return [this.helpers.returnJsonArray(obj)];
358
355
  }
359
- case 'clientesActualizar':
356
+ }
357
+ case 'clientes': {
358
+ try {
359
+ const ajustesHTTP = functions_1.getHttpSettings.call(this);
360
+ const clientesURL = `${centumUrl}/Clientes`;
361
+ const fetchOptions = {
362
+ method: 'GET',
363
+ pagination: ajustesHTTP.pagination,
364
+ cantidadItemsPorPagina: ajustesHTTP.cantidadItemsPorPagina,
365
+ intervaloPagina: ajustesHTTP.intervaloPagina,
366
+ itemsField: 'Items',
367
+ context: this,
368
+ headers,
369
+ };
370
+ let clientes = [];
371
+ const paginated = await (0, functions_1.apiGetRequest)(clientesURL, fetchOptions);
372
+ clientes = paginated;
373
+ return [this.helpers.returnJsonArray(clientes)];
374
+ }
375
+ catch (error) {
376
+ const errorMessage = error?.response?.data?.Message || error.message || 'Error desconocido';
377
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), errorMessage);
378
+ }
379
+ }
380
+ case 'clientesActualizar': {
360
381
  const nuevosDatos = this.getNodeParameter('cuerpoHTTP', 0);
361
382
  try {
362
383
  const updateCustomer = await (0, functions_1.apiRequest)(`${centumUrl}/Clientes/Actualizar`, {
@@ -370,6 +391,114 @@ class Centum {
370
391
  console.log(error);
371
392
  return [this.helpers.returnJsonArray([])];
372
393
  }
394
+ }
395
+ case 'clientesBusqueda': {
396
+ const customerEmail = this.getNodeParameter('email', 0, '');
397
+ const dni = this.getNodeParameter('dni', 0, '');
398
+ const buildQuery = (campo, valor) => valor ? { [campo]: valor } : {};
399
+ const trySearch = async (campo, valor, label) => {
400
+ if (!valor)
401
+ return null;
402
+ try {
403
+ console.log(`[${label}] Buscando cliente por ${campo}: ${valor}`);
404
+ const response = await (0, functions_1.apiRequest)(`${centumUrl}/Clientes`, {
405
+ method: 'GET',
406
+ headers,
407
+ queryParams: buildQuery(campo, valor),
408
+ }, this);
409
+ console.log(`[${label}] Resultado:`, response);
410
+ return response;
411
+ }
412
+ catch (error) {
413
+ console.error(`[${label}] Error:`, error);
414
+ return null;
415
+ }
416
+ };
417
+ try {
418
+ let response = null;
419
+ if (customerEmail) {
420
+ response = await trySearch('Email', customerEmail, 'email');
421
+ }
422
+ if (!response && dni) {
423
+ response = await trySearch('Codigo', `web-${dni}`, 'dni-web');
424
+ }
425
+ if (!response && dni) {
426
+ response = await trySearch('Codigo', `${dni}`, 'dni');
427
+ }
428
+ console.log('Búsqueda finalizada. Resultado:', response);
429
+ return [this.helpers.returnJsonArray(response)];
430
+ }
431
+ catch (error) {
432
+ console.error('Error general durante la búsqueda de cliente:', error);
433
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), `Búsqueda fallida: ${JSON.stringify(error)}`);
434
+ }
435
+ }
436
+ case 'clientesBusquedaPorCuit': {
437
+ const cuit = this.getNodeParameter('cuit', 0, '');
438
+ if (!cuit) {
439
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Debe proporcionar CUIT para buscar clientes.');
440
+ }
441
+ const queryParams = { Cuit: cuit };
442
+ try {
443
+ const response = await (0, functions_1.apiRequest)(`${centumUrl}/Clientes`, {
444
+ method: 'GET',
445
+ headers,
446
+ queryParams,
447
+ });
448
+ return [this.helpers.returnJsonArray(response.Items)];
449
+ }
450
+ catch (error) {
451
+ console.log(`[ClientesBusquedaPorCuit] Error:`, error);
452
+ const errorMessage = error?.response?.data?.Message || error.message || 'Error desconocido';
453
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), errorMessage);
454
+ }
455
+ }
456
+ case 'cobros': {
457
+ const ordenCliente = this.getNodeParameter('cliente', 0);
458
+ const ordenArticulo = this.getNodeParameter('articulo', 0);
459
+ const ordenEnvio = this.getNodeParameter('envio', 0);
460
+ const bodyCharge = (0, functions_1.createChargeJson)(ordenCliente, ordenArticulo, ordenEnvio);
461
+ try {
462
+ const dataCobros = await (0, functions_1.apiRequest)(`${centumUrl}/Cobros`, {
463
+ method: 'POST',
464
+ body: bodyCharge,
465
+ headers,
466
+ });
467
+ return [this.helpers.returnJsonArray(dataCobros)];
468
+ }
469
+ catch (error) {
470
+ console.log(error);
471
+ const errorMessage = error?.response?.data?.Message || error.message || 'Error desconocido';
472
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), errorMessage);
473
+ }
474
+ }
475
+ case 'composicionSaldoCliente': {
476
+ const clientIdParam = this.getNodeParameter('clienteId', 0);
477
+ const desdeSaldoFecha = this.getNodeParameter('priceDateModified', 0);
478
+ const separarFecha = String(desdeSaldoFecha).split('T')[0];
479
+ const clientId = Number(clientIdParam);
480
+ if (isNaN(clientId) || clientId <= 0) {
481
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'clienteId debe ser un número positivo');
482
+ }
483
+ try {
484
+ let url = `${centumUrl}/SaldosCuentasCorrientes/Composicion/${clientId}`;
485
+ if (separarFecha) {
486
+ url += `?fechaVencimientoHasta=${separarFecha}`;
487
+ }
488
+ const response = await (0, functions_1.apiRequest)(url, {
489
+ method: 'GET',
490
+ headers,
491
+ });
492
+ if (!response || typeof response !== 'object') {
493
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Respuesta inválida del servidor');
494
+ }
495
+ return [this.helpers.returnJsonArray(response)];
496
+ }
497
+ catch (error) {
498
+ const errorMessage = error?.response?.data?.Message || error.message || 'Error desconocido';
499
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), `Error obteniendo composición de saldo para cliente ${clientId}: ${errorMessage}`);
500
+ }
501
+ }
373
502
  case 'crearPedidoVenta': {
374
503
  const customerSalesOrder = this.getNodeParameter('cliente', 0);
375
504
  const articlesSalesOrder = this.getNodeParameter('articulo', 0);
@@ -408,167 +537,260 @@ class Centum {
408
537
  throw new n8n_workflow_1.NodeOperationError(this.getNode(), errorMessage);
409
538
  }
410
539
  }
411
- case 'cobros':
412
- const ordenCliente = this.getNodeParameter('cliente', 0);
413
- const ordenArticulo = this.getNodeParameter('articulo', 0);
414
- const ordenEnvio = this.getNodeParameter('envio', 0);
415
- const bodyCharge = (0, functions_1.createChargeJson)(ordenCliente, ordenArticulo, ordenEnvio);
540
+ case 'departamentosLista': {
541
+ const idProvincia = this.getNodeParameter('idProvincia', 0, '');
416
542
  try {
417
- const dataCobros = await (0, functions_1.apiRequest)(`${centumUrl}/Cobros`, {
418
- method: 'POST',
419
- body: bodyCharge,
543
+ const queryParams = {};
544
+ if (idProvincia) {
545
+ queryParams.idProvincia = idProvincia;
546
+ }
547
+ const departamentos = await (0, functions_1.apiRequest)(`${centumUrl}/Departamentos`, {
548
+ method: 'GET',
420
549
  headers,
550
+ queryParams,
421
551
  });
422
- return [this.helpers.returnJsonArray(dataCobros)];
552
+ return [this.helpers.returnJsonArray(departamentos.map((d) => ({ ...d })))];
423
553
  }
424
554
  catch (error) {
425
555
  console.log(error);
426
556
  const errorMessage = error?.response?.data?.Message || error.message || 'Error desconocido';
427
557
  throw new n8n_workflow_1.NodeOperationError(this.getNode(), errorMessage);
428
558
  }
429
- case 'buscarContribuyente': {
430
- const cuit = this.getNodeParameter('cuit', 0, '');
431
- const razonSocial = this.getNodeParameter('razonSocial', 0, '');
432
- if (!cuit && !razonSocial) {
433
- throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Debe proporcionar al menos CUIT o Razón Social para buscar contribuyentes.');
559
+ }
560
+ case 'generarProductosWoo': {
561
+ const data = this.getInputData();
562
+ const json = (0, functions_1.createJsonProducts)(data);
563
+ return [this.helpers.returnJsonArray(json)];
564
+ }
565
+ case 'generarToken': {
566
+ try {
567
+ const tokenGenerado = (0, functions_1.createHash)(headers.publicAccessKey);
568
+ return [this.helpers.returnJsonArray(tokenGenerado)];
434
569
  }
435
- const queryParams = {};
436
- if (cuit)
437
- queryParams.Cuit = cuit;
438
- if (razonSocial)
439
- queryParams.razonSocial = razonSocial;
440
- const requestDetails = {
441
- url: `${centumUrl}/Clientes`,
442
- headers,
443
- queryParams,
444
- };
570
+ catch (error) {
571
+ console.log(error);
572
+ const errorMessage = error?.response?.data?.Message || error.message || 'Error desconocido';
573
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), errorMessage);
574
+ }
575
+ }
576
+ case 'listaPrecios': {
445
577
  try {
446
- console.log(`[BuscarContribuyente] Request:`, JSON.stringify(requestDetails, null, 2));
447
- const response = await (0, functions_1.apiRequest)(requestDetails.url, {
578
+ const response = await (0, functions_1.apiRequest)(`${centumUrl}/ListasPrecios`, {
448
579
  method: 'GET',
449
- headers: requestDetails.headers,
450
- queryParams: requestDetails.queryParams,
580
+ headers,
451
581
  });
452
- console.log(`[BuscarContribuyente] Response:`, JSON.stringify(response, null, 2));
453
- if (response.CantidadTotalItems === 1) {
454
- return [this.helpers.returnJsonArray(response.Items)];
455
- }
456
582
  return [this.helpers.returnJsonArray(response)];
457
583
  }
458
584
  catch (error) {
459
- console.log(`[BuscarContribuyente] Error:`, error);
585
+ console.log('Error en solicitud de promociones para el cliente:', error);
460
586
  const errorMessage = error?.response?.data?.Message || error.message || 'Error desconocido';
461
- throw new n8n_workflow_1.NodeOperationError(this.getNode(), errorMessage);
587
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), `Error obteniendo el listado de precios. \n ${errorMessage}`);
462
588
  }
463
589
  }
464
- case 'clientesBusqueda': {
465
- const customerEmail = this.getNodeParameter('email', 0, '');
466
- const dni = this.getNodeParameter('dni', 0, '');
467
- const buildQuery = (campo, valor) => valor ? { [campo]: valor } : {};
468
- const trySearch = async (campo, valor, label) => {
469
- if (!valor)
470
- return null;
471
- try {
472
- console.log(`[${label}] Buscando cliente por ${campo}: ${valor}`);
473
- const response = await (0, functions_1.apiRequest)(`${centumUrl}/Clientes`, {
474
- method: 'GET',
475
- headers,
476
- queryParams: buildQuery(campo, valor),
477
- }, this);
478
- console.log(`[${label}] Resultado:`, response);
479
- return response;
480
- }
481
- catch (error) {
482
- console.error(`[${label}] Error:`, error);
483
- return null;
484
- }
485
- };
590
+ case 'nuevoContribuyente': {
591
+ const bodyJson = this.getNodeParameter('cuerpoHTTP', 0);
592
+ const cuit = this.getNodeParameter('cuit', 0);
593
+ console.log(bodyJson);
594
+ if (typeof cuit !== 'string' || !/^\d{11}$/.test(cuit)) {
595
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'El CUIT debe ser una cadena de 11 dígitos numéricos.');
596
+ }
597
+ const contribuyenteJSON = (0, functions_1.createContribuyenteJson)(bodyJson, cuit);
486
598
  try {
487
- let response = null;
488
- if (customerEmail) {
489
- response = await trySearch('Email', customerEmail, 'email');
490
- }
491
- if (!response && dni) {
492
- response = await trySearch('Codigo', `web-${dni}`, 'dni-web');
599
+ const crearCliente = await (0, functions_1.apiRequest)(`${centumUrl}/Clientes`, {
600
+ method: 'POST',
601
+ body: contribuyenteJSON,
602
+ headers,
603
+ });
604
+ console.log('Contribuyente creado:', crearCliente);
605
+ return [this.helpers.returnJsonArray([crearCliente])];
606
+ }
607
+ catch (error) {
608
+ console.error('Error al crear contribuyente:', error);
609
+ const statusCode = error?.response?.status;
610
+ const responseData = error?.response?.data;
611
+ const errorMessage = responseData?.Message ||
612
+ responseData?.message ||
613
+ error?.message ||
614
+ 'Error desconocido al crear el contribuyente.';
615
+ const fullMessage = statusCode ? `Error ${statusCode}: ${errorMessage}` : errorMessage;
616
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), fullMessage, {
617
+ description: responseData?.Detail || 'Ocurrió un error inesperado al llamar a la API de Centum.',
618
+ });
619
+ }
620
+ }
621
+ case 'obtenerFacturasCobros': {
622
+ const clientIdParam = this.getNodeParameter('clienteId', 0);
623
+ const desdeSaldoFecha = this.getNodeParameter('balanceStartDate', 0);
624
+ const hastaSaldoFecha = this.getNodeParameter('balanceEndDate', 0);
625
+ const separarFechaDesde = String(desdeSaldoFecha).split('T')[0];
626
+ const separarFechaHasta = String(hastaSaldoFecha).split('T')[0];
627
+ const clientId = Number(clientIdParam);
628
+ if (isNaN(clientId) || clientId <= 0) {
629
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'clienteId debe ser un número positivo');
630
+ }
631
+ if (!desdeSaldoFecha) {
632
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'priceDateModified (fecha desde) es requerido');
633
+ }
634
+ if (!hastaSaldoFecha) {
635
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'priceDateModifiedSince (fecha hasta) es requerido');
636
+ }
637
+ try {
638
+ const body = {
639
+ fechaDocumentoDesde: separarFechaDesde,
640
+ fechaDocumentoHasta: separarFechaHasta,
641
+ IdCliente: clientId,
642
+ };
643
+ const response = await (0, functions_1.apiRequest)(`${centumUrl}/Cobros/FiltrosCobro`, {
644
+ method: 'POST',
645
+ headers,
646
+ body,
647
+ });
648
+ if (!response || typeof response !== 'object') {
649
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Respuesta inválida del servidor');
493
650
  }
494
- if (!response && dni) {
495
- response = await trySearch('Codigo', `${dni}`, 'dni');
651
+ return [this.helpers.returnJsonArray(response)];
652
+ }
653
+ catch (error) {
654
+ console.log('Error en solicitud de facturas pedidos ventas:', error);
655
+ const errorMessage = error?.response?.data?.Message || error.message || 'Error desconocido';
656
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), `Error obteniendo facturas pedidos ventas para cliente ${clientId}: ${errorMessage}`);
657
+ }
658
+ }
659
+ case 'obtenerFacturasPedidosVentas': {
660
+ const clientIdParam = this.getNodeParameter('clienteId', 0);
661
+ const desdeSaldoFecha = this.getNodeParameter('balanceStartDate', 0);
662
+ const hastaSaldoFecha = this.getNodeParameter('balanceEndDate', 0);
663
+ const separarFechaDesde = String(desdeSaldoFecha).split('T')[0];
664
+ const separarFechaHasta = String(hastaSaldoFecha).split('T')[0];
665
+ const clientId = Number(clientIdParam);
666
+ if (isNaN(clientId) || clientId <= 0) {
667
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'clienteId debe ser un número positivo');
668
+ }
669
+ if (!desdeSaldoFecha) {
670
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'priceDateModified (fecha desde) es requerido');
671
+ }
672
+ if (!hastaSaldoFecha) {
673
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'priceDateModifiedSince (fecha hasta) es requerido');
674
+ }
675
+ try {
676
+ const body = {
677
+ fechaDocumentoDesde: separarFechaDesde,
678
+ fechaDocumentoHasta: separarFechaHasta,
679
+ IdCliente: clientId,
680
+ };
681
+ const response = await (0, functions_1.apiRequest)(`${centumUrl}/Ventas/FiltrosVenta`, {
682
+ method: 'POST',
683
+ headers,
684
+ body,
685
+ });
686
+ if (!response || typeof response !== 'object') {
687
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Respuesta inválida del servidor');
496
688
  }
497
- console.log('Búsqueda finalizada. Resultado:', response);
498
689
  return [this.helpers.returnJsonArray(response)];
499
690
  }
500
691
  catch (error) {
501
- console.error('Error general durante la búsqueda de cliente:', error);
502
- throw new n8n_workflow_1.NodeOperationError(this.getNode(), `Búsqueda fallida: ${JSON.stringify(error)}`);
692
+ console.log('Error en solicitud de facturas pedidos ventas:', error);
693
+ const errorMessage = error?.response?.data?.Message || error.message || 'Error desconocido';
694
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), `Error obteniendo facturas pedidos ventas para cliente ${clientId}: ${errorMessage}`);
503
695
  }
504
696
  }
505
- case 'sucursalesFisicas':
697
+ case 'obtenerSaldoCliente': {
698
+ const clientIdParam = this.getNodeParameter('clienteId', 0);
699
+ const desdeSaldoFecha = this.getNodeParameter('priceDateModified', 0);
700
+ const soloFecha = String(desdeSaldoFecha).split('T')[0];
701
+ const clientId = Number(clientIdParam);
702
+ if (isNaN(clientId) || clientId <= 0) {
703
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'clienteId debe ser un número positivo');
704
+ }
506
705
  try {
507
- const dataListBranches = await (0, functions_1.apiRequest)(`${centumUrl}/SucursalesFisicas`, {
706
+ let url = `${centumUrl}/SaldosCuentasCorrientes/${clientId}`;
707
+ if (soloFecha) {
708
+ url += `?fechaVencimientoHasta=${soloFecha}`;
709
+ }
710
+ const response = await (0, functions_1.apiRequest)(url, {
508
711
  method: 'GET',
509
712
  headers,
510
713
  });
511
- return [this.helpers.returnJsonArray(dataListBranches)];
714
+ return [this.helpers.returnJsonArray(response)];
715
+ }
716
+ catch (error) {
717
+ const errorMessage = error?.response?.data?.Message || error.message || 'Error desconocido';
718
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), `Error obteniendo saldo para cliente ${clientId}: ${errorMessage}`);
719
+ }
720
+ }
721
+ case 'pedidoVentaActividad': {
722
+ const pedidoID = this.getNodeParameter('id', 0);
723
+ try {
724
+ const dataActividad = await (0, functions_1.apiRequest)(`${centumUrl}/PedidosVenta/${pedidoID}`, { ...headers });
725
+ return [this.helpers.returnJsonArray(dataActividad)];
512
726
  }
513
727
  catch (error) {
514
728
  console.log(error);
515
729
  const errorMessage = error?.response?.data?.Message || error.message || 'Error desconocido';
516
730
  throw new n8n_workflow_1.NodeOperationError(this.getNode(), errorMessage);
517
731
  }
518
- case 'generarProductosWoo':
519
- const data = this.getInputData();
520
- const json = (0, functions_1.createJsonProducts)(data);
521
- return [this.helpers.returnJsonArray(json)];
522
- case 'obtenerProductos':
732
+ }
733
+ case 'procesarImagenes': {
734
+ const dataImages = this.getNodeParameter('dataImg', 0);
735
+ const db = this.getNodeParameter('lastModifiedImg', 0);
736
+ const result = [];
737
+ for (let i = 0; i < dataImages.length; i++) {
738
+ const element = dataImages[i];
739
+ for (let j = 0; j < element.json.images?.length; j++) {
740
+ const currentData = element.json.images[j];
741
+ const currentInfoImage = element.json.infoImages[j];
742
+ const articleInDB = db.find((dbData) => dbData.articleId === element.json.idArticulo);
743
+ if (!articleInDB) {
744
+ result.push({ json: {}, binary: currentData });
745
+ }
746
+ else {
747
+ const currentImageInDB = articleInDB.dataImage.find((dataImageDB) => dataImageDB.orderNumber === currentInfoImage.orderNumber);
748
+ if (currentImageInDB?.lastModified !== currentInfoImage.lastModified) {
749
+ result.push({ json: {}, binary: currentData });
750
+ }
751
+ }
752
+ }
753
+ }
754
+ if (result.length === 0) {
755
+ result.push([]);
756
+ }
757
+ return [this.helpers.returnJsonArray(result)];
758
+ }
759
+ case 'promocionesCliente': {
760
+ const clientIdParam = this.getNodeParameter('clienteId', 0);
761
+ const documentDate = this.getNodeParameter('documentDate', 0);
762
+ const diaSemana = this.getNodeParameter('diaSemana', 0);
763
+ const clientId = Number(clientIdParam);
764
+ if (!documentDate) {
765
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'documentDate es requerido');
766
+ }
767
+ const formattedDocumentDate = String(documentDate).split('T')[0];
523
768
  try {
524
- const payload = {
525
- "IdCliente": 47924,
526
- "FechaDocumento": "2024-05-31",
527
- "Habilitado": true,
528
- "ActivoWeb": true
769
+ const body = {
770
+ FechaDocumento: formattedDocumentDate,
771
+ IdsCliente: clientId,
772
+ DiaSemana: diaSemana || '',
529
773
  };
530
- const dataProductos = await (0, functions_1.apiRequest)(`${centumUrl}/Articulos/Venta`, {
774
+ const response = await (0, functions_1.apiRequest)(`${centumUrl}/PromocionesComerciales/FiltrosPromocionComercial`, {
531
775
  method: 'POST',
532
- body: payload,
533
- headers
776
+ headers,
777
+ body,
534
778
  });
535
- const items = dataProductos.Articulos?.Items || [];
536
- const formateoObjeto = items.map((item) => ({
537
- IdArticulo: item.IdArticulo,
538
- Codigo: item.Codigo,
539
- Nombre: item.Nombre,
540
- NombreFantasia: item.NombreFantasia,
541
- Habilitado: item.Habilitado,
542
- ActivoWeb: item.ActivoWeb,
543
- Precio: item.Precio,
544
- FechaUltimaActualizacionPrecio: item.FechaUltimaActualizacionPrecio,
545
- StockDisponible: item.StockDisponible,
546
- Rubro: item.Rubro ? {
547
- IdRubro: item.Rubro.IdRubro,
548
- Codigo: item.Rubro.Codigo,
549
- Nombre: item.Rubro.Nombre
550
- } : null,
551
- SubRubro: item.SubRubro ? {
552
- IdSubRubro: item.SubRubro.IdSubRubro,
553
- Codigo: item.SubRubro.Codigo,
554
- Nombre: item.SubRubro.Nombre,
555
- IdRubro: item.SubRubro.IdRubro
556
- } : null,
557
- CategoriaArticulo: item.CategoriaArticulo ? {
558
- IdCategoriaArticulo: item.CategoriaArticulo.IdCategoriaArticulo,
559
- Codigo: item.CategoriaArticulo.Codigo,
560
- Nombre: item.CategoriaArticulo.Nombre,
561
- IdSubRubro: item.CategoriaArticulo.IdSubRubro
562
- } : null
563
- }));
564
- return [this.helpers.returnJsonArray(formateoObjeto)];
779
+ if (!response || typeof response !== 'object') {
780
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Respuesta inválida del servidor');
781
+ }
782
+ if (response.Items && Array.isArray(response.Items)) {
783
+ return [this.helpers.returnJsonArray(response.Items)];
784
+ }
785
+ return [this.helpers.returnJsonArray(response)];
565
786
  }
566
787
  catch (error) {
567
- console.log(error);
788
+ console.log('Error en solicitud de promociones para el cliente:', error);
568
789
  const errorMessage = error?.response?.data?.Message || error.message || 'Error desconocido';
569
- throw new n8n_workflow_1.NodeOperationError(this.getNode(), errorMessage);
790
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), `Error obteniendo promociones para el cliente ${clientId}: \n ${errorMessage}`);
570
791
  }
571
- case "provinciasLista": {
792
+ }
793
+ case 'provinciasLista': {
572
794
  const idPais = this.getNodeParameter('idPais', 0, '');
573
795
  try {
574
796
  const queryParams = {};
@@ -580,7 +802,7 @@ class Centum {
580
802
  headers,
581
803
  queryParams,
582
804
  });
583
- return [this.helpers.returnJsonArray(provincias.map(p => ({ ...p })))];
805
+ return [this.helpers.returnJsonArray(provincias.map((p) => ({ ...p })))];
584
806
  }
585
807
  catch (error) {
586
808
  console.log(error);
@@ -588,19 +810,13 @@ class Centum {
588
810
  throw new n8n_workflow_1.NodeOperationError(this.getNode(), errorMessage);
589
811
  }
590
812
  }
591
- case "departamentosLista": {
592
- const idProvincia = this.getNodeParameter('idProvincia', 0, '');
813
+ case 'sucursalesFisicas': {
593
814
  try {
594
- const queryParams = {};
595
- if (idProvincia) {
596
- queryParams.idProvincia = idProvincia;
597
- }
598
- const departamentos = await (0, functions_1.apiRequest)(`${centumUrl}/Departamentos`, {
815
+ const dataListBranches = await (0, functions_1.apiRequest)(`${centumUrl}/SucursalesFisicas`, {
599
816
  method: 'GET',
600
817
  headers,
601
- queryParams,
602
818
  });
603
- return [this.helpers.returnJsonArray(departamentos.map(d => ({ ...d })))];
819
+ return [this.helpers.returnJsonArray(dataListBranches)];
604
820
  }
605
821
  catch (error) {
606
822
  console.log(error);
@@ -608,8 +824,9 @@ class Centum {
608
824
  throw new n8n_workflow_1.NodeOperationError(this.getNode(), errorMessage);
609
825
  }
610
826
  }
611
- default:
612
- return [this.helpers.returnJsonArray([])];
827
+ default: {
828
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), `Operación no implementada: ${resource}`);
829
+ }
613
830
  }
614
831
  }
615
832
  }