@zauru-sdk/utils 1.0.49 → 1.0.52

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