@zauru-sdk/utils 6.11.0 → 6.13.0

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.
package/dist/esm/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  export * from "./zauru/automatic-number.utils.js";
2
2
  export * from "./zauru/bitacora-edicion-masiva.utils.js";
3
3
  export * from "./zauru/bundles.utils.js";
4
+ export * from "./zauru/catalogs.loader.js";
4
5
  export * from "./zauru/cases.utils.js";
5
6
  export * from "./zauru/consolidated-history.utils.js";
6
7
  export * from "./zauru/costos-items.utils.js";
@@ -0,0 +1,188 @@
1
+ import { createElement } from "react";
2
+ import { redirect } from "@remix-run/node";
3
+ import { get4pinosPoDiscountHistory, get4pinosSolicitudEliminacionPO, get4pinosWeightLimitPerBasket, getAgencies, getAllForms, getAuthorizationUpdateDiscountPO, getBookings, getCaseFormSubmissionsByCaseId, getCases, getCCPorcentajesDeRechazo, getClientCategories, getCurrencies, getEmployees, getFormsByDocumentType, getHeaders, getInvoiceFormSubmissionsByAgencyId, getInvoiceFormSubmissionsByInvoiceId, getInvoicesByAgencyId, getItems, getMotivosRechazo, getMyAgencyLotStocks, getMyCaseFormSubmissions, getPayeeCategories, getPayeeCategoriesByNotesMatch, getPayees, getPaymentMethods, getPaymentTerms, getPrintTemplates, getProviderCategories, getProviders, getSession, getSuggestedPrices, } from "@zauru-sdk/services";
4
+ import { getBitacorasPOMassive } from "./bitacora-edicion-masiva.utils.js";
5
+ import { getBundlesByLabCategory, getBundlesRecipByLabCategory } from "./bundles.utils.js";
6
+ import { getEmployeesByCurrentAgency, getEmployeesByLabAgency } from "./employees.utils.js";
7
+ import { getInvoicesByLabAgency } from "./invoices.utils.js";
8
+ import { getItemServicesByLabCategory, getItemsByLabCategory, getItemsByReceptionCategory, getLabItemCategories, } from "./items.utils.js";
9
+ import { getClientesLaboratorio, TEXT_PAYEE_CATEGORY_NOTES_FOR_PRICE, } from "./payees.utils.js";
10
+ import { getProgramaciones } from "./programaciones.utils.js";
11
+ import { getShipmentsToMyAgency } from "./shipments.utils.js";
12
+ import { getTemplates } from "./templates.utils.js";
13
+ import { getTipoMuestras } from "./tiposMuestra.utils.js";
14
+ import { getReceptionTypes } from "./webapp-tables.utils.js";
15
+ const missingQueryParam = (param) => {
16
+ console.warn({
17
+ description: `No se envió ningún parámetro de ${param} a buscar`,
18
+ title: "Ocurrió un error.",
19
+ error: true,
20
+ type: "error",
21
+ });
22
+ return Response.json({});
23
+ };
24
+ const catalogErrorPayload = (catalog, description) => ({
25
+ [catalog]: [],
26
+ error: true,
27
+ type: "error",
28
+ title: `Ocurrió un error al obtener el catálogo de ${catalog}!.`,
29
+ description,
30
+ });
31
+ const unknownCatalogPayload = {
32
+ description: "No se envió ningún parámetro de catálogo a buscar",
33
+ title: "Ocurrió un error.",
34
+ error: true,
35
+ type: "error",
36
+ };
37
+ const sdkCatalogHandlers = {
38
+ printTemplates: ({ session }) => getPrintTemplates(session),
39
+ paymentMethods: ({ session }) => getPaymentMethods(session),
40
+ invoiceFormSubmissions: ({ session, url }) => {
41
+ const agency_id = url.searchParams.get("agency_id") ?? session.get("agency_id");
42
+ return getInvoiceFormSubmissionsByAgencyId(session, agency_id);
43
+ },
44
+ payees: ({ session }) => getPayees(session),
45
+ items: ({ session }) => getItems(session),
46
+ payeesForLab: ({ session }) => getClientesLaboratorio(session),
47
+ currencies: ({ session }) => getCurrencies(session),
48
+ employees: ({ session }) => getEmployees(session),
49
+ employeesByLab: ({ headers, session }) => getEmployeesByLabAgency(headers, session),
50
+ employeesByCurrentAgency: ({ session }) => getEmployeesByCurrentAgency(session),
51
+ shipmentsToMyAgency: ({ session }) => getShipmentsToMyAgency(session),
52
+ allForms: ({ session, url }) => {
53
+ const withSubmissions = url.searchParams.get("withSubmissions") === "true";
54
+ return getAllForms(session, { withSubmissions });
55
+ },
56
+ invoiceForms: ({ session }) => getFormsByDocumentType(session, "invoice"),
57
+ caseForms: ({ session }) => getFormsByDocumentType(session, "case"),
58
+ paymentTerms: ({ session }) => getPaymentTerms(session),
59
+ invoicesByLab: ({ headers, session }) => getInvoicesByLabAgency(headers, session),
60
+ invoicesByCurrentAgency: ({ session, url }) => {
61
+ const tag_id = url.searchParams.get("tag_id") ?? undefined;
62
+ const invoice_id = url.searchParams.get("invoice_id") ?? undefined;
63
+ return getInvoicesByAgencyId(session, session.get("agency_id"), {
64
+ tag_id,
65
+ invoice_id,
66
+ });
67
+ },
68
+ payeeCategoriesLabPrices: ({ session }) => getPayeeCategoriesByNotesMatch(session, TEXT_PAYEE_CATEGORY_NOTES_FOR_PRICE),
69
+ payeeCategories: ({ session }) => getPayeeCategories(session),
70
+ receptionTypes: ({ headers, session }) => getReceptionTypes(headers, session),
71
+ bitacoraRechazoMasivo: ({ headers, session }) => getBitacorasPOMassive(headers, session),
72
+ cases: ({ session, url }) => {
73
+ const tag_id = url.searchParams.get("tag_id") ?? undefined;
74
+ const assignedToMe = url.searchParams.get("assignedToMe") === "true";
75
+ return getCases(session, {
76
+ tag_id,
77
+ ...(assignedToMe
78
+ ? { responsible_id: Number(session.get("employee_id")) }
79
+ : {}),
80
+ });
81
+ },
82
+ myCases: ({ session }) => getCases(session, {
83
+ responsible_id: Number(session.get("employee_id")),
84
+ }),
85
+ myCaseFormSubmissions: ({ headers, session }) => getMyCaseFormSubmissions(headers, session),
86
+ tiposDeMuestra: ({ headers, session }) => getTipoMuestras(headers, session),
87
+ myAgencyLotStocks: ({ session }) => getMyAgencyLotStocks(session),
88
+ motivosRechazo: ({ headers, session }) => getMotivosRechazo(headers, session),
89
+ ccPorcentajesDeRechazo: ({ headers, session }) => getCCPorcentajesDeRechazo(headers, session),
90
+ programaciones4pinos: ({ headers, session }) => getProgramaciones(headers, session),
91
+ solicitudesEliminacionPO: ({ headers, session }) => get4pinosSolicitudEliminacionPO(headers, session),
92
+ pesoMaximoPorCanasta: ({ headers, session }) => get4pinosWeightLimitPerBasket(headers, session),
93
+ poDiscountHistory: ({ headers, session }) => get4pinosPoDiscountHistory(headers, session),
94
+ authorizationUpdateDiscountPO: ({ headers, session }) => getAuthorizationUpdateDiscountPO(headers, session),
95
+ itemsByReception: ({ headers, session }) => getItemsByReceptionCategory(headers, session),
96
+ itemsByLab: ({ headers, session }) => getItemsByLabCategory(headers, session),
97
+ itemServicesByLab: ({ headers, session }) => getItemServicesByLabCategory(headers, session),
98
+ itemCategoriesForLab: ({ headers, session }) => getLabItemCategories(headers, session),
99
+ bundlesRecipForLab: ({ headers, session }) => getBundlesRecipByLabCategory(headers, session),
100
+ bundlesForLab: ({ headers, session }) => getBundlesByLabCategory(headers, session),
101
+ templates: ({ headers, session }) => getTemplates(headers, session),
102
+ bookings: ({ session, wheres }) => getBookings(session, wheres),
103
+ suggestedPrices: ({ session, url }) => {
104
+ const withItems = url.searchParams.get("withItems") === "true";
105
+ const withItemCategories = url.searchParams.get("withItemCategories") === "true";
106
+ return getSuggestedPrices(session, { withItems, withItemCategories });
107
+ },
108
+ providerCategories: ({ session }) => getProviderCategories(session),
109
+ clientCategories: ({ session }) => getClientCategories(session),
110
+ providers: ({ session }) => getProviders(session),
111
+ agencies: ({ session }) => getAgencies(session),
112
+ invoiceFormSubmissionsByAgencyId: async ({ session, url }) => {
113
+ const agency_id = url.searchParams.get("agency_id");
114
+ if (!agency_id) {
115
+ return missingQueryParam("agency_id");
116
+ }
117
+ return getInvoiceFormSubmissionsByAgencyId(session, agency_id);
118
+ },
119
+ invoiceFormSubmissionsByInvoiceId: async ({ headers, session, url }) => {
120
+ const withFiles = url.searchParams.get("withFiles") === "true";
121
+ const invoiceId = url.searchParams.get("invoiceId");
122
+ if (!invoiceId) {
123
+ return missingQueryParam("invoiceId");
124
+ }
125
+ return getInvoiceFormSubmissionsByInvoiceId(headers, session, invoiceId, withFiles);
126
+ },
127
+ caseFormSubmissionsByCaseId: async ({ headers, session, url }) => {
128
+ const withFiles = url.searchParams.get("withFiles") === "true";
129
+ const caseId = url.searchParams.get("caseId");
130
+ if (!caseId) {
131
+ return missingQueryParam("caseId");
132
+ }
133
+ return getCaseFormSubmissionsByCaseId(headers, session, caseId, withFiles);
134
+ },
135
+ };
136
+ /**
137
+ * Remix loader for `/api/catalogs`. Shared catalog names live in the SDK;
138
+ * pass `extras` to add or override handlers for a single webapp.
139
+ */
140
+ export function createCatalogsLoader(extras) {
141
+ return async ({ request }) => {
142
+ try {
143
+ const cookie = request.headers.get("Cookie");
144
+ const session = await getSession(cookie);
145
+ if (!session.has("username")) {
146
+ return redirect("/");
147
+ }
148
+ const headers = await getHeaders(cookie, session);
149
+ const url = new URL(request.url);
150
+ const catalog = url.searchParams.get("catalog") ?? "";
151
+ const wheres = url.searchParams
152
+ .get("wheres")
153
+ ?.split("&")
154
+ .map((where) => decodeURIComponent(where))
155
+ .filter((where) => where !== "") ?? [];
156
+ if (!catalog) {
157
+ return Response.json(unknownCatalogPayload);
158
+ }
159
+ const handler = extras?.[catalog] ?? sdkCatalogHandlers[catalog];
160
+ if (!handler) {
161
+ return Response.json(unknownCatalogPayload);
162
+ }
163
+ const result = await handler({
164
+ request,
165
+ session,
166
+ headers,
167
+ url,
168
+ catalog,
169
+ wheres,
170
+ });
171
+ if (result instanceof Response) {
172
+ return result;
173
+ }
174
+ if (result.error || !result.data) {
175
+ return Response.json(catalogErrorPayload(catalog, `${result.userMsg ?? ""}`));
176
+ }
177
+ return { [catalog]: result.data };
178
+ }
179
+ catch (error) {
180
+ console.error(error);
181
+ const catalog = new URL(request.url).searchParams.get("catalog") || "catalog";
182
+ return catalogErrorPayload(catalog, `${error}`);
183
+ }
184
+ };
185
+ }
186
+ export function CatalogsRoute() {
187
+ return createElement("div", { style: { fontFamily: "system-ui, sans-serif", lineHeight: "1.4" } }, "CATALOGS LOAD");
188
+ }
@@ -1,4 +1,4 @@
1
- import { CURRENCY_PREFIX, applyRejectionPercentageRulesToFinancials, calculatePurchaseOrderFinancials, getNewDateByFormat, getStringFullDate, getZauruDateByText, handlePossibleAxiosErrors, setRejectionPercentage, } from "@zauru-sdk/common";
1
+ import { CURRENCY_PREFIX, calculatePurchaseOrderFinancials, getNewDateByFormat, getStringFullDate, getZauruDateByText, handlePossibleAxiosErrors, mergeJsonMemo, } from "@zauru-sdk/common";
2
2
  import { commitSession, createNewPurchaseOrder, deleteDelivery, deletePurchaseOrder, deleteReception, getLotesWithPurchaseFormated, getPurchase, getPurchaseOrder, getPurchasesListDataTables, getVariablesByName, inactivarLote, updateReceivedPurchaseOrder, } from "@zauru-sdk/services";
3
3
  import { getActiveRejectionPercentageAdjustmentRules } from "./rejectionPercentageAdjustmentRules.utils.js";
4
4
  /**
@@ -258,32 +258,26 @@ export const updateOchAndDis = async (headers, data, purchase_id, session) => {
258
258
  const payee = purchaseRecord?.payee;
259
259
  const itemIds = extractPurchaseOrderItemIds(loadedPurchase);
260
260
  const tipo = purchaseRecord?.reference;
261
- const adjusted = rules.length > 0
262
- ? applyRejectionPercentageRulesToFinancials({
263
- memo: currentMemo,
264
- originPercentage: rejectionPercentage,
265
- details,
266
- rules,
267
- ctx: {
268
- itemIds,
269
- tipo,
270
- providerCategoryId: payee?.payee_category_id ??
271
- purchaseRecord
272
- ?.payee_category_id,
273
- },
274
- })
275
- : {
276
- memo: setRejectionPercentage(currentMemo, rejectionPercentage),
277
- discount: calculatePurchaseOrderFinancials({
278
- details,
279
- rejectionPercentage,
280
- }).discount,
281
- finalPercentage: rejectionPercentage,
282
- };
261
+ const financials = calculatePurchaseOrderFinancials({
262
+ details,
263
+ rejectionPercentage,
264
+ memo: currentMemo,
265
+ rules,
266
+ ctx: {
267
+ itemIds,
268
+ tipo,
269
+ providerCategoryId: payee?.payee_category_id ??
270
+ purchaseRecord
271
+ ?.payee_category_id,
272
+ },
273
+ });
283
274
  const body = {
284
275
  purchase_order: {
285
- memo: adjusted.memo,
286
- discount: adjusted.discount,
276
+ memo: mergeJsonMemo(currentMemo, {
277
+ rejectionPercentage: financials.rejectionPercentage,
278
+ rejectionCalculations: financials.rejectionCalculations,
279
+ }),
280
+ discount: financials.discount,
287
281
  },
288
282
  };
289
283
  if (data.other_charges !== undefined && data.other_charges !== null) {
@@ -1,7 +1,6 @@
1
- import { handlePossibleAxiosErrors } from "@zauru-sdk/common";
2
- import { createWebAppTableRegister, getRejectionPercentageAdjustmentRulesByHeaders, getVariablesByName, getWebAppTableRegisters, updateWebAppTableRegister, } from "@zauru-sdk/services";
3
- export { applyRejectionPercentageAdjustmentRules, applyRejectionPercentageRulesToFinancials, filterActiveRejectionPercentageAdjustmentRules, formatRejectionPercentageAdjustmentDescription, rejectionPercentageAdjustmentRuleMatches, resolveRejectionPercentageBase, resolveRejectionPercentageOrigin, REJECTION_PERCENTAGE_ADJUSTMENT_RULES_TABLE_VAR, } from "@zauru-sdk/common";
4
- import { filterActiveRejectionPercentageAdjustmentRules, REJECTION_PERCENTAGE_ADJUSTMENT_RULES_TABLE_VAR, } from "@zauru-sdk/common";
1
+ import { filterActiveRejectionPercentageAdjustmentRules, handlePossibleAxiosErrors, REJECTION_PERCENTAGE_ADJUSTMENT_RULES_TABLE_VAR, } from "@zauru-sdk/common";
2
+ import { createWebAppTableRegister, getVariables, getVariablesByName, getWebAppTableRegisters, getWebAppTableRegistersRest, updateWebAppTableRegister, } from "@zauru-sdk/services";
3
+ export { applyRejectionPercentageAdjustmentRules, filterActiveRejectionPercentageAdjustmentRules, formatRejectionPercentageAdjustmentDescription, rejectionPercentageAdjustmentRuleMatches, resolveRejectionPercentageBase, resolveRejectionPercentageOrigin, REJECTION_PERCENTAGE_ADJUSTMENT_RULES_TABLE_VAR, } from "@zauru-sdk/common";
5
4
  const getTableId = async (headers, session) => {
6
5
  const vars = await getVariablesByName(headers, session, [
7
6
  REJECTION_PERCENTAGE_ADJUSTMENT_RULES_TABLE_VAR,
@@ -18,6 +17,24 @@ export const getRejectionPercentageAdjustmentRules = (headers, session) => {
18
17
  return response.data ?? [];
19
18
  });
20
19
  };
20
+ /**
21
+ * Same listing without a Remix session: resolves the table id over REST, for
22
+ * background flows that only carry the Zauru headers.
23
+ */
24
+ export const getRejectionPercentageAdjustmentRulesByHeaders = (headers) => {
25
+ return handlePossibleAxiosErrors(async () => {
26
+ const varsResponse = await getVariables(headers);
27
+ const tableId = varsResponse.data?.find((variable) => variable.name === REJECTION_PERCENTAGE_ADJUSTMENT_RULES_TABLE_VAR)?.value;
28
+ if (varsResponse.error || !tableId) {
29
+ return [];
30
+ }
31
+ const rowsResponse = await getWebAppTableRegistersRest(headers, tableId);
32
+ if (rowsResponse.error) {
33
+ throw new Error(`Ocurrió un error al consultar las reglas de ajuste de porcentaje de rechazo: ${rowsResponse.userMsg}`);
34
+ }
35
+ return rowsResponse.data ?? [];
36
+ });
37
+ };
21
38
  export const getActiveRejectionPercentageAdjustmentRules = async (headers, session) => {
22
39
  try {
23
40
  if (session) {
@@ -151,6 +151,7 @@ export const calculateItemPriceFromWeeklyMatrix = (input) => {
151
151
  source,
152
152
  period,
153
153
  specialItemId,
154
+ providerCategoryId: input.providerCategoryId,
154
155
  };
155
156
  };
156
157
  export const loadLatestWeeklyCostMatrix = (headers, session, date) => {
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  export * from "./zauru/automatic-number.utils.js";
2
2
  export * from "./zauru/bitacora-edicion-masiva.utils.js";
3
3
  export * from "./zauru/bundles.utils.js";
4
+ export * from "./zauru/catalogs.loader.js";
4
5
  export * from "./zauru/cases.utils.js";
5
6
  export * from "./zauru/consolidated-history.utils.js";
6
7
  export * from "./zauru/costos-items.utils.js";
@@ -0,0 +1,19 @@
1
+ import { type ReactElement } from "react";
2
+ import type { LoaderFunction, Session } from "@remix-run/node";
3
+ import { getHeaders } from "@zauru-sdk/services";
4
+ import type { AxiosUtilsResponse } from "@zauru-sdk/types";
5
+ export type CatalogLoaderContext = {
6
+ request: Request;
7
+ session: Session;
8
+ headers: Awaited<ReturnType<typeof getHeaders>>;
9
+ url: URL;
10
+ catalog: string;
11
+ wheres: string[];
12
+ };
13
+ export type CatalogHandler = (ctx: CatalogLoaderContext) => Promise<AxiosUtilsResponse<unknown> | Response>;
14
+ /**
15
+ * Remix loader for `/api/catalogs`. Shared catalog names live in the SDK;
16
+ * pass `extras` to add or override handlers for a single webapp.
17
+ */
18
+ export declare function createCatalogsLoader(extras?: Record<string, CatalogHandler>): LoaderFunction;
19
+ export declare function CatalogsRoute(): ReactElement;
@@ -1,7 +1,12 @@
1
1
  import type { Session } from "@remix-run/node";
2
2
  import { AxiosUtilsResponse, RejectionPercentageAdjustmentRule, WebAppRowGraphQL, WebAppTableUpdateResponse } from "@zauru-sdk/types";
3
- export { applyRejectionPercentageAdjustmentRules, applyRejectionPercentageRulesToFinancials, filterActiveRejectionPercentageAdjustmentRules, formatRejectionPercentageAdjustmentDescription, rejectionPercentageAdjustmentRuleMatches, resolveRejectionPercentageBase, resolveRejectionPercentageOrigin, REJECTION_PERCENTAGE_ADJUSTMENT_RULES_TABLE_VAR, } from "@zauru-sdk/common";
3
+ export { applyRejectionPercentageAdjustmentRules, filterActiveRejectionPercentageAdjustmentRules, formatRejectionPercentageAdjustmentDescription, rejectionPercentageAdjustmentRuleMatches, resolveRejectionPercentageBase, resolveRejectionPercentageOrigin, REJECTION_PERCENTAGE_ADJUSTMENT_RULES_TABLE_VAR, } from "@zauru-sdk/common";
4
4
  export declare const getRejectionPercentageAdjustmentRules: (headers: any, session: Session) => Promise<AxiosUtilsResponse<WebAppRowGraphQL<RejectionPercentageAdjustmentRule>[]>>;
5
+ /**
6
+ * Same listing without a Remix session: resolves the table id over REST, for
7
+ * background flows that only carry the Zauru headers.
8
+ */
9
+ export declare const getRejectionPercentageAdjustmentRulesByHeaders: (headers: any) => Promise<AxiosUtilsResponse<WebAppRowGraphQL<RejectionPercentageAdjustmentRule>[]>>;
5
10
  export declare const getActiveRejectionPercentageAdjustmentRules: (headers: any, session?: Session) => Promise<WebAppRowGraphQL<RejectionPercentageAdjustmentRule>[]>;
6
11
  export declare const createRejectionPercentageAdjustmentRule: (headers: any, session: Session, body: RejectionPercentageAdjustmentRule) => Promise<AxiosUtilsResponse<WebAppTableUpdateResponse>>;
7
12
  export declare const updateRejectionPercentageAdjustmentRule: (headers: any, session: Session, id: string, body: Partial<RejectionPercentageAdjustmentRule>) => Promise<AxiosUtilsResponse<WebAppTableUpdateResponse>>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zauru-sdk/utils",
3
- "version": "6.11.0",
3
+ "version": "6.13.0",
4
4
  "description": "Utilidades, parseo de request y demás para desarrollo de webapps de Zauru",
5
5
  "main": "./dist/esm/index.js",
6
6
  "module": "./dist/esm/index.js",
@@ -20,17 +20,22 @@
20
20
  ],
21
21
  "author": "Oscar Cuéllar",
22
22
  "license": "MIT",
23
+ "peerDependencies": {
24
+ "react": "^18.2.0 || ^19.0.0"
25
+ },
23
26
  "devDependencies": {
27
+ "@types/react": "^18.2.20",
28
+ "react": "^18.2.0",
24
29
  "typescript": "^5.1.6"
25
30
  },
26
31
  "dependencies": {
27
32
  "@remix-run/node": "^2.8.1",
28
- "@zauru-sdk/common": "^6.5.0",
33
+ "@zauru-sdk/common": "^6.6.0",
29
34
  "@zauru-sdk/config": "^6.0.0",
30
35
  "@zauru-sdk/graphql": "^6.7.0",
31
- "@zauru-sdk/services": "^6.10.0",
32
- "@zauru-sdk/types": "^6.15.0",
36
+ "@zauru-sdk/services": "^6.11.0",
37
+ "@zauru-sdk/types": "^6.16.0",
33
38
  "moment": "^2.30.1"
34
39
  },
35
- "gitHead": "2dceb781cae3f4c45ceecb915977c6d142bca6b9"
40
+ "gitHead": "91e3b376891f89cef02d1badd765db595edbe086"
36
41
  }