diff --git a/frontend/admin-panel/src/pages/SeoTrackingPage.tsx b/frontend/admin-panel/src/pages/SeoTrackingPage.tsx index c79094ba..3468efe5 100644 --- a/frontend/admin-panel/src/pages/SeoTrackingPage.tsx +++ b/frontend/admin-panel/src/pages/SeoTrackingPage.tsx @@ -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 = { 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 = { + 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([]); @@ -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(null); const modal = useRef(null); const closeButton = useRef(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
-

پایش عملکرد سئو و بازخورد مدیرعامل

نمایش سنجه‌های ثبت‌شده؛ این صفحه اتصال زنده یا اجرای خودکار دستور را تأیید نمی‌کند.

-
- - - - -
- {error &&
{error}
} - {loading &&

در حال دریافت داده‌ها...

} -
{['موضوع و فرضیه', 'کلیدواژه‌ها', 'وضعیت', 'مقاله مرتبط', 'دستور مدیرعامل', 'تاریخ ایجاد', 'عملیات'].map(text => )} - {!loading && !error && findings.length === 0 && } - {findings.map(f => )} -
یافته‌های پژوهش سئو
{text}
موردی یافت نشد.
{f.title}

{f.hypothesis}

{f.primaryKeyword}

{f.targetKeywords?.filter(k => k !== f.primaryKeyword).join('، ')}

{statuses[f.status] ?? f.status}{f.blog ? {f.blog.title} : 'بدون مقاله'}{f.ceoFeedback ? 'دستور ثبت‌شده' : 'ثبت‌نشده'}{date(f.createdAt)}
- - {detailId && createPortal(
{ - if (e.key === 'Escape') { e.stopPropagation(); close(); } - if (e.key === 'Tab') { - const elements = Array.from(modal.current?.querySelectorAll('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, 'خطا در ثبت بازخورد؛ پیش‌نویس حفظ شد.')); } - }}>

{selected?.title ?? 'جزئیات یافته'}

-

سنجه‌ها از تاریخچه ذخیره‌شده هستند، نه درخواست زنده به منابع.

- {detailLoading &&

در حال بارگذاری جزئیات...

} - {detailError &&
{detailError}
} - {selected && !detailLoading && !detailError && <>

فرضیه: {selected.hypothesis}

نتیجه مورد انتظار: {selected.expectedOutcome}

-

تاریخچه سنجه‌های ثبت‌شده

حداکثر ۳۰ پایش اخیر، به ترتیب جدیدترین تاریخ سنجش.

منابع: GSC / GA4 / Commerce. نبود داده با صفر تفاوت دارد. بازه، زمان گردآوری و واحد فروش فقط در صورت گزارش منبع معتبر است.

- {!snapshots.length &&

هنوز اولین پایش سنجه‌ها برای این موضوع ثبت نشده است.

} - {snapshots.map(snapshot =>

تاریخ سنجش: {date(snapshot.snapshotDate)}

بازه: {date(snapshot.periodStart)} تا {date(snapshot.periodEnd)}

زمان گردآوری: {date(snapshot.collectedAt)} — زمان ثبت: {date(snapshot.createdAt)}

    {(['gsc', 'ga4', 'commerce'] as const).map(source => { const provenance = snapshot.sourceMetadata?.[source]; return
  • {source.toUpperCase()}: {provenance ? `${provenance.source} — ${provenance.status} — دریافت: ${date(provenance.fetchedAt)}` : 'منبع تأییدنشده (تاریخی)'}{provenance?.error && ` — ${provenance.error}`}
  • ; })}
{fields.map(([key, label]) =>
{label}
{snapshot.sourceMetadata?.[key.startsWith('gsc') ? 'gsc' : key.startsWith('ga4') ? 'ga4' : 'commerce']?.status === 'available' ? metric(snapshot[key]) : 'ناموجود'}
)}

پیشنهاد ثبت‌شده: {snapshot.actionRecommendation || 'ناموجود'}

{snapshot.analysisNotes &&

{snapshot.analysisNotes}

}
)} -
-

دستور و بازخورد مدیرعامل

ثبت نظر اختیاری است؛ نظر ثبت‌شده باید در اقدامات بعدی رعایت شود. ذخیره در این صفحه به‌تنهایی اثبات اجرای آن در فرایندهای پایین‌دستی نیست.