@zauru-sdk/utils 1.0.109 → 1.0.111

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