feat(admin): complete resilient SEO tracking and versioned feedback UI

This commit is contained in:
Canina Automation committed 2026-10-28 07:10:09 +00:00
1 parent 6102556eae
commit df5584d214
6 files changed
+384 -528

No files matched your search

@@ -1,64 +1,86 @@
import { render, screen, waitFor } from '@testing-library/react';
import { BrowserRouter } from 'react-router-dom';
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import SeoTrackingPage from './SeoTrackingPage';
import { seoTrackingApi } from '../services/seoTrackingApi';
import { vi, describe, it, expect, beforeEach } from 'vitest';
vi.mock('../services/seoTrackingApi', () => ({
seoTrackingApi: {
getFindings: vi.fn(),
getFindingById: vi.fn(),
updateCeoFeedback: vi.fn(),
},
}));
describe('SeoTrackingPage Admin UI', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('renders table headers and findings correctly', async () => {
(seoTrackingApi.getFindings as any).mockResolvedValueOnce({
data: [
{
id: 'test-finding-1',
title: 'بررسی پوکی استخوان در سگ‌های مسن',
hypothesis: 'کمبود گلوکزآمین در جیره غذایی',
primaryKeyword: 'گلوکزآمین سگ',
targetKeywords: ['گلوکزآمین سگ'],
expectedOutcome: 'افزایش فروش مکمل مفاصل',
status: 'ACTIONED',
blog: {
id: 'b1',
title: 'مقاله سلامت مفاصل',
slug: 'dog-joint-health',
},
ceoFeedback: 'روی نژاد ژرمن شپرد تمرکز شود',
},
],
meta: {
total: 1,
page: 1,
limit: 10,
totalPages: 1,
lastPage: 1,
hasNextPage: false,
hasPrevPage: false,
},
});
render(
<BrowserRouter>
<SeoTrackingPage />
</BrowserRouter>
);
expect(screen.getByText('پایش عملکرد سئو و بازخورد مدیرعامل')).toBeDefined();
await waitFor(() => {
expect(screen.getByText('بررسی پوکی استخوان در سگ‌های مسن')).toBeDefined();
expect(screen.getByText('گلوکزآمین سگ')).toBeDefined();
expect(screen.getByText('دستور ثبت‌شده')).toBeDefined();
});
});
import { seoTrackingApi, type ResearchFinding } from '../services/seoTrackingApi';
vi.mock('../services/seoTrackingApi', () => ({ seoTrackingApi: { getFindings: vi.fn(), getFindingById: vi.fn(), updateCeoFeedback: vi.fn() } }));
const finding = { id: 'f1', title: 'موضوع آزمایشی', hypothesis: 'فرضیه', primaryKeyword: 'کلید', targetKeywords: ['کلید', 'دوم'], expectedOutcome: 'هدف', status: 'ACTIONED', version: 0, createdAt: '2026-10-01T00:00:00Z', updatedAt: '2026-10-02T00:00:00Z', snapshots: [{ id: 's1', snapshotDate: '2026-10-03T00:00:00Z', sourceMetadata: { gsc: { status: 'available', source: 'Search Console', fetchedAt: '2026-10-03T00:00:00Z' }, ga4: { status: 'unavailable', source: 'GA4', fetchedAt: '2026-10-03T00:00:00Z' }, commerce: { status: 'unavailable', source: 'Orders', fetchedAt: '2026-10-03T00:00:00Z' } }, gscImpressions: 0, gscClicks: null, ga4ActiveUsers: null, attributedOrdersCount: null, attributedSalesValue: null }] } as ResearchFinding;
const response = (data = [finding], page = 1, totalPages = 2) => ({ data, meta: { total: 11, page, limit: 10, totalPages, lastPage: totalPages, hasNextPage: page < totalPages, hasPrevPage: page > 1 } });
const list = vi.mocked(seoTrackingApi.getFindings);
const detail = vi.mocked(seoTrackingApi.getFindingById);
const save = vi.mocked(seoTrackingApi.updateCeoFeedback);
async function open() { render(<SeoTrackingPage />); const trigger = await screen.findByRole('button', { name: /مشاهده و پایش/ }); fireEvent.click(trigger); await screen.findByRole('textbox', { name: 'بازخورد مدیرعامل' }); return trigger; }
beforeEach(() => { vi.resetAllMocks(); list.mockResolvedValue(response()); detail.mockResolvedValue(finding); save.mockResolvedValue({ ...finding, ceoFeedback: 'دستور', updatedAt: '2026-10-04T00:00:00Z', snapshots: undefined }); });
afterEach(cleanup);
describe('SEO tracking interactions', () => {
it('renders all history newest first, source periods and legacy provenance without claiming measured zeros', async () => {
detail.mockResolvedValue({ ...finding, snapshots: [
{ ...finding.snapshots![0], id: 'old', snapshotDate: '2026-01-01T00:00:00Z', sourceMetadata: null, actionRecommendation: 'OLD' },
{ ...finding.snapshots![0], id: 'new', snapshotDate: '2026-10-03T00:00:00Z', periodStart: '2026-10-01T00:00:00Z', periodEnd: '2026-10-02T00:00:00Z', actionRecommendation: 'NEW' },
] });
await open(); const articles = within(screen.getByRole('dialog')).getAllByRole('article');
expect(articles).toHaveLength(2); expect(articles[0].textContent).toContain('NEW'); expect(articles[1].textContent).toContain('OLD');
expect(articles[0].textContent).toContain('Search Console'); expect(articles[0].textContent).toContain('available'); expect(articles[0].textContent).toContain('۱۴۰۵/۷/۹');
expect(articles[1].textContent).toContain('منبع تأییدنشده (تاریخی)'); expect(within(articles[1]).queryByText('۰')).toBeNull();
});
it('preserves draft on save failure and sends the new version on subsequent saves, including clear', async () => {
await open(); save.mockRejectedValueOnce(new Error('offline'));
const field = screen.getByLabelText('بازخورد مدیرعامل'); fireEvent.change(field, { target: { value: 'draft' } }); fireEvent.click(screen.getByRole('button', { name: 'ثبت بازخورد' }));
await screen.findByText(/خطا در ثبت بازخورد/); expect((field as HTMLTextAreaElement).value).toBe('draft');
save.mockResolvedValueOnce({ ...finding, ceoFeedback: 'draft', version: 1, snapshots: undefined }); fireEvent.click(screen.getByRole('button', { name: 'ثبت بازخورد' })); await screen.findByText('بازخورد ثبت شد.');
fireEvent.change(field, { target: { value: ' ' } }); fireEvent.click(screen.getByRole('button', { name: 'ثبت بازخورد' }));
await waitFor(() => expect(save).toHaveBeenLastCalledWith('f1', '', 1));
});
it('shows no-snapshot state and initial upstream/access errors distinctly from empty data', async () => {
list.mockRejectedValueOnce({ response: { status: 403 } }); render(<SeoTrackingPage />); await screen.findByText('دسترسی به این بخش مجاز نیست.'); expect(screen.queryByText('موردی یافت نشد.')).toBeNull();
fireEvent.click(screen.getByRole('button', { name: 'تلاش مجدد' })); detail.mockResolvedValue({ ...finding, snapshots: [] }); fireEvent.click(await screen.findByRole('button', { name: /مشاهده و پایش/ })); await screen.findByText('هنوز اولین پایش سنجه‌ها برای این موضوع ثبت نشده است.');
});
it('sends server paging, search, filters and sort and resets page', async () => {
render(<SeoTrackingPage />); await screen.findByText(finding.title);
fireEvent.click(screen.getByRole('button', { name: 'صفحه بعد' }));
await waitFor(() => expect(list).toHaveBeenLastCalledWith(expect.objectContaining({ page: 2 }), expect.any(AbortSignal)));
fireEvent.change(screen.getByLabelText('جستجو'), { target: { value: 'سگ' } });
fireEvent.change(screen.getByLabelText('وضعیت'), { target: { value: 'ACTIONED' } });
fireEvent.change(screen.getByLabelText('مرتب‌سازی'), { target: { value: 'title' } });
fireEvent.change(screen.getByLabelText('جهت مرتب‌سازی'), { target: { value: 'asc' } });
await waitFor(() => expect(list).toHaveBeenLastCalledWith(expect.objectContaining({ page: 1, search: 'سگ', status: 'ACTIONED', sortBy: 'title', sortOrder: 'asc' }), expect.any(AbortSignal)));
});
it('distinguishes empty from errors, retaining old rows on failed refresh', async () => {
render(<SeoTrackingPage />); await screen.findByText(finding.title); list.mockRejectedValueOnce(new Error('offline'));
fireEvent.click(screen.getByRole('button', { name: 'به‌روزرسانی' }));
await screen.findByRole('alert'); expect(screen.getByText(finding.title)).toBeDefined(); expect(screen.queryByText('موردی یافت نشد.')).toBeNull();
list.mockResolvedValueOnce(response([], 1, 0)); fireEvent.click(screen.getByRole('button', { name: 'تلاش مجدد' })); await screen.findByText('موردی یافت نشد.');
});
it('renders snapshot history, real zero vs unavailable, saves version and retains history', async () => {
await open(); const dialog = screen.getByRole('dialog');
expect(within(dialog).getByText('تاریخچه سنجه‌های ثبت‌شده')).toBeDefined(); expect(within(dialog).getAllByText('ناموجود').length).toBeGreaterThan(0); expect(within(dialog).getByText('۰')).toBeDefined();
expect(within(dialog).queryByText(/پایش زنده/)).toBeNull();
fireEvent.change(screen.getByLabelText('بازخورد مدیرعامل'), { target: { value: 'دستور' } }); fireEvent.click(screen.getByRole('button', { name: 'ثبت بازخورد' }));
await waitFor(() => expect(save).toHaveBeenCalledWith('f1', 'دستور', finding.version)); await screen.findByText('بازخورد ثبت شد.'); expect(screen.getByText('۰')).toBeDefined();
});
it('handles conflict without discarding draft, and explicitly reloads latest', async () => {
save.mockRejectedValue({ response: { status: 409 } }); await open();
fireEvent.change(screen.getByLabelText('بازخورد مدیرعامل'), { target: { value: 'پیش‌نویس' } }); fireEvent.click(screen.getByRole('button', { name: 'ثبت بازخورد' }));
await screen.findByText(/رکورد تغییر کرده/); expect((screen.getByLabelText('بازخورد مدیرعامل') as HTMLTextAreaElement).value).toBe('پیش‌نویس');
expect(screen.getByRole('button', { name: 'ثبت بازخورد' }).hasAttribute('disabled')).toBe(true);
detail.mockResolvedValue({ ...finding, ceoFeedback: 'جدید' }); fireEvent.click(screen.getByRole('button', { name: 'دریافت نسخه جدید' })); await waitFor(() => expect((screen.getByLabelText('بازخورد مدیرعامل') as HTMLTextAreaElement).value).toBe('جدید'));
});
it('focuses modal, traps tabs, Escape closes and restores trigger focus', async () => {
const trigger = await open(); const dialog = screen.getByRole('dialog'); const close = within(dialog).getByRole('button', { name: 'بستن' });
expect(dialog.getAttribute('aria-modal')).toBe('true'); expect(document.activeElement).toBe(close);
close.focus(); fireEvent.keyDown(dialog, { key: 'Tab', shiftKey: true }); expect(document.activeElement).toBe(screen.getByRole('button', { name: 'ثبت بازخورد' }));
fireEvent.keyDown(dialog, { key: 'Escape' }); expect(screen.queryByRole('dialog')).toBeNull(); expect(document.activeElement).toBe(trigger);
});
it('shows loading detail immediately and distinct not-found/access errors with retry', async () => {
detail.mockRejectedValueOnce({ response: { status: 404 } }); render(<SeoTrackingPage />); fireEvent.click(await screen.findByRole('button', { name: /مشاهده و پایش/ })); await screen.findByText('یافته پیدا نشد.');
fireEvent.click(screen.getByRole('button', { name: 'تلاش مجدد جزئیات' })); await screen.findByLabelText('بازخورد مدیرعامل');
});
it('cancels requests and ignores stale list/detail completions', async () => {
let resolveOld!: (value: ReturnType<typeof response>) => void;
list.mockImplementationOnce(() => new Promise(resolve => { resolveOld = resolve; })); render(<SeoTrackingPage />);
fireEvent.change(screen.getByLabelText('جستجو'), { target: { value: 'new' } }); await screen.findByText(finding.title);
expect(list.mock.calls[0][1]?.aborted).toBe(true); resolveOld(response([{ ...finding, title: 'stale' }])); await new Promise(resolve => setTimeout(resolve, 0)); expect(screen.queryByText('stale')).toBeNull();
let finish!: (value: ResearchFinding) => void; detail.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
fireEvent.click(screen.getByRole('button', { name: /مشاهده و پایش/ })); expect(screen.getByRole('dialog')).toBeDefined(); fireEvent.click(screen.getByRole('button', { name: 'بستن' })); finish(finding);
await new Promise(resolve => setTimeout(resolve, 0)); expect(screen.queryByRole('dialog')).toBeNull(); expect(detail.mock.calls[0][1]?.aborted).toBe(true);
});
});
+111 -436
View File
@@ -1,450 +1,125 @@
import { useState, useEffect, useCallback } from 'react';
import {
TrendingUp,
Search,
Filter,
Eye,
MessageSquare,
Sparkles,
RefreshCw,
ExternalLink,
ChevronLeft,
ChevronRight,
BarChart2,
Send,
} from 'lucide-react';
import toast from 'react-hot-toast';
import {
seoTrackingApi,
type ResearchFinding,
type PerformanceSnapshot,
} from '../services/seoTrackingApi';
import { useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { seoTrackingApi, type ResearchFinding, type PerformanceSnapshot } from '../services/seoTrackingApi';
const STATUS_LABELS: Record<string, { label: string; color: string }> = {
RESEARCHED: { label: 'تحقیق‌شده', color: 'bg-blue-50 text-blue-700 border-blue-200' },
ACTIONED: { label: 'اقدام‌شده (مقاله زنده)', color: 'bg-emerald-50 text-emerald-700 border-emerald-200' },
EVALUATING: { label: 'در حال پایش سنجه‌ها', color: 'bg-amber-50 text-amber-700 border-amber-200' },
SCALED: { label: 'توسعه‌یافته (موفق)', color: 'bg-purple-50 text-purple-700 border-purple-200' },
PRUNED: { label: 'بازنگری / حذف', color: 'bg-rose-50 text-rose-700 border-rose-200' },
};
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') : 'ناموجود';
function failure(error: unknown, fallback: string) {
const status = (error as { response?: { status?: number } })?.response?.status;
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', 'ارزش فروش منتسب']];
export default function SeoTrackingPage() {
const [findings, setFindings] = useState<ResearchFinding[]>([]);
const [loading, setLoading] = useState(true);
const [page, setPage] = useState(1);
const [limit] = useState(10);
const [totalPages, setTotalPages] = useState(1);
const [totalCount, setTotalCount] = useState(0);
const [meta, setMeta] = useState({ total: 0, totalPages: 0, hasNextPage: false, hasPrevPage: false });
const [search, setSearch] = useState('');
const [statusFilter, setStatusFilter] = useState('');
// Detail Modal & CEO Feedback
const [selectedFinding, setSelectedFinding] = useState<ResearchFinding | null>(null);
const [status, setStatus] = useState('');
const [sortBy, setSortBy] = useState('createdAt');
const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc');
const [reload, setReload] = useState(0);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
const [detailId, setDetailId] = useState<string | null>(null);
const [selected, setSelected] = useState<ResearchFinding | null>(null);
const [detailLoading, setDetailLoading] = useState(false);
const [feedbackText, setFeedbackText] = useState('');
const [submittingFeedback, setSubmittingFeedback] = useState(false);
const fetchFindings = useCallback(async () => {
try {
setLoading(true);
const res = await seoTrackingApi.getFindings({
page,
limit,
search: search.trim() || undefined,
status: statusFilter || undefined,
});
setFindings(res.data);
setTotalPages(res.meta.totalPages);
setTotalCount(res.meta.total);
} catch {
toast.error('خطا در بارگذاری داده‌های پایش سئو');
} finally {
setLoading(false);
}
}, [page, limit, search, statusFilter]);
const [detailError, setDetailError] = useState('');
const [detailReload, setDetailReload] = useState(0);
const [feedback, setFeedback] = useState('');
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);
const opener = useRef<HTMLElement | null>(null);
const detailGeneration = useRef(0);
useEffect(() => {
fetchFindings();
}, [fetchFindings]);
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); });
return () => controller.abort();
}, [page, search, status, sortBy, sortOrder, reload]);
const handleOpenDetail = async (id: string) => {
useEffect(() => {
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); });
return () => controller.abort();
}, [detailId, detailReload]);
useEffect(() => {
if (!detailId) return;
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(); };
}, [detailId]);
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('');
try {
setDetailLoading(true);
const data = await seoTrackingApi.getFindingById(id);
setSelectedFinding(data);
setFeedbackText(data.ceoFeedback || '');
} catch {
toast.error('خطا در دریافت جزئیات یافته سئو');
} finally {
setDetailLoading(false);
}
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);
} 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 handleSaveCeoFeedback = async () => {
if (!selectedFinding) return;
try {
setSubmittingFeedback(true);
const updated = await seoTrackingApi.updateCeoFeedback(
selectedFinding.id,
feedbackText.trim()
);
setSelectedFinding(updated);
toast.success('دستور و بازخورد مدیرعامل با موفقیت ثبت شد');
fetchFindings();
} catch {
toast.error('خطا در ثبت بازخورد مدیرعامل');
} finally {
setSubmittingFeedback(false);
}
};
const latestSnapshot: PerformanceSnapshot | undefined =
selectedFinding?.snapshots && selectedFinding.snapshots.length > 0
? selectedFinding.snapshots[0]
: undefined;
return (
<div className="p-6 space-y-6 font-vazir" dir="rtl">
{/* Header */}
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4 bg-white p-6 rounded-2xl shadow-sm border border-gray-100">
<div className="flex items-center gap-3">
<div className="p-3 bg-purple-50 text-purple-600 rounded-xl">
<TrendingUp className="w-6 h-6" />
</div>
<div>
<h1 className="text-xl font-black text-gray-900">
پایش عملکرد سئو و بازخورد مدیرعامل
</h1>
<p className="text-xs text-gray-500 mt-1">
اتصال هوشمند نتایج تحقیقات روزانه سئو به سنجه‌های زنده گوگل (GSC)، رفتار کاربر (GA4) و فروش استور
</p>
</div>
</div>
<button
onClick={fetchFindings}
className="flex items-center gap-2 px-4 py-2 text-sm font-bold text-gray-700 bg-gray-50 hover:bg-gray-100 rounded-xl transition border border-gray-200"
>
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
به‌روزرسانی
</button>
</div>
{/* Filter and Search Bar */}
<div className="flex flex-col md:flex-row gap-4">
<div className="relative flex-1">
<Search className="w-5 h-5 text-gray-400 absolute right-3.5 top-3" />
<input
type="text"
value={search}
onChange={(e) => {
setSearch(e.target.value);
setPage(1);
}}
placeholder="جستجو در موضوع، کلیدواژه یا فرضیه سئو..."
className="w-full pl-4 pr-11 py-2.5 bg-white border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-purple-500"
/>
</div>
<div className="flex items-center gap-2">
<Filter className="w-5 h-5 text-gray-400" />
<select
value={statusFilter}
onChange={(e) => {
setStatusFilter(e.target.value);
setPage(1);
}}
className="bg-white border border-gray-200 text-sm font-medium rounded-xl px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-purple-500"
>
<option value="">همه وضعیت‌ها</option>
<option value="RESEARCHED">تحقیق‌شده</option>
<option value="ACTIONED">اقدام‌شده (مقاله زنده)</option>
<option value="EVALUATING">در حال پایش</option>
<option value="SCALED">توسعه‌یافته (موفق)</option>
<option value="PRUNED">بازنگری / حذف</option>
</select>
</div>
</div>
{/* Main Table */}
<div className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
<div className="overflow-x-auto">
<table className="w-full text-right text-sm">
<thead className="bg-gray-50/75 border-b border-gray-100 text-gray-500 font-bold text-xs">
<tr>
<th className="p-4">موضوع و فرضیه</th>
<th className="p-4">کلیدواژه اصلی</th>
<th className="p-4">وضعیت</th>
<th className="p-4">مقاله مرتبط</th>
<th className="p-4">دستور مدیرعامل</th>
<th className="p-4 text-center">عملیات</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-50">
{loading ? (
<tr>
<td colSpan={6} className="p-8 text-center text-gray-400">
<RefreshCw className="w-6 h-6 animate-spin mx-auto mb-2 text-purple-600" />
در حال دریافت داده‌ها...
</td>
</tr>
) : findings.length === 0 ? (
<tr>
<td colSpan={6} className="p-8 text-center text-gray-400">
موردی یافت نشد.
</td>
</tr>
) : (
findings.map((f) => {
const statusInfo = STATUS_LABELS[f.status] || {
label: f.status,
color: 'bg-gray-100 text-gray-600 border-gray-200',
};
return (
<tr key={f.id} className="hover:bg-gray-50/50 transition">
<td className="p-4 max-w-xs">
<div className="font-bold text-gray-900 line-clamp-1">{f.title}</div>
<div className="text-xs text-gray-400 line-clamp-1 mt-0.5">{f.hypothesis}</div>
</td>
<td className="p-4">
<span className="inline-block px-2.5 py-1 bg-gray-100 text-gray-700 text-xs font-semibold rounded-lg">
{f.primaryKeyword}
</span>
</td>
<td className="p-4">
<span
className={`inline-block px-2.5 py-1 rounded-full text-xs font-bold border ${statusInfo.color}`}
>
{statusInfo.label}
</span>
</td>
<td className="p-4">
{f.blog ? (
<a
href={`https://canina.ir/blog/${f.blog.slug}`}
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-1 text-xs text-purple-600 hover:text-purple-800 font-bold"
>
<span>{f.blog.title}</span>
<ExternalLink className="w-3 h-3" />
</a>
) : (
<span className="text-xs text-gray-400">بدون مقاله</span>
)}
</td>
<td className="p-4">
{f.ceoFeedback ? (
<span className="inline-flex items-center gap-1 text-xs font-bold text-purple-700 bg-purple-50 px-2.5 py-1 rounded-lg">
<Sparkles className="w-3.5 h-3.5" />
دستور ثبت‌شده
</span>
) : (
<span className="text-xs text-gray-400">ثبت‌نشده</span>
)}
</td>
<td className="p-4 text-center">
<button
onClick={() => handleOpenDetail(f.id)}
className="inline-flex items-center gap-1.5 px-3 py-1.5 bg-purple-50 hover:bg-purple-100 text-purple-700 text-xs font-bold rounded-lg transition"
>
<Eye className="w-3.5 h-3.5" />
مشاهده و پایش
</button>
</td>
</tr>
);
})
)}
</tbody>
</table>
</div>
{/* Pagination Footer */}
<div className="p-4 border-t border-gray-100 flex items-center justify-between text-xs text-gray-500 font-medium">
<div>
تعداد کل: <span className="font-bold text-gray-800">{totalCount}</span> مورد
</div>
<div className="flex items-center gap-2">
<button
disabled={page <= 1}
onClick={() => setPage((p) => Math.max(1, p - 1))}
className="p-1.5 rounded-lg border border-gray-200 disabled:opacity-30 hover:bg-gray-50"
>
<ChevronRight className="w-4 h-4" />
</button>
<span>
صفحه {page} از {totalPages || 1}
</span>
<button
disabled={page >= totalPages}
onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
className="p-1.5 rounded-lg border border-gray-200 disabled:opacity-30 hover:bg-gray-50"
>
<ChevronLeft className="w-4 h-4" />
</button>
</div>
</div>
</div>
{/* Detail & CEO Feedback Modal */}
{selectedFinding && (
<div className="fixed inset-0 z-50 bg-black/40 backdrop-blur-sm flex items-center justify-center p-4">
<div className="bg-white w-full max-w-3xl rounded-3xl shadow-xl border border-gray-100 overflow-hidden max-h-[90vh] flex flex-col">
{/* Modal Header */}
<div className="p-6 border-b border-gray-100 flex items-center justify-between">
<div>
<h2 className="text-lg font-black text-gray-900">{selectedFinding.title}</h2>
<div className="flex items-center gap-2 mt-1">
<span className="text-xs text-gray-400">کلیدواژه اصلی:</span>
<span className="text-xs font-bold text-purple-700 bg-purple-50 px-2 py-0.5 rounded-md">
{selectedFinding.primaryKeyword}
</span>
</div>
</div>
<button
onClick={() => setSelectedFinding(null)}
className="p-2 text-gray-400 hover:text-gray-600 rounded-xl"
>
✕
</button>
</div>
{/* Modal Body */}
<div className="p-6 overflow-y-auto space-y-6">
{detailLoading ? (
<div className="p-12 text-center text-gray-400">
<RefreshCw className="w-8 h-8 animate-spin mx-auto mb-2 text-purple-600" />
در حال بارگذاری جزئیات...
</div>
) : (
<>
{/* Hypothesis & Outcome */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="bg-gray-50 p-4 rounded-2xl border border-gray-100">
<h3 className="text-xs font-bold text-gray-500 mb-2">فرضیه و منطق سئو:</h3>
<p className="text-xs text-gray-700 leading-relaxed font-medium">
{selectedFinding.hypothesis}
</p>
</div>
<div className="bg-gray-50 p-4 rounded-2xl border border-gray-100">
<h3 className="text-xs font-bold text-gray-500 mb-2">نتیجه مورد انتظار بیزینس:</h3>
<p className="text-xs text-gray-700 leading-relaxed font-medium">
{selectedFinding.expectedOutcome}
</p>
</div>
</div>
{/* Performance Metrics Cards */}
<div>
<h3 className="text-sm font-black text-gray-900 mb-3 flex items-center gap-2">
<BarChart2 className="w-4 h-4 text-purple-600" />
آخرین پایش زنده سنجه‌ها
</h3>
{latestSnapshot ? (
<div className="grid grid-cols-2 md:grid-cols-4 gap-3">
<div className="bg-blue-50/50 p-3.5 rounded-2xl border border-blue-100">
<span className="text-xs text-blue-600 font-bold">ایمپرشن سرچ گوگل</span>
<div className="text-lg font-black text-blue-900 mt-1">
{latestSnapshot.gscImpressions.toLocaleString('fa-IR')}
</div>
<span className="text-[10px] text-blue-400">کلیک: {latestSnapshot.gscClicks}</span>
</div>
<div className="bg-emerald-50/50 p-3.5 rounded-2xl border border-emerald-100">
<span className="text-xs text-emerald-600 font-bold">کاربر فعال GA4</span>
<div className="text-lg font-black text-emerald-900 mt-1">
{latestSnapshot.ga4ActiveUsers.toLocaleString('fa-IR')}
</div>
<span className="text-[10px] text-emerald-500">
میانگین حضور: {Math.round(latestSnapshot.ga4AvgEngagementSec)} ثانیه
</span>
</div>
<div className="bg-purple-50/50 p-3.5 rounded-2xl border border-purple-100">
<span className="text-xs text-purple-600 font-bold">سفارش‌های متصل</span>
<div className="text-lg font-black text-purple-900 mt-1">
{latestSnapshot.attributedOrdersCount} سفارش
</div>
<span className="text-[10px] text-purple-500">
فروش: {Number(latestSnapshot.attributedSalesValue).toLocaleString('fa-IR')} ت
</span>
</div>
<div className="bg-amber-50/50 p-3.5 rounded-2xl border border-amber-100">
<span className="text-xs text-amber-600 font-bold">پیشنهاد سیستم</span>
<div className="text-sm font-black text-amber-900 mt-1">
{latestSnapshot.actionRecommendation || 'ادامه پایش'}
</div>
<span className="text-[10px] text-amber-500">خودکار</span>
</div>
</div>
) : (
<div className="p-4 bg-gray-50 border border-dashed border-gray-200 rounded-2xl text-center text-xs text-gray-400">
هنوز اولین پایش سنجه‌ها برای این موضوع ثبت نشده است.
</div>
)}
</div>
{/* CEO Feedback Directive Section */}
<div className="bg-gradient-to-br from-purple-50/40 to-white p-5 rounded-2xl border border-purple-100">
<div className="flex items-center gap-2 mb-2">
<MessageSquare className="w-4 h-4 text-purple-600" />
<h3 className="text-sm font-black text-purple-900">
دستور و بازخورد مستقیم مدیرعامل (Parsa Aghayi)
</h3>
</div>
<p className="text-xs text-gray-500 mb-3">
ثبت نظر در اینجا اختیاری است، ولی در صورت ثبت، به عنوان دستور الزام‌آور در چرخه خودکار بعدی رعایت می‌شود.
</p>
<textarea
rows={3}
value={feedbackText}
onChange={(e) => setFeedbackText(e.target.value)}
placeholder="دستور یا بازخورد خود را درباره این موضوع یا اقدام بعدی وارد کنید..."
className="w-full p-3 bg-white border border-purple-200 rounded-xl text-xs focus:outline-none focus:ring-2 focus:ring-purple-500 font-medium leading-relaxed"
/>
<div className="flex items-center justify-between mt-3">
<span className="text-[11px] text-gray-400">
{selectedFinding.feedbackSubmittedAt ? (
<>آخرین ثبت: {new Date(selectedFinding.feedbackSubmittedAt).toLocaleString('fa-IR')}</>
) : (
'تاکنون نظری ثبت نشده است'
)}
</span>
<button
onClick={handleSaveCeoFeedback}
disabled={submittingFeedback}
className="flex items-center gap-1.5 px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white text-xs font-bold rounded-xl transition shadow-sm disabled:opacity-50"
>
<Send className="w-3.5 h-3.5" />
{submittingFeedback ? 'در حال ثبت...' : 'ثبت دستور الزامی'}
</button>
</div>
</div>
</>
)}
</div>
{/* Modal Footer */}
<div className="p-4 border-t border-gray-100 bg-gray-50 flex justify-end">
<button
onClick={() => setSelectedFinding(null)}
className="px-4 py-2 text-xs font-bold text-gray-600 hover:bg-gray-100 rounded-xl transition"
>
بستن
</button>
</div>
</div>
</div>
)}
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(); }
}
}}><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>;
}