浏览代码

Edicion condicionantes

OscarGil03 11 月之前
父节点
当前提交
eea4198cc9
共有 2 个文件被更改,包括 130 次插入105 次删除
  1. 48 26
      src/views/condicionantes/CondicionanteDetalle.jsx
  2. 82 79
      src/views/condicionantes/Condicionantes.jsx

+ 48 - 26
src/views/condicionantes/CondicionanteDetalle.jsx

@@ -1,5 +1,5 @@
 import { Form, Input, Button, Spin, Row, Col, Switch, Select as AntdSelect, Checkbox, notification, Typography, Modal, Divider } from 'antd';
-import { useEffect, useMemo, useState } from 'react';
+import { useEffect, useMemo, useState, useCallback } from 'react';
 import HttpService from '../../services/httpService';
 import { respuestas } from '../../utilities';
 import { useNavigate } from 'react-router-dom';
@@ -52,6 +52,7 @@ const CondicionanteDetalle = () => {
   const [selectedOrigenes, setSelectedOrigenes] = useState([]);
   const [selectedDestinos, setSelectedDestinos] = useState([]);
   const [isModalVisible, setIsModalVisible] = useState(false);
+  const [catalogLoaded, setCatalogLoaded] = useState(false);
 
   const requestParams = useMemo(() => ({
     name: endpoints.condicionante,
@@ -60,6 +61,16 @@ const CondicionanteDetalle = () => {
   }), [id]);
 
   const { model, modelLoading } = useModel(request);
+  const fetchSubproductos = useCallback(async (productoId) => {
+    try {
+      const response = await HttpService.get(`producto?idPadre=${productoId}`);
+      if (response?.status === 200) {
+        setSubproductos(response.resultado || []);
+      }
+    } catch (error) {
+      console.error("Error fetching subproductos:", error);
+    }
+  }, []);
 
   useEffect(() => {
     if (id) {
@@ -75,6 +86,7 @@ const CondicionanteDetalle = () => {
       let parsedSubproductos = [];
       try {
         parsedSubproductos = JSON.parse(model.subproductos) || [];
+        console.log(parsedSubproductos);
       } catch (e) {
         console.error("Error parsing subproductos:", e);
       }
@@ -93,36 +105,44 @@ const CondicionanteDetalle = () => {
       setSelectedTipos(model.condicionanteTipo.map(tipo => tipo.idTipo));
       setSelectedOrigenes(model.condicionanteOrigen.map(origen => origen.idOrigen));
       setSelectedDestinos(model.condicionanteDestino.map(destino => destino.idDestino));
+      if (model.idProducto) {
+        fetchSubproductos(model.idProducto);
+      }
     }
-  }, [form, model]);
+  }, [form, model, fetchSubproductos]);
 
   useEffect(() => {
-    const fetchCatalogData = async () => {
-      try {
-        const finesResponse = await HttpService.get(`${endpoints.fines}`);
-        const tiposResponse = await HttpService.get(`${endpoints.tipos}`);
-        const estadosResponse = await HttpService.get(`${endpoints.estados}`);
+    if (!catalogLoaded) {
+      const fetchCatalogData = async () => {
+        try {
+          const [finesResponse, tiposResponse, estadosResponse] = await Promise.all([
+            HttpService.get(`${endpoints.fines}`),
+            HttpService.get(`${endpoints.tipos}`),
+            HttpService.get(`${endpoints.estados}`)
+          ]);
 
-        if (finesResponse?.status === 200) {
-          setFines(finesResponse?.resultado || []);
+          if (finesResponse?.status === 200) {
+            setFines(finesResponse?.resultado || []);
+          }
+          if (tiposResponse?.status === 200) {
+            setTipos(tiposResponse?.resultado || []);
+          }
+          if (estadosResponse?.status === 200) {
+            setEstados(estadosResponse?.resultado || []);
+          }
+          setCatalogLoaded(true);
+        } catch (error) {
+          console.error(error);
+          notification.error({
+            message: "Error",
+            description: "No se pudieron cargar los datos del catálogo.",
+          });
         }
-        if (tiposResponse?.status === 200) {
-          setTipos(tiposResponse?.resultado || []);
-        }
-        if (estadosResponse?.status === 200) {
-          setEstados(estadosResponse?.resultado || []);
-        }
-      } catch (error) {
-        console.error(error);
-        notification.error({
-          message: "Error",
-          description: "No se pudieron cargar los datos del catálogo.",
-        });
-      }
-    };
+      };
 
-    fetchCatalogData();
-  }, []);
+      fetchCatalogData();
+    }
+  }, [catalogLoaded]);
 
   const onFinish = async (values) => {
     try {
@@ -168,6 +188,7 @@ const CondicionanteDetalle = () => {
     return <Spin size="large" style={{ display: "block", margin: "auto", marginTop: "50px" }} />;
   }
 
+  console.log(subproductos);
   return (
     <DefaultLayout>
       <Form layout="vertical" name="basic" form={form} onFinish={onFinish} onFinishFailed={() => { }}>
@@ -276,9 +297,10 @@ const CondicionanteDetalle = () => {
                 valueProp="id"
                 append={[model?.producto]}
                 extraParams={{ padre: true }}
-                onChange={(_, item) => {
+                onChange={async (_, item) => {
                   setSubproductos(item?.subproductos || []);
                   setSelectedSubproductos(form.getFieldValue('subproductos'));
+                  console.log(item)
                 }}
               />
             </Form.Item>

+ 82 - 79
src/views/condicionantes/Condicionantes.jsx

@@ -1,4 +1,4 @@
-import { useRef, useState } from "react";
+import { useRef, useState, useCallback, useMemo } from "react";
 import { Form, Modal, Tooltip, notification } from "antd";
 import { DeleteOutlined, PlusOutlined } from "@ant-design/icons";
 import { Tabla } from "../../components";
@@ -17,38 +17,25 @@ const Condicionantes = () => {
   const [form] = Form.useForm();
   const [buscarParams, setBuscarParams] = useState({});
 
-  const onFinish = (values) => {
+  const onFinish = useCallback((values) => {
     const { q } = values;
     const params = {
       q: q ?? "",
       padre: true,
     };
     setBuscarParams(params);    
-  };
+  }, []);
 
-  const botones = [
+  const botones = useMemo(() => [
     {
       onClick: () => navigate(`/condicionantes/agregar`),
       props: { disabled: false, type: "primary", block: false },
       text: "Nuevo",
       icon: <PlusOutlined />,
     },
-  ];
+  ], [navigate]);
 
-  const linkText = (value, row, key) => (
-    <Link
-      to={`/condicionantes/editar?id=${row.id}`}
-      style={{ color: "black" }}
-    >
-      {isEllipsis(columns, key) ? (
-        <Tooltip title={value}>{value}</Tooltip>
-      ) : (
-        value
-      )}
-    </Link>
-  );
-
-  const eliminarRegistro = (nombre, id, url, alTerminar) => {
+  const eliminarRegistro = useCallback((nombre, id, url, alTerminar) => {
     if (!id) return;
     Modal.confirm({
       title: "Eliminar",
@@ -89,67 +76,82 @@ const Condicionantes = () => {
         }
       },
     });
-  };
+  }, []);
 
-  const columns = [
-    {
-      title: "Acciones",
-      key: "id",
-      dataIndex: "id",
-      width: 100,
-      align: "center",
-      render: (_, item) => (
-        <ActionsButton
-          data={[
-            {
-              label: "Editar",
-              onClick: () =>
-                navigate(`/condicionantes/editar?id=${item?.id}`),
-            },
-            {
-              label: "Eliminar",
-              onClick: () => {
-                eliminarRegistro(item?.titulo, item?.id, endPoint+'/eliminar', () =>
-                  tablaRef?.current?.refresh()
-                );
+  const columns = useMemo(() => {
+    const linkText = (value, row, key) => (
+      <Link
+        to={`/condicionantes/editar?id=${row.id}`}
+        style={{ color: "black" }}
+      >
+        {isEllipsis(columns, key) ? (
+          <Tooltip title={value}>{value}</Tooltip>
+        ) : (
+          value
+        )}
+      </Link>
+    );
+
+    return [
+      {
+        title: "Acciones",
+        key: "id",
+        dataIndex: "id",
+        width: 100,
+        align: "center",
+        render: (_, item) => (
+          <ActionsButton
+            data={[
+              {
+                label: "Editar",
+                onClick: () =>
+                  navigate(`/condicionantes/editar?id=${item?.id}`),
               },
-              danger: true,
-            },
-          ]}
-        />
-      ),
-    },
-    {
-      title: "Título",
-      key: "titulo",
-      dataIndex: "titulo",
-      render: linkText,
-    },
-    {
-      title: "Descripción",
-      key: "descripcion",
-      dataIndex: "descripcion",
-      render: linkText,
-    },
-    {
-      title: "Activa",
-      key: "activa",
-      dataIndex: "activa",
-      render: linkText,
-    },
-    {
-      title: "Editado por",
-      key: "editadoPor",
-      dataIndex: "editadoPor",
-      render: linkText,
-    },
-    {
-      title: "Fecha de Edición",
-      key: "fechaEdicion",
-      dataIndex: "fechaEdicion",
-      render: linkText,
-    }
-  ];
+              {
+                label: "Eliminar",
+                onClick: () => {
+                  eliminarRegistro(item?.titulo, item?.id, endPoint + '/eliminar', () =>
+                    tablaRef?.current?.refresh()
+                  );
+                },
+                danger: true,
+              },
+            ]}
+          />
+        ),
+      },
+      {
+        title: "Título",
+        key: "titulo",
+        dataIndex: "titulo",
+        render: linkText,
+      },
+      {
+        title: "Descripción",
+        key: "descripcion",
+        dataIndex: "descripcion",
+        render: linkText,
+      },
+      {
+        title: "Activa",
+        key: "activa",
+        dataIndex: "activa",
+        render: linkText,
+      },
+      {
+        title: "Editado por",
+        key: "editadoPor",
+        dataIndex: "editadoPor",
+        render: linkText,
+      },
+      {
+        title: "Fecha de Edición",
+        key: "fechaEdicion",
+        dataIndex: "fechaEdicion",
+        render: linkText,
+      }
+    ];
+  }, [eliminarRegistro, navigate]);
 
   return (
     <SimpleTableLayout
@@ -159,13 +161,14 @@ const Condicionantes = () => {
     >
       <Formulario
         form={form}
-        onFinish={onFinish} 
+        onFinish={onFinish}
       />
       <Tabla
         columns={columns}
         nameURL={endPoint}
         extraParams={buscarParams}
         scroll={{ x: "30vw" }}
+        ref={tablaRef}
       />
     </SimpleTableLayout>
   );