@zauru-sdk/utils 1.0.50 → 1.0.60

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