@zauru-sdk/hooks 2.0.116 → 2.0.120

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.
@@ -1,5 +1,22 @@
1
1
  import type { AgencyGraphQL, BitacoraPOMassive, BundleGraphQL, CaseGraphQL, CurrencyGraphQL, EmployeeGraphQL, FormGraphQL, InvoiceGraphQL, ItemCategoryGraphQL, ItemGraphQL, LotStockGraphQL, MotivoRechazo, PayeeCategoryGraphQL, PayeeGraphQL, PaymentTermGraphQL, ReceptionType, ShipmentGraphQL, SubmissionCasesGraphQL, SubmissionInvoicesGraphQL, SuggestedPriceGraphQL, Template, TipoMuestra, WebAppRowGraphQL, PrintTemplateGraphQL, PaymentMethodGraphQL } from "@zauru-sdk/types";
2
- import { ReduxParamsConfig } from "@zauru-sdk/redux";
2
+ import { CATALOGS_NAMES, ReduxParamsConfig } from "@zauru-sdk/redux";
3
+ type CatalogType<T> = {
4
+ data: T[];
5
+ loading: boolean;
6
+ };
7
+ /**
8
+ *
9
+ * @param CATALOG_NAME
10
+ * @param param1
11
+ * @returns
12
+ *
13
+ * otherParams usage example:
14
+ *
15
+ * otherParams: {
16
+ includeDiscounts: "true",
17
+ }
18
+ */
19
+ export declare function useGetReduxCatalog<T>(CATALOG_NAME: CATALOGS_NAMES, { online, wheres, otherParams }?: ReduxParamsConfig): CatalogType<T>;
3
20
  /**
4
21
  *
5
22
  * ======================= HOOKS
@@ -154,7 +171,7 @@ export declare const useGetCaseForms: (config?: ReduxParamsConfig) => {
154
171
  loading: boolean;
155
172
  data: FormGraphQL[];
156
173
  };
157
- export declare const useGetInvoiceFormSubmissionsByAgencyId: (agency_id: number | string) => {
174
+ export declare const useGetInvoiceFormSubmissionsByAgencyId: (config?: ReduxParamsConfig) => {
158
175
  loading: boolean;
159
176
  data: SubmissionInvoicesGraphQL[];
160
177
  };
@@ -166,3 +183,4 @@ export declare const useGetInvoiceFormSubmissionsByInvoiceId: (config?: ReduxPar
166
183
  loading: boolean;
167
184
  data: SubmissionInvoicesGraphQL[];
168
185
  };
186
+ export {};
@@ -1,65 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.useGetInvoiceFormSubmissionsByInvoiceId = exports.useGetMyCaseFormSubmissions = exports.useGetInvoiceFormSubmissionsByAgencyId = exports.useGetCaseForms = exports.useGetInvoiceForms = exports.useGetAllForms = exports.useGetBitacoraRechazoMasivo = exports.useGetMotivosDeRechazo = exports.useGetTiposDeMuestra = exports.useGetInvoicesByCurrentAgency = exports.useGetInvoicesByLab = exports.useGetShipmentsToMyAgency = exports.useGetEmployees = exports.useGetEmployeesByCurrentAgency = exports.useGetEmployeesByLab = exports.useGetPaymentMethods = exports.useGetPaymentTerms = exports.useGetSuggestedPrices = exports.useGetAgencies = exports.useGetPrintTemplates = exports.useGetPayeesForLab = exports.useGetPayees = exports.useGetClientCategories = exports.useGetProviderCategories = exports.useGetMyCases = exports.useGetProviders = exports.useGetReceptionTypes = exports.useGetCurrencies = exports.useGetBundlesForLab = exports.useGetBundlesRecipForLab = exports.useGetPayeeCategoriesLabPrices = exports.useGetPayeeCategories = exports.useGetTemplates = exports.useGetBookings = exports.useGetItemCategoriesForLab = exports.useGetItemServicesByLab = exports.useGetMyAgencyLotStocks = exports.useGetItemsByLab = exports.useGetItemsByReception = exports.useGetItems = void 0;
4
+ exports.useGetReduxCatalog = useGetReduxCatalog;
4
5
  const react_1 = require("@remix-run/react");
5
6
  const react_2 = require("react");
6
7
  const index_js_1 = require("./components/index.js");
7
8
  const redux_1 = require("@zauru-sdk/redux");
8
- const useApiCatalog = (CATALOG_NAME, otherParams) => {
9
- try {
10
- const fetcher = (0, react_1.useFetcher)();
11
- const [data, setData] = (0, react_2.useState)({
12
- data: [],
13
- loading: true,
14
- });
15
- (0, react_2.useEffect)(() => {
16
- if (fetcher.data?.title) {
17
- (0, index_js_1.showAlert)({
18
- description: fetcher.data?.description?.toString(),
19
- title: fetcher.data?.title?.toString(),
20
- type: fetcher.data?.type?.toString(),
21
- });
22
- }
23
- }, [fetcher.data]);
24
- (0, react_2.useEffect)(() => {
25
- if (fetcher.state === "idle" && fetcher.data != null) {
26
- const receivedData = fetcher.data;
27
- if (receivedData) {
28
- setData({ data: receivedData[CATALOG_NAME], loading: false });
29
- }
30
- }
31
- }, [fetcher, CATALOG_NAME]);
32
- (0, react_2.useEffect)(() => {
33
- try {
34
- setData({ ...data, loading: true });
35
- // Convert otherParams to query string
36
- const paramsString = otherParams
37
- ? Object.entries(otherParams)
38
- .map(([key, value]) => `${key}=${value}`)
39
- .join("&")
40
- : "";
41
- const url = `/api/catalogs?catalog=${CATALOG_NAME}${paramsString ? `&${paramsString}` : ""}`;
42
- fetcher.load(url);
43
- }
44
- catch (ex) {
45
- (0, index_js_1.showAlert)({
46
- type: "error",
47
- title: `Ocurrió un error al cargar el catálogo: ${CATALOG_NAME}.`,
48
- description: "Error: " + ex,
49
- });
50
- }
51
- }, []);
52
- return data;
53
- }
54
- catch (ex) {
55
- (0, index_js_1.showAlert)({
56
- type: "error",
57
- title: `Ocurrió un error al cargar el catálogo: ${CATALOG_NAME}.`,
58
- description: "Error: " + ex,
59
- });
60
- return { data: [], loading: false };
61
- }
62
- };
63
9
  /**
64
10
  *
65
11
  * @param CATALOG_NAME
@@ -72,64 +18,174 @@ const useApiCatalog = (CATALOG_NAME, otherParams) => {
72
18
  includeDiscounts: "true",
73
19
  }
74
20
  */
75
- const useGetReduxCatalog = (CATALOG_NAME, { online = false, wheres = [], otherParams } = {}) => {
76
- const fetcher = (0, react_1.useFetcher)();
21
+ function useGetReduxCatalog(CATALOG_NAME, { online = false, wheres = [], otherParams } = {}) {
77
22
  const dispatch = (0, redux_1.useAppDispatch)();
23
+ const fetcher = (0, react_1.useFetcher)();
78
24
  const catalogData = (0, redux_1.useAppSelector)((state) => state.catalogs[CATALOG_NAME]);
25
+ // Verifica si ya tenemos algo en Redux
26
+ const hasLocalData = Boolean(catalogData?.data?.length);
79
27
  const [data, setData] = (0, react_2.useState)({
80
- data: catalogData?.data?.length ? catalogData.data : [],
81
- loading: catalogData.loading,
28
+ data: hasLocalData ? catalogData.data : [],
29
+ loading: false,
82
30
  });
83
- (0, react_2.useEffect)(() => {
84
- if (fetcher.data?.description) {
85
- (0, index_js_1.showAlert)({
86
- description: fetcher.data?.description?.toString(),
87
- title: fetcher.data?.title?.toString(),
88
- type: fetcher.data?.type?.toString(),
89
- });
90
- }
91
- }, [fetcher.data]);
92
- (0, react_2.useEffect)(() => {
93
- if (fetcher.state === "idle" && fetcher.data != null) {
94
- const receivedData = fetcher.data;
95
- if (receivedData) {
96
- setData({ data: receivedData[CATALOG_NAME], loading: false });
97
- dispatch((0, redux_1.catalogsFetchSuccess)({
98
- name: CATALOG_NAME,
99
- data: receivedData[CATALOG_NAME],
100
- }));
101
- }
102
- }
103
- }, [fetcher, dispatch, CATALOG_NAME]);
104
- (0, react_2.useEffect)(() => {
105
- if (catalogData?.data?.length <= 0 || catalogData?.reFetch || online) {
106
- try {
107
- setData({ ...data, loading: true });
31
+ try {
32
+ /**
33
+ * Efecto que decide si llamar o no a la API.
34
+ *
35
+ * Lógica:
36
+ * - Si `online: true`, forzamos el fetch.
37
+ * - Si `reFetch: true`, también forzamos el fetch.
38
+ * - Si `online: false` y SÍ tenemos data local, NO hacemos fetch (solo mostramos lo que hay).
39
+ * - Si `online: false` y NO hay data local, SÍ hacemos fetch (porque no hay nada que mostrar).
40
+ */
41
+ (0, react_2.useEffect)(() => {
42
+ const mustFetch = online || catalogData?.reFetch || !hasLocalData;
43
+ if (mustFetch) {
44
+ setData((prev) => ({ ...prev, loading: true }));
108
45
  dispatch((0, redux_1.catalogsFetchStart)(CATALOG_NAME));
109
- // Convierte cada elemento del array a una cadena codificada para URL
110
- const encodedWheres = wheres.map((where) => encodeURIComponent(where));
111
- // Une los elementos codificados con '&'
46
+ // Construimos el query para `wheres` y `otherParams`
47
+ const encodedWheres = (wheres || []).map((where) => encodeURIComponent(where));
112
48
  const wheresQueryParam = encodedWheres.join("&");
113
- // Convert otherParams to query string
114
49
  const paramsString = otherParams
115
50
  ? Object.entries(otherParams)
116
- .map(([key, value]) => `${key}=${value}`)
51
+ .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
117
52
  .join("&")
118
53
  : "";
119
- fetcher.load(`/api/catalogs?catalog=${CATALOG_NAME}&wheres=${wheresQueryParam}${paramsString ? `&${paramsString}` : ""}`);
54
+ const queryStringParts = [];
55
+ if (wheresQueryParam)
56
+ queryStringParts.push(`wheres=${wheresQueryParam}`);
57
+ if (paramsString)
58
+ queryStringParts.push(paramsString);
59
+ const queryString = queryStringParts.length
60
+ ? `&${queryStringParts.join("&")}`
61
+ : "";
62
+ // Disparamos la carga a través de fetcher
63
+ try {
64
+ fetcher.load(`/api/catalogs?catalog=${CATALOG_NAME}${queryString}`);
65
+ }
66
+ catch (error) {
67
+ console.error(error);
68
+ // Si hay datos locales, mostramos los datos locales
69
+ setData({
70
+ data: catalogData?.data || [],
71
+ loading: false,
72
+ });
73
+ (0, index_js_1.showAlert)({
74
+ type: "error",
75
+ title: "Error al cargar el catálogo",
76
+ description: `Error al cargar el catálogo ${CATALOG_NAME}, por favor intente nuevamente. Error: ${error}`,
77
+ });
78
+ }
120
79
  }
121
- catch (ex) {
122
- (0, index_js_1.showAlert)({
123
- type: "error",
124
- title: `Ocurrió un error al cargar el catálogo: ${CATALOG_NAME}.`,
125
- description: "Error: " + ex,
80
+ else {
81
+ // Si no vamos a hacer fetch, asegurarnos de que loading esté en false
82
+ // y mantener lo que ya tengamos en Redux
83
+ setData({
84
+ data: catalogData?.data || [],
85
+ loading: false,
126
86
  });
127
- setData({ ...data, loading: false });
128
87
  }
129
- }
130
- }, []);
88
+ // eslint-disable-next-line react-hooks/exhaustive-deps
89
+ }, [online, catalogData?.reFetch, hasLocalData]);
90
+ /**
91
+ * Efecto que observa la finalización del fetch (fetcher.state === "idle")
92
+ * y decide qué hacer con la data o error recibidos.
93
+ */
94
+ (0, react_2.useEffect)(() => {
95
+ // Cuando fetcher se pone en "idle", significa que ya terminó la petición.
96
+ if (fetcher.state === "idle") {
97
+ // Caso: tenemos algo en fetcher.data
98
+ if (fetcher.data) {
99
+ const possibleError = fetcher.data;
100
+ const possibleData = fetcher.data;
101
+ // Si es un error "clásico" con description, lo manejamos
102
+ if (possibleError?.description) {
103
+ // Aquí interpretamos que la API pudo haber respondido algo tipo { description, ... } => error
104
+ // Pero OJO: si ya teníamos datos locales, no mostramos error "fatal" para no romper el fallback
105
+ if (hasLocalData) {
106
+ // Ya tenemos datos en Redux, así que sólo mostramos el alert informativo,
107
+ // pero no borramos lo que hay en data
108
+ (0, index_js_1.showAlert)({
109
+ type: possibleError.type || "error",
110
+ title: possibleError.title || "Error",
111
+ description: possibleError.description,
112
+ });
113
+ // Marcamos loading false pero dejamos intacto `data.data`
114
+ setData((prev) => ({ ...prev, loading: false }));
115
+ }
116
+ else {
117
+ // No hay datos locales -> mostramos error y no tenemos fallback
118
+ (0, index_js_1.showAlert)({
119
+ type: "error",
120
+ title: possibleError.title || "Error",
121
+ description: possibleError.description,
122
+ });
123
+ setData((prev) => ({ ...prev, loading: false }));
124
+ }
125
+ }
126
+ else {
127
+ // Caso: la respuesta sí es data real
128
+ const newData = possibleData[CATALOG_NAME];
129
+ if (Array.isArray(newData)) {
130
+ // Guardamos en redux y en el state local
131
+ dispatch((0, redux_1.catalogsFetchSuccess)({
132
+ name: CATALOG_NAME,
133
+ data: newData,
134
+ }));
135
+ setData({
136
+ data: newData,
137
+ loading: false,
138
+ });
139
+ }
140
+ else {
141
+ // Por alguna razón no llegó el array esperado
142
+ // Revisamos si hay fallback local
143
+ if (hasLocalData) {
144
+ // No reportar error: usamos lo local
145
+ setData((prev) => ({ ...prev, loading: false }));
146
+ }
147
+ else {
148
+ // No hay nada local -> error
149
+ (0, index_js_1.showAlert)({
150
+ type: "error",
151
+ title: "Error al recibir el catálogo",
152
+ description: `No se obtuvo la propiedad "${CATALOG_NAME}" en la respuesta.`,
153
+ });
154
+ setData((prev) => ({ ...prev, loading: false }));
155
+ }
156
+ }
157
+ }
158
+ }
159
+ else {
160
+ // fetcher.state === "idle" pero fetcher.data es null/undefined => seguramente hubo error global
161
+ if (hasLocalData) {
162
+ // Fallback a datos locales
163
+ setData((prev) => ({ ...prev, loading: false }));
164
+ }
165
+ else {
166
+ // Ni API ni local data => error
167
+ (0, index_js_1.showAlert)({
168
+ type: "error",
169
+ title: "Error al cargar el catálogo",
170
+ description: `No se obtuvo respuesta y no hay datos locales para ${CATALOG_NAME}`,
171
+ });
172
+ setData((prev) => ({ ...prev, loading: false }));
173
+ }
174
+ }
175
+ }
176
+ // eslint-disable-next-line react-hooks/exhaustive-deps
177
+ }, [fetcher.state]);
178
+ }
179
+ catch (error) {
180
+ console.error(error);
181
+ (0, index_js_1.showAlert)({
182
+ type: "error",
183
+ title: "Error al cargar el catálogo",
184
+ description: `Error al cargar el catálogo ${CATALOG_NAME}, por favor intente nuevamente. Error: ${error}`,
185
+ });
186
+ }
131
187
  return data;
132
- };
188
+ }
133
189
  /**
134
190
  *
135
191
  * ======================= HOOKS
@@ -260,9 +316,12 @@ const useGetCaseForms = (config) => {
260
316
  };
261
317
  };
262
318
  exports.useGetCaseForms = useGetCaseForms;
263
- const useGetInvoiceFormSubmissionsByAgencyId = (agency_id) => {
264
- const data = useApiCatalog("invoiceFormSubmissionsByAgencyId", {
265
- agency_id: `${agency_id}`,
319
+ const useGetInvoiceFormSubmissionsByAgencyId = (config) => {
320
+ const agencyId = config?.otherParams?.agency_id;
321
+ const data = useGetReduxCatalog("invoiceFormSubmissionsByAgencyId", {
322
+ otherParams: {
323
+ agency_id: `${agencyId}`,
324
+ },
266
325
  });
267
326
  // Filtrar los registros para obtener sólo los de la versión más alta.
268
327
  const groupedByVersion = (data.data || []).reduce((acc, record) => {
@@ -299,9 +358,11 @@ exports.useGetMyCaseFormSubmissions = useGetMyCaseFormSubmissions;
299
358
  const useGetInvoiceFormSubmissionsByInvoiceId = (config) => {
300
359
  const invoiceId = config?.otherParams?.invoiceId;
301
360
  const withFiles = config?.otherParams?.withFiles;
302
- const data = useApiCatalog("invoiceFormSubmissionsByInvoiceId", {
303
- invoiceId: `${invoiceId}`,
304
- withFiles: `${withFiles}`,
361
+ const data = useGetReduxCatalog("invoiceFormSubmissionsByInvoiceId", {
362
+ otherParams: {
363
+ invoiceId: `${invoiceId}`,
364
+ withFiles: `${withFiles}`,
365
+ },
305
366
  });
306
367
  // Filtrar los registros para obtener sólo los de la versión más alta.
307
368
  const groupedByVersion = (data.data || []).reduce((acc, record) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zauru-sdk/hooks",
3
- "version": "2.0.116",
3
+ "version": "2.0.120",
4
4
  "description": "Hooks reutilizables dentro de las webapps de Zauru.",
5
5
  "main": "./dist/esm/index.js",
6
6
  "module": "./dist/esm/index.js",
@@ -26,12 +26,12 @@
26
26
  },
27
27
  "dependencies": {
28
28
  "@remix-run/react": "^2.8.1",
29
- "@zauru-sdk/common": "^2.0.109",
29
+ "@zauru-sdk/common": "^2.0.118",
30
30
  "@zauru-sdk/icons": "^2.0.99",
31
- "@zauru-sdk/redux": "^2.0.109",
31
+ "@zauru-sdk/redux": "^2.0.120",
32
32
  "@zauru-sdk/types": "^2.0.109",
33
33
  "react": "^18.2.0",
34
34
  "react-dom": "^18.2.0"
35
35
  },
36
- "gitHead": "d62b6a5c42658f4e9e3fb95822535cb6b8017157"
36
+ "gitHead": "05212e4cb104943ac0c6050ada75859622537c6a"
37
37
  }