feat(admin): implement approval separation and verifiable completion policy

- 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
This commit is contained in:
devops committed 2026-10-20 19:41:39 +00:00
1 parent ee90284129
commit 02fe634944
7 files changed
+605 -24

No files matched your search

@@ -0,0 +1,271 @@
import { Test, TestingModule } from "@nestjs/testing";
import { BadRequestException, NotFoundException } from "@nestjs/common";
import { ApprovalsController } from "./approvals.controller";
import { PrismaService } from "../prisma/prisma.service";
describe("ApprovalsController", () => {
let controller: ApprovalsController;
let prisma: {
approvalRequest: {
findUnique: jest.Mock;
findMany: jest.Mock;
count: jest.Mock;
create: jest.Mock;
update: jest.Mock;
delete: jest.Mock;
};
departmentTask: {
findFirst: jest.Mock;
findMany: jest.Mock;
create: jest.Mock;
update: jest.Mock;
deleteMany: jest.Mock;
updateMany: jest.Mock;
};
};
beforeEach(async () => {
prisma = {
approvalRequest: {
findUnique: jest.fn(),
findMany: jest.fn(),
count: jest.fn(),
create: jest.fn(),
update: jest.fn(),
delete: jest.fn(),
},
departmentTask: {
findFirst: jest.fn(),
findMany: jest.fn(),
create: jest.fn(),
update: jest.fn(),
deleteMany: jest.fn(),
updateMany: jest.fn(),
},
};
const module: TestingModule = await Test.createTestingModule({
controllers: [ApprovalsController],
providers: [
{
provide: PrismaService,
useValue: prisma,
},
],
}).compile();
controller = module.get<ApprovalsController>(ApprovalsController);
});
describe("decide - B2B_SUPPLIER_STRATEGY approval separation", () => {
it("B2B_SUPPLIER_STRATEGY approval must not create digital task nor set executedAt as physical action", async () => {
const approvalId = "b2b-strategy-uuid-1";
const approvalItem = {
id: approvalId,
department: "B2B",
category: "B2B_SUPPLIER_STRATEGY",
title: "[طرح استراتژیک تامین‌کننده] توسعه شبکه کلینیکی آلمان",
payload: { target: "German Suppliers", tier: "Direct" },
status: "PENDING",
};
prisma.approvalRequest.findUnique.mockResolvedValue(approvalItem);
prisma.approvalRequest.update.mockResolvedValue({
...approvalItem,
status: "APPROVED",
ceoNotes: "موافقت با مذاکره اولیه",
});
prisma.departmentTask.findFirst.mockResolvedValue(null);
const result = await controller.decide(approvalId, {
decision: "APPROVED",
ceoNotes: "موافقت با مذاکره اولیه",
});
expect(result.success).toBe(true);
expect(prisma.approvalRequest.update).toHaveBeenCalledWith({
where: { id: approvalId },
data: expect.objectContaining({
status: "APPROVED",
ceoNotes: "موافقت با مذاکره اولیه",
}),
});
// Verify executedAt is NOT set as physical action
const updateCall = prisma.approvalRequest.update.mock.calls[0][0];
expect(updateCall.data.executedAt).toBeUndefined();
// Verify NO digital task is created in departmentTask queue
expect(prisma.departmentTask.create).not.toHaveBeenCalled();
expect(prisma.departmentTask.update).not.toHaveBeenCalled();
});
it("B2B_SUPPLIER_STRATEGY approval must not requeue existing digital task", async () => {
const approvalId = "b2b-strategy-uuid-2";
const approvalItem = {
id: approvalId,
department: "B2B",
category: "B2B_SUPPLIER_STRATEGY",
title: "[طرح استراتژیک تامین‌کننده] پکیج نمونه دارویی",
payload: {},
status: "PENDING",
};
prisma.approvalRequest.findUnique.mockResolvedValue(approvalItem);
prisma.approvalRequest.update.mockResolvedValue({
...approvalItem,
status: "APPROVED",
});
prisma.departmentTask.findFirst.mockResolvedValue({
id: "task-existing-1",
status: "BACKLOG",
title: "Legacy task",
});
const result = await controller.decide(approvalId, {
decision: "APPROVED",
});
expect(result.success).toBe(true);
// Ensure existing task was NOT updated or requeued to TODO
expect(prisma.departmentTask.update).not.toHaveBeenCalled();
expect(prisma.departmentTask.create).not.toHaveBeenCalled();
});
});
describe("decide - SEO approval actionable digital task", () => {
it("SEO approval creates actionable digital task in TODO", async () => {
const approvalId = "seo-approval-uuid-1";
const approvalItem = {
id: approvalId,
department: "SEO",
category: "SEO",
title: "بهینه‌سازی متاتگ‌های صفحات دسته‌بندی گربه",
payload: { targetUrl: "/category/cat-food" },
status: "PENDING",
};
prisma.approvalRequest.findUnique.mockResolvedValue(approvalItem);
prisma.approvalRequest.update.mockResolvedValue({
...approvalItem,
status: "APPROVED",
ceoNotes: "در اولویت سئو قرار گیرد",
});
prisma.departmentTask.findFirst.mockResolvedValue(null);
prisma.departmentTask.create.mockResolvedValue({
id: "new-task-uuid",
code: "TSK-892110",
department: "SEO",
title: approvalItem.title,
status: "TODO",
priority: "HIGH",
assignee: "AI_AGENT",
approvalId: approvalId,
});
const result = await controller.decide(approvalId, {
decision: "APPROVED",
ceoNotes: "در اولویت سئو قرار گیرد",
});
expect(result.success).toBe(true);
expect(prisma.approvalRequest.update).toHaveBeenCalledWith({
where: { id: approvalId },
data: expect.objectContaining({
status: "APPROVED",
ceoNotes: "در اولویت سئو قرار گیرد",
}),
});
// Digital task MUST be created with status TODO
expect(prisma.departmentTask.create).toHaveBeenCalledWith({
data: expect.objectContaining({
department: "SEO",
title: approvalItem.title,
status: "TODO",
priority: "HIGH",
assignee: "AI_AGENT",
approvalId: approvalId,
}),
});
});
it("SEO approval requeues existing task to TODO when existing task found", async () => {
const approvalId = "seo-approval-uuid-2";
const approvalItem = {
id: approvalId,
department: "SEO",
category: "SEO",
title: "بررسی کنیبان سئو مقاله تغذیه سگ",
payload: {},
status: "PENDING",
};
const existingTask = {
id: "existing-task-99",
code: "TSK-112233",
status: "IN_REVIEW",
description: "Initial draft",
approvalId: approvalId,
};
prisma.approvalRequest.findUnique.mockResolvedValue(approvalItem);
prisma.approvalRequest.update.mockResolvedValue({
...approvalItem,
status: "APPROVED",
ceoNotes: "تایید نهایی جهت اقدام",
});
prisma.departmentTask.findFirst.mockResolvedValue(existingTask);
prisma.departmentTask.update.mockResolvedValue({
...existingTask,
status: "TODO",
});
const result = await controller.decide(approvalId, {
decision: "APPROVED",
ceoNotes: "تایید نهایی جهت اقدام",
});
expect(result.success).toBe(true);
expect(prisma.departmentTask.update).toHaveBeenCalledWith({
where: { id: existingTask.id },
data: expect.objectContaining({
status: "TODO",
}),
});
});
});
describe("decide - rejection handling", () => {
it("handles REJECTED decision cleanly without deleting approval audit history", async () => {
const approvalId = "approval-reject-uuid";
const approvalItem = {
id: approvalId,
department: "SEO",
category: "SEO",
title: "تغییر ساختار URL",
status: "PENDING",
};
prisma.approvalRequest.findUnique.mockResolvedValue(approvalItem);
prisma.approvalRequest.update.mockResolvedValue({
...approvalItem,
status: "REJECTED",
ceoNotes: "ریسک بالای افت رتبه سئو",
});
const result = await controller.decide(approvalId, {
decision: "REJECTED",
ceoNotes: "ریسک بالای افت رتبه سئو",
});
expect(result.success).toBe(true);
expect(prisma.approvalRequest.update).toHaveBeenCalledWith({
where: { id: approvalId },
data: expect.objectContaining({
status: "REJECTED",
ceoNotes: "ریسک بالای افت رتبه سئو",
}),
});
});
});
});
+56 -11
View File
@@ -106,7 +106,6 @@ export class ApprovalsController {
throw new NotFoundException(`Approval request ${id} not found`);
}
// شبیه‌سازی بسته به دسته‌بندی
let testResult: any = { status: "SIMULATION_SUCCESS" };
if (item.category === "PRICING") {
const payload = item.payload as any;
@@ -152,26 +151,70 @@ export class ApprovalsController {
}
if (dto.decision === "REJECTED") {
// 5. رد توسط مدیرعامل: تسک و درخواست کلاً از سیستم پاکسازی کامل می‌شوند
await (this.prisma as any).departmentTask.deleteMany({
where: { approvalId: id },
});
await (this.prisma as any).approvalRequest.delete({
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: "درخواست با موفقیت رد و از سیستم پاکسازی شد.",
message: "درخواست رد شد و در سوابق ممیزی ثبت گردید.",
data: updated,
};
}
// 1. تایید مدیرعامل: وضعیت درخواست APPROVED و وضعیت تسک در صف اقدام به TODO تغییر می‌یابد
// تفکیک اقدامات استراتژیک تامین‌کننده/مدیریتی از کارهای دیجیتال سایت
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,
executedAt: new Date(),
},
});
@@ -185,14 +228,16 @@ export class ApprovalsController {
where: { id: existingTask.id },
data: {
status: "TODO",
description: dto.ceoNotes ? (existingTask.description || "") + "\n\n[یادداشت مدیرعامل]: " + dto.ceoNotes : existingTask.description,
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,
department: item.department || "SEO",
title: item.title,
description: dto.ceoNotes ? (item.title + "\n\n[یادداشت مدیرعامل]: " + dto.ceoNotes) : item.title,
status: "TODO",
@@ -41,4 +41,44 @@ describe("department task completion policy", () => {
}),
).not.toThrow();
});
it("rejects pseudo-protocol canina:// deliverable URLs", () => {
expect(() =>
assertTaskCanComplete({
deliverableUrl: "canina://blog/sample-article",
acceptanceCriteria: { criteria: ["HTTP 200"] },
executionLogs: [{ status: "QA_PASSED" }],
}),
).toThrow(BadRequestException);
});
it("rejects git://stage staging or repo URLs as verifiable deliverable", () => {
expect(() =>
assertTaskCanComplete({
deliverableUrl: "git://stage/canina-repo#commit123",
acceptanceCriteria: { criteria: ["HTTP 200"] },
executionLogs: [{ status: "QA_PASSED" }],
}),
).toThrow(BadRequestException);
});
it("rejects missing or placeholder post-tsk article deliverables", () => {
expect(() =>
assertTaskCanComplete({
deliverableUrl: "https://canina.ir/blog/post-tsk-49102",
acceptanceCriteria: { criteria: ["HTTP 200"] },
executionLogs: [{ status: "QA_PASSED" }],
}),
).toThrow(BadRequestException);
});
it("rejects completion when QA evidence reports missing article or 404 error", () => {
expect(() =>
assertTaskCanComplete({
deliverableUrl: "https://canina.ir/blog/verified-article",
acceptanceCriteria: { criteria: ["HTTP 200"] },
executionLogs: [{ status: "QA_PASSED", note: "HTTP 404 - مقاله یافت نشد" }],
}),
).toThrow(BadRequestException);
});
});
@@ -1,6 +1,8 @@
import { BadRequestException } from "@nestjs/common";
interface CompletabaleTask {
export interface CompletableTask {
code?: string | null;
title?: string | null;
deliverableUrl?: string | null;
acceptanceCriteria?: unknown;
executionLogs?: unknown;
@@ -18,23 +20,74 @@ function hasAcceptanceCriteria(criteria: unknown): boolean {
return false;
}
function hasQaEvidence(logs: unknown): boolean {
function hasValidQaEvidence(logs: unknown): boolean {
if (!Array.isArray(logs)) return false;
return logs.some((log) => {
if (!log || typeof log !== "object") return false;
const status = String((log as Record<string, unknown>).status || "").toUpperCase();
return ["QA_PASSED", "VERIFIED", "PRODUCTION_VERIFIED"].includes(status);
});
const validPassStatuses = ["QA_PASSED", "VERIFIED", "PRODUCTION_VERIFIED"];
let foundValidPass = false;
for (const log of logs) {
if (!log || typeof log !== "object") continue;
const entry = log as Record<string, unknown>;
const status = String(entry.status || "").toUpperCase();
const note = String(entry.note || "").toLowerCase();
// Rejection of invalid QA claims: 404, missing article, not found, post-tsk
if (
note.includes("404") ||
note.includes("مقاله یافت نشد") ||
note.includes("not found") ||
note.includes("missing article") ||
note.includes("post-tsk")
) {
return false;
}
if (validPassStatuses.includes(status)) {
foundValidPass = true;
}
}
return foundValidPass;
}
export function assertTaskCanComplete(task: CompletabaleTask): void {
if (!task.deliverableUrl?.trim()) {
export function assertTaskCanComplete(task: CompletableTask): void {
const rawUrl = task.deliverableUrl?.trim();
if (!rawUrl) {
throw new BadRequestException("DONE requires a verifiable deliverable URL");
}
const lowerUrl = rawUrl.toLowerCase();
// Reject internal pseudo-protocols
if (lowerUrl.startsWith("canina://") || lowerUrl.includes("canina://")) {
throw new BadRequestException("Deliverable URL cannot use pseudo-protocol canina://; an independently verifiable HTTP(S) URL is required");
}
// Reject git repository pointers or staging branches as production deliverables
if (lowerUrl.startsWith("git://") || lowerUrl.includes("git://stage")) {
throw new BadRequestException("Deliverable URL cannot be a git staging reference; an independently verifiable HTTP(S) URL is required");
}
// Must be an HTTP or HTTPS URL
if (!lowerUrl.startsWith("http://") && !lowerUrl.startsWith("https://")) {
throw new BadRequestException("DONE requires an independently verifiable HTTP or HTTPS deliverable URL");
}
// Reject deleted or placeholder post-tsk articles
if (/post[-_]?tsk/i.test(rawUrl)) {
throw new BadRequestException("Deliverable URL references an unverified or deleted post-tsk placeholder article");
}
if (task.title && /post[-_]?tsk/i.test(task.title)) {
throw new BadRequestException("Task references an unverified or deleted post-tsk article");
}
if (task.code && /post[-_]?tsk/i.test(task.code)) {
throw new BadRequestException("Task references an unverified or deleted post-tsk code");
}
if (!hasAcceptanceCriteria(task.acceptanceCriteria)) {
throw new BadRequestException("DONE requires explicit acceptance criteria");
}
if (!hasQaEvidence(task.executionLogs)) {
if (!hasValidQaEvidence(task.executionLogs)) {
throw new BadRequestException("DONE requires QA/production verification evidence");
}
}
@@ -0,0 +1,163 @@
import { Test, TestingModule } from "@nestjs/testing";
import { BadRequestException, NotFoundException } from "@nestjs/common";
import { DepartmentTasksController } from "./department-tasks.controller";
import { PrismaService } from "../prisma/prisma.service";
describe("DepartmentTasksController", () => {
let controller: DepartmentTasksController;
let prisma: {
departmentTask: {
findUnique: jest.Mock;
findMany: jest.Mock;
count: jest.Mock;
create: jest.Mock;
update: jest.Mock;
delete: jest.Mock;
};
auditLog: {
create: jest.Mock;
};
};
beforeEach(async () => {
prisma = {
departmentTask: {
findUnique: jest.fn(),
findMany: jest.fn(),
count: jest.fn(),
create: jest.fn(),
update: jest.fn(),
delete: jest.fn(),
},
auditLog: {
create: jest.fn().mockResolvedValue({ id: "audit-1" }),
},
};
const module: TestingModule = await Test.createTestingModule({
controllers: [DepartmentTasksController],
providers: [
{
provide: PrismaService,
useValue: prisma,
},
],
}).compile();
controller = module.get<DepartmentTasksController>(DepartmentTasksController);
});
describe("updateStatus - verifiable completion guards", () => {
it("rejects completion with pseudo-protocol canina://", async () => {
const taskId = "task-101";
prisma.departmentTask.findUnique.mockResolvedValue({
id: taskId,
code: "TSK-100101",
title: "Test Task",
status: "TEST",
acceptanceCriteria: { criteria: ["200 OK"] },
executionLogs: [{ status: "QA_PASSED" }],
deliverableUrl: null,
});
await expect(
controller.updateStatus(taskId, {
status: "DONE",
deliverableUrl: "canina://blog/fake-article",
}),
).rejects.toThrow(BadRequestException);
});
it("rejects completion with git://stage repository reference", async () => {
const taskId = "task-102";
prisma.departmentTask.findUnique.mockResolvedValue({
id: taskId,
code: "TSK-100102",
title: "Test Task",
status: "TEST",
acceptanceCriteria: { criteria: ["200 OK"] },
executionLogs: [{ status: "QA_PASSED" }],
deliverableUrl: null,
});
await expect(
controller.updateStatus(taskId, {
status: "DONE",
deliverableUrl: "git://stage/canina-repo#commit-xyz",
}),
).rejects.toThrow(BadRequestException);
});
it("rejects completion with post-tsk placeholder article", async () => {
const taskId = "task-103";
prisma.departmentTask.findUnique.mockResolvedValue({
id: taskId,
code: "TSK-100103",
title: "Test Task",
status: "TEST",
acceptanceCriteria: { criteria: ["200 OK"] },
executionLogs: [{ status: "QA_PASSED" }],
deliverableUrl: null,
});
await expect(
controller.updateStatus(taskId, {
status: "DONE",
deliverableUrl: "https://canina.ir/blog/post-tsk-998877",
}),
).rejects.toThrow(BadRequestException);
});
it("rejects completion when QA log reports missing article / 404", async () => {
const taskId = "task-104";
prisma.departmentTask.findUnique.mockResolvedValue({
id: taskId,
code: "TSK-100104",
title: "Test Task",
status: "TEST",
acceptanceCriteria: { criteria: ["200 OK"] },
executionLogs: [],
deliverableUrl: "https://canina.ir/blog/real-article",
});
await expect(
controller.updateStatus(taskId, {
status: "DONE",
logNote: "QA_PASSED but received 404 - مقاله یافت نشد",
}),
).rejects.toThrow(BadRequestException);
});
it("allows completion with valid HTTPS deliverable URL and verified QA evidence", async () => {
const taskId = "task-105";
const existingTask = {
id: taskId,
code: "TSK-100105",
title: "Optimized Cat Food Landing",
status: "TEST",
acceptanceCriteria: { criteria: ["HTTP 200", "Lighthouse > 90"] },
executionLogs: [{ status: "PRODUCTION_VERIFIED", note: "Live 200 verified on production" }],
deliverableUrl: "https://canina.ir/blog/cat-food-nutrition",
};
prisma.departmentTask.findUnique.mockResolvedValue(existingTask);
prisma.departmentTask.update.mockResolvedValue({
...existingTask,
status: "DONE",
completedAt: new Date(),
});
const res = await controller.updateStatus(taskId, {
status: "DONE",
});
expect(res.success).toBe(true);
expect(prisma.departmentTask.update).toHaveBeenCalledWith({
where: { id: taskId },
data: expect.objectContaining({
status: "DONE",
completedAt: expect.any(Date),
}),
});
});
});
});
@@ -130,7 +130,6 @@ export class DepartmentTasksController {
},
});
// ثبت در تاریخچه لاگ‌ها
await (this.prisma as any).auditLog.create({
data: {
entity: "task",
@@ -169,6 +168,8 @@ export class DepartmentTasksController {
const candidateDeliverableUrl = body.deliverableUrl || existing.deliverableUrl;
if (body.status === "DONE") {
assertTaskCanComplete({
code: existing.code,
title: existing.title,
deliverableUrl: candidateDeliverableUrl,
acceptanceCriteria: existing.acceptanceCriteria,
executionLogs: logs,
@@ -182,7 +183,6 @@ export class DepartmentTasksController {
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();
// اگر تست QA ناموفق بود و به TODO برگشت، لاگ اصلاح ضمیمه می‌شود
if (body.status === "TODO" && body.logNote) {
updateData.description = (existing.description || "") + "\n\n[اصلاحات و تضمین کیفیت QA]: " + body.logNote;
}
@@ -192,7 +192,6 @@ export class DepartmentTasksController {
data: updateData,
});
// ثبت در تاریخچه
await (this.prisma as any).auditLog.create({
data: {
entity: "task",
@@ -33,6 +33,16 @@ export class DecideApprovalDto {
@IsOptional()
@IsString()
ceoNotes?: string;
@ApiPropertyOptional({ description: "نتیجه اقدام مدیریتی یا استراتژیک" })
@IsOptional()
@IsString()
outcome?: string;
@ApiPropertyOptional({ description: "مستندات و مدرک اقدام مدیریتی" })
@IsOptional()
@IsString()
evidence?: string;
}
export class QueryApprovalDto {