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

+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,
},
});
}
}