n8n-nodes-centum 0.2.11 → 0.2.13

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