@zauru-sdk/utils 1.0.7 → 1.0.8

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 +8 -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 +5 -5
  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,114 @@
1
+ import type { Session } from "@remix-run/node";
2
+ import { AxiosUtilsResponse, LoteWithPurchaseFormatedSchema, PurchaseOrderGraphQL, PurchasesDataTableListFormatedSchema, PurchasesListResponseSchema } from "@zauru-sdk/types";
3
+ /**
4
+ * Obtiene el listado de ordenes de compra, formateado especialmente para armar la tabla de edición de porcentajes y tolerancia
5
+ * @param headers
6
+ * @param session
7
+ * @returns
8
+ */
9
+ export declare const getPurchasesDataTableListFormated: (headers: any, session: Session, params: {
10
+ page: string | null;
11
+ perPage: string | null;
12
+ search: string | null;
13
+ from_production_agency_id?: boolean;
14
+ }) => Promise<AxiosUtilsResponse<PurchasesListResponseSchema<LoteWithPurchaseFormatedSchema>>>;
15
+ /**
16
+ * getPurchaseOrderDataTables Obtiene una orden de compra ya formateada con todos sus campos.
17
+ * @param headers
18
+ * @param tag_id
19
+ * @param agency_id
20
+ * @param search
21
+ * @returns
22
+ */
23
+ export declare const getPurchaseOrderDataTables: (headers: any, search: string, tag_id?: string, agency_id?: string) => Promise<PurchasesDataTableListFormatedSchema>;
24
+ /**
25
+ * updatePurchaseItemPrice
26
+ * @param headers
27
+ * @param data
28
+ * @param purchase_id
29
+ */
30
+ export declare const updatePurchaseItemPrice: (headers: any, data: {
31
+ purchase_order_details_attributes: Record<string, {
32
+ unit_cost: number;
33
+ item_id: number;
34
+ id: number;
35
+ }>;
36
+ }, purchase_id: number) => Promise<AxiosUtilsResponse<boolean>>;
37
+ /**
38
+ * updateOchAndDis
39
+ * @param headers
40
+ * @param session
41
+ * @returns
42
+ */
43
+ export declare const updateOchAndDis: (headers: any, data: {
44
+ discount?: number | string;
45
+ other_charges?: number | string;
46
+ }, purchase_id: number) => Promise<AxiosUtilsResponse<boolean>>;
47
+ /**
48
+ * updatePurchaseOrderReception
49
+ * @param headers
50
+ * @param data
51
+ * @param purchase_id
52
+ * @returns
53
+ */
54
+ export declare const updatePurchaseOrderReception: (headers: any, data: {
55
+ payee_id?: string;
56
+ purchase_order_details_attributes: Record<string, {
57
+ item_id: number;
58
+ id: number;
59
+ }>;
60
+ }, purchase_id: number) => Promise<AxiosUtilsResponse<boolean>>;
61
+ /**
62
+ * Obtengo los id's de las órdenes de compra en un arreglo numérico
63
+ * @param headers
64
+ * @param session
65
+ * @param extraParams
66
+ * @returns
67
+ */
68
+ export declare const getOrderIDS: (headers: any, session: Session, extraParams: {
69
+ vendor?: string;
70
+ vendor_category?: string;
71
+ item?: string;
72
+ desde?: string;
73
+ hasta?: string;
74
+ }) => Promise<AxiosUtilsResponse<number[]>>;
75
+ /**
76
+ * deleteOrder
77
+ * @returns
78
+ */
79
+ export declare const deletePurchaseOrderProcess: (headers: any, session: Session, id: string | number) => Promise<AxiosUtilsResponse<boolean>>;
80
+ export type TaskSchema = {
81
+ timeStamp: number;
82
+ iniciada: string;
83
+ total_ordenes: number;
84
+ completadas: number;
85
+ };
86
+ /**
87
+ * Commitea una task iniciada para la pantalla de edición masiva de órdenes de compra
88
+ * @param session
89
+ * @param ordenes
90
+ * @param timeStamp
91
+ */
92
+ export declare const commitTask: (session: Session, ordenes: Array<number>, timeStamp: number) => Promise<void>;
93
+ /**
94
+ * Comitea una task finalizada para la pantalla de edición de órdenes de compra masiva
95
+ * @param session
96
+ * @param timeStamp
97
+ */
98
+ export declare const commitEndTask: (session: Session, timeStamp: number) => Promise<void>;
99
+ /**
100
+ * Elimina de la sesión una task.
101
+ * @param session
102
+ * @param timeStamp
103
+ */
104
+ export declare const deleteTask: (session: Session, timeStamp: number) => Promise<boolean>;
105
+ /**
106
+ * createNewLabItemRequest
107
+ * @param headers
108
+ * @param session
109
+ * @param body
110
+ * @returns
111
+ */
112
+ export declare const createNewLabItemRequest: (headers: any, session: Session, body: Partial<PurchaseOrderGraphQL> & {
113
+ [key: string]: any;
114
+ }) => Promise<AxiosUtilsResponse<PurchaseOrderGraphQL>>;
@@ -0,0 +1,376 @@
1
+ import { CURRENCY_PREFIX, getNewDateByFormat, getStringFullDate, getZauruDateByText, handlePossibleAxiosErrors } from "@zauru-sdk/common";
2
+ import { commitSession, createNewPurchaseOrder, deleteDelivery, deletePurchaseOrder, deleteReception, generateDistinctCode, getLotesWithPurchaseFormated, getPurchaseOrder, getPurchasesListDataTables, getVariablesByName, inactivarLote, updateReceivedPurchaseOrder } from "@zauru-sdk/services";
3
+ /**
4
+ * Obtiene el listado de ordenes de compra, formateado especialmente para armar la tabla de edición de porcentajes y tolerancia
5
+ * @param headers
6
+ * @param session
7
+ * @returns
8
+ */
9
+ export const getPurchasesDataTableListFormated = async (headers, session, params) => {
10
+ return handlePossibleAxiosErrors(async () => {
11
+ //PASO 1: Obtengo las variables, para buscar mi tag_id y mi basket_id
12
+ const { recepciones_tag_id: tag_id, recepciones_basket_item_id: basket_id, production_agency_id: temp_production_agency_id, } = await getVariablesByName(headers, session, [
13
+ "recepciones_tag_id",
14
+ "recepciones_basket_item_id",
15
+ "production_agency_id",
16
+ ]);
17
+ const hashProductionAgencyId = JSON.parse(temp_production_agency_id ?? "{}");
18
+ const production_agency_id = hashProductionAgencyId[session.get("agency_id")];
19
+ const agency_id = params.from_production_agency_id
20
+ ? production_agency_id
21
+ : session.get("agency_id");
22
+ //PASO 2: Busco mis ordenes de compra
23
+ const ordersDataTablesResponse = await getOrdersDataTables(headers, params?.page ? Number(params?.page) : 1, params?.perPage ? Number(params?.perPage) : 10, params?.search ?? "", tag_id, agency_id);
24
+ if (ordersDataTablesResponse.error) {
25
+ throw new Error(ordersDataTablesResponse.userMsg);
26
+ }
27
+ const ordersDataTables = ordersDataTablesResponse?.data;
28
+ //PASO 3: Busco mis lotes
29
+ const lotesResponse = await getLotesWithPurchaseFormated(headers, agency_id, Number(basket_id), ordersDataTables?.orders ?? {}, ordersDataTables?.desde, ordersDataTables?.hasta);
30
+ if (lotesResponse.error) {
31
+ throw new Error(lotesResponse.userMsg);
32
+ }
33
+ //PASO 4: Retorno la información
34
+ return {
35
+ recordsTotal: ordersDataTables?.recordsTotal ?? 0,
36
+ recordsFiltered: ordersDataTables?.recordsFiltered ?? 0,
37
+ draw: ordersDataTables?.draw ?? 0,
38
+ data: lotesResponse?.data ?? [],
39
+ };
40
+ });
41
+ };
42
+ /**
43
+ *
44
+ * @param headers
45
+ * @param tag_id
46
+ * @param agency_id
47
+ * @param page
48
+ * @param perPage
49
+ * @param search
50
+ * @returns
51
+ */
52
+ const getOrdersDataTables = async (headers, page, perPage, search, tag_id, agency_id) => {
53
+ return handlePossibleAxiosErrors(async () => {
54
+ const body = {
55
+ order: { "0": { column: "1", dir: "desc" } },
56
+ start: ((page ?? 1) - 1) * (perPage ?? 0),
57
+ length: perPage ?? 0,
58
+ search: { value: search ?? "", regex: false },
59
+ tag: tag_id,
60
+ agency: agency_id,
61
+ };
62
+ //Voy por las ordenes y las ordeno por fecha de recepción
63
+ const ordersDataTablesResponse = await getPurchasesListDataTables(headers, body);
64
+ const ordersDataTables = ordersDataTablesResponse.data;
65
+ const orders = ordersDataTables?.data.sort((a, b) => getNewDateByFormat(a.rd).getTime() - getNewDateByFormat(b.rd).getTime());
66
+ const purchaseOrders = {};
67
+ orders?.forEach((value) => {
68
+ const id_i_pos = value.z.indexOf("purchase_orders/") + 16;
69
+ const id_f_pos = value.z.indexOf('">');
70
+ const zid_f_pos = value.z.indexOf("</a>");
71
+ const id_n_i_pos = value.i.indexOf(">");
72
+ const id_n_f_pos = value.i.indexOf("</a>");
73
+ const new_date = getNewDateByFormat(value.dte);
74
+ const ven_i_pos = value.ven.indexOf('">');
75
+ const ven_f_pos = value.ven.indexOf("</a>");
76
+ const id_number = value.i.substring(id_n_i_pos + 1, id_n_f_pos);
77
+ const purchase_id = value.DT_RowId.replace("purchases-purchase-order-", "");
78
+ purchaseOrders[id_number] = {
79
+ id: value.z.substring(id_i_pos, id_f_pos),
80
+ zid: value.z.substring(id_f_pos + 2, zid_f_pos),
81
+ id_number: Number(id_number),
82
+ no_orden: Number(purchase_id),
83
+ dte: new_date,
84
+ o: Boolean(value.o),
85
+ vendor: value.ven.substring(ven_i_pos + 2, ven_f_pos),
86
+ po_editable: parseInt(value.due.substring(1)) > 0,
87
+ dis: Number(value.dis),
88
+ och: Number(value.och),
89
+ rd: value.rd,
90
+ };
91
+ });
92
+ return {
93
+ orders: purchaseOrders,
94
+ draw: ordersDataTables?.draw ?? 0,
95
+ recordsFiltered: ordersDataTables?.recordsFiltered ?? 0,
96
+ recordsTotal: ordersDataTables?.recordsTotal ?? 0,
97
+ desde: orders?.length ? getZauruDateByText(orders[0].rd) : undefined,
98
+ hasta: orders?.length
99
+ ? getZauruDateByText(orders[orders.length - 1].rd)
100
+ : undefined,
101
+ };
102
+ });
103
+ };
104
+ /**
105
+ * getPurchaseOrderDataTables Obtiene una orden de compra ya formateada con todos sus campos.
106
+ * @param headers
107
+ * @param tag_id
108
+ * @param agency_id
109
+ * @param search
110
+ * @returns
111
+ */
112
+ export const getPurchaseOrderDataTables = async (headers, search, tag_id, agency_id) => {
113
+ const body = {
114
+ order: { "0": { column: "1", dir: "desc" } },
115
+ start: 0,
116
+ length: 0,
117
+ search: { value: search, regex: false },
118
+ tag: tag_id,
119
+ agency: agency_id,
120
+ };
121
+ //Voy por las ordenes y las ordeno por fecha de recepción
122
+ const ordersDataTablesResponse = await getPurchasesListDataTables(headers, body);
123
+ const ordersDataTables = ordersDataTablesResponse.data;
124
+ const getPurchaseOrderFormated = (value) => {
125
+ const id_i_pos = value.z.indexOf("purchase_orders/") + 16;
126
+ const id_f_pos = value.z.indexOf('">');
127
+ const zid_f_pos = value.z.indexOf("</a>");
128
+ const id_n_i_pos = value.i.indexOf(">");
129
+ const id_n_f_pos = value.i.indexOf("</a>");
130
+ const new_date = getNewDateByFormat(value.dte);
131
+ const ven_i_pos = value.ven.indexOf('">');
132
+ const ven_f_pos = value.ven.indexOf("</a>");
133
+ const id_number = value.i.substring(id_n_i_pos + 1, id_n_f_pos);
134
+ const purchase_id = value.DT_RowId.replace("purchases-purchase-order-", "");
135
+ return {
136
+ id: value.z.substring(id_i_pos, id_f_pos),
137
+ zid: value.z.substring(id_f_pos + 2, zid_f_pos),
138
+ id_number: Number(id_number),
139
+ no_orden: Number(purchase_id),
140
+ dte: new_date,
141
+ o: Boolean(value.o),
142
+ vendor: value.ven.substring(ven_i_pos + 2, ven_f_pos),
143
+ po_editable: parseInt(value.due.substring(1)) > 0,
144
+ dis: Number(value.dis),
145
+ och: Number(value.och),
146
+ rd: value.rd,
147
+ };
148
+ };
149
+ !ordersDataTables?.data?.length &&
150
+ console.log("========== NO SE ENCONTRO NINGUNA ORDEN DE COMPRA ===========");
151
+ const purchaseOrderDataTable = getPurchaseOrderFormated(ordersDataTables?.data[0]);
152
+ return purchaseOrderDataTable;
153
+ };
154
+ /**
155
+ * updatePurchaseItemPrice
156
+ * @param headers
157
+ * @param data
158
+ * @param purchase_id
159
+ */
160
+ export const updatePurchaseItemPrice = async (headers, data, purchase_id) => {
161
+ return handlePossibleAxiosErrors(async () => {
162
+ const body = {
163
+ purchase_order: {
164
+ purchase_order_details_attributes: data.purchase_order_details_attributes,
165
+ },
166
+ };
167
+ const responseUpdate = await updateReceivedPurchaseOrder(headers, body, purchase_id);
168
+ if (responseUpdate.error) {
169
+ throw new Error(responseUpdate.userMsg);
170
+ }
171
+ return true;
172
+ });
173
+ };
174
+ /**
175
+ * updateOchAndDis
176
+ * @param headers
177
+ * @param session
178
+ * @returns
179
+ */
180
+ export const updateOchAndDis = async (headers, data, purchase_id) => {
181
+ return handlePossibleAxiosErrors(async () => {
182
+ const body = {
183
+ purchase_order: {
184
+ discount: data?.discount,
185
+ other_charges: data.other_charges,
186
+ },
187
+ };
188
+ await updateReceivedPurchaseOrder(headers, body, purchase_id);
189
+ return true;
190
+ });
191
+ };
192
+ /**
193
+ * updatePurchaseOrderReception
194
+ * @param headers
195
+ * @param data
196
+ * @param purchase_id
197
+ * @returns
198
+ */
199
+ export const updatePurchaseOrderReception = async (headers, data, purchase_id) => {
200
+ return handlePossibleAxiosErrors(async () => {
201
+ const body = {
202
+ purchase_order: {
203
+ payee_id: data.payee_id,
204
+ purchase_order_details_attributes: data.purchase_order_details_attributes,
205
+ },
206
+ };
207
+ await updateReceivedPurchaseOrder(headers, body, purchase_id);
208
+ return true;
209
+ });
210
+ };
211
+ /**
212
+ * Obtengo los id's de las órdenes de compra en un arreglo numérico
213
+ * @param headers
214
+ * @param session
215
+ * @param extraParams
216
+ * @returns
217
+ */
218
+ export const getOrderIDS = async (headers, session, extraParams) => {
219
+ return handlePossibleAxiosErrors(async () => {
220
+ const { recepciones_tag_id: tag_id } = await getVariablesByName(headers, session, ["recepciones_tag_id", "recepciones_basket_item_id"]);
221
+ const body = {
222
+ order: { "0": { column: "1", dir: "desc" } },
223
+ start: 0,
224
+ length: 2000, //para ir por todas
225
+ search: { value: "", regex: false },
226
+ tag: tag_id,
227
+ agency: session.get("agency_id") ?? undefined,
228
+ vendor: extraParams.vendor,
229
+ vendor_category: extraParams.vendor_category,
230
+ item: extraParams.item,
231
+ Desde: extraParams.desde,
232
+ Hasta: extraParams.hasta,
233
+ };
234
+ //Voy por las ordenes y las ordeno por fecha de recepción
235
+ const ordersDataTablesResponse = await getPurchasesListDataTables(headers, body);
236
+ const ordersDataTables = ordersDataTablesResponse.data;
237
+ return (ordersDataTables?.data?.map((x) => Number(x.DT_RowId.replace("purchases-purchase-order-", ""))) ?? []);
238
+ });
239
+ };
240
+ /**
241
+ * deleteOrder
242
+ * @returns
243
+ */
244
+ export const deletePurchaseOrderProcess = async (headers, session, id) => {
245
+ return handlePossibleAxiosErrors(async () => {
246
+ const { data: purchaseOrder, error: poError, userMsg: poUserMsg, } = await getPurchaseOrder(session, id);
247
+ if (poError || !purchaseOrder) {
248
+ throw new Error(poUserMsg);
249
+ }
250
+ //Elimino las recepciones si es que tiene
251
+ for (const reception of purchaseOrder.receptions) {
252
+ if (reception.received && !reception.voided) {
253
+ const responseDeleteReception = await deleteReception(headers, reception.id, purchaseOrder.id);
254
+ if (responseDeleteReception.error || !responseDeleteReception.data) {
255
+ throw new Error(responseDeleteReception.userMsg);
256
+ }
257
+ }
258
+ }
259
+ //Elimino los envíos si es que tiene
260
+ for (const ship of purchaseOrder.shipment_purchase_orders) {
261
+ const responseDeleteShip = await deleteDelivery(headers, ship.shipment_id);
262
+ if (responseDeleteShip.error || !responseDeleteShip.data) {
263
+ throw new Error(responseDeleteShip.userMsg);
264
+ }
265
+ }
266
+ //Inactivo los lotes que tenga
267
+ for (const lot of purchaseOrder.lots) {
268
+ await inactivarLote(headers, lot.id);
269
+ }
270
+ const responseDeletePO = await deletePurchaseOrder(headers, id);
271
+ if (responseDeletePO.error) {
272
+ throw new Error(responseDeletePO.userMsg);
273
+ }
274
+ return true;
275
+ });
276
+ };
277
+ /**
278
+ * Commitea una task iniciada para la pantalla de edición masiva de órdenes de compra
279
+ * @param session
280
+ * @param ordenes
281
+ * @param timeStamp
282
+ */
283
+ export const commitTask = async (session, ordenes, timeStamp) => {
284
+ const newTask = {
285
+ timeStamp,
286
+ iniciada: getStringFullDate(new Date()),
287
+ total_ordenes: ordenes.length,
288
+ completadas: 0,
289
+ };
290
+ const updateTasks = (session.get("updateTasks") ?? []);
291
+ session.set("updateTasks", [...updateTasks, newTask]);
292
+ await commitSession(session);
293
+ };
294
+ /**
295
+ * Comitea una task finalizada para la pantalla de edición de órdenes de compra masiva
296
+ * @param session
297
+ * @param timeStamp
298
+ */
299
+ export const commitEndTask = async (session, timeStamp) => {
300
+ let updateTasks = session.get("updateTasks");
301
+ if (Array.isArray(updateTasks) &&
302
+ updateTasks.some((task) => task.timeStamp === timeStamp)) {
303
+ updateTasks = updateTasks.map((x) => {
304
+ if (x.timeStamp === timeStamp) {
305
+ return {
306
+ ...x,
307
+ completadas: Number(x.completadas) + 1,
308
+ };
309
+ }
310
+ return x;
311
+ });
312
+ session.set("updateTasks", updateTasks);
313
+ await commitSession(session);
314
+ }
315
+ };
316
+ /**
317
+ * Elimina de la sesión una task.
318
+ * @param session
319
+ * @param timeStamp
320
+ */
321
+ export const deleteTask = async (session, timeStamp) => {
322
+ let updateTasks = session.get("updateTasks");
323
+ if (Array.isArray(updateTasks) &&
324
+ updateTasks.some((task) => task.timeStamp === timeStamp)) {
325
+ //La elimino de la lista
326
+ updateTasks = updateTasks.filter((task) => task.timeStamp !== timeStamp);
327
+ session.set("updateTasks", updateTasks);
328
+ await commitSession(session);
329
+ return true;
330
+ }
331
+ return false;
332
+ };
333
+ /**
334
+ * createNewLabItemRequest
335
+ * @param headers
336
+ * @param session
337
+ * @param body
338
+ * @returns
339
+ */
340
+ export const createNewLabItemRequest = (headers, session, body) => {
341
+ return handlePossibleAxiosErrors(async () => {
342
+ const { lab_charge_term_default_id, lab_agency_id, laboratory_proyect_id } = await getVariablesByName(headers, session, [
343
+ "lab_charge_term_default_id",
344
+ "lab_agency_id",
345
+ "laboratory_proyect_id",
346
+ ]);
347
+ const id_number = generateDistinctCode("POLAB");
348
+ const sendBody = {
349
+ ...body,
350
+ shipping_date: body.issue_date,
351
+ charge_term_id: Number(lab_charge_term_default_id),
352
+ agency_id: Number(lab_agency_id),
353
+ currency_id: CURRENCY_PREFIX.find((x) => x.prefix === "Q")?.id,
354
+ incoterm_id: 1,
355
+ taxable: false,
356
+ import: false,
357
+ id_number,
358
+ reference: "LABORATORIO - Solicitud de insumos desde WebApp",
359
+ origin: "LABORATORIO",
360
+ purchase_order_details: [
361
+ {
362
+ booked_quantity: body.booked_quantity,
363
+ item_id: body.item_id,
364
+ unit_cost: 1,
365
+ tag_id: Number(laboratory_proyect_id),
366
+ },
367
+ ],
368
+ taggings: [{ tag_id: Number(laboratory_proyect_id) }],
369
+ };
370
+ const response = await createNewPurchaseOrder(headers, sendBody);
371
+ if (!response.data || response.error) {
372
+ throw new Error("Ocurrió un error al crear la recepción de insumos: " + response.userMsg);
373
+ }
374
+ return response.data;
375
+ });
376
+ };
@@ -0,0 +1,21 @@
1
+ import type { Session } from "@remix-run/node";
2
+ import { AxiosUtilsResponse, ShipmentGraphQL } from "@zauru-sdk/types";
3
+ /**
4
+ *
5
+ * @param headers
6
+ * @param session
7
+ * @returns
8
+ */
9
+ export declare const getShipmentsToMyAgency: (session: Session) => Promise<AxiosUtilsResponse<ShipmentGraphQL[]>>;
10
+ /**
11
+ *
12
+ * @param headers
13
+ * @param session
14
+ * @param props
15
+ * @returns
16
+ */
17
+ export declare const shipmentToVirtualClientAgency: (headers: any, session: Session, props: {
18
+ deliver_quantity: number;
19
+ item_id: number;
20
+ esPerecedero?: boolean;
21
+ }) => Promise<AxiosUtilsResponse<boolean>>;
@@ -0,0 +1,90 @@
1
+ import { getDatePickerCurrentDate, handlePossibleAxiosErrors, reduceAdd } from "@zauru-sdk/common";
2
+ import { getDeliveryByBooking, getMyAgencyLotStocks, getShipmentsByToAgencyLast100Id_booking, getVariablesByName, insertBookings } from "@zauru-sdk/services";
3
+ /**
4
+ *
5
+ * @param headers
6
+ * @param session
7
+ * @returns
8
+ */
9
+ export const getShipmentsToMyAgency = async (session) => {
10
+ return handlePossibleAxiosErrors(async () => {
11
+ const response = await getShipmentsByToAgencyLast100Id_booking(session, session.get("agency_id"));
12
+ if (response.error) {
13
+ throw new Error(`Ocurrió un error al consultar los envíos a mi agencia actual: ${response.userMsg}`);
14
+ }
15
+ return response?.data ?? [];
16
+ });
17
+ };
18
+ /**
19
+ *
20
+ * @param headers
21
+ * @param session
22
+ * @param props
23
+ * @returns
24
+ */
25
+ export const shipmentToVirtualClientAgency = async (headers, session, props) => {
26
+ return handlePossibleAxiosErrors(async () => {
27
+ const { virtual_client_agency_id } = await getVariablesByName(headers, session, ["virtual_client_agency_id"]);
28
+ let bookingBody = {};
29
+ if (props?.esPerecedero) {
30
+ const responseStocks = await getMyAgencyLotStocks(session);
31
+ if (!responseStocks.data || responseStocks.error) {
32
+ throw new Error(`Ocurrió un error al tratar de obtener los stocks de mi agencia. ${responseStocks.userMsg}`);
33
+ }
34
+ let deliverQuantity = props.deliver_quantity;
35
+ const itemStocks = responseStocks.data
36
+ .filter((x) => x.lot.item_id === props.item_id)
37
+ .sort((a, b) => b.available - a.available);
38
+ if (itemStocks.map((x) => x.available).reduce(reduceAdd, 0) <
39
+ props.deliver_quantity) {
40
+ throw new Error(`No hay suficiente stock en los lotes para realizar el descuento.`);
41
+ }
42
+ const movements = itemStocks.reduce((acc, stock) => {
43
+ if (deliverQuantity > 0 && stock.available > 0) {
44
+ const bookedQuantity = Math.min(stock.available, deliverQuantity);
45
+ deliverQuantity -= bookedQuantity;
46
+ acc.push({
47
+ item_id: props.item_id,
48
+ booked_quantity: bookedQuantity,
49
+ lot_id: stock.lot_id,
50
+ });
51
+ }
52
+ return acc;
53
+ }, []);
54
+ bookingBody = {
55
+ reference: "LABORATORIO - Descuento de stock, desde webapp.",
56
+ agency_from_id: session.get("agency_id"),
57
+ agency_to_id: Number(virtual_client_agency_id),
58
+ booker_id: session.get("employee_id"),
59
+ transporter_id: session.get("employee_id"),
60
+ planned_delivery: getDatePickerCurrentDate(),
61
+ needs_transport: false,
62
+ movements,
63
+ };
64
+ }
65
+ else {
66
+ bookingBody = {
67
+ reference: "LABORATORIO - Descuento de stock, desde webapp.",
68
+ agency_from_id: session.get("agency_id"),
69
+ agency_to_id: Number(virtual_client_agency_id),
70
+ booker_id: session.get("employee_id"),
71
+ transporter_id: session.get("employee_id"),
72
+ planned_delivery: getDatePickerCurrentDate(),
73
+ needs_transport: false,
74
+ movements: [
75
+ { item_id: props.item_id, booked_quantity: props.deliver_quantity },
76
+ ],
77
+ };
78
+ }
79
+ const response1 = await insertBookings(headers, bookingBody);
80
+ if (response1.error || !response1.data) {
81
+ throw new Error(`Ocurrió un error al tratar de crear el envío a agencia virtual de cliente: ${response1.userMsg}`);
82
+ }
83
+ //Entregar el envío
84
+ const response2 = await getDeliveryByBooking(headers, response1.data.id);
85
+ if (response2.error || !response2.data) {
86
+ throw new Error(`Ocurrió un error al tratar de recibir: ${response1.userMsg}`);
87
+ }
88
+ return true;
89
+ });
90
+ };
@@ -0,0 +1,34 @@
1
+ import type { Session } from "@remix-run/node";
2
+ import { AxiosUtilsResponse, SpecialItem, WebAppRowGraphQL, WebAppTableUpdateResponse } from "@zauru-sdk/types";
3
+ /**
4
+ * Get specialItems from the web app table.
5
+ * @param headers Request headers.
6
+ * @param session Session object.
7
+ * @returns A Promise of AxiosUtilsResponse<WebAppRowGraphQL<SpecialItem>[]>>.
8
+ */
9
+ export declare function getSpecialItems(headers: any, session: Session): Promise<AxiosUtilsResponse<WebAppRowGraphQL<SpecialItem>[]>>;
10
+ /**
11
+ * Create a specialItem in the web app table.
12
+ * @param headers Request headers.
13
+ * @param session Session object.
14
+ * @param body SpecialItem data to be created.
15
+ * @returns A Promise of AxiosUtilsResponse<WebAppTableUpdateResponse>.
16
+ */
17
+ export declare function createSpecialItem(headers: any, session: Session, body: SpecialItem): Promise<AxiosUtilsResponse<WebAppTableUpdateResponse>>;
18
+ /**
19
+ * Delete a specialItem from the web app table.
20
+ * @param headers Request headers.
21
+ * @param session Session object.
22
+ * @param id ID of the specialItem to be deleted.
23
+ * @returns A Promise of AxiosUtilsResponse<WebAppTableUpdateResponse>.
24
+ */
25
+ export declare function deleteSpecialItem(headers: any, session: Session, id: string): Promise<AxiosUtilsResponse<WebAppTableUpdateResponse>>;
26
+ /**
27
+ * Update a specialItem in the web app table.
28
+ * @param headers Request headers.
29
+ * @param session Session object.
30
+ * @param id ID of the specialItem to be updated.
31
+ * @param body Updated specialItem data.
32
+ * @returns A Promise of AxiosUtilsResponse<WebAppTableUpdateResponse>.
33
+ */
34
+ export declare function updateSpecialItem(headers: any, session: Session, id: string, body: Partial<SpecialItem>): Promise<AxiosUtilsResponse<WebAppTableUpdateResponse>>;