- {/* Header */}
-
-
-
-
-
-
-
- پایش عملکرد سئو و بازخورد مدیرعامل
-
-
- اتصال هوشمند نتایج تحقیقات روزانه سئو به سنجههای زنده گوگل (GSC)، رفتار کاربر (GA4) و فروش استور
-
-
-
-
-
-
-
- {/* Filter and Search Bar */}
-
-
-
- {
- 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"
- />
-
-
-
-
-
-
-
-
- {/* Main Table */}
-
-
-
-
-
- | موضوع و فرضیه |
- کلیدواژه اصلی |
- وضعیت |
- مقاله مرتبط |
- دستور مدیرعامل |
- عملیات |
-
-
-
- {loading ? (
-
- |
-
- در حال دریافت دادهها...
- |
-
- ) : findings.length === 0 ? (
-
- |
- موردی یافت نشد.
- |
-
- ) : (
- findings.map((f) => {
- const statusInfo = STATUS_LABELS[f.status] || {
- label: f.status,
- color: 'bg-gray-100 text-gray-600 border-gray-200',
- };
-
- return (
-
- |
- {f.title}
- {f.hypothesis}
- |
-
-
- {f.primaryKeyword}
-
- |
-
-
- {statusInfo.label}
-
- |
-
- {f.blog ? (
-
- {f.blog.title}
-
-
- ) : (
- بدون مقاله
- )}
- |
-
- {f.ceoFeedback ? (
-
-
- دستور ثبتشده
-
- ) : (
- ثبتنشده
- )}
- |
-
-
- |
-
- );
- })
- )}
-
-
-
-
- {/* Pagination Footer */}
-
-
- تعداد کل: {totalCount} مورد
-
-
-
-
-
- صفحه {page} از {totalPages || 1}
-
-
-
-
-
-
- {/* Detail & CEO Feedback Modal */}
- {selectedFinding && (
-
-
- {/* Modal Header */}
-
-
-
{selectedFinding.title}
-
- کلیدواژه اصلی:
-
- {selectedFinding.primaryKeyword}
-
-
-
-
-
-
- {/* Modal Body */}
-
- {detailLoading ? (
-
-
- در حال بارگذاری جزئیات...
-
- ) : (
- <>
- {/* Hypothesis & Outcome */}
-
-
-
فرضیه و منطق سئو:
-
- {selectedFinding.hypothesis}
-
-
-
-
-
نتیجه مورد انتظار بیزینس:
-
- {selectedFinding.expectedOutcome}
-
-
-
-
- {/* Performance Metrics Cards */}
-
-
-
- آخرین پایش زنده سنجهها
-
-
- {latestSnapshot ? (
-
-
-
ایمپرشن سرچ گوگل
-
- {latestSnapshot.gscImpressions.toLocaleString('fa-IR')}
-
-
کلیک: {latestSnapshot.gscClicks}
-
-
-
-
کاربر فعال GA4
-
- {latestSnapshot.ga4ActiveUsers.toLocaleString('fa-IR')}
-
-
- میانگین حضور: {Math.round(latestSnapshot.ga4AvgEngagementSec)} ثانیه
-
-
-
-
-
سفارشهای متصل
-
- {latestSnapshot.attributedOrdersCount} سفارش
-
-
- فروش: {Number(latestSnapshot.attributedSalesValue).toLocaleString('fa-IR')} ت
-
-
-
-
-
پیشنهاد سیستم
-
- {latestSnapshot.actionRecommendation || 'ادامه پایش'}
-
-
خودکار
-
-
- ) : (
-
- هنوز اولین پایش سنجهها برای این موضوع ثبت نشده است.
-
- )}
-
-
- {/* CEO Feedback Directive Section */}
-
-
-
-
- دستور و بازخورد مستقیم مدیرعامل (Parsa Aghayi)
-
-
-
- ثبت نظر در اینجا اختیاری است، ولی در صورت ثبت، به عنوان دستور الزامآور در چرخه خودکار بعدی رعایت میشود.
-
-
-
- >
- )}
-
-
- {/* Modal Footer */}
-
-
-
-
-
- )}
+ const snapshots = [...(selected?.snapshots ?? [])].sort((a, b) => Date.parse(b.snapshotDate) - Date.parse(a.snapshotDate));
+ const control = 'border border-gray-300 rounded-lg p-2 bg-white';
+ return
+
+
+
+
+
+
- );
+ {error &&
{error}
}
+ {loading &&
در حال دریافت دادهها...
}
+
یافتههای پژوهش سئو{['موضوع و فرضیه', 'کلیدواژهها', 'وضعیت', 'مقاله مرتبط', 'دستور مدیرعامل', 'تاریخ ایجاد', 'عملیات'].map(text => | {text} | )}
+ {!loading && !error && findings.length === 0 && | موردی یافت نشد. |
}
+ {findings.map(f => | {f.title} {f.hypothesis} | {f.primaryKeyword} {f.targetKeywords?.filter(k => k !== f.primaryKeyword).join('، ')} | {statuses[f.status] ?? f.status} | {f.blog ? {f.blog.title} : 'بدون مقاله'} | {f.ceoFeedback ? 'دستور ثبتشده' : 'ثبتنشده'} | {date(f.createdAt)} | |
)}
+
+
+ {detailId && createPortal(
{
+ if (e.key === 'Escape') { e.stopPropagation(); close(); }
+ if (e.key === 'Tab') {
+ const elements = Array.from(modal.current?.querySelectorAll
('button, textarea, a[href], select, input') ?? []).filter(element => !(element as HTMLButtonElement).disabled);
+ const first = elements[0]; const last = elements[elements.length - 1];
+ if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last?.focus(); }
+ else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first?.focus(); }
+ }
+ }}>{selected?.title ?? 'جزئیات یافته'}
+ سنجهها از تاریخچه ذخیرهشده هستند، نه درخواست زنده به منابع.
+ {detailLoading && در حال بارگذاری جزئیات...
}
+ {detailError && {detailError}
}
+ {selected && !detailLoading && !detailError && <>فرضیه: {selected.hypothesis}
نتیجه مورد انتظار: {selected.expectedOutcome}
+ تاریخچه سنجههای ثبتشده
حداکثر ۳۰ پایش اخیر، به ترتیب جدیدترین تاریخ سنجش.
منابع: GSC / GA4 / Commerce. نبود داده با صفر تفاوت دارد. بازه، زمان گردآوری و واحد فروش فقط در صورت گزارش منبع معتبر است.
+ {!snapshots.length && هنوز اولین پایش سنجهها برای این موضوع ثبت نشده است.
}
+ {snapshots.map(snapshot => تاریخ سنجش: {date(snapshot.snapshotDate)}
بازه: {date(snapshot.periodStart)} تا {date(snapshot.periodEnd)}
زمان گردآوری: {date(snapshot.collectedAt)} — زمان ثبت: {date(snapshot.createdAt)}
{(['gsc', 'ga4', 'commerce'] as const).map(source => { const provenance = snapshot.sourceMetadata?.[source]; return - {source.toUpperCase()}: {provenance ? `${provenance.source} — ${provenance.status} — دریافت: ${date(provenance.fetchedAt)}` : 'منبع تأییدنشده (تاریخی)'}{provenance?.error && ` — ${provenance.error}`}
; })}
{fields.map(([key, label]) => - {label}
- {snapshot.sourceMetadata?.[key.startsWith('gsc') ? 'gsc' : key.startsWith('ga4') ? 'ga4' : 'commerce']?.status === 'available' ? metric(snapshot[key]) : 'ناموجود'}
)}
پیشنهاد ثبتشده: {snapshot.actionRecommendation || 'ناموجود'}
{snapshot.analysisNotes && {snapshot.analysisNotes}
})}
+
+ دستور و بازخورد مدیرعامل
ثبت نظر اختیاری است؛ نظر ثبتشده باید در اقدامات بعدی رعایت شود. ذخیره در این صفحه بهتنهایی اثبات اجرای آن در فرایندهای پاییندستی نیست.
آخرین ثبت: {date(selected.feedbackSubmittedAt)}
{conflict && }{feedbackMessage && {feedbackMessage}
}
+ >}
+ , document.body)}
+
;
}
diff --git a/frontend/admin-panel/src/services/seoTrackingApi.test.ts b/frontend/admin-panel/src/services/seoTrackingApi.test.ts
new file mode 100644
index 00000000..3875219a
--- /dev/null
+++ b/frontend/admin-panel/src/services/seoTrackingApi.test.ts
@@ -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
(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;
+ });
+});
diff --git a/frontend/admin-panel/src/services/seoTrackingApi.ts b/frontend/admin-panel/src/services/seoTrackingApi.ts
index 4b9c0eb4..dccb27ce 100644
--- a/frontend/admin-panel/src/services/seoTrackingApi.ts
+++ b/frontend/admin-panel/src/services/seoTrackingApi.ts
@@ -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 =>
+ 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 => {
- const res = await api.get('/admin/seo-tracking', { params });
- return res.data;
+ getFindings: async (params?: FindingsParams, signal?: AbortSignal): Promise => {
+ const { data } = await api.get('/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 => {
- const res = await api.get(`/admin/seo-tracking/${id}`);
- return res.data;
+ getFindingById: async (id: string, signal?: AbortSignal): Promise => {
+ const { data } = await api.get(`/admin/seo-tracking/${encodeURIComponent(id)}`, { signal });
+ return findingResponse(data);
},
- updateCeoFeedback: async (id: string, feedback: string): Promise => {
- const res = await api.patch(`/admin/seo-tracking/${id}/feedback`, { feedback });
- return res.data;
+ updateCeoFeedback: async (id: string, feedback: string, expectedVersion: number): Promise => {
+ const { data } = await api.patch(`/admin/seo-tracking/${encodeURIComponent(id)}/feedback`, { feedback, expectedVersion });
+ return findingResponse(data);
},
addSnapshot: async (id: string, snapshot: Partial): Promise => {
- const res = await api.post(`/admin/seo-tracking/${id}/snapshots`, snapshot);
- return res.data;
+ const { data } = await api.post(`/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;
},
};