@zauru-sdk/utils 1.0.6 → 1.0.8

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 (74) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/index.d.ts +23 -2
  3. package/dist/index.js +23 -2
  4. package/dist/zauru/automatic-number.utils.d.ts +9 -0
  5. package/dist/zauru/automatic-number.utils.js +24 -0
  6. package/dist/zauru/bitacora-edicion-masiva.utils.d.ts +23 -0
  7. package/dist/zauru/bitacora-edicion-masiva.utils.js +50 -0
  8. package/dist/zauru/bundles.utils.d.ts +39 -0
  9. package/dist/zauru/bundles.utils.js +160 -0
  10. package/dist/zauru/cases.utils.d.ts +9 -0
  11. package/dist/zauru/cases.utils.js +17 -0
  12. package/dist/zauru/consolidated-history.utils.d.ts +24 -0
  13. package/dist/zauru/consolidated-history.utils.js +52 -0
  14. package/dist/zauru/costos-items.utils.d.ts +87 -0
  15. package/dist/zauru/costos-items.utils.js +601 -0
  16. package/dist/zauru/deliveries.utils.d.ts +17 -0
  17. package/dist/zauru/deliveries.utils.js +46 -0
  18. package/dist/zauru/discharges-histsory.utils.d.ts +24 -0
  19. package/dist/zauru/discharges-histsory.utils.js +46 -0
  20. package/dist/zauru/employees.utils.d.ts +16 -0
  21. package/dist/zauru/employees.utils.js +39 -0
  22. package/dist/zauru/form.utils.d.ts +34 -0
  23. package/dist/zauru/form.utils.js +152 -0
  24. package/dist/zauru/invoices.utils.d.ts +22 -0
  25. package/dist/zauru/invoices.utils.js +79 -0
  26. package/dist/zauru/items.utils.d.ts +52 -0
  27. package/dist/zauru/items.utils.js +152 -0
  28. package/dist/zauru/lotes.utils.d.ts +31 -0
  29. package/dist/zauru/lotes.utils.js +307 -0
  30. package/dist/zauru/motivos-rechazo.utils.d.ts +10 -0
  31. package/dist/zauru/motivos-rechazo.utils.js +18 -0
  32. package/dist/zauru/payees.utils.d.ts +42 -0
  33. package/dist/zauru/payees.utils.js +128 -0
  34. package/dist/zauru/profiles.utils.d.ts +15 -0
  35. package/dist/zauru/profiles.utils.js +37 -0
  36. package/dist/zauru/providers.utils.d.ts +13 -0
  37. package/dist/zauru/providers.utils.js +36 -0
  38. package/dist/zauru/purchase-orders.utils.d.ts +114 -0
  39. package/dist/zauru/purchase-orders.utils.js +376 -0
  40. package/dist/zauru/shipments.utils.d.ts +21 -0
  41. package/dist/zauru/shipments.utils.js +90 -0
  42. package/dist/zauru/specialItem.utils.d.ts +34 -0
  43. package/dist/zauru/specialItem.utils.js +62 -0
  44. package/dist/zauru/templates.utils.d.ts +49 -0
  45. package/dist/zauru/templates.utils.js +93 -0
  46. package/dist/zauru/tiposMuestra.utils.d.ts +34 -0
  47. package/dist/zauru/tiposMuestra.utils.js +62 -0
  48. package/dist/zauru/webapp-tables.utils.d.ts +16 -0
  49. package/dist/zauru/webapp-tables.utils.js +51 -0
  50. package/package.json +6 -6
  51. package/src/index.ts +23 -0
  52. package/src/zauru/bitacora-edicion-masiva.utils.ts +99 -0
  53. package/src/zauru/bundles.utils.ts +251 -0
  54. package/src/zauru/cases.utils.ts +31 -0
  55. package/src/zauru/consolidated-history.utils.ts +102 -0
  56. package/src/zauru/costos-items.utils.ts +865 -0
  57. package/src/zauru/deliveries.utils.ts +77 -0
  58. package/src/zauru/discharges-histsory.utils.ts +105 -0
  59. package/src/zauru/employees.utils.ts +59 -0
  60. package/src/zauru/form.utils.ts +243 -0
  61. package/src/zauru/invoices.utils.ts +114 -0
  62. package/src/zauru/items.utils.ts +269 -0
  63. package/src/zauru/lotes.utils.ts +411 -0
  64. package/src/zauru/motivos-rechazo.utils.ts +47 -0
  65. package/src/zauru/payees.utils.ts +213 -0
  66. package/src/zauru/profiles.utils.ts +44 -0
  67. package/src/zauru/providers.utils.ts +67 -0
  68. package/src/zauru/purchase-orders.utils.ts +594 -0
  69. package/src/zauru/shipments.utils.ts +139 -0
  70. package/src/zauru/specialItem.utils.ts +126 -0
  71. package/src/zauru/templates.utils.ts +199 -0
  72. package/src/zauru/tiposMuestra.utils.ts +136 -0
  73. package/src/zauru/webapp-tables.utils.ts +94 -0
  74. /package/src/{automatic-number.utils.ts → zauru/automatic-number.utils.ts} +0 -0
@@ -0,0 +1,865 @@
1
+ import type { Session } from "@remix-run/node";
2
+ import {
3
+ handlePossibleAxiosErrors,
4
+ localDateToUSDate,
5
+ } from "@zauru-sdk/common";
6
+ import {
7
+ SpecialItem,
8
+ WebAppRowGraphQL,
9
+ RowDataType,
10
+ AxiosUtilsResponse,
11
+ CostoSemanalSpecialItem,
12
+ PurchaseOrderCosto,
13
+ CostoSemanal,
14
+ BitacoraCostosItems,
15
+ WebAppTableUpdateResponse,
16
+ } from "@zauru-sdk/types";
17
+ import moment from "moment";
18
+ import { createSpecialItem, updateSpecialItem } from "./specialItem.utils.js";
19
+ import { createWebAppTableRegister, getPurchasesList, getVariablesByName, getWebAppTableRegisters, updateWebAppTableRegister } from "@zauru-sdk/services";
20
+ import { updatePurchaseItemPrice } from "./purchase-orders.utils.js";
21
+
22
+ /**
23
+ *
24
+ * @param headers
25
+ * @param session
26
+ * @param configuration
27
+ * @param specialItems
28
+ */
29
+ export const guardarConfiguracionProductosEspeciales = (
30
+ headers: any,
31
+ session: Session,
32
+ configuration: (RowDataType & SpecialItem)[],
33
+ specialItems?: WebAppRowGraphQL<SpecialItem>[]
34
+ ): Promise<AxiosUtilsResponse<boolean>> => {
35
+ return handlePossibleAxiosErrors(async () => {
36
+ specialItems?.forEach(async (x) => {
37
+ if (!configuration.some((y) => y.id === x.id)) {
38
+ //Elimino los que ya no están
39
+ const response = await updateSpecialItem(
40
+ headers,
41
+ session,
42
+ x.id.toString(),
43
+ {
44
+ ...x.data,
45
+ fechaEliminacion: moment().format("DD/MM/YYYY HH:mm:ss"),
46
+ }
47
+ );
48
+ if (response.error) {
49
+ throw new Error(
50
+ `Ocurrió un error al intentar eliminar un item especial. - ${
51
+ response.userMsg ?? ""
52
+ }`
53
+ );
54
+ }
55
+ }
56
+ });
57
+
58
+ configuration.forEach(async (x) => {
59
+ if (typeof x.id === "string") {
60
+ //Creación
61
+ const response = await createSpecialItem(headers, session, {
62
+ ...x,
63
+ });
64
+ if (response.error) {
65
+ throw new Error(
66
+ `Ocurrió un error al intentar guardar la configuración de items especiales. - ${
67
+ response.userMsg ?? ""
68
+ }`
69
+ );
70
+ }
71
+ } else {
72
+ //actualización
73
+ const response = await updateSpecialItem(
74
+ headers,
75
+ session,
76
+ x.id.toString(),
77
+ {
78
+ ...x,
79
+ }
80
+ );
81
+ if (response.error) {
82
+ throw new Error(
83
+ `Ocurrió un error al intentar actualizar un item especial. - ${
84
+ response.userMsg ?? ""
85
+ }`
86
+ );
87
+ }
88
+ }
89
+ });
90
+ return true;
91
+ });
92
+ };
93
+
94
+ /**
95
+ *
96
+ * @returns
97
+ */
98
+ export const obtenerSemanaAnterior = () => {
99
+ const hoy = moment();
100
+
101
+ const semanaAnterior = hoy.clone().subtract(7, "days");
102
+
103
+ const fechaInicio = semanaAnterior.clone().startOf("isoWeek");
104
+ const fechaInicioFormateada = fechaInicio.format("YYYY/MM/DD");
105
+
106
+ const fechaFin = fechaInicio.clone().endOf("isoWeek");
107
+ const fechaFinFormateada = fechaFin.format("YYYY/MM/DD");
108
+
109
+ const label =
110
+ "Semana anterior, del Lunes " +
111
+ fechaInicio.date() +
112
+ " al Domingo " +
113
+ fechaFin.date() +
114
+ ", de " +
115
+ fechaInicio.format("MMMM") +
116
+ " de " +
117
+ fechaInicio.year();
118
+
119
+ return {
120
+ fechaInicio: fechaInicioFormateada,
121
+ fechaFin: fechaFinFormateada,
122
+ label: label,
123
+ getDay: (dayIndex: number) => {
124
+ if (dayIndex < 0 || dayIndex > 6) {
125
+ throw new Error("Day index must be between 0 (Monday) and 6 (Sunday).");
126
+ }
127
+
128
+ const targetDate = fechaInicio.clone().add(dayIndex, "days");
129
+ return targetDate.format("YYYY/MM/DD");
130
+ },
131
+ };
132
+ };
133
+
134
+ const getPriceByDate = (
135
+ date: string,
136
+ fechas: {
137
+ lunes: string;
138
+ martes: string;
139
+ miercoles: string;
140
+ jueves: string;
141
+ viernes: string;
142
+ sabado: string;
143
+ domingo: string;
144
+ },
145
+ costo?: CostoSemanal | CostoSemanalSpecialItem
146
+ ) => {
147
+ const originDate = new Date(date).setHours(0, 0, 0, 0);
148
+ const lunesDate = new Date(fechas.lunes).setHours(0, 0, 0, 0);
149
+ const martesDate = new Date(fechas.martes).setHours(0, 0, 0, 0);
150
+ const miercolesDate = new Date(fechas.miercoles).setHours(0, 0, 0, 0);
151
+ const juevesDate = new Date(fechas.jueves).setHours(0, 0, 0, 0);
152
+ const viernesDate = new Date(fechas.viernes).setHours(0, 0, 0, 0);
153
+ const sabadoDate = new Date(fechas.sabado).setHours(0, 0, 0, 0);
154
+ const domingoDate = new Date(fechas.domingo).setHours(0, 0, 0, 0);
155
+
156
+ if (originDate === lunesDate || originDate === martesDate) {
157
+ return costo?.lunMar ?? 1;
158
+ } else if (originDate === miercolesDate || originDate === juevesDate) {
159
+ return costo?.mieJue ?? 1;
160
+ } else if (
161
+ originDate === viernesDate ||
162
+ originDate === sabadoDate ||
163
+ originDate === domingoDate
164
+ ) {
165
+ return costo?.vieSabDom ?? 1;
166
+ } else {
167
+ return 1;
168
+ }
169
+ };
170
+
171
+ const logTotal = (total: number) => {
172
+ console.log(
173
+ "========================================================================"
174
+ );
175
+ console.log(
176
+ "========================================================================"
177
+ );
178
+ console.log(
179
+ "========================================================================"
180
+ );
181
+ console.log(
182
+ "========================================================================"
183
+ );
184
+ console.log(`A PUNTO DE ACTUALIZAR: ${total} órdenes de compra`);
185
+ console.log(
186
+ "========================================================================"
187
+ );
188
+ console.log(
189
+ "========================================================================"
190
+ );
191
+ console.log(
192
+ "========================================================================"
193
+ );
194
+ console.log(
195
+ "========================================================================"
196
+ );
197
+ };
198
+
199
+ /**
200
+ * updateOneItemPrice
201
+ * @param headers
202
+ * @param session
203
+ * @param body
204
+ * @returns
205
+ */
206
+ export async function updateOneItemPrice(
207
+ headers: any,
208
+ session: Session,
209
+ body: {
210
+ fechaInicio: string;
211
+ fechaFin: string;
212
+ item: number;
213
+ price: number;
214
+ }
215
+ ): Promise<AxiosUtilsResponse<any>> {
216
+ return handlePossibleAxiosErrors(async () => {
217
+ //PASO 1
218
+ //Obtengo todas las órdenes de compra dentro del rango de fechas
219
+ const fechaInicio = localDateToUSDate(body.fechaInicio);
220
+ const fechaFin = localDateToUSDate(body.fechaFin);
221
+ console.log(
222
+ `==============================> OBTENIENDO ÓRDENES DE COMPRA EN EL RANGO ${fechaInicio} - ${fechaFin}`
223
+ );
224
+ const allPurchases = await getPurchasesList(headers, session, {
225
+ fechaInicio: fechaInicio,
226
+ fechaFin: fechaFin,
227
+ });
228
+ console.log("ORDENES DE COMPRA OBTENIDAS: ", allPurchases.data?.length);
229
+
230
+ if (allPurchases.error || !allPurchases.data) {
231
+ //TODO: REGISTRAR EL FALLO EN LA ACTUALIZACIÓN
232
+ return "error";
233
+ }
234
+
235
+ //PASO 2
236
+ //Por cada órden de compra, voy a buscar su item para verificar el precio a colocarle en el día que fue emitida
237
+ //Obtengo todos los id's de las órdenes de compra en ese rango de fechas
238
+ const costosWithPurchaseIds: PurchaseOrderCosto[] = [];
239
+ const purchaseIterations = allPurchases.data.filter((x) =>
240
+ x.purchase_order_details.some((y) => y.item_id === body.item)
241
+ );
242
+ for (const purchase of purchaseIterations) {
243
+ const purchase_order_details = purchase.purchase_order_details.map(
244
+ (details) => {
245
+ return {
246
+ id: details.id,
247
+ item_id: details.item_id,
248
+ unit_cost: body.price,
249
+ };
250
+ }
251
+ );
252
+
253
+ costosWithPurchaseIds.push({
254
+ id: purchase.id,
255
+ fecha: purchase.created_at,
256
+ finalizado: true,
257
+ msgResultado: "",
258
+ purchase_order_details,
259
+ });
260
+ }
261
+
262
+ //PASO 3
263
+ //Editar los precios de todas las órdenes de compra
264
+ logTotal(costosWithPurchaseIds.length);
265
+ for (let i = 0; i < costosWithPurchaseIds.length; i++) {
266
+ const x = costosWithPurchaseIds[i];
267
+ console.log(
268
+ `==============================> ACTUALIZANDO ÓRDEN DE COMPRA: ID: ${
269
+ x.id
270
+ } PRICE: ${x.purchase_order_details
271
+ .map((x) => x.unit_cost)
272
+ .join(",")} ID_ITEM: ${x.purchase_order_details
273
+ .map((x) => x.item_id)
274
+ .join(",")}`
275
+ );
276
+
277
+ const updateResponse = await updatePurchaseItemPrice(
278
+ headers,
279
+ {
280
+ purchase_order_details_attributes: {
281
+ ...x.purchase_order_details
282
+ .map((detail, index) => {
283
+ return {
284
+ [`${index}`]: {
285
+ id: detail.id,
286
+ item_id: detail.item_id,
287
+ unit_cost: detail.unit_cost,
288
+ },
289
+ };
290
+ })
291
+ .reduce((acc, curr) => Object.assign(acc, curr), {}),
292
+ } as any,
293
+ },
294
+ x.id
295
+ );
296
+ if (updateResponse.error) {
297
+ // Si hay error
298
+ costosWithPurchaseIds[i].finalizado = false;
299
+ costosWithPurchaseIds[i].msgResultado =
300
+ updateResponse.userMsg ?? JSON.stringify(updateResponse);
301
+ }
302
+ }
303
+
304
+ //PASO 4
305
+ //Guardo la bitácora de cambios
306
+ console.log(
307
+ `==============================> GUARDANDO BITÁCORA DE CAMBIOS`
308
+ );
309
+ const response = await saveBitacoraCostos(headers, session, {
310
+ costosEspeciales: [
311
+ { specialItemId: body.item, lunMar: 1, mieJue: 1, vieSabDom: 1 },
312
+ ],
313
+ accion: "Costos individualmente",
314
+ fechaCreacion: moment().format("DD/MM/YYYY HH:mm:ss"),
315
+ fechas: {
316
+ lunes: "",
317
+ martes: "",
318
+ miercoles: "",
319
+ jueves: "",
320
+ viernes: "",
321
+ sabado: "",
322
+ domingo: "",
323
+ },
324
+ modificadoPor: session.get("name"),
325
+ costos: [{ item: body.item, lunMar: 1, mieJue: 1, vieSabDom: 1 }],
326
+ costosActualizados: costosWithPurchaseIds,
327
+ costosEspecialesActualizados: [],
328
+ });
329
+
330
+ if (response.error || !response.data) {
331
+ throw new Error(
332
+ response.userMsg ??
333
+ "Respuesta vacía de saveBitacoraCostos en updateOneItemPrice"
334
+ );
335
+ }
336
+
337
+ return response.data;
338
+ });
339
+ }
340
+
341
+ /**
342
+ * changePricesInit
343
+ * @param headers
344
+ * @param session
345
+ * @param specialItems
346
+ * @param body
347
+ * @returns
348
+ */
349
+ export async function changePricesInit(
350
+ headers: any,
351
+ session: Session,
352
+ specialItems: WebAppRowGraphQL<SpecialItem>[],
353
+ body: BitacoraCostosItems
354
+ ): Promise<AxiosUtilsResponse<WebAppTableUpdateResponse>> {
355
+ return handlePossibleAxiosErrors(async () => {
356
+ //PASO 1
357
+ //Obtengo todas las órdenes de compra dentro del rango de fechas
358
+ console.log("=======================> FECHAS: ", body.fechas);
359
+ const fechaInicio = body.fechas.lunes;
360
+ const fechaFin = body.fechas.domingo;
361
+ console.log(
362
+ `==============================> OBTENIENDO ÓRDENES DE COMPRA EN EL RANGO ${fechaInicio} - ${fechaFin}`
363
+ );
364
+ const allPurchases = await getPurchasesList(headers, session, {
365
+ fechaInicio: fechaInicio,
366
+ fechaFin: fechaFin,
367
+ });
368
+
369
+ if (allPurchases.error || !allPurchases.data) {
370
+ throw new Error(
371
+ `Error al ubicar las órdenes de compra en el rango de fechas establecido: ${allPurchases.userMsg}`
372
+ );
373
+ }
374
+ //PASO 2
375
+ //Por cada órden de compra, voy a buscar su item para verificar el precio a colocarle en el día que fue emitida
376
+ //Obtengo todos los id's de las órdenes de compra en ese rango de fechas
377
+ const costosWithPurchaseIds: PurchaseOrderCosto[] = [];
378
+ const costosEspecialesWithPurchaseIds: PurchaseOrderCosto[] = []; //Para las verduras especiales
379
+
380
+ ForPrincipal: for (const purchase of allPurchases.data) {
381
+ //Pregunto si la órden de compra coincide con alguno de los casos especiales
382
+ for (const costoEspecial of body.costosEspeciales) {
383
+ //Ubico la configuración de item especial.
384
+ const specialItem = specialItems.find(
385
+ (x) => x.id === costoEspecial.specialItemId
386
+ );
387
+ for (const details of purchase.purchase_order_details) {
388
+ //Tengo que preguntar por proveedor, region, categoría de proveedores, tipo e item.
389
+ if (
390
+ specialItem?.data.region === purchase.incoterm_destination &&
391
+ specialItem?.data?.tipo === purchase.reference &&
392
+ specialItem.data.item === details.item_id
393
+ ) {
394
+ const costo = body.costosEspeciales.find(
395
+ (x) => x.specialItemId === specialItem.id
396
+ );
397
+ const price = getPriceByDate(
398
+ purchase.created_at,
399
+ body.fechas,
400
+ costo
401
+ );
402
+ costosWithPurchaseIds.push({
403
+ id: purchase.id,
404
+ fecha: purchase.created_at,
405
+ purchase_order_details: [
406
+ {
407
+ id: details.id,
408
+ item_id: details.item_id,
409
+ unit_cost: price,
410
+ },
411
+ ],
412
+ });
413
+ continue ForPrincipal;
414
+ }
415
+ }
416
+ }
417
+
418
+ //SI SIGUE AQUÍ, ES POR QUE NO ES VERDURA ESPECIAL
419
+ const purchase_order_details = purchase.purchase_order_details.map(
420
+ (details) => {
421
+ const costo = body.costos.find((x) => x.item === details.item_id);
422
+ const price = getPriceByDate(purchase.created_at, body.fechas, costo);
423
+ return { id: details.id, item_id: details.item_id, unit_cost: price };
424
+ }
425
+ );
426
+
427
+ costosWithPurchaseIds.push({
428
+ id: purchase.id,
429
+ fecha: purchase.created_at,
430
+ purchase_order_details,
431
+ });
432
+ }
433
+
434
+ //PASO 5
435
+ //Guardo la bitácora de cambios
436
+ console.log(
437
+ `==============================> GUARDANDO BITÁCORA DE CAMBIOS`
438
+ );
439
+ const response = await saveBitacoraCostos(headers, session, {
440
+ ...body,
441
+ costosActualizados: costosWithPurchaseIds,
442
+ costosEspecialesActualizados: costosEspecialesWithPurchaseIds,
443
+ });
444
+
445
+ if (response.error || !response.data) {
446
+ const errorMsg =
447
+ `Error al guardar la bitácora de costos ${response.userMsg}` ??
448
+ "Respuesta vacía de saveBitacoraCostos en changePrices";
449
+ console.error(errorMsg);
450
+ throw new Error(errorMsg);
451
+ }
452
+
453
+ return response.data;
454
+ });
455
+ }
456
+
457
+ /**
458
+ * changePrice
459
+ * @param headers
460
+ * @param session
461
+ * @param body
462
+ * @returns
463
+ */
464
+ export async function changePrice(
465
+ headers: any,
466
+ costo: PurchaseOrderCosto
467
+ ): Promise<PurchaseOrderCosto> {
468
+ const x = costo;
469
+
470
+ const msgActualizando = `==============================> ACTUALIZANDO ÓRDEN DE COMPRA: ID: ${
471
+ x.id
472
+ } PRICE: ${x.purchase_order_details
473
+ .map((x) => x.unit_cost)
474
+ .join(",")} ID_ITEM: ${x.purchase_order_details
475
+ .map((x) => x.item_id)
476
+ .join(",")}`;
477
+
478
+ const body = {
479
+ purchase_order_details_attributes: {
480
+ ...x.purchase_order_details
481
+ .map((detail, index) => {
482
+ return {
483
+ [`${index}`]: {
484
+ id: detail.id,
485
+ item_id: detail.item_id,
486
+ unit_cost: detail.unit_cost,
487
+ },
488
+ };
489
+ })
490
+ .reduce((acc, curr) => Object.assign(acc, curr), {}),
491
+ } as any,
492
+ };
493
+ console.log(msgActualizando);
494
+ const updateResponse = await updatePurchaseItemPrice(headers, body, x.id);
495
+ if (updateResponse.error) {
496
+ // Si hay error
497
+ costo.finalizado = false;
498
+ costo.msgResultado =
499
+ updateResponse.userMsg ??
500
+ `Ocurrió un error al editar la órden de compra ${JSON.stringify(
501
+ updateResponse
502
+ )}`;
503
+ } else {
504
+ costo.finalizado = true;
505
+ }
506
+ return costo;
507
+ }
508
+
509
+ /**
510
+ * changePrices
511
+ * @param headers
512
+ * @param session
513
+ * @param body
514
+ * @returns
515
+ */
516
+ export async function changePrices(
517
+ headers: any,
518
+ session: Session,
519
+ bitacora: BitacoraCostosItems,
520
+ id_bitacora: string
521
+ ): Promise<AxiosUtilsResponse<any>> {
522
+ return handlePossibleAxiosErrors(async () => {
523
+ const costosWithPurchaseIds = bitacora.costosActualizados;
524
+ const costosEspecialesWithPurchaseIds =
525
+ bitacora.costosEspecialesActualizados;
526
+
527
+ //PASO 3
528
+ //Editar los precios de todas las órdenes de compra
529
+ logTotal(costosWithPurchaseIds.length);
530
+ for (let i = 0; i < costosWithPurchaseIds.length; i++) {
531
+ const x = costosWithPurchaseIds[i];
532
+ const msgActualizando = `==============================> ACTUALIZANDO ÓRDEN DE COMPRA: ID: ${
533
+ x.id
534
+ } PRICE: ${x.purchase_order_details
535
+ .map((x) => x.unit_cost)
536
+ .join(",")} ID_ITEM: ${x.purchase_order_details
537
+ .map((x) => x.item_id)
538
+ .join(",")}`;
539
+ console.log(msgActualizando);
540
+ const updateResponse = await updatePurchaseItemPrice(
541
+ headers,
542
+ {
543
+ purchase_order_details_attributes: {
544
+ ...x.purchase_order_details
545
+ .map((detail, index) => {
546
+ return {
547
+ [`${index}`]: {
548
+ id: detail.id,
549
+ item_id: detail.item_id,
550
+ unit_cost: detail.unit_cost,
551
+ },
552
+ };
553
+ })
554
+ .reduce((acc, curr) => Object.assign(acc, curr), {}),
555
+ } as any,
556
+ },
557
+ x.id
558
+ );
559
+ if (updateResponse.error) {
560
+ // Si hay error
561
+ costosWithPurchaseIds[i].finalizado = false;
562
+ costosWithPurchaseIds[i].msgResultado =
563
+ updateResponse.userMsg ?? JSON.stringify(updateResponse);
564
+ }
565
+ }
566
+
567
+ //PASO 4
568
+ //EDITO LAS ORDENES DE COMPRA PARA ITEMS ESPECIALES
569
+ logTotal(costosEspecialesWithPurchaseIds.length);
570
+ for (let i = 0; i < costosEspecialesWithPurchaseIds.length; i++) {
571
+ const x = costosEspecialesWithPurchaseIds[i];
572
+ console.log(
573
+ `==============================> ACTUALIZANDO ÓRDEN DE COMPRA (ESPECIAL): ID: ${
574
+ x.id
575
+ } PRICE: ${x.purchase_order_details
576
+ .map((x) => x.unit_cost)
577
+ .join(",")} ID_ITEM: ${x.purchase_order_details
578
+ .map((x) => x.item_id)
579
+ .join(",")}`
580
+ );
581
+ const updateResponse = await updatePurchaseItemPrice(
582
+ headers,
583
+ {
584
+ purchase_order_details_attributes: {
585
+ ...x.purchase_order_details
586
+ .map((detail, index) => {
587
+ return {
588
+ [`${index}`]: {
589
+ id: detail.id,
590
+ item_id: detail.item_id,
591
+ unit_cost: detail.unit_cost,
592
+ },
593
+ };
594
+ })
595
+ .reduce((acc, curr) => Object.assign(acc, curr), {}),
596
+ } as any,
597
+ },
598
+ x.id
599
+ );
600
+ if (updateResponse.error) {
601
+ // Si hay error
602
+ costosEspecialesWithPurchaseIds[i].finalizado = false;
603
+ costosEspecialesWithPurchaseIds[i].msgResultado =
604
+ updateResponse.userMsg ?? JSON.stringify(updateResponse);
605
+ }
606
+ }
607
+
608
+ //PASO 5
609
+ //Actualizo la bitácora de cambios
610
+ console.log(
611
+ `==============================> GUARDANDO BITÁCORA DE CAMBIOS`
612
+ );
613
+ const response = await updateBitacoraCostos(
614
+ headers,
615
+ session,
616
+ {
617
+ ...bitacora,
618
+ costosActualizados: costosWithPurchaseIds,
619
+ costosEspecialesActualizados: costosEspecialesWithPurchaseIds,
620
+ },
621
+ id_bitacora
622
+ );
623
+
624
+ if (response.error || !response.data) {
625
+ const errorMsg =
626
+ response.userMsg ?? "Respuesta vacía de updateBitacora en changePrices";
627
+ console.error(errorMsg);
628
+ throw new Error(errorMsg);
629
+ }
630
+
631
+ return response.data;
632
+ });
633
+ }
634
+
635
+ /**
636
+ * corregirCostos
637
+ * @param headers
638
+ * @param session
639
+ * @param costos
640
+ * @returns
641
+ */
642
+ export async function corregirCostos(
643
+ headers: any,
644
+ session: Session,
645
+ costos: PurchaseOrderCosto[],
646
+ costosEspeciales: PurchaseOrderCosto[]
647
+ ) {
648
+ return handlePossibleAxiosErrors(async () => {
649
+ //PASO 1
650
+ //Hago una copia
651
+ const costosTemp = costos;
652
+ const costosEspecialesTemp = costosEspeciales;
653
+ //PASO 2
654
+ //Editar los precios de todas las órdenes de compra
655
+ logTotal(costosTemp.length);
656
+ for (let i = 0; i < costosTemp.length; i++) {
657
+ const x = costosTemp[i];
658
+ console.log(
659
+ `==============================> ACTUALIZANDO ÓRDEN DE COMPRA: ID: ${
660
+ x.id
661
+ } PRICE: ${x.purchase_order_details
662
+ .map((x) => x.unit_cost)
663
+ .join(",")} ID_ITEM: ${x.purchase_order_details
664
+ .map((x) => x.item_id)
665
+ .join(",")}`
666
+ );
667
+
668
+ const updateResponse = await updatePurchaseItemPrice(
669
+ headers,
670
+ {
671
+ purchase_order_details_attributes: {
672
+ ...x.purchase_order_details
673
+ .map((detail, index) => {
674
+ return {
675
+ [`${index}`]: {
676
+ id: detail.id,
677
+ item_id: detail.item_id,
678
+ unit_cost: detail.unit_cost,
679
+ },
680
+ };
681
+ })
682
+ .reduce((acc, curr) => Object.assign(acc, curr), {}),
683
+ } as any,
684
+ },
685
+ x.id
686
+ );
687
+
688
+ if (!updateResponse.error) {
689
+ // Si hay error
690
+ costosTemp[i].finalizado = true;
691
+ } else {
692
+ costosTemp[i].finalizado = false;
693
+ costosTemp[i].msgResultado =
694
+ updateResponse.userMsg ?? JSON.stringify(updateResponse);
695
+ }
696
+ }
697
+
698
+ //PASO 3
699
+ //Editar los precios de todas las órdenes de compra de precios especiales
700
+ logTotal(costosEspecialesTemp.length);
701
+ for (let i = 0; i < costosEspecialesTemp.length; i++) {
702
+ const x = costosEspecialesTemp[i];
703
+ console.log(
704
+ `==============================> ACTUALIZANDO ÓRDEN DE COMPRA (ESPECIAL): ID: ${
705
+ x.id
706
+ } PRICE: ${x.purchase_order_details
707
+ .map((x) => x.unit_cost)
708
+ .join(",")} ID_ITEM: ${x.purchase_order_details
709
+ .map((x) => x.item_id)
710
+ .join(",")}`
711
+ );
712
+
713
+ const updateResponse = await updatePurchaseItemPrice(
714
+ headers,
715
+ {
716
+ purchase_order_details_attributes: {
717
+ ...x.purchase_order_details
718
+ .map((detail, index) => {
719
+ return {
720
+ [`${index}`]: {
721
+ id: detail.id,
722
+ item_id: detail.item_id,
723
+ unit_cost: detail.unit_cost,
724
+ },
725
+ };
726
+ })
727
+ .reduce((acc, curr) => Object.assign(acc, curr), {}),
728
+ } as any,
729
+ },
730
+ x.id
731
+ );
732
+
733
+ if (!updateResponse.error) {
734
+ // Si hay error
735
+ costosEspecialesTemp[i].finalizado = true;
736
+ } else {
737
+ costosEspecialesTemp[i].finalizado = false;
738
+ costosEspecialesTemp[i].msgResultado =
739
+ updateResponse.userMsg ?? JSON.stringify(updateResponse);
740
+ }
741
+ }
742
+
743
+ //PASO 3
744
+ //Guardo la bitácora de cambios
745
+ console.log(
746
+ `==============================> GUARDANDO BITÁCORA DE CAMBIOS`
747
+ );
748
+ const response = await saveBitacoraCostos(headers, session, {
749
+ accion: "Reintento de asignación de costos",
750
+ costos: [],
751
+ costosEspeciales: [],
752
+ fechaCreacion: moment().format("DD/MM/YYYY HH:mm:ss"),
753
+ fechas: {
754
+ domingo: "",
755
+ jueves: "",
756
+ lunes: "",
757
+ martes: "",
758
+ miercoles: "",
759
+ sabado: "",
760
+ viernes: "",
761
+ },
762
+ modificadoPor: session.get("name"),
763
+ costosActualizados: costosTemp,
764
+ costosEspecialesActualizados: costosEspecialesTemp,
765
+ });
766
+
767
+ if (response.error || !response.data) {
768
+ throw new Error(
769
+ response.userMsg ??
770
+ "Respuesta vacía de saveBitacoraCostos en changePrices"
771
+ );
772
+ }
773
+
774
+ return response.data;
775
+ });
776
+ }
777
+
778
+ /**
779
+ * Get saveBitacoraCostos from the web app table.
780
+ * @param headers Request headers.
781
+ * @param session Session object.
782
+ * @returns A Promise of AxiosUtilsResponse<WebAppRowGraphQL<BitacoraCostosItems>[]>.
783
+ */
784
+ export async function saveBitacoraCostos(
785
+ headers: any,
786
+ session: Session,
787
+ body: BitacoraCostosItems
788
+ ): Promise<AxiosUtilsResponse<WebAppTableUpdateResponse>> {
789
+ return handlePossibleAxiosErrors(async () => {
790
+ const { bitacora_costos_verduras_web_app_table_id } =
791
+ await getVariablesByName(headers, session, [
792
+ "bitacora_costos_verduras_web_app_table_id",
793
+ ]);
794
+
795
+ const response = await createWebAppTableRegister<BitacoraCostosItems>(
796
+ headers,
797
+ bitacora_costos_verduras_web_app_table_id,
798
+ { ...body, modificadoPor: session.get("name") }
799
+ );
800
+
801
+ return response;
802
+ });
803
+ }
804
+
805
+ /**
806
+ * Put updateBitacoraCostos from the web app table.
807
+ * @param headers Request headers.
808
+ * @param session Session object.
809
+ * @returns A Promise of AxiosUtilsResponse<WebAppRowGraphQL<BitacoraCostosItems>[]>.
810
+ */
811
+ export async function updateBitacoraCostos(
812
+ headers: any,
813
+ session: Session,
814
+ body: BitacoraCostosItems,
815
+ id_registro: string | number
816
+ ): Promise<AxiosUtilsResponse<WebAppTableUpdateResponse>> {
817
+ return handlePossibleAxiosErrors(async () => {
818
+ const { bitacora_costos_verduras_web_app_table_id } =
819
+ await getVariablesByName(headers, session, [
820
+ "bitacora_costos_verduras_web_app_table_id",
821
+ ]);
822
+
823
+ const response = await updateWebAppTableRegister<BitacoraCostosItems>(
824
+ headers,
825
+ bitacora_costos_verduras_web_app_table_id,
826
+ id_registro,
827
+ { ...body, modificadoPor: session.get("name") }
828
+ );
829
+
830
+ return response;
831
+ });
832
+ }
833
+
834
+ /**
835
+ * Get getCostosBitacora from the web app table.
836
+ * @param headers Request headers.
837
+ * @param session Session object.
838
+ * @returns A Promise of AxiosUtilsResponse<WebAppRowGraphQL<BitacoraCostosItems>[]>.
839
+ */
840
+ export async function getCostosBitacora(
841
+ headers: any,
842
+ session: Session
843
+ ): Promise<AxiosUtilsResponse<WebAppRowGraphQL<BitacoraCostosItems>[]>> {
844
+ return handlePossibleAxiosErrors(async () => {
845
+ const { bitacora_costos_verduras_web_app_table_id } =
846
+ await getVariablesByName(headers, session, [
847
+ "bitacora_costos_verduras_web_app_table_id",
848
+ ]);
849
+
850
+ const response = await getWebAppTableRegisters<BitacoraCostosItems>(
851
+ session,
852
+ bitacora_costos_verduras_web_app_table_id
853
+ );
854
+
855
+ if (response.error) {
856
+ throw new Error(
857
+ `Ocurrió un error al tratar de obtener la bitácora de costos: ${response.userMsg}`
858
+ );
859
+ }
860
+
861
+ const bitacora = response.data ?? [];
862
+
863
+ return bitacora;
864
+ });
865
+ }