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

@@ -0,0 +1,20 @@
# SEO tracking UI local verification
Scope: admin-panel only; no push, deployment, migration, scheduling or production writes. Reviewed specification/plan/tasks: `/opt/data/engineering/canina-spec-baseline/specs/002-seo-performance-tracking/`; contract: `/opt/data/analytics-engine/contract.md` v2. Source at start: develop `13f4fdc58dff96f192c612a8d38f33d314f70fad`; unrelated .specify/evidence existed. Shared worktree backend agent changes excluded from frontend commit.
Graphify navigation query: `SeoTrackingPage seoTrackingApi adminRoutes Sidebar`, graph hash `6a73473cee9e207543fdeeb668bea544f766200a1b16b8a3a9ce18d4e42e51af` (4304 nodes, 287 matches; truncated query). Graph SHA binding not established, therefore navigation only; direct source verified route/sidebar, API interceptor, backend global DecimalInterceptor, controller, DTO and service. Axios preserves response, server returns raw bodies, not a success/data wrapper.
Acceptance/implementation: server-driven page/search/status/sort with page reset; distinct loading/empty/error and retained stale rows after failed refetch; read cancellation and late-response guards; portal modal with labels, initial focus, inert page content, Tab wrap, Escape and focus restoration. Detail shows latest 30 stored snapshots, newest first, Tehran dates, source status/fetchedAt/period metadata. Null, unavailable and provenance-free legacy metrics never become measured zeros. Feedback is optional, requires expectedVersion, preserves snapshots and drafts after failure, rejects stale 409 save until explicit reload. Text does not claim downstream directive enforcement or live source queries.
RED: 7 UI tests failed with missing labels/sort/dialog/error handling and null metric crash (3 unhandled errors); `/opt/data/cache/scratch/seo-ui-red.log`. Service RED: 12 failed / 6 passed before implementation, exercised missing cancellation/version/response validation.
Final commands, all exit 0 (2026-10-28 UTC):
- `npm test -- --maxWorkers=2`: 53 files, 341 tests passed, 149.46s. Includes 10 SEO interaction tests plus 21 real Axios adapter/interceptor contract tests.
- `npx tsc -p tsconfig.app.json --noEmit`: passes actual application project. Root npm typecheck alone uses references and is not sufficient.
- `npm run lint`: 0 errors, 147 repository warnings; no lint errors introduced.
- `npm run build`: successful Vite production build.
- `git diff --check`: passes before commit.
Command logs: `/opt/data/cache/scratch/seo-admin-{full-tests,typecheck,lint,build}.log`.
Removed three unused Sidebar icon imports that prevented application typecheck. Route/sidebar SEO entry already existed and is unchanged. Verification uses mocked network fixtures, not live API/Google data; no browser/end-to-end or deployed acceptance is asserted. Backend version/schema rollout and legacy backfill remain backend/release responsibilities.
@@ -1,6 +1,5 @@
import {
Activity,
CheckSquare,
BookOpen,
Building2,
ChevronDown,
@@ -36,8 +35,6 @@ import {
UserCheck,
Users,
Video,
History,
Briefcase
} from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
import { Link, useLocation } from 'react-router-dom';
@@ -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>;
}
@@ -0,0 +1,106 @@
import axios, { AxiosError, CanceledError } from 'axios';
import type { AxiosAdapter, InternalAxiosRequestConfig } from 'axios';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import api from './api';
import { useAdminAuthStore } from '../store/adminAuthStore';
import { seoTrackingApi } from './seoTrackingApi';
vi.mock('react-hot-toast', () => ({ default: { error: vi.fn() } }));
// Exercise the real Axios instance and its request/response interceptors.
// main.ts registers DecimalInterceptor (recursive decimals, no success envelope).
const finding = {
id: 'finding-1', title: 'Research', hypothesis: 'Hypothesis',
targetKeywords: ['keyword'], primaryKeyword: 'keyword', expectedOutcome: 'Outcome',
status: 'RESEARCHED', createdAt: '2026-10-01T00:00:00.000Z',
updatedAt: '2026-10-02T00:00:00.000Z', version: 0, snapshots: [],
};
const meta = { total: 1, page: 1, limit: 10, totalPages: 1, lastPage: 1, hasNextPage: false, hasPrevPage: false };
const originalAdapter = api.defaults.adapter;
function respond(data: unknown, inspect?: (config: InternalAxiosRequestConfig) => void) {
api.defaults.adapter = (async (config) => {
inspect?.(config);
return { data, status: 200, statusText: 'OK', headers: {}, config };
}) satisfies AxiosAdapter;
}
beforeEach(() => { useAdminAuthStore.setState({ accessToken: 'test-access-token' }); });
afterEach(() => { api.defaults.adapter = originalAdapter; useAdminAuthStore.getState().clearAuth(); vi.clearAllMocks(); });
describe('seoTrackingApi wire contract', () => {
it('preserves the raw paginated controller payload and uses bearer authentication', async () => {
const payload = { data: [finding], meta };
const signal = new AbortController().signal;
respond(payload, config => {
expect(config.url).toBe('/admin/seo-tracking');
expect(config.params).toEqual({ page: 2, search: 'cat', status: 'RESEARCHED' });
expect(config.signal).toBe(signal);
expect(config.headers.Authorization).toBe('Bearer test-access-token');
expect(config.withCredentials).toBe(true);
});
expect(await seoTrackingApi.getFindings({ page: 2, search: 'cat', status: 'RESEARCHED' }, signal)).toEqual(payload);
});
it('returns raw details and passes their AbortSignal', async () => {
const signal = new AbortController().signal;
respond(finding, config => { expect(config.signal).toBe(signal); expect(config.url).toBe('/admin/seo-tracking/finding-1'); });
expect(await seoTrackingApi.getFindingById('finding-1', signal)).toEqual(finding);
});
it('sends the exact expectedVersion concurrency token with feedback', async () => {
respond(finding, config => {
expect(config.method).toBe('patch');
expect(config.url).toBe('/admin/seo-tracking/finding-1/feedback');
expect(JSON.parse(config.data)).toEqual({ feedback: 'Reviewed', expectedVersion: finding.version });
});
expect(await seoTrackingApi.updateCeoFeedback('finding-1', 'Reviewed', finding.version)).toEqual(finding);
});
it('preserves snapshot nulls, numeric zeros and source metadata without fabricated metrics', async () => {
const snapshot = { id: 'snapshot-1', findingId: finding.id, snapshotDate: finding.createdAt,
gscClicks: 0, ga4ActiveUsers: null, attributedSalesValue: null,
periodStart: finding.createdAt, periodEnd: finding.updatedAt, collectedAt: finding.updatedAt,
createdAt: finding.updatedAt };
respond(snapshot, config => { expect(config.method).toBe('post'); expect(JSON.parse(config.data)).toEqual({ ga4ActiveUsers: null, gscClicks: 0 }); });
expect(await seoTrackingApi.addSnapshot(finding.id, { ga4ActiveUsers: null, gscClicks: 0 })).toEqual(snapshot);
});
it('preserves a genuinely empty page with server pagination', async () => {
const payload = { data: [], meta: { ...meta, total: 0 } };
respond(payload);
expect(await seoTrackingApi.getFindings()).toEqual(payload);
});
it.each([null, {}, { data: [] }, { data: [finding], meta: { ...meta, total: '1' } }, { data: [{}], meta }, { success: true, data: { data: [finding], meta } }])('rejects malformed or unsupported list shapes: %j', async payload => {
respond(payload);
await expect(seoTrackingApi.getFindings()).rejects.toThrow('Invalid SEO tracking response');
});
it.each([null, {}, { success: true, data: finding }])('rejects malformed or unsupported detail shapes: %j', async payload => {
respond(payload);
await expect(seoTrackingApi.getFindingById(finding.id)).rejects.toThrow('Invalid SEO tracking response');
});
it.each([403, 404, 409, 422, 500])('preserves HTTP %i instead of disguising failures as empty results', async status => {
api.defaults.adapter = async config => {
const response = { data: { message: 'Failure' }, status, statusText: 'Failure', headers: {}, config };
throw new AxiosError('Failure', AxiosError.ERR_BAD_RESPONSE, config, undefined, response);
};
await expect(seoTrackingApi.getFindings()).rejects.toMatchObject({ response: { status } });
});
it.each(['list', 'detail'])('cancels an in-flight %s request using Axios cancellation', async endpoint => {
const controller = new AbortController();
let started!: () => void;
const ready = new Promise<void>(resolve => { started = resolve; });
api.defaults.adapter = config => new Promise((_resolve, reject) => {
config.signal?.addEventListener?.('abort', () => reject(new CanceledError('Canceled')));
started();
});
const request = endpoint === 'list' ? seoTrackingApi.getFindings({}, controller.signal) : seoTrackingApi.getFindingById(finding.id, controller.signal);
const assertion = expect(request).rejects.toSatisfy(axios.isCancel);
await ready;
controller.abort();
await assertion;
});
});
@@ -19,21 +19,27 @@ export interface ResearchFinding {
snapshots?: PerformanceSnapshot[];
createdAt: string;
updatedAt: string;
version: number;
feedbackVersion?: number;
}
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;
gscImpressions: number | null;
gscClicks: number | null;
gscPosition: number | null;
ga4ActiveUsers: number | null;
ga4AvgEngagementSec: number | null;
ga4BounceRate: number | null;
ga4ScrollDepthRate: number | null;
attributedOrdersCount: number | null;
attributedSalesValue: number | null;
periodStart?: string | null;
periodEnd?: string | null;
collectedAt?: string | null;
sourceMetadata?: Record<'gsc' | 'ga4' | 'commerce', { status: 'available' | 'unavailable' | 'error'; source: string; fetchedAt: string; error?: string }> | null;
actionRecommendation?: string | null;
analysisNotes?: string | null;
createdAt: string;
@@ -52,31 +58,61 @@ export interface FindingsResponse {
};
}
export interface FindingsParams {
page?: number;
limit?: number;
search?: string;
status?: string;
sortBy?: string;
sortOrder?: 'asc' | 'desc';
}
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === 'object' && value !== null && !Array.isArray(value);
const invalidResponse = () => new Error('Invalid SEO tracking response');
const isFinding = (value: unknown): value is ResearchFinding =>
isRecord(value) && ['id', 'title', 'hypothesis', 'primaryKeyword', 'expectedOutcome', 'createdAt', 'updatedAt']
.every(key => typeof value[key] === 'string') &&
Array.isArray(value.targetKeywords) && value.targetKeywords.every(keyword => typeof keyword === 'string') &&
['RESEARCHED', 'ACTIONED', 'EVALUATING', 'SCALED', 'PRUNED'].includes(String(value.status)) &&
Number.isInteger(value.version) && Number(value.version) >= 0 &&
(value.snapshots === undefined || Array.isArray(value.snapshots));
function findingResponse(value: unknown): ResearchFinding {
if (!isFinding(value)) throw invalidResponse();
return value;
}
// api.ts preserves AxiosResponse; main.ts only installs DecimalInterceptor,
// which recursively serializes decimals but DOES NOT add a success/data wrapper.
// Lists already contain their own { data, meta }; never unwrap that data twice.
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;
getFindings: async (params?: FindingsParams, signal?: AbortSignal): Promise<FindingsResponse> => {
const { data } = await api.get<unknown>('/admin/seo-tracking', { params, signal });
if (!isRecord(data) || !Array.isArray(data.data) || !data.data.every(isFinding) || !isRecord(data.meta)) {
throw invalidResponse();
}
const meta = data.meta;
if (!['total', 'page', 'limit', 'totalPages', 'lastPage'].every(key =>
typeof meta[key] === 'number' && Number.isFinite(meta[key]) && Number.isInteger(meta[key]) && meta[key] >= 0) ||
typeof meta.hasNextPage !== 'boolean' || typeof meta.hasPrevPage !== 'boolean') throw invalidResponse();
return data as unknown as FindingsResponse;
},
getFindingById: async (id: string): Promise<ResearchFinding> => {
const res = await api.get(`/admin/seo-tracking/${id}`);
return res.data;
getFindingById: async (id: string, signal?: AbortSignal): Promise<ResearchFinding> => {
const { data } = await api.get<unknown>(`/admin/seo-tracking/${encodeURIComponent(id)}`, { signal });
return findingResponse(data);
},
updateCeoFeedback: async (id: string, feedback: string): Promise<ResearchFinding> => {
const res = await api.patch(`/admin/seo-tracking/${id}/feedback`, { feedback });
return res.data;
updateCeoFeedback: async (id: string, feedback: string, expectedVersion: number): Promise<ResearchFinding> => {
const { data } = await api.patch<unknown>(`/admin/seo-tracking/${encodeURIComponent(id)}/feedback`, { feedback, expectedVersion });
return findingResponse(data);
},
addSnapshot: async (id: string, snapshot: Partial<PerformanceSnapshot>): Promise<PerformanceSnapshot> => {
const res = await api.post(`/admin/seo-tracking/${id}/snapshots`, snapshot);
return res.data;
const { data } = await api.post<unknown>(`/admin/seo-tracking/${encodeURIComponent(id)}/snapshots`, snapshot);
if (!isRecord(data) || typeof data.id !== 'string' || typeof data.findingId !== 'string' ||
typeof data.snapshotDate !== 'string' || typeof data.createdAt !== 'string') throw invalidResponse();
return data as unknown as PerformanceSnapshot;
},
};