- Separate B2B_SUPPLIER_STRATEGY strategic manager actions from digital tasks - Ensure strategic proposals do not create/requeue digital tasks or set executedAt - Ensure SEO and digital approvals transition actionable tasks to TODO - Strengthen task completion policy: require independently verifiable HTTP(S) deliverables, reject canina://, git://stage, and post-tsk missing article placeholders - Reject completion when QA verification evidence reports 404 or missing article errors - Add unit test coverage for ApprovalsController, DepartmentTasksController and completion policy
265 lines
8.8 KiB
TypeScript
265 lines
8.8 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");
|
|
}
|
|
|
|
const item = await (this.prisma as any).approvalRequest.findUnique({
|
|
where: { id },
|
|
});
|
|
if (!item) {
|
|
throw new NotFoundException(`Approval request ${id} not found`);
|
|
}
|
|
|
|
if (dto.decision === "REJECTED") {
|
|
const updated = await (this.prisma as any).approvalRequest.update({
|
|
where: { id },
|
|
data: {
|
|
status: "REJECTED",
|
|
ceoNotes: dto.ceoNotes || null,
|
|
},
|
|
});
|
|
|
|
if ((this.prisma as any).departmentTask?.updateMany) {
|
|
await (this.prisma as any).departmentTask.updateMany({
|
|
where: { approvalId: id },
|
|
data: { status: "REJECTED" },
|
|
});
|
|
}
|
|
|
|
return {
|
|
success: true,
|
|
message: "درخواست رد شد و در سوابق ممیزی ثبت گردید.",
|
|
data: updated,
|
|
};
|
|
}
|
|
|
|
// تفکیک اقدامات استراتژیک تامینکننده/مدیریتی از کارهای دیجیتال سایت
|
|
const isStrategicSupplierAction =
|
|
item.category === "B2B_SUPPLIER_STRATEGY" ||
|
|
item.category === "PARTNERSHIP" ||
|
|
(item.department === "B2B" && String(item.category || "").includes("STRATEGY"));
|
|
|
|
if (isStrategicSupplierAction) {
|
|
// طرحهای B2B_SUPPLIER_STRATEGY منحصراً در سوابق مدیریتی تایید میشوند.
|
|
// هیچ تسک دیجیتالی ایجاد یا بازگشایی نمیشود و executedAt فیزیکی ثبت نمیگردد.
|
|
const updateData: any = {
|
|
status: "APPROVED",
|
|
ceoNotes: dto.ceoNotes || null,
|
|
};
|
|
|
|
if (dto.outcome || dto.evidence) {
|
|
const payload = typeof item.payload === "object" && item.payload !== null
|
|
? { ...(item.payload as Record<string, any>) }
|
|
: {};
|
|
if (dto.outcome) payload.outcome = dto.outcome;
|
|
if (dto.evidence) payload.evidence = dto.evidence;
|
|
updateData.payload = payload;
|
|
}
|
|
|
|
const updated = await (this.prisma as any).approvalRequest.update({
|
|
where: { id },
|
|
data: updateData,
|
|
});
|
|
|
|
return {
|
|
success: true,
|
|
message: "طرح استراتژیک تامینکننده تایید گردید و در سوابق مدیریتی ثبت شد.",
|
|
data: updated,
|
|
};
|
|
}
|
|
|
|
// کارهای دیجیتال (مانند SEO، محتوا، قیمتگذاری و فنی)
|
|
// تایید مجوز اجرای کار دیجیتال است و تسک متناظر را در صف TODO قرار میدهد
|
|
const updated = await (this.prisma as any).approvalRequest.update({
|
|
where: { id },
|
|
data: {
|
|
status: "APPROVED",
|
|
ceoNotes: dto.ceoNotes || null,
|
|
},
|
|
});
|
|
|
|
// جستجو یا ایجاد تسک متناظر با استاتوس TODO
|
|
const existingTask = await (this.prisma as any).departmentTask.findFirst({
|
|
where: { approvalId: id },
|
|
});
|
|
|
|
if (existingTask) {
|
|
await (this.prisma as any).departmentTask.update({
|
|
where: { id: existingTask.id },
|
|
data: {
|
|
status: "TODO",
|
|
description: dto.ceoNotes
|
|
? (existingTask.description || "") + "\n\n[یادداشت مدیرعامل]: " + dto.ceoNotes
|
|
: existingTask.description,
|
|
},
|
|
});
|
|
} else {
|
|
await (this.prisma as any).departmentTask.create({
|
|
data: {
|
|
code: "TSK-" + Date.now().toString().slice(-6),
|
|
department: item.department || "SEO",
|
|
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: "درخواست تایید شد و مأموریت به صف اقدام (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" };
|
|
}
|
|
}
|