Files
canina/backend/src/admin/approvals.controller.ts
T

216 lines
8.0 KiB
TypeScript

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) || 100;
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");
}
return (this.prisma as any).$transaction(async (tx: any) => {
const item = await tx.approvalRequest.findUnique({ where: { id } });
if (!item) throw new NotFoundException(`Approval request ${id} not found`);
if (dto.decision === "REJECTED") {
if (item.status !== "PENDING") {
throw new BadRequestException("Only pending requests can be rejected");
}
await tx.departmentTask.deleteMany({ where: { approvalId: id } });
await tx.approvalRequest.delete({ where: { id, status: "PENDING" } });
return { success: true, message: "درخواست با موفقیت رد و از سیستم پاکسازی شد." };
}
// Only explicitly digital site work may enter the automated task queue.
// Supplier strategy and every unknown category remain outside orchestration.
const automatedCategories = new Set(["SEO", "SEO_DIGITAL", "CEO_EXPEDITE"]);
if (item.category !== "B2B_SUPPLIER_STRATEGY" && !automatedCategories.has(item.category)) {
throw new BadRequestException(`Approval category ${item.category} is not routed to automated tasks`);
}
if (item.status !== "PENDING") {
return { success: true, message: "درخواست پیش‌تر تایید شده است.", data: item };
}
// The conditional write locks the approval row. A racing decision loses
// the PENDING predicate and must not create a second task or reset one.
const claimed = await tx.approvalRequest.updateMany({
where: { id, status: "PENDING" },
data: { status: "APPROVED", ceoNotes: dto.ceoNotes || null, executedAt: new Date() },
});
if (claimed.count !== 1) {
const current = await tx.approvalRequest.findUnique({ where: { id } });
if (!current) throw new NotFoundException(`Approval request ${id} not found`);
return { success: true, message: "درخواست پیش‌تر بررسی شده است.", data: current };
}
const updated = await tx.approvalRequest.findUnique({ where: { id } });
if (automatedCategories.has(item.category)) {
const existingTask = await tx.departmentTask.findFirst({ where: { approvalId: id } });
if (!existingTask) {
await tx.departmentTask.create({
data: {
code: "TSK-" + item.id,
department: item.department,
title: item.title,
description: dto.ceoNotes ? item.title + "\n\n[یادداشت مدیرعامل]: " + dto.ceoNotes : item.title,
status: "TODO",
priority: "HIGH",
assignee: "AI_AGENT",
approvalId: item.id,
},
});
}
}
return {
success: true,
message: automatedCategories.has(item.category)
? "درخواست تایید شد و مأموریت به صف اقدام (TODO) دپارتمان منتقل گردید."
: "طرح تامین‌کننده تایید شد؛ تسک خودکار ایجاد نشد.",
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" };
}
}