diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index 12575ac8..a9deee44 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -999,3 +999,55 @@ model ApprovalRequest { @@index([createdAt]) @@map("approval_requests") } + + +// ------------------------------------------------------------------------------ +// 6. AuditLog (System & Database Changes History) +// ------------------------------------------------------------------------------ +model AuditLog { + id String @id @default(uuid()) @db.Uuid + entity String @db.VarChar(50) // e.g. product, blog, order, approval, settings + entityId String? @map("entity_id") @db.VarChar(100) + action String @db.VarChar(50) // CREATE, UPDATE, DELETE, EXECUTE, APPROVE, REJECT + department String? @db.VarChar(50) // devops, seo, content, vet, commerce, pmo + actor String @default("SYSTEM") @db.VarChar(100) + summary String @db.VarChar(255) + oldValues Json? @map("old_values") @db.JsonB + newValues Json? @map("new_values") @db.JsonB + metadata Json? @db.JsonB + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() + + @@index([entity]) + @@index([action]) + @@index([department]) + @@index([createdAt]) + @@map("audit_logs") +} + +// ------------------------------------------------------------------------------ +// 7. DepartmentTask (Autonomous Corporate Task & Kanban Manager) +// ------------------------------------------------------------------------------ +model DepartmentTask { + id String @id @default(uuid()) @db.Uuid + code String @unique @db.VarChar(50) + department String @db.VarChar(50) // devops, seo, content, vet, commerce, pmo + title String @db.VarChar(255) + description String? @db.Text + status String @default("BACKLOG") @db.VarChar(30) // BACKLOG, IN_PROGRESS, IN_REVIEW, APPROVED, DEPLOYING, DONE + priority String @default("MEDIUM") @db.VarChar(20) // LOW, MEDIUM, HIGH, CRITICAL + assignee String? @db.VarChar(100) + acceptanceCriteria Json? @map("acceptance_criteria") @db.JsonB + executionLogs Json? @map("execution_logs") @db.JsonB + deliverableUrl String? @map("deliverable_url") @db.VarChar(255) + approvalId String? @map("approval_id") @db.Uuid + startedAt DateTime? @map("started_at") @db.Timestamptz() + completedAt DateTime? @map("completed_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([status]) + @@index([priority]) + @@index([createdAt]) + @@map("department_tasks") +} diff --git a/backend/src/admin/admin.module.ts b/backend/src/admin/admin.module.ts index d7e2db48..a362c268 100644 --- a/backend/src/admin/admin.module.ts +++ b/backend/src/admin/admin.module.ts @@ -22,6 +22,8 @@ import { B2BLeadsController } from "./b2b-leads.controller"; import { PricingSuggestionsController } from "./pricing-suggestions.controller"; import { SmsCampaignsController } from "./sms-campaigns.controller"; import { ApprovalsController } from "./approvals.controller"; +import { AuditLogsController } from "./audit-logs.controller"; +import { DepartmentTasksController } from "./department-tasks.controller"; import { PrismaModule } from "../prisma/prisma.module"; import { RedisModule } from "../redis/redis.module"; import { SettingsModule } from "../settings/settings.module"; @@ -43,6 +45,8 @@ import { SettingsModule } from "../settings/settings.module"; PricingSuggestionsController, SmsCampaignsController, ApprovalsController, + AuditLogsController, + DepartmentTasksController, ], providers: [ AdminService, diff --git a/backend/src/admin/approvals.controller.ts b/backend/src/admin/approvals.controller.ts index fc9cfc05..958de9c4 100644 --- a/backend/src/admin/approvals.controller.ts +++ b/backend/src/admin/approvals.controller.ts @@ -34,7 +34,7 @@ export class ApprovalsController { @ApiOperation({ summary: "لیست موارد کارتابل تاییدات مدیریت" }) async findAll(@Query() query: QueryApprovalDto) { const page = Number(query.page) || 1; - const limit = Number(query.limit) || 20; + const limit = Number(query.limit) || 100; const skip = (page - 1) * limit; const where: any = {}; diff --git a/backend/src/admin/audit-logs.controller.ts b/backend/src/admin/audit-logs.controller.ts new file mode 100644 index 00000000..57a9ce70 --- /dev/null +++ b/backend/src/admin/audit-logs.controller.ts @@ -0,0 +1,94 @@ +import { + Controller, + Get, + Post, + Body, + Query, + UseGuards, + Param, +} 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"; + +@ApiTags("Admin - System Audit & History") +@ApiBearerAuth() +@UseGuards(JwtAuthGuard, RolesGuard) +@Roles("Admin", "SUPER_ADMIN") +@Controller("admin/audit-logs") +export class AuditLogsController { + constructor(private readonly prisma: PrismaService) {} + + @Get() + @ApiOperation({ summary: "لیست لاگ‌های تغییرات دیتابیس و سیستم" }) + async findAll(@Query() query: any) { + const page = Number(query.page) || 1; + const limit = Number(query.limit) || 30; + const skip = (page - 1) * limit; + + const where: any = {}; + if (query.entity) where.entity = query.entity; + if (query.action) where.action = query.action; + if (query.department) where.department = query.department; + if (query.search) { + where.OR = [ + { summary: { contains: query.search, mode: "insensitive" } }, + { actor: { contains: query.search, mode: "insensitive" } }, + { entityId: { contains: query.search, mode: "insensitive" } }, + ]; + } + + const [total, items] = await Promise.all([ + (this.prisma as any).auditLog.count({ where }), + (this.prisma as any).auditLog.findMany({ + where, + skip, + take: limit, + orderBy: { createdAt: "desc" }, + }), + ]); + + return { + success: true, + data: items, + meta: { + total, + page, + limit, + totalPages: Math.ceil(total / limit), + }, + }; + } + + @Get("recent") + @ApiOperation({ summary: "آخرین رخدادهای سیستم برای ویجت داشبورد" }) + async getRecent(@Query("limit") limitParam?: string) { + const limit = Number(limitParam) || 10; + const items = await (this.prisma as any).auditLog.findMany({ + take: limit, + orderBy: { createdAt: "desc" }, + }); + return { success: true, data: items }; + } + + @Post() + @ApiOperation({ summary: "ثبت لاگ جدید در تاریخچه سیستم" }) + async create(@Body() body: any) { + const item = await (this.prisma as any).auditLog.create({ + data: { + entity: body.entity, + entityId: body.entityId ? String(body.entityId) : null, + action: body.action || "UPDATE", + department: body.department || "system", + actor: body.actor || "ADMIN", + summary: body.summary, + oldValues: body.oldValues || null, + newValues: body.newValues || null, + metadata: body.metadata || null, + }, + }); + return { success: true, data: item }; + } +} diff --git a/backend/src/admin/department-tasks.controller.ts b/backend/src/admin/department-tasks.controller.ts new file mode 100644 index 00000000..f9612734 --- /dev/null +++ b/backend/src/admin/department-tasks.controller.ts @@ -0,0 +1,202 @@ +import { + Controller, + Get, + Post, + Put, + Delete, + Body, + Param, + Query, + UseGuards, + NotFoundException, +} 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"; + +@ApiTags("Admin - Department & Agent Tasks") +@ApiBearerAuth() +@UseGuards(JwtAuthGuard, RolesGuard) +@Roles("Admin", "SUPER_ADMIN") +@Controller("admin/department-tasks") +export class DepartmentTasksController { + constructor(private readonly prisma: PrismaService) {} + + @Get() + @ApiOperation({ summary: "لیست تسک‌های دپارتمان‌ها و ایجنت‌ها" }) + async findAll(@Query() query: any) { + const page = Number(query.page) || 1; + const limit = Number(query.limit) || 100; + const skip = (page - 1) * limit; + + const where: any = {}; + if (query.department) where.department = query.department; + if (query.status) where.status = query.status; + if (query.priority) where.priority = query.priority; + if (query.search) { + where.OR = [ + { code: { contains: query.search, mode: "insensitive" } }, + { title: { contains: query.search, mode: "insensitive" } }, + { description: { contains: query.search, mode: "insensitive" } }, + ]; + } + + const [total, items] = await Promise.all([ + (this.prisma as any).departmentTask.count({ where }), + (this.prisma as any).departmentTask.findMany({ + where, + skip, + take: limit, + orderBy: [{ priority: "desc" }, { createdAt: "desc" }], + }), + ]); + + return { + success: true, + data: items, + meta: { + total, + page, + limit, + totalPages: Math.ceil(total / limit), + }, + }; + } + + @Get("stats") + @ApiOperation({ summary: "آمار تسک‌ها به تفکیک استیت و دپارتمان" }) + async getStats() { + const tasks = await (this.prisma as any).departmentTask.findMany({ + select: { department: true, status: true, priority: true }, + }); + + const statusCounts: Record = { + BACKLOG: 0, + IN_PROGRESS: 0, + IN_REVIEW: 0, + APPROVED: 0, + DEPLOYING: 0, + DONE: 0, + }; + const departmentCounts: Record = {}; + + for (const t of tasks) { + statusCounts[t.status] = (statusCounts[t.status] || 0) + 1; + departmentCounts[t.department] = (departmentCounts[t.department] || 0) + 1; + } + + return { + success: true, + data: { + total: tasks.length, + byStatus: statusCounts, + byDepartment: departmentCounts, + }, + }; + } + + @Get(":id") + @ApiOperation({ summary: "دریافت جزییات یک تسک" }) + async findOne(@Param("id") id: string) { + const task = await (this.prisma as any).departmentTask.findUnique({ + where: { id }, + }); + if (!task) throw new NotFoundException(`Task ${id} not found`); + return { success: true, data: task }; + } + + @Post() + @ApiOperation({ summary: "ایجاد تسک جدید سازمانی" }) + async create(@Body() body: any) { + const code = body.code || "TSK-" + Date.now().toString().slice(-6); + const task = await (this.prisma as any).departmentTask.create({ + data: { + code, + department: body.department, + title: body.title, + description: body.description || null, + status: body.status || "BACKLOG", + priority: body.priority || "MEDIUM", + assignee: body.assignee || "AI_AGENT", + acceptanceCriteria: body.acceptanceCriteria || null, + executionLogs: body.executionLogs || [], + deliverableUrl: body.deliverableUrl || null, + startedAt: body.status === "IN_PROGRESS" ? new Date() : null, + }, + }); + + // ثبت در تاریخچه لاگ‌ها + await (this.prisma as any).auditLog.create({ + data: { + entity: "task", + entityId: task.id, + action: "CREATE", + department: task.department, + actor: task.assignee || "SYSTEM", + summary: "تسک جدید " + task.code + " (" + task.title + ") ایجاد شد.", + newValues: task, + }, + }); + + return { success: true, data: task }; + } + + @Put(":id/status") + @ApiOperation({ summary: "تغییر وضعیت تسک همراه با لاگ اجرا" }) + async updateStatus( + @Param("id") id: string, + @Body() body: { status: string; logNote?: string; deliverableUrl?: string } + ) { + const existing = await (this.prisma as any).departmentTask.findUnique({ + where: { id }, + }); + if (!existing) throw new NotFoundException(`Task ${id} not found`); + + const logs = Array.isArray(existing.executionLogs) ? [...existing.executionLogs] : []; + if (body.logNote) { + logs.push({ + timestamp: new Date().toISOString(), + status: body.status, + note: body.logNote, + }); + } + + const updateData: any = { + status: body.status, + executionLogs: logs, + }; + if (body.deliverableUrl) updateData.deliverableUrl = body.deliverableUrl; + if (body.status === "IN_PROGRESS" && !existing.startedAt) updateData.startedAt = new Date(); + if (body.status === "DONE") updateData.completedAt = new Date(); + + const updated = await (this.prisma as any).departmentTask.update({ + where: { id }, + data: updateData, + }); + + // ثبت در تاریخچه + await (this.prisma as any).auditLog.create({ + data: { + entity: "task", + entityId: updated.id, + action: "UPDATE", + department: updated.department, + actor: "SYSTEM", + summary: "وضعیت تسک " + updated.code + " به " + body.status + " تغییر یافت.", + oldValues: { status: existing.status }, + newValues: { status: updated.status, note: body.logNote }, + }, + }); + + return { success: true, data: updated }; + } + + @Delete(":id") + @ApiOperation({ summary: "حذف تسک" }) + async remove(@Param("id") id: string) { + await (this.prisma as any).departmentTask.delete({ where: { id } }); + return { success: true, message: "Deleted successfully" }; + } +} diff --git a/frontend/admin-panel/src/components/Sidebar.tsx b/frontend/admin-panel/src/components/Sidebar.tsx index 64ffd158..47311dbe 100644 --- a/frontend/admin-panel/src/components/Sidebar.tsx +++ b/frontend/admin-panel/src/components/Sidebar.tsx @@ -1,44 +1,46 @@ import { -Activity, + Activity, CheckSquare, -BookOpen, -Building2, -ChevronDown, -CreditCard, -DollarSign, -FileText, -FlaskConical, -FolderTree, -Globe, -Heart, -HelpCircle, -Image, -Key, -Languages, -Layers, -LayoutDashboard, -Menu, -MessageSquare, -MessageSquareQuote, -Package, -PhoneCall, -Receipt, -RotateCcw, -Settings, -ShieldCheck, -ShoppingCart, -Sliders, -Sparkles, -Star, -Tag, -TrendingUp, -Truck, -UserCheck, -Users, -Video, + BookOpen, + Building2, + ChevronDown, + CreditCard, + DollarSign, + FileText, + FlaskConical, + FolderTree, + Globe, + Heart, + HelpCircle, + Image, + Key, + Languages, + Layers, + LayoutDashboard, + Menu, + MessageSquare, + MessageSquareQuote, + Package, + PhoneCall, + Receipt, + RotateCcw, + Settings, + ShieldCheck, + ShoppingCart, + Sliders, + Sparkles, + Star, + Tag, + TrendingUp, + Truck, + UserCheck, + Users, + Video, + History, + Briefcase } from 'lucide-react'; -import { useEffect,useRef,useState } from 'react'; -import { Link,useLocation } from 'react-router-dom'; +import { useEffect, useRef, useState } from 'react'; +import { Link, useLocation } from 'react-router-dom'; import api from '../services/api'; interface SubMenuItem { @@ -66,7 +68,6 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side const [newOrdersCount, setNewOrdersCount] = useState(0); const intervalRef = useRef | null>(null); - // Auto-close sidebar on mobile navigation and manage body overflow useEffect(() => { setIsOpen(false); }, [location.pathname, setIsOpen]); @@ -112,20 +113,20 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side }, { id: 'governance', - title: 'حاکمیت و تاییدات مدیریت', + title: 'حاکمیت، تاییدات و وظایف', icon: CheckSquare, items: [ { icon: CheckSquare, label: 'کارتابل تاییدات مدیریت', path: '/approvals' }, + { icon: Briefcase, label: 'وظایف دپارتمان‌ها و ایجنت‌ها', path: '/tasks' }, + { icon: History, label: 'تاریخچه تغییرات دیتابیس (Audit)', path: '/history' }, ], }, { id: 'monitoring', title: 'مرکز مانیتورینگ و سلامت', icon: Activity, - CheckSquare, items: [ - { icon: Activity, - CheckSquare, label: 'مانیتورینگ زنده سرویس‌ها', path: '/monitoring' }, + { icon: Activity, label: 'مانیتورینگ زنده سرویس‌ها', path: '/monitoring' }, { icon: RotateCcw, label: 'پرتال مالی و استرداد زیبال', path: '/zibal-portal' }, ], }, @@ -208,7 +209,6 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side }, ]; - // Store only the active group ID so only one group stays expanded at a time const [activeGroupId, setActiveGroupId] = useState(() => { for (const g of menuGroups) { const hasActive = g.items.some( @@ -221,7 +221,6 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side return 'main'; }); - // Keep active group synchronized with URL navigation useEffect(() => { for (const g of menuGroups) { const hasActive = g.items.some( @@ -242,7 +241,6 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side return ( <> - {/* Mobile Backdrop */} {isOpen && (
- {/* Header */}
@@ -269,12 +266,11 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side
{!isCollapsed && ( - v2.4 + v2.5 )}
- {/* Menu Navigation - touch friendly & full scrolling */}