@zauru-sdk/utils 1.0.62 → 1.0.64

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.
@@ -33,254 +33,256 @@ exports.getLotesFormated = getLotesFormated;
33
33
  * @param byPercent
34
34
  */
35
35
  const procesarLote = async (headers, session, data, poId) => {
36
- //=====================================================================================
37
- //=====================================================================================
38
- //PASO 1: OBTENER TODAS LAS VARIABLES QUE VAMOS A UTILIZAR EN EL FLUJO
39
- const { production_agency, operative_rejection_agency_id, recepciones_basket_item_id: basket_id, } = await (0, services_1.getVariablesByName)(headers, session, [
40
- "production_agency",
41
- "operative_rejection_agency_id",
42
- "recepciones_basket_item_id",
43
- ]);
44
- const session_agency_id = session.get("agency_id");
45
- const hashObject = JSON.parse(operative_rejection_agency_id);
46
- const op_rejection_agency_id = hashObject[session_agency_id];
47
- //PARSEO DE LA INFORMACIÓN QUE VIENE DEL SUBMIT
48
- const byPercent = data.byPercent === "true";
49
- const porcentajeRechazo = !byPercent
50
- ? (0, common_1.toFixedIfNeeded)((Number(data.lbRechazo ?? "0") /
51
- (Number(data?.lbRechazo ?? "0") + Number(data.lbBueno))) *
52
- 100)
53
- : data.porcentajeRechazo;
54
- const basket_keys = Object.keys(data).filter((x) => x.includes("basket-"));
55
- const baskets_regresadas = basket_keys.map((basket_key) => {
56
- //ejemplo de una key: basket-CONVENCIONAL-58281
57
- const splited = basket_key.split("-");
58
- return {
59
- id: splited[2] || 0,
60
- color: splited[1] || "",
61
- total: Number(data[basket_key]) || 0,
62
- };
63
- });
64
- //1.2 OBTENER LA INFORMACIÓN DEL LOTE A PROCESAR (LA TOMO DE LA QUE YA TENGO AL CARGAR LA INFO)
65
- const purchaseOrderResponse = await (0, services_1.getPurchaseOrder)(session, poId, {
66
- withLotStocksToMyAgency: true,
67
- });
68
- if (purchaseOrderResponse.error || !purchaseOrderResponse?.data) {
69
- throw new Error(`Error al intentar encontrar la órden de compra: ${purchaseOrderResponse.userMsg}`);
70
- }
71
- const purchaseOrder = purchaseOrderResponse.data;
72
- const lbsEsperadas = purchaseOrder.lots[0].lot_stocks[0].available;
73
- const lbsMalas = lbsEsperadas * (Number(porcentajeRechazo) / 100);
74
- const lbsBuenas = lbsEsperadas - lbsMalas;
75
- const baskets_memo = (0, common_1.getBasketsSchema)(purchaseOrder.memo);
76
- const baskets_memo_quantity = baskets_memo
77
- .map((basket) => basket.total)
78
- .reduce(common_1.reduceAdd, 0);
79
- //SI SE INGRESA POR LIBRAS, ES QUE SE ESTÁ INGRESANDO CANASTAS A DEVOLVER ETC Y HAY QUE HACER LOS ENVÍOS CORRESPONDIENTES
80
- if (!byPercent) {
81
- console.log("=============> PROCESANDO DATA POR PESO...");
82
- //CUANDO NO ES POR PORCENTAJE DIRECTO HAY QUE HACER TODO EL FLUJO DE CREAR LOS ENVÍOS ETC...
83
- //1.3: SE CREA EL ENVÍO DE VEGETALES Y CANASTAS DEVUELTOS POR CONTROL DE CALIDAD, (LOS QUE ESTÁN BUENOS)
84
- //Las canastas vienen en data en campos como estos "basket-CONVENCIONAL-58281": "2",
85
- const bodyGoodToProduction = {
86
- booker_id: Number(session.get("employee_id")),
87
- needs_transport: false,
88
- payee_id: purchaseOrder.payee_id,
89
- memo: `${purchaseOrder.lots[0].id};${purchaseOrder.id_number};${purchaseOrder.purchase_order_details[0]?.item?.name};${purchaseOrder.purchase_order_details
90
- .map((purchase) => Number(purchase.booked_quantity))
91
- .reduce(common_1.reduceAdd, 0)};${baskets_memo_quantity};${porcentajeRechazo};${purchaseOrder.delivery_date}`,
92
- planned_delivery: `${data.date}`,
93
- agency_from_id: Number(session_agency_id), //agencia donde está loggeado mi usuario
94
- agency_to_id: purchaseOrder.agency_id, //de donde viene la orden de compra
95
- reference: "Vegetales buenos devueltos desde control de calidad.",
96
- movements: [
97
- {
98
- item_id: purchaseOrder.purchase_order_details[0].item_id,
99
- lot_id: purchaseOrder.lots[0].id,
100
- reference: "Vegetales devueltos de CC",
101
- booked_quantity: lbsBuenas,
102
- },
103
- ],
104
- };
105
- /**
106
- * Para las canastas
107
- * el item_id = 490533 = recepciones_basket_item_id
108
- * lot_id: código de la canasta,
109
- * booked_quantity = cantidad de canastas que ingresa el usuario que va a devolver
110
- */
111
- baskets_regresadas.forEach((basket) => {
112
- bodyGoodToProduction.movements.push({
113
- item_id: Number(basket_id),
114
- lot_id: basket.id,
115
- reference: `Canasta ${basket.color}-${basket.id} devuelta a CC`,
116
- booked_quantity: basket.total,
117
- });
36
+ return (0, common_1.handlePossibleAxiosErrors)(async () => {
37
+ //=====================================================================================
38
+ //=====================================================================================
39
+ //PASO 1: OBTENER TODAS LAS VARIABLES QUE VAMOS A UTILIZAR EN EL FLUJO
40
+ const { production_agency, operative_rejection_agency_id, recepciones_basket_item_id: basket_id, } = await (0, services_1.getVariablesByName)(headers, session, [
41
+ "production_agency",
42
+ "operative_rejection_agency_id",
43
+ "recepciones_basket_item_id",
44
+ ]);
45
+ const session_agency_id = session.get("agency_id");
46
+ const hashObject = JSON.parse(operative_rejection_agency_id);
47
+ const op_rejection_agency_id = hashObject[session_agency_id];
48
+ //PARSEO DE LA INFORMACIÓN QUE VIENE DEL SUBMIT
49
+ const byPercent = data.byPercent === "true";
50
+ const porcentajeRechazo = !byPercent
51
+ ? (0, common_1.toFixedIfNeeded)((Number(data.lbRechazo ?? "0") /
52
+ (Number(data?.lbRechazo ?? "0") + Number(data.lbBueno))) *
53
+ 100)
54
+ : data.porcentajeRechazo;
55
+ const basket_keys = Object.keys(data).filter((x) => x.includes("basket-"));
56
+ const baskets_regresadas = basket_keys.map((basket_key) => {
57
+ //ejemplo de una key: basket-CONVENCIONAL-58281
58
+ const splited = basket_key.split("-");
59
+ return {
60
+ id: splited[2] || 0,
61
+ color: splited[1] || "",
62
+ total: Number(data[basket_key]) || 0,
63
+ };
118
64
  });
119
- console.log("-------- Insertando booking con canastas buenas devueltas");
120
- const goodVegetablesInserted = await (0, services_1.insertBookings)(headers, bodyGoodToProduction, `${purchaseOrder.id}`);
121
- if (!goodVegetablesInserted.error && goodVegetablesInserted.data) {
122
- //1.4 Recibir la reserva para que las cantidades se muevan correctamente a la bodega de destino
123
- console.log("recibiendo la reserva: ", goodVegetablesInserted.data?.id);
124
- await (0, services_1.getDeliveryByBooking)(headers, goodVegetablesInserted.data?.id);
65
+ //1.2 OBTENER LA INFORMACIÓN DEL LOTE A PROCESAR (LA TOMO DE LA QUE YA TENGO AL CARGAR LA INFO)
66
+ const purchaseOrderResponse = await (0, services_1.getPurchaseOrder)(session, poId, {
67
+ withLotStocksToMyAgency: true,
68
+ });
69
+ if (purchaseOrderResponse.error || !purchaseOrderResponse?.data) {
70
+ throw new Error(`Error al intentar encontrar la órden de compra: ${purchaseOrderResponse.userMsg}`);
125
71
  }
126
- if (lbsMalas && lbsMalas > 0) {
127
- //=====================================================================================
128
- //=====================================================================================
129
- //PASO 2: Envío con vegetales rechazados a bodega de PRODUCCIÓN desde la agencia del usuario loggeado
130
- const bodyOchToProduction = {
72
+ const purchaseOrder = purchaseOrderResponse.data;
73
+ const lbsEsperadas = purchaseOrder.lots[0].lot_stocks[0].available;
74
+ const lbsMalas = lbsEsperadas * (Number(porcentajeRechazo) / 100);
75
+ const lbsBuenas = lbsEsperadas - lbsMalas;
76
+ const baskets_memo = (0, common_1.getBasketsSchema)(purchaseOrder.memo);
77
+ const baskets_memo_quantity = baskets_memo
78
+ .map((basket) => basket.total)
79
+ .reduce(common_1.reduceAdd, 0);
80
+ //SI SE INGRESA POR LIBRAS, ES QUE SE ESTÁ INGRESANDO CANASTAS A DEVOLVER ETC Y HAY QUE HACER LOS ENVÍOS CORRESPONDIENTES
81
+ if (!byPercent) {
82
+ console.log("=============> PROCESANDO DATA POR PESO...");
83
+ //CUANDO NO ES POR PORCENTAJE DIRECTO HAY QUE HACER TODO EL FLUJO DE CREAR LOS ENVÍOS ETC...
84
+ //1.3: SE CREA EL ENVÍO DE VEGETALES Y CANASTAS DEVUELTOS POR CONTROL DE CALIDAD, (LOS QUE ESTÁN BUENOS)
85
+ //Las canastas vienen en data en campos como estos "basket-CONVENCIONAL-58281": "2",
86
+ const bodyGoodToProduction = {
131
87
  booker_id: Number(session.get("employee_id")),
132
88
  needs_transport: false,
133
- memo: "",
89
+ payee_id: purchaseOrder.payee_id,
90
+ memo: `${purchaseOrder.lots[0].id};${purchaseOrder.id_number};${purchaseOrder.purchase_order_details[0]?.item?.name};${purchaseOrder.purchase_order_details
91
+ .map((purchase) => Number(purchase.booked_quantity))
92
+ .reduce(common_1.reduceAdd, 0)};${baskets_memo_quantity};${porcentajeRechazo};${purchaseOrder.delivery_date}`,
134
93
  planned_delivery: `${data.date}`,
135
94
  agency_from_id: Number(session_agency_id), //agencia donde está loggeado mi usuario
136
- agency_to_id: Number(production_agency), //de donde viene la orden de compra
137
- reference: "Envío de vegetales rechazados a la bodega de producción.",
95
+ agency_to_id: purchaseOrder.agency_id, //de donde viene la orden de compra
96
+ reference: "Vegetales buenos devueltos desde control de calidad.",
138
97
  movements: [
139
98
  {
140
99
  item_id: purchaseOrder.purchase_order_details[0].item_id,
141
100
  lot_id: purchaseOrder.lots[0].id,
142
- reference: "Vegetales rechazados de CC",
143
- booked_quantity: lbsMalas,
101
+ reference: "Vegetales devueltos de CC",
102
+ booked_quantity: lbsBuenas,
144
103
  },
145
104
  ],
146
105
  };
147
- console.log("--------- enviando a insertar booking de rechazo a la bodega de producción");
148
- const ochToProductionVegetablesInserted = await (0, services_1.insertBookings)(headers, bodyOchToProduction, `${purchaseOrder.id}`);
149
- if (!ochToProductionVegetablesInserted.error &&
150
- ochToProductionVegetablesInserted.data) {
151
- //2.1 Recibir la reserva para que las cantidades se muevan correctamente a la bodega de destino
152
- console.log("Recibiendo booking de rechazo...");
153
- await (0, services_1.getDeliveryByBooking)(headers, ochToProductionVegetablesInserted.data.id);
106
+ /**
107
+ * Para las canastas
108
+ * el item_id = 490533 = recepciones_basket_item_id
109
+ * lot_id: código de la canasta,
110
+ * booked_quantity = cantidad de canastas que ingresa el usuario que va a devolver
111
+ */
112
+ baskets_regresadas.forEach((basket) => {
113
+ bodyGoodToProduction.movements.push({
114
+ item_id: Number(basket_id),
115
+ lot_id: basket.id,
116
+ reference: `Canasta ${basket.color}-${basket.id} devuelta a CC`,
117
+ booked_quantity: basket.total,
118
+ });
119
+ });
120
+ console.log("-------- Insertando booking con canastas buenas devueltas");
121
+ const goodVegetablesInserted = await (0, services_1.insertBookings)(headers, bodyGoodToProduction, `${purchaseOrder.id}`);
122
+ if (!goodVegetablesInserted.error && goodVegetablesInserted.data) {
123
+ //1.4 Recibir la reserva para que las cantidades se muevan correctamente a la bodega de destino
124
+ console.log("recibiendo la reserva: ", goodVegetablesInserted.data?.id);
125
+ await (0, services_1.getDeliveryByBooking)(headers, goodVegetablesInserted.data?.id);
126
+ }
127
+ if (lbsMalas && lbsMalas > 0) {
128
+ //=====================================================================================
129
+ //=====================================================================================
130
+ //PASO 2: Envío con vegetales rechazados a bodega de PRODUCCIÓN desde la agencia del usuario loggeado
131
+ const bodyOchToProduction = {
132
+ booker_id: Number(session.get("employee_id")),
133
+ needs_transport: false,
134
+ memo: "",
135
+ planned_delivery: `${data.date}`,
136
+ agency_from_id: Number(session_agency_id), //agencia donde está loggeado mi usuario
137
+ agency_to_id: Number(production_agency), //de donde viene la orden de compra
138
+ reference: "Envío de vegetales rechazados a la bodega de producción.",
139
+ movements: [
140
+ {
141
+ item_id: purchaseOrder.purchase_order_details[0].item_id,
142
+ lot_id: purchaseOrder.lots[0].id,
143
+ reference: "Vegetales rechazados de CC",
144
+ booked_quantity: lbsMalas,
145
+ },
146
+ ],
147
+ };
148
+ console.log("--------- enviando a insertar booking de rechazo a la bodega de producción");
149
+ const ochToProductionVegetablesInserted = await (0, services_1.insertBookings)(headers, bodyOchToProduction, `${purchaseOrder.id}`);
150
+ if (!ochToProductionVegetablesInserted.error &&
151
+ ochToProductionVegetablesInserted.data) {
152
+ //2.1 Recibir la reserva para que las cantidades se muevan correctamente a la bodega de destino
153
+ console.log("Recibiendo booking de rechazo...");
154
+ await (0, services_1.getDeliveryByBooking)(headers, ochToProductionVegetablesInserted.data.id);
155
+ }
156
+ //=====================================================================================
157
+ //=====================================================================================
158
+ //PASO 3: Envío con vegetales rechazados a bodega de RECHAZO desde la bodega de PRODUCCIÓN
159
+ //Sólo cambia el agency_from_id y el agency_to_id, de ahí lo demás lo mismo que PASO 2
160
+ bodyOchToProduction.agency_from_id = Number(production_agency);
161
+ bodyOchToProduction.agency_to_id = Number(op_rejection_agency_id);
162
+ bodyOchToProduction.reference =
163
+ "Envío de vegetales rechazados a la bodega de rechazo.";
164
+ console.log("--------- enviando a insertar booking de rechazo a la bodega de rechazo");
165
+ const ochToOchVegetablesInserted = await (0, services_1.insertBookings)(headers, bodyOchToProduction);
166
+ if (!ochToOchVegetablesInserted.error &&
167
+ ochToOchVegetablesInserted.data) {
168
+ //3.1 Recibir la reserva para que las cantidades se muevan correctamente a la bodega de destino
169
+ await (0, services_1.getDeliveryByBooking)(headers, ochToOchVegetablesInserted.data?.id);
170
+ }
154
171
  }
155
172
  //=====================================================================================
156
173
  //=====================================================================================
157
- //PASO 3: Envío con vegetales rechazados a bodega de RECHAZO desde la bodega de PRODUCCIÓN
158
- //Sólo cambia el agency_from_id y el agency_to_id, de ahí lo demás lo mismo que PASO 2
159
- bodyOchToProduction.agency_from_id = Number(production_agency);
160
- bodyOchToProduction.agency_to_id = Number(op_rejection_agency_id);
161
- bodyOchToProduction.reference =
162
- "Envío de vegetales rechazados a la bodega de rechazo.";
163
- console.log("--------- enviando a insertar booking de rechazo a la bodega de rechazo");
164
- const ochToOchVegetablesInserted = await (0, services_1.insertBookings)(headers, bodyOchToProduction);
165
- if (!ochToOchVegetablesInserted.error &&
166
- ochToOchVegetablesInserted.data) {
167
- //3.1 Recibir la reserva para que las cantidades se muevan correctamente a la bodega de destino
168
- await (0, services_1.getDeliveryByBooking)(headers, ochToOchVegetablesInserted.data?.id);
174
+ //PASO 5: Modificación de canastas en el lote de verdura
175
+ //la misma description del detalle del lote pero modificando la cantidad de canastas que quedaron.
176
+ //ejemplo: original: 27-53311-VERDE,1-53313-ROJA,1-53317-CELESTE,3-53312-AZUL,3-53314-AMARILLA
177
+ //ahora: 27-53311-VERDE,1-53313-ROJA,1-53317-CELESTE,2-53312-AZUL,3-53314-AMARILLA // ahora sólo 2 azules porque no devolví una
178
+ const newDescriptions = [];
179
+ baskets_memo.forEach((basket) => {
180
+ //Si existe una basket a regresar con el mismo id, pregunto cuantas va a regresar, para restarlas del total.
181
+ const basket_regresada = baskets_regresadas.find((x) => x.id === basket.id);
182
+ const resta = basket_regresada?.total ?? 0;
183
+ newDescriptions.push(`${basket.total - resta}-${basket.id}-${basket.color}`);
184
+ });
185
+ await (0, services_1.updateLote)(headers, purchaseOrder.lots[0].id, {
186
+ lot: {
187
+ description: newDescriptions.join(","),
188
+ },
189
+ });
190
+ }
191
+ else {
192
+ console.log("PROCESANDO DATA POR PORCENTAJE...");
193
+ //CUANDO NO ES POR PORCENTAJE DIRECTO HAY QUE HACER TODO EL FLUJO DE CREAR LOS ENVÍOS ETC...
194
+ //1.3: SE CREA EL ENVÍO DE VEGETALES Y CANASTAS DEVUELTOS POR CONTROL DE CALIDAD, (LOS QUE ESTÁN BUENOS)
195
+ //Las canastas vienen en data en campos como estos "basket-CONVENCIONAL-58281": "2",
196
+ const bodyGoodToProduction = {
197
+ booker_id: Number(session.get("employee_id")),
198
+ needs_transport: false,
199
+ payee_id: purchaseOrder.payee_id,
200
+ memo: `${purchaseOrder.lots[0].id};${purchaseOrder.lots[0].name};${purchaseOrder.purchase_order_details[0]?.item?.name};${purchaseOrder.purchase_order_details
201
+ .map((detail) => Number(detail.booked_quantity))
202
+ .reduce(common_1.reduceAdd, 0)};${baskets_memo_quantity};${porcentajeRechazo};${purchaseOrder.delivery_date}`,
203
+ planned_delivery: `${data.date}`,
204
+ agency_from_id: Number(session_agency_id), //agencia donde está loggeado mi usuario
205
+ agency_to_id: purchaseOrder.agency_id, //de donde viene la orden de compra
206
+ reference: "Regreando vegetales buenos desde control de calidad.",
207
+ movements: [
208
+ {
209
+ item_id: purchaseOrder.purchase_order_details[0].item_id,
210
+ lot_id: purchaseOrder.lots[0].id,
211
+ reference: "Vegetales devueltos de CC",
212
+ booked_quantity: lbsEsperadas, //devuelvo la misma cantidad que fue enviada
213
+ },
214
+ ],
215
+ };
216
+ /**
217
+ * Para las canastas
218
+ * el item_id = 490533 = recepciones_basket_item_id
219
+ * lot_id: código de la canasta,
220
+ * booked_quantity = cantidad de canastas que ingresa el usuario que va a devolver
221
+ */
222
+ //Todas las canastas que fueron enviadas originalmente
223
+ baskets_memo.forEach((basket) => {
224
+ bodyGoodToProduction.movements.push({
225
+ item_id: Number(basket_id),
226
+ lot_id: basket.id,
227
+ reference: `Canasta ${basket.color}-${basket.id} devuelta a CC`,
228
+ booked_quantity: basket.total,
229
+ });
230
+ });
231
+ console.log("-------- Insertando booking con canastas buenas devueltas");
232
+ const goodVegetablesInserted = await (0, services_1.insertBookings)(headers, bodyGoodToProduction, `${purchaseOrder.id}`);
233
+ //1.4 Recibir la reserva para que las cantidades se muevan correctamente a la bodega de destino
234
+ if (!goodVegetablesInserted.error && goodVegetablesInserted.data) {
235
+ console.log("A RECIBIR BOOKING - POR PORCENTAJE");
236
+ await (0, services_1.getDeliveryByBooking)(headers, goodVegetablesInserted.data.id);
169
237
  }
170
238
  }
171
239
  //=====================================================================================
172
240
  //=====================================================================================
173
- //PASO 5: Modificación de canastas en el lote de verdura
174
- //la misma description del detalle del lote pero modificando la cantidad de canastas que quedaron.
175
- //ejemplo: original: 27-53311-VERDE,1-53313-ROJA,1-53317-CELESTE,3-53312-AZUL,3-53314-AMARILLA
176
- //ahora: 27-53311-VERDE,1-53313-ROJA,1-53317-CELESTE,2-53312-AZUL,3-53314-AMARILLA // ahora sólo 2 azules porque no devolví una
177
- const newDescriptions = [];
178
- baskets_memo.forEach((basket) => {
179
- //Si existe una basket a regresar con el mismo id, pregunto cuantas va a regresar, para restarlas del total.
180
- const basket_regresada = baskets_regresadas.find((x) => x.id === basket.id);
181
- const resta = basket_regresada?.total ?? 0;
182
- newDescriptions.push(`${basket.total - resta}-${basket.id}-${basket.color}`);
183
- });
184
- await (0, services_1.updateLote)(headers, purchaseOrder.lots[0].id, {
185
- lot: {
186
- description: newDescriptions.join(","),
187
- },
188
- });
189
- }
190
- else {
191
- console.log("PROCESANDO DATA POR PORCENTAJE...");
192
- //CUANDO NO ES POR PORCENTAJE DIRECTO HAY QUE HACER TODO EL FLUJO DE CREAR LOS ENVÍOS ETC...
193
- //1.3: SE CREA EL ENVÍO DE VEGETALES Y CANASTAS DEVUELTOS POR CONTROL DE CALIDAD, (LOS QUE ESTÁN BUENOS)
194
- //Las canastas vienen en data en campos como estos "basket-CONVENCIONAL-58281": "2",
195
- const bodyGoodToProduction = {
196
- booker_id: Number(session.get("employee_id")),
197
- needs_transport: false,
198
- payee_id: purchaseOrder.payee_id,
199
- memo: `${purchaseOrder.lots[0].id};${purchaseOrder.lots[0].name};${purchaseOrder.purchase_order_details[0]?.item?.name};${purchaseOrder.purchase_order_details
200
- .map((detail) => Number(detail.booked_quantity))
201
- .reduce(common_1.reduceAdd, 0)};${baskets_memo_quantity};${porcentajeRechazo};${purchaseOrder.delivery_date}`,
202
- planned_delivery: `${data.date}`,
203
- agency_from_id: Number(session_agency_id), //agencia donde está loggeado mi usuario
204
- agency_to_id: purchaseOrder.agency_id, //de donde viene la orden de compra
205
- reference: "Regreando vegetales buenos desde control de calidad.",
206
- movements: [
207
- {
208
- item_id: purchaseOrder.purchase_order_details[0].item_id,
209
- lot_id: purchaseOrder.lots[0].id,
210
- reference: "Vegetales devueltos de CC",
211
- booked_quantity: lbsEsperadas, //devuelvo la misma cantidad que fue enviada
212
- },
213
- ],
241
+ //PASO 4: Modificación de porcentaje de rechazo en la orden de compra
242
+ //4.1 El primer paso es devolver la recepción recibida en la orden de compra.
243
+ //Primero se debe obtener el id de dicha recepción
244
+ const reception = purchaseOrder.receptions[0];
245
+ const reception_details = reception?.reception_details[0];
246
+ //4.2 Habilito la orden de compra
247
+ await (0, services_1.enablePurchase)(headers, purchaseOrder.id, reception?.id);
248
+ //4.3 Editar porcentajes de rechazo
249
+ const updateBodyPurchase = {
250
+ purchase_order: { discount: porcentajeRechazo },
214
251
  };
215
- /**
216
- * Para las canastas
217
- * el item_id = 490533 = recepciones_basket_item_id
218
- * lot_id: código de la canasta,
219
- * booked_quantity = cantidad de canastas que ingresa el usuario que va a devolver
220
- */
221
- //Todas las canastas que fueron enviadas originalmente
222
- baskets_memo.forEach((basket) => {
223
- bodyGoodToProduction.movements.push({
224
- item_id: Number(basket_id),
225
- lot_id: basket.id,
226
- reference: `Canasta ${basket.color}-${basket.id} devuelta a CC`,
227
- booked_quantity: basket.total,
228
- });
229
- });
230
- console.log("-------- Insertando booking con canastas buenas devueltas");
231
- const goodVegetablesInserted = await (0, services_1.insertBookings)(headers, bodyGoodToProduction, `${purchaseOrder.id}`);
232
- //1.4 Recibir la reserva para que las cantidades se muevan correctamente a la bodega de destino
233
- if (!goodVegetablesInserted.error && goodVegetablesInserted.data) {
234
- console.log("A RECIBIR BOOKING - POR PORCENTAJE");
235
- await (0, services_1.getDeliveryByBooking)(headers, goodVegetablesInserted.data.id);
236
- }
237
- }
238
- //=====================================================================================
239
- //=====================================================================================
240
- //PASO 4: Modificación de porcentaje de rechazo en la orden de compra
241
- //4.1 El primer paso es devolver la recepción recibida en la orden de compra.
242
- //Primero se debe obtener el id de dicha recepción
243
- const reception = purchaseOrder.receptions[0];
244
- const reception_details = reception?.reception_details[0];
245
- //4.2 Habilito la orden de compra
246
- await (0, services_1.enablePurchase)(headers, purchaseOrder.id, reception?.id);
247
- //4.3 Editar porcentajes de rechazo
248
- const updateBodyPurchase = {
249
- purchase_order: { discount: porcentajeRechazo },
250
- };
251
- await (0, services_1.updatePurchaseOrder)(headers, updateBodyPurchase, purchaseOrder.id);
252
- //4.4 Crear una nueva recepcion
253
- const bodyReception = {
254
- reception: {
255
- agency_id: reception.agency_id,
256
- entity_id: reception.entity_id,
257
- needs_transit: false,
258
- purchase_order_id: purchaseOrder.id,
259
- received_at: new Date(Date.now() + 12096e5).toISOString().split("T")[0],
260
- invoice_number: `${reception.invoice_number ?? ""}`,
261
- reception_details_attributes: {
262
- "0": {
263
- item_id: `${reception_details?.item_id}`,
264
- lot_delivered_quantity: [reception_details?.lot_delivered_quantity],
265
- lot_description: [reception_details?.lot_description],
266
- lot_expire: [reception_details?.lot_expire],
267
- lot_name: [reception_details?.lot_name],
268
- purchase_order_detail_id: `${reception_details?.purchase_order_detail_id}`,
252
+ await (0, services_1.updatePurchaseOrder)(headers, updateBodyPurchase, purchaseOrder.id);
253
+ //4.4 Crear una nueva recepcion
254
+ const bodyReception = {
255
+ reception: {
256
+ agency_id: reception.agency_id,
257
+ entity_id: reception.entity_id,
258
+ needs_transit: false,
259
+ purchase_order_id: purchaseOrder.id,
260
+ received_at: new Date(Date.now() + 12096e5).toISOString().split("T")[0],
261
+ invoice_number: `${reception.invoice_number ?? ""}`,
262
+ reception_details_attributes: {
263
+ "0": {
264
+ item_id: `${reception_details?.item_id}`,
265
+ lot_delivered_quantity: [reception_details?.lot_delivered_quantity],
266
+ lot_description: [reception_details?.lot_description],
267
+ lot_expire: [reception_details?.lot_expire],
268
+ lot_name: [reception_details?.lot_name],
269
+ purchase_order_detail_id: `${reception_details?.purchase_order_detail_id}`,
270
+ },
269
271
  },
270
272
  },
271
- },
272
- };
273
- await (0, services_1.createNewReception)(headers, bodyReception, purchaseOrder.id);
274
- //=====================================================================================
275
- //=====================================================================================
276
- //PASO 6: Guardar razones de rechazo en webapp table
277
- await (0, services_1.saveMotivosDeRechazoByPurchase)(headers, session, {
278
- Razon_primaria: `${data.razonPrincipal ?? ""}`,
279
- Razon_secundaria: `${data.razonSecundaria ?? ""}`,
280
- Razon_terciaria: `${data.razonTerciaria ?? ""}`,
281
- Canastas: `${data.ochBaskets ?? ""}`,
282
- }, {
283
- temp_purchase_order_id: `${purchaseOrder.id}`,
273
+ };
274
+ await (0, services_1.createNewReception)(headers, bodyReception, purchaseOrder.id);
275
+ //=====================================================================================
276
+ //=====================================================================================
277
+ //PASO 6: Guardar razones de rechazo en webapp table
278
+ await (0, services_1.saveMotivosDeRechazoByPurchase)(headers, session, {
279
+ Razon_primaria: `${data.razonPrincipal ?? ""}`,
280
+ Razon_secundaria: `${data.razonSecundaria ?? ""}`,
281
+ Razon_terciaria: `${data.razonTerciaria ?? ""}`,
282
+ Canastas: `${data.ochBaskets ?? ""}`,
283
+ }, {
284
+ temp_purchase_order_id: `${purchaseOrder.id}`,
285
+ });
284
286
  });
285
287
  };
286
288
  exports.procesarLote = procesarLote;
@@ -1,5 +1,5 @@
1
- import { getBasketsSchema, reduceAdd, toFixedIfNeeded } from "@zauru-sdk/common";
2
- import { createNewReception, enablePurchase, getDeliveryByBooking, getLote, getLotesFiltered, getPurchase, getPurchaseOrder, getVariablesByName, insertBookings, saveMotivosDeRechazoByPurchase, updateLote, updatePurchaseOrder } from "@zauru-sdk/services";
1
+ import { getBasketsSchema, handlePossibleAxiosErrors, reduceAdd, toFixedIfNeeded, } from "@zauru-sdk/common";
2
+ import { createNewReception, enablePurchase, getDeliveryByBooking, getLote, getLotesFiltered, getPurchase, getPurchaseOrder, getVariablesByName, insertBookings, saveMotivosDeRechazoByPurchase, updateLote, updatePurchaseOrder, } from "@zauru-sdk/services";
3
3
  import { getPurchaseOrderDataTables } from "./purchase-orders.utils.js";
4
4
  /**
5
5
  * Obtiene el listado de ordenes de compra, formateado especialmente para armar la tabla de edición de porcentajes de rechazo
@@ -29,254 +29,256 @@ export const getLotesFormated = async (headers, session) => {
29
29
  * @param byPercent
30
30
  */
31
31
  export const procesarLote = async (headers, session, data, poId) => {
32
- //=====================================================================================
33
- //=====================================================================================
34
- //PASO 1: OBTENER TODAS LAS VARIABLES QUE VAMOS A UTILIZAR EN EL FLUJO
35
- const { production_agency, operative_rejection_agency_id, recepciones_basket_item_id: basket_id, } = await getVariablesByName(headers, session, [
36
- "production_agency",
37
- "operative_rejection_agency_id",
38
- "recepciones_basket_item_id",
39
- ]);
40
- const session_agency_id = session.get("agency_id");
41
- const hashObject = JSON.parse(operative_rejection_agency_id);
42
- const op_rejection_agency_id = hashObject[session_agency_id];
43
- //PARSEO DE LA INFORMACIÓN QUE VIENE DEL SUBMIT
44
- const byPercent = data.byPercent === "true";
45
- const porcentajeRechazo = !byPercent
46
- ? toFixedIfNeeded((Number(data.lbRechazo ?? "0") /
47
- (Number(data?.lbRechazo ?? "0") + Number(data.lbBueno))) *
48
- 100)
49
- : data.porcentajeRechazo;
50
- const basket_keys = Object.keys(data).filter((x) => x.includes("basket-"));
51
- const baskets_regresadas = basket_keys.map((basket_key) => {
52
- //ejemplo de una key: basket-CONVENCIONAL-58281
53
- const splited = basket_key.split("-");
54
- return {
55
- id: splited[2] || 0,
56
- color: splited[1] || "",
57
- total: Number(data[basket_key]) || 0,
58
- };
59
- });
60
- //1.2 OBTENER LA INFORMACIÓN DEL LOTE A PROCESAR (LA TOMO DE LA QUE YA TENGO AL CARGAR LA INFO)
61
- const purchaseOrderResponse = await getPurchaseOrder(session, poId, {
62
- withLotStocksToMyAgency: true,
63
- });
64
- if (purchaseOrderResponse.error || !purchaseOrderResponse?.data) {
65
- throw new Error(`Error al intentar encontrar la órden de compra: ${purchaseOrderResponse.userMsg}`);
66
- }
67
- const purchaseOrder = purchaseOrderResponse.data;
68
- const lbsEsperadas = purchaseOrder.lots[0].lot_stocks[0].available;
69
- const lbsMalas = lbsEsperadas * (Number(porcentajeRechazo) / 100);
70
- const lbsBuenas = lbsEsperadas - lbsMalas;
71
- const baskets_memo = getBasketsSchema(purchaseOrder.memo);
72
- const baskets_memo_quantity = baskets_memo
73
- .map((basket) => basket.total)
74
- .reduce(reduceAdd, 0);
75
- //SI SE INGRESA POR LIBRAS, ES QUE SE ESTÁ INGRESANDO CANASTAS A DEVOLVER ETC Y HAY QUE HACER LOS ENVÍOS CORRESPONDIENTES
76
- if (!byPercent) {
77
- console.log("=============> PROCESANDO DATA POR PESO...");
78
- //CUANDO NO ES POR PORCENTAJE DIRECTO HAY QUE HACER TODO EL FLUJO DE CREAR LOS ENVÍOS ETC...
79
- //1.3: SE CREA EL ENVÍO DE VEGETALES Y CANASTAS DEVUELTOS POR CONTROL DE CALIDAD, (LOS QUE ESTÁN BUENOS)
80
- //Las canastas vienen en data en campos como estos "basket-CONVENCIONAL-58281": "2",
81
- const bodyGoodToProduction = {
82
- booker_id: Number(session.get("employee_id")),
83
- needs_transport: false,
84
- payee_id: purchaseOrder.payee_id,
85
- memo: `${purchaseOrder.lots[0].id};${purchaseOrder.id_number};${purchaseOrder.purchase_order_details[0]?.item?.name};${purchaseOrder.purchase_order_details
86
- .map((purchase) => Number(purchase.booked_quantity))
87
- .reduce(reduceAdd, 0)};${baskets_memo_quantity};${porcentajeRechazo};${purchaseOrder.delivery_date}`,
88
- planned_delivery: `${data.date}`,
89
- agency_from_id: Number(session_agency_id), //agencia donde está loggeado mi usuario
90
- agency_to_id: purchaseOrder.agency_id, //de donde viene la orden de compra
91
- reference: "Vegetales buenos devueltos desde control de calidad.",
92
- movements: [
93
- {
94
- item_id: purchaseOrder.purchase_order_details[0].item_id,
95
- lot_id: purchaseOrder.lots[0].id,
96
- reference: "Vegetales devueltos de CC",
97
- booked_quantity: lbsBuenas,
98
- },
99
- ],
100
- };
101
- /**
102
- * Para las canastas
103
- * el item_id = 490533 = recepciones_basket_item_id
104
- * lot_id: código de la canasta,
105
- * booked_quantity = cantidad de canastas que ingresa el usuario que va a devolver
106
- */
107
- baskets_regresadas.forEach((basket) => {
108
- bodyGoodToProduction.movements.push({
109
- item_id: Number(basket_id),
110
- lot_id: basket.id,
111
- reference: `Canasta ${basket.color}-${basket.id} devuelta a CC`,
112
- booked_quantity: basket.total,
113
- });
32
+ return handlePossibleAxiosErrors(async () => {
33
+ //=====================================================================================
34
+ //=====================================================================================
35
+ //PASO 1: OBTENER TODAS LAS VARIABLES QUE VAMOS A UTILIZAR EN EL FLUJO
36
+ const { production_agency, operative_rejection_agency_id, recepciones_basket_item_id: basket_id, } = await getVariablesByName(headers, session, [
37
+ "production_agency",
38
+ "operative_rejection_agency_id",
39
+ "recepciones_basket_item_id",
40
+ ]);
41
+ const session_agency_id = session.get("agency_id");
42
+ const hashObject = JSON.parse(operative_rejection_agency_id);
43
+ const op_rejection_agency_id = hashObject[session_agency_id];
44
+ //PARSEO DE LA INFORMACIÓN QUE VIENE DEL SUBMIT
45
+ const byPercent = data.byPercent === "true";
46
+ const porcentajeRechazo = !byPercent
47
+ ? toFixedIfNeeded((Number(data.lbRechazo ?? "0") /
48
+ (Number(data?.lbRechazo ?? "0") + Number(data.lbBueno))) *
49
+ 100)
50
+ : data.porcentajeRechazo;
51
+ const basket_keys = Object.keys(data).filter((x) => x.includes("basket-"));
52
+ const baskets_regresadas = basket_keys.map((basket_key) => {
53
+ //ejemplo de una key: basket-CONVENCIONAL-58281
54
+ const splited = basket_key.split("-");
55
+ return {
56
+ id: splited[2] || 0,
57
+ color: splited[1] || "",
58
+ total: Number(data[basket_key]) || 0,
59
+ };
114
60
  });
115
- console.log("-------- Insertando booking con canastas buenas devueltas");
116
- const goodVegetablesInserted = await insertBookings(headers, bodyGoodToProduction, `${purchaseOrder.id}`);
117
- if (!goodVegetablesInserted.error && goodVegetablesInserted.data) {
118
- //1.4 Recibir la reserva para que las cantidades se muevan correctamente a la bodega de destino
119
- console.log("recibiendo la reserva: ", goodVegetablesInserted.data?.id);
120
- await getDeliveryByBooking(headers, goodVegetablesInserted.data?.id);
61
+ //1.2 OBTENER LA INFORMACIÓN DEL LOTE A PROCESAR (LA TOMO DE LA QUE YA TENGO AL CARGAR LA INFO)
62
+ const purchaseOrderResponse = await getPurchaseOrder(session, poId, {
63
+ withLotStocksToMyAgency: true,
64
+ });
65
+ if (purchaseOrderResponse.error || !purchaseOrderResponse?.data) {
66
+ throw new Error(`Error al intentar encontrar la órden de compra: ${purchaseOrderResponse.userMsg}`);
121
67
  }
122
- if (lbsMalas && lbsMalas > 0) {
123
- //=====================================================================================
124
- //=====================================================================================
125
- //PASO 2: Envío con vegetales rechazados a bodega de PRODUCCIÓN desde la agencia del usuario loggeado
126
- const bodyOchToProduction = {
68
+ const purchaseOrder = purchaseOrderResponse.data;
69
+ const lbsEsperadas = purchaseOrder.lots[0].lot_stocks[0].available;
70
+ const lbsMalas = lbsEsperadas * (Number(porcentajeRechazo) / 100);
71
+ const lbsBuenas = lbsEsperadas - lbsMalas;
72
+ const baskets_memo = getBasketsSchema(purchaseOrder.memo);
73
+ const baskets_memo_quantity = baskets_memo
74
+ .map((basket) => basket.total)
75
+ .reduce(reduceAdd, 0);
76
+ //SI SE INGRESA POR LIBRAS, ES QUE SE ESTÁ INGRESANDO CANASTAS A DEVOLVER ETC Y HAY QUE HACER LOS ENVÍOS CORRESPONDIENTES
77
+ if (!byPercent) {
78
+ console.log("=============> PROCESANDO DATA POR PESO...");
79
+ //CUANDO NO ES POR PORCENTAJE DIRECTO HAY QUE HACER TODO EL FLUJO DE CREAR LOS ENVÍOS ETC...
80
+ //1.3: SE CREA EL ENVÍO DE VEGETALES Y CANASTAS DEVUELTOS POR CONTROL DE CALIDAD, (LOS QUE ESTÁN BUENOS)
81
+ //Las canastas vienen en data en campos como estos "basket-CONVENCIONAL-58281": "2",
82
+ const bodyGoodToProduction = {
127
83
  booker_id: Number(session.get("employee_id")),
128
84
  needs_transport: false,
129
- memo: "",
85
+ payee_id: purchaseOrder.payee_id,
86
+ memo: `${purchaseOrder.lots[0].id};${purchaseOrder.id_number};${purchaseOrder.purchase_order_details[0]?.item?.name};${purchaseOrder.purchase_order_details
87
+ .map((purchase) => Number(purchase.booked_quantity))
88
+ .reduce(reduceAdd, 0)};${baskets_memo_quantity};${porcentajeRechazo};${purchaseOrder.delivery_date}`,
130
89
  planned_delivery: `${data.date}`,
131
90
  agency_from_id: Number(session_agency_id), //agencia donde está loggeado mi usuario
132
- agency_to_id: Number(production_agency), //de donde viene la orden de compra
133
- reference: "Envío de vegetales rechazados a la bodega de producción.",
91
+ agency_to_id: purchaseOrder.agency_id, //de donde viene la orden de compra
92
+ reference: "Vegetales buenos devueltos desde control de calidad.",
134
93
  movements: [
135
94
  {
136
95
  item_id: purchaseOrder.purchase_order_details[0].item_id,
137
96
  lot_id: purchaseOrder.lots[0].id,
138
- reference: "Vegetales rechazados de CC",
139
- booked_quantity: lbsMalas,
97
+ reference: "Vegetales devueltos de CC",
98
+ booked_quantity: lbsBuenas,
140
99
  },
141
100
  ],
142
101
  };
143
- console.log("--------- enviando a insertar booking de rechazo a la bodega de producción");
144
- const ochToProductionVegetablesInserted = await insertBookings(headers, bodyOchToProduction, `${purchaseOrder.id}`);
145
- if (!ochToProductionVegetablesInserted.error &&
146
- ochToProductionVegetablesInserted.data) {
147
- //2.1 Recibir la reserva para que las cantidades se muevan correctamente a la bodega de destino
148
- console.log("Recibiendo booking de rechazo...");
149
- await getDeliveryByBooking(headers, ochToProductionVegetablesInserted.data.id);
102
+ /**
103
+ * Para las canastas
104
+ * el item_id = 490533 = recepciones_basket_item_id
105
+ * lot_id: código de la canasta,
106
+ * booked_quantity = cantidad de canastas que ingresa el usuario que va a devolver
107
+ */
108
+ baskets_regresadas.forEach((basket) => {
109
+ bodyGoodToProduction.movements.push({
110
+ item_id: Number(basket_id),
111
+ lot_id: basket.id,
112
+ reference: `Canasta ${basket.color}-${basket.id} devuelta a CC`,
113
+ booked_quantity: basket.total,
114
+ });
115
+ });
116
+ console.log("-------- Insertando booking con canastas buenas devueltas");
117
+ const goodVegetablesInserted = await insertBookings(headers, bodyGoodToProduction, `${purchaseOrder.id}`);
118
+ if (!goodVegetablesInserted.error && goodVegetablesInserted.data) {
119
+ //1.4 Recibir la reserva para que las cantidades se muevan correctamente a la bodega de destino
120
+ console.log("recibiendo la reserva: ", goodVegetablesInserted.data?.id);
121
+ await getDeliveryByBooking(headers, goodVegetablesInserted.data?.id);
122
+ }
123
+ if (lbsMalas && lbsMalas > 0) {
124
+ //=====================================================================================
125
+ //=====================================================================================
126
+ //PASO 2: Envío con vegetales rechazados a bodega de PRODUCCIÓN desde la agencia del usuario loggeado
127
+ const bodyOchToProduction = {
128
+ booker_id: Number(session.get("employee_id")),
129
+ needs_transport: false,
130
+ memo: "",
131
+ planned_delivery: `${data.date}`,
132
+ agency_from_id: Number(session_agency_id), //agencia donde está loggeado mi usuario
133
+ agency_to_id: Number(production_agency), //de donde viene la orden de compra
134
+ reference: "Envío de vegetales rechazados a la bodega de producción.",
135
+ movements: [
136
+ {
137
+ item_id: purchaseOrder.purchase_order_details[0].item_id,
138
+ lot_id: purchaseOrder.lots[0].id,
139
+ reference: "Vegetales rechazados de CC",
140
+ booked_quantity: lbsMalas,
141
+ },
142
+ ],
143
+ };
144
+ console.log("--------- enviando a insertar booking de rechazo a la bodega de producción");
145
+ const ochToProductionVegetablesInserted = await insertBookings(headers, bodyOchToProduction, `${purchaseOrder.id}`);
146
+ if (!ochToProductionVegetablesInserted.error &&
147
+ ochToProductionVegetablesInserted.data) {
148
+ //2.1 Recibir la reserva para que las cantidades se muevan correctamente a la bodega de destino
149
+ console.log("Recibiendo booking de rechazo...");
150
+ await getDeliveryByBooking(headers, ochToProductionVegetablesInserted.data.id);
151
+ }
152
+ //=====================================================================================
153
+ //=====================================================================================
154
+ //PASO 3: Envío con vegetales rechazados a bodega de RECHAZO desde la bodega de PRODUCCIÓN
155
+ //Sólo cambia el agency_from_id y el agency_to_id, de ahí lo demás lo mismo que PASO 2
156
+ bodyOchToProduction.agency_from_id = Number(production_agency);
157
+ bodyOchToProduction.agency_to_id = Number(op_rejection_agency_id);
158
+ bodyOchToProduction.reference =
159
+ "Envío de vegetales rechazados a la bodega de rechazo.";
160
+ console.log("--------- enviando a insertar booking de rechazo a la bodega de rechazo");
161
+ const ochToOchVegetablesInserted = await insertBookings(headers, bodyOchToProduction);
162
+ if (!ochToOchVegetablesInserted.error &&
163
+ ochToOchVegetablesInserted.data) {
164
+ //3.1 Recibir la reserva para que las cantidades se muevan correctamente a la bodega de destino
165
+ await getDeliveryByBooking(headers, ochToOchVegetablesInserted.data?.id);
166
+ }
150
167
  }
151
168
  //=====================================================================================
152
169
  //=====================================================================================
153
- //PASO 3: Envío con vegetales rechazados a bodega de RECHAZO desde la bodega de PRODUCCIÓN
154
- //Sólo cambia el agency_from_id y el agency_to_id, de ahí lo demás lo mismo que PASO 2
155
- bodyOchToProduction.agency_from_id = Number(production_agency);
156
- bodyOchToProduction.agency_to_id = Number(op_rejection_agency_id);
157
- bodyOchToProduction.reference =
158
- "Envío de vegetales rechazados a la bodega de rechazo.";
159
- console.log("--------- enviando a insertar booking de rechazo a la bodega de rechazo");
160
- const ochToOchVegetablesInserted = await insertBookings(headers, bodyOchToProduction);
161
- if (!ochToOchVegetablesInserted.error &&
162
- ochToOchVegetablesInserted.data) {
163
- //3.1 Recibir la reserva para que las cantidades se muevan correctamente a la bodega de destino
164
- await getDeliveryByBooking(headers, ochToOchVegetablesInserted.data?.id);
170
+ //PASO 5: Modificación de canastas en el lote de verdura
171
+ //la misma description del detalle del lote pero modificando la cantidad de canastas que quedaron.
172
+ //ejemplo: original: 27-53311-VERDE,1-53313-ROJA,1-53317-CELESTE,3-53312-AZUL,3-53314-AMARILLA
173
+ //ahora: 27-53311-VERDE,1-53313-ROJA,1-53317-CELESTE,2-53312-AZUL,3-53314-AMARILLA // ahora sólo 2 azules porque no devolví una
174
+ const newDescriptions = [];
175
+ baskets_memo.forEach((basket) => {
176
+ //Si existe una basket a regresar con el mismo id, pregunto cuantas va a regresar, para restarlas del total.
177
+ const basket_regresada = baskets_regresadas.find((x) => x.id === basket.id);
178
+ const resta = basket_regresada?.total ?? 0;
179
+ newDescriptions.push(`${basket.total - resta}-${basket.id}-${basket.color}`);
180
+ });
181
+ await updateLote(headers, purchaseOrder.lots[0].id, {
182
+ lot: {
183
+ description: newDescriptions.join(","),
184
+ },
185
+ });
186
+ }
187
+ else {
188
+ console.log("PROCESANDO DATA POR PORCENTAJE...");
189
+ //CUANDO NO ES POR PORCENTAJE DIRECTO HAY QUE HACER TODO EL FLUJO DE CREAR LOS ENVÍOS ETC...
190
+ //1.3: SE CREA EL ENVÍO DE VEGETALES Y CANASTAS DEVUELTOS POR CONTROL DE CALIDAD, (LOS QUE ESTÁN BUENOS)
191
+ //Las canastas vienen en data en campos como estos "basket-CONVENCIONAL-58281": "2",
192
+ const bodyGoodToProduction = {
193
+ booker_id: Number(session.get("employee_id")),
194
+ needs_transport: false,
195
+ payee_id: purchaseOrder.payee_id,
196
+ memo: `${purchaseOrder.lots[0].id};${purchaseOrder.lots[0].name};${purchaseOrder.purchase_order_details[0]?.item?.name};${purchaseOrder.purchase_order_details
197
+ .map((detail) => Number(detail.booked_quantity))
198
+ .reduce(reduceAdd, 0)};${baskets_memo_quantity};${porcentajeRechazo};${purchaseOrder.delivery_date}`,
199
+ planned_delivery: `${data.date}`,
200
+ agency_from_id: Number(session_agency_id), //agencia donde está loggeado mi usuario
201
+ agency_to_id: purchaseOrder.agency_id, //de donde viene la orden de compra
202
+ reference: "Regreando vegetales buenos desde control de calidad.",
203
+ movements: [
204
+ {
205
+ item_id: purchaseOrder.purchase_order_details[0].item_id,
206
+ lot_id: purchaseOrder.lots[0].id,
207
+ reference: "Vegetales devueltos de CC",
208
+ booked_quantity: lbsEsperadas, //devuelvo la misma cantidad que fue enviada
209
+ },
210
+ ],
211
+ };
212
+ /**
213
+ * Para las canastas
214
+ * el item_id = 490533 = recepciones_basket_item_id
215
+ * lot_id: código de la canasta,
216
+ * booked_quantity = cantidad de canastas que ingresa el usuario que va a devolver
217
+ */
218
+ //Todas las canastas que fueron enviadas originalmente
219
+ baskets_memo.forEach((basket) => {
220
+ bodyGoodToProduction.movements.push({
221
+ item_id: Number(basket_id),
222
+ lot_id: basket.id,
223
+ reference: `Canasta ${basket.color}-${basket.id} devuelta a CC`,
224
+ booked_quantity: basket.total,
225
+ });
226
+ });
227
+ console.log("-------- Insertando booking con canastas buenas devueltas");
228
+ const goodVegetablesInserted = await insertBookings(headers, bodyGoodToProduction, `${purchaseOrder.id}`);
229
+ //1.4 Recibir la reserva para que las cantidades se muevan correctamente a la bodega de destino
230
+ if (!goodVegetablesInserted.error && goodVegetablesInserted.data) {
231
+ console.log("A RECIBIR BOOKING - POR PORCENTAJE");
232
+ await getDeliveryByBooking(headers, goodVegetablesInserted.data.id);
165
233
  }
166
234
  }
167
235
  //=====================================================================================
168
236
  //=====================================================================================
169
- //PASO 5: Modificación de canastas en el lote de verdura
170
- //la misma description del detalle del lote pero modificando la cantidad de canastas que quedaron.
171
- //ejemplo: original: 27-53311-VERDE,1-53313-ROJA,1-53317-CELESTE,3-53312-AZUL,3-53314-AMARILLA
172
- //ahora: 27-53311-VERDE,1-53313-ROJA,1-53317-CELESTE,2-53312-AZUL,3-53314-AMARILLA // ahora sólo 2 azules porque no devolví una
173
- const newDescriptions = [];
174
- baskets_memo.forEach((basket) => {
175
- //Si existe una basket a regresar con el mismo id, pregunto cuantas va a regresar, para restarlas del total.
176
- const basket_regresada = baskets_regresadas.find((x) => x.id === basket.id);
177
- const resta = basket_regresada?.total ?? 0;
178
- newDescriptions.push(`${basket.total - resta}-${basket.id}-${basket.color}`);
179
- });
180
- await updateLote(headers, purchaseOrder.lots[0].id, {
181
- lot: {
182
- description: newDescriptions.join(","),
183
- },
184
- });
185
- }
186
- else {
187
- console.log("PROCESANDO DATA POR PORCENTAJE...");
188
- //CUANDO NO ES POR PORCENTAJE DIRECTO HAY QUE HACER TODO EL FLUJO DE CREAR LOS ENVÍOS ETC...
189
- //1.3: SE CREA EL ENVÍO DE VEGETALES Y CANASTAS DEVUELTOS POR CONTROL DE CALIDAD, (LOS QUE ESTÁN BUENOS)
190
- //Las canastas vienen en data en campos como estos "basket-CONVENCIONAL-58281": "2",
191
- const bodyGoodToProduction = {
192
- booker_id: Number(session.get("employee_id")),
193
- needs_transport: false,
194
- payee_id: purchaseOrder.payee_id,
195
- memo: `${purchaseOrder.lots[0].id};${purchaseOrder.lots[0].name};${purchaseOrder.purchase_order_details[0]?.item?.name};${purchaseOrder.purchase_order_details
196
- .map((detail) => Number(detail.booked_quantity))
197
- .reduce(reduceAdd, 0)};${baskets_memo_quantity};${porcentajeRechazo};${purchaseOrder.delivery_date}`,
198
- planned_delivery: `${data.date}`,
199
- agency_from_id: Number(session_agency_id), //agencia donde está loggeado mi usuario
200
- agency_to_id: purchaseOrder.agency_id, //de donde viene la orden de compra
201
- reference: "Regreando vegetales buenos desde control de calidad.",
202
- movements: [
203
- {
204
- item_id: purchaseOrder.purchase_order_details[0].item_id,
205
- lot_id: purchaseOrder.lots[0].id,
206
- reference: "Vegetales devueltos de CC",
207
- booked_quantity: lbsEsperadas, //devuelvo la misma cantidad que fue enviada
208
- },
209
- ],
237
+ //PASO 4: Modificación de porcentaje de rechazo en la orden de compra
238
+ //4.1 El primer paso es devolver la recepción recibida en la orden de compra.
239
+ //Primero se debe obtener el id de dicha recepción
240
+ const reception = purchaseOrder.receptions[0];
241
+ const reception_details = reception?.reception_details[0];
242
+ //4.2 Habilito la orden de compra
243
+ await enablePurchase(headers, purchaseOrder.id, reception?.id);
244
+ //4.3 Editar porcentajes de rechazo
245
+ const updateBodyPurchase = {
246
+ purchase_order: { discount: porcentajeRechazo },
210
247
  };
211
- /**
212
- * Para las canastas
213
- * el item_id = 490533 = recepciones_basket_item_id
214
- * lot_id: código de la canasta,
215
- * booked_quantity = cantidad de canastas que ingresa el usuario que va a devolver
216
- */
217
- //Todas las canastas que fueron enviadas originalmente
218
- baskets_memo.forEach((basket) => {
219
- bodyGoodToProduction.movements.push({
220
- item_id: Number(basket_id),
221
- lot_id: basket.id,
222
- reference: `Canasta ${basket.color}-${basket.id} devuelta a CC`,
223
- booked_quantity: basket.total,
224
- });
225
- });
226
- console.log("-------- Insertando booking con canastas buenas devueltas");
227
- const goodVegetablesInserted = await insertBookings(headers, bodyGoodToProduction, `${purchaseOrder.id}`);
228
- //1.4 Recibir la reserva para que las cantidades se muevan correctamente a la bodega de destino
229
- if (!goodVegetablesInserted.error && goodVegetablesInserted.data) {
230
- console.log("A RECIBIR BOOKING - POR PORCENTAJE");
231
- await getDeliveryByBooking(headers, goodVegetablesInserted.data.id);
232
- }
233
- }
234
- //=====================================================================================
235
- //=====================================================================================
236
- //PASO 4: Modificación de porcentaje de rechazo en la orden de compra
237
- //4.1 El primer paso es devolver la recepción recibida en la orden de compra.
238
- //Primero se debe obtener el id de dicha recepción
239
- const reception = purchaseOrder.receptions[0];
240
- const reception_details = reception?.reception_details[0];
241
- //4.2 Habilito la orden de compra
242
- await enablePurchase(headers, purchaseOrder.id, reception?.id);
243
- //4.3 Editar porcentajes de rechazo
244
- const updateBodyPurchase = {
245
- purchase_order: { discount: porcentajeRechazo },
246
- };
247
- await updatePurchaseOrder(headers, updateBodyPurchase, purchaseOrder.id);
248
- //4.4 Crear una nueva recepcion
249
- const bodyReception = {
250
- reception: {
251
- agency_id: reception.agency_id,
252
- entity_id: reception.entity_id,
253
- needs_transit: false,
254
- purchase_order_id: purchaseOrder.id,
255
- received_at: new Date(Date.now() + 12096e5).toISOString().split("T")[0],
256
- invoice_number: `${reception.invoice_number ?? ""}`,
257
- reception_details_attributes: {
258
- "0": {
259
- item_id: `${reception_details?.item_id}`,
260
- lot_delivered_quantity: [reception_details?.lot_delivered_quantity],
261
- lot_description: [reception_details?.lot_description],
262
- lot_expire: [reception_details?.lot_expire],
263
- lot_name: [reception_details?.lot_name],
264
- purchase_order_detail_id: `${reception_details?.purchase_order_detail_id}`,
248
+ await updatePurchaseOrder(headers, updateBodyPurchase, purchaseOrder.id);
249
+ //4.4 Crear una nueva recepcion
250
+ const bodyReception = {
251
+ reception: {
252
+ agency_id: reception.agency_id,
253
+ entity_id: reception.entity_id,
254
+ needs_transit: false,
255
+ purchase_order_id: purchaseOrder.id,
256
+ received_at: new Date(Date.now() + 12096e5).toISOString().split("T")[0],
257
+ invoice_number: `${reception.invoice_number ?? ""}`,
258
+ reception_details_attributes: {
259
+ "0": {
260
+ item_id: `${reception_details?.item_id}`,
261
+ lot_delivered_quantity: [reception_details?.lot_delivered_quantity],
262
+ lot_description: [reception_details?.lot_description],
263
+ lot_expire: [reception_details?.lot_expire],
264
+ lot_name: [reception_details?.lot_name],
265
+ purchase_order_detail_id: `${reception_details?.purchase_order_detail_id}`,
266
+ },
265
267
  },
266
268
  },
267
- },
268
- };
269
- await createNewReception(headers, bodyReception, purchaseOrder.id);
270
- //=====================================================================================
271
- //=====================================================================================
272
- //PASO 6: Guardar razones de rechazo en webapp table
273
- await saveMotivosDeRechazoByPurchase(headers, session, {
274
- Razon_primaria: `${data.razonPrincipal ?? ""}`,
275
- Razon_secundaria: `${data.razonSecundaria ?? ""}`,
276
- Razon_terciaria: `${data.razonTerciaria ?? ""}`,
277
- Canastas: `${data.ochBaskets ?? ""}`,
278
- }, {
279
- temp_purchase_order_id: `${purchaseOrder.id}`,
269
+ };
270
+ await createNewReception(headers, bodyReception, purchaseOrder.id);
271
+ //=====================================================================================
272
+ //=====================================================================================
273
+ //PASO 6: Guardar razones de rechazo en webapp table
274
+ await saveMotivosDeRechazoByPurchase(headers, session, {
275
+ Razon_primaria: `${data.razonPrincipal ?? ""}`,
276
+ Razon_secundaria: `${data.razonSecundaria ?? ""}`,
277
+ Razon_terciaria: `${data.razonTerciaria ?? ""}`,
278
+ Canastas: `${data.ochBaskets ?? ""}`,
279
+ }, {
280
+ temp_purchase_order_id: `${purchaseOrder.id}`,
281
+ });
280
282
  });
281
283
  };
282
284
  /**
@@ -1,5 +1,5 @@
1
1
  import type { Session } from "@remix-run/node";
2
- import { BasketSchema } from "@zauru-sdk/types";
2
+ import { AxiosUtilsResponse, BasketSchema } from "@zauru-sdk/types";
3
3
  /**
4
4
  * Obtiene el listado de ordenes de compra, formateado especialmente para armar la tabla de edición de porcentajes de rechazo
5
5
  * @param headers
@@ -14,7 +14,7 @@ export declare const getLotesFormated: (headers: any, session: Session) => Promi
14
14
  * @param data
15
15
  * @param byPercent
16
16
  */
17
- export declare const procesarLote: (headers: any, session: Session, data: any, poId: number | string) => Promise<void>;
17
+ export declare const procesarLote: (headers: any, session: Session, data: any, poId: number | string) => Promise<AxiosUtilsResponse<any>>;
18
18
  /**
19
19
  * Obtiene toda la información de lote, con las canastas y razones de rechazo
20
20
  * @param headers
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zauru-sdk/utils",
3
- "version": "1.0.62",
3
+ "version": "1.0.64",
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",
@@ -27,9 +27,9 @@
27
27
  "@remix-run/node": "^2.8.1",
28
28
  "@zauru-sdk/common": "^1.0.60",
29
29
  "@zauru-sdk/config": "^1.0.60",
30
- "@zauru-sdk/graphql": "^1.0.62",
31
- "@zauru-sdk/services": "^1.0.62",
30
+ "@zauru-sdk/graphql": "^1.0.64",
31
+ "@zauru-sdk/services": "^1.0.64",
32
32
  "@zauru-sdk/types": "^1.0.60"
33
33
  },
34
- "gitHead": "afaa820e0f482c6e2f57ae673aa420d362fd2561"
34
+ "gitHead": "7edda6e02380d48667a0daa4625ad3e87341f6b4"
35
35
  }