Upload index.html
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856<!DOCTYPE html><html lang="ar" dir="rtl" id="html-root"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title id="page-title">منصة الأداء - رؤية 2030</title> <!-- Tailwind CSS --> <script src="https://cdn.tailwindcss.com"></script> <!-- Chart.js للرسوم البيانية --> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <!-- Lucide Icons للأيقونات الاحترافية --> <script src="https://unpkg.com/lucide@latest"></script> <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700&display=swap" rel="stylesheet"> <style> body { font-family: 'Cairo', sans-serif; background-color: #f8fafc; } </style></head><body class="flex h-screen overflow-hidden">
<!-- القائمة الجانبية (Sidebar) --> <aside class="w-64 bg-white border-l border-gray-200 flex flex-col justify-between hidden md:flex" id="sidebar"> <div> <!-- ترويسة الشعار --> <div class="p-6 flex items-center justify-between border-b border-gray-100"> <div class="text-right rtl:text-right ltr:text-left"> <h1 class="text-lg font-bold text-teal-700" id="nav-brand">منصة الأداء</h1> <p class="text-xs text-gray-400" id="nav-sub">رؤية 2030</p> </div> <div class="w-9 h-9 rounded-xl bg-teal-600 flex items-center justify-center text-white font-bold"> <i data-lucide="sparkles" class="w-5 h-5"></i> </div> </div> <!-- روابط التنقل --> <nav class="p-4 space-y-2"> <button onclick="switchTab('dashboard')" id="btn-dashboard" class="w-full flex items-center gap-3 px-4 py-3 rounded-xl text-sm font-semibold transition bg-teal-700 text-white shadow-sm"> <i data-lucide="layout-dashboard" class="w-5 h-5"></i> <span data-i18n="menu_dashboard">لوحة التحكم</span> </button> <button onclick="switchTab('kpis')" id="btn-kpis" class="w-full flex items-center gap-3 px-4 py-3 rounded-xl text-sm font-semibold transition text-gray-600 hover:bg-gray-50"> <i data-lucide="line-chart" class="w-5 h-5"></i> <span data-i18n="menu_kpis">مؤشرات الأداء</span> </button> <button class="w-full flex items-center gap-3 px-4 py-3 rounded-xl text-sm font-semibold text-gray-600 hover:bg-gray-50"> <i data-lucide="check-square" class="w-5 h-5"></i> <span data-i18n="menu_tasks">إدارة المهام</span> </button> <button class="w-full flex items-center gap-3 px-4 py-3 rounded-xl text-sm font-semibold text-gray-600 hover:bg-gray-50"> <i data-lucide="file-text" class="w-5 h-5"></i> <span data-i18n="menu_reports">التقارير</span> </button> </nav> </div>
<!-- معلومات المستخدم في أسفل القائمة --> <div class="p-4 border-t border-gray-100 flex items-center gap-3"> <div class="w-10 h-10 rounded-full bg-teal-700 text-white flex items-center justify-center font-bold">أ</div> <div class="text-right rtl:text-right ltr:text-left"> <h4 class="text-sm font-bold text-gray-800" data-i18n="user_name">أحمد العتيبي</h4> <p class="text-xs text-gray-500" data-i18n="user_role">مدير الأداء</p> </div> </div> </aside>
<!-- المحتوى الرئيسي --> <main class="flex-1 flex flex-col h-screen overflow-y-auto"> <!-- الشريط العلوي (Navbar) --> <header class="bg-white border-b border-gray-200 px-8 py-4 flex items-center justify-between sticky top-0 z-10"> <div class="flex items-center gap-4 w-1/3 relative"> <input type="text" id="search-input" placeholder="البحث عن مؤشرات، مهام، أو تقارير..." class="w-full bg-gray-50 border border-gray-200 rounded-xl px-4 py-2 pr-10 text-sm focus:outline-none focus:border-teal-600"> <i data-lucide="search" class="w-4 h-4 text-gray-400 absolute right-3 top-3"></i> </div> <div class="flex items-center gap-4"> <button onclick="toggleLanguage()" class="bg-gray-100 hover:bg-gray-200 text-gray-700 font-bold px-3 py-1.5 rounded-xl text-xs transition flex items-center gap-1.5"> <i data-lucide="globe" class="w-4 h-4"></i> <span id="lang-btn-text">English</span> </button> <i data-lucide="bell" class="w-5 h-5 text-gray-500 cursor-pointer"></i> </div> </header>
<!-- محتوى التطبيق --> <div class="p-8 space-y-8">
<!-- ================= الواجهة الأولى: لوحة التحكم ================= --> <section id="view-dashboard" class="space-y-8"> <div> <h2 class="text-xl font-bold text-gray-800" data-i18n="dash_title">لوحة التحكم</h2> <p class="text-sm text-gray-500" data-i18n="dash_subtitle">نظرة شاملة على مؤشرات الأداء الرئيسية</p> </div>
<!-- البطاقات الأربع العلوية --> <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6"> <div class="bg-white p-6 rounded-2xl border border-gray-100 shadow-sm flex flex-col justify-between"> <div class="flex justify-between items-start"> <div class="w-12 h-12 rounded-2xl bg-teal-50 flex items-center justify-center text-teal-600"> <i data-lucide="target" class="w-6 h-6"></i> </div> <span class="text-xs font-bold text-emerald-600 bg-emerald-50 px-2 py-1 rounded-lg">12%+ ↗</span> </div> <div class="mt-4"> <h3 class="text-2xl font-bold text-gray-800" id="card-total-val">0</h3> <p class="text-xs text-gray-500 mt-1" data-i18n="card_total">إجمالي المؤشرات</p> </div> </div>
<div class="bg-white p-6 rounded-2xl border border-gray-100 shadow-sm flex flex-col justify-between"> <div class="flex justify-between items-start"> <div class="w-12 h-12 rounded-2xl bg-emerald-50 flex items-center justify-center text-emerald-600"> <i data-lucide="check-circle-2" class="w-6 h-6"></i> </div> <span class="text-xs font-bold text-emerald-600 bg-emerald-50 px-2 py-1 rounded-lg">8%+ ↗</span> </div> <div class="mt-4"> <h3 class="text-2xl font-bold text-gray-800" id="card-good-val">0</h3> <p class="text-xs text-gray-500 mt-1" data-i18n="card_completed">المؤشرات المكتملة</p> </div> </div>
<div class="bg-white p-6 rounded-2xl border border-gray-100 shadow-sm flex flex-col justify-between"> <div class="flex justify-between items-start"> <div class="w-12 h-12 rounded-2xl bg-red-50 flex items-center justify-center text-red-600"> <i data-lucide="alert-circle" class="w-6 h-6"></i> </div> <span class="text-xs font-bold text-red-600 bg-red-50 px-2 py-1 rounded-lg">2%- ↘</span> </div> <div class="mt-4"> <h3 class="text-2xl font-bold text-gray-800" id="card-late-val">0</h3> <p class="text-xs text-gray-500 mt-1" data-i18n="card_delayed">المؤشرات المتأخرة</p> </div> </div>
<div class="bg-white p-6 rounded-2xl border border-gray-100 shadow-sm flex flex-col justify-between"> <div class="flex justify-between items-start"> <div class="w-12 h-12 rounded-2xl bg-teal-50 flex items-center justify-center text-teal-600"> <i data-lucide="trending-up" class="w-6 h-6"></i> </div> <span class="text-xs font-bold text-teal-600 bg-teal-50 px-2 py-1 rounded-lg">5%+ ↗</span> </div> <div class="mt-4"> <h3 class="text-2xl font-bold text-gray-800" id="card-avg-val">0%</h3> <p class="text-xs text-gray-500 mt-1" data-i18n="card_rate">نسبة الإنجاز</p> </div> </div> </div>
<!-- قسم توزيع الحالات + أداء المؤشرات الديناميكي --> <div class="grid grid-cols-1 lg:grid-cols-3 gap-6"> <div class="bg-white p-6 rounded-2xl border border-gray-100 shadow-sm"> <h3 class="font-bold text-gray-800 mb-4" data-i18n="status_dist">توزيع الحالات</h3> <div class="flex flex-col items-center justify-center py-4"> <div class="w-40 h-40"> <canvas id="statusDoughnutChart"></canvas> </div> </div> <div class="flex justify-around text-xs text-gray-600 mt-4"> <span class="flex items-center gap-1"><i class="w-2.5 h-2.5 rounded-full bg-emerald-500 inline-block"></i> <span data-i18n="status_good">جيد</span> (<span id="count-good">0</span>)</span> <span class="flex items-center gap-1"><i class="w-2.5 h-2.5 rounded-full bg-amber-500 inline-block"></i> <span data-i18n="status_medium">متوسط</span> (<span id="count-medium">0</span>)</span> <span class="flex items-center gap-1"><i class="w-2.5 h-2.5 rounded-full bg-red-500 inline-block"></i> <span data-i18n="status_late">متأخر</span> (<span id="count-late">0</span>)</span> </div> </div>
<div class="bg-white p-6 rounded-2xl border border-gray-100 shadow-sm lg:col-span-2"> <h3 class="font-bold text-gray-800 mb-6" data-i18n="kpi_performance">أداء المؤشرات الرئيسية</h3> <div id="dashboard-progress-bars" class="space-y-5"></div> </div> </div>
<!-- مخطط تطور الأداء الخطي --> <div class="bg-white p-6 rounded-2xl border border-gray-100 shadow-sm space-y-4"> <h3 class="font-bold text-gray-800" data-i18n="perf_evolution">تطور الأداء (خلال 60 يوماً)</h3> <div class="w-full h-64"> <canvas id="performanceChart"></canvas> </div> </div>
<!-- التحليلات الذكية --> <div class="bg-teal-50/50 p-6 rounded-2xl border border-teal-100 space-y-4"> <div class="flex flex-wrap items-center justify-between gap-3"> <h3 class="font-bold text-gray-800 text-lg flex items-center gap-2"> <i data-lucide="sparkles" class="w-5 h-5 text-teal-600"></i> <span data-i18n="ai_insights_title">التحليلات الذكية</span> </h3> <button id="show-ai-insights-btn" type="button" onclick="toggleAiInsights()" class="bg-teal-700 hover:bg-teal-800 text-white px-4 py-2 rounded-xl text-sm font-bold shadow-sm transition flex items-center gap-2"> <i data-lucide="sparkles" class="w-4 h-4"></i> <span data-i18n="show_ai_insights_btn">إظهار التحليلات بالذكاء الاصطناعي</span> </button> </div> <div class="grid grid-cols-1 md:grid-cols-3 gap-6 hidden" id="ai-insights-container" aria-live="polite"></div> </div> </section>
<!-- ================= الواجهة الثانية: إدارة المؤشرات ================= --> <section id="view-kpis" class="space-y-6 hidden"> <div class="flex justify-between items-center"> <div> <h2 class="text-xl font-bold text-gray-800" data-i18n="kpi_mgmt_title">إدارة مؤشرات الأداء</h2> <p class="text-sm text-gray-500" data-i18n="kpi_mgmt_sub">إنشاء ومتابعة وتحليل مؤشرات الأداء الرئيسية</p> </div> <div class="flex items-center gap-3"> <button onclick="toggleNewKpiForm()" class="bg-teal-700 text-white px-4 py-2 rounded-xl text-sm font-bold shadow-sm hover:bg-teal-800 transition flex items-center gap-1.5"> <i data-lucide="plus" class="w-4 h-4"></i> إنشاء مؤشر جديد </button> <!-- زر توليد Qwen التحليلي الفوري والمستند للداتا --> <button onclick="generateQwenAiKpi()" class="bg-teal-50 text-teal-700 border border-teal-200 px-4 py-2 rounded-xl text-sm font-bold shadow-sm hover:bg-teal-100 transition flex items-center gap-1.5"> <i data-lucide="sparkles" class="w-4 h-4 text-teal-600"></i> <span data-i18n="ai_gen_btn">توليد مؤشرات بالذكاء الاصطناعي (Qwen)</span> </button> </div> </div>
<!-- صندوق عرض رد تحليل نموذج Qwen الفعلي المربوط بالداتا --> <div id="qwen-result-box" class="bg-teal-900 text-white p-6 rounded-2xl shadow-lg hidden space-y-3"> <div class="flex justify-between items-center border-b border-teal-700 pb-3"> <h4 class="font-bold text-teal-200 flex items-center gap-2">✨ تحليل وتوليد نموذج Qwen 2.5 (مستند لبيانات الملف)</h4> <button onclick="document.getElementById('qwen-result-box').classList.add('hidden')" class="text-teal-300 hover:text-white text-xs">إغلاق ✕</button> </div> <div id="qwen-output-content" class="text-sm whitespace-pre-line leading-relaxed text-teal-50 space-y-2"> جاري تحليل البيانات عبر محرك Qwen الذكي... </div> </div>
<!-- نموذج إنشاء مؤشر جديد --> <div id="new-kpi-form-card" class="bg-white p-6 rounded-2xl border border-gray-100 shadow-sm space-y-6 hidden"> <h3 class="font-bold text-gray-800 text-lg" data-i18n="form_title">إنشاء مؤشر أداء جديد</h3> <div class="grid grid-cols-1 md:grid-cols-2 gap-6"> <div class="space-y-2"> <label class="text-xs font-bold text-gray-700" data-i18n="label_name">اسم المؤشر</label> <input type="text" id="input-kpi-name" placeholder="أدخل اسم المؤشر" class="w-full bg-gray-50 border border-gray-200 rounded-xl px-4 py-2 text-sm focus:outline-none focus:border-teal-600"> </div> <div class="space-y-2"> <label class="text-xs font-bold text-gray-700" data-i18n="label_dept">الجهة المسؤولة</label> <input type="text" id="input-kpi-dept" placeholder="أدخل اسم الجهة" class="w-full bg-gray-50 border border-gray-200 rounded-xl px-4 py-2 text-sm focus:outline-none focus:border-teal-600"> </div> </div> <div class="space-y-2"> <label class="text-xs font-bold text-gray-700" data-i18n="label_desc">الوصف</label> <textarea id="input-kpi-desc" rows="3" placeholder="أدخل وصف المؤشر" class="w-full bg-gray-50 border border-gray-200 rounded-xl px-4 py-2 text-sm focus:outline-none focus:border-teal-600"></textarea> </div> <div class="grid grid-cols-1 md:grid-cols-2 gap-6"> <div class="space-y-2"> <label class="text-xs font-bold text-gray-700" data-i18n="label_target">القيمة المستهدفة</label> <input type="number" id="input-kpi-target" placeholder="90" class="w-full bg-gray-50 border border-gray-200 rounded-xl px-4 py-2 text-sm focus:outline-none focus:border-teal-600"> </div> <div class="space-y-2"> <label class="text-xs font-bold text-gray-700" data-i18n="label_date">تاريخ الإنجاز</label> <input type="text" id="input-kpi-date" placeholder="يوم/شهر/سنة" class="w-full bg-gray-50 border border-gray-200 rounded-xl px-4 py-2 text-sm focus:outline-none focus:border-teal-600"> </div> </div> <div class="flex justify-end gap-3 pt-2"> <button onclick="toggleNewKpiForm()" class="bg-gray-100 text-gray-700 px-5 py-2 rounded-xl text-sm font-bold hover:bg-gray-200 transition" data-i18n="btn_cancel">إلغاء</button> <button onclick="saveNewKpi()" class="bg-teal-700 text-white px-5 py-2 rounded-xl text-sm font-bold shadow-sm hover:bg-teal-800 transition" data-i18n="btn_save">حفظ المؤشر</button> </div> </div>
<div id="kpi-cards-container" class="space-y-4"></div> </section>
</div> </main>
<!-- البرمجية والتوليد الذكي المستند للبيانات الفعليّة --> <script> const translations = { ar: { 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: "التحليلات الذكية", show_ai_insights_btn: "إظهار التحليلات بالذكاء الاصطناعي", 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: { 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", show_ai_insights_btn: "Show AI 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;
// ضع هنا رابط Cloudflare Worker بعد نشره. لا تضع HF_TOKEN في هذا الملف مطلقًا. const AI_API_URL = ""; 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('تعذر تحميل ملف البيانات'); currentKpiData = await response.json(); renderAll(); } catch (error) { console.error("Error fetching JSON:", error); } }
function toggleLanguage() { currentLang = currentLang === 'ar' ? 'en' : 'ar'; const root = document.getElementById('html-root'); root.lang = currentLang; root.dir = currentLang === 'ar' ? 'rtl' : 'ltr'; document.getElementById('lang-btn-text').innerText = currentLang === 'ar' ? 'English' : 'عربي'; document.getElementById('search-input').placeholder = translations[currentLang].search_placeholder; const insightsButtonText = document.querySelector("#show-ai-insights-btn span[data-i18n='show_ai_insights_btn']"); if (insightsButtonText) insightsButtonText.textContent = document.getElementById("ai-insights-container").classList.contains("hidden") ? (currentLang === "ar" ? "إظهار التحليلات بالذكاء الاصطناعي" : "Show AI insights") : (currentLang === "ar" ? "إخفاء التحليلات الذكية" : "Hide AI insights");
document.querySelectorAll('[data-i18n]').forEach(el => { const key = el.getAttribute('data-i18n'); if (translations[currentLang][key]) { el.innerText = translations[currentLang][key]; } });
loadExternalData(); }
function toggleNewKpiForm() { document.getElementById('new-kpi-form-card').classList.toggle('hidden'); }
// يرسل البيانات الفعلية إلى Backend آمن، ولا يستدعي النموذج مباشرة من المتصفح. async function callAiApi(path, payload) { const apiBase = AI_API_URL ? AI_API_URL.replace(/\/+$/, "") : ""; const response = await fetch(`${apiBase}${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) { throw new Error(result.error || result.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) { 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"); 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`; const fallbackTitles = currentLang === "ar" ? ["تحسين ملحوظ", "تنبيه", "توصية"] : ["Notable Improvement", "Alert", "Recommendation"]; appendTextElement(card, "h4", `font-bold ${colors[index % colors.length].title} text-sm`, fallbackTitles[index] || 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 toggleAiInsights() { const container = document.getElementById("ai-insights-container"); const buttonText = document.querySelector("#show-ai-insights-btn span[data-i18n='show_ai_insights_btn']"); const isHidden = container.classList.contains("hidden"); if (!isHidden) { container.classList.add("hidden"); if (buttonText) buttonText.textContent = currentLang === "ar" ? "إظهار التحليلات بالذكاء الاصطناعي" : "Show AI insights"; return; } container.classList.remove("hidden"); if (buttonText) buttonText.textContent = currentLang === "ar" ? "إخفاء التحليلات الذكية" : "Hide AI insights"; await updateAiInsights(true); }
async function updateAiInsights(force = false) { const container = document.getElementById("ai-insights-container"); 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 = currentLang === "ar" ? "⏳ يرسل التطبيق بيانات المؤشرات إلى Qwen لتحليلها. قد يستغرق الرد بعض الوقت..." : "⏳ Sending KPI data to Qwen for analysis. This may take a little while..."; 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"); outputContent.replaceChildren(); appendTextElement(outputContent, "p", "font-bold text-teal-100 mb-3", currentLang === "ar" ? "اقترح Qwen المؤشرات التالية بناءً على البيانات الحالية. راجعي كل اقتراح قبل إضافته." : "Qwen suggested these KPIs from the current data. Review each suggestion before adding it.");
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;
document.getElementById("input-kpi-name").value = item.kpi_name || ""; document.getElementById("input-kpi-dept").value = item.department || ""; document.getElementById("input-kpi-desc").value = [ item.description || "", item.formula ? (currentLang === "ar" ? "طريقة القياس: " : "Measurement: ") + item.formula : "", item.rationale ? (currentLang === "ar" ? "مبرر الاقتراح: " : "Rationale: ") + item.rationale : "" ].filter(Boolean).join("\n\n"); document.getElementById("input-kpi-target").value = Number.isFinite(Number(item.target)) ? Number(item.target) : 90; if (document.getElementById("new-kpi-form-card").classList.contains("hidden")) { toggleNewKpiForm(); } document.getElementById("new-kpi-form-card").scrollIntoView({ behavior: "smooth", block: "start" }); }
async function generateQwenAiKpi() { const resultBox = document.getElementById("qwen-result-box"); const outputContent = document.getElementById("qwen-output-content"); resultBox.classList.remove("hidden"); outputContent.replaceChildren(); appendTextElement(outputContent, "p", "text-teal-100", currentLang === "ar" ? "⏳ يرسل التطبيق المؤشرات الحالية إلى Qwen لتوليد اقتراحات جديدة..." : "⏳ Sending the current KPIs to Qwen to generate new suggestions...");
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); } }
function saveNewKpi() { const name = document.getElementById('input-kpi-name').value; const dept = document.getElementById('input-kpi-dept').value; const desc = document.getElementById('input-kpi-desc').value; const target = parseFloat(document.getElementById('input-kpi-target').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: 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); toggleNewKpiForm(); renderAll();
document.getElementById('input-kpi-name').value = ''; document.getElementById('input-kpi-dept').value = ''; document.getElementById('input-kpi-desc').value = ''; document.getElementById('input-kpi-target').value = ''; document.getElementById('input-kpi-date').value = ''; }
function updateSummaryCards() { if(!currentKpiData || currentKpiData.length === 0) return;
let goodCount = 0, mediumCount = 0, lateCount = 0, totalValSum = 0;
currentKpiData.forEach(item => { totalValSum += item.latest_value; const statusStr = 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);
document.getElementById('card-total-val').innerText = totalKpis; document.getElementById('card-good-val').innerText = goodCount; document.getElementById('card-late-val').innerText = lateCount; document.getElementById('card-avg-val').innerText = `${avgRate}%`;
document.getElementById('count-good').innerText = goodCount; document.getElementById('count-medium').innerText = mediumCount; document.getElementById('count-late').innerText = lateCount;
renderDoughnutChart(goodCount, mediumCount, lateCount); }
function renderDoughnutChart(good, medium, late) { const ctx = document.getElementById('statusDoughnutChart').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'); container.innerHTML = '';
currentKpiData.forEach(item => { let color = item.latest_value >= 80 ? 'bg-emerald-500' : (item.latest_value >= 60 ? 'bg-amber-500' : 'bg-red-500'); const targetText = translations[currentLang].target_label; container.innerHTML += ` <div> <div class="flex justify-between text-sm mb-1"> <span class="font-bold text-gray-700">${item.kpi_name}</span> <span class="text-gray-500">${targetText}: ${item.target}% (<span class="font-bold text-gray-800">${item.latest_value}%</span>)</span> </div> <div class="w-full bg-gray-100 h-3 rounded-full overflow-hidden"> <div class="${color} h-full rounded-full transition-all duration-500" style="width: ${item.latest_value}%"></div> </div> </div> `; }); }
function renderKPIsList() { const container = document.getElementById('kpi-cards-container'); container.innerHTML = '';
currentKpiData.forEach(item => { let isGood = item.latest_value >= 80; let isMedium = item.latest_value >= 60 && item.latest_value < 80; let badgeColor = isGood ? 'bg-emerald-50 text-emerald-600' : (isMedium ? 'bg-amber-50 text-amber-600' : 'bg-red-50 text-red-600'); const t = translations[currentLang];
container.innerHTML += ` <div class="bg-white p-6 rounded-2xl border border-gray-100 shadow-sm space-y-4"> <div class="flex justify-between items-start"> <div> <div class="flex items-center gap-3"> <h3 class="font-bold text-gray-800 text-lg">${item.kpi_name}</h3> <span class="text-xs font-bold px-3 py-1 rounded-full ${badgeColor}">${item.status}</span> </div> <p class="text-xs text-gray-500 mt-1">${item.description}</p> </div> <div class="flex gap-2 text-gray-400"> <button class="hover:text-teal-600 p-1"><i data-lucide="edit-2" class="w-4 h-4"></i></button> <button class="hover:text-red-600 p-1"><i data-lucide="trash-2" class="w-4 h-4"></i></button> </div> </div>
<div class="grid grid-cols-2 gap-4 text-xs text-gray-500 bg-gray-50 p-3 rounded-xl"> <div>${t.dept_label}: <span class="font-bold text-gray-700">${item.department}</span></div> <div>${t.target_label}: <span class="font-bold text-gray-700">${item.target}%</span></div> </div>
<div> <div class="flex justify-between text-xs mb-1 text-gray-500"> <span>${t.progress_label}</span> <span class="font-bold text-gray-700">${item.latest_value}%</span> </div> <div class="w-full bg-gray-100 h-2.5 rounded-full overflow-hidden"> <div class="bg-emerald-500 h-full rounded-full" style="width: ${item.latest_value}%"></div> </div> </div> </div> `; }); lucide.createIcons(); }
function renderPerformanceChart() { const ctx = document.getElementById('performanceChart').getContext('2d'); if (lineChartInstance) lineChartInstance.destroy();
if (!currentKpiData || currentKpiData.length === 0) return;
const labels = currentKpiData[0].daily_history.map(d => d.date || `Day ${d.day}`); const palette = ['#0D9488', '#3B82F6', '#F59E0B', '#EF4444', '#8B5CF6'];
const datasets = currentKpiData.map((kpi, idx) => ({ label: kpi.kpi_name, data: kpi.daily_history.map(d => d.value), borderColor: palette[idx % palette.length], backgroundColor: palette[idx % palette.length], tension: 0.3, borderWidth: 2, pointRadius: 0 }));
lineChartInstance = new Chart(ctx, { type: 'line', data: { labels: labels, datasets: datasets }, options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { position: 'bottom' } }, scales: { x: { grid: { display: false } }, y: { min: 0, max: 100 } } } }); }
function switchTab(tab) { if(tab === 'dashboard') { document.getElementById('view-dashboard').classList.remove('hidden'); document.getElementById('view-kpis').classList.add('hidden'); document.getElementById('btn-dashboard').className = "w-full flex items-center gap-3 px-4 py-3 rounded-xl text-sm font-semibold transition bg-teal-700 text-white shadow-sm"; document.getElementById('btn-kpis').className = "w-full flex items-center gap-3 px-4 py-3 rounded-xl text-sm font-semibold transition text-gray-600 hover:bg-gray-50"; } else { document.getElementById('view-dashboard').classList.add('hidden'); document.getElementById('view-kpis').classList.remove('hidden'); document.getElementById('btn-kpis').className = "w-full flex items-center gap-3 px-4 py-3 rounded-xl text-sm font-semibold transition bg-teal-700 text-white shadow-sm"; document.getElementById('btn-dashboard').className = "w-full flex items-center gap-3 px-4 py-3 rounded-xl text-sm font-semibold transition text-gray-600 hover:bg-gray-50"; } }
function renderAll() { updateSummaryCards(); renderDashboardProgress(); renderKPIsList(); renderPerformanceChart(); lucide.createIcons(); }
loadExternalData(); </script></body></html>index.htmlAdded+856