453 lines
15 KiB
Plaintext
453 lines
15 KiB
Plaintext
import { Button, ButtonGroup, Stack } from '@mui/material';
|
|
import Box from '@mui/material/Box';
|
|
|
|
import { useEffect, useState } from 'react';
|
|
import { AgGridReact } from 'ag-grid-react';
|
|
import useAxiosPrivate from '../../utils/useAxiosPrivate';
|
|
import EditNoteRoundedIcon from '@mui/icons-material/EditNoteRounded';
|
|
import DeleteSweepRoundedIcon from '@mui/icons-material/DeleteSweepRounded';
|
|
// import ImportExportRoundedIcon from '@mui/icons-material/ImportExportRounded';
|
|
import AddCircleOutlineRoundedIcon from '@mui/icons-material/AddCircleOutlineRounded';
|
|
import Popup from './Popup';
|
|
import FirstAidForm from './FirstAidForm';
|
|
//import { FirstAidValidationForm } from './Validationform';
|
|
import { useFormik } from "formik";
|
|
import { ToastContainer, toast } from 'react-toastify';
|
|
import 'react-toastify/dist/ReactToastify.css';
|
|
import PictureAsPdfIcon from '@mui/icons-material/PictureAsPdf';
|
|
import DownloadIcon from '@mui/icons-material/Download';
|
|
import ExcelJS from 'exceljs';
|
|
import jsPDF from 'jspdf';
|
|
import 'jspdf-autotable';
|
|
import PropTypes from "prop-types";
|
|
import * as Yup from 'yup';
|
|
|
|
const FirstAidValidationForm = Yup.object({
|
|
boxName: Yup.string().required("Please enter Box Name "),
|
|
boxCode: Yup.string().required("Please enter box Code"),
|
|
boxLoc: Yup.string().required("Please enter box Loc"),
|
|
// firstAider: Yup.array().required("Please enter first Aider"),
|
|
firstAiderIds: Yup.array()
|
|
.min(1, 'At least one option must be selected')
|
|
.of(
|
|
Yup.object().shape({
|
|
id: Yup.number().required(),
|
|
label: Yup.string().required(),
|
|
})
|
|
),
|
|
});
|
|
|
|
const FirstAidList = () => {
|
|
|
|
|
|
const [rowData, setRowData] = useState([]);
|
|
|
|
const [colDefs, setColDefs] = useState([]);
|
|
|
|
const [openPopup, setOpenPopup] = useState(false);
|
|
|
|
const axiosClientPrivate = useAxiosPrivate();
|
|
|
|
const [id,setId] = useState(1);
|
|
|
|
const [showupdate,setShowupdate] = useState(false);
|
|
|
|
const [fetchTrigger, setFetchTrigger] = useState(0);
|
|
|
|
const [patientData,setPatientData] = useState([]);
|
|
|
|
// const [patientPair,setPatientPair] = useState({})
|
|
// "boxName": "First Aid Box 1",
|
|
// "boxCode": "FAB001",
|
|
// "boxLoc": " ",
|
|
// "patientIds":[1,2]
|
|
|
|
|
|
const initialValues = {
|
|
boxName:"",
|
|
boxCode:"",
|
|
boxLoc:"",
|
|
firstAiderIds: []
|
|
};
|
|
|
|
|
|
const {
|
|
values,
|
|
touched,
|
|
errors,
|
|
handleBlur,
|
|
handleChange,
|
|
setFieldValue,
|
|
handleSubmit,
|
|
resetForm,
|
|
} = useFormik({
|
|
initialValues: initialValues,
|
|
validationSchema: FirstAidValidationForm,
|
|
// onSubmit: (values, action) => {
|
|
// console.log("check before",values);
|
|
// const patientId = values.patientIds.map((item)=> item.id)
|
|
// // console.log("w",patientId);
|
|
// // setFieldValue("patientIds",patientId)
|
|
// values.patientIds = patientId,
|
|
// console.log("check after",values);
|
|
// action.resetForm();
|
|
// },
|
|
onSubmit: async (values, {resetForm}) => {
|
|
try {
|
|
const patientId = values.firstAiderIds.map((item)=> item.id)
|
|
values.firstAiderIds = patientId
|
|
console.log(values);
|
|
const response = await axiosClientPrivate.post('/first-aid-boxes', values);
|
|
toast.success("Saved Successfully!",{
|
|
position:"top-center",
|
|
autoClose : 500
|
|
});
|
|
setFetchTrigger(prev => prev+1);
|
|
console.log('Response:', response.data);
|
|
resetForm();
|
|
} catch (error) {
|
|
console.log(values);
|
|
console.error('Error:', error);
|
|
}
|
|
},
|
|
});
|
|
|
|
|
|
const handleEdit = async (id) => {
|
|
// alert(id);
|
|
try {
|
|
|
|
const response1 = await axiosClientPrivate.get('/patients');
|
|
const items1 = response1.data.content;
|
|
const patientPair = {};
|
|
items1.map((item)=>{
|
|
patientPair[item.id] = item.patientName
|
|
});
|
|
|
|
const response = await axiosClientPrivate.get(`/first-aid-boxes/${id}`);
|
|
const items = response.data
|
|
// console.log(response.data);
|
|
|
|
// console.log(response.data.content);
|
|
|
|
console.log(patientPair);
|
|
|
|
const updatedFirstAiderIds = items.firstAiderIds.map((id) => ({
|
|
label: patientPair[parseInt(id)], // Get the label from patientPair using the ID
|
|
id: id, // Keep the original ID
|
|
}));
|
|
|
|
items.firstAiderIds = updatedFirstAiderIds
|
|
|
|
console.log("edit",items);
|
|
|
|
|
|
setFieldValue("id",items.id);
|
|
setFieldValue("boxName",items.boxName);
|
|
setFieldValue("boxCode",items.boxCode);
|
|
setFieldValue("boxLoc",items.boxLoc);
|
|
setFieldValue("firstAiderIds",items.firstAiderIds);
|
|
|
|
setId(id);
|
|
setShowupdate(true);
|
|
setOpenPopup(true);
|
|
} catch (error) {
|
|
console.error('Error fetching item for edit:', error);
|
|
}
|
|
};
|
|
|
|
|
|
const handleUpdate = async (id)=> {
|
|
alert(id);
|
|
const patientId = values.firstAiderIds.map((item)=> item.id)
|
|
values.firstAiderIds = patientId
|
|
|
|
console.log("update values",values);
|
|
|
|
// const update = values;
|
|
try{
|
|
console.log(values);
|
|
await axiosClientPrivate.put(`/first-aid-boxes/${id}`,values);
|
|
toast.success("Updated Successfully!",{
|
|
position:"top-center",
|
|
autoClose: 500,
|
|
});
|
|
resetForm();
|
|
// setRowData(rowData => [...rowData,values]);
|
|
setFetchTrigger(prev => prev+1);
|
|
|
|
}
|
|
catch(err){
|
|
console.log(values);
|
|
console.log(err);
|
|
}
|
|
}
|
|
|
|
|
|
// to delete a row
|
|
const handleDeleteRow = async (id) => {
|
|
// alert(id)
|
|
if(window.confirm('Are you sure you want to delete this data?')){
|
|
try {
|
|
await axiosClientPrivate.delete(`first-aid-boxes/${id}`);
|
|
// setRowData(prevData => prevData.filter(row => row.buId !== id));
|
|
setFetchTrigger(prev => prev+1);
|
|
|
|
} catch (error) {
|
|
console.error('Error deleting row:', error);
|
|
}
|
|
}
|
|
};
|
|
|
|
const CustomActionComponent = ({id}) => {
|
|
CustomActionComponent.propTypes = {
|
|
id: PropTypes.number.isRequired,
|
|
};
|
|
return <div> <Button onClick={() => handleEdit(id)} > <EditNoteRoundedIcon /></Button>
|
|
<Button color="error" onClick={() => handleDeleteRow(id)}> <DeleteSweepRoundedIcon /> </Button> </div>
|
|
|
|
};
|
|
|
|
const pagination = true;
|
|
const paginationPageSize = 50;
|
|
const paginationPageSizeSelector = [50, 100, 200, 500];
|
|
|
|
useEffect(() => {
|
|
const controller = new AbortController();
|
|
|
|
const getAllOhc = async () => {
|
|
try {
|
|
|
|
const response1 = await axiosClientPrivate.get('/patients', { signal: controller.signal });
|
|
const items1 = response1.data.content;
|
|
console.log("check check",response1);
|
|
const patientPair = {};
|
|
const options = items1.map((item)=>{
|
|
patientPair[item.id] = item.patientName
|
|
return {label:item.patientName,id:item.id};
|
|
});
|
|
|
|
// console.log(patientPair);
|
|
// setPatientPair(patientPair);
|
|
setPatientData(options);
|
|
|
|
|
|
const response = await axiosClientPrivate.get('/first-aid-boxes', { signal: controller.signal });
|
|
const items = response.data.content;
|
|
// console.log("first-aid",items);
|
|
|
|
const updatedItems = items.map((item) => {
|
|
item.firstAiderIds = item.firstAiderIds.map((id) => patientPair[parseInt(id)] || id);
|
|
return item; // Return the updated item
|
|
});
|
|
// console.log("change data",updatedItems);
|
|
|
|
setRowData(updatedItems);
|
|
if (items.length > 0) {
|
|
const columns = Object.keys(items[0]).map(key => ({
|
|
field: key,
|
|
headerName: key.charAt(0).toUpperCase() + key.slice(1),
|
|
filter: true,
|
|
floatingFilter: true,
|
|
sortable: true
|
|
}));
|
|
|
|
columns.unshift({
|
|
field: "Actions", cellRenderer: (params) =>{
|
|
const id = params.data.id;
|
|
return <CustomActionComponent id={id} />
|
|
}
|
|
});
|
|
|
|
setColDefs(columns);
|
|
}
|
|
|
|
|
|
|
|
} catch (err) {
|
|
console.error("Failed to fetch data: ", err);
|
|
setRowData([]);
|
|
}
|
|
};
|
|
|
|
getAllOhc();
|
|
|
|
return () => {
|
|
controller.abort();
|
|
};
|
|
|
|
}, [fetchTrigger,axiosClientPrivate]);
|
|
|
|
|
|
// useEffect(() => {
|
|
// const controller = new AbortController();
|
|
|
|
// const getAllOhc = async () => {
|
|
|
|
// try {
|
|
// const response = await axiosClientPrivate.get('/patients', { signal: controller.signal });
|
|
// const items = response.data.content;
|
|
// console.log("patient names :-",items);
|
|
|
|
// // const newDiagnosisMap = new Map();
|
|
// // items.forEach(item => newDiagnosisMap.set(item.ailmentSysName, item.id));
|
|
// // setBodysystem(newDiagnosisMap);
|
|
|
|
// // console.log(diagnosisMap.size);
|
|
// // const ailment = items.map((item)=>{
|
|
// // // diagnosisMap.set(item.id,item.ailmentSysName);
|
|
// // return item.ailmentSysName;
|
|
// // });
|
|
// const patientPair = {}
|
|
// const options = items.map((item)=>{
|
|
// patientPair[item.id] = item.patientName
|
|
// return {label:item.patientName,id:item.id};
|
|
// });
|
|
|
|
// setPatientPair(patientPair);
|
|
// setPatientData(options);
|
|
// console.log("patient",options);
|
|
|
|
|
|
// // const unitobj = {};
|
|
// // items.map((item)=>{
|
|
// // unitobj[item.id] = item.unitName;
|
|
// // });
|
|
|
|
// // setUnitpair(unitobj);
|
|
// // console.log(ailment);
|
|
|
|
// } catch (err) {
|
|
// console.error("Failed to fetch data: ", err);
|
|
// console.log("user cancel");
|
|
// }
|
|
// };
|
|
|
|
// getAllOhc();
|
|
|
|
// return () => {
|
|
// controller.abort();
|
|
// };
|
|
|
|
// }, [axiosClientPrivate]);
|
|
|
|
|
|
|
|
|
|
|
|
const exportpdf = async () => {
|
|
|
|
const doc = new jsPDF();
|
|
const header = [['Id', 'Box Name',"Box Code","Box Location","First Aiders"]];
|
|
const tableData = rowData.map(item => [
|
|
item.id,
|
|
item.boxName,
|
|
item.boxCode,
|
|
item.boxLoc,
|
|
item.firstAiderIds,
|
|
|
|
]);
|
|
doc.autoTable({
|
|
head: header,
|
|
body: tableData,
|
|
startY: 20,
|
|
theme: 'grid',
|
|
margin: { top: 30 },
|
|
styles: { fontSize: 5 },
|
|
columnStyles: { 0: { cellWidth: 'auto' }, 1: { cellWidth: 'auto' } }
|
|
});
|
|
doc.save("FirstAidList.pdf");
|
|
};
|
|
|
|
|
|
const exportExcelfile = async () => {
|
|
const workbook = new ExcelJS.Workbook();
|
|
const sheet = workbook.addWorksheet('My Sheet');
|
|
|
|
|
|
const headerStyle = {
|
|
|
|
alignment: { horizontal: 'center' }
|
|
|
|
};
|
|
|
|
sheet.getRow(1).font = { bold: true };
|
|
|
|
const columnWidths = {
|
|
Id: 10,
|
|
boxName: 20,
|
|
boxCode: 15,
|
|
boxLoc: 25,
|
|
firstAiderIds: 50,
|
|
};
|
|
|
|
sheet.columns = [
|
|
{ header: "Id", key: 'buId', width: columnWidths.buId, style: headerStyle },
|
|
{ header: "Box Name", key: 'boxName', width: columnWidths.boxName, style: headerStyle },
|
|
{ header: "Box Code", key: 'boxCode', width: columnWidths.boxCode, style: headerStyle },
|
|
{ header: "Box Location", key: 'boxLoc', width: columnWidths.boxLoc, style: headerStyle },
|
|
{ header: "First Aiders", key: 'firstAiderIds', width: columnWidths.firstAiderIds, style: headerStyle },
|
|
|
|
];
|
|
|
|
rowData.map(product =>{
|
|
sheet.addRow({
|
|
id: product.id,
|
|
boxName: product.boxName,
|
|
boxCode: product.boxCode,
|
|
boxLoc: product.boxLoc,
|
|
firstAiderIds: product.firstAiderIds,
|
|
})
|
|
});
|
|
|
|
workbook.xlsx.writeBuffer().then(data => {
|
|
const blob = new Blob([data], {
|
|
type: "application/vnd.openxmlformats-officedocument.spreadsheet.sheet",
|
|
});
|
|
const url = window.URL.createObjectURL(blob);
|
|
const anchor = document.createElement('a');
|
|
anchor.href = url;
|
|
anchor.download = 'FirstAidList.xlsx';
|
|
anchor.click();
|
|
|
|
})
|
|
}
|
|
|
|
|
|
return (
|
|
<>
|
|
<ToastContainer />
|
|
<Box
|
|
className="ag-theme-quartz"
|
|
style={{ height: 500 }}
|
|
>
|
|
|
|
<Stack sx={{ display: 'flex', flexDirection: 'row' }} marginY={1} paddingX={1}>
|
|
<ButtonGroup variant="contained" aria-label="Basic button group">
|
|
<Button variant="contained" endIcon={<AddCircleOutlineRoundedIcon />} onClick={() => { setOpenPopup(true) }}>Add New</Button>
|
|
<Button variant="contained" onClick={exportpdf} color="success" endIcon={<PictureAsPdfIcon/>}>PDF</Button>
|
|
<Button variant="contained" onClick={()=> exportExcelfile()} color="success" endIcon={<DownloadIcon/>}>Excel</Button>
|
|
</ButtonGroup>
|
|
|
|
</Stack>
|
|
<AgGridReact
|
|
rowData={rowData}
|
|
columnDefs={colDefs}
|
|
animateRows={true}
|
|
pagination={pagination}
|
|
paginationPageSize={paginationPageSize}
|
|
paginationPageSizeSelector={paginationPageSizeSelector}
|
|
/>
|
|
</Box>
|
|
|
|
<Popup showupdate={showupdate} id= {id} handleUpdate={handleUpdate} setShowupdate={setShowupdate} resetForm={resetForm} handleSubmit={handleSubmit} openPopup={openPopup} setOpenPopup={setOpenPopup} title="First Aid Box">
|
|
|
|
<FirstAidForm patientData={patientData} values={values} touched={touched} errors={errors} handleBlur={handleBlur} handleChange={handleChange} setFieldValue={setFieldValue} handleSubmit={handleSubmit} />
|
|
|
|
</Popup>
|
|
</>
|
|
);
|
|
};
|
|
|
|
export default FirstAidList;
|