import { useEffect, useState, useMemo, useRef } from "react"; import axios from "axios"; import PayrollModal from "./payrollModal"; import "../../../Styles/components/payroll/payroll.css"; import { useSession } from "../../context/SessionContext"; import "react-datepicker/dist/react-datepicker.css"; import Calendar from "./calendar_UI/calendar"; import { Edit, AlignJustify, Trash2, Search, Grid3x3, Logs, } from "lucide-react"; import { EllipsisHorizontalIcon } from "@heroicons/react/24/outline"; import Swal from "sweetalert2"; import { confirmHoldToDelete } from "../utils/confirmHoldToDelete"; import BASE_URL from "@backend/server/config"; import { CalendarCog, ReceiptText, Printer } from "lucide-react"; import PayrollLog from "./payrollLog"; import Breadcrumbs from "../breadcrumbs/Breadcrumbs"; import { Tooltip } from "@mui/material"; import { tooltipClasses } from "@mui/material"; // import { handlePrint } from '../../../src/components/payroll/printPayroll'; // Adjust path if needed const Payroll = () => { const { user } = useSession(); const [loading, setLoading] = useState(true); const [error, setError] = useState(""); const [isModalOpen, setIsModalOpen] = useState(false); const [selectedPayroll, setSelectedPayroll] = useState(null); const [modalType, setModalType] = useState(""); const [openDropdownId, setOpenDropdownId] = useState(null); const [openDropdownDetails, setOpenDropdownDetails] = useState(null); const [payrollData, setPayrollData] = useState([]); const [selectedPayrolls, setSelectedPayrolls] = useState([]); const [showtablelist, setShowTableList] = useState(false); const [closetablelist, setCloseTableList] = useState(true); const [buttonClicked, setButtonClicked] = useState(false); const [showPayrollLog, setShowPayrollLog] = useState(false); // State to control visibility const [searchTerm, setSearchTerm] = useState(""); const modalRef = useRef(null); const [showListView, setShowListView] = useState(true); const [showGridView, setShowGridView] = useState(false); const [activeView, setActiveView] = useState("list"); // Define a function named goToDepartment that does not take any parameters const handleListView = () => { setActiveView("list"); setShowListView(true); setShowGridView(false); }; const handleGridView = () => { setActiveView("grid"); setShowListView(false); setShowGridView(true); }; useEffect(() => { const handleClickOutside = (event) => { if (modalRef.current && !modalRef.current.contains(event.target)) { closePayrollLog(); } }; if (showPayrollLog) { document.addEventListener("mousedown", handleClickOutside); } return () => { document.removeEventListener("mousedown", handleClickOutside); }; }, [showPayrollLog]); const toggleActionsDropdown = (payrollId) => { setOpenDropdownId(openDropdownId === payrollId ? null : payrollId); }; const toggleDetailsDropdown = (payroll) => { if (openDropdownDetails === payroll.payroll_id) { setOpenDropdownDetails(null); } else { setOpenDropdownDetails(payroll.payroll_id); } setOpenDropdownId(false); }; const handleNewButtonClick = () => { setShowTableList(false); setButtonClicked(false); setCloseTableList(true); }; const handleButtonClick = () => { setShowTableList(true); setButtonClicked(true); setCloseTableList(false); }; const filteredPayrollData = useMemo(() => { return payrollData.filter((payroll) => { const nameMatch = payroll.name ?.toLowerCase() .includes(searchTerm.toLowerCase()); const idMatch = payroll.employee_id ?.toLowerCase() .includes(searchTerm.toLowerCase()); return nameMatch || idMatch; }); }, [searchTerm, payrollData]); const fetchPayrolls = async () => { try { const response = await axios.get(`${BASE_URL}/api/payroll/payroll`); if (response.data.success) { setPayrollData(response.data.data); } else { setError(response.data.message); } setLoading(false); } catch (error) { setError("Error fetching data: " + error.message); setLoading(false); } }; useEffect(() => { fetchPayrolls(); }, []); const openModal = (type, payroll = null) => { setSelectedPayroll(payroll); setModalType(type); setIsModalOpen(true); }; const closeModal = () => { setIsModalOpen(false); setSelectedPayroll(null); setModalType(""); }; const handleDelete = async (payroll) => { const result = await confirmHoldToDelete({ title: "Are you sure?", text: "This payroll record will be permanently deleted!", }); if (result.isConfirmed) { try { await axios.post(`${BASE_URL}/api/payroll/delete_payroll`, { payroll_id: payroll.payroll_id, }); Swal.fire({ icon: "success", title: "Deleted!", text: "Payroll record deleted successfully.", }).then(() => { fetchPayrolls(); // Auto refresh after confirmation }); } catch (error) { console.error("Error deleting record:", error); Swal.fire({ icon: "error", title: "Error!", text: "Failed to delete the payroll record.", }); } } }); }; const handleSelectPayroll = (payrollId) => { setSelectedPayrolls((prev) => prev.includes(payrollId) ? prev.filter((id) => id !== payrollId) : [...prev, payrollId], ); }; const handleSelectAll = () => { if (selectedPayrolls.length === payrollData.length) { setSelectedPayrolls([]); } else { setSelectedPayrolls(payrollData.map((payroll) => payroll.payroll_id)); } }; const formatDate = (dateString) => { const options = { year: "numeric", month: "short", day: "2-digit" }; const date = new Date(dateString); const formattedDate = date.toLocaleDateString("en-US", options); // Replace the month abbreviation with the one that includes a dot return formattedDate.replace( /(\w{3})\s(\d{1,2}),\s(\d{4})/, (match, month, day, year) => { const monthWithDot = month + "."; // Append a dot to the month return `${monthWithDot} ${day}, ${year}`; }, ); }; const closePayrollLog = () => { setShowPayrollLog(false); // Close the payroll log modal }; const handlePrint = (payrolls) => { const printWindow = window.open("", "_blank"); if (printWindow) { printWindow.document.write(` Payslip
`); payrolls.forEach((payroll) => { const sss = parseFloat(payroll.sss_employee_share) || 0; const philhealth = parseFloat(payroll.philhealth_employee_share) || 0; const pagibig = parseFloat(payroll.pagibig_employee_share) || 0; const totalDeduction = (sss + philhealth + pagibig).toFixed(2); const totalBasic = parseFloat(payroll.total_basic_salary) || 0; const netSalary = (totalBasic - parseFloat(totalDeduction)).toFixed(2); printWindow.document.write(`

${payroll.company_name || "Centralize"}

Address

PAYSLIP

Employee Name: ${payroll.name}

Designation: ${payroll.position_name}

Day From: ${new Date(payroll.date_from).toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" })}

Day Until: ${new Date(payroll.date_until).toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" })}

Earnings Amount Deductions Amount
Basic Salary ${payroll.basic_salary} SSS ${payroll.sss_employee_share}
Days ${payroll.total_days} PHIL. HEALTH ${payroll.philhealth_employee_share}
Incentives - Pag-ibig ${payroll.pagibig_employee_share}
Retroactive - Others -
Gross Earning: ${payroll.total_basic_salary} CA -
Over Time ${payroll.total_overtime_request} Total Deduction: ${totalDeduction}
Net Salary: ${netSalary}

Alan T. Ang or HR

Employer's Signature

Employee Copy

_________________________

Employee Signature

${payroll.company_name || "Centralize"}

Address

PAYSLIP

Employee Name: ${payroll.name}

Designation: ${payroll.position_name}

Day From: ${new Date(payroll.date_from).toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" })}

Day Until: ${new Date(payroll.date_until).toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" })}

Earnings Amount Deductions Amount
Basic Salary ${payroll.basic_salary} SSS ${payroll.sss_employee_share}
Days ${payroll.total_days} PHIL. HEALTH ${payroll.philhealth_employee_share}
Incentives - Pag-ibig ${payroll.pagibig_employee_share}
Retroactive - Others -
Gross Earning: ${payroll.total_basic_salary} CA -
Over Time ${payroll.total_overtime_request} Total Deduction: ${totalDeduction}
Net Salary: ${netSalary}

Alan T. Ang or HR

Employer's Signature

Employer Copy

_________________________

Employee Signature

`); }); printWindow.document.write(`
`); printWindow.document.close(); printWindow.focus(); } }; const breadcrumbItems = [ // { label: 'Home', path: '/' }, { label: "Payroll Dashboard", path: "/payrolldashboard" }, { label: "Payroll Records" }, ]; return (
Payroll Records
setSearchTerm(e.target.value)} />
{user?.role === "ADMIN" && ( )}
{/* Modal for Payroll Log */} {showPayrollLog && (
{/* This is the backdrop area that listens for outside clicks */}
)} {showGridView && (
{filteredPayrollData.map((payroll) => (
{openDropdownId === payroll.payroll_id && (
)}
toggleDetailsDropdown(payroll)}>
{payroll.name}

Department: {payroll.department_name}

Position: {payroll.position_name}

{openDropdownDetails === payroll.payroll_id && (

More Information

Employee ID: {payroll.employee_id} Payroll ID: {payroll.payroll_id}

Date From:{" "}

{" "} {new Date(payroll.date_from).toLocaleDateString()}

Date Until:{" "}

{" "} {new Date(payroll.date_until).toLocaleDateString()}

Total Days:{" "}

{" "} {payroll.total_days}

Total Salary:{" "}

{" "} {payroll.total_basic_salary}
)}
))}
{selectedPayroll && (

Selected Payroll Details:

Total Days: {selectedPayroll.total_days}

Total Salary:{" "} {selectedPayroll.total_basic_salary}

)}
)} {showListView && (
{!loading && payrollData.length > 0 && (
0 } />
EMPLOYEE DETAILS
POSITION
DAYS
DEDUCTION
TOTAL
{filteredPayrollData.map((payroll, index) => (
handleSelectPayroll(payroll.payroll_id)} className="rounded" />
{payroll.name}
Employee ID:{" "} {payroll.employee_id}
Payroll ID:{" "} {payroll.payroll_id}
Post. ID:
{payroll.position_name}
Dept. ID:
{payroll.department_name}
{formatDate(payroll.date_from)} {/* TO */} {/* */}
{/* */}
{/* */}
{formatDate(payroll.date_until)}
Total Days:
{payroll.total_days}
Total Overtime:
{/* {payroll.total_overtime_hours} */} {payroll.total_overtime_request}
Phil. Health:
{payroll.philhealth_employee_share}
SSS:
{payroll.sss_employee_share}
Pag-ibig:
{payroll.pagibig_employee_share}
Total Salary:
{" "} {payroll.total_basic_salary}
Total Deduction:
{( (parseFloat(payroll.philhealth_employee_share) || 0) + (parseFloat(payroll.sss_employee_share) || 0) + (parseFloat(payroll.pagibig_employee_share) || 0) ).toFixed(2)}
{/* {user?.role === "ADMIN" &&
} */}
))}
)}
)} {isModalOpen && ( )}
); }; export default Payroll;