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 apiService from "~/lib/api"; 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; fromMonth?: 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 projectManagerRoute = "/dashboard/project-management"; const [currentYear, setCurrentYear] = useState({ since: jy, until: jy, }); const [selectedDate, setSelectedDate] = useState({}); useEffect(() => { const storedDate = localStorage.getItem("dateSelected"); if (storedDate) { const parsedDate = JSON.parse(storedDate); setSelectedDate(parsedDate); const sinceYear = parsedDate.start ? parseInt(parsedDate.start.split("/")[0], 10) : jy; const untilYear = parsedDate.end ? parseInt(parsedDate.end.split("/")[0], 10) : jy; setCurrentYear({ since: sinceYear, until: untilYear }); } else { const defaultDate = { sinceMonth: "بهار", fromMonth: "زمستان", start: `${jy}/01/01`, end: `${jy}/12/30`, }; setSelectedDate(defaultDate); localStorage.setItem("dateSelected", JSON.stringify(defaultDate)); setCurrentYear({ since: jy, until: jy }); } }, []); const redirectHandler = async () => { try { const getData = await apiService.post("/GenerateSsoCode"); const url = `https://inogen-bpms.pelekan.org/redirect/${getData.data}`; window.open(url, "_blank"); } catch (error) { console.log(error); } }; 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}`, fromMonth: 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); const fetchableColumns = columns.filter((c) => !c.computed); const outputFields = fetchableColumns.map((c) => c.apiField ?? c.key); const response = await apiService.select({ ProcessName: "project", OutputFields: outputFields, Conditions: [ ["start_date", ">=", selectedDate?.start || null, "and"], ["start_date", "<=", selectedDate?.end || null], ], }); const parsedData = JSON.parse(response.data); setExcelLoading(false); return parsedData; }; 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?.fromMonth} {handleDataValue(currentYear.until)}
) : ( "تاریخ مورد نظر خود را انتخاب نمایید" )}
{openCalendar && (
)}
{/* Right Section */}
{/* User Menu */}
{location.pathname === projectManagerRoute ? (
دانلود فایل اکسل
) : ( "" )} {user?.id === 2041 && ( )}
{/* 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;