parent
747f5a2f4a
commit
784f2ae26c
@ -0,0 +1,490 @@ |
||||
import React, { FC, useEffect, useState } from 'react' |
||||
import { Button, Card, Col, Form, Modal, Row } from 'react-bootstrap' |
||||
import { IconContext } from 'react-icons' |
||||
import ICatFraccionesVulnerables from '../../../Interfaces/Catalogos/ICatFraccionesVulnerables' |
||||
import FraccionesVulnerables from '../../../Services/Catalogos/FraccionesVulnerables' |
||||
import { useDispatch, useSelector } from 'react-redux' |
||||
// import { RootState } from '../../../store/store';
|
||||
import { BsFileEarmarkExcel, BsFillPencilFill, BsSearch } from 'react-icons/bs' |
||||
import DataTable from 'react-data-table-component' |
||||
import * as XLSX from 'xlsx' |
||||
import { FaEraser } from 'react-icons/fa' |
||||
// import * as CurrencyFormat from 'react-currency-format';
|
||||
// import { addCatFraccionesVulnerables, deleteCatFraccionesVulnerables } from '../../../store/features/CatFraccionesVulnerables/CatFraccionesVulnerablesSlice';
|
||||
// import { MsgInformativo } from '../../Utils/Toast/msgInformativo';
|
||||
// import { data } from 'cypress/types/jquery';
|
||||
import { FormControl } from 'react-bootstrap' |
||||
import { AiFillCloseCircle } from 'react-icons/ai' |
||||
import { AiOutlineSave } from 'react-icons/ai' |
||||
// import { Console } from 'console';
|
||||
// import { NewLineKind } from 'typescript';
|
||||
|
||||
// Define types for the component props and table row data
|
||||
interface IProps {} |
||||
|
||||
export default function CatFraccionesVulnerables(props: IProps) { |
||||
const [UserType, setUserType] = useState(() => { |
||||
const stickyValue = window.localStorage.getItem('UserType') |
||||
return stickyValue !== null ? JSON.parse(stickyValue) : '' |
||||
}) |
||||
const dispatch = useDispatch() |
||||
const [Data, setData] = useState<ICatFraccionesVulnerables[]>([]) |
||||
// const [filteredData, setFilteredData] = useState<ICatFraccionesVulnerables[]>([]);
|
||||
// const [DoneColor, setDoneColor] = useState('#CCD1D1')
|
||||
const [tipoReporte, setTipoReporte] = useState(0) |
||||
// const [filtro, setFiltro] = useState('')
|
||||
const [DataOriginal, setDataOriginal] = useState<ICatFraccionesVulnerables[]>( |
||||
[] |
||||
) |
||||
// const mFraccionesVulnerables = useSelector((state: RootState) => state.CatFraccionesVulnerables.CatFraccionesVulnerables);
|
||||
const [header, setHeader] = useState<string>('') // Specify the type of 'header'
|
||||
// const [msgColor, setMsgColor] = useState<string>('primary'); // Specify the type of 'msgColor'
|
||||
const [show, setShowMsg] = useState<boolean>(false) // Specify the type of 'show'
|
||||
const [msg, setMsg] = useState<string>('') // Specify the type of 'msg'
|
||||
// const [msgDialog, setMsgDialog] = useState<boolean>(false); // Specify the type of 'msgDialog'
|
||||
const [id, setId] = useState<number>(0) // Specify the type of 'id'
|
||||
const [Fraccion, setFraccion] = useState<number>(0) // Specify the type of 'Fraccion'
|
||||
const [Nico, setNico] = useState<string>('') // Specify the type of 'Nico'
|
||||
const [Activo, setActivo] = useState<number>(0) // Specify the type of 'Activo'
|
||||
// const [CurrentTime2Number, setCurrentTime2Number] = useState(0)
|
||||
const [showModal, setShowModal] = useState<boolean>(false) |
||||
const [editMode, setEditMode] = useState(false) // Nuevo estado para controlar el modo de edición
|
||||
const [selectedRow, setSelectedRow] = |
||||
useState<ICatFraccionesVulnerables | null>(null) // Nuevo estado para almacenar la fila seleccionada
|
||||
// const [fraccionesVulnerables, setFraccionesVulnerables] = useState([]);
|
||||
const [modalFileManager, setModalFileManager] = useState(false) |
||||
// const [modalFileManagerCorresponsal, setModalFileManagerCorresponsal] =
|
||||
// useState(false)
|
||||
|
||||
const columnsFraccionesVulnerables = [ |
||||
{ |
||||
name: 'Id', |
||||
width: '14%', |
||||
selector: (row: ICatFraccionesVulnerables) => row.id, |
||||
sortable: true |
||||
}, |
||||
{ |
||||
name: 'Fraccion', |
||||
width: '20%', |
||||
|
||||
selector: (row: ICatFraccionesVulnerables) => row.fraccion, |
||||
sortable: true |
||||
}, |
||||
{ |
||||
name: 'Nico', |
||||
width: '15%', |
||||
|
||||
selector: (row: ICatFraccionesVulnerables) => row.nico, |
||||
sortable: true |
||||
}, |
||||
{ |
||||
name: 'Activo', |
||||
width: '15%', |
||||
selector: (row: ICatFraccionesVulnerables) => |
||||
row.activo === 1 ? 'Sí' : 'No', |
||||
sortable: true |
||||
}, |
||||
{ |
||||
name: 'Edita', |
||||
width: '15%', |
||||
|
||||
cell: (row: ICatFraccionesVulnerables) => ( |
||||
<Button |
||||
size="sm" |
||||
variant="light" |
||||
style={{ |
||||
textAlign: 'right', |
||||
visibility: UserType === '4' ? 'hidden' : 'visible' |
||||
}} |
||||
onClick={() => loadRow(row)} // Cambia esta línea para pasar el objeto 'row' a la función 'loadRow'
|
||||
> |
||||
<IconContext.Provider value={{ color: 'blue', size: '20px' }}> |
||||
<BsFillPencilFill /> |
||||
</IconContext.Provider>{' '} |
||||
</Button> |
||||
) |
||||
}, |
||||
{ |
||||
name: 'Elimina', |
||||
width: '15%', |
||||
cell: (row: ICatFraccionesVulnerables) => ( |
||||
<Button |
||||
size="sm" |
||||
variant="light" |
||||
style={{ |
||||
textAlign: 'right', |
||||
visibility: UserType === '4' ? 'hidden' : 'visible' |
||||
}} |
||||
onClick={() => deleteRow(row.id)} // Llama a la función deleteRow pasando el ID de la fila
|
||||
> |
||||
<IconContext.Provider value={{ color: 'red', size: '20px' }}> |
||||
<AiFillCloseCircle /> |
||||
</IconContext.Provider>{' '} |
||||
</Button> |
||||
) |
||||
} |
||||
] |
||||
|
||||
const loadRow = (data: ICatFraccionesVulnerables): void => { |
||||
setSelectedRow(data) // Al hacer clic en el botón de edición, establecemos la fila seleccionada en el estado
|
||||
setEditMode(true) // Cambiamos a modo de edición
|
||||
setId(data.id) // Establecemos el id de la fila seleccionada
|
||||
setFraccion(data.fraccion) // Cargamos los valores de fracción y nico para edición
|
||||
setNico(data.nico) |
||||
} |
||||
|
||||
const generaReporte = () => { |
||||
setTipoReporte(0) |
||||
FraccionesVulnerables.getAll() |
||||
.then((response) => { |
||||
setData(response.data) |
||||
setDataOriginal(response.data) |
||||
// uploadAllRows(response.data)
|
||||
}) |
||||
.catch((e: Error) => { |
||||
setHeader('Error') |
||||
setMsg('Ocurrio un error: ' + e) |
||||
setShowMsg(true) |
||||
return |
||||
}) |
||||
} |
||||
|
||||
const uploadAllRows = (data: ICatFraccionesVulnerables[]) => { |
||||
// Iteramos sobre los datos y realizamos la petición para cada fila
|
||||
data.forEach((row) => { |
||||
uploadFile(row) |
||||
}) |
||||
} |
||||
|
||||
useEffect(() => { |
||||
// console.log(id) // Esto imprimirá el valor actualizado de id después de que cambie
|
||||
}, [id]) |
||||
|
||||
const handleCreateNewRecord = () => { |
||||
// console.log('se han borrod los texbox ')
|
||||
|
||||
setSelectedRow(null) |
||||
setFraccion(0) |
||||
setNico('') |
||||
setActivo(0) // Establecer a 0 (No)
|
||||
setEditMode(true) |
||||
setId(0) |
||||
setShowModal(false) |
||||
} |
||||
|
||||
function deleteRow(id: number): void { |
||||
FraccionesVulnerables.Delete(id) |
||||
.then((response) => { |
||||
// Una vez que obtengas la respuesta exitosa del servidor, puedes actualizar la tabla para reflejar el cambio.
|
||||
// Podrías eliminar la fila directamente o marcarla como desactivada según tus necesidades.
|
||||
|
||||
// Por ejemplo, supongamos que en tu objeto ICatFraccionesVulnerables tienes una propiedad 'activo' que indica si la fila está activa o no.
|
||||
// Podrías marcarla como desactivada al recibir la respuesta del servidor.
|
||||
setData((prevData) => |
||||
prevData.map((item) => |
||||
item.id === id ? { ...item, activo: 0 } : item |
||||
) |
||||
) |
||||
|
||||
console.log(response.data) |
||||
}) |
||||
.catch((e: Error) => { |
||||
setHeader('Error') |
||||
setMsg('Ocurrió un error: ' + e) |
||||
|
||||
return |
||||
}) |
||||
} |
||||
|
||||
const uploadFile = (data: ICatFraccionesVulnerables): Promise<any> => { |
||||
return new Promise((resolve, reject) => { |
||||
FraccionesVulnerables.Append(data) |
||||
.then((response) => { |
||||
// console.log(response.data) // Mensaje de éxito
|
||||
resolve(response.data) |
||||
}) |
||||
.catch((e: Error) => { |
||||
console.error('Error durante la inserción:', e) // Mensaje de error
|
||||
reject(e) |
||||
}) |
||||
}) |
||||
} |
||||
|
||||
const handleSaveChanges = async () => { |
||||
if (id === 0) { |
||||
if (Nico.length > 2) { |
||||
console.log( |
||||
'El valor de Nico tiene más de 2 caracteres. No se actualizará la tabla ni se realizará la petición uploadFile.' |
||||
) |
||||
return |
||||
} |
||||
|
||||
const newRecord = { |
||||
id: id, |
||||
fraccion: Fraccion, |
||||
nico: Nico, |
||||
activo: Activo |
||||
} |
||||
|
||||
try { |
||||
const response = await uploadFile(newRecord) |
||||
const newId = response.id // Asegúrate de usar el nombre correcto para el nuevo ID
|
||||
|
||||
// Actualizar el estado local con el nuevo registro que incluye el nuevo ID
|
||||
const updatedRecord = { ...newRecord, id: newId } |
||||
setData((prevData) => [...prevData, updatedRecord]) |
||||
|
||||
// console.log('este el newId' + newId)
|
||||
// console.log('este el id normal ' + id)
|
||||
|
||||
// Restablecer valores de los campos
|
||||
setFraccion(0) |
||||
setNico('') |
||||
setActivo(1) |
||||
setEditMode(false) |
||||
setShowModal(false) |
||||
} catch (error) { |
||||
console.error('Error durante la inserción:', error) |
||||
} |
||||
} else { |
||||
// Aquí actualizamos el registro existente
|
||||
|
||||
if (Nico.length > 2) { |
||||
console.log( |
||||
'El valor de Nico tiene más de 2 caracteres. No se actualizará la tabla ni se realizará la petición uploadFile.' |
||||
) |
||||
return // Sale de la función sin hacer nada más
|
||||
} |
||||
const updatedData = Data.map((row) => |
||||
row.id === selectedRow?.id |
||||
? { ...row, fraccion: Fraccion, nico: Nico, activo: Activo } |
||||
: row |
||||
) |
||||
setData(updatedData) |
||||
const updatedRow = updatedData.find((row) => row.id === selectedRow?.id) |
||||
if (updatedRow) { |
||||
uploadFile(updatedRow) // Llamada a uploadFile para actualizar el registro
|
||||
} |
||||
setEditMode(false) |
||||
setShowModal(false) |
||||
} |
||||
} |
||||
|
||||
const downloadExcel = () => { |
||||
exportExcel(Data, 'Fracciones Vulnerables') |
||||
} |
||||
|
||||
function exportExcel( |
||||
jsonData: ICatFraccionesVulnerables[], |
||||
fileName: string |
||||
): void { |
||||
let Heading = [['Id', 'Fraccion', 'Nico', 'Activo']] |
||||
const wb = XLSX.utils.book_new() |
||||
const ws: XLSX.WorkSheet = XLSX.utils.json_to_sheet([]) |
||||
XLSX.utils.sheet_add_aoa(ws, Heading) |
||||
XLSX.utils.sheet_add_json(ws, jsonData, { origin: 'A2', skipHeader: true }) |
||||
XLSX.utils.book_append_sheet(wb, ws, 'Sheet1') |
||||
XLSX.writeFile(wb, fileName + '.xlsx') |
||||
var range = XLSX.utils.decode_range(ws['!ref?']) |
||||
for (var C = range.s.c; C <= range.e.c; ++C) { |
||||
var address = XLSX.utils.encode_col(C) + '1' // <-- first row, column number C
|
||||
if (!ws[address]) continue |
||||
ws[address].v = ws[address].v.toUpperCase() |
||||
} |
||||
} |
||||
|
||||
// Función para manejar el cambio en el campo de entrada de la fracción
|
||||
const handleFraccionChange = (e: React.ChangeEvent<HTMLInputElement>) => { |
||||
const value = parseFloat(e.target.value) |
||||
setFraccion(isNaN(value) ? 0 : value) |
||||
} |
||||
|
||||
return ( |
||||
<div className="mt-2"> |
||||
<Card> |
||||
<Card.Body> |
||||
<div className="container"> |
||||
<div |
||||
className="row mb-4 " |
||||
style={{ |
||||
display: 'flex', |
||||
justifyContent: 'center', |
||||
alignItems: 'center', |
||||
minHeight: '1vh' |
||||
}} |
||||
> |
||||
<Card |
||||
style={{ |
||||
paddingTop: '10px', |
||||
paddingBottom: '5px', |
||||
width: '900px', |
||||
height: '50px' |
||||
}} |
||||
> |
||||
<Row> |
||||
<Col xs={12}></Col> |
||||
<Col xs={12}> |
||||
<Row className="align-items-center"> |
||||
<Col xs={1}> |
||||
<Form.Label className="mb-0">Fracción</Form.Label> |
||||
</Col> |
||||
<Col xs={1}> |
||||
<FormControl |
||||
type="text" |
||||
value={Fraccion} |
||||
onChange={handleFraccionChange} |
||||
inputMode="numeric" |
||||
className="orm-select mx-2" |
||||
maxLength={8} |
||||
style={{ |
||||
backgroundColor: 'white', |
||||
color: 'black', |
||||
padding: '4px', |
||||
width: '80px', |
||||
height: '30px' |
||||
}} |
||||
/> |
||||
</Col> |
||||
<Col |
||||
xs={1} |
||||
style={{ textAlign: 'right', width: '100px' }} |
||||
> |
||||
<Form.Label className="mb-0 ">Nico</Form.Label> |
||||
</Col> |
||||
<Col xs={1}> |
||||
<FormControl |
||||
type="text" |
||||
value={Nico} |
||||
onChange={(e) => setNico(e.target.value)} |
||||
className="orm-select mx-2" |
||||
maxLength={2} |
||||
style={{ |
||||
backgroundColor: 'white', |
||||
color: 'black', |
||||
padding: '4px', |
||||
width: '30px', |
||||
height: '30px' |
||||
}} |
||||
/> |
||||
</Col> |
||||
<Col xs={2} style={{ textAlign: 'right', width: '50px' }}> |
||||
<Form.Label className="mb-0">Activo</Form.Label> |
||||
</Col> |
||||
<Col xs={2}> |
||||
<Form.Select |
||||
value={Activo} |
||||
onChange={(e) => setActivo(Number(e.target.value))} |
||||
className="form-select mx-2" |
||||
style={{ |
||||
backgroundColor: 'white', |
||||
color: 'black', |
||||
padding: '4px', |
||||
width: '60px', |
||||
height: '30px' |
||||
}} |
||||
> |
||||
<option value={1}>Si</option> |
||||
<option value={0}>No</option> |
||||
</Form.Select> |
||||
</Col> |
||||
<Col xs={0} style={{ width: '100px' }}> |
||||
<Button |
||||
size="sm" |
||||
variant="light" |
||||
onClick={handleCreateNewRecord} |
||||
style={{ |
||||
backgroundColor: 'orange', |
||||
color: 'white', |
||||
padding: '4px', |
||||
width: '50px', |
||||
height: '32px' |
||||
}} |
||||
> |
||||
<FaEraser /> |
||||
</Button> |
||||
</Col> |
||||
|
||||
<Col xs={0} style={{ width: '110px' }}> |
||||
<Button |
||||
style={{ |
||||
backgroundColor: 'blue', |
||||
color: 'white', |
||||
padding: '2px', |
||||
width: '55px', |
||||
height: '30px' |
||||
}} |
||||
variant="primary" |
||||
size="sm" |
||||
onClick={() => { |
||||
generaReporte() |
||||
}} |
||||
> |
||||
<BsSearch /> |
||||
</Button> |
||||
</Col> |
||||
<Col xs={0} style={{ width: '110px' }}> |
||||
<Button |
||||
style={{ |
||||
backgroundColor: 'blue', |
||||
color: 'white', |
||||
padding: '0px', |
||||
width: '55px', |
||||
height: '30px' |
||||
}} |
||||
variant="primary" |
||||
onClick={handleSaveChanges} |
||||
> |
||||
<AiOutlineSave /> |
||||
</Button> |
||||
</Col> |
||||
<Col xs={0} style={{ width: '110px' }}> |
||||
<Button |
||||
size="sm" |
||||
variant="success" |
||||
onClick={() => { |
||||
downloadExcel() |
||||
}} |
||||
style={{ |
||||
backgroundColor: 'green', |
||||
color: 'white', |
||||
padding: '1px', |
||||
width: '55px', |
||||
height: '30px' |
||||
}} |
||||
> |
||||
<BsFileEarmarkExcel /> |
||||
</Button> |
||||
</Col> |
||||
</Row> |
||||
</Col> |
||||
<Col xs={1}></Col> |
||||
</Row> |
||||
</Card> |
||||
</div> |
||||
<Row> |
||||
<Col xs={3}></Col> |
||||
<Col xs={6}> |
||||
<Card> |
||||
<DataTable |
||||
noHeader |
||||
defaultSortFieldId={'id'} |
||||
defaultSortAsc={true} |
||||
striped={true} |
||||
dense={true} |
||||
paginationPerPage={10} |
||||
pagination |
||||
highlightOnHover |
||||
columns={columnsFraccionesVulnerables} |
||||
data={Data} |
||||
pointerOnHover |
||||
/> |
||||
</Card> |
||||
</Col> |
||||
<Col xs={1}></Col> |
||||
</Row> |
||||
</div> |
||||
</Card.Body> |
||||
</Card> |
||||
</div> |
||||
) |
||||
} |
@ -0,0 +1,6 @@ |
||||
export default interface ICatFraccionesVulnerables{ |
||||
id : number ,
|
||||
fraccion : number,
|
||||
nico : string,
|
||||
activo : number |
||||
} |
@ -0,0 +1,27 @@ |
||||
import http from "../common/http-common"; |
||||
import ICatFraccionesVulnerables from '../../Interfaces/Catalogos/ICatFraccionesVulnerables' |
||||
|
||||
|
||||
|
||||
class FraccionesVulnerablesDataService { |
||||
|
||||
|
||||
constructor() |
||||
{ |
||||
type returnData = [ICatFraccionesVulnerables[]] |
||||
} |
||||
|
||||
getAll() { |
||||
return http.get<ICatFraccionesVulnerables[]>(`/Catalogos/CatFraccionesVulnerables/getAll`); |
||||
} |
||||
|
||||
Append(data: ICatFraccionesVulnerables) { |
||||
return http.post<ICatFraccionesVulnerables>(`/Catalogos/CatFraccionesVulnerables/Append`, data); |
||||
} |
||||
Delete(id: number) { |
||||
return http.delete<ICatFraccionesVulnerables>(`/Catalogos/CatFraccionesVulnerables/Delete/${id}`); |
||||
} |
||||
|
||||
|
||||
} |
||||
export default new FraccionesVulnerablesDataService(); |
@ -0,0 +1,42 @@ |
||||
import { createSlice, PayloadAction } from '@reduxjs/toolkit' |
||||
import ICatFraccionesVulnerables from '../../../Interfaces/Catalogos/ICatFraccionesVulnerables'; |
||||
const CatFraccionesVulnerables: ICatFraccionesVulnerables[] = [{id:0, fraccion:0 , nico:'' , activo:0 }] |
||||
const initialState = { CatFraccionesVulnerables } |
||||
|
||||
export const CatFraccionesVulnerablesSlice = createSlice({ |
||||
name: 'CatCorresponsales', |
||||
initialState: initialState, |
||||
reducers: { |
||||
populateCatFraccionesVulnerables : (state, action: PayloadAction<ICatFraccionesVulnerables[]>) => { |
||||
state.CatFraccionesVulnerables = [] |
||||
state.CatFraccionesVulnerables.push(... action.payload) |
||||
}, |
||||
addCatFraccionesVulnerables : (state, action: PayloadAction<ICatFraccionesVulnerables>) => { |
||||
var Existe = state.CatFraccionesVulnerables.find(function(item) { |
||||
return item.id === action.payload.id; |
||||
}); |
||||
if (!Existe) state.CatFraccionesVulnerables.push(action.payload) |
||||
}, |
||||
updateCatFraccionesVulnerables : (state, action: PayloadAction<ICatFraccionesVulnerables>) => { |
||||
const i = state.CatFraccionesVulnerables.findIndex(_element => _element.id === action.payload.id); |
||||
if (i > -1) state.CatFraccionesVulnerables[i] = action.payload; |
||||
else state.CatFraccionesVulnerables.push(action.payload); |
||||
|
||||
}, |
||||
deleteCatFraccionesVulnerables : (state, action: PayloadAction<number>) => { |
||||
const newArr = state.CatFraccionesVulnerables.filter(data => data.id != action.payload); |
||||
state.CatFraccionesVulnerables=newArr |
||||
}, |
||||
InitCatFraccionesVulnerables : (state, action: PayloadAction<number>) => { |
||||
state.CatFraccionesVulnerables.splice(0,state.CatFraccionesVulnerables.length-1) |
||||
// state.CatCorresponsales = [{id:0, factura:'-Seleccione-', idTrafico:0, valorFacturaDls:0, proveedor:0}]
|
||||
}, |
||||
}, |
||||
}) |
||||
|
||||
export const { addCatFraccionesVulnerables,
|
||||
populateCatFraccionesVulnerables,
|
||||
updateCatFraccionesVulnerables,
|
||||
deleteCatFraccionesVulnerables, |
||||
InitCatFraccionesVulnerables } = CatFraccionesVulnerablesSlice.actions; |
||||
export default CatFraccionesVulnerablesSlice.reducer; |
Loading…
Reference in new issue