@zauru-sdk/utils 1.0.7 → 1.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/index.d.ts +23 -2
  3. package/dist/index.js +23 -2
  4. package/dist/zauru/automatic-number.utils.d.ts +9 -0
  5. package/dist/zauru/automatic-number.utils.js +24 -0
  6. package/dist/zauru/bitacora-edicion-masiva.utils.d.ts +23 -0
  7. package/dist/zauru/bitacora-edicion-masiva.utils.js +50 -0
  8. package/dist/zauru/bundles.utils.d.ts +39 -0
  9. package/dist/zauru/bundles.utils.js +160 -0
  10. package/dist/zauru/cases.utils.d.ts +9 -0
  11. package/dist/zauru/cases.utils.js +17 -0
  12. package/dist/zauru/consolidated-history.utils.d.ts +24 -0
  13. package/dist/zauru/consolidated-history.utils.js +52 -0
  14. package/dist/zauru/costos-items.utils.d.ts +87 -0
  15. package/dist/zauru/costos-items.utils.js +601 -0
  16. package/dist/zauru/deliveries.utils.d.ts +17 -0
  17. package/dist/zauru/deliveries.utils.js +46 -0
  18. package/dist/zauru/discharges-histsory.utils.d.ts +24 -0
  19. package/dist/zauru/discharges-histsory.utils.js +46 -0
  20. package/dist/zauru/employees.utils.d.ts +16 -0
  21. package/dist/zauru/employees.utils.js +39 -0
  22. package/dist/zauru/form.utils.d.ts +34 -0
  23. package/dist/zauru/form.utils.js +152 -0
  24. package/dist/zauru/invoices.utils.d.ts +22 -0
  25. package/dist/zauru/invoices.utils.js +79 -0
  26. package/dist/zauru/items.utils.d.ts +52 -0
  27. package/dist/zauru/items.utils.js +152 -0
  28. package/dist/zauru/lotes.utils.d.ts +31 -0
  29. package/dist/zauru/lotes.utils.js +307 -0
  30. package/dist/zauru/motivos-rechazo.utils.d.ts +10 -0
  31. package/dist/zauru/motivos-rechazo.utils.js +18 -0
  32. package/dist/zauru/payees.utils.d.ts +42 -0
  33. package/dist/zauru/payees.utils.js +128 -0
  34. package/dist/zauru/profiles.utils.d.ts +15 -0
  35. package/dist/zauru/profiles.utils.js +37 -0
  36. package/dist/zauru/providers.utils.d.ts +13 -0
  37. package/dist/zauru/providers.utils.js +36 -0
  38. package/dist/zauru/purchase-orders.utils.d.ts +114 -0
  39. package/dist/zauru/purchase-orders.utils.js +376 -0
  40. package/dist/zauru/shipments.utils.d.ts +21 -0
  41. package/dist/zauru/shipments.utils.js +90 -0
  42. package/dist/zauru/specialItem.utils.d.ts +34 -0
  43. package/dist/zauru/specialItem.utils.js +62 -0
  44. package/dist/zauru/templates.utils.d.ts +49 -0
  45. package/dist/zauru/templates.utils.js +93 -0
  46. package/dist/zauru/tiposMuestra.utils.d.ts +34 -0
  47. package/dist/zauru/tiposMuestra.utils.js +62 -0
  48. package/dist/zauru/webapp-tables.utils.d.ts +16 -0
  49. package/dist/zauru/webapp-tables.utils.js +51 -0
  50. package/package.json +6 -6
  51. package/src/index.ts +23 -0
  52. package/src/zauru/bitacora-edicion-masiva.utils.ts +99 -0
  53. package/src/zauru/bundles.utils.ts +251 -0
  54. package/src/zauru/cases.utils.ts +31 -0
  55. package/src/zauru/consolidated-history.utils.ts +102 -0
  56. package/src/zauru/costos-items.utils.ts +865 -0
  57. package/src/zauru/deliveries.utils.ts +77 -0
  58. package/src/zauru/discharges-histsory.utils.ts +105 -0
  59. package/src/zauru/employees.utils.ts +59 -0
  60. package/src/zauru/form.utils.ts +243 -0
  61. package/src/zauru/invoices.utils.ts +114 -0
  62. package/src/zauru/items.utils.ts +269 -0
  63. package/src/zauru/lotes.utils.ts +411 -0
  64. package/src/zauru/motivos-rechazo.utils.ts +47 -0
  65. package/src/zauru/payees.utils.ts +213 -0
  66. package/src/zauru/profiles.utils.ts +44 -0
  67. package/src/zauru/providers.utils.ts +67 -0
  68. package/src/zauru/purchase-orders.utils.ts +594 -0
  69. package/src/zauru/shipments.utils.ts +139 -0
  70. package/src/zauru/specialItem.utils.ts +126 -0
  71. package/src/zauru/templates.utils.ts +199 -0
  72. package/src/zauru/tiposMuestra.utils.ts +136 -0
  73. package/src/zauru/webapp-tables.utils.ts +94 -0
  74. /package/src/{automatic-number.utils.ts → zauru/automatic-number.utils.ts} +0 -0
@@ -0,0 +1,307 @@
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";
3
+ import { getPurchaseOrderDataTables } from "./purchase-orders.utils.js";
4
+ /**
5
+ * Obtiene el listado de ordenes de compra, formateado especialmente para armar la tabla de edición de porcentajes de rechazo
6
+ * @param headers
7
+ * @param session
8
+ * @returns
9
+ */
10
+ export const getLotesFormated = async (headers, session) => {
11
+ //PASO 1: Obtengo las variables, para buscar mi tag_id y mi basket_id
12
+ const { recepciones_basket_item_id: basket_id, production_agency_id /**{5693: 5696} */, } = await getVariablesByName(headers, session, [
13
+ "recepciones_basket_item_id",
14
+ "production_agency_id",
15
+ ]);
16
+ const hashAgencyId = JSON.parse(production_agency_id ?? "{}");
17
+ const agency_id = hashAgencyId[session.get("agency_id")];
18
+ //PASO 2: Busco mis lotes
19
+ if (agency_id) {
20
+ return await getLotesFiltered(headers, agency_id, false, Number(basket_id));
21
+ }
22
+ return [];
23
+ };
24
+ /**
25
+ * procesarLote
26
+ * @param headers
27
+ * @param session
28
+ * @param data
29
+ * @param byPercent
30
+ */
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
+ });
114
+ });
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);
121
+ }
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 = {
127
+ booker_id: Number(session.get("employee_id")),
128
+ needs_transport: false,
129
+ memo: "",
130
+ planned_delivery: `${data.date}`,
131
+ 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.",
134
+ movements: [
135
+ {
136
+ item_id: purchaseOrder.purchase_order_details[0].item_id,
137
+ lot_id: purchaseOrder.lots[0].id,
138
+ reference: "Vegetales rechazados de CC",
139
+ booked_quantity: lbsMalas,
140
+ },
141
+ ],
142
+ };
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);
150
+ }
151
+ //=====================================================================================
152
+ //=====================================================================================
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);
165
+ }
166
+ }
167
+ //=====================================================================================
168
+ //=====================================================================================
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
+ ],
210
+ };
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}`,
265
+ },
266
+ },
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}`,
280
+ });
281
+ };
282
+ /**
283
+ * Obtiene toda la información de lote, con las canastas y razones de rechazo
284
+ * @param headers
285
+ * @param session
286
+ * @returns
287
+ */
288
+ export const getLoteDescription = async (headers, session, lote_id) => {
289
+ //PASO 1: Obtengo las variables, para buscar mi basket_id
290
+ const { production_agency_id /**{5693: 5696} */ } = await getVariablesByName(headers, session, ["production_agency_id"]);
291
+ const hashAgencyId = JSON.parse(production_agency_id ?? "{}");
292
+ const agency_id = hashAgencyId[session.get("agency_id")];
293
+ //PASO 2: Busco mi lote
294
+ const lote = await getLote(headers, lote_id, agency_id);
295
+ //PASO 3: Obtener listado de canastas enviadas a bodega control de calidad
296
+ //El primer paso es ubicar la orden de compra original, la cual permitirá ubicar el envío que se
297
+ //realizó a la bodega de control de calidad
298
+ const purchase_order = await getPurchaseOrderDataTables(headers, lote.name.replace("-RETENIDO", "") // por si trae la palabra RETENIDO,
299
+ );
300
+ //PASO 4: Obtener los envíos asociados a la orden de compra
301
+ const purchaseResponse = await getPurchase(headers, purchase_order.no_orden);
302
+ return {
303
+ lote,
304
+ purchase_order,
305
+ purchase: purchaseResponse.data,
306
+ };
307
+ };
@@ -0,0 +1,10 @@
1
+ import { Session } from "@remix-run/node";
2
+ import { AxiosUtilsResponse, BasicIdNameSchema, MotivoRechazo, WebAppRowGraphQL, WebAppTableUpdateResponse } from "@zauru-sdk/types";
3
+ export declare function formatearMotivoDeRechazo(entity: WebAppRowGraphQL<MotivoRechazo>): BasicIdNameSchema;
4
+ /**
5
+ * Post saveBitacoraPOMassive from the web app table.
6
+ * @param headers Request headers.
7
+ * @param session Session object.
8
+ * @returns A Promise of AxiosUtilsResponse<WebAppRowGraphQL<BitacoraPOMassive>[]>.
9
+ */
10
+ export declare function saveRechazoCanastas(headers: any, session: Session, body: any): Promise<AxiosUtilsResponse<WebAppTableUpdateResponse>>;
@@ -0,0 +1,18 @@
1
+ import { handlePossibleAxiosErrors } from "@zauru-sdk/common";
2
+ import { createWebAppTableRegister, getVariablesByName, } from "@zauru-sdk/services";
3
+ export function formatearMotivoDeRechazo(entity) {
4
+ return { id: entity.id, name: entity.data.Nombre };
5
+ }
6
+ /**
7
+ * Post saveBitacoraPOMassive from the web app table.
8
+ * @param headers Request headers.
9
+ * @param session Session object.
10
+ * @returns A Promise of AxiosUtilsResponse<WebAppRowGraphQL<BitacoraPOMassive>[]>.
11
+ */
12
+ export async function saveRechazoCanastas(headers, session, body) {
13
+ return handlePossibleAxiosErrors(async () => {
14
+ const { recepciones_rejections_webapp_table_id } = await getVariablesByName(headers, session, ["recepciones_rejections_webapp_table_id"]);
15
+ const response = await createWebAppTableRegister(headers, recepciones_rejections_webapp_table_id, { ...body });
16
+ return response;
17
+ });
18
+ }
@@ -0,0 +1,42 @@
1
+ import type { Session } from "@remix-run/node";
2
+ import { AxiosUtilsResponse, PayeeCategoryGraphQL, PayeeGraphQL } from "@zauru-sdk/types";
3
+ export declare const TEXT_PAYEE_CATEGORY_NOTES_FOR_PRICE = "CATEGORIA_QUE_REPRESENTA_UN_PRECIO_DE_LABORATORIO (No borrar esto): ";
4
+ export declare const TEXT_PAYEE_CATEGORY_NAME_FOR_PRICE = "CAT-LABORATORIO: ";
5
+ /**
6
+ * getClientesLaboratorio
7
+ * @param session
8
+ * @param headers
9
+ * @returns
10
+ */
11
+ export declare function getClientesLaboratorio(session: Session): Promise<AxiosUtilsResponse<PayeeGraphQL[]>>;
12
+ /**
13
+ * createNewLaboratoryClient
14
+ * @param session
15
+ * @param headers
16
+ * @param body
17
+ * @returns
18
+ */
19
+ export declare function createNewLaboratoryClient(headers: any, body: Partial<PayeeGraphQL>): Promise<AxiosUtilsResponse<boolean>>;
20
+ /**
21
+ * createNewLaboratoryClientCategoryPrice
22
+ * @param session
23
+ * @param headers
24
+ * @param body
25
+ * @returns
26
+ */
27
+ export declare function updateLaboratoryClientCategoryPrice(headers: any, body: Partial<PayeeCategoryGraphQL>): Promise<AxiosUtilsResponse<boolean>>;
28
+ /**
29
+ * createNewLaboratoryClientCategoryPrice
30
+ * @param session
31
+ * @param headers
32
+ * @param body
33
+ * @returns
34
+ */
35
+ export declare function createNewLaboratoryClientCategoryPrice(headers: any, session: Session, body: Partial<PayeeCategoryGraphQL>): Promise<AxiosUtilsResponse<boolean>>;
36
+ /**
37
+ * deleteLaboratoryClientCategoryPrice
38
+ * @param headers
39
+ * @param body
40
+ * @returns
41
+ */
42
+ export declare function deleteLaboratoryClientCategoryPrice(headers: any, body: Partial<PayeeCategoryGraphQL>): Promise<AxiosUtilsResponse<boolean>>;
@@ -0,0 +1,128 @@
1
+ import { handlePossibleAxiosErrors } from "@zauru-sdk/common";
2
+ import { createPayee, createPayeeCategory, createPriceList, deletePayeeCategory, deletePriceList, getPayeeCategoriesByNotesMatch, getPaymentTermById, getVariablesByName, updatePayeeCategory, updatePaymentTerm, } from "@zauru-sdk/services";
3
+ export const TEXT_PAYEE_CATEGORY_NOTES_FOR_PRICE = "CATEGORIA_QUE_REPRESENTA_UN_PRECIO_DE_LABORATORIO (No borrar esto): ";
4
+ export const TEXT_PAYEE_CATEGORY_NAME_FOR_PRICE = "CAT-LABORATORIO: ";
5
+ /**
6
+ * getClientesLaboratorio
7
+ * @param session
8
+ * @param headers
9
+ * @returns
10
+ */
11
+ export async function getClientesLaboratorio(session) {
12
+ return handlePossibleAxiosErrors(async () => {
13
+ const clientesResponse = await getPayeeCategoriesByNotesMatch(session, TEXT_PAYEE_CATEGORY_NOTES_FOR_PRICE);
14
+ if (clientesResponse.error || !clientesResponse.data) {
15
+ throw new Error(clientesResponse.userMsg);
16
+ }
17
+ const clientes = [];
18
+ clientesResponse.data.forEach((x) => clientes.push(...x.payees));
19
+ return clientes;
20
+ });
21
+ }
22
+ /**
23
+ * createNewLaboratoryClient
24
+ * @param session
25
+ * @param headers
26
+ * @param body
27
+ * @returns
28
+ */
29
+ export async function createNewLaboratoryClient(headers, body) {
30
+ return handlePossibleAxiosErrors(async () => {
31
+ const sendBody = {
32
+ ...body,
33
+ vendor: false,
34
+ currency_id: 1,
35
+ buyer: true,
36
+ service_provider: true,
37
+ };
38
+ const createResponse = await createPayee(headers, sendBody);
39
+ if (!createResponse.data) {
40
+ throw new Error(`Ocurrió un error al intentar crear el cliente: ${createResponse.userMsg}`);
41
+ }
42
+ return true;
43
+ });
44
+ }
45
+ /**
46
+ * createNewLaboratoryClientCategoryPrice
47
+ * @param session
48
+ * @param headers
49
+ * @param body
50
+ * @returns
51
+ */
52
+ export async function updateLaboratoryClientCategoryPrice(headers, body) {
53
+ return handlePossibleAxiosErrors(async () => {
54
+ const sendBody = {
55
+ ...body,
56
+ name: `${TEXT_PAYEE_CATEGORY_NAME_FOR_PRICE}${body.name ?? ""}`,
57
+ notes: `${TEXT_PAYEE_CATEGORY_NOTES_FOR_PRICE}${body.notes ?? ""}`,
58
+ };
59
+ const createResponse = await updatePayeeCategory(headers, sendBody);
60
+ if (!createResponse.data || createResponse.error) {
61
+ throw new Error(`Ocurrió un error al intentar editar la categoría de cliente: ${createResponse.userMsg}`);
62
+ }
63
+ return true;
64
+ });
65
+ }
66
+ /**
67
+ * createNewLaboratoryClientCategoryPrice
68
+ * @param session
69
+ * @param headers
70
+ * @param body
71
+ * @returns
72
+ */
73
+ export async function createNewLaboratoryClientCategoryPrice(headers, session, body) {
74
+ return handlePossibleAxiosErrors(async () => {
75
+ const sendBody = {
76
+ ...body,
77
+ name: `${TEXT_PAYEE_CATEGORY_NAME_FOR_PRICE}${body.name ?? ""}`,
78
+ notes: `${TEXT_PAYEE_CATEGORY_NOTES_FOR_PRICE}${body.notes ?? ""}`,
79
+ };
80
+ const createResponse = await createPayeeCategory(headers, sendBody);
81
+ if (!createResponse.data || createResponse.error) {
82
+ throw new Error(`Ocurrió un error al intentar crear la categoría de cliente: ${createResponse.userMsg}`);
83
+ }
84
+ //Luego creo el listado de precios también
85
+ const sendBodyPriceList = {
86
+ client_exclusive: true,
87
+ name: `PRECIO_LABORATORIO: ${body.name}`,
88
+ description: `Listado de precio asociado a la categoría de cliente: ${body.name} id: ${createResponse.data?.id}`,
89
+ payee_category_ids: [createResponse.data.id?.toString()],
90
+ };
91
+ const createPriceResponse = await createPriceList(headers, sendBodyPriceList);
92
+ if (!createPriceResponse.data || createPriceResponse.error) {
93
+ throw new Error(`Ocurrió un error al intentar crear el listado de precio: ${createPriceResponse.userMsg}`);
94
+ }
95
+ //Por último, asigno la categoría de empleados al término de pago de laboratorio
96
+ const { lab_payment_term_default_id } = await getVariablesByName(headers, session, ["lab_payment_term_default_id"]);
97
+ const paymentTermResponse = await getPaymentTermById(session, lab_payment_term_default_id);
98
+ if (!paymentTermResponse.data || paymentTermResponse.error) {
99
+ throw new Error(`Ocurrió un error al intentar encontrar el término de pago: ${paymentTermResponse.userMsg}`);
100
+ }
101
+ const updatePaymentTermResponse = await updatePaymentTerm(headers, {
102
+ id: Number(lab_payment_term_default_id),
103
+ payee_category_ids: [
104
+ ...paymentTermResponse?.data?.allowed_payment_terms?.map((x) => x.payee_category_id.toString()),
105
+ createResponse.data.id?.toString(),
106
+ ],
107
+ });
108
+ if (!updatePaymentTermResponse.data || updatePaymentTermResponse.error) {
109
+ throw new Error(`Ocurrió un error al intentar actualizar el término de pago: ${updatePaymentTermResponse.userMsg}`);
110
+ }
111
+ return true;
112
+ });
113
+ }
114
+ /**
115
+ * deleteLaboratoryClientCategoryPrice
116
+ * @param headers
117
+ * @param body
118
+ * @returns
119
+ */
120
+ export async function deleteLaboratoryClientCategoryPrice(headers, body) {
121
+ return handlePossibleAxiosErrors(async () => {
122
+ //Elimino la categoría
123
+ await deletePayeeCategory(headers, body.id ?? "");
124
+ //Elimino la lista de precios
125
+ await deletePriceList(headers, body.price_list_id ?? "");
126
+ return true;
127
+ });
128
+ }
@@ -0,0 +1,15 @@
1
+ import { ProfileResponse, SelectFieldOption } from "@zauru-sdk/types";
2
+ /**
3
+ *
4
+ * @param profileInfoObject
5
+ * @returns
6
+ */
7
+ export declare function getInitialProfileInfo(profileInfoObject?: ProfileResponse): {
8
+ profileLabelInfo: SelectFieldOption[];
9
+ membershipsInfo: {
10
+ entity: any;
11
+ contractExpiration: string;
12
+ nextPay: string;
13
+ entityId: any;
14
+ }[];
15
+ };
@@ -0,0 +1,37 @@
1
+ /**
2
+ *
3
+ * @param profileInfoObject
4
+ * @returns
5
+ */
6
+ export function getInitialProfileInfo(profileInfoObject) {
7
+ if (!Object.keys(profileInfoObject ?? {}).length || !profileInfoObject) {
8
+ return {
9
+ profileLabelInfo: [
10
+ { label: "Nombre", value: "Cargando..." },
11
+ { label: "E Mail", value: "Cargando..." },
12
+ ],
13
+ membershipsInfo: [
14
+ {
15
+ entity: "Cargando...",
16
+ contractExpiration: "Cargando...",
17
+ nextPay: "Cargando...",
18
+ entityId: 0,
19
+ },
20
+ ],
21
+ };
22
+ }
23
+ const profile = profileInfoObject.profile;
24
+ const profileLabelInfo = [
25
+ { label: "Nombre", value: profile.name },
26
+ { label: "E Mail", value: profile.email },
27
+ ];
28
+ const membershipsInfo = profileInfoObject.memberships.map((membership) => {
29
+ return {
30
+ entity: membership.entity.name,
31
+ contractExpiration: membership.eternal ? "NUNCA" : "EXPIRA",
32
+ nextPay: new Date(Date.parse(membership.expires)).toLocaleDateString(),
33
+ entityId: membership.entity_id,
34
+ };
35
+ });
36
+ return { profileLabelInfo, membershipsInfo };
37
+ }
@@ -0,0 +1,13 @@
1
+ import type { Session } from "@remix-run/node";
2
+ import { AxiosUtilsResponse, BasicIdNameSchema } from "@zauru-sdk/types";
3
+ /**
4
+ * getProvidersList
5
+ * @param headers
6
+ * @param session
7
+ * @param byReceptions
8
+ * @returns
9
+ */
10
+ export declare const getProvidersList: (headers: any, session: Session, byReceptions?: boolean) => Promise<AxiosUtilsResponse<{
11
+ vendors: BasicIdNameSchema[];
12
+ vendors_categories: BasicIdNameSchema[];
13
+ }>>;
@@ -0,0 +1,36 @@
1
+ import { handlePossibleAxiosErrors } from "@zauru-sdk/common";
2
+ import { getPurchasesListDataTables, getVariablesByName, } from "@zauru-sdk/services";
3
+ /**
4
+ * getProvidersList
5
+ * @param headers
6
+ * @param session
7
+ * @param byReceptions
8
+ * @returns
9
+ */
10
+ export const getProvidersList = async (headers, session, byReceptions = true) => {
11
+ return handlePossibleAxiosErrors(async () => {
12
+ let tag_id = undefined;
13
+ if (byReceptions) {
14
+ const { recepciones_tag_id } = await getVariablesByName(headers, session, ["recepciones_tag_id"]);
15
+ tag_id = recepciones_tag_id;
16
+ }
17
+ //Obtengo los proveedores, que vienen en el endpoint de órdenes de compra
18
+ const body = {
19
+ order: { "0": { column: "1", dir: "desc" } },
20
+ start: 0,
21
+ length: 1,
22
+ search: { value: "", regex: false },
23
+ tag: tag_id,
24
+ agency: session.get("agency_id") ?? "",
25
+ };
26
+ //Voy por las ordenes y las ordeno por fecha de recepción
27
+ const ordersDataTablesResponse = await getPurchasesListDataTables(headers, body);
28
+ if (ordersDataTablesResponse.error)
29
+ throw new Error(ordersDataTablesResponse.userMsg);
30
+ const ordersDataTables = ordersDataTablesResponse.data;
31
+ return {
32
+ vendors: ordersDataTables?.vendors ?? [],
33
+ vendors_categories: ordersDataTables?.vendor_categories ?? [],
34
+ };
35
+ });
36
+ };