const translations = { ar: { qwen_box_title: "مقترحات مؤشرات الأداء", qwen_close_btn: "إغلاق ✕", insights_generate_btn: "إنشاء التحليلات", insights_idle: "اضغطي على الزر لإنشاء تحليل محدث لمؤشرات الأداء.", insights_loading: "جارٍ إعداد التحليلات...", kpi_generating: "جارٍ إعداد مقترحات مؤشرات الأداء...", kpi_suggestions_intro: "فيما يلي ثلاثة مقترحات لمؤشرات أداء جديدة. راجعي تفاصيل كل مقترح قبل استخدامه.", page_title: "منصة الأداء - رؤية 2030", nav_brand: "منصة الأداء", nav_sub: "رؤية 2030", menu_dashboard: "لوحة التحكم", menu_kpis: "مؤشرات الأداء", menu_tasks: "إدارة المهام", menu_reports: "التقارير", user_name: "أحمد العتيبي", user_role: "مدير الأداء", search_placeholder: "البحث عن مؤشرات، مهام، أو تقارير...", dash_title: "لوحة التحكم", dash_subtitle: "نظرة شاملة على مؤشرات الأداء الرئيسية", card_total: "إجمالي المؤشرات", card_completed: "المؤشرات المكتملة", card_delayed: "المؤشرات المتأخرة", card_rate: "نسبة الإنجاز", status_dist: "توزيع الحالات", status_general: "الحالة العامة", status_good: "جيد", status_medium: "متوسط", status_late: "متأخر", kpi_performance: "أداء المؤشرات الرئيسية", perf_evolution: "تطور الأداء (خلال 60 يوماً)", ai_insights_title: "التحليلات الذكية (رؤى تحليلية مولدة من البيانات)", kpi_mgmt_title: "إدارة مؤشرات الأداء", kpi_mgmt_sub: "إنشاء ومتابعة وتحليل مؤشرات الأداء الرئيسية", new_kpi_btn: "إنشاء مؤشر جديد", ai_gen_btn: "توليد مؤشرات بالذكاء الاصطناعي (Qwen)", form_title: "إنشاء مؤشر أداء جديد", label_name: "اسم المؤشر", label_dept: "الجهة المسؤولة", label_desc: "الوصف", label_target: "القيمة المستهدفة", label_date: "تاريخ الإنجاز", btn_cancel: "إلغاء", btn_save: "حفظ المؤشر", target_label: "الهدف", dept_label: "الجهة المسؤولة", progress_label: "نسبة التقدم" }, en: { qwen_box_title: "KPI Recommendations", qwen_close_btn: "Close ✕", insights_generate_btn: "Generate Insights", insights_idle: "Select the button to generate updated performance insights.", insights_loading: "Preparing performance insights...", kpi_generating: "Preparing KPI recommendations...", kpi_suggestions_intro: "Here are three proposed performance indicators. Review each proposal before using it.", page_title: "Performance Platform - Vision 2030", nav_brand: "Performance Platform", nav_sub: "Vision 2030", menu_dashboard: "Dashboard", menu_kpis: "KPIs Management", menu_tasks: "Tasks Management", menu_reports: "Reports", user_name: "Ahmed Al-Otaibi", user_role: "Performance Director", search_placeholder: "Search for KPIs, tasks, or reports...", dash_title: "Dashboard", dash_subtitle: "Comprehensive overview of key performance indicators", card_total: "Total KPIs", card_completed: "Completed KPIs", card_delayed: "Delayed KPIs", card_rate: "Completion Rate", status_dist: "Status Distribution", status_general: "Overall Status", status_good: "Good", status_medium: "Medium", status_late: "Late", kpi_performance: "Key Indicators Performance", perf_evolution: "Performance Evolution (60 Days)", ai_insights_title: "Smart Analytics (AI-Powered Insights)", kpi_mgmt_title: "KPIs Management", kpi_mgmt_sub: "Create, monitor, and analyze key performance indicators", new_kpi_btn: "New KPI", ai_gen_btn: "AI KPI Generation (Qwen)", form_title: "Create New KPI", label_name: "KPI Name", label_dept: "Responsible Dept", label_desc: "Description", label_target: "Target Value", label_date: "Completion Date", btn_cancel: "Cancel", btn_save: "Save KPI", target_label: "Target", dept_label: "Responsible Dept", progress_label: "Progress Rate" } }; let currentLang = "ar"; let currentKpiData = []; let lineChartInstance = null; let doughnutChartInstance = null; let aiInsightsCacheKey = ""; let aiInsightsRequestId = 0; let latestAiKpiSuggestions = []; async function loadExternalData() { const fileName = currentLang === "ar" ? "/data_ar.json" : "/data_en.json"; try { const response = await fetch(fileName); if (!response.ok) { throw new Error(`تعذر تحميل ملف البيانات (HTTP ${response.status})`); } currentKpiData = await response.json(); renderAll(); } catch (error) { console.error("Error fetching KPI JSON:", error); const container = document.getElementById("ai-insights-container"); if (container) { showAiError(container, `تعذر تحميل بيانات المؤشرات: ${error.message}`); } } } function toggleLanguage() { currentLang = currentLang === "ar" ? "en" : "ar"; const root = document.getElementById("html-root"); if (root) { root.lang = currentLang; root.dir = currentLang === "ar" ? "rtl" : "ltr"; } const languageButton = document.getElementById("lang-btn-text"); if (languageButton) { languageButton.innerText = currentLang === "ar" ? "English" : "عربي"; } const searchInput = document.getElementById("search-input"); if (searchInput) { searchInput.placeholder = translations[currentLang].search_placeholder; } document.querySelectorAll("[data-i18n]").forEach(el => { const key = el.getAttribute("data-i18n"); if (translations[currentLang][key]) { el.innerText = translations[currentLang][key]; } }); aiInsightsCacheKey = ""; loadExternalData(); } function toggleNewKpiForm() { const form = document.getElementById("new-kpi-form-card"); if (form) form.classList.toggle("hidden"); } async function callAiApi(path, payload) { const response = await fetch(path, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) }); let result; try { result = await response.json(); } catch { throw new Error( currentLang === "ar" ? "الخادم أعاد استجابة غير مفهومة." : "The server returned an unreadable response." ); } if (!response.ok) { const detail = result.detail || result.error; throw new Error( detail || (currentLang === "ar" ? `تعذر الاتصال بخدمة الذكاء الاصطناعي (HTTP ${response.status}).` : `AI request failed (HTTP ${response.status}).`) ); } return result; } function buildAiKpiPayload() { return currentKpiData.map(k => ({ kpi_id: k.kpi_id || "", kpi_name: k.kpi_name || "", description: k.description || "", department: k.department || "", target: Number(k.target), latest_value: Number(k.latest_value), status: k.status || "", daily_history: Array.isArray(k.daily_history) ? k.daily_history.slice(-15).map(d => ({ date: d.date || "", day: d.day ?? "", value: Number(d.value) })) : [] })); } function appendTextElement(parent, tagName, className, text) { const el = document.createElement(tagName); if (className) el.className = className; el.textContent = text == null ? "" : String(text); parent.appendChild(el); return el; } function showAiError(container, message) { if (!container) return; container.replaceChildren(); const card = document.createElement("div"); card.className = "bg-white p-5 rounded-2xl border border-red-200 shadow-sm text-sm text-red-700"; card.setAttribute("role", "alert"); card.textContent = message; container.appendChild(card); } function renderAiInsights(insights) { const container = document.getElementById("ai-insights-container"); if (!container) return; const colors = [ { border: "border-r-emerald-500", title: "text-emerald-600" }, { border: "border-r-amber-500", title: "text-amber-600" }, { border: "border-r-blue-500", title: "text-blue-600" } ]; container.replaceChildren(); insights.slice(0, 3).forEach((insight, index) => { const card = document.createElement("div"); card.className = `bg-white p-5 rounded-2xl border border-gray-100 shadow-sm border-r-4 ${colors[index % colors.length].border} space-y-2`; appendTextElement( card, "h4", `font-bold ${colors[index % colors.length].title} text-sm`, insight.title || (currentLang === "ar" ? `رؤية تحليلية ${index + 1}` : `Insight ${index + 1}`) ); appendTextElement( card, "p", "text-xs text-gray-700 leading-6", insight.finding || "" ); if (insight.evidence) { appendTextElement( card, "p", "text-xs text-gray-500 leading-6", (currentLang === "ar" ? "الدليل من البيانات: " : "Evidence: ") + insight.evidence ); } if (insight.recommendation) { appendTextElement( card, "p", "text-xs text-teal-800 leading-6", (currentLang === "ar" ? "الإجراء المقترح: " : "Suggested action: ") + insight.recommendation ); } container.appendChild(card); }); } async function updateAiInsights(force = false) { const container = document.getElementById("ai-insights-container"); if (!container) return; if (!currentKpiData || currentKpiData.length === 0) { container.replaceChildren(); return; } const payloadKpis = buildAiKpiPayload(); const requestKey = JSON.stringify({ language: currentLang, kpis: payloadKpis }); if (!force && requestKey === aiInsightsCacheKey) return; aiInsightsCacheKey = requestKey; const requestId = ++aiInsightsRequestId; container.replaceChildren(); const loading = document.createElement("div"); loading.className = "md:col-span-3 bg-white p-5 rounded-2xl border border-teal-100 text-sm text-teal-800"; loading.setAttribute("role", "status"); loading.textContent = "⏳ " + translations[currentLang].insights_loading; container.appendChild(loading); try { const result = await callAiApi("/api/insights", { language: currentLang, kpis: payloadKpis }); if (requestId !== aiInsightsRequestId) return; if (!Array.isArray(result.insights) || result.insights.length !== 3) { throw new Error( currentLang === "ar" ? "لم يرجع النموذج ثلاثة تحليلات بالشكل المتوقع. حاولي مرة أخرى." : "The model did not return exactly three insights. Please try again." ); } renderAiInsights(result.insights); } catch (error) { if (requestId !== aiInsightsRequestId) return; aiInsightsCacheKey = ""; showAiError( container, (currentLang === "ar" ? "تعذر توليد التحليلات: " : "Could not generate insights: ") + error.message ); } } function renderSuggestedKpis(indicators) { const outputContent = document.getElementById("qwen-output-content"); if (!outputContent) return; outputContent.replaceChildren(); appendTextElement( outputContent, "p", "font-bold text-teal-100 mb-3", translations[currentLang].kpi_suggestions_intro ); const grid = document.createElement("div"); grid.className = "grid grid-cols-1 lg:grid-cols-3 gap-4 mt-4"; indicators.forEach((item, index) => { const card = document.createElement("div"); card.className = "bg-white text-gray-800 p-4 rounded-xl shadow-sm space-y-2"; appendTextElement( card, "h5", "font-bold text-teal-800", item.kpi_name || (currentLang === "ar" ? "مؤشر مقترح" : "Suggested KPI") ); appendTextElement( card, "p", "text-xs leading-6 text-gray-600", item.description || "" ); appendTextElement( card, "p", "text-xs", `${currentLang === "ar" ? "الجهة المقترحة: " : "Suggested department: "}${item.department || (currentLang === "ar" ? "تُحدد لاحقًا" : "To be determined")}` ); if (item.formula) { appendTextElement( card, "p", "text-xs leading-5", `${currentLang === "ar" ? "طريقة القياس: " : "Measurement: "}${item.formula}` ); } appendTextElement( card, "p", "text-xs font-bold text-teal-800", `${currentLang === "ar" ? "الهدف المقترح: " : "Suggested target: "}${item.target ?? "—"}%` ); if (item.rationale) { appendTextElement( card, "p", "text-xs leading-5 text-gray-600", `${currentLang === "ar" ? "سبب الاقتراح: " : "Rationale: "}${item.rationale}` ); } if (item.data_needed) { appendTextElement( card, "p", "text-xs leading-5 text-gray-500", `${currentLang === "ar" ? "البيانات المطلوبة: " : "Data needed: "}${item.data_needed}` ); } const button = document.createElement("button"); button.type = "button"; button.className = "w-full mt-2 bg-teal-700 hover:bg-teal-800 text-white text-xs font-bold px-3 py-2 rounded-lg transition"; button.textContent = currentLang === "ar" ? "استخدام هذا الاقتراح" : "Use this suggestion"; button.addEventListener("click", () => applyAiKpiSuggestion(index)); card.appendChild(button); grid.appendChild(card); }); outputContent.appendChild(grid); } function applyAiKpiSuggestion(index) { const item = latestAiKpiSuggestions[index]; if (!item) return; const nameInput = document.getElementById("input-kpi-name"); const deptInput = document.getElementById("input-kpi-dept"); const descInput = document.getElementById("input-kpi-desc"); const targetInput = document.getElementById("input-kpi-target"); const form = document.getElementById("new-kpi-form-card"); if (nameInput) nameInput.value = item.kpi_name || ""; if (deptInput) deptInput.value = item.department || ""; if (descInput) { descInput.value = [ item.description || "", item.formula ? (currentLang === "ar" ? "طريقة القياس: " : "Measurement: ") + item.formula : "", item.rationale ? (currentLang === "ar" ? "مبرر الاقتراح: " : "Rationale: ") + item.rationale : "" ].filter(Boolean).join("\n\n"); } if (targetInput) { targetInput.value = Number.isFinite(Number(item.target)) ? Number(item.target) : 90; } if (form && form.classList.contains("hidden")) { toggleNewKpiForm(); } if (form) { form.scrollIntoView({ behavior: "smooth", block: "start" }); } } async function generateQwenAiKpi() { const resultBox = document.getElementById("qwen-result-box"); const outputContent = document.getElementById("qwen-output-content"); if (!resultBox || !outputContent) { console.error("Qwen output elements were not found in index.html."); return; } resultBox.classList.remove("hidden"); outputContent.replaceChildren(); appendTextElement( outputContent, "p", "text-teal-100", "⏳ " + translations[currentLang].kpi_generating ); if (!currentKpiData || currentKpiData.length === 0) { outputContent.textContent = currentLang === "ar" ? "لا توجد بيانات لتحليلها." : "There is no data to analyze."; return; } try { const result = await callAiApi("/api/generate-kpis", { language: currentLang, kpis: buildAiKpiPayload() }); if (!Array.isArray(result.indicators) || result.indicators.length !== 3) { throw new Error( currentLang === "ar" ? "لم يرجع النموذج ثلاثة مؤشرات بالشكل المتوقع. حاولي مرة أخرى." : "The model did not return exactly three KPIs. Please try again." ); } latestAiKpiSuggestions = result.indicators; renderSuggestedKpis(latestAiKpiSuggestions); } catch (error) { outputContent.replaceChildren(); const errorBox = document.createElement("div"); errorBox.className = "bg-red-50 text-red-800 rounded-xl p-4"; errorBox.setAttribute("role", "alert"); errorBox.textContent = (currentLang === "ar" ? "تعذر توليد المؤشرات: " : "Could not generate KPIs: ") + error.message; outputContent.appendChild(errorBox); console.error("Qwen KPI generation error:", error); } } function saveNewKpi() { const nameInput = document.getElementById("input-kpi-name"); const deptInput = document.getElementById("input-kpi-dept"); const descInput = document.getElementById("input-kpi-desc"); const targetInput = document.getElementById("input-kpi-target"); const name = nameInput ? nameInput.value.trim() : ""; const dept = deptInput ? deptInput.value : ""; const desc = descInput ? descInput.value : ""; const target = parseFloat(targetInput ? targetInput.value : "") || 90; if (!name) { alert( currentLang === "ar" ? "الرجاء إدخال اسم المؤشر" : "Please enter KPI name" ); return; } const newKpi = { kpi_id: "KPI_0" + (currentKpiData.length + 1), kpi_name: name, description: desc || ( currentLang === "ar" ? "وصف المؤشر الجديد" : "New KPI description" ), department: dept || ( currentLang === "ar" ? "الإدارة العامة" : "General Department" ), target, status: currentLang === "ar" ? "جيد" : "Good", latest_value: Math.round(target * 0.9), daily_history: Array.from( { length: 60 }, (_, i) => ({ day: i + 1, value: Math.round(target * 0.8) }) ) }; currentKpiData.push(newKpi); const form = document.getElementById("new-kpi-form-card"); if (form && !form.classList.contains("hidden")) { toggleNewKpiForm(); } if (nameInput) nameInput.value = ""; if (deptInput) deptInput.value = ""; if (descInput) descInput.value = ""; if (targetInput) targetInput.value = ""; aiInsightsCacheKey = ""; renderAll(); } function updateSummaryCards() { if (!currentKpiData || currentKpiData.length === 0) return; let goodCount = 0; let mediumCount = 0; let lateCount = 0; let totalValSum = 0; currentKpiData.forEach(item => { totalValSum += Number(item.latest_value) || 0; const statusStr = String(item.status || "").toLowerCase(); if (statusStr.includes("good") || statusStr.includes("جيد")) { goodCount++; } else if ( statusStr.includes("needs") || statusStr.includes("متابعة") || statusStr.includes("متوسط") ) { mediumCount++; } else { lateCount++; } }); const totalKpis = currentKpiData.length; const avgRate = (totalValSum / totalKpis).toFixed(1); const setText = (id, value) => { const element = document.getElementById(id); if (element) element.innerText = value; }; setText("card-total-val", totalKpis); setText("card-good-val", goodCount); setText("card-late-val", lateCount); setText("card-avg-val", `${avgRate}%`); setText("count-good", goodCount); setText("count-medium", mediumCount); setText("count-late", lateCount); renderDoughnutChart(goodCount, mediumCount, lateCount); } function renderDoughnutChart(good, medium, late) { const canvas = document.getElementById("statusDoughnutChart"); if (!canvas) return; const ctx = canvas.getContext("2d"); if (doughnutChartInstance) { doughnutChartInstance.destroy(); } doughnutChartInstance = new Chart(ctx, { type: "doughnut", data: { labels: [ translations[currentLang].status_good, translations[currentLang].status_medium, translations[currentLang].status_late ], datasets: [{ data: [good, medium, late], backgroundColor: ["#10B981", "#F59E0B", "#EF4444"], borderWidth: 2, hoverOffset: 4 }] }, options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: false } }, cutout: "75%" } }); } function renderDashboardProgress() { const container = document.getElementById("dashboard-progress-bars"); if (!container) return; container.innerHTML = ""; currentKpiData.forEach(item => { const value = Number(item.latest_value) || 0; const color = value >= 80 ? "bg-emerald-500" : value >= 60 ? "bg-amber-500" : "bg-red-500"; container.innerHTML += `
${item.description}