ohctechv3/.svn/pristine/ec/ec0a6cce58c605ebbe211aaf9942737ad3ae4fa7.svn-base
2024-10-28 15:03:36 +05:30

584 lines
22 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 VaccineForm from './VaccineForm';
// import { VaccineValidationForm } 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";
// new
import 'ag-grid-community/styles/ag-grid.css';
import 'ag-grid-community/styles/ag-theme-alpine.css';
import * as Yup from 'yup';
import { useNavigate } from 'react-router-dom';
const VaccineValidationForm = Yup.object({
vaccineName: Yup.string().required("Please enter Vaccine Name"),
vaccineCompany: Yup.string().required("Please Enter Company Name"),
vaccineDesc: Yup.string().required("Please Enter Vaccine Description"),
});
const AppointmentHistory = () => {
const navigate = useNavigate();
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 [paginationPageSize, setPaginationPageSize] = useState(100);
const [isLoading,setIsLoading] = useState(false);
// const [change, setChange] = useState("";)
// console.log("check",paginationPageSize);
// const initialValues = {
// vaccineName:"",
// vaccineCompany:"",
// vaccineDesc:""
// };
// function formatDate(dateString) {
// if (dateString != null || dateString != undefined || dateString != "") {
// const [year, month, day] = dateString.split("-");
// return `${day}-${month}-${year}`;
// }
// }
// const formateDate = formatDate('2024-10-08')
console.log('appointment history');
const {
values,
touched,
errors,
handleBlur,
handleChange,
setFieldValue,
handleSubmit,
resetForm
} = useFormik({
initialValues: {
},
// validationSchema: VaccineValidationForm,
// onSubmit: (values, action) => {
// console.log(values);
// action.resetForm();
// },
onSubmit: async (values, {resetForm}) => {
try {
const response = await axiosClientPrivate.post('/vaccines', values);
toast.success("Saved Successfully!",{
position:"top-center"
});
// getting id(key,value) of last index
// const id = rowData[rowData.length-1].buId;
// const obj = {
// buId : id+1,
// ...values
// }
// console.log(obj);
// setRowData(rowData => [...rowData, obj]);
setFetchTrigger(prev => prev+1);
console.log('Response:', response.data);
resetForm();
} catch (error) {
console.log(values);
console.error('Error:', error);
}
},
});
const handleEdit = (id) => {
const empEditId = id;
navigate('/edit-employee-details', { state: { empEditId } });
// try {
// const response = await axiosClientPrivate.get(`/procurements/${id}`);
// console.log("procurement edit",response.data);
// setFieldValue("id",response.data.id);
// setFieldValue("vaccineName",response.data.vaccineName);
// setFieldValue("vaccineCompany",response.data.vaccineCompany);
// setFieldValue("vaccineDesc",response.data.vaccineDesc);
// setFieldValue("lastModified", response.data.lastModified);
// setFieldValue("modifiedBy", response.data.modifiedBy);
// setId(id);
// setShowupdate(true);
// setOpenPopup(true);
// } catch (error) {
// console.error('Error fetching item for edit:', error);
// }
};
const handleUpdate = async (id)=> {
// alert(id);
const update = values;
try{
console.log(values);
await axiosClientPrivate.put(`/procurements/procurement-indent/${id}`,update);
toast.success("Updated Successfully!",{
position:"top-center",
autoClose: 3000,
});
resetForm();
// setRowData(rowData => [...rowData,values]);
setFetchTrigger(prev => prev+1);
}
catch(err){
console.log(values);
console.log(err);
}
}
// to delete a row
const handleDelete = async (id) => {
alert(id)
if(window.confirm('Are you sure you want to delete this data?')){
try {
await axiosClientPrivate.delete(`/patients/${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={() => handleDelete(id)}> <DeleteSweepRoundedIcon /> </Button> </div>
// };
// const paginationPageSizeSelector = [50, 100, 200, 500];
const pageSizeOptions = [2, 4, 8, 10];
const formatDate = (dateString) => {
const date = new Date(dateString);
return date.toLocaleDateString('en-GB', {
day: '2-digit',
month: 'short',
year: 'numeric',
}).replace(/ /g, '-');
};
const formatMonth = (dateString) => {
const date = new Date(dateString);
return date.toLocaleDateString('en-GB', {
month: 'short',
year: 'numeric',
}).replace(' ', '-');
};
useEffect(() => {
const controller = new AbortController();
const getAllOhc = async () => {
try {
const response = await axiosClientPrivate.get(`/patients?page=0&size=${paginationPageSize}`, { signal: controller.signal });
const items = response.data.content;
console.log("patients",items);
// if(items?.length > 0){
// const chaneItems = items.map((item,index)=>{
// return {
// ...item,
// Sr : index + 1,
// isFirstAid : item.isFirstAid == 1 ? "Yes" : item.isFirstAid == 0 ? 'No' : '',
// isOhcStaff : item.isOhcStaff == 1 ? "Yes" : item.isOhcStaff == 0 ? 'No' : ''
// }
// })
// // setRowData(chaneItems)
// }
if (items.length > 0) {
const columns = [
{ headerName: 'Sr', field: 'count', width: 150, sortable: false, floatingFilter: true, filter: "agTextColumnFilter" },
{ headerName: '', field: 'link', width: 150, sortable: false, floatingFilter: true, filter: "agTextColumnFilter" },
{ headerName: 'Date', field: 'appointment_date', width: 200, sortable: true, floatingFilter: true, filter: "agDateColumnFilter" },
{ headerName: 'Ticket No', field: 'ticket_no', width: 150, sortable: true, floatingFilter: true, filter: "agTextColumnFilter" },
{ headerName: 'ECode/G.Pass', field: 'emp_code', width: 150, sortable: true, floatingFilter: true, filter: "agTextColumnFilter" },
{ headerName: 'Patient Name', field: 'patient_name', width: 200, sortable: true, floatingFilter: true, filter: "agTextColumnFilter" },
{ headerName: 'Injury', field: 'appointment_type', width: 150, sortable: true, floatingFilter: true, filter: "agTextColumnFilter" },
{ headerName: 'Consulted By', field: 'doctor_attended_flag', width: 150, sortable: true, floatingFilter: true, filter: "agTextColumnFilter" },
{ headerName: 'Complaints', field: 'complaints', width: 200, sortable: true, floatingFilter: true, filter: "agTextColumnFilter" },
{ headerName: 'Diagnosis', field: 'injury_types_new', width: 200, sortable: true, floatingFilter: true, filter: "agTextColumnFilter" },
{ headerName: 'Treatments', field: 'hospital_treatment', width: 300, sortable: true, floatingFilter: true, filter: "agTextColumnFilter" },
{ headerName: 'Absence Start', field: 'date_absent', width: 150, sortable: true, floatingFilter: true, filter: "agDateColumnFilter" },
{ headerName: 'Rejoining Date', field: 'date_return', width: 150, sortable: true, floatingFilter: true, filter: "agDateColumnFilter" },
{ headerName: 'Days of Leaves', field: 'date_difference', width: 150, sortable: true, floatingFilter: true, filter: "agNumberColumnFilter" },
{ headerName: 'Referral', field: 'referral', width: 100, sortable: true, floatingFilter: true, filter: "agTextColumnFilter" },
{ headerName: 'Vitals', field: 'checkup_results', width: 150, sortable: false, floatingFilter: true, filter: "agTextColumnFilter" },
{ headerName: 'Doc Comment', field: 'doc_comment', width: 150, sortable: false, floatingFilter: true, filter: "agTextColumnFilter" }
];
// columns.unshift({
// field: "Actions", cellRenderer: (params) =>{
// const id = params.data.id;
// return <CustomActionComponent id={id} />
// }
// });
setColDefs(columns);
}
} catch (err) {
console.error("Failed to fetch patient data: ", err);
setRowData([]);
}
};
getAllOhc();
return () => {
controller.abort();
};
}, [paginationPageSize,fetchTrigger]);
const exportpdf = async () => {
const doc = new jsPDF();
// Define table headers based on column definitions
const header = [['Link', 'Sr', 'ECode', 'Patient Name', 'Plant', 'Grade', 'Father Name', 'Patient Type', 'Contractor/Company', 'Designation', 'Division', 'Department', 'Section', 'Gender', 'Blood Group', 'Email', 'Phone', 'Aadhar', 'Primary Patient', 'Is OHC STAFF', 'Is First Aider']];
// Map the rowData to match the column definitions
const tableData = rowData.map(item => [
item.Sr || '',
item.empCode || '',
item.patientName || '',
item.ohcType || '',
item.designation || '',
item.fatherName || '',
item.patientCategory || '',
item.employerContractor || '',
item.designation || '',
item.businessUnit || '',
item.department || '',
item.section || '',
item.gender || '',
item.bloodGroup || '',
item.emailId || '',
item.primaryPhone || '',
item.aadharNo || '',
item.primary_patient_id || '',
item.isOhcStaff || '',
item.isFirstAid || ''
]);
// Generate the table inside the PDF
doc.autoTable({
head: header,
body: tableData,
startY: 20,
theme: 'grid',
margin: { top: 30 },
styles: { fontSize: 5 },
columnStyles: { 0: { cellWidth: 'auto' }, 1: { cellWidth: 'auto' } } // Adjust column width if needed
});
// Save the PDF with a name of your choice
doc.save("AppointmentHistory.pdf");
};
const exportExcelfile = async () => {
const workbook = new ExcelJS.Workbook();
const sheet = workbook.addWorksheet("Employee List");
const headerStyle = {
alignment: { horizontal: "center" },
};
sheet.getRow(1).font = { bold: true };
// Define column widths for each field based on PDF
const columnWidths = {
Sr: 10,
empCode: 20,
patientName: 25,
ohcType: 15,
grade: 15,
fatherName: 25,
patientCategory: 20,
employerContractor: 25,
designation: 20,
businessUnit: 20,
department: 20,
section: 30,
gender: 10,
bloodGroup: 15,
emailId: 25,
primaryPhone: 15,
aadharNo: 20,
primaryPatientId: 20,
isOhcStaff: 15,
isFirstAid: 15
};
// Set up columns for the Excel sheet
sheet.columns = [
{ header: "Sr", key: "Sr", width: columnWidths.Sr, style: headerStyle },
{ header: "ECode", key: "empCode", width: columnWidths.empCode, style: headerStyle },
{ header: "Patient Name", key: "patientName", width: columnWidths.patientName, style: headerStyle },
{ header: "Plant", key: "ohcType", width: columnWidths.ohcType, style: headerStyle },
{ header: "Grade", key: "grade", width: columnWidths.grade, style: headerStyle },
{ header: "Father Name", key: "fatherName", width: columnWidths.fatherName, style: headerStyle },
{ header: "Patient Type", key: "patientCategory", width: columnWidths.patientCategory, style: headerStyle },
{ header: "Contractor/Company", key: "employerContractor", width: columnWidths.employerContractor, style: headerStyle },
{ header: "Designation", key: "designation", width: columnWidths.designation, style: headerStyle },
{ header: "Division", key: "businessUnit", width: columnWidths.businessUnit, style: headerStyle },
{ header: "Department", key: "department", width: columnWidths.department, style: headerStyle },
{ header: "Section", key: "section", width: columnWidths.section, style: headerStyle },
{ header: "Gender", key: "gender", width: columnWidths.gender, style: headerStyle },
{ header: "Blood Group", key: "bloodGroup", width: columnWidths.bloodGroup, style: headerStyle },
{ header: "Email", key: "emailId", width: columnWidths.emailId, style: headerStyle },
{ header: "Phone", key: "primaryPhone", width: columnWidths.primaryPhone, style: headerStyle },
{ header: "Aadhar", key: "aadharNo", width: columnWidths.aadharNo, style: headerStyle },
{ header: "Primary Patient", key: "primaryPatientId", width: columnWidths.primaryPatientId, style: headerStyle },
{ header: "Is OHC STAFF", key: "isOhcStaff", width: columnWidths.isOhcStaff, style: headerStyle },
{ header: "Is First Aider", key: "isFirstAid", width: columnWidths.isFirstAid, style: headerStyle },
];
// Add data rows, mapping to match the keys defined above
rowData.map((employee, index) => {
sheet.addRow({
Sr: index + 1,
empCode: employee.empCode,
patientName: employee.patientName,
ohcType: employee.ohcType,
grade: employee.grade,
fatherName: employee.fatherName,
patientCategory: employee.patientCategory,
employerContractor: employee.employerContractor,
designation: employee.designation,
businessUnit: employee.businessUnit,
department: employee.department,
section: employee.section,
gender: employee.gender,
bloodGroup: employee.bloodGroup,
emailId: employee.emailId,
primaryPhone: employee.primaryPhone,
aadharNo: employee.aadharNo,
primaryPatientId: employee.primaryPatientId,
isOhcStaff: employee.isOhcStaff,
isFirstAid: employee.isFirstAid,
});
});
// Wrap text in columns where necessary
sheet.columns.forEach(column => {
column.alignment = { wrapText: true };
});
// Write the workbook to an Excel file and trigger download
const buffer = await workbook.xlsx.writeBuffer();
const blob = new Blob([buffer], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
const url = window.URL.createObjectURL(blob);
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = "AppointmentHistory.xlsx";
anchor.click();
};
// download template
const downloadEmployeeTemplate = () => {
const workbook = new ExcelJS.Workbook();
const worksheet = workbook.addWorksheet('Employee Template');
// Define header row
worksheet.columns = [
{ header: 'ECode', key: 'emp_code', width: 20 },
{ header: 'Patient Name', key: 'patient_name', width: 25 },
{ header: 'Plant', key: 'plant_id', width: 15 },
{ header: 'Grade', key: 'grade_id', width: 15 },
{ header: 'Father Name', key: 'father_name', width: 25 },
{ header: 'Patient Type', key: 'patient_cat_name', width: 20 },
{ header: 'Contractor/Company', key: 'employer_contractor_name', width: 25 },
{ header: 'Designation', key: 'designation_name', width: 20 },
{ header: 'Division', key: 'bu_name', width: 20 },
{ header: 'Department', key: 'dept_name', width: 20 },
{ header: 'Section', key: 'section', width: 30 },
{ header: 'Gender', key: 'gender', width: 10 },
{ header: 'Blood Group', key: 'blood_group', width: 15 },
{ header: 'Email', key: 'offiial_email_id', width: 25 },
{ header: 'Phone', key: 'primary_phone', width: 15 },
{ header: 'Aadhar', key: 'aadhar_no', width: 20 },
{ header: 'Primary Patient', key: 'primary_patient_id', width: 20 },
{ header: 'Is OHC STAFF', key: 'is_ohc_staff', width: 15 },
{ header: 'Is First Aider', key: 'is_first_aid', width: 15 },
];
// Add empty rows for the user to fill in data
for (let i = 0; i < 5; i++) {
worksheet.addRow({});
}
// Apply styles to header row (bold, background color, borders)
worksheet.getRow(1).eachCell((cell) => {
cell.font = { bold: true };
cell.fill = {
type: 'pattern',
pattern: 'solid',
fgColor: { argb: 'FFCCCCCC' },
};
cell.border = {
top: { style: 'thin' },
left: { style: 'thin' },
bottom: { style: 'thin' },
right: { style: 'thin' },
};
cell.alignment = { vertical: 'middle', horizontal: 'center' };
});
// Apply borders and alignment to data cells
worksheet.eachRow((row, rowNumber) => {
if (rowNumber > 1) {
row.eachCell((cell) => {
cell.border = {
top: { style: 'thin' },
left: { style: 'thin' },
bottom: { style: 'thin' },
right: { style: 'thin' },
};
cell.alignment = { vertical: 'middle', horizontal: 'center' };
});
}
});
// Generate and download the Excel file
workbook.xlsx.writeBuffer().then((buffer) => {
const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
// Create a link element and trigger a download
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'employee_template.xlsx';
a.click();
// Cleanup
window.URL.revokeObjectURL(url);
});
};
// filter
const [temp,setTemp] = useState("");
const onFilterChanged = (params) => {
const filterModel = params.api.getFilterModel();
setTemp(filterModel)
};
console.log("tempppp filter",temp);
const [index,setIndex] = useState();
console.log("index for next page : ",index);
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" 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={true}
paginationPageSize={paginationPageSize}
paginationPageSizeSelector={pageSizeOptions}
onPaginationChanged={(event) => {
setPaginationPageSize(event.api.paginationGetPageSize());
setIndex(event.api.paginationGetCurrentPage());
}}
onFilterChanged={onFilterChanged}
// paginationNumberFormatter={paginationNumberFormatter}
// onGridReady={(params) => {
// params.api.paginationGoToPage(currentPageIndex);
// }}
// paginationTotalRowCount = {200}
// paginationGetPageSize = {200}
/>
</Box>
</>
);
};
export default AppointmentHistory;