import { saveAs } from "file-saver"; import jalaali from "jalaali-js"; import { Calendar, ChevronLeft, FileChartColumnIncreasing, Menu, PanelLeft, Server, User, } from "lucide-react"; import React, { useEffect, useRef, useState } from "react"; import { useLocation } from "react-router"; import XLSX from "xlsx-js-style"; import { Button } from "~/components/ui/button"; import { Calendar as CustomCalendar } from "~/components/ui/Calendar"; import { useAuth } from "~/contexts/auth-context"; import { readStoredDate } from "~/hooks/useStoredDate"; import { reportingApi } from "~/lib/reporting-api"; import { useDeploymentProfile } from "~/contexts/deployment-profile-context"; import { cn, EventBus, handleDataValue } from "~/lib/utils"; interface HeaderProps { onToggleSidebar?: () => void; className?: string; title?: string; titleIcon?: React.ComponentType<{ className?: string }> | null; } interface MonthItem { id: string; label: string; start: string; end: string; } interface CurrentDay { start?: string; end?: string; sinceMonth?: string; untilMonth?: string; } interface SelectedDate { since?: number; until?: number; } const monthList: Array = [ { id: "month-1", label: "بهار", start: "01/01", end: "03/31", }, { id: "month-2", label: "تابستان", start: "04/01", end: "06/31", }, { id: "month-3", label: "پاییز", start: "07/01", end: "09/31", }, { id: "month-4", label: "زمستان", start: "10/01", end: "12/30", }, ]; const columns: Array = [ { key: "title", label: "عنوان پروژه", sortable: true, width: "300px" }, { key: "importance_project", label: "میزان اهمیت", sortable: true, width: "160px", }, { key: "strategic_theme", label: "مضمون راهبردی", sortable: true, width: "200px", }, { key: "value_technology_and_innovation", label: "ارزش فناوری و نوآوری", sortable: true, width: "220px", }, { key: "type_of_innovation", label: "انواع نوآوری", sortable: true, width: "160px", }, { key: "innovation", label: "میزان نوآوری", sortable: true, width: "140px", }, { key: "person_executing", label: "مسئول اجرا", sortable: true, width: "180px", }, { key: "excellent_observer", label: "ناطر عالی", sortable: true, width: "180px", }, { key: "observer", label: "ناظر پروژه", sortable: true, width: "180px" }, { key: "moderator", label: "مجری", sortable: true, width: "180px" }, { key: "executive_phase", label: "فاز اجرایی", sortable: true, width: "160px", }, { key: "start_date", label: "تاریخ شروع", sortable: true, width: "120px", }, { key: "remaining_time", label: "زمان باقی مانده", sortable: true, width: "140px", computed: true, }, { key: "end_date", label: "تاریخ پایان (برنامه‌ریزی)", sortable: true, width: "160px", }, { key: "renewed_duration", label: "مدت زمان تمدید", sortable: true, width: "140px", }, { key: "done_date", label: "تاریخ پایان (واقعی)", sortable: true, width: "160px", }, { key: "deviation_from_program", label: "متوسط انحراف برنامه‌ای", sortable: true, width: "160px", }, { key: "approved_budget", label: "بودجه مصوب", sortable: true, width: "150px", }, { key: "budget_spent", label: "بودجه صرف شده", sortable: true, width: "150px", }, { key: "cost_deviation", label: "متوسط انحراف هزینه‌ای", sortable: true, width: "160px", }, ]; export function Header({ onToggleSidebar, className, title = "صفحه اول", titleIcon, }: HeaderProps) { const { user } = useAuth(); const { jy } = jalaali.toJalaali(new Date()); const calendarRef = useRef(null); const [isProfileMenuOpen, setIsProfileMenuOpen] = useState(false); const [isNotificationOpen, setIsNotificationOpen] = useState(false); const [openCalendar, setOpenCalendar] = useState(false); const [excelLoading, setExcelLoading] = useState(false); const location = useLocation(); const { profile } = useDeploymentProfile(); const projectManagerRoute = "/dashboard/project-management"; const [currentYear, setCurrentYear] = useState({ since: jy, until: jy, }); const [selectedDate, setSelectedDate] = useState({}); useEffect(() => { const parsedDate = readStoredDate(); setSelectedDate(parsedDate); setCurrentYear({ since: parseInt(parsedDate.start!.split("/")[0], 10), until: parseInt(parsedDate.end!.split("/")[0], 10), }); }, []); const redirectHandler = () => { window.open("/admin", "_blank", "noopener,noreferrer"); }; const changeSinceYear = (delta: number) => { if (!currentYear) return; const newSince = (currentYear.since ?? 0) + delta; if (newSince > (currentYear.until ?? Infinity) || newSince < 0) return; const updatedYear = { ...currentYear, since: newSince }; setCurrentYear(updatedYear); const updatedDate = { ...selectedDate, start: `${newSince}/${selectedDate.start?.split("/").slice(1).join("/")}`, }; setSelectedDate(updatedDate); localStorage.setItem("dateSelected", JSON.stringify(updatedDate)); EventBus.emit("dateSelected", updatedDate); }; const nextFromYearHandler = () => changeSinceYear(1); const prevFromYearHandler = () => changeSinceYear(-1); const selectFromDateHandler = (val: MonthItem) => { const data = { ...selectedDate, start: `${currentYear.since}/${val.start}`, sinceMonth: val.label, }; setSelectedDate(data); localStorage.setItem("dateSelected", JSON.stringify(data)); EventBus.emit("dateSelected", data); }; const changeUntilYear = (delta: number) => { if (!currentYear) return; const newUntil = (currentYear.until ?? 0) + delta; if (newUntil < (currentYear.since ?? 0)) return; const updatedYear = { ...currentYear, until: newUntil }; setCurrentYear(updatedYear); const updatedDate = { ...selectedDate, end: `${newUntil}/${selectedDate.end?.split("/").slice(1).join("/")}`, }; setSelectedDate(updatedDate); localStorage.setItem("dateSelected", JSON.stringify(updatedDate)); EventBus.emit("dateSelected", updatedDate); }; const nextUntilYearHandler = () => changeUntilYear(1); const prevUntilYearHandler = () => changeUntilYear(-1); const selectUntilDateHandler = (val: MonthItem) => { const data = { ...selectedDate, end: `${currentYear.until}/${val.end}`, untilMonth: val.label, }; setSelectedDate(data); localStorage.setItem("dateSelected", JSON.stringify(data)); EventBus.emit("dateSelected", data); toggleCalendar(); }; const toggleCalendar = () => { setOpenCalendar(!openCalendar); }; useEffect(() => { const handleClickOutside = (event: MouseEvent) => { if ( calendarRef.current && !calendarRef.current.contains(event.target as Node) ) { setOpenCalendar(false); } }; document.addEventListener("mousedown", handleClickOutside); return () => { document.removeEventListener("mousedown", handleClickOutside); }; }, []); const exportToExcel = async () => { let arr = []; const data: any = await fetchExcelData(); for (let i = 0; i < data.length; i++) { let obj: Record = {}; const project = data[i]; Object.entries(project).forEach(([pKey, pValue]: [any, any]) => { Object.values(columns).forEach((col) => { if (pKey === col?.key) { ``; obj[col?.label] = handleDataValue( pValue?.includes(",") ? pValue.replaceAll(",", "") : pValue ); } }); }); arr.push(obj); } const worksheet = XLSX.utils.json_to_sheet(arr); const workbook = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(workbook, worksheet, "People"); const excelBuffer = XLSX.write(workbook, { bookType: "xlsx", type: "array", }); const blob = new Blob([excelBuffer], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", }); saveAs(blob, "reports.xls"); }; const fetchExcelData = async () => { setExcelLoading(true); try { const first = await reportingApi.projectManagement(selectedDate?.start, selectedDate?.end, 1, 100, "start_date", "asc"); const pages = Math.ceil(first.totalCount / first.pageSize); const rest = pages > 1 ? await Promise.all(Array.from({ length: pages - 1 }, (_, index) => reportingApi.projectManagement(selectedDate?.start, selectedDate?.end, index + 2, 100, "start_date", "asc"))) : []; return [first, ...rest].flatMap((page) => page.items); } finally { setExcelLoading(false); } }; const handleDownloadFile = () => { if (excelLoading) return null; else exportToExcel(); }; return (
{/* Left Section */}
{/* Mobile Menu Toggle */} {onToggleSidebar && ( )} {/* Page Title */}

{/* Right-side icon for current page */} {titleIcon ? (
{React.createElement(titleIcon, { className: "w-5 h-5 " })}
) : ( )} {title.includes("-") ? (
{title.split("-")[0]} {title.split("-")[1]}
) : ( title )}

{selectedDate ? (
از {selectedDate?.sinceMonth} {handleDataValue(currentYear.since)}
تا {selectedDate?.untilMonth} {handleDataValue(currentYear.until)}
) : ( "تاریخ مورد نظر خود را انتخاب نمایید" )}
{openCalendar && (
)}
{/* Right Section */}
{/* User Menu */}
{location.pathname === projectManagerRoute ? (
دانلود فایل اکسل
) : ( "" )} {user?.roles.includes("Admin") && ( )}
{/* Profile Dropdown */} {isProfileMenuOpen && (
{user?.name} {user?.family}
{user?.email}
{/*
setIsProfileMenuOpen(false)} > پروفایل کاربری setIsProfileMenuOpen(false)} > تنظیمات
*/}
)}
{/* Click outside to close dropdowns */} {(isProfileMenuOpen || isNotificationOpen) && (
{ setIsProfileMenuOpen(false); setIsNotificationOpen(false); }} /> )}
); } export default Header;