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

+65
View File
@@ -219,6 +219,7 @@ model Blog {
category BlogCategory? @relation(fields: [categoryId], references: [id], onDelete: SetNull)
tags BlogTag[]
comments BlogComment[]
researchFinding ContentResearchFinding?
@@index([categoryId])
@@index([status])
@@ -1020,3 +1021,67 @@ model SmsCampaign {
@@map("sms_campaigns")
}
// ------------------------------------------------------------------------------
// 5. SEO & Performance Tracking Models
// ------------------------------------------------------------------------------
enum ResearchFindingStatus {
RESEARCHED
ACTIONED
EVALUATING
SCALED
PRUNED
}
model ContentResearchFinding {
id String @id @default(uuid()) @db.Uuid
title String @db.VarChar(255)
hypothesis String @db.Text
targetKeywords String[] @map("target_keywords")
primaryKeyword String @map("primary_keyword") @db.VarChar(128)
expectedOutcome String @map("expected_outcome") @db.Text
status ResearchFindingStatus @default(RESEARCHED)
blogId String? @unique @map("blog_id") @db.Uuid
blog Blog? @relation(fields: [blogId], references: [id], onDelete: SetNull)
ceoFeedback String? @map("ceo_feedback") @db.Text
feedbackSubmittedAt DateTime? @map("feedback_submitted_at") @db.Timestamptz()
snapshots ContentPerformanceSnapshot[]
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz()
@@index([status])
@@index([primaryKeyword])
@@map("content_research_findings")
}
model ContentPerformanceSnapshot {
id String @id @default(uuid()) @db.Uuid
findingId String @map("finding_id") @db.Uuid
finding ContentResearchFinding @relation(fields: [findingId], references: [id], onDelete: Cascade)
snapshotDate DateTime @default(now()) @map("snapshot_date") @db.Timestamptz()
gscImpressions Int @default(0) @map("gsc_impressions")
gscClicks Int @default(0) @map("gsc_clicks")
gscPosition Float @default(0.0) @map("gsc_position")
ga4ActiveUsers Int @default(0) @map("ga4_active_users")
ga4AvgEngagementSec Float @default(0.0) @map("ga4_avg_engagement_sec")
ga4BounceRate Float @default(0.0) @map("ga4_bounce_rate")
ga4ScrollDepthRate Float @default(0.0) @map("ga4_scroll_depth_rate")
attributedOrdersCount Int @default(0) @map("attributed_orders_count")
attributedSalesValue Decimal @default(0) @map("attributed_sales_value") @db.Decimal(15, 2)
actionRecommendation String? @map("action_recommendation") @db.VarChar(64)
analysisNotes String? @map("analysis_notes") @db.Text
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
@@index([findingId, snapshotDate])
@@map("content_performance_snapshots")
}
+2
View File
@@ -38,10 +38,12 @@ import { FaqModule } from "./faq/faq.module";
import { MenuModule } from "./menu/menu.module";
import { RevalidationModule } from "./common/revalidation/revalidation.module";
import { SeoTrackingModule } from "./seo-tracking/seo-tracking.module";
import { Request, Response, NextFunction } from "express";
@Module({
imports: [
SeoTrackingModule,
SupportChatModule,
RevalidationModule,
SmsModule,
@@ -0,0 +1,95 @@
import { IsString, IsArray, IsOptional, IsEnum, IsUUID, ArrayNotEmpty } from 'class-validator';
import { ResearchFindingStatus } from '@prisma/client';
export class CreateFindingDto {
@IsString()
title: string;
@IsString()
hypothesis: string;
@IsArray()
@ArrayNotEmpty()
@IsString({ each: true })
targetKeywords: string[];
@IsString()
primaryKeyword: string;
@IsString()
expectedOutcome: string;
@IsOptional()
@IsEnum(ResearchFindingStatus)
status?: ResearchFindingStatus;
@IsOptional()
@IsUUID()
blogId?: string;
}
export class UpdateCeoFeedbackDto {
@IsString()
feedback: string;
}
export class QueryFindingsDto {
@IsOptional()
page?: number;
@IsOptional()
limit?: number;
@IsOptional()
@IsString()
search?: string;
@IsOptional()
@IsEnum(ResearchFindingStatus)
status?: ResearchFindingStatus;
@IsOptional()
@IsString()
sortBy?: string;
@IsOptional()
@IsString()
sortOrder?: 'asc' | 'desc';
}
export class CreateSnapshotDto {
@IsOptional()
gscImpressions?: number;
@IsOptional()
gscClicks?: number;
@IsOptional()
gscPosition?: number;
@IsOptional()
ga4ActiveUsers?: number;
@IsOptional()
ga4AvgEngagementSec?: number;
@IsOptional()
ga4BounceRate?: number;
@IsOptional()
ga4ScrollDepthRate?: number;
@IsOptional()
attributedOrdersCount?: number;
@IsOptional()
attributedSalesValue?: number;
@IsOptional()
@IsString()
actionRecommendation?: string;
@IsOptional()
@IsString()
analysisNotes?: string;
}
@@ -0,0 +1,58 @@
import {
Controller,
Get,
Post,
Patch,
Body,
Param,
Query,
UseGuards,
} from '@nestjs/common';
import { SeoTrackingService } from './seo-tracking.service';
import {
CreateFindingDto,
QueryFindingsDto,
UpdateCeoFeedbackDto,
CreateSnapshotDto,
} from './dto/seo-tracking.dto';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { RolesGuard } from '../common/guards/roles.guard';
import { Roles } from '../common/decorators/roles.decorator';
@Controller('admin/seo-tracking')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('ADMIN', 'SUPER_ADMIN')
export class SeoTrackingController {
constructor(private readonly seoTrackingService: SeoTrackingService) {}
@Post()
async createFinding(@Body() dto: CreateFindingDto) {
return this.seoTrackingService.createFinding(dto);
}
@Get()
async findAll(@Query() query: QueryFindingsDto) {
return this.seoTrackingService.findAll(query);
}
@Get(':id')
async findOne(@Param('id') id: string) {
return this.seoTrackingService.findOne(id);
}
@Patch(':id/feedback')
async updateCeoFeedback(
@Param('id') id: string,
@Body() dto: UpdateCeoFeedbackDto,
) {
return this.seoTrackingService.updateCeoFeedback(id, dto);
}
@Post(':id/snapshots')
async addSnapshot(
@Param('id') id: string,
@Body() dto: CreateSnapshotDto,
) {
return this.seoTrackingService.addSnapshot(id, dto);
}
}
@@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { SeoTrackingController } from './seo-tracking.controller';
import { SeoTrackingService } from './seo-tracking.service';
import { PrismaModule } from '../prisma/prisma.module';
@Module({
imports: [PrismaModule],
controllers: [SeoTrackingController],
providers: [SeoTrackingService],
exports: [SeoTrackingService],
})
export class SeoTrackingModule {}
@@ -0,0 +1,119 @@
import { Test, TestingModule } from '@nestjs/testing';
import { SeoTrackingService } from './seo-tracking.service';
import { PrismaService } from '../prisma/prisma.service';
import { NotFoundException } from '@nestjs/common';
describe('SeoTrackingService (TDD)', () => {
let service: SeoTrackingService;
let prisma: any;
const mockFinding = {
id: 'f9d3b841-8f52-4412-bc78-8316c029e001',
title: 'تغذیه گربه مبتلا به نارسایی کلیه',
hypothesis: 'تمرکز بر مکمل رنال و اسیدهای آمینه به دلیل خلا در نتایج فارسی',
targetKeywords: ['غذای کلیه گربه', 'مکمل رنال گربه'],
primaryKeyword: 'مکمل رنال گربه',
expectedOutcome: 'افزایش بازدید ارگانیک و رشد فروش مکمل‌های کلیه',
status: 'RESEARCHED',
blogId: null,
ceoFeedback: null,
feedbackSubmittedAt: null,
createdAt: new Date(),
updatedAt: new Date(),
};
beforeEach(async () => {
prisma = {
contentResearchFinding: {
create: jest.fn().mockResolvedValue(mockFinding),
findMany: jest.fn().mockResolvedValue([mockFinding]),
count: jest.fn().mockResolvedValue(1),
findUnique: jest.fn().mockResolvedValue(mockFinding),
update: jest.fn().mockImplementation(({ data }) =>
Promise.resolve({ ...mockFinding, ...data }),
),
},
contentPerformanceSnapshot: {
create: jest.fn().mockResolvedValue({
id: 'snap-1',
findingId: mockFinding.id,
gscImpressions: 1200,
gscClicks: 85,
attributedOrdersCount: 4,
attributedSalesValue: 2400000,
}),
},
};
const module: TestingModule = await Test.createTestingModule({
providers: [
SeoTrackingService,
{ provide: PrismaService, useValue: prisma },
],
}).compile();
service = module.get<SeoTrackingService>(SeoTrackingService);
});
it('should create a new research finding', async () => {
const dto = {
title: 'تغذیه گربه مبتلا به نارسایی کلیه',
hypothesis: 'تمرکز بر مکمل رنال',
targetKeywords: ['غذای کلیه گربه'],
primaryKeyword: 'مکمل رنال گربه',
expectedOutcome: 'فروش بیشتر',
};
const result = await service.createFinding(dto as any);
expect(result).toBeDefined();
expect(result.title).toBe(dto.title);
expect(prisma.contentResearchFinding.create).toHaveBeenCalled();
});
it('should return paginated findings with standard metadata', async () => {
const res = await service.findAll({ page: 1, limit: 10 });
expect(res.data).toHaveLength(1);
expect(res.meta).toEqual({
total: 1,
page: 1,
limit: 10,
totalPages: 1,
lastPage: 1,
hasNextPage: false,
hasPrevPage: false,
});
});
it('should update CEO feedback atomically and record timestamp', async () => {
const feedback = 'تمرکز باید دقیقاً روی علائم زودرس کراتینین بالا باشد.';
const updated = await service.updateCeoFeedback(mockFinding.id, { feedback });
expect(updated.ceoFeedback).toBe(feedback);
expect(prisma.contentResearchFinding.update).toHaveBeenCalledWith(
expect.objectContaining({
where: { id: mockFinding.id },
data: expect.objectContaining({
ceoFeedback: feedback,
}),
}),
);
});
it('should throw NotFoundException if finding does not exist for feedback', async () => {
prisma.contentResearchFinding.findUnique.mockResolvedValueOnce(null);
await expect(
service.updateCeoFeedback('non-existing', { feedback: 'test' }),
).rejects.toThrow(NotFoundException);
});
it('should add performance snapshot with GSC and Sales data', async () => {
const snap = await service.addSnapshot(mockFinding.id, {
gscImpressions: 1200,
gscClicks: 85,
attributedOrdersCount: 4,
attributedSalesValue: 2400000,
});
expect(snap.attributedOrdersCount).toBe(4);
expect(prisma.contentPerformanceSnapshot.create).toHaveBeenCalled();
});
});
@@ -0,0 +1,122 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { CreateFindingDto, QueryFindingsDto, UpdateCeoFeedbackDto, CreateSnapshotDto } from './dto/seo-tracking.dto';
import { createPaginationMeta } from '../common/utils/search.utils';
import { Prisma } from '@prisma/client';
@Injectable()
export class SeoTrackingService {
constructor(private prisma: PrismaService) {}
async createFinding(dto: CreateFindingDto) {
return this.prisma.contentResearchFinding.create({
data: {
title: dto.title,
hypothesis: dto.hypothesis,
targetKeywords: dto.targetKeywords,
primaryKeyword: dto.primaryKeyword,
expectedOutcome: dto.expectedOutcome,
status: dto.status || 'RESEARCHED',
blogId: dto.blogId,
},
include: {
blog: {
select: { id: true, title: true, slug: true, status: true },
},
},
});
}
async findAll(query: QueryFindingsDto) {
const { page = 1, limit = 10, search, status, sortBy = 'createdAt', sortOrder = 'desc' } = query;
const safePage = Math.max(1, Number(page) || 1);
const safeLimit = Math.max(1, Number(limit) || 10);
const skip = (safePage - 1) * safeLimit;
const where: Prisma.ContentResearchFindingWhereInput = {};
if (status) {
where.status = status;
}
if (search) {
where.OR = [
{ title: { contains: search, mode: 'insensitive' } },
{ primaryKeyword: { contains: search, mode: 'insensitive' } },
{ hypothesis: { contains: search, mode: 'insensitive' } },
];
}
const [data, total] = await Promise.all([
this.prisma.contentResearchFinding.findMany({
where,
skip,
take: safeLimit,
orderBy: { [sortBy]: sortOrder },
include: {
blog: { select: { id: true, title: true, slug: true } },
snapshots: {
orderBy: { snapshotDate: 'desc' },
take: 1,
},
},
}),
this.prisma.contentResearchFinding.count({ where }),
]);
return {
data,
meta: createPaginationMeta(total, safePage, safeLimit),
};
}
async findOne(id: string) {
const finding = await this.prisma.contentResearchFinding.findUnique({
where: { id },
include: {
blog: true,
snapshots: {
orderBy: { snapshotDate: 'desc' },
take: 30,
},
},
});
if (!finding) {
throw new NotFoundException(`Research finding with ID ${id} not found`);
}
return finding;
}
async updateCeoFeedback(id: string, dto: UpdateCeoFeedbackDto) {
await this.findOne(id);
return this.prisma.contentResearchFinding.update({
where: { id },
data: {
ceoFeedback: dto.feedback,
feedbackSubmittedAt: new Date(),
},
});
}
async addSnapshot(findingId: string, dto: CreateSnapshotDto) {
await this.findOne(findingId);
return this.prisma.contentPerformanceSnapshot.create({
data: {
findingId,
gscImpressions: dto.gscImpressions || 0,
gscClicks: dto.gscClicks || 0,
gscPosition: dto.gscPosition || 0.0,
ga4ActiveUsers: dto.ga4ActiveUsers || 0,
ga4AvgEngagementSec: dto.ga4AvgEngagementSec || 0.0,
ga4BounceRate: dto.ga4BounceRate || 0.0,
ga4ScrollDepthRate: dto.ga4ScrollDepthRate || 0.0,
attributedOrdersCount: dto.attributedOrdersCount || 0,
attributedSalesValue: dto.attributedSalesValue || 0,
actionRecommendation: dto.actionRecommendation,
analysisNotes: dto.analysisNotes,
},
});
}
}
@@ -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;
},
};