@zauru-sdk/utils 1.0.117 → 1.0.119

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.
@@ -296,8 +296,9 @@ export const changePricesInit = (headers, session, specialItems, body) => {
296
296
  costosEspecialesActualizados: costosEspecialesWithPurchaseIds,
297
297
  });
298
298
  if (response.error || !response.data) {
299
- const errorMsg = `Error al guardar la bitácora de costos ${response.userMsg}` ??
300
- "Respuesta vacía de saveBitacoraCostos en changePrices";
299
+ const errorMsg = response.userMsg
300
+ ? `Error al guardar la bitácora de costos ${response.userMsg}`
301
+ : "Respuesta vacía de saveBitacoraCostos en changePrices";
301
302
  console.error(errorMsg);
302
303
  throw new Error(errorMsg);
303
304
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zauru-sdk/utils",
3
- "version": "1.0.117",
3
+ "version": "1.0.119",
4
4
  "description": "Utilidades, parseo de request y demás para desarrollo de webapps de Zauru",
5
5
  "main": "./dist/cjs/index.js",
6
6
  "module": "./dist/esm/index.js",
@@ -10,8 +10,7 @@
10
10
  "access": "public"
11
11
  },
12
12
  "scripts": {
13
- "build": "npm run build:cjs && npm run build:esm",
14
- "build:cjs": "tsc -p tsconfig.cjs.json",
13
+ "build": "npm run build:esm",
15
14
  "build:esm": "tsc -p tsconfig.esm.json",
16
15
  "test": "echo \"Error: no test specified\" && exit 1"
17
16
  },
@@ -25,11 +24,11 @@
25
24
  },
26
25
  "dependencies": {
27
26
  "@remix-run/node": "^2.8.1",
28
- "@zauru-sdk/common": "^1.0.117",
29
- "@zauru-sdk/config": "^1.0.60",
30
- "@zauru-sdk/graphql": "^1.0.115",
31
- "@zauru-sdk/services": "^1.0.117",
32
- "@zauru-sdk/types": "^1.0.117"
27
+ "@zauru-sdk/common": "^1.0.119",
28
+ "@zauru-sdk/config": "^1.0.119",
29
+ "@zauru-sdk/graphql": "^1.0.119",
30
+ "@zauru-sdk/services": "^1.0.119",
31
+ "@zauru-sdk/types": "^1.0.119"
33
32
  },
34
- "gitHead": "4534ce5b582579835c080f54facdcd4b7fad3b72"
33
+ "gitHead": "61a0842f7e502c72e54defddb197fa69aa58f422"
35
34
  }
package/dist/cjs/index.js DELETED
@@ -1,41 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./zauru/4pinos-receptions-form-history.utils.js"), exports);
18
- __exportStar(require("./zauru/4pinos-reception-register.utils.js"), exports);
19
- __exportStar(require("./zauru/automatic-number.utils.js"), exports);
20
- __exportStar(require("./zauru/bitacora-edicion-masiva.utils.js"), exports);
21
- __exportStar(require("./zauru/bundles.utils.js"), exports);
22
- __exportStar(require("./zauru/cases.utils.js"), exports);
23
- __exportStar(require("./zauru/consolidated-history.utils.js"), exports);
24
- __exportStar(require("./zauru/costos-items.utils.js"), exports);
25
- __exportStar(require("./zauru/deliveries.utils.js"), exports);
26
- __exportStar(require("./zauru/discharges-histsory.utils.js"), exports);
27
- __exportStar(require("./zauru/employees.utils.js"), exports);
28
- __exportStar(require("./zauru/form.utils.js"), exports);
29
- __exportStar(require("./zauru/invoices.utils.js"), exports);
30
- __exportStar(require("./zauru/items.utils.js"), exports);
31
- __exportStar(require("./zauru/lotes.utils.js"), exports);
32
- __exportStar(require("./zauru/motivos-rechazo.utils.js"), exports);
33
- __exportStar(require("./zauru/payees.utils.js"), exports);
34
- __exportStar(require("./zauru/profiles.utils.js"), exports);
35
- __exportStar(require("./zauru/providers.utils.js"), exports);
36
- __exportStar(require("./zauru/purchase-orders.utils.js"), exports);
37
- __exportStar(require("./zauru/shipments.utils.js"), exports);
38
- __exportStar(require("./zauru/specialItem.utils.js"), exports);
39
- __exportStar(require("./zauru/templates.utils.js"), exports);
40
- __exportStar(require("./zauru/tiposMuestra.utils.js"), exports);
41
- __exportStar(require("./zauru/webapp-tables.utils.js"), exports);
@@ -1,450 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.retryPO = exports.register4pinosReception = void 0;
4
- const common_1 = require("@zauru-sdk/common");
5
- const services_1 = require("@zauru-sdk/services");
6
- const motivos_rechazo_utils_js_1 = require("./motivos-rechazo.utils.js");
7
- const _4pinos_receptions_form_history_utils_js_1 = require("./4pinos-receptions-form-history.utils.js");
8
- const register4pinosReception = async ({ cookie, idWebAppTable, agency_id, values, originApiResponses = {}, }) => {
9
- const session = await (0, services_1.getSession)(cookie);
10
- const headers = await (0, services_1.getHeaders)(cookie, session);
11
- let apiResponses = {
12
- apiCall: originApiResponses.apiCall ?? 1,
13
- ...originApiResponses,
14
- };
15
- try {
16
- if (apiResponses.apiCall === 1) {
17
- const responseUpdate = await (0, _4pinos_receptions_form_history_utils_js_1.updateQueueFormReceptionHistory)(headers, session, {
18
- estado: _4pinos_receptions_form_history_utils_js_1.ESTADOS_COLA_RECEPCIONES.EN_PROCESO,
19
- }, idWebAppTable);
20
- if (responseUpdate.error) {
21
- throw new Error("Error al intentar actualizar el estado de la cola: " +
22
- responseUpdate?.userMsg);
23
- }
24
- apiResponses.apiCall = apiResponses.apiCall + 1;
25
- }
26
- if (apiResponses.apiCall === 2) {
27
- //SI EL API CALL ES DIFERENTE DE 1 SIGNIFICA QUE SOLO VA A REINTENTAR DESDE DONDE FALLÓ
28
- //Validando que no exista ya una recepción con ese número:
29
- const responsePOSearch = await (0, services_1.getPurchasesOrderByIdNumber)(session, values?.idNumberInput);
30
- if (responsePOSearch.error || !responsePOSearch.data) {
31
- throw new Error(`No hay comunicación con la red para la validación de exists - Validate Exists: ${responsePOSearch?.userMsg}`);
32
- }
33
- const existentes = responsePOSearch?.data?.filter((x) => !x.voided);
34
- if (existentes?.length > 0) {
35
- throw new Error(`Ya existe una órden de compra con este número de contraseña asociado, revise el listado general. Peso: ${existentes[0].due}, Ingresado el: ${(0, common_1.getFormattedDate)(existentes[0].issue_date, false)}, Memo: ${existentes[0].memo}, Tipo: ${existentes[0].reference}`);
36
- }
37
- }
38
- const webapp_table_rejection = {
39
- Canastas: "int",
40
- Razon_primaria: "string",
41
- Razon_secundaria: "string",
42
- Razon_terciaria: "string",
43
- Otras_razones: "string",
44
- };
45
- const { recepciones_tag_id: tag_id, recepciones_vendor_agency_id: origin_agency, recepciones_my_quality_control_agency_id, } = await (0, services_1.getVariablesByName)(headers, session, [
46
- "recepciones_tag_id",
47
- "recepciones_vendor_agency_id",
48
- "recepciones_my_quality_control_agency_id",
49
- ]);
50
- // Remplaza los caracteres ':' por '":' y '{ ' por '{"', de esta manera las claves estarán entre comillas dobles
51
- const fixedString = recepciones_my_quality_control_agency_id
52
- .replace(/([a-zA-Z0-9_]+):/g, '"$1":')
53
- .replace("{ ", '{"');
54
- const hashRecepcionesQCAgency = JSON.parse(fixedString ?? "{}");
55
- const quality_control_agency = hashRecepcionesQCAgency[agency_id];
56
- //-------------------REACT SELECT VALUES-------------------------
57
- console.log("values", values);
58
- const vendor = values.vendor;
59
- const itemId = values.item;
60
- const purchaser = values.purchaser;
61
- const payeeType = values.rType;
62
- const idNumberInput = values.idNumberInput;
63
- const discountReason = values.discountReason;
64
- const issue_date = values.issue_date;
65
- const esCentroDeAcopio = values?.esCentroDeAcopio === "true";
66
- const singleBasketWeight = Number(values.singleBasketWeight);
67
- const recepciones_basket_item_id = Number(values?.recepciones_basket_item_id.toString());
68
- const rejections = JSON.parse(values.rejections.toString() ?? "[]");
69
- const provenance = values.selectedProvenance;
70
- const purchaseOrderGeneralInfo = JSON.parse(values?.purchaseOrderGeneralInfo?.toString() ?? "{}");
71
- let controlCalidadValues = {
72
- porcentajeRechazo: values.porcentajeRechazo,
73
- razonPrincipal: values.razonPrincipal,
74
- razonSecundaria: values.razonSecundaria,
75
- razonTerciaria: values.razonTerciaria,
76
- otrasRazones: values.otrasRazones,
77
- };
78
- let keys = Object.keys(values);
79
- let netWeight = values.netWgt;
80
- const total_baskets = values.totalBaskets + "";
81
- const stockInteger = values.stockInteger == "true";
82
- let webapp_table_object = {};
83
- const buildArray = (keyIncludes, processValue) => {
84
- const regex = /\d/; // Expresión regular para buscar al menos un dígito.
85
- return keys
86
- .filter((key) => key.includes(keyIncludes) && regex.test(key))
87
- .map((key) => [
88
- key.substring(keyIncludes?.length, key?.length),
89
- processValue(values[key]),
90
- ])
91
- .filter(([key, value]) => Number(value) > 0)
92
- .map(([kv, val]) => `${val}-${kv}`);
93
- };
94
- const buildSimpleArray = (keyIncludes, processValue) => {
95
- const regex = /\d/; // Expresión regular para buscar al menos un dígito.
96
- return keys
97
- .filter((key) => key.includes(keyIncludes) && regex.test(key))
98
- .map((key) => processValue(values[key] === "" || values[key] === "NaN" ? 0 : values[key]));
99
- };
100
- const processValues = () => {
101
- const received_baskets = buildArray("rec", parseInt);
102
- const qualityControlBaskets = buildArray("qC", parseInt);
103
- const detail_baskets = buildSimpleArray("basket", parseInt);
104
- const detail_discounts = buildSimpleArray("discount", parseFloat);
105
- const detail_weights = buildSimpleArray("weight", parseFloat);
106
- Object.keys(webapp_table_rejection ?? {})?.forEach((value, index) => {
107
- const temp = index === 0
108
- ? values[value]?.toString()
109
- : rejections[index - 1]?.split(";").join(", ") || "";
110
- webapp_table_object[value] = temp;
111
- });
112
- return [
113
- received_baskets,
114
- qualityControlBaskets,
115
- detail_baskets,
116
- detail_discounts,
117
- detail_weights,
118
- ];
119
- };
120
- let [received_baskets, qualityControlBaskets, detail_baskets, detail_discounts, detail_weights,] = processValues();
121
- //========== PRIMERA LLAMADA DE API Y CAPTURA DE ERRORES
122
- if (apiResponses.apiCall === 2) {
123
- console.log("========================================>");
124
- console.log("paso 1: REGISTRANDO NUEVA ORDEN DE COMPRA AUTORIZADA...");
125
- //build net_weights
126
- const detail_netWeights = keys
127
- .filter((key) => key.includes("weight"))
128
- .map((key, index) => {
129
- const weight = Number(values[key]);
130
- const detail_basket = Number(detail_baskets[index]);
131
- const detail_discount = Number(detail_discounts[index]) ?? 0;
132
- return ((weight - (stockInteger ? 0 : detail_basket * singleBasketWeight)) *
133
- ((100 - detail_discount) / 100));
134
- });
135
- const newPurchaseOrderDetails = detail_baskets.map((x, index) => {
136
- return {
137
- reference: `${detail_weights[index]},${x},${detail_discounts[index]}`,
138
- item_id: Number(itemId),
139
- booked_quantity: detail_netWeights[index],
140
- unit_cost: 1,
141
- };
142
- });
143
- const newPurchaseOrderBody = {
144
- reference: payeeType,
145
- taxable: false,
146
- issue_date,
147
- shipping_date: issue_date,
148
- incoterm_id: purchaseOrderGeneralInfo?.incoterm_id,
149
- currency_id: purchaseOrderGeneralInfo?.currency_id,
150
- charge_term_id: purchaseOrderGeneralInfo?.charge_term_id,
151
- payee_id: vendor,
152
- agency_id,
153
- purchaser_id: Number(purchaser),
154
- import: false,
155
- tag_ids: ["", tag_id],
156
- memo: qualityControlBaskets + "",
157
- origin: netWeight,
158
- purchase_order_details: newPurchaseOrderDetails,
159
- incoterm_destination: provenance.slice(0, 254),
160
- transport_type: discountReason,
161
- id_number: idNumberInput,
162
- ...(esCentroDeAcopio
163
- ? { discount: Number(controlCalidadValues.porcentajeRechazo) }
164
- : {}),
165
- };
166
- console.log("REGISTRANDO ORDEN DE COMPRA: ", JSON.stringify(newPurchaseOrderBody));
167
- const newAuthorizedPurchaseResponse = await (0, services_1.createNewAuthorizedPurchaseOrder)(headers, newPurchaseOrderBody, false);
168
- if (newAuthorizedPurchaseResponse?.error ||
169
- !newAuthorizedPurchaseResponse.data) {
170
- throw new Error("Error al intentar crear la órden de compra autorizada: " +
171
- newAuthorizedPurchaseResponse?.userMsg +
172
- " Body: " +
173
- JSON.stringify(newPurchaseOrderBody));
174
- }
175
- apiResponses.authorizedPO = newAuthorizedPurchaseResponse.data;
176
- apiResponses.apiCall = apiResponses.apiCall + 1;
177
- }
178
- if (apiResponses.apiCall === 3) {
179
- const createNewReceptionBodyFunction = () => {
180
- const receptionDetails = {};
181
- apiResponses.authorizedPO.purchase_order_details.forEach((pod, index) => (receptionDetails[index] = {
182
- item_id: `${pod.item_id}`,
183
- purchase_order_detail_id: `${pod.id}`,
184
- lot_delivered_quantity: [`${pod.booked_quantity}`],
185
- lot_name: [apiResponses.authorizedPO.id_number],
186
- lot_expire: [
187
- new Date(Date.now() + 12096e5).toISOString().split("T")[0],
188
- ],
189
- lot_description: [received_baskets.join(",")],
190
- }));
191
- const newReception = {
192
- reception: {
193
- agency_id,
194
- received_at: issue_date,
195
- purchase_order_id: apiResponses.authorizedPO.id + "",
196
- entity_id: apiResponses.authorizedPO.entity_id + "",
197
- needs_transit: "0",
198
- invoice_number: "",
199
- reception_details_attributes: receptionDetails,
200
- },
201
- };
202
- return newReception;
203
- };
204
- //first create reception and receive it with the basket shipment
205
- const newReception = createNewReceptionBodyFunction();
206
- console.log("========================================>");
207
- console.log("paso 2: CREANDO RECEPCION, ENVIO DE CANASTAS, WEBAPP TABLE DE RECHAZO DIRECTO");
208
- console.log("------------ CREANDO RECEPCIÓN.......");
209
- const responseNewReception = await (0, services_1.createNewReception)(headers, newReception, apiResponses.authorizedPO.id);
210
- if (responseNewReception.error || !responseNewReception.data) {
211
- throw new Error("Error al intentar crear la recepción: " +
212
- responseNewReception?.userMsg);
213
- }
214
- apiResponses.apiCall = apiResponses.apiCall + 1;
215
- }
216
- if (apiResponses.apiCall === 4) {
217
- console.log("------------- REALIZANDO ENVÍO DE CANASTAS A LA AGENCIA");
218
- const createBasketsShipmentBodyFunction = () => {
219
- const movementDetails = [];
220
- received_baskets.forEach((basket, index) => {
221
- movementDetails.push({
222
- item_id: recepciones_basket_item_id,
223
- lot_id: basket.split("-")[1],
224
- booked_quantity: basket.split("-")[0],
225
- });
226
- });
227
- const BasketShipment = {
228
- booker_id: Number(purchaser),
229
- reference: "Envio de canastas (De proveedor a agencia)",
230
- needs_transport: false,
231
- planned_delivery: issue_date,
232
- agency_from_id: Number(origin_agency),
233
- agency_to_id: agency_id,
234
- movements: movementDetails,
235
- };
236
- return BasketShipment;
237
- };
238
- const newBasketShipment = createBasketsShipmentBodyFunction();
239
- const newShipmentResponse = await (0, services_1.insertBookings)(headers, newBasketShipment, `${apiResponses.authorizedPO.id}`);
240
- if (newShipmentResponse.error || !newShipmentResponse.data) {
241
- throw new Error("Error al intentar crear el envío: " +
242
- newShipmentResponse?.userMsg +
243
- " Body: " +
244
- JSON.stringify(newBasketShipment));
245
- }
246
- apiResponses.apiCall = apiResponses.apiCall + 1;
247
- apiResponses.shipment = newShipmentResponse.data;
248
- }
249
- if (apiResponses.apiCall === 5) {
250
- console.log("------------- RECIBIENDO EL ENVÍO DE CANASTAS");
251
- const getShipmentResponse = await (0, services_1.getDeliveryByBooking)(headers, apiResponses.shipment.id);
252
- if (getShipmentResponse.error) {
253
- throw new Error("Error al intentar recibir el envío: " + getShipmentResponse?.userMsg);
254
- }
255
- apiResponses.apiCall = apiResponses.apiCall + 1;
256
- }
257
- if (!esCentroDeAcopio) {
258
- //Al momento de este comentario, un ejemplo es que sólo Planta Central no es centro de acopio
259
- //Ellos si envían canastas a control de calidad.
260
- //Si es de un centro de acopio, se salta esto...
261
- if (apiResponses.apiCall === 6 && qualityControlBaskets.length > 0) {
262
- console.log("------------- REALIZANDO ENVÍO DE CANASTAS A CONTROL DE CALIDAD");
263
- const total_qc_baskets = Number(values.totalQCBaskets);
264
- const netWeightByBasket = Number(netWeight) / total_qc_baskets;
265
- const lotResponse = await (0, services_1.getLoteByName)(session, apiResponses.authorizedPO.id_number);
266
- if (lotResponse.error || !lotResponse.data || !lotResponse.data.id) {
267
- throw new Error("Error al intentar obtener el lote por nombre: " +
268
- lotResponse?.userMsg);
269
- }
270
- const createQCBasketShipmentBody = async () => {
271
- const qcMovementDetails = qualityControlBaskets.map((basket) => {
272
- const booked_quantity = Number(basket.split("-")[0]);
273
- const lot_id = Number(basket.split("-")[1]);
274
- return {
275
- item_id: recepciones_basket_item_id,
276
- lot_id,
277
- booked_quantity,
278
- reference: "Canastas a control de calidad.",
279
- };
280
- });
281
- qcMovementDetails.push({
282
- item_id: apiResponses.authorizedPO.purchase_order_details[0].item_id,
283
- lot_id: Number(lotResponse.data?.id),
284
- booked_quantity: total_qc_baskets * netWeightByBasket,
285
- reference: "Verduras a control de calidad.",
286
- });
287
- const qcBasketShipment = {
288
- booker_id: Number(purchaser),
289
- reference: "Envio de canastas y verduras a CC",
290
- needs_transport: false,
291
- planned_delivery: issue_date,
292
- agency_from_id: agency_id,
293
- agency_to_id: quality_control_agency,
294
- movements: qcMovementDetails,
295
- };
296
- return qcBasketShipment;
297
- };
298
- const newQCBasketShipment = await createQCBasketShipmentBody();
299
- const new_qc_shipment_response = await (0, services_1.insertBookings)(headers, newQCBasketShipment, `${apiResponses.authorizedPO.id}`);
300
- if (!new_qc_shipment_response.data || new_qc_shipment_response.error) {
301
- console.log("Body: ", JSON.stringify(newQCBasketShipment));
302
- throw new Error("Error al intentar crear el envío a control de calidad: " +
303
- new_qc_shipment_response?.userMsg +
304
- " Body: " +
305
- JSON.stringify(newQCBasketShipment));
306
- }
307
- apiResponses.apiCall = apiResponses.apiCall + 1;
308
- apiResponses.qcShipment = new_qc_shipment_response.data;
309
- }
310
- if (apiResponses.apiCall === 7) {
311
- console.log("------------- RECIBIENDO ENVÍO DE CANASTAS A CONTROL DE CALIDAD");
312
- const getQCDeliveryResponse = await (0, services_1.getDeliveryByBooking)(headers, apiResponses.qcShipment.id);
313
- if (getQCDeliveryResponse.error) {
314
- throw new Error("Error al intentar recibir el envío de control de calidad: " +
315
- getQCDeliveryResponse?.userMsg +
316
- " Body: " +
317
- JSON.stringify(apiResponses.qcShipment));
318
- }
319
- apiResponses.apiCall = apiResponses.apiCall + 1;
320
- }
321
- if (apiResponses.apiCall === 8 || qualityControlBaskets.length === 0) {
322
- if (webapp_table_object.Canastas !== "" &&
323
- webapp_table_object.Canastas !== "0") {
324
- console.log("----------- Guardando rechazo de canastas directo...... -----------");
325
- const responseRechazo = await (0, motivos_rechazo_utils_js_1.saveRechazoCanastas)(headers, session, {
326
- temp_purchase_order_id: `${apiResponses.authorizedPO.id}`,
327
- webapp_row: {
328
- data: webapp_table_object,
329
- },
330
- });
331
- if (responseRechazo.error) {
332
- throw new Error("Error al intentar guardar el rechazo de canastas directo: " +
333
- responseRechazo?.userMsg);
334
- }
335
- apiResponses.apiCall = apiResponses.apiCall + 1;
336
- }
337
- }
338
- }
339
- else {
340
- //Si es centro de acopio, guardo los motivos de rechazo
341
- if (controlCalidadValues?.razonPrincipal ||
342
- controlCalidadValues?.razonSecundaria ||
343
- controlCalidadValues?.razonTerciaria ||
344
- controlCalidadValues?.otrasRazones) {
345
- if (apiResponses.apiCall === 6) {
346
- console.log("========================================>");
347
- console.log("paso 3: GUARDAR MOTIVOS DE RECHAZO");
348
- const saveMotivosResponse = await (0, services_1.saveMotivosDeRechazoByPurchase)(headers, session, {
349
- Razon_primaria: `${controlCalidadValues?.razonPrincipal ?? ""}`,
350
- Razon_secundaria: `${controlCalidadValues?.razonSecundaria ?? ""}`,
351
- Razon_terciaria: `${controlCalidadValues?.razonTerciaria ?? ""}`,
352
- Otras_razones: `${controlCalidadValues?.otrasRazones ?? ""}`,
353
- }, { temp_purchase_order_id: `${apiResponses.authorizedPO.id}` });
354
- if (saveMotivosResponse.error) {
355
- throw new Error("Error al intentar guardar los motivos de rechazo: " +
356
- saveMotivosResponse?.userMsg);
357
- }
358
- }
359
- }
360
- }
361
- console.log("========================================>");
362
- console.log("paso 4: ELIMINAR EL REGISTRO DE LA COLA");
363
- //ELIMINAR EL REGISTRO DE LA COLA
364
- await (0, _4pinos_receptions_form_history_utils_js_1.deleteQueueFormReceptionHistory)(headers, session, idWebAppTable);
365
- }
366
- catch (e) {
367
- //SI OCURRE ALGÚN ERROR, SE INTENTA GUARDAR EL RETRY
368
- console.log("========================================>");
369
- console.log("paso -1: ACTUALIZAR EL REGISTRO DE LA COLA A ERROR");
370
- console.error(`Error: ${e?.toString()}, idWebAppTable: ${idWebAppTable}`);
371
- await (0, _4pinos_receptions_form_history_utils_js_1.updateQueueFormReceptionHistory)(headers, session, {
372
- estado: _4pinos_receptions_form_history_utils_js_1.ESTADOS_COLA_RECEPCIONES.ERROR,
373
- description: e?.toString(),
374
- apiResponses,
375
- }, idWebAppTable);
376
- }
377
- };
378
- exports.register4pinosReception = register4pinosReception;
379
- const retryPO = async (register, session, headers, hostname, cookie) => {
380
- console.log("REINTENTO DE REGISTRO DE ORDEN DE COMPRA =======================>");
381
- if (!register.data.apiResponses || register.data.apiResponses.apiCall === 1) {
382
- const responsePOSearch = await (0, services_1.getPurchasesOrderByIdNumber)(session, register.data?.formSubmited?.idNumberInput);
383
- if (responsePOSearch.error || !responsePOSearch.data) {
384
- console.error("Validate Exists: ", responsePOSearch.userMsg);
385
- return {
386
- error: true,
387
- title: "No se logró comunicar con la red.",
388
- type: "error",
389
- description: `No hay comunicación con la red para el reintento - Validate Exists: ${responsePOSearch.userMsg}`,
390
- };
391
- }
392
- const existentes = responsePOSearch?.data?.filter((x) => !x.voided);
393
- if (existentes?.length > 0) {
394
- const msg = `Ya existe una órden de compra con este número de contraseña asociado, revise el listado general. Peso: ${existentes[0].due}, Ingresado el: ${(0, common_1.getFormattedDate)(existentes[0].issue_date)}, Memo: ${existentes[0].memo}, Tipo: ${existentes[0].reference}`;
395
- console.error(msg);
396
- await (0, _4pinos_receptions_form_history_utils_js_1.updateQueueFormReceptionHistory)(headers, session, {
397
- description: msg,
398
- estado: _4pinos_receptions_form_history_utils_js_1.ESTADOS_COLA_RECEPCIONES.ERROR,
399
- }, register.id);
400
- return {
401
- error: true,
402
- title: "No se puede crear la órden de compra.",
403
- type: "error",
404
- description: msg,
405
- };
406
- }
407
- }
408
- const queueResponse = await (0, _4pinos_receptions_form_history_utils_js_1.updateQueueFormReceptionHistory)(headers, session, {
409
- estado: _4pinos_receptions_form_history_utils_js_1.ESTADOS_COLA_RECEPCIONES.REINTENTANDO,
410
- }, register.id);
411
- if (queueResponse.error || !queueResponse.data?.id) {
412
- return {
413
- error: true,
414
- title: "No se logró comunicar con la red.",
415
- type: "error",
416
- description: `No hay comunicación con la red para el reintento: ${queueResponse?.userMsg}`,
417
- };
418
- }
419
- if (hostname.includes("localhost")) {
420
- console.log("------- EJECUTANDO LOCALMENTE", ` para ${register.data?.formSubmited?.idNumberInput}`);
421
- (0, exports.register4pinosReception)({
422
- values: register.data?.formSubmited,
423
- cookie,
424
- idWebAppTable: register.id,
425
- agency_id: register.data?.agency_id,
426
- originApiResponses: register.data?.apiResponses,
427
- });
428
- }
429
- else {
430
- console.log("------- ENVIANDO A EJECUTAR NETLIFY FUNCTION: 4pinosNewPurchaseOrder-background", ` para ${register.data?.formSubmited?.idNumberInput}`);
431
- fetch(`https://${hostname}/.netlify/functions/4pinosNewPurchaseOrder-background`, {
432
- method: "post",
433
- headers: { "Content-type": "application/json" },
434
- body: JSON.stringify({
435
- values: register.data?.formSubmited,
436
- cookie,
437
- idWebAppTable: register.id,
438
- agency_id: register.data?.agency_id,
439
- originApiResponses: register.data?.apiResponses,
440
- }),
441
- });
442
- }
443
- return {
444
- error: false,
445
- title: "Reintento iniciado con éxito.",
446
- type: "success",
447
- description: `Se está procesando el reintento de ingreso de recepción!.`,
448
- };
449
- };
450
- exports.retryPO = retryPO;
@@ -1,102 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.deleteQueueFormReceptionHistory = exports.updateQueueFormReceptionHistory = exports.createQueueFormReceptionHistory = exports.getQueueFormReceptionHistoryByID = exports.getQueueFormReceptionHistories = exports.ESTADOS_COLA_RECEPCIONES = void 0;
4
- const common_1 = require("@zauru-sdk/common");
5
- const services_1 = require("@zauru-sdk/services");
6
- exports.ESTADOS_COLA_RECEPCIONES = {
7
- INICIADO: "Iniciado",
8
- EN_PROCESO: "En proceso",
9
- ERROR: "Con error",
10
- REINTENTANDO: "Reintentando",
11
- PENDIENTE_DE_REINTENTO: "Pendiente de reintento",
12
- OFFLINE: "Registro local",
13
- };
14
- /**
15
- * Get getQueueFormReceptionHistories from the web app table.
16
- * @param headers Request headers.
17
- * @param session Session object.
18
- * @returns A Promise of AxiosUtilsResponse<QueueFormReceptionWebAppTable[]>.
19
- */
20
- const getQueueFormReceptionHistories = (headers, session) => {
21
- return (0, common_1.handlePossibleAxiosErrors)(async () => {
22
- const { queue_form_recepcion_submited_web_app_table_id } = await (0, services_1.getVariablesByName)(headers, session, [
23
- "queue_form_recepcion_submited_web_app_table_id",
24
- ]);
25
- const response = await (0, services_1.getWebAppTableRegisters)(session, queue_form_recepcion_submited_web_app_table_id);
26
- if (response.error) {
27
- throw new Error(`Ocurrió un error al consultar el historial de colas: ${response.userMsg}`);
28
- }
29
- const history = response?.data ?? [];
30
- return history;
31
- });
32
- };
33
- exports.getQueueFormReceptionHistories = getQueueFormReceptionHistories;
34
- /**
35
- * Get getQueueFormReceptionHistories from the web app table.
36
- * @param headers Request headers.
37
- * @param session Session object.
38
- * @returns A Promise of AxiosUtilsResponse<QueueFormReceptionWebAppTable[]>.
39
- */
40
- const getQueueFormReceptionHistoryByID = (session, id) => {
41
- return (0, common_1.handlePossibleAxiosErrors)(async () => {
42
- const response = await (0, services_1.getWebAppRow)(session, Number(id));
43
- if (response.error) {
44
- throw new Error(`Ocurrió un error al consultar el historial de colas: ${response.userMsg}`);
45
- }
46
- const history = response?.data ?? null;
47
- return history;
48
- });
49
- };
50
- exports.getQueueFormReceptionHistoryByID = getQueueFormReceptionHistoryByID;
51
- /**
52
- * Create a template in the web app table.
53
- * @param headers Request headers.
54
- * @param session Session object.
55
- * @param body QueueFormReceptionWebAppTable data to be created.
56
- * @returns A Promise of AxiosUtilsResponse<QueueFormReceptionWebAppTable>.
57
- */
58
- const createQueueFormReceptionHistory = (headers, session, body) => {
59
- return (0, common_1.handlePossibleAxiosErrors)(async () => {
60
- const { queue_form_recepcion_submited_web_app_table_id } = await (0, services_1.getVariablesByName)(headers, session, [
61
- "queue_form_recepcion_submited_web_app_table_id",
62
- ]);
63
- //Esto es para simular el tiempo de carga de la API nunca subir a producción
64
- //await new Promise((resolve) => setTimeout(resolve, 7000));
65
- //throw new Error("Error al crear el historial de colas");
66
- const response = await (0, services_1.createWebAppTableRegister)(headers, queue_form_recepcion_submited_web_app_table_id, body);
67
- return response;
68
- });
69
- };
70
- exports.createQueueFormReceptionHistory = createQueueFormReceptionHistory;
71
- /**
72
- * Put updateQueueFormReception from the web app table.
73
- * @param headers Request headers.
74
- * @param session Session object.
75
- * @returns A Promise of AxiosUtilsResponse<QueueFormReceptionWebAppTable[]>.
76
- */
77
- const updateQueueFormReceptionHistory = (headers, session, body, id_registro) => {
78
- return (0, common_1.handlePossibleAxiosErrors)(async () => {
79
- const { queue_form_recepcion_submited_web_app_table_id } = await (0, services_1.getVariablesByName)(headers, session, [
80
- "queue_form_recepcion_submited_web_app_table_id",
81
- ]);
82
- const response = await (0, services_1.updateWebAppTableRegister)(headers, queue_form_recepcion_submited_web_app_table_id, id_registro, { ...body });
83
- return response;
84
- });
85
- };
86
- exports.updateQueueFormReceptionHistory = updateQueueFormReceptionHistory;
87
- /**
88
- * Delete QueueFormReceptionHistory from the web app table.
89
- * @param headers Request headers.
90
- * @param session Session object.
91
- * @returns A Promise of AxiosUtilsResponse<QueueFormReceptionWebAppTable[]>.
92
- */
93
- const deleteQueueFormReceptionHistory = (headers, session, id) => {
94
- return (0, common_1.handlePossibleAxiosErrors)(async () => {
95
- const { queue_form_recepcion_submited_web_app_table_id } = await (0, services_1.getVariablesByName)(headers, session, [
96
- "queue_form_recepcion_submited_web_app_table_id",
97
- ]);
98
- const response = await (0, services_1.deleteWebAppTableRegister)(headers, queue_form_recepcion_submited_web_app_table_id, Number(id));
99
- return response;
100
- });
101
- };
102
- exports.deleteQueueFormReceptionHistory = deleteQueueFormReceptionHistory;