@zauru-sdk/utils 1.0.93 → 1.0.95

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.
@@ -0,0 +1,355 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ 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
+ //SI EL API CALL ES DIFERENTE DE 1 SIGNIFICA QUE SOLO VA A REINTENTAR DESDE DONDE FALLÓ
18
+ //Validando que no exista ya una recepción con ese número:
19
+ const responsePOSearch = await (0, services_1.getPurchasesOrderByIdNumber)(session, values?.idNumberInput);
20
+ if (responsePOSearch.error || !responsePOSearch.data) {
21
+ throw new Error(`No hay comunicación con la red para la validación de exists - Validate Exists: ${responsePOSearch?.userMsg}`);
22
+ }
23
+ const existentes = responsePOSearch?.data?.filter((x) => !x.voided);
24
+ if (existentes?.length > 0) {
25
+ 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.zauruDateToLongString)(existentes[0].issue_date)}, Memo: ${existentes[0].memo}, Tipo: ${existentes[0].reference}`);
26
+ }
27
+ }
28
+ const esCentroDeAcopio = values?.esCentroDeAcopio === "true";
29
+ const basketLots = JSON.parse(values?.basketLots.toString());
30
+ const webapp_table_rejection = {
31
+ Canastas: "int",
32
+ Razon_primaria: "string",
33
+ Razon_secundaria: "string",
34
+ Razon_terciaria: "string",
35
+ Otras_razones: "string",
36
+ };
37
+ 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, [
38
+ "recepciones_tag_id",
39
+ "recepciones_vendor_agency_id",
40
+ "recepciones_my_quality_control_agency_id",
41
+ ]);
42
+ // Remplaza los caracteres ':' por '":' y '{ ' por '{"', de esta manera las claves estarán entre comillas dobles
43
+ const fixedString = recepciones_my_quality_control_agency_id
44
+ .replace(/([a-zA-Z0-9_]+):/g, '"$1":')
45
+ .replace("{ ", '{"');
46
+ const hashRecepcionesQCAgency = JSON.parse(fixedString ?? "{}");
47
+ const quality_control_agency = hashRecepcionesQCAgency[agency_id];
48
+ //-------------------REACT SELECT VALUES-------------------------
49
+ const vendor = values.vendor;
50
+ const itemId = values.item;
51
+ const purchaser = values.purchaser;
52
+ const payeeType = values.rType;
53
+ const idNumberInput = values.idNumberInput;
54
+ const discountReason = values.discountReason;
55
+ const issue_date = values.issue_date;
56
+ const rejections = JSON.parse(values.rejections.toString() ?? "[]");
57
+ const provenance = values.selectedProvenance;
58
+ const purchaseOrderGeneralInfo = JSON.parse(values?.purchaseOrderGeneralInfo?.toString() ?? "{}");
59
+ let controlCalidadValues = {
60
+ porcentajeRechazo: values.porcentajeRechazo,
61
+ razonPrincipal: values.razonPrincipal,
62
+ razonSecundaria: values.razonSecundaria,
63
+ razonTerciaria: values.razonTerciaria,
64
+ otrasRazones: values.otrasRazones,
65
+ };
66
+ let keys = Object.keys(values);
67
+ let netWeight = values.netWgt;
68
+ let singleBasketWeight = values.singleBasketWeight;
69
+ const total_baskets = values.totalBaskets + "";
70
+ const stockInteger = values.stockInteger + "" == "true";
71
+ let webapp_table_object = {};
72
+ const buildArray = (keyIncludes, processValue) => {
73
+ return keys
74
+ .filter((key) => key.includes(keyIncludes))
75
+ .map((kbv) => [
76
+ kbv.substring(keyIncludes?.length, kbv?.length),
77
+ processValue(values[kbv]),
78
+ ])
79
+ .filter(([key, value]) => Number(value) > 0)
80
+ .map(([kv, val]) => `${val}-${kv}`);
81
+ };
82
+ const buildSimpleArray = (keyIncludes, processValue) => {
83
+ const regex = /\d/; // Expresión regular para buscar al menos un dígito.
84
+ return keys
85
+ .filter((key) => key.includes(keyIncludes) && regex.test(key))
86
+ .map((kbv) => processValue(values[kbv] === "" ? 0 : values[kbv]));
87
+ };
88
+ const processValues = () => {
89
+ const received_baskets = buildArray("rec", parseInt);
90
+ const qualityControlBaskets = buildArray("qC", parseInt);
91
+ const detail_baskets = buildSimpleArray("basket", parseInt);
92
+ const detail_discounts = buildSimpleArray("discount", parseFloat);
93
+ const detail_weights = buildSimpleArray("weight", parseFloat);
94
+ Object.keys(webapp_table_rejection ?? {})?.forEach((value, index) => {
95
+ const temp = index === 0
96
+ ? values[value]?.toString()
97
+ : rejections[index - 1]?.split(";").join(", ") || "";
98
+ webapp_table_object[value] = temp;
99
+ });
100
+ return [
101
+ received_baskets,
102
+ qualityControlBaskets,
103
+ detail_baskets,
104
+ detail_discounts,
105
+ detail_weights,
106
+ ];
107
+ };
108
+ let [received_baskets, qualityControlBaskets, detail_baskets, detail_discounts, detail_weights,] = processValues();
109
+ //build net_weights
110
+ const detail_netWeights = keys
111
+ .filter((key) => key.includes("weight"))
112
+ .map((kbv, index) => (parseFloat(values[kbv]) -
113
+ (stockInteger
114
+ ? 0
115
+ : detail_baskets[index] * parseFloat(singleBasketWeight))) *
116
+ ((100 - detail_discounts[index]) / 100));
117
+ // //---------------------------PURCHASE ORDER OBJECT----------------------------------
118
+ console.log("========================================>");
119
+ console.log("paso 1: REGISTRANDO NUEVA ORDEN DE COMPRA AUTORIZADA...");
120
+ const newPurchaseOrderDetails = [];
121
+ detail_baskets.forEach((x, index) => {
122
+ newPurchaseOrderDetails.push({
123
+ reference: `${detail_weights[index]},${detail_baskets[index]},${detail_discounts[index]}`,
124
+ item_id: Number(itemId),
125
+ booked_quantity: detail_netWeights[index],
126
+ unit_cost: 1,
127
+ });
128
+ });
129
+ const newPurchaseOrderBody = {
130
+ reference: payeeType,
131
+ taxable: false,
132
+ issue_date,
133
+ shipping_date: issue_date,
134
+ incoterm_id: purchaseOrderGeneralInfo?.incoterm_id,
135
+ currency_id: purchaseOrderGeneralInfo?.currency_id,
136
+ charge_term_id: purchaseOrderGeneralInfo?.charge_term_id,
137
+ payee_info: vendor,
138
+ agency_id,
139
+ purchaser_id: Number(purchaser),
140
+ import: false,
141
+ tag_ids: ["", tag_id],
142
+ memo: qualityControlBaskets + "",
143
+ origin: netWeight,
144
+ purchase_order_details: newPurchaseOrderDetails,
145
+ incoterm_destination: provenance.slice(0, 254),
146
+ transport_type: discountReason,
147
+ id_number: idNumberInput,
148
+ ...(esCentroDeAcopio
149
+ ? { discount: Number(controlCalidadValues.porcentajeRechazo) }
150
+ : {}),
151
+ };
152
+ //========== PRIMERA LLAMADA DE API Y CAPTURA DE ERRORES
153
+ if (apiResponses.apiCall === 1) {
154
+ console.log("REGISTRANDO ORDEN DE COMPRA: ", JSON.stringify(newPurchaseOrderBody));
155
+ const newAuthorizedPurchaseResponse = await (0, services_1.createNewAuthorizedPurchaseOrder)(headers, newPurchaseOrderBody, false);
156
+ if (newAuthorizedPurchaseResponse?.error ||
157
+ !newAuthorizedPurchaseResponse.data) {
158
+ throw new Error("Error al intentar crear la órden de compra autorizada: " +
159
+ newAuthorizedPurchaseResponse?.userMsg);
160
+ }
161
+ apiResponses.authorizedPO = newAuthorizedPurchaseResponse.data;
162
+ apiResponses.apiCall = apiResponses.apiCall + 1;
163
+ }
164
+ console.log("========================================>");
165
+ console.log("paso 2: CREANDO RECEPCION, ENVIO DE CANASTAS, WEBAPP TABLE DE RECHAZO DIRECTO");
166
+ const createNewReceptionBodyFunction = () => {
167
+ const receptionDetails = {};
168
+ apiResponses.authorizedPO.purchase_order_details.forEach((pod, index) => (receptionDetails[index] = {
169
+ item_id: `${pod.item_id}`,
170
+ purchase_order_detail_id: `${pod.id}`,
171
+ lot_delivered_quantity: [`${pod.booked_quantity}`],
172
+ lot_name: [apiResponses.authorizedPO.id_number],
173
+ lot_expire: [
174
+ new Date(Date.now() + 12096e5).toISOString().split("T")[0],
175
+ ],
176
+ lot_description: [received_baskets.join(",")],
177
+ }));
178
+ const newReception = {
179
+ reception: {
180
+ agency_id,
181
+ received_at: issue_date,
182
+ purchase_order_id: apiResponses.authorizedPO.id + "",
183
+ entity_id: apiResponses.authorizedPO.entity_id + "",
184
+ needs_transit: "0",
185
+ invoice_number: "",
186
+ reception_details_attributes: receptionDetails,
187
+ },
188
+ };
189
+ return newReception;
190
+ };
191
+ const createBasketsShipmentBodyFunction = () => {
192
+ const movementDetails = [];
193
+ received_baskets.forEach((basket, index) => {
194
+ movementDetails.push({
195
+ item_id: basketLots?.recepciones_basket_item_id,
196
+ lot_id: basket.split("-")[1],
197
+ booked_quantity: basket.split("-")[0],
198
+ });
199
+ });
200
+ const BasketShipment = {
201
+ booker_id: Number(purchaser),
202
+ reference: "Envio de canastas (De proveedor a agencia)",
203
+ needs_transport: false,
204
+ planned_delivery: issue_date,
205
+ agency_from_id: Number(origin_agency),
206
+ agency_to_id: agency_id,
207
+ movements: movementDetails,
208
+ };
209
+ return BasketShipment;
210
+ };
211
+ const createQCBasketShipmentBody = async () => {
212
+ const qcMovementDetails = [];
213
+ qualityControlBaskets.forEach((basket) => {
214
+ qcMovementDetails.push({
215
+ item_id: basketLots?.recepciones_basket_item_id,
216
+ lot_id: Number(basket.split("-")[1]),
217
+ booked_quantity: Number(basket.split("-")[0]),
218
+ });
219
+ });
220
+ const total_qc_baskets = parseInt(values.totalQCBaskets + "");
221
+ const basket_weight = parseFloat(netWeight) / parseInt(total_baskets);
222
+ const lotResponse = await (0, services_1.getLoteByName)(session, apiResponses.authorizedPO.id_number);
223
+ if (lotResponse.error || !lotResponse.data) {
224
+ throw new Error("Error al intentar obtener el lote por nombre: " +
225
+ lotResponse?.userMsg);
226
+ }
227
+ if (lotResponse.data?.id) {
228
+ qcMovementDetails.push({
229
+ item_id: apiResponses.authorizedPO.purchase_order_details[0].item_id,
230
+ lot_id: Number(lotResponse.data.id),
231
+ booked_quantity: Number(Math.round(total_qc_baskets * basket_weight)), //TODO: Revisar si esto está bien así.
232
+ });
233
+ }
234
+ const qcBasketShipment = {
235
+ booker_id: Number(purchaser),
236
+ reference: "Envio de canastas y verduras a CC",
237
+ needs_transport: false,
238
+ planned_delivery: issue_date,
239
+ agency_from_id: agency_id,
240
+ agency_to_id: quality_control_agency,
241
+ movements: qcMovementDetails,
242
+ };
243
+ return qcBasketShipment;
244
+ };
245
+ //first create reception and receive it with the basket shipment
246
+ const newReception = createNewReceptionBodyFunction();
247
+ const newBasketShipment = createBasketsShipmentBodyFunction();
248
+ if (apiResponses.apiCall === 2) {
249
+ console.log("------------ CREANDO RECEPCIÓN.......");
250
+ const responseNewReception = await (0, services_1.createNewReception)(headers, newReception, apiResponses.authorizedPO.id);
251
+ if (responseNewReception.error || !responseNewReception.data) {
252
+ throw new Error("Error al intentar crear la recepción: " +
253
+ responseNewReception?.userMsg);
254
+ }
255
+ apiResponses.apiCall = apiResponses.apiCall + 1;
256
+ }
257
+ if (apiResponses.apiCall === 3) {
258
+ console.log("------------- REALIZANDO ENVÍO DE CANASTAS A LA AGENCIA");
259
+ const newShipmentResponse = await (0, services_1.insertBookings)(headers, newBasketShipment, `${apiResponses.authorizedPO.id}`);
260
+ if (newShipmentResponse.error || !newShipmentResponse.data) {
261
+ throw new Error("Error al intentar crear el envío: " + newShipmentResponse?.userMsg);
262
+ }
263
+ apiResponses.apiCall = apiResponses.apiCall + 1;
264
+ apiResponses.shipment = newShipmentResponse.data;
265
+ }
266
+ if (apiResponses.apiCall === 4) {
267
+ console.log("------------- RECIBIENDO EL ENVÍO DE CANASTAS");
268
+ const getShipmentResponse = await (0, services_1.getDeliveryByBooking)(headers, apiResponses.shipment.id);
269
+ if (getShipmentResponse.error) {
270
+ throw new Error("Error al intentar recibir el envío: " + getShipmentResponse?.userMsg);
271
+ }
272
+ apiResponses.apiCall = apiResponses.apiCall + 1;
273
+ }
274
+ if (!esCentroDeAcopio) {
275
+ //Al momento de este comentario, un ejemplo es que sólo Planta Central no es centro de acopio
276
+ //Ellos si envían canastas a control de calidad.
277
+ //Si es de un centro de acopio, se salta esto...
278
+ const newQCBasketShipment = await createQCBasketShipmentBody();
279
+ if (apiResponses.apiCall === 5) {
280
+ console.log("------------- REALIZANDO ENVÍO DE CANASTAS A CONTROL DE CALIDAD");
281
+ const new_qc_shipment_response = await (0, services_1.insertBookings)(headers, newQCBasketShipment, `${apiResponses.authorizedPO.id}`);
282
+ if (!new_qc_shipment_response.data || new_qc_shipment_response.error) {
283
+ console.log("Body: ", JSON.stringify(newQCBasketShipment));
284
+ throw new Error("Error al intentar crear el envío a control de calidad: " +
285
+ new_qc_shipment_response?.userMsg);
286
+ }
287
+ apiResponses.apiCall = apiResponses.apiCall + 1;
288
+ apiResponses.qcShipment = new_qc_shipment_response.data;
289
+ }
290
+ if (apiResponses.apiCall === 6) {
291
+ console.log("------------- RECIBIENDO ENVÍO DE CANASTAS A CONTROL DE CALIDAD");
292
+ const getQCDeliveryResponse = await (0, services_1.getDeliveryByBooking)(headers, apiResponses.qcShipment.id);
293
+ if (getQCDeliveryResponse.error) {
294
+ throw new Error("Error al intentar recibir el envío de control de calidad: " +
295
+ getQCDeliveryResponse?.userMsg);
296
+ }
297
+ apiResponses.apiCall = apiResponses.apiCall + 1;
298
+ }
299
+ if (apiResponses.apiCall === 7) {
300
+ if (webapp_table_object.Canastas !== "" &&
301
+ webapp_table_object.Canastas !== "0") {
302
+ console.log("----------- Guardando rechazo de canastas directo...... -----------");
303
+ const responseRechazo = await (0, motivos_rechazo_utils_js_1.saveRechazoCanastas)(headers, session, {
304
+ temp_purchase_order_id: `${apiResponses.authorizedPO.id}`,
305
+ webapp_row: {
306
+ data: webapp_table_object,
307
+ },
308
+ });
309
+ if (responseRechazo.error) {
310
+ throw new Error("Error al intentar guardar el rechazo de canastas directo: " +
311
+ responseRechazo?.userMsg);
312
+ }
313
+ apiResponses.apiCall = apiResponses.apiCall + 1;
314
+ }
315
+ }
316
+ }
317
+ if (esCentroDeAcopio) {
318
+ //Si es centro de acopio, guardo los motivos de rechazo
319
+ if (controlCalidadValues?.razonPrincipal ||
320
+ controlCalidadValues?.razonSecundaria ||
321
+ controlCalidadValues?.razonTerciaria ||
322
+ controlCalidadValues?.otrasRazones) {
323
+ if (apiResponses.apiCall === 5) {
324
+ console.log("========================================>");
325
+ console.log("paso 3: GUARDAR MOTIVOS DE RECHAZO");
326
+ const saveMotivosResponse = await (0, services_1.saveMotivosDeRechazoByPurchase)(headers, session, {
327
+ Razon_primaria: `${controlCalidadValues?.razonPrincipal ?? ""}`,
328
+ Razon_secundaria: `${controlCalidadValues?.razonSecundaria ?? ""}`,
329
+ Razon_terciaria: `${controlCalidadValues?.razonTerciaria ?? ""}`,
330
+ Otras_razones: `${controlCalidadValues?.otrasRazones ?? ""}`,
331
+ }, { temp_purchase_order_id: `${apiResponses.authorizedPO.id}` });
332
+ if (saveMotivosResponse.error) {
333
+ throw new Error("Error al intentar guardar los motivos de rechazo: " +
334
+ saveMotivosResponse?.userMsg);
335
+ }
336
+ }
337
+ }
338
+ }
339
+ console.log("========================================>");
340
+ console.log("paso 4: ELIMINAR EL REGISTRO DE LA COLA");
341
+ //ELIMINAR EL REGISTRO DE LA COLA
342
+ await (0, _4pinos_receptions_form_history_utils_js_1.deleteQueueFormReceptionHistory)(headers, session, idWebAppTable);
343
+ }
344
+ catch (e) {
345
+ //SI OCURRE ALGÚN ERROR, SE INTENTA GUARDAR EL RETRY
346
+ console.log("========================================>");
347
+ console.log("paso -1: ACTUALIZAR EL REGISTRO DE LA COLA A ERROR");
348
+ await (0, _4pinos_receptions_form_history_utils_js_1.updateQueueFormReceptionHistory)(headers, session, {
349
+ estado: _4pinos_receptions_form_history_utils_js_1.ESTADOS_COLA_RECEPCIONES.ERROR,
350
+ description: e?.toString(),
351
+ apiResponses,
352
+ }, idWebAppTable);
353
+ }
354
+ };
355
+ exports.register4pinosReception = register4pinosReception;
@@ -0,0 +1,351 @@
1
+ import { zauruDateToLongString } from "@zauru-sdk/common";
2
+ import { createNewAuthorizedPurchaseOrder, createNewReception, getDeliveryByBooking, getHeaders, getLoteByName, getPurchasesOrderByIdNumber, getSession, getVariablesByName, insertBookings, saveMotivosDeRechazoByPurchase, } from "@zauru-sdk/services";
3
+ import { saveRechazoCanastas } from "./motivos-rechazo.utils.js";
4
+ import { deleteQueueFormReceptionHistory, ESTADOS_COLA_RECEPCIONES, updateQueueFormReceptionHistory, } from "./4pinos-receptions-form-history.utils.js";
5
+ export const register4pinosReception = async ({ cookie, idWebAppTable, agency_id, values, originApiResponses = {}, }) => {
6
+ const session = await getSession(cookie);
7
+ const headers = await getHeaders(cookie, session);
8
+ let apiResponses = {
9
+ apiCall: originApiResponses.apiCall ?? 1,
10
+ ...originApiResponses,
11
+ };
12
+ try {
13
+ if (apiResponses.apiCall === 1) {
14
+ //SI EL API CALL ES DIFERENTE DE 1 SIGNIFICA QUE SOLO VA A REINTENTAR DESDE DONDE FALLÓ
15
+ //Validando que no exista ya una recepción con ese número:
16
+ const responsePOSearch = await getPurchasesOrderByIdNumber(session, values?.idNumberInput);
17
+ if (responsePOSearch.error || !responsePOSearch.data) {
18
+ throw new Error(`No hay comunicación con la red para la validación de exists - Validate Exists: ${responsePOSearch?.userMsg}`);
19
+ }
20
+ const existentes = responsePOSearch?.data?.filter((x) => !x.voided);
21
+ if (existentes?.length > 0) {
22
+ 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: ${zauruDateToLongString(existentes[0].issue_date)}, Memo: ${existentes[0].memo}, Tipo: ${existentes[0].reference}`);
23
+ }
24
+ }
25
+ const esCentroDeAcopio = values?.esCentroDeAcopio === "true";
26
+ const basketLots = JSON.parse(values?.basketLots.toString());
27
+ const webapp_table_rejection = {
28
+ Canastas: "int",
29
+ Razon_primaria: "string",
30
+ Razon_secundaria: "string",
31
+ Razon_terciaria: "string",
32
+ Otras_razones: "string",
33
+ };
34
+ const { recepciones_tag_id: tag_id, recepciones_vendor_agency_id: origin_agency, recepciones_my_quality_control_agency_id, } = await getVariablesByName(headers, session, [
35
+ "recepciones_tag_id",
36
+ "recepciones_vendor_agency_id",
37
+ "recepciones_my_quality_control_agency_id",
38
+ ]);
39
+ // Remplaza los caracteres ':' por '":' y '{ ' por '{"', de esta manera las claves estarán entre comillas dobles
40
+ const fixedString = recepciones_my_quality_control_agency_id
41
+ .replace(/([a-zA-Z0-9_]+):/g, '"$1":')
42
+ .replace("{ ", '{"');
43
+ const hashRecepcionesQCAgency = JSON.parse(fixedString ?? "{}");
44
+ const quality_control_agency = hashRecepcionesQCAgency[agency_id];
45
+ //-------------------REACT SELECT VALUES-------------------------
46
+ const vendor = values.vendor;
47
+ const itemId = values.item;
48
+ const purchaser = values.purchaser;
49
+ const payeeType = values.rType;
50
+ const idNumberInput = values.idNumberInput;
51
+ const discountReason = values.discountReason;
52
+ const issue_date = values.issue_date;
53
+ const rejections = JSON.parse(values.rejections.toString() ?? "[]");
54
+ const provenance = values.selectedProvenance;
55
+ const purchaseOrderGeneralInfo = JSON.parse(values?.purchaseOrderGeneralInfo?.toString() ?? "{}");
56
+ let controlCalidadValues = {
57
+ porcentajeRechazo: values.porcentajeRechazo,
58
+ razonPrincipal: values.razonPrincipal,
59
+ razonSecundaria: values.razonSecundaria,
60
+ razonTerciaria: values.razonTerciaria,
61
+ otrasRazones: values.otrasRazones,
62
+ };
63
+ let keys = Object.keys(values);
64
+ let netWeight = values.netWgt;
65
+ let singleBasketWeight = values.singleBasketWeight;
66
+ const total_baskets = values.totalBaskets + "";
67
+ const stockInteger = values.stockInteger + "" == "true";
68
+ let webapp_table_object = {};
69
+ const buildArray = (keyIncludes, processValue) => {
70
+ return keys
71
+ .filter((key) => key.includes(keyIncludes))
72
+ .map((kbv) => [
73
+ kbv.substring(keyIncludes?.length, kbv?.length),
74
+ processValue(values[kbv]),
75
+ ])
76
+ .filter(([key, value]) => Number(value) > 0)
77
+ .map(([kv, val]) => `${val}-${kv}`);
78
+ };
79
+ const buildSimpleArray = (keyIncludes, processValue) => {
80
+ const regex = /\d/; // Expresión regular para buscar al menos un dígito.
81
+ return keys
82
+ .filter((key) => key.includes(keyIncludes) && regex.test(key))
83
+ .map((kbv) => processValue(values[kbv] === "" ? 0 : values[kbv]));
84
+ };
85
+ const processValues = () => {
86
+ const received_baskets = buildArray("rec", parseInt);
87
+ const qualityControlBaskets = buildArray("qC", parseInt);
88
+ const detail_baskets = buildSimpleArray("basket", parseInt);
89
+ const detail_discounts = buildSimpleArray("discount", parseFloat);
90
+ const detail_weights = buildSimpleArray("weight", parseFloat);
91
+ Object.keys(webapp_table_rejection ?? {})?.forEach((value, index) => {
92
+ const temp = index === 0
93
+ ? values[value]?.toString()
94
+ : rejections[index - 1]?.split(";").join(", ") || "";
95
+ webapp_table_object[value] = temp;
96
+ });
97
+ return [
98
+ received_baskets,
99
+ qualityControlBaskets,
100
+ detail_baskets,
101
+ detail_discounts,
102
+ detail_weights,
103
+ ];
104
+ };
105
+ let [received_baskets, qualityControlBaskets, detail_baskets, detail_discounts, detail_weights,] = processValues();
106
+ //build net_weights
107
+ const detail_netWeights = keys
108
+ .filter((key) => key.includes("weight"))
109
+ .map((kbv, index) => (parseFloat(values[kbv]) -
110
+ (stockInteger
111
+ ? 0
112
+ : detail_baskets[index] * parseFloat(singleBasketWeight))) *
113
+ ((100 - detail_discounts[index]) / 100));
114
+ // //---------------------------PURCHASE ORDER OBJECT----------------------------------
115
+ console.log("========================================>");
116
+ console.log("paso 1: REGISTRANDO NUEVA ORDEN DE COMPRA AUTORIZADA...");
117
+ const newPurchaseOrderDetails = [];
118
+ detail_baskets.forEach((x, index) => {
119
+ newPurchaseOrderDetails.push({
120
+ reference: `${detail_weights[index]},${detail_baskets[index]},${detail_discounts[index]}`,
121
+ item_id: Number(itemId),
122
+ booked_quantity: detail_netWeights[index],
123
+ unit_cost: 1,
124
+ });
125
+ });
126
+ const newPurchaseOrderBody = {
127
+ reference: payeeType,
128
+ taxable: false,
129
+ issue_date,
130
+ shipping_date: issue_date,
131
+ incoterm_id: purchaseOrderGeneralInfo?.incoterm_id,
132
+ currency_id: purchaseOrderGeneralInfo?.currency_id,
133
+ charge_term_id: purchaseOrderGeneralInfo?.charge_term_id,
134
+ payee_info: vendor,
135
+ agency_id,
136
+ purchaser_id: Number(purchaser),
137
+ import: false,
138
+ tag_ids: ["", tag_id],
139
+ memo: qualityControlBaskets + "",
140
+ origin: netWeight,
141
+ purchase_order_details: newPurchaseOrderDetails,
142
+ incoterm_destination: provenance.slice(0, 254),
143
+ transport_type: discountReason,
144
+ id_number: idNumberInput,
145
+ ...(esCentroDeAcopio
146
+ ? { discount: Number(controlCalidadValues.porcentajeRechazo) }
147
+ : {}),
148
+ };
149
+ //========== PRIMERA LLAMADA DE API Y CAPTURA DE ERRORES
150
+ if (apiResponses.apiCall === 1) {
151
+ console.log("REGISTRANDO ORDEN DE COMPRA: ", JSON.stringify(newPurchaseOrderBody));
152
+ const newAuthorizedPurchaseResponse = await createNewAuthorizedPurchaseOrder(headers, newPurchaseOrderBody, false);
153
+ if (newAuthorizedPurchaseResponse?.error ||
154
+ !newAuthorizedPurchaseResponse.data) {
155
+ throw new Error("Error al intentar crear la órden de compra autorizada: " +
156
+ newAuthorizedPurchaseResponse?.userMsg);
157
+ }
158
+ apiResponses.authorizedPO = newAuthorizedPurchaseResponse.data;
159
+ apiResponses.apiCall = apiResponses.apiCall + 1;
160
+ }
161
+ console.log("========================================>");
162
+ console.log("paso 2: CREANDO RECEPCION, ENVIO DE CANASTAS, WEBAPP TABLE DE RECHAZO DIRECTO");
163
+ const createNewReceptionBodyFunction = () => {
164
+ const receptionDetails = {};
165
+ apiResponses.authorizedPO.purchase_order_details.forEach((pod, index) => (receptionDetails[index] = {
166
+ item_id: `${pod.item_id}`,
167
+ purchase_order_detail_id: `${pod.id}`,
168
+ lot_delivered_quantity: [`${pod.booked_quantity}`],
169
+ lot_name: [apiResponses.authorizedPO.id_number],
170
+ lot_expire: [
171
+ new Date(Date.now() + 12096e5).toISOString().split("T")[0],
172
+ ],
173
+ lot_description: [received_baskets.join(",")],
174
+ }));
175
+ const newReception = {
176
+ reception: {
177
+ agency_id,
178
+ received_at: issue_date,
179
+ purchase_order_id: apiResponses.authorizedPO.id + "",
180
+ entity_id: apiResponses.authorizedPO.entity_id + "",
181
+ needs_transit: "0",
182
+ invoice_number: "",
183
+ reception_details_attributes: receptionDetails,
184
+ },
185
+ };
186
+ return newReception;
187
+ };
188
+ const createBasketsShipmentBodyFunction = () => {
189
+ const movementDetails = [];
190
+ received_baskets.forEach((basket, index) => {
191
+ movementDetails.push({
192
+ item_id: basketLots?.recepciones_basket_item_id,
193
+ lot_id: basket.split("-")[1],
194
+ booked_quantity: basket.split("-")[0],
195
+ });
196
+ });
197
+ const BasketShipment = {
198
+ booker_id: Number(purchaser),
199
+ reference: "Envio de canastas (De proveedor a agencia)",
200
+ needs_transport: false,
201
+ planned_delivery: issue_date,
202
+ agency_from_id: Number(origin_agency),
203
+ agency_to_id: agency_id,
204
+ movements: movementDetails,
205
+ };
206
+ return BasketShipment;
207
+ };
208
+ const createQCBasketShipmentBody = async () => {
209
+ const qcMovementDetails = [];
210
+ qualityControlBaskets.forEach((basket) => {
211
+ qcMovementDetails.push({
212
+ item_id: basketLots?.recepciones_basket_item_id,
213
+ lot_id: Number(basket.split("-")[1]),
214
+ booked_quantity: Number(basket.split("-")[0]),
215
+ });
216
+ });
217
+ const total_qc_baskets = parseInt(values.totalQCBaskets + "");
218
+ const basket_weight = parseFloat(netWeight) / parseInt(total_baskets);
219
+ const lotResponse = await getLoteByName(session, apiResponses.authorizedPO.id_number);
220
+ if (lotResponse.error || !lotResponse.data) {
221
+ throw new Error("Error al intentar obtener el lote por nombre: " +
222
+ lotResponse?.userMsg);
223
+ }
224
+ if (lotResponse.data?.id) {
225
+ qcMovementDetails.push({
226
+ item_id: apiResponses.authorizedPO.purchase_order_details[0].item_id,
227
+ lot_id: Number(lotResponse.data.id),
228
+ booked_quantity: Number(Math.round(total_qc_baskets * basket_weight)), //TODO: Revisar si esto está bien así.
229
+ });
230
+ }
231
+ const qcBasketShipment = {
232
+ booker_id: Number(purchaser),
233
+ reference: "Envio de canastas y verduras a CC",
234
+ needs_transport: false,
235
+ planned_delivery: issue_date,
236
+ agency_from_id: agency_id,
237
+ agency_to_id: quality_control_agency,
238
+ movements: qcMovementDetails,
239
+ };
240
+ return qcBasketShipment;
241
+ };
242
+ //first create reception and receive it with the basket shipment
243
+ const newReception = createNewReceptionBodyFunction();
244
+ const newBasketShipment = createBasketsShipmentBodyFunction();
245
+ if (apiResponses.apiCall === 2) {
246
+ console.log("------------ CREANDO RECEPCIÓN.......");
247
+ const responseNewReception = await createNewReception(headers, newReception, apiResponses.authorizedPO.id);
248
+ if (responseNewReception.error || !responseNewReception.data) {
249
+ throw new Error("Error al intentar crear la recepción: " +
250
+ responseNewReception?.userMsg);
251
+ }
252
+ apiResponses.apiCall = apiResponses.apiCall + 1;
253
+ }
254
+ if (apiResponses.apiCall === 3) {
255
+ console.log("------------- REALIZANDO ENVÍO DE CANASTAS A LA AGENCIA");
256
+ const newShipmentResponse = await insertBookings(headers, newBasketShipment, `${apiResponses.authorizedPO.id}`);
257
+ if (newShipmentResponse.error || !newShipmentResponse.data) {
258
+ throw new Error("Error al intentar crear el envío: " + newShipmentResponse?.userMsg);
259
+ }
260
+ apiResponses.apiCall = apiResponses.apiCall + 1;
261
+ apiResponses.shipment = newShipmentResponse.data;
262
+ }
263
+ if (apiResponses.apiCall === 4) {
264
+ console.log("------------- RECIBIENDO EL ENVÍO DE CANASTAS");
265
+ const getShipmentResponse = await getDeliveryByBooking(headers, apiResponses.shipment.id);
266
+ if (getShipmentResponse.error) {
267
+ throw new Error("Error al intentar recibir el envío: " + getShipmentResponse?.userMsg);
268
+ }
269
+ apiResponses.apiCall = apiResponses.apiCall + 1;
270
+ }
271
+ if (!esCentroDeAcopio) {
272
+ //Al momento de este comentario, un ejemplo es que sólo Planta Central no es centro de acopio
273
+ //Ellos si envían canastas a control de calidad.
274
+ //Si es de un centro de acopio, se salta esto...
275
+ const newQCBasketShipment = await createQCBasketShipmentBody();
276
+ if (apiResponses.apiCall === 5) {
277
+ console.log("------------- REALIZANDO ENVÍO DE CANASTAS A CONTROL DE CALIDAD");
278
+ const new_qc_shipment_response = await insertBookings(headers, newQCBasketShipment, `${apiResponses.authorizedPO.id}`);
279
+ if (!new_qc_shipment_response.data || new_qc_shipment_response.error) {
280
+ console.log("Body: ", JSON.stringify(newQCBasketShipment));
281
+ throw new Error("Error al intentar crear el envío a control de calidad: " +
282
+ new_qc_shipment_response?.userMsg);
283
+ }
284
+ apiResponses.apiCall = apiResponses.apiCall + 1;
285
+ apiResponses.qcShipment = new_qc_shipment_response.data;
286
+ }
287
+ if (apiResponses.apiCall === 6) {
288
+ console.log("------------- RECIBIENDO ENVÍO DE CANASTAS A CONTROL DE CALIDAD");
289
+ const getQCDeliveryResponse = await getDeliveryByBooking(headers, apiResponses.qcShipment.id);
290
+ if (getQCDeliveryResponse.error) {
291
+ throw new Error("Error al intentar recibir el envío de control de calidad: " +
292
+ getQCDeliveryResponse?.userMsg);
293
+ }
294
+ apiResponses.apiCall = apiResponses.apiCall + 1;
295
+ }
296
+ if (apiResponses.apiCall === 7) {
297
+ if (webapp_table_object.Canastas !== "" &&
298
+ webapp_table_object.Canastas !== "0") {
299
+ console.log("----------- Guardando rechazo de canastas directo...... -----------");
300
+ const responseRechazo = await saveRechazoCanastas(headers, session, {
301
+ temp_purchase_order_id: `${apiResponses.authorizedPO.id}`,
302
+ webapp_row: {
303
+ data: webapp_table_object,
304
+ },
305
+ });
306
+ if (responseRechazo.error) {
307
+ throw new Error("Error al intentar guardar el rechazo de canastas directo: " +
308
+ responseRechazo?.userMsg);
309
+ }
310
+ apiResponses.apiCall = apiResponses.apiCall + 1;
311
+ }
312
+ }
313
+ }
314
+ if (esCentroDeAcopio) {
315
+ //Si es centro de acopio, guardo los motivos de rechazo
316
+ if (controlCalidadValues?.razonPrincipal ||
317
+ controlCalidadValues?.razonSecundaria ||
318
+ controlCalidadValues?.razonTerciaria ||
319
+ controlCalidadValues?.otrasRazones) {
320
+ if (apiResponses.apiCall === 5) {
321
+ console.log("========================================>");
322
+ console.log("paso 3: GUARDAR MOTIVOS DE RECHAZO");
323
+ const saveMotivosResponse = await saveMotivosDeRechazoByPurchase(headers, session, {
324
+ Razon_primaria: `${controlCalidadValues?.razonPrincipal ?? ""}`,
325
+ Razon_secundaria: `${controlCalidadValues?.razonSecundaria ?? ""}`,
326
+ Razon_terciaria: `${controlCalidadValues?.razonTerciaria ?? ""}`,
327
+ Otras_razones: `${controlCalidadValues?.otrasRazones ?? ""}`,
328
+ }, { temp_purchase_order_id: `${apiResponses.authorizedPO.id}` });
329
+ if (saveMotivosResponse.error) {
330
+ throw new Error("Error al intentar guardar los motivos de rechazo: " +
331
+ saveMotivosResponse?.userMsg);
332
+ }
333
+ }
334
+ }
335
+ }
336
+ console.log("========================================>");
337
+ console.log("paso 4: ELIMINAR EL REGISTRO DE LA COLA");
338
+ //ELIMINAR EL REGISTRO DE LA COLA
339
+ await deleteQueueFormReceptionHistory(headers, session, idWebAppTable);
340
+ }
341
+ catch (e) {
342
+ //SI OCURRE ALGÚN ERROR, SE INTENTA GUARDAR EL RETRY
343
+ console.log("========================================>");
344
+ console.log("paso -1: ACTUALIZAR EL REGISTRO DE LA COLA A ERROR");
345
+ await updateQueueFormReceptionHistory(headers, session, {
346
+ estado: ESTADOS_COLA_RECEPCIONES.ERROR,
347
+ description: e?.toString(),
348
+ apiResponses,
349
+ }, idWebAppTable);
350
+ }
351
+ };
@@ -0,0 +1 @@
1
+ export declare const register4pinosReception: ({ cookie, idWebAppTable, agency_id, values, originApiResponses, }: any) => Promise<void>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zauru-sdk/utils",
3
- "version": "1.0.93",
3
+ "version": "1.0.95",
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.88",
28
+ "@zauru-sdk/common": "^1.0.95",
29
29
  "@zauru-sdk/config": "^1.0.60",
30
- "@zauru-sdk/graphql": "^1.0.93",
31
- "@zauru-sdk/services": "^1.0.93",
32
- "@zauru-sdk/types": "^1.0.88"
30
+ "@zauru-sdk/graphql": "^1.0.94",
31
+ "@zauru-sdk/services": "^1.0.95",
32
+ "@zauru-sdk/types": "^1.0.95"
33
33
  },
34
- "gitHead": "a4e373756557e03f71ada4063312c34945737bb7"
34
+ "gitHead": "b9bc25c0b055b244f322740a211facdd0aa8b5ba"
35
35
  }