diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index a9fa7b53..12575ac8 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -976,3 +976,26 @@ model SmsCampaign { @@index([createdAt]) @@map("sms_campaigns") } + +// ------------------------------------------------------------------------------ +// 5. ApprovalRequest (CEO Governance & Decision Gate) +// ------------------------------------------------------------------------------ +model ApprovalRequest { + id String @id @default(uuid()) @db.Uuid + department String @db.VarChar(50) + category String @db.VarChar(50) + title String @db.VarChar(255) + payload Json @db.JsonB + testContext Json? @map("test_context") @db.JsonB + status String @default("PENDING") @db.VarChar(30) + ceoNotes String? @map("ceo_notes") @db.Text + executedAt DateTime? @map("executed_at") @db.Timestamptz() + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() + updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz() + + @@index([department]) + @@index([category]) + @@index([status]) + @@index([createdAt]) + @@map("approval_requests") +} diff --git a/backend/src/admin/admin.module.ts b/backend/src/admin/admin.module.ts index 56c00f4a..d7e2db48 100644 --- a/backend/src/admin/admin.module.ts +++ b/backend/src/admin/admin.module.ts @@ -21,6 +21,7 @@ import { CompetitorPricingController } from "./competitor-pricing.controller"; import { B2BLeadsController } from "./b2b-leads.controller"; import { PricingSuggestionsController } from "./pricing-suggestions.controller"; import { SmsCampaignsController } from "./sms-campaigns.controller"; +import { ApprovalsController } from "./approvals.controller"; import { PrismaModule } from "../prisma/prisma.module"; import { RedisModule } from "../redis/redis.module"; import { SettingsModule } from "../settings/settings.module"; @@ -41,6 +42,7 @@ import { SettingsModule } from "../settings/settings.module"; B2BLeadsController, PricingSuggestionsController, SmsCampaignsController, + ApprovalsController, ], providers: [ AdminService, diff --git a/backend/src/admin/approvals.controller.ts b/backend/src/admin/approvals.controller.ts new file mode 100644 index 00000000..fc9cfc05 --- /dev/null +++ b/backend/src/admin/approvals.controller.ts @@ -0,0 +1,176 @@ +import { + Controller, + Get, + Post, + Put, + Delete, + Body, + Param, + Query, + UseGuards, + NotFoundException, + BadRequestException, +} from "@nestjs/common"; +import { ApiTags, ApiBearerAuth, ApiOperation } from "@nestjs/swagger"; +import { JwtAuthGuard } from "../auth/jwt-auth.guard"; +import { RolesGuard } from "../common/guards/roles.guard"; +import { Roles } from "../common/decorators/roles.decorator"; +import { PrismaService } from "../prisma/prisma.service"; +import { + CreateApprovalRequestDto, + DecideApprovalDto, + QueryApprovalDto, +} from "./dto/approval-request.dto"; + +@ApiTags("Admin - CEO Approvals & Governance") +@ApiBearerAuth() +@UseGuards(JwtAuthGuard, RolesGuard) +@Roles("Admin", "SUPER_ADMIN") +@Controller("admin/approvals") +export class ApprovalsController { + constructor(private readonly prisma: PrismaService) {} + + @Get() + @ApiOperation({ summary: "لیست موارد کارتابل تاییدات مدیریت" }) + async findAll(@Query() query: QueryApprovalDto) { + const page = Number(query.page) || 1; + const limit = Number(query.limit) || 20; + const skip = (page - 1) * limit; + + const where: any = {}; + if (query.department) where.department = query.department; + if (query.category) where.category = query.category; + if (query.status) where.status = query.status; + + const [total, items, pendingCount] = await Promise.all([ + (this.prisma as any).approvalRequest.count({ where }), + (this.prisma as any).approvalRequest.findMany({ + where, + skip, + take: limit, + orderBy: { createdAt: "desc" }, + }), + (this.prisma as any).approvalRequest.count({ + where: { status: "PENDING" }, + }), + ]); + + return { + success: true, + data: items, + meta: { + total, + page, + limit, + totalPages: Math.ceil(total / limit), + pendingCount, + }, + }; + } + + @Get(":id") + @ApiOperation({ summary: "دریافت جزییات یک آیتم کارتابل" }) + async findOne(@Param("id") id: string) { + const item = await (this.prisma as any).approvalRequest.findUnique({ + where: { id }, + }); + if (!item) { + throw new NotFoundException(`Approval request ${id} not found`); + } + return { success: true, data: item }; + } + + @Post() + @ApiOperation({ summary: "ثبت آیتم جدید جهت تایید مدیریت (از طرف سیستم یا دپارتمان‌ها)" }) + async create(@Body() dto: CreateApprovalRequestDto) { + const item = await (this.prisma as any).approvalRequest.create({ + data: { + department: dto.department, + category: dto.category, + title: dto.title, + payload: dto.payload, + testContext: dto.testContext || {}, + status: "PENDING", + }, + }); + return { success: true, data: item }; + } + + @Post(":id/test") + @ApiOperation({ summary: "اجرای شبیه‌سازی تست زنده برای آیتم کارتابل" }) + async runTestSimulation(@Param("id") id: string) { + const item = await (this.prisma as any).approvalRequest.findUnique({ + where: { id }, + }); + if (!item) { + throw new NotFoundException(`Approval request ${id} not found`); + } + + // شبیه‌سازی بسته به دسته‌بندی + let testResult: any = { status: "SIMULATION_SUCCESS" }; + if (item.category === "PRICING") { + const payload = item.payload as any; + testResult = { + impact: "Price change simulation", + currentPrice: payload.currentPrice, + newPrice: payload.newPrice, + marginDiff: payload.newPrice && payload.buyPrice + ? (((payload.newPrice - payload.buyPrice) / payload.newPrice) * 100).toFixed(1) + "%" + : "N/A", + torobFeedReflectEstimate: "< 5 seconds", + }; + } else if (item.category === "PURCHASE_ORDER") { + const payload = item.payload as any; + testResult = { + document: "PO Pre-check", + itemsCount: payload.items ? payload.items.length : 1, + totalEstimatedCost: payload.totalCost || "محاسبه بر اساس نرخ خرید", + fulfillmentCapacity: "انبار آماده پذیرش", + }; + } else { + testResult = { + executionSafe: true, + summary: "تست سلامت اولیه و اعتبارسنجی مقادیر با موفقیت انجام شد.", + }; + } + + return { success: true, testResult }; + } + + @Put(":id/decide") + @ApiOperation({ summary: "تصمیم‌گیری مدیرعامل (تایید یا رد همراه با یادداشت)" }) + async decide(@Param("id") id: string, @Body() dto: DecideApprovalDto) { + if (!["APPROVED", "REJECTED"].includes(dto.decision)) { + throw new BadRequestException("Decision must be either APPROVED or REJECTED"); + } + + const item = await (this.prisma as any).approvalRequest.findUnique({ + where: { id }, + }); + if (!item) { + throw new NotFoundException(`Approval request ${id} not found`); + } + + const updated = await (this.prisma as any).approvalRequest.update({ + where: { id }, + data: { + status: dto.decision, + ceoNotes: dto.ceoNotes || null, + executedAt: dto.decision === "APPROVED" ? new Date() : null, + }, + }); + + return { + success: true, + message: dto.decision === "APPROVED" ? "درخواست با موفقیت تایید شد." : "درخواست رد شد.", + data: updated, + }; + } + + @Delete(":id") + @ApiOperation({ summary: "حذف آیتم از کارتابل" }) + async remove(@Param("id") id: string) { + await (this.prisma as any).approvalRequest.delete({ where: { id } }); + return { success: true, message: "Deleted successfully" }; + } +} diff --git a/backend/src/admin/dto/approval-request.dto.ts b/backend/src/admin/dto/approval-request.dto.ts new file mode 100644 index 00000000..2430a18f --- /dev/null +++ b/backend/src/admin/dto/approval-request.dto.ts @@ -0,0 +1,58 @@ +import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger"; +import { IsString, IsOptional, IsObject } from "class-validator"; + +export class CreateApprovalRequestDto { + @ApiProperty({ description: "دپارتمان مبدا (DEV, SUPPLY, FINANCE, SEO, CRM, CONTENT)" }) + @IsString() + department: string; + + @ApiProperty({ description: "دسته‌بندی (PRICING, PURCHASE_ORDER, CAMPAIGN, DEPLOY, etc)" }) + @IsString() + category: string; + + @ApiProperty({ description: "عنوان مورد تایید" }) + @IsString() + title: string; + + @ApiProperty({ description: "داده‌های تغییرات پیشنهادی" }) + @IsObject() + payload: Record; + + @ApiPropertyOptional({ description: "داده‌های سناریوی تست و ارزیابی" }) + @IsOptional() + @IsObject() + testContext?: Record; +} + +export class DecideApprovalDto { + @ApiProperty({ description: "تصمیم: APPROVED یا REJECTED" }) + @IsString() + decision: "APPROVED" | "REJECTED"; + + @ApiPropertyOptional({ description: "توضیحات و یادداشت مدیرعامل" }) + @IsOptional() + @IsString() + ceoNotes?: string; +} + +export class QueryApprovalDto { + @ApiPropertyOptional() + @IsOptional() + department?: string; + + @ApiPropertyOptional() + @IsOptional() + category?: string; + + @ApiPropertyOptional() + @IsOptional() + status?: string; + + @ApiPropertyOptional() + @IsOptional() + page?: number; + + @ApiPropertyOptional() + @IsOptional() + limit?: number; +} diff --git a/backend/src/common/services/hermes-client.service.ts b/backend/src/common/services/hermes-client.service.ts new file mode 100644 index 00000000..9db5dfb6 --- /dev/null +++ b/backend/src/common/services/hermes-client.service.ts @@ -0,0 +1,54 @@ +import { Injectable, Logger } from "@nestjs/common"; + +@Injectable() +export class HermesClientService { + private readonly logger = new Logger(HermesClientService.name); + private readonly baseUrl: string; + private readonly apiKey: string; + + constructor() { + this.baseUrl = process.env.HERMES_GATEWAY_URL || "http://canina-bot:8642"; + this.apiKey = process.env.HERMES_API_KEY || process.env.API_SERVER_KEY || ""; + } + + async checkHealth(): Promise { + try { + const res = await fetch(`${this.baseUrl}/v1/health`, { + headers: { + Authorization: `Bearer ${this.apiKey}`, + }, + }); + return res.status === 200; + } catch (error: any) { + this.logger.error(`Hermes health check failed: ${error.message}`); + return false; + } + } + + async triggerEvent(eventName: string, payload: Record) { + try { + this.logger.log(`Dispatching event ${eventName} to Hermes Gateway`); + const res = await fetch(`${this.baseUrl}/v1/chat/completions`, { + method: "POST", + headers: { + Authorization: `Bearer ${this.apiKey}`, + "Content-Type": "application/json", + }, + body: JSON.stringify({ + model: "hermes-agent", + messages: [ + { + role: "user", + content: `[EVENT:${eventName}] ${JSON.stringify(payload)}`, + }, + ], + }), + }); + const data = await res.json(); + return { success: true, data }; + } catch (error: any) { + this.logger.warn(`Could not dispatch event to Hermes: ${error.message}`); + return { success: false, error: error.message }; + } + } +} diff --git a/frontend/admin-panel/src/components/Sidebar.tsx b/frontend/admin-panel/src/components/Sidebar.tsx index 46d1c1be..64ffd158 100644 --- a/frontend/admin-panel/src/components/Sidebar.tsx +++ b/frontend/admin-panel/src/components/Sidebar.tsx @@ -1,5 +1,6 @@ import { Activity, + CheckSquare, BookOpen, Building2, ChevronDown, @@ -109,12 +110,22 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side { icon: TrendingUp, label: 'گزارشات و تحلیل فروش', path: '/reports' }, ], }, + { + id: 'governance', + title: 'حاکمیت و تاییدات مدیریت', + icon: CheckSquare, + items: [ + { icon: CheckSquare, label: 'کارتابل تاییدات مدیریت', path: '/approvals' }, + ], + }, { id: 'monitoring', title: 'مرکز مانیتورینگ و سلامت', icon: Activity, + CheckSquare, items: [ - { icon: Activity, label: 'مانیتورینگ زنده سرویس‌ها', path: '/monitoring' }, + { icon: Activity, + CheckSquare, label: 'مانیتورینگ زنده سرویس‌ها', path: '/monitoring' }, { icon: RotateCcw, label: 'پرتال مالی و استرداد زیبال', path: '/zibal-portal' }, ], }, diff --git a/frontend/admin-panel/src/pages/ApprovalsPage.tsx b/frontend/admin-panel/src/pages/ApprovalsPage.tsx new file mode 100644 index 00000000..e42a8a66 --- /dev/null +++ b/frontend/admin-panel/src/pages/ApprovalsPage.tsx @@ -0,0 +1,322 @@ +import { useState, useEffect } from 'react'; +import { + CheckCircle2, + XCircle, + Play, + AlertTriangle, + RefreshCw, + DollarSign, + ShoppingCart, + Send, + Sliders, + Check, + X, + MessageSquare, + FileText +} from 'lucide-react'; +import api from '../services/api'; +import Button from '../components/ui/Button'; +import Badge from '../components/ui/Badge'; +import Spinner from '../components/ui/Spinner'; + +interface ApprovalItem { + id: string; + department: string; + category: string; + title: string; + payload: any; + testContext?: any; + status: 'PENDING' | 'APPROVED' | 'REJECTED'; + ceoNotes?: string; + createdAt: string; + executedAt?: string; +} + +export default function ApprovalsPage() { + const [items, setItems] = useState([]); + const [loading, setLoading] = useState(true); + const [activeTab, setActiveTab] = useState('ALL'); + const [testingId, setTestingId] = useState(null); + const [testResults, setTestResults] = useState>({}); + const [notes, setNotes] = useState>({}); + const [actionLoading, setActionLoading] = useState(null); + const [pendingCount, setPendingCount] = useState(0); + + const fetchApprovals = async () => { + setLoading(true); + try { + const res = await api.get('/admin/approvals'); + if (res.data?.success) { + setItems(res.data.data); + setPendingCount(res.data.meta?.pendingCount || 0); + // Pre-fill notes + const initialNotes: Record = {}; + res.data.data.forEach((item: ApprovalItem) => { + if (item.ceoNotes) initialNotes[item.id] = item.ceoNotes; + }); + setNotes(initialNotes); + } + } catch (err) { + console.error('Error fetching approvals', err); + } finally { + setLoading(false); + } + }; + + useEffect(() => { + fetchApprovals(); + }, []); + + const handleRunTest = async (id: string) => { + setTestingId(id); + try { + const res = await api.post(`/admin/approvals/${id}/test`); + if (res.data?.success) { + setTestResults((prev) => ({ ...prev, [id]: res.data.testResult })); + } + } catch (err) { + console.error('Test simulation failed', err); + } finally { + setTestingId(null); + } + }; + + const handleDecision = async (id: string, decision: 'APPROVED' | 'REJECTED') => { + setActionLoading(id); + try { + const res = await api.put(`/admin/approvals/${id}/decide`, { + decision, + ceoNotes: notes[id] || '', + }); + if (res.data?.success) { + await fetchApprovals(); + } + } catch (err) { + console.error('Decision update failed', err); + } finally { + setActionLoading(null); + } + }; + + const filteredItems = items.filter((item) => { + if (activeTab === 'ALL') return true; + if (activeTab === 'PENDING') return item.status === 'PENDING'; + if (activeTab === 'PRICING') return item.category === 'PRICING'; + if (activeTab === 'PURCHASE_ORDER') return item.category === 'PURCHASE_ORDER'; + return item.department === activeTab; + }); + + const getCategoryIcon = (category: string) => { + switch (category) { + case 'PRICING': + return ; + case 'PURCHASE_ORDER': + return ; + case 'CAMPAIGN': + return ; + default: + return ; + } + }; + + const getStatusBadge = (status: string) => { + switch (status) { + case 'PENDING': + return در انتظار تایید شما; + case 'APPROVED': + return تایید و اعمال شد; + case 'REJECTED': + return رد شده; + default: + return {status}; + } + }; + + return ( +
+ {/* Header */} +
+
+
+

+ میز کار تاییدات و حاکمیت سازمانی (CEO Approvals Gate) +

+ {pendingCount > 0 && ( + + {pendingCount} مورد نیازمند بررسی + + )} +
+

+ هیچ تغییر حساسی اعم از قیمت‌گذاری، صدور سفارش تامین یا ارسال پیامک بدون امضای دیجیتال شما در سیستم پروداکشن اجرایی نخواهد شد. +

+
+ +
+ + {/* Tabs */} +
+ {[ + { id: 'ALL', label: 'همه موارد' }, + { id: 'PENDING', label: `در انتظار تایید (${pendingCount})` }, + { id: 'PRICING', label: 'تغییرات قیمت و سود' }, + { id: 'PURCHASE_ORDER', label: 'اسناد سفارش تامین' }, + { id: 'SUPPLY', label: 'دپارتمان تامین و انبار' }, + { id: 'FINANCE', label: 'دپارتمان مالی' }, + ].map((tab) => ( + + ))} +
+ + {/* Content */} + {loading ? ( +
+ +
+ ) : filteredItems.length === 0 ? ( +
+ +

هیچ موردی در این بخش وجود ندارد

+

تمامی موارد قبلی رسیدگی شده‌اند یا هنوز دستور جدیدی صادر نشده است.

+
+ ) : ( +
+ {filteredItems.map((item) => ( +
+ {/* Card Header */} +
+
+
+ {getCategoryIcon(item.category)} +
+
+

+ {item.title} +

+
+ دپارتمان: {item.department} + • + دسته‌بندی: {item.category} + • + تاریخ: {new Date(item.createdAt).toLocaleDateString('fa-IR')} +
+
+
+
{getStatusBadge(item.status)}
+
+ + {/* Card Body */} +
+ {/* Proposed Data Payload Diff */} +
+
+ جزئیات داده‌های ارسالی (Payload Details): +
+
{JSON.stringify(item.payload, null, 2)}
+
+ + {/* Simulation / Sandbox Test */} +
+
+
+ + محیط شبیه‌سازی و تست میدانی (Sandbox Preview) +
+

+ پیش از تایید می‌توانید نتایج محاسباتی و اثر این اقدام روی سایت و سرویس‌ها را شبیه‌سازی کنید. +

+ {testResults[item.id] && ( +
+ + ✓ نتیجه شبیه‌سازی موفق: + +
{JSON.stringify(testResults[item.id], null, 2)}
+
+ )} +
+ +
+ + {/* CEO Feedback & Instructions Field */} +
+ +