Compare commits

...
2 changed files with 108 additions and 58 deletions

No files matched your search

@@ -0,0 +1,54 @@
import { BadRequestException } from "@nestjs/common";
import { ApprovalsController } from "./approvals.controller";
function fixture(category: string, status = "PENDING") {
const approval = { id: "approval-1", department: "seo", category, title: "Proposal", status };
const tx = {
approvalRequest: {
findUnique: jest.fn().mockResolvedValue(approval),
updateMany: jest.fn().mockResolvedValue({ count: 1 }),
findFirst: jest.fn().mockResolvedValue({ ...approval, status: "APPROVED" }),
},
departmentTask: {
findFirst: jest.fn().mockResolvedValue(null),
create: jest.fn().mockResolvedValue({ id: "task-1" }),
update: jest.fn(),
},
};
const prisma = { $transaction: jest.fn((fn: (client: typeof tx) => Promise<unknown>) => fn(tx)) };
return { controller: new ApprovalsController(prisma as any), prisma, tx };
}
describe("approval routing", () => {
it("keeps supplier strategy managerial and does not enqueue", async () => {
const { controller, tx } = fixture("B2B_SUPPLIER_STRATEGY");
await controller.decide("approval-1", { decision: "APPROVED", ceoNotes: "Review with supplier" });
expect(tx.approvalRequest.updateMany).toHaveBeenCalledWith(expect.objectContaining({ where: { id: "approval-1", status: "PENDING" } }));
expect(tx.departmentTask.create).not.toHaveBeenCalled();
expect(tx.departmentTask.update).not.toHaveBeenCalled();
});
it("enqueues an approved SEO digital proposal once within the transaction", async () => {
const { controller, prisma, tx } = fixture("SEO");
await controller.decide("approval-1", { decision: "APPROVED", ceoNotes: "Go" });
expect(prisma.$transaction).toHaveBeenCalledTimes(1);
expect(tx.departmentTask.create).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ approvalId: "approval-1", status: "TODO" }) }));
tx.approvalRequest.updateMany.mockResolvedValue({ count: 0 });
await controller.decide("approval-1", { decision: "APPROVED", ceoNotes: "Go" });
expect(tx.departmentTask.create).toHaveBeenCalledTimes(1);
expect(tx.departmentTask.update).not.toHaveBeenCalled();
});
it("refuses an unknown category instead of entering the automatic queue", async () => {
const { controller, tx } = fixture("UNKNOWN_FUTURE_CATEGORY");
await expect(controller.decide("approval-1", { decision: "APPROVED" })).rejects.toBeInstanceOf(BadRequestException);
expect(tx.departmentTask.create).not.toHaveBeenCalled();
});
it("does not requeue an already approved proposal", async () => {
const { controller, tx } = fixture("SEO", "APPROVED");
await controller.decide("approval-1", { decision: "APPROVED" });
expect(tx.approvalRequest.updateMany).not.toHaveBeenCalled();
expect(tx.departmentTask.create).not.toHaveBeenCalled();
});
});
+54 -58
View File
@@ -144,70 +144,66 @@ export class ApprovalsController {
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`);
}
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") {
// 5. رد توسط مدیرعامل: تسک و درخواست کلاً از سیستم پاکسازی کامل می‌شوند
await (this.prisma as any).departmentTask.deleteMany({
where: { approvalId: id },
});
await (this.prisma as any).approvalRequest.delete({
where: { id },
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: "درخواست با موفقیت رد و از سیستم پاکسازی شد.",
message: automatedCategories.has(item.category)
? "درخواست تایید شد و مأموریت به صف اقدام (TODO) دپارتمان منتقل گردید."
: "طرح تامین‌کننده تایید شد؛ تسک خودکار ایجاد نشد.",
data: updated,
};
}
// 1. تایید مدیرعامل: وضعیت درخواست APPROVED و وضعیت تسک در صف اقدام به TODO تغییر می‌یابد
const updated = await (this.prisma as any).approvalRequest.update({
where: { id },
data: {
status: "APPROVED",
ceoNotes: dto.ceoNotes || null,
executedAt: new Date(),
},
});
// جستجو یا ایجاد تسک متناظر با استاتوس 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,
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")