feat(admin): redesign SEO tracking page with mobile-first card UI and rich status cards
Deploy Canina / deploy (push) Successful in 7m1s

This commit is contained in:
Canina Automation committed 2026-10-28 10:30:04 +00:00
1 parent fb1deadbbc
commit 8197259e54
1 file changed
+760 -62
@@ -1,15 +1,68 @@
import { useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import {
TrendingUp,
Search,
RefreshCw,
Eye,
Calendar,
AlertCircle,
FileText,
X,
Tag,
CheckCircle2,
Clock,
Sparkles,
ExternalLink,
MessageSquare,
ShieldAlert,
ChevronLeft,
ChevronRight,
BarChart2,
Target
} from 'lucide-react';
import { seoTrackingApi, type ResearchFinding, type PerformanceSnapshot } from '../services/seoTrackingApi';
const statuses: Record<string, string> = { RESEARCHED: 'تحقیق‌شده', ACTIONED: 'اقدام‌شده', EVALUATING: 'در حال پایش', SCALED: 'توسعه‌یافته', PRUNED: 'بازنگری / حذف' };
const date = (value?: string | null) => value && Number.isFinite(Date.parse(value)) ? new Date(value).toLocaleString('fa-IR', { timeZone: 'Asia/Tehran' }) : 'نامشخص';
const metric = (value: unknown) => value !== null && value !== undefined && value !== '' && Number.isFinite(Number(value)) ? Number(value).toLocaleString('fa-IR') : 'ناموجود';
const statuses: Record<string, { label: string; bg: string; text: string; border: string }> = {
RESEARCHED: { label: 'تحقیق‌شده', bg: 'bg-sky-50', text: 'text-sky-700', border: 'border-sky-200' },
ACTIONED: { label: 'اقدام‌شده', bg: 'bg-emerald-50', text: 'text-emerald-700', border: 'border-emerald-200' },
EVALUATING: { label: 'در حال پایش', bg: 'bg-amber-50', text: 'text-amber-700', border: 'border-amber-200' },
SCALED: { label: 'توسعه‌یافته', bg: 'bg-purple-50', text: 'text-purple-700', border: 'border-purple-200' },
PRUNED: { label: 'بازنگری / حذف', bg: 'bg-rose-50', text: 'text-rose-700', border: 'border-rose-200' },
};
const date = (value?: string | null) =>
value && Number.isFinite(Date.parse(value))
? new Date(value).toLocaleString('fa-IR', { timeZone: 'Asia/Tehran' })
: 'نامشخص';
const metric = (value: unknown) =>
value !== null && value !== undefined && value !== '' && Number.isFinite(Number(value))
? Number(value).toLocaleString('fa-IR')
: 'ناموجود';
function failure(error: unknown, fallback: string) {
const status = (error as { response?: { status?: number } })?.response?.status;
return status === 404 ? 'یافته پیدا نشد.' : status === 403 ? 'دسترسی به این بخش مجاز نیست.' : status === 401 ? 'نشست منقضی شده؛ دوباره وارد شوید.' : fallback;
return status === 404
? 'یافته پیدا نشد.'
: status === 403
? 'دسترسی به این بخش مجاز نیست.'
: status === 401
? 'نشست منقضی شده؛ دوباره وارد شوید.'
: fallback;
}
const fields: [keyof PerformanceSnapshot, string][] = [['gscImpressions', 'ایمپرشن GSC'], ['gscClicks', 'کلیک GSC'], ['gscPosition', 'رتبه GSC'], ['ga4ActiveUsers', 'کاربران فعال GA4'], ['ga4AvgEngagementSec', 'تعامل GA4 (ثانیه)'], ['ga4BounceRate', 'نرخ پرش GA4'], ['ga4ScrollDepthRate', 'نرخ اسکرول GA4'], ['attributedOrdersCount', 'سفارش‌های منتسب'], ['attributedSalesValue', 'ارزش فروش منتسب']];
const fields: [keyof PerformanceSnapshot, string][] = [
['gscImpressions', 'ایمپرشن GSC'],
['gscClicks', 'کلیک GSC'],
['gscPosition', 'رتبه GSC'],
['ga4ActiveUsers', 'کاربران فعال GA4'],
['ga4AvgEngagementSec', 'تعامل GA4 (ثانیه)'],
['ga4BounceRate', 'نرخ پرش GA4'],
['ga4ScrollDepthRate', 'نرخ اسکرول GA4'],
['attributedOrdersCount', 'سفارش‌های منتسب'],
['attributedSalesValue', 'ارزش فروش منتسب'],
];
export default function SeoTrackingPage() {
const [findings, setFindings] = useState<ResearchFinding[]>([]);
@@ -31,6 +84,7 @@ export default function SeoTrackingPage() {
const [saving, setSaving] = useState(false);
const [conflict, setConflict] = useState(false);
const [feedbackMessage, setFeedbackMessage] = useState('');
const pageContent = useRef<HTMLDivElement>(null);
const modal = useRef<HTMLDivElement>(null);
const closeButton = useRef<HTMLButtonElement>(null);
@@ -39,11 +93,27 @@ export default function SeoTrackingPage() {
useEffect(() => {
const controller = new AbortController();
setLoading(true); setError('');
seoTrackingApi.getFindings({ page, limit: 10, search: search.trim() || undefined, status: status || undefined, sortBy, sortOrder }, controller.signal)
.then(result => { if (!controller.signal.aborted) { setFindings(result.data); setMeta(result.meta); } })
.catch(err => { if (!controller.signal.aborted) setError(failure(err, 'خطا در بارگذاری داده‌ها؛ داده‌های قبلی ممکن است قدیمی باشند.')); })
.finally(() => { if (!controller.signal.aborted) setLoading(false); });
setLoading(true);
setError('');
seoTrackingApi
.getFindings(
{ page, limit: 10, search: search.trim() || undefined, status: status || undefined, sortBy, sortOrder },
controller.signal
)
.then((result) => {
if (!controller.signal.aborted) {
setFindings(result.data);
setMeta(result.meta);
}
})
.catch((err) => {
if (!controller.signal.aborted) {
setError(failure(err, 'خطا در بارگذاری داده‌ها؛ داده‌های قبلی ممکن است قدیمی باشند.'));
}
})
.finally(() => {
if (!controller.signal.aborted) setLoading(false);
});
return () => controller.abort();
}, [page, search, status, sortBy, sortOrder, reload]);
@@ -51,11 +121,24 @@ export default function SeoTrackingPage() {
if (!detailId) return;
const controller = new AbortController();
const generation = ++detailGeneration.current;
setDetailLoading(true); setDetailError(''); setFeedbackMessage('');
seoTrackingApi.getFindingById(detailId, controller.signal).then(data => {
if (!controller.signal.aborted && generation === detailGeneration.current) { setSelected(data); setFeedback(data.ceoFeedback ?? ''); setConflict(false); }
}).catch(err => { if (!controller.signal.aborted) setDetailError(failure(err, 'خطا در دریافت جزئیات.')); })
.finally(() => { if (!controller.signal.aborted) setDetailLoading(false); });
setDetailLoading(true);
setDetailError('');
setFeedbackMessage('');
seoTrackingApi
.getFindingById(detailId, controller.signal)
.then((data) => {
if (!controller.signal.aborted && generation === detailGeneration.current) {
setSelected(data);
setFeedback(data.ceoFeedback ?? '');
setConflict(false);
}
})
.catch((err) => {
if (!controller.signal.aborted) setDetailError(failure(err, 'خطا در دریافت جزئیات.'));
})
.finally(() => {
if (!controller.signal.aborted) setDetailLoading(false);
});
return () => controller.abort();
}, [detailId, detailReload]);
@@ -64,62 +147,677 @@ export default function SeoTrackingPage() {
const previousOverflow = document.body.style.overflow;
const content = pageContent.current;
if (content) content.inert = true;
document.body.style.overflow = 'hidden'; closeButton.current?.focus();
return () => { if (content) content.inert = false; document.body.style.overflow = previousOverflow; opener.current?.focus(); };
document.body.style.overflow = 'hidden';
closeButton.current?.focus();
return () => {
if (content) content.inert = false;
document.body.style.overflow = previousOverflow;
opener.current?.focus();
};
}, [detailId]);
const close = () => { detailGeneration.current++; setDetailId(null); setSelected(null); setSaving(false); };
const close = () => {
detailGeneration.current++;
setDetailId(null);
setSelected(null);
setSaving(false);
};
const save = async () => {
if (!selected || saving || conflict) return;
const generation = detailGeneration.current;
setSaving(true); setFeedbackMessage('');
setSaving(true);
setFeedbackMessage('');
try {
const updated = await seoTrackingApi.updateCeoFeedback(selected.id, feedback.trim(), selected.version);
if (generation !== detailGeneration.current) return;
setSelected(current => current ? { ...current, ...updated, snapshots: updated.snapshots ?? current.snapshots } : current);
setFeedback(updated.ceoFeedback ?? ''); setFeedbackMessage('بازخورد ثبت شد.'); setReload(value => value + 1);
setSelected((current) =>
current ? { ...current, ...updated, snapshots: updated.snapshots ?? current.snapshots } : current
);
setFeedback(updated.ceoFeedback ?? '');
setFeedbackMessage('بازخورد ثبت شد.');
setReload((value) => value + 1);
} catch (err) {
if (generation !== detailGeneration.current) return;
if ((err as { response?: { status?: number } })?.response?.status === 409) { setConflict(true); setFeedbackMessage('رکورد تغییر کرده؛ پیش از ذخیره، نسخه جدید را دریافت کنید. پیش‌نویس شما حفظ شده است.'); }
else setFeedbackMessage(failure(err, 'خطا در ثبت بازخورد؛ پیش‌نویس حفظ شد.'));
} finally { if (generation === detailGeneration.current) setSaving(false); }
};
const snapshots = [...(selected?.snapshots ?? [])].sort((a, b) => Date.parse(b.snapshotDate) - Date.parse(a.snapshotDate));
const control = 'border border-gray-300 rounded-lg p-2 bg-white';
return <div ref={pageContent} className="p-6 space-y-5" dir="rtl">
<header className="flex justify-between gap-4"><div><h1 className="text-xl font-bold">پایش عملکرد سئو و بازخورد مدیرعامل</h1><p>نمایش سنجه‌های ثبت‌شده؛ این صفحه اتصال زنده یا اجرای خودکار دستور را تأیید نمی‌کند.</p></div><button className={control} onClick={() => setReload(n => n + 1)}>به‌روزرسانی</button></header>
<div className="flex flex-wrap gap-3">
<label>جستجو<input className={control} value={search} onChange={e => { setSearch(e.target.value); setPage(1); }} /></label>
<label>وضعیت<select className={control} value={status} onChange={e => { setStatus(e.target.value); setPage(1); }}><option value="">همه وضعیت‌ها</option>{Object.entries(statuses).map(([key, label]) => <option key={key} value={key}>{label}</option>)}</select></label>
<label>مرتب‌سازی<select className={control} value={sortBy} onChange={e => { setSortBy(e.target.value); setPage(1); }}><option value="createdAt">تاریخ ایجاد</option><option value="updatedAt">آخرین تغییر</option><option value="title">عنوان</option><option value="status">وضعیت</option></select></label>
<label>جهت مرتب‌سازی<select className={control} value={sortOrder} onChange={e => { setSortOrder(e.target.value as 'asc' | 'desc'); setPage(1); }}><option value="desc">نزولی</option><option value="asc">صعودی</option></select></label>
</div>
{error && <div role="alert">{error} <button className={control} onClick={() => setReload(n => n + 1)}>تلاش مجدد</button></div>}
{loading && <p role="status">در حال دریافت داده‌ها...</p>}
<div className="overflow-x-auto bg-white rounded-xl"><table className="w-full text-right" aria-busy={loading}><caption className="sr-only">یافته‌های پژوهش سئو</caption><thead><tr>{['موضوع و فرضیه', 'کلیدواژه‌ها', 'وضعیت', 'مقاله مرتبط', 'دستور مدیرعامل', 'تاریخ ایجاد', 'عملیات'].map(text => <th scope="col" key={text} className="p-3">{text}</th>)}</tr></thead><tbody>
{!loading && !error && findings.length === 0 && <tr><td colSpan={7} className="p-5">موردی یافت نشد.</td></tr>}
{findings.map(f => <tr key={f.id} className="border-t"><td className="p-3"><strong>{f.title}</strong><p>{f.hypothesis}</p></td><td>{f.primaryKeyword}<p>{f.targetKeywords?.filter(k => k !== f.primaryKeyword).join('، ')}</p></td><td>{statuses[f.status] ?? f.status}</td><td>{f.blog ? <a className="text-blue-700 underline" href={`https://canina.ir/blog/${encodeURIComponent(f.blog.slug)}`} target="_blank" rel="noopener noreferrer">{f.blog.title}</a> : 'بدون مقاله'}</td><td>{f.ceoFeedback ? 'دستور ثبت‌شده' : 'ثبت‌نشده'}</td><td>{date(f.createdAt)}</td><td><button className={control} onClick={e => { opener.current = e.currentTarget; setSelected(null); setDetailError(''); setFeedbackMessage(''); setDetailId(f.id); }}>مشاهده و پایش</button></td></tr>)}
</tbody></table></div>
<nav aria-label="صفحه‌بندی" className="flex gap-4 items-center"><span>تعداد کل: {meta.total} مورد</span><button className={control} aria-label="صفحه قبل" disabled={loading || !meta.hasPrevPage} onClick={() => setPage(p => Math.max(1, p - 1))}>قبلی</button><span>صفحه {page} از {meta.totalPages || 1}</span><button className={control} aria-label="صفحه بعد" disabled={loading || !meta.hasNextPage} onClick={() => setPage(p => p + 1)}>بعدی</button></nav>
{detailId && createPortal(<div className="fixed inset-0 z-50 bg-black/40 flex items-center justify-center p-4" dir="rtl"><div ref={modal} role="dialog" aria-modal="true" aria-labelledby="seo-detail-title" aria-describedby="seo-detail-description" className="bg-white rounded-xl p-6 w-full max-w-4xl max-h-[90vh] overflow-y-auto space-y-4" onKeyDown={e => {
if (e.key === 'Escape') { e.stopPropagation(); close(); }
if (e.key === 'Tab') {
const elements = Array.from(modal.current?.querySelectorAll<HTMLElement>('button, textarea, a[href], select, input') ?? []).filter(element => !(element as HTMLButtonElement).disabled);
const first = elements[0]; const last = elements[elements.length - 1];
if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last?.focus(); }
else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first?.focus(); }
if ((err as { response?: { status?: number } })?.response?.status === 409) {
setConflict(true);
setFeedbackMessage(
'رکورد تغییر کرده؛ پیش از ذخیره، نسخه جدید را دریافت کنید. پیش‌نویس شما حفظ شده است.'
);
} else {
setFeedbackMessage(failure(err, 'خطا در ثبت بازخورد؛ پیش‌نویس حفظ شد.'));
}
}}><div className="flex justify-between gap-4"><h2 id="seo-detail-title" className="font-bold text-lg">{selected?.title ?? 'جزئیات یافته'}</h2><button ref={closeButton} className={control} onClick={close}>بستن</button></div>
<p id="seo-detail-description">سنجه‌ها از تاریخچه ذخیره‌شده هستند، نه درخواست زنده به منابع.</p>
{detailLoading && <p role="status">در حال بارگذاری جزئیات...</p>}
{detailError && <div role="alert">{detailError} <button className={control} onClick={() => setDetailReload(n => n + 1)}>تلاش مجدد جزئیات</button></div>}
{selected && !detailLoading && !detailError && <><p>فرضیه: {selected.hypothesis}</p><p>نتیجه مورد انتظار: {selected.expectedOutcome}</p>
<section aria-label="تاریخچه سنجه‌ها"><h3 className="font-bold">تاریخچه سنجه‌های ثبت‌شده</h3><p>حداکثر ۳۰ پایش اخیر، به ترتیب جدیدترین تاریخ سنجش.</p><p>منابع: GSC / GA4 / Commerce. نبود داده با صفر تفاوت دارد. بازه، زمان گردآوری و واحد فروش فقط در صورت گزارش منبع معتبر است.</p>
{!snapshots.length && <p>هنوز اولین پایش سنجه‌ها برای این موضوع ثبت نشده است.</p>}
{snapshots.map(snapshot => <article key={snapshot.id} className="border rounded-lg p-3 my-3"><h4>تاریخ سنجش: {date(snapshot.snapshotDate)}</h4><p>بازه: {date(snapshot.periodStart)} تا {date(snapshot.periodEnd)}</p><p>زمان گردآوری: {date(snapshot.collectedAt)} — زمان ثبت: {date(snapshot.createdAt)}</p><ul>{(['gsc', 'ga4', 'commerce'] as const).map(source => { const provenance = snapshot.sourceMetadata?.[source]; return <li key={source}>{source.toUpperCase()}: {provenance ? `${provenance.source} — ${provenance.status} — دریافت: ${date(provenance.fetchedAt)}` : 'منبع تأییدنشده (تاریخی)'}{provenance?.error && ` — ${provenance.error}`}</li>; })}</ul><dl className="grid grid-cols-2 md:grid-cols-3 gap-3">{fields.map(([key, label]) => <div key={key}><dt>{label}</dt><dd className="font-bold">{snapshot.sourceMetadata?.[key.startsWith('gsc') ? 'gsc' : key.startsWith('ga4') ? 'ga4' : 'commerce']?.status === 'available' ? metric(snapshot[key]) : 'ناموجود'}</dd></div>)}</dl><p>پیشنهاد ثبت‌شده: {snapshot.actionRecommendation || 'ناموجود'}</p>{snapshot.analysisNotes && <p>{snapshot.analysisNotes}</p>}</article>)}
</section>
<section><h3 className="font-bold">دستور و بازخورد مدیرعامل</h3><p>ثبت نظر اختیاری است؛ نظر ثبت‌شده باید در اقدامات بعدی رعایت شود. ذخیره در این صفحه به‌تنهایی اثبات اجرای آن در فرایندهای پایین‌دستی نیست.</p><label className="block">بازخورد مدیرعامل<textarea rows={4} maxLength={10000} className={`${control} w-full`} value={feedback} disabled={saving} onChange={e => setFeedback(e.target.value)} /></label><p>آخرین ثبت: {date(selected.feedbackSubmittedAt)}</p><button className={control} disabled={saving || conflict} onClick={save}>{saving ? 'در حال ثبت...' : 'ثبت بازخورد'}</button>{conflict && <button className={control} onClick={() => setDetailReload(n => n + 1)}>دریافت نسخه جدید</button>}{feedbackMessage && <p role="status">{feedbackMessage}</p>}</section>
</>}
</div></div>, document.body)}
</div>;
} finally {
if (generation === detailGeneration.current) setSaving(false);
}
};
const snapshots = [...(selected?.snapshots ?? [])].sort(
(a, b) => Date.parse(b.snapshotDate) - Date.parse(a.snapshotDate)
);
const inputClass =
'w-full text-sm border border-slate-300 rounded-xl px-3 py-2 bg-white text-slate-800 placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-amber-500/20 focus:border-amber-500 transition-all';
return (
<div ref={pageContent} className="p-4 sm:p-6 lg:p-8 space-y-6 max-w-7xl mx-auto" dir="rtl">
{/* هدر صفحه */}
<header className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 pb-2 border-b border-slate-200">
<div>
<div className="flex items-center gap-2.5">
<div className="w-10 h-10 rounded-xl bg-amber-50 border border-amber-200/60 flex items-center justify-center text-amber-600 shadow-sm">
<TrendingUp className="w-5 h-5" />
</div>
<div>
<h1 className="text-xl sm:text-2xl font-black text-slate-900 tracking-tight">
پایش عملکرد سئو و بازخورد مدیرعامل
</h1>
<p className="text-xs sm:text-sm text-slate-500 mt-0.5">
نمایش سنجه‌های ثبت‌شده؛ این صفحه اتصال زنده یا اجرای خودکار دستور را تأیید نمی‌کند.
</p>
</div>
</div>
</div>
<button
className="inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-semibold text-slate-700 bg-white hover:bg-slate-50 border border-slate-200 shadow-sm active:scale-[0.98] transition-all cursor-pointer"
onClick={() => setReload((n) => n + 1)}
>
<RefreshCw className={`w-4 h-4 text-slate-500 ${loading ? 'animate-spin' : ''}`} />
<span>به‌روزرسانی</span>
</button>
</header>
{/* فیلترها و جستجو */}
<div className="bg-white rounded-2xl p-4 sm:p-5 border border-slate-200/80 shadow-sm">
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3.5">
<div>
<label className="block text-xs font-semibold text-slate-600 mb-1.5">
جستجو
<div className="relative mt-1">
<input
className={`${inputClass} pl-9`}
placeholder="عنوان، فرضیه یا کلمه کلیدی..."
value={search}
onChange={(e) => {
setSearch(e.target.value);
setPage(1);
}}
/>
<Search className="w-4 h-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2 pointer-events-none" />
</div>
</label>
</div>
<div>
<label className="block text-xs font-semibold text-slate-600 mb-1.5">
وضعیت
<select
className={`${inputClass} mt-1`}
value={status}
onChange={(e) => {
setStatus(e.target.value);
setPage(1);
}}
>
<option value="">همه وضعیت‌ها</option>
{Object.entries(statuses).map(([key, item]) => (
<option key={key} value={key}>
{item.label}
</option>
))}
</select>
</label>
</div>
<div>
<label className="block text-xs font-semibold text-slate-600 mb-1.5">
مرتب‌سازی
<select
className={`${inputClass} mt-1`}
value={sortBy}
onChange={(e) => {
setSortBy(e.target.value);
setPage(1);
}}
>
<option value="createdAt">تاریخ ایجاد</option>
<option value="updatedAt">آخرین تغییر</option>
<option value="title">عنوان</option>
<option value="status">وضعیت</option>
</select>
</label>
</div>
<div>
<label className="block text-xs font-semibold text-slate-600 mb-1.5">
جهت مرتب‌سازی
<select
className={`${inputClass} mt-1`}
value={sortOrder}
onChange={(e) => {
setSortOrder(e.target.value as 'asc' | 'desc');
setPage(1);
}}
>
<option value="desc">نزولی (جدیدترین)</option>
<option value="asc">صعودی (قدیمی‌ترین)</option>
</select>
</label>
</div>
</div>
</div>
{/* وضعیت‌های خطا و لودینگ */}
{error && (
<div
role="alert"
className="flex items-center justify-between gap-3 p-4 rounded-xl bg-rose-50 border border-rose-200 text-rose-800 text-sm font-medium"
>
<div className="flex items-center gap-2.5">
<AlertCircle className="w-5 h-5 text-rose-600 shrink-0" />
<span>{error}</span>
</div>
<button
className="px-3 py-1.5 rounded-lg bg-white border border-rose-200 text-rose-700 text-xs font-semibold hover:bg-rose-100 transition-colors shrink-0"
onClick={() => setReload((n) => n + 1)}
>
تلاش مجدد
</button>
</div>
)}
{loading && (
<div role="status" className="flex items-center justify-center p-8 text-slate-500 text-sm gap-2">
<RefreshCw className="w-5 h-5 animate-spin text-amber-500" />
<span>در حال دریافت داده‌ها...</span>
</div>
)}
{/* لیست یافته‌ها (سازگار با موبایل و دسکتاپ) */}
<div className="bg-white rounded-2xl border border-slate-200/90 shadow-sm overflow-hidden">
<table className="w-full text-right" aria-busy={loading}>
<caption className="sr-only">یافته‌های پژوهش سئو</caption>
<thead className="hidden md:table-header-group bg-slate-50/80 border-b border-slate-200 text-slate-700 text-xs font-bold uppercase tracking-wider">
<tr>
{['موضوع و فرضیه', 'کلیدواژه‌ها', 'وضعیت', 'مقاله مرتبط', 'دستور مدیرعامل', 'تاریخ ایجاد', 'عملیات'].map(
(text) => (
<th scope="col" key={text} className="p-3.5 first:pr-5 last:pl-5">
{text}
</th>
)
)}
</tr>
</thead>
<tbody className="divide-y divide-slate-100 block md:table-row-group">
{!loading && !error && findings.length === 0 && (
<tr className="block md:table-row">
<td colSpan={7} className="p-12 text-center text-slate-500 text-sm block md:table-cell">
<div className="max-w-xs mx-auto space-y-2">
<FileText className="w-8 h-8 text-slate-300 mx-auto" />
<p className="font-semibold text-slate-700">موردی یافت نشد.</p>
<p className="text-xs text-slate-400">عبارت جستجو یا فیلترهای بالا را تغییر دهید.</p>
</div>
</td>
</tr>
)}
{findings.map((f) => {
const statusCfg = statuses[f.status] ?? {
label: f.status,
bg: 'bg-slate-100',
text: 'text-slate-700',
border: 'border-slate-200',
};
const otherKeywords = f.targetKeywords?.filter((k) => k !== f.primaryKeyword) ?? [];
return (
<tr
key={f.id}
className="block md:table-row p-4 sm:p-5 md:p-0 border-b md:border-b-0 border-slate-100 hover:bg-slate-50/60 transition-colors"
>
{/* موضوع و فرضیه */}
<td className="block md:table-cell p-0 md:p-3.5 md:pr-5 pb-2 md:pb-3.5 align-top">
<div className="space-y-1">
<div className="flex items-center gap-2 md:hidden mb-2">
<span
className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-semibold border ${statusCfg.bg} ${statusCfg.text} ${statusCfg.border}`}
>
{statusCfg.label}
</span>
{f.ceoFeedback ? (
<span className="inline-flex items-center gap-1 text-[11px] font-semibold text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded-full border border-emerald-200">
<CheckCircle2 className="w-3 h-3" />
دستور ثبت‌شده
</span>
) : (
<span className="inline-flex items-center text-[11px] text-slate-500 bg-slate-50 px-2 py-0.5 rounded-full border border-slate-200">
ثبت‌نشده
</span>
)}
</div>
<strong className="block text-sm sm:text-base font-bold text-slate-900 leading-snug">
{f.title}
</strong>
<p className="text-xs sm:text-sm text-slate-600 line-clamp-2 md:line-clamp-none bg-slate-50/80 md:bg-transparent p-2 md:p-0 rounded-lg md:rounded-none border md:border-0 border-slate-100">
{f.hypothesis}
</p>
</div>
</td>
{/* کلیدواژه‌ها */}
<td className="block md:table-cell p-0 md:p-3.5 py-2 md:py-3.5 align-top">
<div className="flex flex-wrap items-center gap-1.5">
<span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-lg text-xs font-bold bg-amber-50 text-amber-800 border border-amber-200">
<Tag className="w-3 h-3 text-amber-600" />
{f.primaryKeyword}
</span>
{otherKeywords.length > 0 && (
<p className="text-xs text-slate-500">
{otherKeywords.join('، ')}
</p>
)}
</div>
</td>
{/* وضعیت (در دسکتاپ) */}
<td className="hidden md:table-cell p-3.5 align-top">
<span
className={`inline-flex items-center px-2.5 py-1 rounded-full text-xs font-semibold border ${statusCfg.bg} ${statusCfg.text} ${statusCfg.border}`}
>
{statusCfg.label}
</span>
</td>
{/* مقاله مرتبط */}
<td className="block md:table-cell p-0 md:p-3.5 py-2 md:py-3.5 align-top text-xs sm:text-sm">
<span className="md:hidden font-semibold text-slate-500 ml-1">مقاله: </span>
{f.blog ? (
<a
className="inline-flex items-center gap-1 text-blue-700 hover:text-blue-800 font-semibold underline underline-offset-2 transition-colors"
href={`https://canina.ir/blog/${encodeURIComponent(f.blog.slug)}`}
target="_blank"
rel="noopener noreferrer"
>
<span>{f.blog.title}</span>
<ExternalLink className="w-3 h-3 shrink-0" />
</a>
) : (
<span className="text-slate-400 font-normal">بدون مقاله</span>
)}
</td>
{/* دستور مدیرعامل (در دسکتاپ) */}
<td className="hidden md:table-cell p-3.5 align-top text-xs sm:text-sm">
{f.ceoFeedback ? (
<span className="inline-flex items-center gap-1 text-xs font-semibold text-emerald-700 bg-emerald-50 px-2.5 py-1 rounded-full border border-emerald-200">
<CheckCircle2 className="w-3.5 h-3.5" />
دستور ثبت‌شده
</span>
) : (
<span className="text-xs text-slate-400 bg-slate-50 px-2.5 py-1 rounded-full border border-slate-200">
ثبت‌نشده
</span>
)}
</td>
{/* تاریخ ایجاد */}
<td className="block md:table-cell p-0 md:p-3.5 py-1 md:py-3.5 align-top text-xs text-slate-500">
<div className="flex items-center gap-1">
<Calendar className="w-3.5 h-3.5 text-slate-400 md:hidden" />
<span>{date(f.createdAt)}</span>
</div>
</td>
{/* دکمه عملیات */}
<td className="block md:table-cell p-0 md:p-3.5 md:pl-5 pt-3 md:pt-3.5 align-top">
<button
className="w-full md:w-auto inline-flex items-center justify-center gap-2 px-3.5 py-2 rounded-xl text-xs sm:text-sm font-semibold text-slate-700 bg-slate-100 hover:bg-slate-200 border border-slate-200 shadow-sm active:scale-[0.98] transition-all cursor-pointer"
onClick={(e) => {
opener.current = e.currentTarget;
setSelected(null);
setDetailError('');
setFeedbackMessage('');
setDetailId(f.id);
}}
>
<Eye className="w-4 h-4 text-slate-600" />
<span>مشاهده و پایش</span>
</button>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
{/* صفحه‌بندی مدرن */}
<nav
aria-label="صفحه‌بندی"
className="flex flex-col sm:flex-row items-center justify-between gap-4 p-4 bg-white rounded-2xl border border-slate-200/90 shadow-sm text-sm text-slate-600"
>
<span className="font-medium text-xs sm:text-sm">تعداد کل: {meta.total} مورد</span>
<div className="flex items-center gap-2">
<button
className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl border border-slate-200 font-semibold text-xs sm:text-sm bg-white hover:bg-slate-50 disabled:opacity-40 disabled:pointer-events-none transition-all cursor-pointer shadow-sm"
aria-label="صفحه قبل"
disabled={loading || !meta.hasPrevPage}
onClick={() => setPage((p) => Math.max(1, p - 1))}
>
<ChevronRight className="w-4 h-4" />
<span>قبلی</span>
</button>
<span className="px-3 py-1 rounded-lg bg-slate-100 font-bold text-xs sm:text-sm text-slate-800">
صفحه {page} از {meta.totalPages || 1}
</span>
<button
className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl border border-slate-200 font-semibold text-xs sm:text-sm bg-white hover:bg-slate-50 disabled:opacity-40 disabled:pointer-events-none transition-all cursor-pointer shadow-sm"
aria-label="صفحه بعد"
disabled={loading || !meta.hasNextPage}
onClick={() => setPage((p) => p + 1)}
>
<span>بعدی</span>
<ChevronLeft className="w-4 h-4" />
</button>
</div>
</nav>
{/* مودال جزئیات و پایش سنجه‌ها */}
{detailId &&
createPortal(
<div className="fixed inset-0 z-50 bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-3 sm:p-6" dir="rtl">
<div
ref={modal}
role="dialog"
aria-modal="true"
aria-labelledby="seo-detail-title"
aria-describedby="seo-detail-description"
className="bg-white rounded-3xl shadow-2xl w-full max-w-4xl max-h-[92vh] flex flex-col overflow-hidden border border-slate-200"
onKeyDown={(e) => {
if (e.key === 'Escape') {
e.stopPropagation();
close();
}
if (e.key === 'Tab') {
const elements = Array.from(
modal.current?.querySelectorAll<HTMLElement>(
'button, textarea, a[href], select, input'
) ?? []
).filter((element) => !(element as HTMLButtonElement).disabled);
const first = elements[0];
const last = elements[elements.length - 1];
if (e.shiftKey && document.activeElement === first) {
e.preventDefault();
last?.focus();
} else if (!e.shiftKey && document.activeElement === last) {
e.preventDefault();
first?.focus();
}
}
}}
>
{/* هدر مودال */}
<div className="flex items-center justify-between gap-4 px-6 py-4 border-b border-slate-200 bg-slate-50/70">
<div className="flex items-center gap-3">
<div className="w-9 h-9 rounded-xl bg-amber-100 text-amber-700 flex items-center justify-center shadow-xs">
<BarChart2 className="w-5 h-5" />
</div>
<div>
<h2 id="seo-detail-title" className="font-black text-base sm:text-lg text-slate-900">
{selected?.title ?? 'جزئیات یافته'}
</h2>
<p id="seo-detail-description" className="text-xs text-slate-500">
سنجه‌ها از تاریخچه ذخیره‌شده هستند، نه درخواست زنده به منابع.
</p>
</div>
</div>
<button
ref={closeButton}
className="p-2 rounded-xl text-slate-500 hover:text-slate-800 hover:bg-slate-200/80 transition-colors cursor-pointer"
onClick={close}
aria-label="بستن"
>
<X className="w-5 h-5" />
<span className="sr-only">بستن</span>
</button>
</div>
{/* بدنه مودال با اسکرول */}
<div className="p-6 overflow-y-auto space-y-6">
{detailLoading && (
<div role="status" className="flex items-center justify-center p-12 text-slate-500 text-sm gap-2">
<RefreshCw className="w-5 h-5 animate-spin text-amber-500" />
<span>در حال بارگذاری جزئیات...</span>
</div>
)}
{detailError && (
<div
role="alert"
className="p-4 rounded-xl bg-rose-50 border border-rose-200 text-rose-800 text-sm flex items-center justify-between"
>
<span>{detailError}</span>
<button
className="px-3 py-1.5 rounded-lg bg-white border border-rose-200 text-rose-700 text-xs font-semibold hover:bg-rose-100"
onClick={() => setDetailReload((n) => n + 1)}
>
تلاش مجدد جزئیات
</button>
</div>
)}
{selected && !detailLoading && !detailError && (
<>
{/* کارت فرضیه و هدف کلیدی */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="bg-sky-50/60 rounded-2xl p-4 border border-sky-100">
<div className="flex items-center gap-2 text-sky-800 font-bold text-xs mb-1.5">
<Sparkles className="w-4 h-4 text-sky-600" />
<span>فرضیه تحقیق</span>
</div>
<p className="text-xs sm:text-sm text-slate-700 leading-relaxed">
فرضیه: {selected.hypothesis}
</p>
</div>
<div className="bg-emerald-50/60 rounded-2xl p-4 border border-emerald-100">
<div className="flex items-center gap-2 text-emerald-800 font-bold text-xs mb-1.5">
<Target className="w-4 h-4 text-emerald-600" />
<span>هدف و دستاورد مورد انتظار</span>
</div>
<p className="text-xs sm:text-sm text-slate-700 leading-relaxed">
نتیجه مورد انتظار: {selected.expectedOutcome}
</p>
</div>
</div>
{/* تاریخچه سنجه‌ها */}
<section aria-label="تاریخچه سنجه‌ها" className="space-y-4">
<div className="flex items-center justify-between pb-2 border-b border-slate-100">
<div>
<h3 className="font-bold text-sm sm:text-base text-slate-900 flex items-center gap-2">
<Clock className="w-4 h-4 text-slate-500" />
<span>تاریخچه سنجه‌های ثبت‌شده</span>
</h3>
<p className="text-xs text-slate-500 mt-0.5">
حداکثر ۳۰ پایش اخیر، به ترتیب جدیدترین تاریخ سنجش.
</p>
</div>
</div>
<p className="text-xs text-slate-500 bg-slate-50 p-3 rounded-xl border border-slate-100">
منابع: GSC / GA4 / Commerce. نبود داده با صفر تفاوت دارد. بازه، زمان گردآوری و واحد فروش فقط در صورت گزارش منبع معتبر است.
</p>
{!snapshots.length && (
<div className="p-8 text-center bg-slate-50 rounded-2xl border border-slate-100">
<p className="text-sm font-semibold text-slate-600">
هنوز اولین پایش سنجه‌ها برای این موضوع ثبت نشده است.
</p>
<p className="text-xs text-slate-400 mt-1">
ورکر پایش دوره‌ای پس از انتشار مقاله و گذر زمان مورد نیاز سنجه‌های عملکرد را ثبت خواهد کرد.
</p>
</div>
)}
{snapshots.map((snapshot) => (
<article
key={snapshot.id}
className="bg-white rounded-2xl p-5 border border-slate-200/90 shadow-xs space-y-4"
>
{/* هدر کارت پایش */}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 pb-3 border-b border-slate-100">
<h4 className="font-bold text-sm text-slate-800 flex items-center gap-1.5">
<Calendar className="w-4 h-4 text-amber-500" />
<span>تاریخ سنجش: {date(snapshot.snapshotDate)}</span>
</h4>
<div className="text-xs text-slate-500">
<span>بازه: {date(snapshot.periodStart)} تا {date(snapshot.periodEnd)}</span>
</div>
</div>
<div className="text-[11px] text-slate-400 flex flex-wrap gap-x-4 gap-y-1">
<span>زمان گردآوری: {date(snapshot.collectedAt)} — زمان ثبت: {date(snapshot.createdAt)}</span>
</div>
{/* وضعیت منابع */}
<ul className="flex flex-wrap gap-2 text-xs">
{(['gsc', 'ga4', 'commerce'] as const).map((source) => {
const provenance = snapshot.sourceMetadata?.[source];
const isAvailable = provenance?.status === 'available';
return (
<li
key={source}
className={`px-3 py-1 rounded-lg border text-xs font-medium ${
isAvailable
? 'bg-emerald-50 text-emerald-800 border-emerald-200'
: 'bg-slate-50 text-slate-600 border-slate-200'
}`}
>
{source.toUpperCase()}:{' '}
{provenance
? `${provenance.source} — ${provenance.status} — دریافت: ${date(provenance.fetchedAt)}`
: 'منبع تأییدنشده (تاریخی)'}
{provenance?.error && ` — ${provenance.error}`}
</li>
);
})}
</ul>
{/* جدول ماتریسی مقادیر سنجه‌ها */}
<dl className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-3 gap-3">
{fields.map(([key, label]) => {
const sourceKey = key.startsWith('gsc')
? 'gsc'
: key.startsWith('ga4')
? 'ga4'
: 'commerce';
const isAvail = snapshot.sourceMetadata?.[sourceKey]?.status === 'available';
return (
<div
key={key}
className="bg-slate-50/70 p-3 rounded-xl border border-slate-100 flex flex-col justify-between"
>
<dt className="text-xs text-slate-500 font-medium mb-1">{label}</dt>
<dd className="font-black text-base sm:text-lg text-slate-900 tracking-tight">
{isAvail ? metric(snapshot[key]) : 'ناموجود'}
</dd>
</div>
);
})}
</dl>
{/* توصیه پیشنهادی هوشمند */}
<div className="bg-amber-50/70 border border-amber-200/80 p-3.5 rounded-xl space-y-1">
<div className="flex items-center gap-1.5 text-xs font-bold text-amber-900">
<Sparkles className="w-3.5 h-3.5 text-amber-600" />
<span>پیشنهاد سیستم:</span>
</div>
<p className="text-xs sm:text-sm text-amber-950 font-medium">
پیشنهاد ثبت‌شده: {snapshot.actionRecommendation || 'ناموجود'}
</p>
</div>
{snapshot.analysisNotes && (
<p className="text-xs text-slate-600 bg-slate-50 p-3 rounded-xl border border-slate-100">
{snapshot.analysisNotes}
</p>
)}
</article>
))}
</section>
{/* ثبت بازخورد و دستور مدیرعامل */}
<section className="bg-slate-50 rounded-2xl p-5 border border-slate-200 space-y-4">
<div className="flex items-center gap-2">
<MessageSquare className="w-5 h-5 text-amber-600" />
<div>
<h3 className="font-bold text-sm sm:text-base text-slate-900">
دستور و بازخورد مدیرعامل
</h3>
<p className="text-xs text-slate-500 mt-0.5">
ثبت نظر اختیاری است؛ نظر ثبت‌شده باید در اقدامات بعدی رعایت شود. ذخیره در این صفحه به‌تنهایی اثبات اجرای آن در فرایندهای پایین‌دستی نیست.
</p>
</div>
</div>
<div>
<label className="block text-xs font-bold text-slate-700 mb-1.5">
بازخورد مدیرعامل
<textarea
rows={4}
maxLength={10000}
className="mt-1 w-full text-sm border border-slate-300 rounded-xl p-3 bg-white text-slate-800 placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-amber-500/20 focus:border-amber-500 transition-all"
placeholder="دستورات استراتژیک، تعیین اولویت یا اصلاحیه برای این موضوع..."
value={feedback}
disabled={saving}
onChange={(e) => setFeedback(e.target.value)}
/>
</label>
<p className="text-xs text-slate-400 mt-1">آخرین ثبت: {date(selected.feedbackSubmittedAt)}</p>
</div>
<div className="flex flex-wrap items-center gap-3 pt-2">
<button
className="px-5 py-2.5 rounded-xl font-bold text-sm bg-amber-500 hover:bg-amber-600 text-slate-950 shadow-sm active:scale-[0.98] transition-all cursor-pointer disabled:opacity-50 disabled:pointer-events-none"
disabled={saving || conflict}
onClick={save}
>
{saving ? 'در حال ثبت...' : 'ثبت بازخورد'}
</button>
{conflict && (
<button
className="px-4 py-2.5 rounded-xl font-semibold text-sm bg-rose-100 hover:bg-rose-200 text-rose-800 border border-rose-200 transition-all cursor-pointer"
onClick={() => setDetailReload((n) => n + 1)}
>
دریافت نسخه جدید
</button>
)}
{feedbackMessage && (
<p
role="status"
className={`text-xs font-semibold px-3 py-1.5 rounded-lg ${
conflict
? 'bg-rose-50 text-rose-700 border border-rose-200'
: 'bg-emerald-50 text-emerald-700 border border-emerald-200'
}`}
>
{feedbackMessage}
</p>
)}
</div>
</section>
</>
)}
</div>
</div>
</div>,
document.body
)}
</div>
);
}