feat(seo-tracking): implement closed-loop performance tracking, admin panel and CEO directive gate

This commit is contained in:
Canina Automation committed 2026-10-28 06:31:49 +00:00
1 parent 00ba4360cf
commit 13f4fdc58d
12 files changed
+1072

No files matched your search

@@ -172,6 +172,7 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side
items: [
{ icon: Image, label: 'بنرها و اسلایدرها', path: '/banners' },
{ icon: FileText, label: 'وبلاگ و مقالات', path: '/blogs' },
{ icon: TrendingUp, label: 'پایش سئو و عملکرد', path: '/seo-tracking' },
{ icon: FlaskConical, label: 'دانشنامه ترکیبات', path: '/ingredients' },
{ icon: BookOpen, label: 'دانشنامه عمومی و علمی', path: '/wiki' },
{ icon: UserCheck, label: 'پزشکان و کادر علمی', path: '/doctors' },
@@ -0,0 +1,64 @@
import { render, screen, waitFor } from '@testing-library/react';
import { BrowserRouter } from 'react-router-dom';
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();
});
});
});
@@ -0,0 +1,450 @@
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';
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' },
};
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 [search, setSearch] = useState('');
const [statusFilter, setStatusFilter] = useState('');
// Detail Modal & CEO Feedback
const [selectedFinding, setSelectedFinding] = 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]);
useEffect(() => {
fetchFindings();
}, [fetchFindings]);
const handleOpenDetail = async (id: string) => {
try {
setDetailLoading(true);
const data = await seoTrackingApi.getFindingById(id);
setSelectedFinding(data);
setFeedbackText(data.ceoFeedback || '');
} catch {
toast.error('خطا در دریافت جزئیات یافته سئو');
} finally {
setDetailLoading(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>
)}
</div>
);
}
@@ -20,6 +20,7 @@ const Categories = lazyWithRetry(() => import('../pages/Categories'));
const SymptomsPage = lazyWithRetry(() => import('../pages/SymptomsPage'));
const Blogs = lazyWithRetry(() => import('../pages/Blogs'));
const SeoTrackingPage = lazyWithRetry(() => import('../pages/SeoTrackingPage'));
const Wiki = lazyWithRetry(() => import('../pages/Wiki'));
const Pets = lazyWithRetry(() => import('../pages/Pets'));
const UITexts = lazyWithRetry(() => import('../pages/UITexts'));
@@ -95,6 +96,7 @@ export const router = createBrowserRouter([
{ path: 'symptoms/*', element: <SymptomsPage /> },
{ path: 'blogs/*', element: <Blogs /> },
{ path: 'seo-tracking', element: <SeoTrackingPage /> },
{ path: 'wiki/*', element: <Wiki /> },
{ path: 'videos/*', element: <Videos /> },
{ path: 'doctors/*', element: <DoctorsManager /> },
@@ -0,0 +1,82 @@
import api from './api';
export interface ResearchFinding {
id: string;
title: string;
hypothesis: string;
targetKeywords: string[];
primaryKeyword: string;
expectedOutcome: string;
status: 'RESEARCHED' | 'ACTIONED' | 'EVALUATING' | 'SCALED' | 'PRUNED';
blogId?: string | null;
blog?: {
id: string;
title: string;
slug: string;
} | null;
ceoFeedback?: string | null;
feedbackSubmittedAt?: string | null;
snapshots?: PerformanceSnapshot[];
createdAt: string;
updatedAt: string;
}
export interface PerformanceSnapshot {
id: string;
findingId: string;
snapshotDate: string;
gscImpressions: number;
gscClicks: number;
gscPosition: number;
ga4ActiveUsers: number;
ga4AvgEngagementSec: number;
ga4BounceRate: number;
ga4ScrollDepthRate: number;
attributedOrdersCount: number;
attributedSalesValue: number;
actionRecommendation?: string | null;
analysisNotes?: string | null;
createdAt: string;
}
export interface FindingsResponse {
data: ResearchFinding[];
meta: {
total: number;
page: number;
limit: number;
totalPages: number;
lastPage: number;
hasNextPage: boolean;
hasPrevPage: boolean;
};
}
export const seoTrackingApi = {
getFindings: async (params?: {
page?: number;
limit?: number;
search?: string;
status?: string;
sortBy?: string;
sortOrder?: 'asc' | 'desc';
}): Promise<FindingsResponse> => {
const res = await api.get('/admin/seo-tracking', { params });
return res.data;
},
getFindingById: async (id: string): Promise<ResearchFinding> => {
const res = await api.get(`/admin/seo-tracking/${id}`);
return res.data;
},
updateCeoFeedback: async (id: string, feedback: string): Promise<ResearchFinding> => {
const res = await api.patch(`/admin/seo-tracking/${id}/feedback`, { feedback });
return res.data;
},
addSnapshot: async (id: string, snapshot: Partial<PerformanceSnapshot>): Promise<PerformanceSnapshot> => {
const res = await api.post(`/admin/seo-tracking/${id}/snapshots`, snapshot);
return res.data;
},
};