ehsan-dashboards/dashboards/old_hermes/dashboard/index.html

777 lines
44 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>سامانه مدیریت و پایش پکیج‌های مارکتینگ اکیپا | Ekeepa Marketing Intelligence</title>
<!-- Tailwind CSS -->
<script src="https://cdn.tailwindcss.com"></script>
<!-- Font Vazirmatn -->
<link href="https://cdn.jsdelivr.net/gh/rastikerdar/vazirmatn@v33.003/Vazirmatn-font-face.css" rel="stylesheet" type="text/css" />
<!-- ApexCharts -->
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
<style>
* { font-family: 'Vazirmatn', sans-serif; }
.tnum { font-feature-settings: "tnum"; font-variant-numeric: tabular-nums; }
.custom-scrollbar::-webkit-scrollbar { width: 6px; height: 6px; }
.custom-scrollbar::-webkit-scrollbar-track { background: #F1F5F9; border-radius: 4px; }
.custom-scrollbar::-webkit-scrollbar-thumb { background: #CBD5E1; border-radius: 4px; }
.custom-scrollbar::-webkit-scrollbar-thumb:hover { background: #94A3B8; }
.sticky-filters {
position: -webkit-sticky;
position: sticky;
top: 4rem; /* 64px below header */
z-index: 30;
}
</style>
</head>
<body class="bg-[#F8FAFC] text-[#0F172A] min-h-screen">
<!-- Top Navigation -->
<header class="bg-white border-b border-slate-200 sticky top-0 z-40 shadow-sm h-16">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 h-full flex items-center justify-between">
<div class="flex items-center space-x-3 space-x-reverse">
<div class="w-10 h-10 rounded-xl bg-gradient-to-tr from-amber-500 to-amber-600 flex items-center justify-center text-white font-bold shadow-md shadow-amber-500/20 text-lg">
📦
</div>
<div>
<h1 class="text-base sm:text-lg font-black text-slate-800 tracking-tight">داشبورد هوش تجاری و عملیات پکیج‌ها</h1>
<p class="text-xs text-slate-500 font-medium">Ekeepa Marketing Channel & Execution Tracker</p>
</div>
</div>
<div class="flex items-center space-x-3 space-x-reverse">
<button onclick="syncMetabaseNow()" id="btn-sync" class="flex items-center gap-1.5 bg-slate-50 hover:bg-slate-100 text-slate-700 text-xs font-semibold px-3 py-2 rounded-xl border border-slate-300 transition shadow-sm">
<svg id="sync-spinner" class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/></svg>
بروزرسانی داده‌ها
</button>
<button onclick="exportToCSV()" class="flex items-center gap-1.5 bg-slate-800 hover:bg-slate-900 text-white text-xs font-semibold px-3.5 py-2 rounded-xl transition shadow-sm">
<svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>
خروجی CSV
</button>
</div>
</div>
</header>
<!-- Sticky Filter & Period Bar (Pinned below header) -->
<div class="sticky-filters bg-white/95 backdrop-blur-md border-b border-slate-200 shadow-md">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-3 space-y-2.5">
<div class="flex flex-wrap items-center justify-between gap-3">
<!-- Period Dropdowns -->
<div class="flex flex-wrap items-center gap-2">
<span class="text-xs font-bold text-slate-700 flex items-center gap-1 ml-1">
<svg class="w-3.5 h-3.5 text-amber-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"/></svg>
دوره:
</span>
<!-- Year Selector -->
<select id="select-year" onchange="onPeriodChange()" class="bg-slate-100 hover:bg-slate-200/80 border border-slate-300 text-slate-800 rounded-lg px-2.5 py-1.5 text-xs font-bold focus:ring-2 focus:ring-amber-500 focus:outline-none transition cursor-pointer">
<option value="1405" selected>۱۴۰۵</option>
<option value="1404">۱۴۰۴</option>
</select>
<!-- Month Selector -->
<select id="select-month" onchange="onPeriodChange()" class="bg-slate-100 hover:bg-slate-200/80 border border-slate-300 text-slate-800 rounded-lg px-2.5 py-1.5 text-xs font-bold focus:ring-2 focus:ring-amber-500 focus:outline-none transition cursor-pointer">
<option value="0">کل سال (همه ماه‌ها)</option>
<option value="1">فروردین</option>
<option value="2">اردیبهشت</option>
<option value="3">خرداد</option>
<option value="4">تیر</option>
<option value="5">مرداد</option>
<option value="6">شهریور</option>
<option value="7" selected>مهر (ماه جاری)</option>
<option value="8">آبان</option>
<option value="9">آذر</option>
<option value="10">دی</option>
<option value="11">بهمن</option>
<option value="12">اسفند</option>
</select>
<div id="period-badge" class="bg-amber-50 text-amber-900 text-[11px] font-bold px-2 py-1 rounded-md border border-amber-300/70 tnum hidden sm:block">
بازه: -
</div>
</div>
<!-- Status and Category Filters -->
<div class="flex flex-wrap items-center gap-2">
<!-- NEW: Package Status Filter (حذف شده / فعال / پایان یافته) -->
<select id="filter-pkg-status" onchange="applyClientFilters()" class="bg-slate-100 hover:bg-slate-200/80 border border-slate-300 text-slate-800 rounded-lg px-2.5 py-1.5 text-xs font-bold focus:ring-2 focus:ring-amber-500 focus:outline-none cursor-pointer">
<option value="">همه وضعیت‌ها (کلی)</option>
<option value="active">درحال اجرا / فعال 🟢</option>
<option value="deleted">حذف شده 🔴</option>
<option value="expired">پایان یافته ⚪</option>
</select>
<!-- City Filter -->
<select id="filter-city" onchange="applyClientFilters()" class="bg-slate-100 hover:bg-slate-200/80 border border-slate-300 text-slate-700 rounded-lg px-2.5 py-1.5 text-xs font-semibold focus:ring-2 focus:ring-amber-500 focus:outline-none cursor-pointer">
<option value="">همه شهرها</option>
</select>
<!-- Package Model Filter -->
<select id="filter-model" onchange="applyClientFilters()" class="bg-slate-100 hover:bg-slate-200/80 border border-slate-300 text-slate-700 rounded-lg px-2.5 py-1.5 text-xs font-semibold focus:ring-2 focus:ring-amber-500 focus:outline-none cursor-pointer">
<option value="">همه مدل‌ها</option>
</select>
<!-- Task Execution Status Filter -->
<select id="filter-task-status" onchange="applyClientFilters()" class="bg-slate-100 hover:bg-slate-200/80 border border-slate-300 text-slate-700 rounded-lg px-2.5 py-1.5 text-xs font-semibold focus:ring-2 focus:ring-amber-500 focus:outline-none cursor-pointer">
<option value="">همه تسک‌ها</option>
<option value="has_pending">دارای تسک در انتظار 🟡</option>
<option value="all_completed">تکمیل تمام کانال‌ها 🟢</option>
</select>
</div>
</div>
<!-- Live Search Input -->
<div class="relative">
<input type="text" id="search-input" oninput="applyClientFilters()" placeholder="جستجوی آنی در نام اتاق، برند، منطقه، شناسه پکیج، متن یادداشت‌ها..."
class="w-full pr-9 pl-4 py-2 bg-slate-100/90 border border-slate-300 rounded-xl text-xs font-medium focus:ring-2 focus:ring-amber-500 focus:bg-white focus:outline-none transition">
<svg class="w-4 h-4 text-slate-400 absolute right-3 top-2.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/></svg>
</div>
</div>
</div>
<!-- Main Content Container -->
<main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6 space-y-6">
<!-- KPI Summary Cards -->
<section class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
<!-- Total Active Packages -->
<div class="bg-white p-5 rounded-2xl border border-slate-200 shadow-sm relative overflow-hidden">
<div class="flex items-center justify-between">
<div>
<p class="text-xs font-semibold text-slate-500">پکیج‌های انتخابی</p>
<h3 id="kpi-packages-count" class="text-2xl font-black text-slate-800 mt-1 tnum">۰</h3>
</div>
<div class="w-11 h-11 bg-blue-50 text-blue-600 rounded-xl flex items-center justify-center text-xl font-bold">
📦
</div>
</div>
<div class="mt-2 text-xs text-slate-500">
<span id="kpi-unique-brands" class="font-bold text-blue-600 tnum">۰</span> برند منحصر‌به‌فرد
</div>
</div>
<!-- Telegram Channel Status -->
<div class="bg-white p-5 rounded-2xl border border-slate-200 shadow-sm relative overflow-hidden">
<div class="flex items-center justify-between">
<div>
<p class="text-xs font-semibold text-slate-500">تسک‌های تلگرام</p>
<h3 id="kpi-tg-count" class="text-2xl font-black text-sky-600 mt-1 tnum">۰ / ۰</h3>
</div>
<div class="w-11 h-11 bg-sky-50 text-sky-600 rounded-xl flex items-center justify-center text-lg font-bold">
✈️
</div>
</div>
<div class="mt-2 flex items-center gap-1.5 text-xs text-slate-500">
<span class="w-2 h-2 rounded-full bg-sky-500"></span>
<span id="kpi-tg-progress" class="font-bold text-sky-700 tnum">۰٪ تکمیل شده</span>
</div>
</div>
<!-- Story Channel Status -->
<div class="bg-white p-5 rounded-2xl border border-slate-200 shadow-sm relative overflow-hidden">
<div class="flex items-center justify-between">
<div>
<p class="text-xs font-semibold text-slate-500">تسک‌های استوری</p>
<h3 id="kpi-story-count" class="text-2xl font-black text-pink-600 mt-1 tnum">۰ / ۰</h3>
</div>
<div class="w-11 h-11 bg-pink-50 text-pink-600 rounded-xl flex items-center justify-center text-lg font-bold">
📸
</div>
</div>
<div class="mt-2 flex items-center gap-1.5 text-xs text-slate-500">
<span class="w-2 h-2 rounded-full bg-pink-500"></span>
<span id="kpi-story-progress" class="font-bold text-pink-700 tnum">۰٪ تکمیل شده</span>
</div>
</div>
<!-- Reels & Post Channel Status -->
<div class="bg-white p-5 rounded-2xl border border-slate-200 shadow-sm relative overflow-hidden">
<div class="flex items-center justify-between">
<div>
<p class="text-xs font-semibold text-slate-500">تسک‌های ریلز / پست</p>
<h3 id="kpi-reels-count" class="text-2xl font-black text-purple-600 mt-1 tnum">۰ / ۰</h3>
</div>
<div class="w-11 h-11 bg-purple-50 text-purple-600 rounded-xl flex items-center justify-center text-lg font-bold">
🎬
</div>
</div>
<div class="mt-2 flex items-center gap-1.5 text-xs text-slate-500">
<span class="w-2 h-2 rounded-full bg-purple-500"></span>
<span id="kpi-reels-progress" class="font-bold text-purple-700 tnum">۰٪ تکمیل شده</span>
</div>
</div>
</section>
<!-- Charts Section -->
<section class="grid grid-cols-1 lg:grid-cols-2 gap-5">
<!-- Channel Execution Progress Chart -->
<div class="bg-white p-5 rounded-2xl border border-slate-200 shadow-sm">
<h3 class="text-sm font-bold text-slate-800 mb-3 flex items-center gap-2">
<span class="w-2.5 h-2.5 rounded-full bg-emerald-500"></span>
وضعیت اجرای کانال‌های تبلیغاتی (تکمیل / در انتظار / لغو)
</h3>
<div id="chart-channel-progress" class="h-60"></div>
</div>
<!-- City Distribution Chart -->
<div class="bg-white p-5 rounded-2xl border border-slate-200 shadow-sm">
<h3 class="text-sm font-bold text-slate-800 mb-3 flex items-center gap-2">
<span class="w-2.5 h-2.5 rounded-full bg-amber-500"></span>
تعداد پکیج‌ها به تفکیک شهرها
</h3>
<div id="chart-city-distribution" class="h-60"></div>
</div>
</section>
<!-- Main Interactive Data Table -->
<section class="bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden">
<div class="p-4 sm:p-5 border-b border-slate-200 flex flex-wrap items-center justify-between gap-3">
<div class="flex items-center gap-2">
<h3 class="text-sm font-bold text-slate-800">لیست پکیج‌ها و وضعیت کانال‌ها</h3>
<span class="text-[11px] bg-slate-100 text-slate-600 px-2 py-0.5 rounded-md font-semibold">(کلیک روی هر سلول برای ویرایش نوت و تاریخ)</span>
</div>
<span id="table-count" class="text-xs font-semibold text-slate-500 tnum">در حال بارگذاری...</span>
</div>
<div class="overflow-x-auto custom-scrollbar">
<table class="w-full text-right text-xs">
<thead class="bg-slate-50 border-b border-slate-200 text-slate-600 font-bold">
<tr>
<th class="py-3.5 px-3.5">شناسه</th>
<th class="py-3.5 px-4">نام اتاق</th>
<th class="py-3.5 px-4">برند</th>
<th class="py-3.5 px-3.5">شهر / منطقه</th>
<th class="py-3.5 px-3.5">مدل پکیج</th>
<th class="py-3.5 px-3.5 text-center">بازه اجرا</th>
<th class="py-3.5 px-3.5 text-center">درصد</th>
<!-- 3 New Dedicated Channel Columns -->
<th class="py-3.5 px-4 text-center bg-sky-50/70 text-sky-800 border-x border-sky-100">تلگرام ✈️</th>
<th class="py-3.5 px-4 text-center bg-pink-50/70 text-pink-800 border-r border-pink-100">استوری 📸</th>
<th class="py-3.5 px-4 text-center bg-purple-50/70 text-purple-800 border-r border-purple-100">ریلز یا پست 🎬</th>
<th class="py-3.5 px-3.5 text-center">وضعیت</th>
</tr>
</thead>
<tbody id="packages-table-body" class="divide-y divide-slate-100 font-medium text-slate-700">
<!-- Dynamic Rows -->
</tbody>
</table>
</div>
</section>
</main>
<!-- Modal for Editing Channel Execution Date & Notes -->
<div id="channel-modal" class="fixed inset-0 z-50 hidden bg-slate-900/60 backdrop-blur-sm flex items-center justify-center p-4">
<div class="bg-white w-full max-w-md rounded-2xl shadow-2xl border border-slate-200 overflow-hidden transform transition-all">
<div class="p-5 border-b border-slate-200 flex items-center justify-between bg-slate-50/80">
<div class="flex items-center gap-2.5">
<div id="modal-channel-icon" class="w-9 h-9 rounded-xl flex items-center justify-center text-base font-bold shadow-xs"></div>
<div>
<h3 id="modal-title" class="text-sm font-bold text-slate-800">ویرایش تسک کانال</h3>
<p id="modal-subtitle" class="text-[11px] text-slate-500 font-medium">-</p>
</div>
</div>
<button onclick="closeModal()" class="text-slate-400 hover:text-slate-600 transition p-1">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
</button>
</div>
<form id="modal-form" onsubmit="saveModalData(event)" class="p-5 space-y-4">
<input type="hidden" id="modal-pkg-id">
<input type="hidden" id="modal-channel-key">
<!-- Status Selector -->
<div>
<label class="block text-xs font-bold text-slate-700 mb-1.5">وضعیت اجرا:</label>
<div class="grid grid-cols-3 gap-2">
<label class="cursor-pointer">
<input type="radio" name="modal_status" value="completed" class="peer sr-only">
<div class="p-2.5 text-center text-xs font-bold rounded-xl border border-slate-200 peer-checked:bg-emerald-50 peer-checked:border-emerald-500 peer-checked:text-emerald-700 transition">
🟢 انجام شد
</div>
</label>
<label class="cursor-pointer">
<input type="radio" name="modal_status" value="pending" class="peer sr-only">
<div class="p-2.5 text-center text-xs font-bold rounded-xl border border-slate-200 peer-checked:bg-amber-50 peer-checked:border-amber-500 peer-checked:text-amber-700 transition">
🟡 در انتظار
</div>
</label>
<label class="cursor-pointer">
<input type="radio" name="modal_status" value="cancelled" class="peer sr-only">
<div class="p-2.5 text-center text-xs font-bold rounded-xl border border-slate-200 peer-checked:bg-rose-50 peer-checked:border-rose-500 peer-checked:text-rose-700 transition">
🔴 لغو شده
</div>
</label>
</div>
</div>
<!-- Execution Date -->
<div>
<label class="block text-xs font-bold text-slate-700 mb-1.5">تاریخ اجرا (شمسی):</label>
<input type="text" id="modal-date" placeholder="مثال: 1405-07-15"
class="w-full px-3.5 py-2.5 bg-slate-50 border border-slate-300 rounded-xl text-xs font-medium focus:ring-2 focus:ring-amber-500 focus:outline-none transition tnum">
</div>
<!-- Notes / Text -->
<div>
<label class="block text-xs font-bold text-slate-700 mb-1.5">توضیحات / لینک / یادداشت:</label>
<textarea id="modal-note" rows="3" placeholder="متن یادداشت، لینک پست یا استوری، هماهنگی‌ها یا توضیحات تکمیلی..."
class="w-full px-3.5 py-2.5 bg-slate-50 border border-slate-300 rounded-xl text-xs font-medium focus:ring-2 focus:ring-amber-500 focus:outline-none transition"></textarea>
</div>
<!-- Actions -->
<div class="flex items-center justify-end gap-2.5 pt-2 border-t border-slate-100">
<button type="button" onclick="closeModal()" class="px-4 py-2 text-xs font-semibold text-slate-600 hover:bg-slate-100 rounded-xl transition">انصراف</button>
<button type="submit" id="modal-submit-btn" class="px-5 py-2 bg-amber-500 hover:bg-amber-600 text-white text-xs font-bold rounded-xl transition shadow-md shadow-amber-500/20">ذخیره تغییرات</button>
</div>
</form>
</div>
</div>
<!-- Notification Toast -->
<div id="toast" class="fixed bottom-5 left-5 z-50 transform translate-y-20 opacity-0 transition-all duration-300 bg-slate-900 text-white px-4 py-3 rounded-xl shadow-lg flex items-center gap-2 text-xs font-bold">
<span id="toast-icon">✅</span>
<span id="toast-msg">تغییرات با موفقیت ذخیره شد</span>
</div>
<footer class="mt-12 border-t border-slate-200 bg-white py-6 text-center text-xs text-slate-400 font-medium">
سامانه پایش و مدیریت عملیات پکیج‌های مارکتینگ اکیپا © ۲۰۲۶
</footer>
<script>
let rawPackages = [];
let filteredPackages = [];
let filterOptions = {};
const CHANNEL_LABELS = {
"telegram": { name: "تلگرام", icon: "✈️", bg: "bg-sky-50", text: "text-sky-700", border: "border-sky-200" },
"story": { name: "استوری", icon: "📸", bg: "bg-pink-50", text: "text-pink-700", border: "border-pink-200" },
"reels_post": { name: "ریلز یا پست", icon: "🎬", bg: "bg-purple-50", text: "text-purple-700", border: "border-purple-200" }
};
function showToast(msg, isError = false) {
const toast = document.getElementById('toast');
document.getElementById('toast-msg').innerText = msg;
document.getElementById('toast-icon').innerText = isError ? '❌' : '✅';
toast.classList.remove('translate-y-20', 'opacity-0');
setTimeout(() => {
toast.classList.add('translate-y-20', 'opacity-0');
}, 3000);
}
async function initDashboard() {
try {
const optRes = await fetch('/api/filter-options');
filterOptions = await optRes.json();
populateDropdowns();
await loadPackagesData();
} catch (err) {
console.error('Init error:', err);
showToast('خطا در بارگذاری اولیه اطلاعات', true);
}
}
function populateDropdowns() {
const citySelect = document.getElementById('filter-city');
filterOptions.cities.forEach(c => {
const opt = document.createElement('option');
opt.value = c;
opt.innerText = c;
citySelect.appendChild(opt);
});
const modelSelect = document.getElementById('filter-model');
filterOptions.models.forEach(m => {
const opt = document.createElement('option');
opt.value = m;
opt.innerText = m;
modelSelect.appendChild(opt);
});
}
async function loadPackagesData() {
const year = document.getElementById('select-year').value;
const month = document.getElementById('select-month').value;
document.getElementById('table-count').innerText = 'در حال دریافت اطلاعات...';
try {
const url = `/api/packages?year=${year}&month=${month}`;
const res = await fetch(url);
const data = await res.json();
rawPackages = data.packages || [];
const range = data.date_range;
document.getElementById('period-badge').innerText = `بازه: ${range.start_j} تا ${range.end_j}`;
applyClientFilters();
} catch (err) {
console.error('Fetch packages error:', err);
document.getElementById('table-count').innerText = 'خطا در دریافت داده‌ها';
}
}
function onPeriodChange() {
loadPackagesData();
}
function applyClientFilters() {
const query = document.getElementById('search-input').value.trim().toLowerCase();
const pkgStatus = document.getElementById('filter-pkg-status').value;
const city = document.getElementById('filter-city').value;
const model = document.getElementById('filter-model').value;
const taskStatus = document.getElementById('filter-task-status').value;
const todayISO = new Date().toISOString().split('T')[0];
filteredPackages = rawPackages.filter(p => {
// Search query match
const matchQuery = !query ||
(p.room_name && p.room_name.toLowerCase().includes(query)) ||
(p.brand && p.brand.toLowerCase().includes(query)) ||
(p.district && p.district.toLowerCase().includes(query)) ||
(p.id && p.id.toString().includes(query)) ||
(p.telegram && p.telegram.note && p.telegram.note.toLowerCase().includes(query)) ||
(p.story && p.story.note && p.story.note.toLowerCase().includes(query)) ||
(p.reels_post && p.reels_post.note && p.reels_post.note.toLowerCase().includes(query));
// Package status filter
let matchStatus = true;
const isDeleted = !!p.deleted_at;
const isExpired = p.end_date_g && p.end_date_g < todayISO;
if (pkgStatus === 'active') {
matchStatus = !isDeleted && !isExpired;
} else if (pkgStatus === 'deleted') {
matchStatus = isDeleted;
} else if (pkgStatus === 'expired') {
matchStatus = !isDeleted && isExpired;
}
const matchCity = !city || p.city === city;
const matchModel = !model || p.package_model === model;
// Task execution status filter
let matchTask = true;
if (taskStatus === 'has_pending') {
matchTask = p.telegram.status === 'pending' || p.story.status === 'pending' || p.reels_post.status === 'pending';
} else if (taskStatus === 'all_completed') {
matchTask = p.telegram.status === 'completed' && p.story.status === 'completed' && p.reels_post.status === 'completed';
}
return matchQuery && matchStatus && matchCity && matchModel && matchTask;
});
renderKPIs();
renderCharts();
renderTable();
}
function renderKPIs() {
const total = filteredPackages.length;
const uniqueBrands = new Set(filteredPackages.map(p => p.brand).filter(Boolean)).size;
let tgDone = 0, storyDone = 0, reelsDone = 0;
filteredPackages.forEach(p => {
if (p.telegram && p.telegram.status === 'completed') tgDone++;
if (p.story && p.story.status === 'completed') storyDone++;
if (p.reels_post && p.reels_post.status === 'completed') reelsDone++;
});
const tgPct = total > 0 ? Math.round((tgDone / total) * 100) : 0;
const storyPct = total > 0 ? Math.round((storyDone / total) * 100) : 0;
const reelsPct = total > 0 ? Math.round((reelsDone / total) * 100) : 0;
document.getElementById('kpi-packages-count').innerText = Number(total).toLocaleString('fa-IR');
document.getElementById('kpi-unique-brands').innerText = Number(uniqueBrands).toLocaleString('fa-IR');
document.getElementById('kpi-tg-count').innerText = `${Number(tgDone).toLocaleString('fa-IR')} / ${Number(total).toLocaleString('fa-IR')}`;
document.getElementById('kpi-tg-progress').innerText = `${Number(tgPct).toLocaleString('fa-IR')}٪ تکمیل شده`;
document.getElementById('kpi-story-count').innerText = `${Number(storyDone).toLocaleString('fa-IR')} / ${Number(total).toLocaleString('fa-IR')}`;
document.getElementById('kpi-story-progress').innerText = `${Number(storyPct).toLocaleString('fa-IR')}٪ تکمیل شده`;
document.getElementById('kpi-reels-count').innerText = `${Number(reelsDone).toLocaleString('fa-IR')} / ${Number(total).toLocaleString('fa-IR')}`;
document.getElementById('kpi-reels-progress').innerText = `${Number(reelsPct).toLocaleString('fa-IR')}٪ تکمیل شده`;
}
let chartProgressInstance, chartCityInstance;
function renderCharts() {
let tgC = 0, tgP = 0, tgX = 0;
let stC = 0, stP = 0, stX = 0;
let rlC = 0, rlP = 0, rlX = 0;
filteredPackages.forEach(p => {
if (p.telegram.status === 'completed') tgC++; else if (p.telegram.status === 'cancelled') tgX++; else tgP++;
if (p.story.status === 'completed') stC++; else if (p.story.status === 'cancelled') stX++; else stP++;
if (p.reels_post.status === 'completed') rlC++; else if (p.reels_post.status === 'cancelled') rlX++; else rlP++;
});
if (chartProgressInstance) chartProgressInstance.destroy();
chartProgressInstance = new ApexCharts(document.querySelector("#chart-channel-progress"), {
chart: { type: 'bar', height: 240, stacked: true, fontFamily: 'Vazirmatn', toolbar: { show: false } },
series: [
{ name: 'انجام شده 🟢', data: [tgC, stC, rlC] },
{ name: 'در انتظار 🟡', data: [tgP, stP, rlP] },
{ name: 'لغو شده 🔴', data: [tgX, stX, rlX] }
],
xaxis: { categories: ['تلگرام', 'استوری', 'ریلز / پست'], labels: { style: { fontSize: '11px', fontWeight: 'bold' } } },
colors: ['#10B981', '#F59E0B', '#EF4444'],
plotOptions: { bar: { horizontal: false, borderRadius: 6, columnWidth: '35%' } },
legend: { position: 'top', fontSize: '11px' }
});
chartProgressInstance.render();
const cityMap = {};
filteredPackages.forEach(p => {
const c = p.city || 'نامشخص';
cityMap[c] = (cityMap[c] || 0) + 1;
});
const cityKeys = Object.keys(cityMap).sort((a,b) => cityMap[b] - cityMap[a]).slice(0, 7);
const cityVals = cityKeys.map(k => cityMap[k]);
if (chartCityInstance) chartCityInstance.destroy();
chartCityInstance = new ApexCharts(document.querySelector("#chart-city-distribution"), {
chart: { type: 'bar', height: 240, fontFamily: 'Vazirmatn', toolbar: { show: false } },
series: [{ name: 'تعداد پکیج', data: cityVals }],
xaxis: { categories: cityKeys, labels: { style: { fontSize: '11px' } } },
colors: ['#F59E0B'],
plotOptions: { bar: { borderRadius: 6, horizontal: true } }
});
chartCityInstance.render();
}
function createChannelCell(pkgId, channelKey, chData) {
const status = chData ? chData.status : 'pending';
const date = chData && chData.execution_date ? chData.execution_date : '';
const note = chData && chData.note ? chData.note : '';
let badgeClass = "bg-amber-50 text-amber-800 border-amber-300/80";
let statusText = "در انتظار 🟡";
if (status === 'completed') {
badgeClass = "bg-emerald-50 text-emerald-800 border-emerald-400";
statusText = date ? `انجام: ${date}` : "انجام شد 🟢";
} else if (status === 'cancelled') {
badgeClass = "bg-rose-100 text-rose-800 border-rose-300";
statusText = "لغو شده 🔴";
}
const hasNote = note.trim().length > 0;
return `
<td class="py-2.5 px-3 text-center border-x border-slate-100/80">
<button onclick="openModal(${pkgId}, '${channelKey}')"
class="w-full text-center px-2 py-1.5 rounded-lg border text-[11px] font-semibold transition hover:scale-[1.02] shadow-xs ${badgeClass}">
<div class="flex items-center justify-center gap-1">
<span class="tnum">${statusText}</span>
${hasNote ? '<span title="' + note.replace(/"/g, '&quot;') + '" class="text-[10px] text-slate-500">📝</span>' : ''}
</div>
${hasNote ? '<p class="text-[10px] text-slate-600 truncate max-w-[120px] mx-auto mt-0.5">' + note + '</p>' : ''}
</button>
</td>
`;
}
function renderTable() {
const tbody = document.getElementById('packages-table-body');
tbody.innerHTML = '';
document.getElementById('table-count').innerText = `نمایش ${Number(filteredPackages.length).toLocaleString('fa-IR')} پکیج`;
if (filteredPackages.length === 0) {
tbody.innerHTML = `<tr><td colspan="11" class="text-center py-10 text-slate-400 font-semibold">هیچ پکیجی با فیلترهای انتخابی یافت نشد</td></tr>`;
return;
}
const todayISO = new Date().toISOString().split('T')[0];
filteredPackages.forEach(p => {
const tr = document.createElement('tr');
const isDeleted = !!p.deleted_at;
const isExpired = p.end_date_g && p.end_date_g < todayISO;
// Stronger distinct red styling for deleted packages
let rowBg = 'hover:bg-slate-50/80 border-b border-slate-100';
let statusBadge = '<span class="bg-emerald-50 text-emerald-700 border border-emerald-300 px-2.5 py-0.5 rounded-full text-[10px] font-bold">درحال اجرا</span>';
if (isDeleted) {
rowBg = 'bg-[#FDE8E8] hover:bg-[#FBD5D5] border-b border-rose-200 text-rose-950 font-semibold';
statusBadge = '<span class="bg-rose-600 text-white shadow-xs px-2.5 py-0.5 rounded-full text-[10px] font-extrabold tracking-wide">حذف شده</span>';
} else if (isExpired) {
statusBadge = '<span class="bg-slate-100 text-slate-600 border border-slate-300 px-2.5 py-0.5 rounded-full text-[10px] font-bold">پایان یافته</span>';
}
tr.className = `transition ${rowBg}`;
tr.innerHTML = `
<td class="py-3.5 px-3.5 font-bold ${isDeleted ? 'text-rose-900' : 'text-slate-500'} tnum">${p.id}</td>
<td class="py-3.5 px-4 font-bold ${isDeleted ? 'text-rose-950 line-through decoration-rose-400' : 'text-slate-800'}">${p.room_name || '-'}</td>
<td class="py-3.5 px-4 ${isDeleted ? 'text-rose-900' : 'text-slate-600'}">${p.brand || '-'}</td>
<td class="py-3.5 px-3.5 ${isDeleted ? 'text-rose-800' : 'text-slate-500'} text-[11px]">${p.city || '-'} / ${p.district || '-'}</td>
<td class="py-3.5 px-3.5">
<span class="${isDeleted ? 'bg-rose-200/80 text-rose-900 border-rose-300' : 'bg-amber-50 text-amber-800 border-amber-200/50'} px-2 py-0.5 rounded text-[11px] font-semibold border">${p.package_model || '-'}</span>
</td>
<td class="py-3.5 px-3.5 text-[11px] ${isDeleted ? 'text-rose-800' : 'text-slate-500'} tnum text-center">${p.start_date} تا ${p.end_date}</td>
<td class="py-3.5 px-3.5 font-bold ${isDeleted ? 'text-rose-900' : 'text-slate-700'} tnum text-center">${(p.percentage_rate * 100).toFixed(0)}%</td>
<!-- 3 Channel Cells -->
${createChannelCell(p.id, 'telegram', p.telegram)}
${createChannelCell(p.id, 'story', p.story)}
${createChannelCell(p.id, 'reels_post', p.reels_post)}
<td class="py-3.5 px-3.5 text-center">${statusBadge}</td>
`;
tbody.appendChild(tr);
});
}
// Modal Management
function openModal(pkgId, channelKey) {
const pkg = rawPackages.find(p => p.id === pkgId);
if (!pkg) return;
const chConfig = CHANNEL_LABELS[channelKey];
const chData = pkg[channelKey] || { status: 'pending', execution_date: '', note: '' };
document.getElementById('modal-pkg-id').value = pkgId;
document.getElementById('modal-channel-key').value = channelKey;
document.getElementById('modal-channel-icon').innerText = chConfig.icon;
document.getElementById('modal-channel-icon').className = `w-9 h-9 rounded-xl flex items-center justify-center text-base font-bold shadow-xs ${chConfig.bg} ${chConfig.text}`;
document.getElementById('modal-title').innerText = `مدیریت تسک ${chConfig.name}`;
document.getElementById('modal-subtitle').innerText = `${pkg.room_name} (${pkg.brand})`;
const radios = document.getElementsByName('modal_status');
for (let r of radios) {
r.checked = (r.value === (chData.status || 'pending'));
}
document.getElementById('modal-date').value = chData.execution_date || '';
document.getElementById('modal-note').value = chData.note || '';
document.getElementById('channel-modal').classList.remove('hidden');
}
function closeModal() {
document.getElementById('channel-modal').classList.add('hidden');
}
async function saveModalData(e) {
e.preventDefault();
const pkgId = parseInt(document.getElementById('modal-pkg-id').value);
const channelKey = document.getElementById('modal-channel-key').value;
let status = 'pending';
const radios = document.getElementsByName('modal_status');
for (let r of radios) {
if (r.checked) status = r.value;
}
const execDate = document.getElementById('modal-date').value.trim();
const note = document.getElementById('modal-note').value.trim();
const btn = document.getElementById('modal-submit-btn');
btn.innerText = 'در حال ذخیره...';
btn.disabled = true;
try {
const res = await fetch('/api/channels/save', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
package_id: pkgId,
channel: channelKey,
status: status,
execution_date: execDate,
note: note
})
});
const result = await res.json();
if (result.status === 'success') {
const pkg = rawPackages.find(p => p.id === pkgId);
if (pkg) {
pkg[channelKey] = {
status: status,
execution_date: execDate,
note: note
};
}
applyClientFilters();
closeModal();
showToast('تغییرات با موفقیت ذخیره شد');
} else {
showToast('خطا در ذخیره سازی', true);
}
} catch (err) {
console.error(err);
showToast('خطای شبکه در ارتباط با سرور', true);
} finally {
btn.innerText = 'ذخیره تغییرات';
btn.disabled = false;
}
}
async function syncMetabaseNow() {
const btn = document.getElementById('btn-sync');
const spinner = document.getElementById('sync-spinner');
spinner.classList.add('animate-spin');
btn.disabled = true;
try {
await fetch('/api/sync-now', { method: 'POST' });
showToast('درخواست همگام‌سازی به متابیس ارسال شد');
setTimeout(() => {
loadPackagesData();
spinner.classList.remove('animate-spin');
btn.disabled = false;
}, 3000);
} catch (e) {
spinner.classList.remove('animate-spin');
btn.disabled = false;
showToast('خطا در همگام‌سازی', true);
}
}
function exportToCSV() {
if (!filteredPackages.length) return;
const headers = [
"شناسه", "کد اتاق", "نام اتاق", "برند", "شهر", "منطقه", "مدل پکیج",
"شروع", "پایان", "درصد",
"وضعیت تلگرام", "تاریخ تلگرام", "نوت تلگرام",
"وضعیت استوری", "تاریخ استوری", "نوت استوری",
"وضعیت ریلز_پست", "تاریخ ریلز_پست", "نوت ریلز_پست",
"وضعیت پکیج"
];
const rows = filteredPackages.map(p => [
p.id, p.room_id, `"${p.room_name}"`, `"${p.brand}"`, `"${p.city}"`, `"${p.district}"`,
`"${p.package_model}"`, p.start_date, p.end_date, p.percentage_rate,
p.telegram.status, p.telegram.execution_date, `"${(p.telegram.note || '').replace(/"/g, '""')}"`,
p.story.status, p.story.execution_date, `"${(p.story.note || '').replace(/"/g, '""')}"`,
p.reels_post.status, p.reels_post.execution_date, `"${(p.reels_post.note || '').replace(/"/g, '""')}"`,
p.status
]);
let csvContent = "\uFEFF" + headers.join(",") + "\n" + rows.map(e => e.join(",")).join("\n");
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.setAttribute("download", `ekeepa_packages_channels_${Date.now()}.csv`);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
initDashboard();
</script>
</body>
</html>