import { BrainCircuit, ChevronDown, ChevronUp, Database, Key, LoaderCircle, RefreshCw, Sprout, TrendingDown, TrendingUp, Zap, } from "lucide-react"; import moment from "moment-jalaali"; import { useCallback, useEffect, useRef, useState } from "react"; import toast from "react-hot-toast"; import { Badge } from "~/components/ui/badge"; import { BaseCard } from "~/components/ui/base-card"; import { Button } from "~/components/ui/button"; import { Card, CardContent } from "~/components/ui/card"; import { Checkbox } from "~/components/ui/checkbox"; import { CustomBarChart } from "~/components/ui/custom-bar-chart"; import { Dialog, DialogContent, DialogHeader, DialogTitle, } from "~/components/ui/dialog"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from "~/components/ui/table"; import { useStoredDate } from "~/hooks/useStoredDate"; import { reportingApi } from "~/lib/reporting-api"; import { EventBus, formatCurrency, formatNumber } from "~/lib/utils"; import type { CalendarDate } from "~/types/util.type"; import { DashboardLayout } from "../layout"; moment.loadPersian({ usePersianDigits: true }); interface SortConfig { field: string; direction: "asc" | "desc"; } interface StatsCard { id: string; title: string; value: string; description?: string; icon: React.ReactNode; color: string; } // Raw API response interface for digital innovation metrics interface DigitalInnovationMetrics { count_innovation_digital_projects: string; increased_revenue: string; increased_revenue_percent: string; reduce_costs: string; reduce_costs_percent: string; reduce_energy_consumption: string; reduce_energy_consumption_percent: string; resource_productivity: string; resource_productivity_percent: string; average_project_score?: number; } // Normalized interface for digital innovation stats interface DigitalInnovationStats { // totalDigitalProjects: number; increasedRevenue: number; increasedRevenuePercent: number; reduceCosts: number; reduceCostsPercent: number; reduceEnergyConsumption: number; reduceEnergyConsumptionPercent: number; resourceProductivity: number | null; resourceProductivityPercent: number | null; avarageProjectScore: number; countInnovationDigitalProjects: number; } enum DigitalCardLabel { decreasCost = "کاهش هزینه‌ها", increaseRevenue = "افزایش درآمد", performance = "بهره‌وری منابع", decreaseEnergy = "کاهش مصرف انرژی", } enum projectStatus { propozal = "پروپوزال", contract = "پیشنویس قرارداد", inprogress = "در حال انجام", stop = "متوقف شده", mafasa = "مرحله مفاصا", finish = "پایان یافته", } interface ProcessInnovationData { WorkflowID: number; project_id: string; desired_strategy: string; digital_capability: string; digital_competence: string; digital_puberty_elements: string; innovation_cost_reduction: number | string; operational_plan: string; originality_digital_solution: string; project_description: string; project_no: string; project_rating: number | string; project_status: string; actual_progress_percent: number | null; reduce_costs_percent: number; title: string; } interface HouseItem { index: number; color?: string; style?: string; } interface ListItem { label: string; development: number | null; house: HouseItem[]; } const columns = [ // { key: "select", label: "", sortable: false, width: "50px" }, { key: "project_no", label: "شماره پروژه", sortable: true, width: "140px" }, { key: "title", label: "عنوان پروژه", sortable: true, width: "400px" }, { key: "project_status", label: "وضعیت پروژه", sortable: true, width: "140px", }, { key: "project_rating", label: "امتیاز پروژه", sortable: true, width: "140px", }, { key: "details", label: "جزئیات پروژه", sortable: false, width: "140px" }, ]; export function DigitalInnovationPage() { const [projects, setProjects] = useState([]); const [loading, setLoading] = useState(false); const [loadingMore, setLoadingMore] = useState(false); const [currentPage, setCurrentPage] = useState(1); const [pageSize] = useState(20); const [hasMore, setHasMore] = useState(true); const [date, setDate] = useStoredDate(); const [actualTotalCount, setActualTotalCount] = useState(0); const [statsLoading, setStatsLoading] = useState(false); const [rating, setRating] = useState([]); const [dialogInfo, setDialogInfo] = useState(); const [stats, setStats] = useState({ increasedRevenue: 0, increasedRevenuePercent: 0, reduceCosts: 0, reduceCostsPercent: 0, reduceEnergyConsumption: 0, reduceEnergyConsumptionPercent: 0, resourceProductivity: null, resourceProductivityPercent: null, avarageProjectScore: 0, countInnovationDigitalProjects: 0, }); const [sortConfig, setSortConfig] = useState({ field: "start_date", direction: "asc", }); const [selectedProjects, setSelectedProjects] = useState>( new Set() ); const [detailsDialogOpen, setDetailsDialogOpen] = useState(false); // const [avarage, setAvarage] = useState(0); const observerRef = useRef(null); const fetchingRef = useRef(false); const scrollTimeoutRef = useRef(null); const scrollContainerRef = useRef(null); // Selection handlers const handleSelectAll = () => { if (selectedProjects.size === projects.length) { setSelectedProjects(new Set()); } else { setSelectedProjects(new Set(projects.map((p) => p.project_id))); } }; const handleProjectDetails = (project: ProcessInnovationData) => { const progress = project.actual_progress_percent == null ? null : Math.min(100, Math.max(0, Number(project.actual_progress_percent))); const model: ListItem = { label: project.operational_plan?.trim() || project.title, development: progress, house: Array.from({ length: 10 }, (_, index) => { const segmentStart = index * 10; const filledPercent = progress == null ? 0 : Math.min(100, Math.max(0, (progress - segmentStart) * 10)); return { index, style: filledPercent === 100 ? "#34d399" : filledPercent > 0 ? `linear-gradient(to right, #34d399 0%, #34d399 ${filledPercent}%, #6b7280 ${filledPercent}%, #6b7280 100%)` : "#6b7280", }; }), }; setRating([model]); setDialogInfo(project); setDetailsDialogOpen(true); }; // ...existing code... const statsCards: StatsCard[] = [ { id: "production-stops-prevention", title: DigitalCardLabel.decreasCost, value: formatNumber(stats.reduceCosts.toFixed?.(1) ?? stats.reduceCosts), description: "میلیون ریال کاهش یافته", icon: , color: "text-pr-green", }, { id: "bottleneck-removal", title: DigitalCardLabel.increaseRevenue, value: formatNumber(stats.increasedRevenue), description: "میلیون ریال افزایش یافته", icon: , color: "text-pr-green", }, { id: "currency-reduction", title: DigitalCardLabel.performance, value: stats.resourceProductivity == null ? formatNumber(0) : formatNumber(stats.resourceProductivity.toFixed(0)), description: "تن بازیافت یا بازیابی‌شده", icon: , color: "text-pr-green", }, { id: "frequent-failures-reduction", title: DigitalCardLabel.decreaseEnergy, value: formatNumber( stats.reduceEnergyConsumption.toFixed?.(1) ?? stats.reduceEnergyConsumption ), description: "مگاوات کاهش یافته", icon: , color: "text-pr-green", }, ]; const fetchTable = async (reset = false) => { if (fetchingRef.current) { return; } try { fetchingRef.current = true; if (reset) { setLoading(true); setCurrentPage(1); } else { setLoadingMore(true); } const pageToFetch = reset ? 1 : currentPage; const response = await reportingApi.digitalProjects( date?.start, date?.end, pageToFetch, pageSize, sortConfig.field, sortConfig.direction, ); if (reset) setProjects(response.items); else setProjects((prev) => [...prev, ...response.items]); setActualTotalCount(response.totalCount); setHasMore(pageToFetch * response.pageSize < response.totalCount); } catch (error) { console.error("Error fetching projects:", error); toast.error("خطا در دریافت اطلاعات پروژه‌ها"); if (reset) { setProjects([]); // setTotalCount(0); } setHasMore(false); } finally { setLoading(false); setLoadingMore(false); fetchingRef.current = false; } }; const loadMore = useCallback(() => { if (hasMore && !loading && !loadingMore && !fetchingRef.current) { setCurrentPage((prev) => prev + 1); } }, [hasMore, loading, loadingMore]); useEffect(() => { if (date?.start && date?.end) { fetchTable(true); fetchTotalCount(); fetchStats(); } }, [sortConfig, date]); useEffect(() => { const handler = (date: CalendarDate) => { if (date) setDate(date); }; EventBus.on("dateSelected", handler); return () => { EventBus.off("dateSelected", handler); }; }, []); useEffect(() => { if (currentPage > 1 && date?.start && date?.end) { fetchTable(false); } }, [currentPage]); // Infinite scroll observer with debouncing useEffect(() => { const scrollContainer = scrollContainerRef.current; const handleScroll = () => { if (!scrollContainer || !hasMore || loadingMore || fetchingRef.current) return; // Clear previous timeout if (scrollTimeoutRef.current) { clearTimeout(scrollTimeoutRef.current); } // Debounce scroll events scrollTimeoutRef.current = setTimeout(() => { const { scrollTop, scrollHeight, clientHeight } = scrollContainer; const scrollPercentage = (scrollTop + clientHeight) / scrollHeight; // Trigger load more when scrolled to 95% of the container if (scrollPercentage >= 0.95) { loadMore(); } }, 150); }; if (scrollContainer) { scrollContainer.addEventListener("scroll", handleScroll, { passive: true, }); } return () => { if (scrollContainer) { scrollContainer.removeEventListener("scroll", handleScroll); } if (scrollTimeoutRef.current) { clearTimeout(scrollTimeoutRef.current); } }; }, [loadMore, hasMore, loadingMore]); const handleSort = (field: string) => { fetchingRef.current = false; setSortConfig((prev) => ({ field, direction: prev.field === field && prev.direction === "asc" ? "desc" : "asc", })); fetchTotalCount(date?.start, date?.end); fetchStats(); setCurrentPage(1); setProjects([]); setHasMore(true); }; const fetchTotalCount = async (startDate?: string, endDate?: string) => { try { const response = await reportingApi.digitalProjects(startDate, endDate, 1, 1); setActualTotalCount(response.totalCount); } catch (error) { console.error("Error fetching total count:", error); } }; // Fetch aggregated stats from backend call API (innovation_process_function) const fetchStats = async () => { try { setStatsLoading(true); const payload = await reportingApi.digitalReport( date?.start, date?.end, selectedProjects.size ? Array.from(selectedProjects) : undefined, ); const parseNum = (v: unknown): number => { if (v == null) return 0; if (typeof v === "number") return v; if (typeof v === "string") { const cleaned = v.replace(/,/g, "").trim(); const n = parseFloat(cleaned); return isNaN(n) ? 0 : n; } return 0; }; const normalized: DigitalInnovationStats = { increasedRevenue: parseNum(payload?.incomeIncrease?.value), increasedRevenuePercent: parseNum(payload?.incomeIncrease?.percent), reduceCosts: parseNum(payload?.costReduction?.value), reduceCostsPercent: parseNum(payload?.costReduction?.percent), reduceEnergyConsumption: parseNum(payload?.energyConsumptionReduction?.value), reduceEnergyConsumptionPercent: parseNum(payload?.energyConsumptionReduction?.percent), resourceProductivity: payload?.resourceProductivity?.value == null ? null : parseNum(payload.resourceProductivity.value), resourceProductivityPercent: payload?.resourceProductivity?.percent == null ? null : parseNum(payload.resourceProductivity.percent), avarageProjectScore: parseNum(payload?.averageProjectScore), countInnovationDigitalProjects: parseNum(payload?.projectCount), }; setActualTotalCount(normalized.countInnovationDigitalProjects); setStats(normalized); } catch (error) { console.error("Error fetching stats:", error); } finally { setStatsLoading(false); } }; // const handleRefresh = () => { // fetchingRef.current = false; // setCurrentPage(1); // setProjects([]); // setHasMore(true); // fetchTable(true); // fetchTotalCount(); // fetchStats(); // }; // const renderProgress = useMemo(() => { // const total = 10; // for (let i = 0; i < rating.length; i++) { // const currentElm = rating[i]; // currentElm.house = []; // const greenBoxes = Math.floor((total * currentElm.development) / 100); // const partialPercent = // (total * currentElm.development) / 100 - greenBoxes; // for (let j = 0; j < greenBoxes; j++) { // currentElm.house.push({ // index: j, // color: "!bg-emerald-400", // }); // } // if (partialPercent != 0 && greenBoxes != 10) // currentElm.house.push({ // index: greenBoxes + 1, // style: `linear-gradient( // to right, // oklch(76.5% 0.177 163.223) 0%, // oklch(76.5% 0.177 163.223) ${partialPercent * 100}%, // oklch(55.1% 0.027 264.364) ${partialPercent * 100}%, // oklch(55.1% 0.027 264.364) 100% // )`, // }); // } // }, [rating]); const statusColor = (status: projectStatus): any => { let el = null; switch (status) { case projectStatus.contract: el = "teal"; break; case projectStatus.finish: el = "info"; break; case projectStatus.stop: el = "warning"; break; case projectStatus.inprogress: el = "teal"; break; case projectStatus.mafasa: el = "destructive"; break; case projectStatus.propozal: el = "info"; } return el; }; const renderCellContent = (item: any, column: any) => { const value = item[column.key as keyof ProcessInnovationData]; switch (column.key) { case "select": return ( { const next = new Set(selectedProjects); if (next.has(item.project_id)) next.delete(item.project_id); else next.add(item.project_id); setSelectedProjects(next); }} className="data-[state=checked]:bg-emerald-600 data-[state=checked]:border-emerald-600" /> ); case "details": return ( ); case "amount_currency_reduction": return ( {formatCurrency(String(value))} ); case "project_no": return ( {value == null || value === "" ? "-" : String(value)} ); case "title": return ( {String(value)} ); case "project_status": return (
{String(value)}
); case "project_rating": return ( {formatNumber(String(value))} ); case "reduce_prevention_production_stops": case "throat_removal": case "Reduce_rate_failure": return ( {formatNumber(String(value))} ); default: return {String(value) || "-"}; } }; return (
{/* Stats Cards */}
{/* Stats Grid */}
{loading ? // Loading skeleton for stats cards - matching new design Array.from({ length: 4 }).map((_, index) => (
)) : statsCards.map((card) => (

{card.title}

{card.icon}

{card.value}

{card.description}

))}
{/* Process Impacts Chart */} {/* */}
{/* Data Table */}
{columns.map((column) => ( {column.key === "select" ? (
0 } onCheckedChange={handleSelectAll} className="data-[state=checked]:bg-emerald-600 data-[state=checked]:border-emerald-600" />
) : column.sortable ? ( ) : ( column.label )}
))}
{loading ? ( // Skeleton loading rows (compact) Array.from({ length: 10 }).map((_, index) => ( {columns.map((column) => (
))} )) ) : projects.length === 0 ? ( هیچ پروژه‌ای یافت نشد ) : ( projects.map((project, index) => ( {columns.map((column) => ( {renderCellContent(project, column)} ))} )) )}
{/* Infinite scroll trigger */}
{loadingMore && (
)}
{/* Footer */}
کل پروژه‌ها:{" "} {formatNumber(actualTotalCount)}
میانگین:{" "} {formatNumber( ((stats.avarageProjectScore ?? 0) as number).toFixed?.(1) ?? 0 )}
{/*
کل پروژه ها : {formatNumber(actualTotalCount)}
میانگین :‌
{formatNumber( ((stats.avarageProjectScore ?? 0) as number).toFixed?.( 1 ) ?? 0 )}
*/}
{/* Project Details Dialog */} شرح پروژه
{dialogInfo?.title}

{dialogInfo?.project_description}

ویژگی های اصلی پروژه:
شایستگی دیجیتال:
{dialogInfo?.digital_capability}
اصالت راهکار دیجیتال:
{dialogInfo?.digital_competence}
المان های بلوغ دیجیتال:
{dialogInfo?.digital_puberty_elements}
توسعه قابلیت های دیجیتال:{" "}
{dialogInfo?.digital_capability}
برنامه های عملیاتی مرتبط:
{dialogInfo?.operational_plan}
استراتژی های مورد نظر:
{dialogInfo?.desired_strategy}
{/*
قابلیت شماره یک
*/} {/*
قابلیت شماره یک
*/}
کاهش هزینه ها
%{" "} {formatNumber( ( Math.round( dialogInfo?.reduce_costs_percent! * 100 ) / 100 ).toFixed(2) )} درصد به کل هزینه ها
{formatNumber(+dialogInfo?.innovation_cost_reduction!)} میلیون ریال
عنوان فرآیند درصد پیشرفت
{rating.map((el, index) => { return (
{el.label}
{el.house.map((segment) => ( ))}
); })}
); } export default DigitalInnovationPage;