Merge develop into main: complete autonomous corporate orchestration, manager actions separation, and truthful QA gates
Deploy Canina / deploy (push) Successful in 50s
Deploy Canina / deploy (push) Successful in 50s
This commit is contained in:
commit
459f8b59fe
23 files changed
+1923
-460
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: "ریسک بالای افت رتبه سئو",
|
||||
}),
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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 {
|
||||
|
||||
@@ -117,8 +117,9 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side
|
||||
title: 'حاکمیت، تاییدات و وظایف',
|
||||
icon: CheckSquare,
|
||||
items: [
|
||||
{ icon: Sparkles, label: 'اتاق ارکستراسیون ۳بعدی (HQ)', path: '/governance/hq' },
|
||||
{ icon: CheckSquare, label: 'کارتابل تاییدات مدیریت', path: '/approvals' },
|
||||
{ icon: Building2, label: 'نمای وضعیت دپارتمانها', path: '/governance/hq' },
|
||||
{ icon: Briefcase, label: 'اقدامات مدیریتی و همکاریها', path: '/manager-actions' },
|
||||
{ icon: CheckSquare, label: 'مجوزهای عملیاتی', path: '/approvals' },
|
||||
{ icon: Briefcase, label: 'وظایف دپارتمانها و ایجنتها', path: '/tasks' },
|
||||
{ icon: History, label: 'تاریخچه تغییرات دیتابیس (Audit)', path: '/history' },
|
||||
],
|
||||
|
||||
@@ -12,6 +12,9 @@ interface TopbarProps {
|
||||
}
|
||||
|
||||
const SEARCHABLE_PAGES = [
|
||||
{ label: "اقدامات مدیریتی و همکاریها (Manager Actions)", path: "/manager-actions", keywords: ["اقدامات", "مدیریتی", "همکاری", "b2b", "تامین", "استراتژی", "actions"] },
|
||||
{ label: "مجوزهای عملیاتی مدیریت (Operational Approvals)", path: "/approvals", keywords: ["مجوز", "مجوزها", "تاییدات", "approvals", "عملیاتی", "تایید"] },
|
||||
{ label: "وضعیت دپارتمانها و ارکستراسیون (HQ)", path: "/governance/hq", keywords: ["ارکستراسیون", "دپارتمان", "hq", "governance", "وضعیت"] },
|
||||
{ label: 'داشبورد (خلاصه وضعیت فروشگاه)', path: '/', keywords: ['dashboard', 'آمار', 'فروش', 'خانه'] },
|
||||
{ label: 'مرکز مانیتورینگ و سلامت سرویسها', path: '/monitoring', keywords: ['monitoring', 'مانیتورینگ', 'سلامت', 'پینگ', 'وضعیت', 'سرعت'] },
|
||||
{ label: 'مدیریت نسخههای پزشکی (Prescriptions)', path: '/prescriptions', keywords: ['نسخه', 'نسخهها', 'پزشک', 'دارو', 'تجویز', 'rx', 'prescription', 'بررسی نسخه'] },
|
||||
|
||||
@@ -15,6 +15,8 @@ import {
|
||||
FileText,
|
||||
Search,
|
||||
ArrowUpDown,
|
||||
ArrowUpRight,
|
||||
Briefcase,
|
||||
Filter,
|
||||
CheckCheck,
|
||||
Building2,
|
||||
@@ -474,8 +476,9 @@ export default function ApprovalsPage() {
|
||||
try {
|
||||
const res = await api.get('/admin/approvals?limit=100');
|
||||
if (res.data?.success) {
|
||||
setItems(res.data.data);
|
||||
setPendingCount(res.data.meta?.pendingCount || 0);
|
||||
const authorizations = (res.data.data as ApprovalItem[]).filter(item => item.category !== 'B2B_SUPPLIER_STRATEGY');
|
||||
setItems(authorizations);
|
||||
setPendingCount(authorizations.filter(item => item.status === 'PENDING').length);
|
||||
const initialNotes: Record<string, string> = {};
|
||||
res.data.data.forEach((item: ApprovalItem) => {
|
||||
if (item.ceoNotes) initialNotes[item.id] = item.ceoNotes;
|
||||
@@ -520,7 +523,7 @@ export default function ApprovalsPage() {
|
||||
if (res.data?.success) {
|
||||
toast.success(
|
||||
decision === 'APPROVED'
|
||||
? 'درخواست تایید و مأموریت وارد چرخه اجرا شد'
|
||||
? 'مجوز تایید شد؛ نتیجه اجرا جداگانه پیگیری شود'
|
||||
: 'درخواست رد شد'
|
||||
);
|
||||
await fetchApprovals();
|
||||
@@ -578,7 +581,7 @@ export default function ApprovalsPage() {
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-black bg-emerald-50 text-emerald-800 border border-emerald-200">
|
||||
<CheckCircle2 className="w-3.5 h-3.5 text-emerald-600" />
|
||||
<span>تایید و ابلاغ شد</span>
|
||||
<span>مجوز تایید شد</span>
|
||||
</span>
|
||||
);
|
||||
case 'REJECTED':
|
||||
@@ -688,6 +691,23 @@ export default function ApprovalsPage() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Separation Banner */}
|
||||
<div className="bg-indigo-50/80 border border-indigo-200 p-4 rounded-2xl flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 shadow-xs">
|
||||
<div className="flex items-center gap-2.5 text-xs text-indigo-950 font-medium">
|
||||
<Briefcase className="w-4 h-4 text-indigo-600 shrink-0" />
|
||||
<span>
|
||||
اقدامات مدیریتی، توسعه سازمانی و استراتژی تامینکنندگان به بخش مستقل <strong>«اقدامات مدیریتی و همکاریها»</strong> تفکیک شدهاند.
|
||||
</span>
|
||||
</div>
|
||||
<a
|
||||
href="/manager-actions"
|
||||
className="inline-flex items-center gap-1.5 px-3.5 py-1.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl text-xs font-bold shrink-0 transition-all shadow-2xs"
|
||||
>
|
||||
<span>مشاهده اقدامات مدیریتی</span>
|
||||
<ArrowUpRight className="w-3.5 h-3.5" />
|
||||
</a>
|
||||
</div>
|
||||
|
||||
{/* Summary KPI Cards */}
|
||||
<div className="grid grid-cols-2 sm:grid-cols-4 gap-3.5">
|
||||
<div className="bg-white p-4 rounded-2xl border border-gray-200/80 shadow-xs flex items-center justify-between">
|
||||
@@ -712,7 +732,7 @@ export default function ApprovalsPage() {
|
||||
|
||||
<div className="bg-white p-4 rounded-2xl border border-emerald-200 shadow-xs flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-[11px] font-bold text-emerald-700">تایید و اعمالشده</p>
|
||||
<p className="text-[11px] font-bold text-emerald-700">مجوزهای تاییدشده</p>
|
||||
<p className="text-2xl font-black text-emerald-700 mt-1 font-mono">{approvedCount}</p>
|
||||
</div>
|
||||
<div className="w-10 h-10 rounded-xl bg-emerald-50 text-emerald-700 flex items-center justify-center font-bold">
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
import React, { useEffect, useState, useRef } from 'react';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import {
|
||||
Building2,
|
||||
BrainCircuit,
|
||||
CheckCircle2,
|
||||
Clock,
|
||||
AlertTriangle,
|
||||
ArrowUpRight,
|
||||
RefreshCw,
|
||||
Sparkles,
|
||||
ShieldCheck,
|
||||
Briefcase,
|
||||
FileText,
|
||||
@@ -15,11 +13,10 @@ import {
|
||||
Search,
|
||||
Headphones,
|
||||
Cpu,
|
||||
ExternalLink,
|
||||
ChevronRight,
|
||||
Layers,
|
||||
Terminal,
|
||||
Activity
|
||||
Layers,
|
||||
Terminal,
|
||||
Activity,
|
||||
XCircle,
|
||||
} from 'lucide-react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import api from '../services/api';
|
||||
@@ -38,7 +35,6 @@ interface DepartmentCard {
|
||||
recentReasoningSnippet: string;
|
||||
}
|
||||
|
||||
|
||||
const BASE_DEPARTMENTS: Omit<DepartmentCard, 'status' | 'pendingApprovals' | 'completedTasks' | 'recentReasoningSnippet' | 'currentFocus'>[] = [
|
||||
{
|
||||
id: 'CONTENT',
|
||||
@@ -91,51 +87,66 @@ const BASE_DEPARTMENTS: Omit<DepartmentCard, 'status' | 'pendingApprovals' | 'co
|
||||
];
|
||||
|
||||
export default function CompanyOrchestrationHQ() {
|
||||
const [activeTab, setActiveTab] = useState<'3D_VIEW' | 'BOARD_VIEW'>('3D_VIEW');
|
||||
const [selectedDept, setSelectedDept] = useState<DepartmentCard | null>(null);
|
||||
const [departments, setDepartments] = useState<DepartmentCard[]>([]);
|
||||
const [totalPendingApprovals, setTotalPendingApprovals] = useState<number>(0);
|
||||
const [totalTasksCount, setTotalTasksCount] = useState<number>(0);
|
||||
const [isLoading, setIsLoading] = useState<boolean>(true);
|
||||
const canvasRef = useRef<HTMLCanvasElement | null>(null);
|
||||
const [hasError, setHasError] = useState<boolean>(false);
|
||||
|
||||
const fetchLiveStatus = async () => {
|
||||
setIsLoading(true);
|
||||
setHasError(false);
|
||||
try {
|
||||
const [statsRes, tasksRes, approvalsRes] = await Promise.all([
|
||||
api.get('/admin/department-tasks/stats').catch(() => ({ data: { data: {} } })),
|
||||
api.get('/admin/department-tasks?limit=50').catch(() => ({ data: { data: [] } })),
|
||||
api.get('/admin/approvals?status=PENDING&limit=10').catch(() => ({ data: { meta: { pendingCount: 0 }, data: [] } }))
|
||||
const [_statsRes, tasksRes, approvalsRes] = await Promise.all([
|
||||
api.get('/admin/department-tasks/stats'),
|
||||
api.get('/admin/department-tasks?limit=100'),
|
||||
api.get('/admin/approvals?limit=100')
|
||||
]);
|
||||
|
||||
const stats = statsRes.data?.data?.byDepartment || {};
|
||||
const tasks = tasksRes.data?.data || [];
|
||||
const pendingCount = approvalsRes.data?.meta?.pendingCount ?? approvalsRes.data?.data?.length ?? 0;
|
||||
setTotalPendingApprovals(pendingCount);
|
||||
const approvals = approvalsRes.data?.data || [];
|
||||
|
||||
// Calculate operational pending approvals (excluding non-authorization items)
|
||||
const pendingApprovalsList = approvals.filter((a: any) =>
|
||||
a.status === 'PENDING' && a.category !== 'B2B_SUPPLIER_STRATEGY'
|
||||
);
|
||||
setTotalPendingApprovals(pendingApprovalsList.length);
|
||||
setTotalTasksCount(tasks.length);
|
||||
|
||||
const mapped: DepartmentCard[] = BASE_DEPARTMENTS.map(base => {
|
||||
const deptTasks = tasks.filter((t: any) => t.department === base.id || (base.id === 'DEVOPS' && t.department === 'DEV'));
|
||||
const deptTasks = tasks.filter((t: any) =>
|
||||
t.department === base.id || (base.id === 'DEVOPS' && t.department === 'DEV')
|
||||
);
|
||||
const inProgress = deptTasks.find((t: any) => t.status === 'IN_PROGRESS');
|
||||
const latestTask = deptTasks[0];
|
||||
const completedCount = deptTasks.filter((t: any) => t.status === 'DONE').length;
|
||||
|
||||
let status: 'ACTIVE' | 'PROCESSING' | 'STANDBY' = 'STANDBY';
|
||||
if (inProgress) status = 'ACTIVE';
|
||||
else if (deptTasks.some((t: any) => t.status === 'TEST' || t.status === 'WAITING_DEPENDENCIES')) status = 'PROCESSING';
|
||||
else if (deptTasks.some((t: any) => t.status === 'TEST' || t.status === 'WAITING_DEPENDENCIES')) {
|
||||
status = 'PROCESSING';
|
||||
}
|
||||
|
||||
let currentFocus = 'در حال پایش و آمادهباش برای دریافت دستورات جدید';
|
||||
let currentFocus = 'آمادهباش / بدون وظیفه فعال در حال حاضر';
|
||||
if (inProgress) currentFocus = inProgress.title;
|
||||
else if (latestTask) currentFocus = latestTask.title;
|
||||
|
||||
let snippet = 'پایش خودکار سیستم؛ وظایف دپارتمان طبق استاندارد در حال ارزیابی است.';
|
||||
let snippet = 'بدون ثبت لاگ اجرایی در وظایف اخیر.';
|
||||
if (latestTask?.executionLogs?.length) {
|
||||
const lastLog = latestTask.executionLogs[latestTask.executionLogs.length - 1];
|
||||
snippet = lastLog?.summary || lastLog?.note || (lastLog?.deliverable?.type ? `تحویل دلیوربل ${lastLog.deliverable.type}` : snippet);
|
||||
snippet = lastLog?.summary || lastLog?.note || (lastLog?.deliverable?.type ? `تحویل خروجی: ${lastLog.deliverable.type}` : snippet);
|
||||
}
|
||||
|
||||
// Real department-specific pending approvals (strictly from live data, no synthetic telemetry)
|
||||
const deptPendingCount = pendingApprovalsList.filter((a: any) =>
|
||||
a.department === base.id || (base.id === 'DEVOPS' && a.department === 'DEV')
|
||||
).length;
|
||||
|
||||
return {
|
||||
...base,
|
||||
status,
|
||||
currentFocus,
|
||||
pendingApprovals: base.id === 'CONTENT' || base.id === 'CLINICAL_RD' ? Math.min(pendingCount, 2) : 0,
|
||||
pendingApprovals: deptPendingCount,
|
||||
completedTasks: completedCount,
|
||||
recentReasoningSnippet: snippet
|
||||
};
|
||||
@@ -143,7 +154,8 @@ export default function CompanyOrchestrationHQ() {
|
||||
|
||||
setDepartments(mapped);
|
||||
} catch (err) {
|
||||
console.error('Error fetching live HQ telemetry:', err);
|
||||
console.error('Error fetching live orchestration telemetry:', err);
|
||||
setHasError(true);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
@@ -151,315 +163,189 @@ export default function CompanyOrchestrationHQ() {
|
||||
|
||||
useEffect(() => {
|
||||
fetchLiveStatus();
|
||||
const interval = setInterval(fetchLiveStatus, 10000);
|
||||
return () => clearInterval(interval);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const canvas = canvasRef.current;
|
||||
if (!canvas) return;
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) return;
|
||||
|
||||
let animationFrameId: number;
|
||||
let angle = 0;
|
||||
|
||||
const render = () => {
|
||||
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
||||
const centerX = canvas.width / 2;
|
||||
const centerY = canvas.height / 2;
|
||||
|
||||
ctx.strokeStyle = 'rgba(139, 92, 246, 0.15)';
|
||||
ctx.lineWidth = 1.5;
|
||||
ctx.beginPath();
|
||||
ctx.arc(centerX, centerY, 130, 0, Math.PI * 2);
|
||||
ctx.stroke();
|
||||
|
||||
ctx.strokeStyle = 'rgba(59, 130, 246, 0.1)';
|
||||
ctx.beginPath();
|
||||
ctx.arc(centerX, centerY, 210, 0, Math.PI * 2);
|
||||
ctx.stroke();
|
||||
|
||||
ctx.fillStyle = '#8b5cf6';
|
||||
ctx.shadowColor = '#8b5cf6';
|
||||
ctx.shadowBlur = 20;
|
||||
ctx.beginPath();
|
||||
ctx.arc(centerX, centerY, 32, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
ctx.shadowBlur = 0;
|
||||
|
||||
const totalNodes = departments.length;
|
||||
departments.forEach((dept, idx) => {
|
||||
const theta = angle + (idx * (Math.PI * 2 / totalNodes));
|
||||
const radius = 170;
|
||||
const nodeX = centerX + Math.cos(theta) * radius;
|
||||
const nodeY = centerY + Math.sin(theta) * radius * 0.55;
|
||||
|
||||
ctx.strokeStyle = 'rgba(139, 92, 246, 0.25)';
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(centerX, centerY);
|
||||
ctx.lineTo(nodeX, nodeY);
|
||||
ctx.stroke();
|
||||
|
||||
ctx.fillStyle = dept.status === 'ACTIVE' ? '#10b981' : '#3b82f6';
|
||||
ctx.shadowColor = ctx.fillStyle;
|
||||
ctx.shadowBlur = 10;
|
||||
ctx.beginPath();
|
||||
ctx.arc(nodeX, nodeY, 14, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
ctx.shadowBlur = 0;
|
||||
});
|
||||
|
||||
angle += 0.006;
|
||||
animationFrameId = requestAnimationFrame(render);
|
||||
};
|
||||
|
||||
render();
|
||||
|
||||
return () => {
|
||||
cancelAnimationFrame(animationFrameId);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="space-y-6 font-vazir" dir="rtl">
|
||||
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4 bg-gradient-to-l from-purple-950/40 via-gray-900 to-gray-950 p-6 rounded-3xl border border-purple-500/20 shadow-2xl backdrop-blur-xl">
|
||||
{/* Honest Executive Header */}
|
||||
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4 bg-white p-6 rounded-3xl border border-gray-200 shadow-sm">
|
||||
<div>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="p-3 bg-purple-600/20 text-purple-400 rounded-2xl border border-purple-500/30">
|
||||
<div className="p-3 bg-purple-100 text-purple-700 rounded-2xl border border-purple-200">
|
||||
<Building2 className="w-8 h-8" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-2xl font-black text-white flex items-center gap-3">
|
||||
اتاق وضعیت و ارکستراسیون هوشمند کنینا (Autonomous Corporate HQ)
|
||||
<span className="text-[10px] px-2.5 py-1 rounded-full font-black bg-emerald-500/20 text-emerald-400 border border-emerald-500/30 animate-pulse">
|
||||
سیستم زنده و فعال
|
||||
</span>
|
||||
<h1 className="text-xl md:text-2xl font-black text-gray-900 flex items-center gap-3">
|
||||
وضعیت و ارکستراسیون دپارتمانها (Department Governance Status)
|
||||
{hasError ? (
|
||||
<span className="text-[10px] px-2.5 py-1 rounded-full font-black bg-rose-100 text-rose-800 border border-rose-300">
|
||||
خطا در همگامسازی وضعیت
|
||||
</span>
|
||||
) : isLoading ? (
|
||||
<span className="text-[10px] px-2.5 py-1 rounded-full font-black bg-blue-100 text-blue-800 border border-blue-300">
|
||||
در حال دریافت دادهها...
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-[10px] px-2.5 py-1 rounded-full font-black bg-emerald-100 text-emerald-800 border border-emerald-300">
|
||||
دادههای زنده سیستم
|
||||
</span>
|
||||
)}
|
||||
</h1>
|
||||
<p className="text-xs text-gray-400 mt-1 font-medium">
|
||||
نمای سه بعدی و پانورامای مدیریت دپارتمانها، تصمیمات استراتژیک، و جریان تفکر ایجنتهای هوش مصنوعی
|
||||
<p className="text-xs text-gray-500 mt-1 font-medium">
|
||||
پایش وظایف، وضعیت و خروجی عملیاتی دپارتمانها و ایجنتها بر اساس دادههای واقعی سرویس
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex bg-gray-900/80 p-1.5 rounded-2xl border border-gray-800">
|
||||
<button
|
||||
onClick={() => setActiveTab('3D_VIEW')}
|
||||
className={
|
||||
activeTab === '3D_VIEW'
|
||||
? 'flex items-center gap-2 px-4 py-2 rounded-xl text-xs font-bold transition-all bg-purple-600 text-white shadow-lg shadow-purple-600/30'
|
||||
: 'flex items-center gap-2 px-4 py-2 rounded-xl text-xs font-bold transition-all text-gray-400 hover:text-white'
|
||||
}
|
||||
>
|
||||
<BrainCircuit className="w-4 h-4" />
|
||||
<span>نمای سهبعدی و بصری</span>
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setActiveTab('BOARD_VIEW')}
|
||||
className={
|
||||
activeTab === 'BOARD_VIEW'
|
||||
? 'flex items-center gap-2 px-4 py-2 rounded-xl text-xs font-bold transition-all bg-purple-600 text-white shadow-lg shadow-purple-600/30'
|
||||
: 'flex items-center gap-2 px-4 py-2 rounded-xl text-xs font-bold transition-all text-gray-400 hover:text-white'
|
||||
}
|
||||
>
|
||||
<Briefcase className="w-4 h-4" />
|
||||
<span>فهرست دپارتمانها</span>
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2.5">
|
||||
<Link
|
||||
to="/manager-actions"
|
||||
className="flex items-center gap-1.5 px-3.5 py-2 bg-indigo-50 hover:bg-indigo-100 text-indigo-700 border border-indigo-200 rounded-xl text-xs font-bold transition-all"
|
||||
>
|
||||
<Briefcase className="w-4 h-4 text-indigo-600" />
|
||||
<span>اقدامات مدیریتی و همکاریها</span>
|
||||
</Link>
|
||||
|
||||
<Link
|
||||
to="/approvals"
|
||||
className="flex items-center gap-2 px-4 py-2.5 bg-gradient-to-r from-amber-500 to-amber-600 hover:from-amber-600 hover:to-amber-700 text-white rounded-2xl text-xs font-black shadow-lg shadow-amber-500/20 transition-all"
|
||||
className="flex items-center gap-1.5 px-3.5 py-2 bg-amber-50 hover:bg-amber-100 text-amber-800 border border-amber-300 rounded-xl text-xs font-bold transition-all"
|
||||
>
|
||||
<ShieldCheck className="w-4 h-4" />
|
||||
<span>میز تاییدات مدیریت ({totalPendingApprovals} مورد)</span>
|
||||
<ShieldCheck className="w-4 h-4 text-amber-600" />
|
||||
<span>مجوزهای عملیاتی ({totalPendingApprovals} مورد)</span>
|
||||
</Link>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={fetchLiveStatus}
|
||||
disabled={isLoading}
|
||||
className="inline-flex items-center gap-1.5 px-3 py-2 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-700 text-xs font-bold transition-all border border-gray-200 cursor-pointer disabled:opacity-50"
|
||||
>
|
||||
<RefreshCw className={`w-3.5 h-3.5 ${isLoading ? 'animate-spin' : ''}`} />
|
||||
<span>تازهسازی</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{activeTab === '3D_VIEW' && (
|
||||
<div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
|
||||
<div className="lg:col-span-7 bg-gray-950 rounded-3xl p-6 border border-gray-800 relative overflow-hidden flex flex-col items-center justify-center min-h-[460px] shadow-2xl">
|
||||
<div className="absolute top-5 right-5 z-10 flex items-center gap-2">
|
||||
<span className="w-2.5 h-2.5 rounded-full bg-emerald-500 animate-ping" />
|
||||
<span className="text-[11px] font-bold text-gray-400">مرکز فرماندهی PMO زنده</span>
|
||||
{/* Honest Error State */}
|
||||
{hasError ? (
|
||||
<div className="bg-white p-8 rounded-3xl border border-rose-200 shadow-sm text-center space-y-3">
|
||||
<XCircle className="w-12 h-12 text-rose-500 mx-auto" />
|
||||
<h3 className="text-base font-black text-gray-900">دادههای وضعیت در دسترس نیست</h3>
|
||||
<p className="text-xs text-gray-500 max-w-md mx-auto">
|
||||
امکان ارتباط با سرویس ارکستراسیون یا دریافت آمار وظایف دپارتمانها وجود ندارد. به منظور حفظ صداقت عملیاتی، هیچ وضعیت شبیهسازیشدهای رندر نمیشود.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={fetchLiveStatus}
|
||||
className="px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-xl text-xs font-bold transition-all"
|
||||
>
|
||||
تلاش مجدد جهت اتصال
|
||||
</button>
|
||||
</div>
|
||||
) : isLoading ? (
|
||||
<div className="py-24 flex flex-col justify-center items-center gap-3">
|
||||
<RefreshCw className="w-8 h-8 text-purple-600 animate-spin" />
|
||||
<span className="text-xs font-bold text-gray-500">در حال واکشی وضعیت واقعی دپارتمانها...</span>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{/* Honest Metrics Summary */}
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
|
||||
<div className="bg-white p-4 rounded-2xl border border-gray-200 shadow-xs">
|
||||
<span className="text-[11px] font-bold text-gray-500">کل دپارتمانهای سازمانی</span>
|
||||
<p className="text-2xl font-black text-gray-900 mt-1 font-mono">{departments.length}</p>
|
||||
</div>
|
||||
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
width={560}
|
||||
height={380}
|
||||
className="max-w-full h-auto cursor-pointer"
|
||||
/>
|
||||
|
||||
<div className="absolute bottom-5 inset-x-5 flex items-center justify-between text-[11px] text-gray-500 bg-gray-900/60 backdrop-blur-md px-4 py-2.5 rounded-2xl border border-gray-800/80">
|
||||
<span className="flex items-center gap-1.5 font-bold text-purple-400">
|
||||
<BrainCircuit className="w-4 h-4" />
|
||||
هسته مرکزی: Hermes PMO Autonomous Loop
|
||||
</span>
|
||||
<span>مدل فعال عملیاتی: Canina-content</span>
|
||||
<div className="bg-white p-4 rounded-2xl border border-gray-200 shadow-xs">
|
||||
<span className="text-[11px] font-bold text-gray-500">کل وظایف ثبتشده</span>
|
||||
<p className="text-2xl font-black text-gray-900 mt-1 font-mono">{totalTasksCount}</p>
|
||||
</div>
|
||||
<div className="bg-white p-4 rounded-2xl border border-amber-200 shadow-xs">
|
||||
<span className="text-[11px] font-bold text-amber-700">مجوزهای عملیاتی معلق</span>
|
||||
<p className="text-2xl font-black text-amber-700 mt-1 font-mono">{totalPendingApprovals}</p>
|
||||
</div>
|
||||
<div className="bg-white p-4 rounded-2xl border border-emerald-200 shadow-xs">
|
||||
<span className="text-[11px] font-bold text-emerald-700">دپارتمانهای در حال کار</span>
|
||||
<p className="text-2xl font-black text-emerald-700 mt-1 font-mono">
|
||||
{departments.filter(d => d.status === 'ACTIVE').length}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="lg:col-span-5 space-y-4">
|
||||
<h3 className="text-sm font-black text-gray-200 flex items-center gap-2">
|
||||
<Layers className="w-4 h-4 text-purple-400" />
|
||||
<span>دپارتمانهای فعال در مدار سازمانی</span>
|
||||
</h3>
|
||||
|
||||
<div className="space-y-3">
|
||||
{departments.slice(0, 4).map((dept) => (
|
||||
<div
|
||||
key={dept.id}
|
||||
onClick={() => setSelectedDept(dept)}
|
||||
className="p-4 bg-gray-900/60 hover:bg-gray-900 border border-gray-800/80 hover:border-purple-500/40 rounded-2xl transition-all cursor-pointer group shadow-sm"
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
{/* Department Cards Grid */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
|
||||
{departments.map((dept) => (
|
||||
<div
|
||||
key={dept.id}
|
||||
className="bg-white border border-gray-200 rounded-3xl p-5 hover:border-purple-300 hover:shadow-md transition-all flex flex-col justify-between shadow-xs"
|
||||
>
|
||||
<div>
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className={`p-2.5 rounded-xl bg-gradient-to-br ${dept.avatarColor} text-white shadow-md`}>
|
||||
<dept.icon className="w-4 h-4" />
|
||||
<div className={`p-3 rounded-2xl bg-gradient-to-br ${dept.avatarColor} text-white shadow-xs`}>
|
||||
<dept.icon className="w-5 h-5" />
|
||||
</div>
|
||||
<div>
|
||||
<h4 className="text-xs font-black text-white group-hover:text-purple-300 transition-colors">
|
||||
{dept.name}
|
||||
</h4>
|
||||
<span className="text-[10px] text-gray-400 font-medium">
|
||||
{dept.agentName}
|
||||
</span>
|
||||
<h3 className="text-sm font-black text-gray-900">{dept.name}</h3>
|
||||
<p className="text-[11px] text-purple-700 font-bold">{dept.agentName}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
{dept.pendingApprovals > 0 && (
|
||||
<span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-amber-500/20 text-amber-300 border border-amber-500/30">
|
||||
{dept.pendingApprovals} تایید معلق
|
||||
</span>
|
||||
)}
|
||||
<ChevronRight className="w-4 h-4 text-gray-600 group-hover:text-white transition-colors" />
|
||||
</div>
|
||||
<span className={`text-[10px] font-black px-2 py-0.5 rounded-full border ${
|
||||
dept.status === 'ACTIVE'
|
||||
? 'bg-emerald-50 text-emerald-800 border-emerald-200'
|
||||
: dept.status === 'PROCESSING'
|
||||
? 'bg-amber-50 text-amber-800 border-amber-200'
|
||||
: 'bg-gray-100 text-gray-600 border-gray-200'
|
||||
}`}>
|
||||
{dept.status === 'ACTIVE' ? 'در حال کار' : dept.status === 'PROCESSING' ? 'در حال تست' : 'آمادهباش'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<p className="text-[11px] text-gray-400 mt-2.5 line-clamp-1 font-medium bg-gray-950/60 p-2 rounded-xl border border-gray-800/50">
|
||||
<span className="text-purple-400 font-bold ml-1">تمرکز جاری:</span>
|
||||
{dept.currentFocus}
|
||||
<p className="text-xs text-gray-600 mt-3 font-medium leading-relaxed">
|
||||
{dept.role}
|
||||
</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{activeTab === 'BOARD_VIEW' && (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
|
||||
{departments.map((dept) => (
|
||||
<div
|
||||
key={dept.id}
|
||||
className="bg-gray-900/60 border border-gray-800/90 rounded-3xl p-5 hover:border-purple-500/40 transition-all flex flex-col justify-between shadow-xl"
|
||||
>
|
||||
<div>
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className={`p-3 rounded-2xl bg-gradient-to-br ${dept.avatarColor} text-white shadow-md`}>
|
||||
<dept.icon className="w-5 h-5" />
|
||||
<div className="mt-4 p-3 rounded-2xl bg-gray-50 border border-gray-100 space-y-1">
|
||||
<div className="text-[10px] font-bold text-gray-500 flex items-center gap-1.5">
|
||||
<Activity className="w-3.5 h-3.5 text-purple-600" />
|
||||
<span>تمرکز فعلی دپارتمان:</span>
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-sm font-black text-white">{dept.name}</h3>
|
||||
<p className="text-[11px] text-purple-400 font-bold">{dept.agentName}</p>
|
||||
<p className="text-xs text-gray-800 font-medium line-clamp-1">
|
||||
{dept.currentFocus}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="mt-2 p-3 rounded-2xl bg-gray-50 border border-gray-100 space-y-1">
|
||||
<div className="text-[10px] font-bold text-gray-500 flex items-center gap-1.5">
|
||||
<Terminal className="w-3.5 h-3.5 text-purple-600" />
|
||||
<span>آخرین لاگ و استدلال واقعی:</span>
|
||||
</div>
|
||||
<p className="text-[11px] text-gray-700 font-mono leading-relaxed line-clamp-2">
|
||||
{dept.recentReasoningSnippet}
|
||||
</p>
|
||||
</div>
|
||||
<span className={`text-[10px] font-black px-2 py-0.5 rounded-full border ${
|
||||
dept.status === 'ACTIVE'
|
||||
? 'bg-emerald-500/20 text-emerald-400 border-emerald-500/30'
|
||||
: 'bg-blue-500/20 text-blue-400 border-blue-500/30'
|
||||
}`}>
|
||||
{dept.status === 'ACTIVE' ? 'در حال کار' : 'آمادهباش'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-gray-400 mt-3 font-medium leading-relaxed">
|
||||
{dept.role}
|
||||
</p>
|
||||
|
||||
<div className="mt-4 p-3 rounded-2xl bg-gray-950/80 border border-gray-800/80 space-y-1.5">
|
||||
<div className="text-[10px] font-bold text-gray-500 flex items-center gap-1.5">
|
||||
<Terminal className="w-3.5 h-3.5 text-purple-400" />
|
||||
<span>آخرین استدلال و تفکر مدل:</span>
|
||||
<div className="mt-5 pt-4 border-t border-gray-100 flex items-center justify-between text-xs">
|
||||
<div className="space-x-2 space-x-reverse text-gray-600">
|
||||
<span>وظایف انجامشده: <strong className="text-gray-900 font-bold">{dept.completedTasks}</strong></span>
|
||||
{dept.pendingApprovals > 0 && (
|
||||
<span className="text-amber-700 font-bold">({dept.pendingApprovals} مجوز معلق)</span>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-[11px] text-gray-300 font-mono leading-relaxed line-clamp-2">
|
||||
{dept.recentReasoningSnippet}
|
||||
</p>
|
||||
|
||||
<Link
|
||||
to="/tasks"
|
||||
className="flex items-center gap-1 text-purple-700 hover:text-purple-800 font-bold text-xs"
|
||||
>
|
||||
<span>مشاهده وظایف</span>
|
||||
<ArrowUpRight className="w-3.5 h-3.5" />
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-5 pt-4 border-t border-gray-800/80 flex items-center justify-between text-xs">
|
||||
<span className="text-gray-400 font-medium">
|
||||
تسکهای تکمیلشده: <strong className="text-white font-bold">{dept.completedTasks}</strong>
|
||||
</span>
|
||||
|
||||
<Link
|
||||
to="/tasks"
|
||||
className="flex items-center gap-1 text-purple-400 hover:text-purple-300 font-bold text-[11px]"
|
||||
>
|
||||
<span>مشاهده صف کارتابل</span>
|
||||
<ArrowUpRight className="w-3.5 h-3.5" />
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{selectedDept && (
|
||||
<div className="fixed inset-0 z-50 bg-black/80 backdrop-blur-md flex items-center justify-center p-4">
|
||||
<div className="bg-gray-900 border border-purple-500/30 rounded-3xl max-w-2xl w-full p-6 shadow-2xl space-y-4">
|
||||
<div className="flex items-center justify-between border-b border-gray-800 pb-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className={`p-3 rounded-2xl bg-gradient-to-br ${selectedDept.avatarColor} text-white`}>
|
||||
<selectedDept.icon className="w-6 h-6" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-base font-black text-white">{selectedDept.name}</h3>
|
||||
<p className="text-xs text-purple-400 font-bold">{selectedDept.agentName}</p>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setSelectedDept(null)}
|
||||
className="text-gray-400 hover:text-white text-xs font-bold px-3 py-1.5 rounded-xl bg-gray-800"
|
||||
>
|
||||
بستن
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div>
|
||||
<h4 className="text-xs font-bold text-gray-400">ماموریت اصلی دپارتمان:</h4>
|
||||
<p className="text-xs text-gray-200 mt-1 font-medium">{selectedDept.role}</p>
|
||||
</div>
|
||||
|
||||
<div className="p-4 bg-gray-950 rounded-2xl border border-gray-800 space-y-2">
|
||||
<h4 className="text-xs font-bold text-purple-400 flex items-center gap-2">
|
||||
<Terminal className="w-4 h-4" />
|
||||
<span>لاگ استدلال و آخرین فعالیت زنده:</span>
|
||||
</h4>
|
||||
<p className="text-xs text-gray-300 font-mono leading-relaxed">
|
||||
{selectedDept.recentReasoningSnippet}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-end gap-3 pt-4 border-t border-gray-800">
|
||||
<Link
|
||||
to="/tasks"
|
||||
className="px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-xl text-xs font-bold transition-all shadow-md"
|
||||
>
|
||||
رفتن به کارتابل وظایف این واحد
|
||||
</Link>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import CompanyOrchestrationHQ from './CompanyOrchestrationHQ';
|
||||
|
||||
vi.mock('../services/api', () => ({ default: { get: vi.fn() } }));
|
||||
|
||||
describe('governance source integrity', () => {
|
||||
beforeEach(() => { vi.clearAllMocks(); });
|
||||
it('shows unavailable instead of a synthetic active department when APIs fail', async () => {
|
||||
vi.mocked(api.get).mockRejectedValue(new Error('offline'));
|
||||
render(<MemoryRouter><CompanyOrchestrationHQ /></MemoryRouter>);
|
||||
expect(await screen.findByText(/دادههای وضعیت در دسترس نیست/)).toBeInTheDocument();
|
||||
expect(screen.queryByText(/سیستم زنده و فعال/)).not.toBeInTheDocument();
|
||||
expect(screen.queryByText(/نمای سهبعدی و بصری/)).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,150 @@
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import ManagerActionsPage from './ManagerActionsPage';
|
||||
|
||||
vi.mock('../services/api', () => ({
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
put: vi.fn(),
|
||||
post: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('react-hot-toast', () => ({
|
||||
default: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
const mockItems = [
|
||||
{
|
||||
id: 'act-supplier-1',
|
||||
category: 'B2B_SUPPLIER_STRATEGY',
|
||||
department: 'B2B',
|
||||
title: 'توسعه استراتژی تامینکننده صدف لبسبز آلمان',
|
||||
status: 'IN_PROGRESS',
|
||||
createdAt: '2026-10-19T08:00:00Z',
|
||||
payload: {
|
||||
'1_مسئله_و_شکاف_بازار': 'کمبود ماده موثره پودر صدف در خطوط تولید داخلی',
|
||||
'2_راهحل_و_مزیت_کنینا': 'عقد تفاهمنامه مستقیم با تامینکننده لوکزامبورگ/آلمان',
|
||||
'3_طرح_اقدام_عملیاتی': 'مذاکره بازرگانی جهت دریافت نمونه آزمایشگاهی و بچ آزمایشی',
|
||||
'4_دپارتمانهای_مسئول': 'B2B, CLINICAL_RD',
|
||||
},
|
||||
// No outcome or evidence yet
|
||||
outcome: null,
|
||||
evidence: null,
|
||||
},
|
||||
{
|
||||
id: 'act-supplier-2',
|
||||
category: 'B2B_SUPPLIER_STRATEGY',
|
||||
department: 'B2B',
|
||||
title: 'قرارداد عاملیت توزیع کلینیکی بیمارستان دامپزشکی مرکزی',
|
||||
status: 'COMPLETED',
|
||||
createdAt: '2026-10-18T10:00:00Z',
|
||||
payload: {
|
||||
partner_name: 'بیمارستان دامپزشکی مرکزی',
|
||||
scope: 'توزیع انحصاری مکملهای مفاصل و آرامبخش',
|
||||
},
|
||||
outcome: 'انعقاد قرارداد رسمی عاملیت توزیع سالانه با سهمیه ماهانه ۵۰ بسته',
|
||||
evidence: 'قرارداد امضاشده شماره B2B-1405-091 در بایگانی حقوقی',
|
||||
},
|
||||
{
|
||||
id: 'auth-seo-1',
|
||||
category: 'SEO',
|
||||
department: 'SEO',
|
||||
title: 'تغییر عنوان متاتگ و ریدایرکتهای مقالات مفاصل',
|
||||
status: 'PENDING',
|
||||
createdAt: '2026-10-19T09:00:00Z',
|
||||
payload: {
|
||||
target_url: '/blog/joint-supplements-guide',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
describe('ManagerActionsPage Component', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(api.get).mockResolvedValue({
|
||||
data: {
|
||||
success: true,
|
||||
data: mockItems,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('renders B2B_SUPPLIER_STRATEGY items and excludes operational SEO authorizations', async () => {
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<ManagerActionsPage />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
expect(await screen.findByText('توسعه استراتژی تامینکننده صدف لبسبز آلمان')).toBeInTheDocument();
|
||||
expect(screen.getByText('قرارداد عاملیت توزیع کلینیکی بیمارستان دامپزشکی مرکزی')).toBeInTheDocument();
|
||||
|
||||
// SEO item belongs strictly in operational authorization queue, not here!
|
||||
expect(screen.queryByText('تغییر عنوان متاتگ و ریدایرکتهای مقالات مفاصل')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('never displays an approval button; requires explicit outcome and evidence for completion', async () => {
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<ManagerActionsPage />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
await screen.findByText('توسعه استراتژی تامینکننده صدف لبسبز آلمان');
|
||||
|
||||
// Rule: Manager actions are NOT operational authorizations. No "approval" button allowed!
|
||||
expect(screen.queryByRole('button', { name: /تایید و صدور مجوز اجرا/i })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: /تایید درخواست/i })).not.toBeInTheDocument();
|
||||
|
||||
// Incomplete manager action shows explicit requirement indicator
|
||||
expect(screen.getByText(/نیازمند ثبت نتیجه و مدرک جهت احراز تکمیل/i)).toBeInTheDocument();
|
||||
|
||||
// Completed action displays its explicit outcome and evidence
|
||||
expect(screen.getByText(/انعقاد قرارداد رسمی عاملیت توزیع سالانه با سهمیه ماهانه ۵۰ بسته/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/قرارداد امضاشده شماره B2B-1405-091 در بایگانی حقوقی/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/تکمیلشده و احراز شده با مستندات/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('allows recording explicit outcome and evidence for an action', async () => {
|
||||
vi.mocked(api.put).mockResolvedValue({
|
||||
data: { success: true },
|
||||
});
|
||||
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<ManagerActionsPage />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
expect(await screen.findByText('توسعه استراتژی تامینکننده صدف لبسبز آلمان')).toBeInTheDocument();
|
||||
|
||||
const outcomeInput = screen.getByPlaceholderText(/نتیجه حاصله از این اقدام مدیریتی.../i);
|
||||
const evidenceInput = screen.getByPlaceholderText(/مستندات، شماره سند، لینک گزارش یا فایل.../i);
|
||||
|
||||
fireEvent.change(outcomeInput, { target: { value: 'نمونه اولیه آزمایشگاهی با خلوص ۹۸٪ تایید شد' } });
|
||||
fireEvent.change(evidenceInput, { target: { value: 'گواهی آنالیز آزمایشگاه رازی کد QA-9921' } });
|
||||
|
||||
const submitBtn = screen.getByRole('button', { name: /ثبت نتیجه و مستندات اقدام/i });
|
||||
fireEvent.click(submitBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.put).toHaveBeenCalledWith(
|
||||
'/admin/approvals/act-supplier-1/decide',
|
||||
expect.objectContaining({
|
||||
outcome: 'نمونه اولیه آزمایشگاهی با خلوص ۹۸٪ تایید شد',
|
||||
evidence: 'گواهی آنالیز آزمایشگاه رازی کد QA-9921',
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,477 @@
|
||||
import React, { useState, useEffect, useMemo } from 'react';
|
||||
import {
|
||||
Building2,
|
||||
Briefcase,
|
||||
CheckCircle2,
|
||||
AlertTriangle,
|
||||
Clock,
|
||||
RefreshCw,
|
||||
Search,
|
||||
FileText,
|
||||
ShieldCheck,
|
||||
Send,
|
||||
AlertCircle,
|
||||
Layers,
|
||||
} from 'lucide-react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import toast from 'react-hot-toast';
|
||||
import api from '../services/api';
|
||||
|
||||
interface ManagerActionItem {
|
||||
id: string;
|
||||
department: string;
|
||||
category: string;
|
||||
title: string;
|
||||
payload: any;
|
||||
status: string;
|
||||
ceoNotes?: string;
|
||||
outcome?: string | null;
|
||||
evidence?: string | null;
|
||||
createdAt: string;
|
||||
executedAt?: string;
|
||||
}
|
||||
|
||||
export default function ManagerActionsPage() {
|
||||
const [items, setItems] = useState<ManagerActionItem[]>([]);
|
||||
const [loading, setLoading] = useState<boolean>(true);
|
||||
const [error, setError] = useState<boolean>(false);
|
||||
const [searchQuery, setSearchQuery] = useState<string>('');
|
||||
const [statusFilter, setStatusFilter] = useState<'ALL' | 'VERIFIED' | 'PENDING_EVIDENCE'>('ALL');
|
||||
|
||||
// Input states for outcome and evidence editing
|
||||
const [actionForm, setActionForm] = useState<Record<string, { outcome: string; evidence: string }>>({});
|
||||
const [submittingId, setSubmittingId] = useState<string | null>(null);
|
||||
|
||||
const fetchActions = async () => {
|
||||
setLoading(true);
|
||||
setError(false);
|
||||
try {
|
||||
const res = await api.get('/admin/approvals?limit=100');
|
||||
if (res.data?.success && Array.isArray(res.data.data)) {
|
||||
// Manager actions are strategic categories like B2B_SUPPLIER_STRATEGY or PARTNERSHIP
|
||||
// Operational authorizations (SEO, PRICING, SMS, etc.) are strictly excluded!
|
||||
const managerActions = res.data.data.filter((item: any) =>
|
||||
item.category === 'B2B_SUPPLIER_STRATEGY' ||
|
||||
item.category === 'PARTNERSHIP' ||
|
||||
(item.department === 'B2B' && item.category?.includes('STRATEGY'))
|
||||
);
|
||||
|
||||
const initialForms: Record<string, { outcome: string; evidence: string }> = {};
|
||||
managerActions.forEach((item: ManagerActionItem) => {
|
||||
initialForms[item.id] = {
|
||||
outcome: item.outcome || item.payload?.outcome || item.payload?.['نتیجه_اقدام'] || '',
|
||||
evidence: item.evidence || item.payload?.evidence || item.payload?.['مستندات_و_مدرک'] || '',
|
||||
};
|
||||
});
|
||||
|
||||
setItems(managerActions);
|
||||
setActionForm(initialForms);
|
||||
} else {
|
||||
setError(true);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch manager actions:', err);
|
||||
setError(true);
|
||||
toast.error('خطا در دریافت لیست اقدامات مدیریتی');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchActions();
|
||||
}, []);
|
||||
|
||||
const handleSaveEvidence = async (id: string) => {
|
||||
const form = actionForm[id] || { outcome: '', evidence: '' };
|
||||
if (!form.outcome.trim() || !form.evidence.trim()) {
|
||||
toast.error('برای ثبت اقدام، درج هر دو مورد نتیجه و مدرک/مستندات الزامی است.');
|
||||
return;
|
||||
}
|
||||
|
||||
setSubmittingId(id);
|
||||
try {
|
||||
const res = await api.put(`/admin/approvals/${id}/decide`, {
|
||||
decision: 'APPROVED',
|
||||
outcome: form.outcome.trim(),
|
||||
evidence: form.evidence.trim(),
|
||||
ceoNotes: `اقدام تکمیل شد با نتیجه: ${form.outcome.trim()}`,
|
||||
});
|
||||
|
||||
if (res.data?.success) {
|
||||
toast.success('نتیجه و مستندات اقدام مدیریتی با موفقیت ثبت شد');
|
||||
// Update local item with verified outcome and evidence
|
||||
setItems((prev) =>
|
||||
prev.map((item) =>
|
||||
item.id === id
|
||||
? {
|
||||
...item,
|
||||
status: 'COMPLETED',
|
||||
outcome: form.outcome.trim(),
|
||||
evidence: form.evidence.trim(),
|
||||
}
|
||||
: item
|
||||
)
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to update manager action evidence:', err);
|
||||
toast.error('خطا در ثبت نتیجه و مستندات اقدام');
|
||||
} finally {
|
||||
setSubmittingId(null);
|
||||
}
|
||||
};
|
||||
|
||||
const filteredItems = useMemo(() => {
|
||||
return items.filter((item) => {
|
||||
const isVerified = Boolean(item.outcome?.trim()) && Boolean(item.evidence?.trim());
|
||||
|
||||
if (statusFilter === 'VERIFIED' && !isVerified) return false;
|
||||
if (statusFilter === 'PENDING_EVIDENCE' && isVerified) return false;
|
||||
|
||||
if (searchQuery.trim()) {
|
||||
const q = searchQuery.toLowerCase().trim();
|
||||
const form = actionForm[item.id] || { outcome: '', evidence: '' };
|
||||
const matchTitle = item.title?.toLowerCase().includes(q);
|
||||
const matchDept = item.department?.toLowerCase().includes(q);
|
||||
const matchPayload = JSON.stringify(item.payload || {}).toLowerCase().includes(q);
|
||||
const matchOutcome = (item.outcome || form.outcome)?.toLowerCase().includes(q);
|
||||
if (!matchTitle && !matchDept && !matchPayload && !matchOutcome) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
}, [items, actionForm, statusFilter, searchQuery]);
|
||||
|
||||
const verifiedCount = items.filter(
|
||||
(item) => Boolean(item.outcome?.trim()) && Boolean(item.evidence?.trim())
|
||||
).length;
|
||||
const pendingEvidenceCount = items.length - verifiedCount;
|
||||
|
||||
return (
|
||||
<div className="space-y-6 max-w-7xl mx-auto p-4 md:p-6 font-vazir text-gray-900 bg-gray-50 min-h-screen" dir="rtl">
|
||||
{/* Header */}
|
||||
<div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 bg-white p-6 rounded-3xl border border-gray-200/80 shadow-xs">
|
||||
<div>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-10 h-10 rounded-2xl bg-indigo-100 flex items-center justify-center text-indigo-700 shadow-xs">
|
||||
<Briefcase className="w-6 h-6" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-xl md:text-2xl font-black text-gray-900 tracking-tight">
|
||||
اقدامات مدیریتی و همکاریها (Manager Strategic Actions & Partnerships)
|
||||
</h1>
|
||||
<p className="text-xs text-gray-500 font-medium mt-1 leading-relaxed">
|
||||
طرحهای راهبردی، پروژههای B2B و تامینکنندگان. این موارد مجوز سیستمی نیستند؛ تکمیل اقدام صرفاً با احراز نتیجه و مستندات معتبر صورت میگیرد.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2.5">
|
||||
<Link
|
||||
to="/approvals"
|
||||
className="inline-flex items-center gap-1.5 px-3.5 py-2 rounded-2xl bg-amber-50 hover:bg-amber-100 text-amber-800 text-xs font-bold transition-all border border-amber-300"
|
||||
>
|
||||
<ShieldCheck className="w-4 h-4 text-amber-600" />
|
||||
<span>رفتن به مجوزهای عملیاتی</span>
|
||||
</Link>
|
||||
|
||||
<Link
|
||||
to="/tasks"
|
||||
className="inline-flex items-center gap-1.5 px-3.5 py-2 rounded-2xl bg-purple-50 hover:bg-purple-100 text-purple-700 text-xs font-bold transition-all border border-purple-200"
|
||||
>
|
||||
<Layers className="w-4 h-4 text-purple-600" />
|
||||
<span>مشاهده وظایف دپارتمانها</span>
|
||||
</Link>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={fetchActions}
|
||||
disabled={loading}
|
||||
className="inline-flex items-center gap-1.5 px-3.5 py-2 rounded-2xl bg-gray-100 hover:bg-gray-200 text-gray-700 text-xs font-bold transition-all border border-gray-200 cursor-pointer disabled:opacity-50"
|
||||
>
|
||||
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
|
||||
<span className="hidden sm:inline">تازهسازی</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Governance Directive Banner */}
|
||||
<div className="bg-indigo-50/80 border border-indigo-200 p-4 rounded-2xl flex items-start gap-3">
|
||||
<AlertCircle className="w-5 h-5 text-indigo-700 shrink-0 mt-0.5" />
|
||||
<div className="text-xs text-indigo-950 space-y-1">
|
||||
<p className="font-bold">قانون تفکیک حاکمیتی اقدامات مدیریتی از مجوزهای عملیاتی:</p>
|
||||
<p className="leading-relaxed text-indigo-900">
|
||||
طرحهای استراتژیک تامینکنندگان (B2B_SUPPLIER_STRATEGY) و همکاریهای تجاری، وظایف انسانی و راهبردی هستند که دکمه تایید فوری ندارند. تکمیل این موارد صرفاً با درج صریح نتیجه واقعی (Outcome) و مستندات قابل اعتبارسنجی (Evidence) محقق میشود.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* KPI Cards */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3.5">
|
||||
<div className="bg-white p-4 rounded-2xl border border-gray-200/80 shadow-xs flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-[11px] font-bold text-gray-500">کل اقدامات مدیریتی</p>
|
||||
<p className="text-2xl font-black text-gray-900 mt-1 font-mono">{items.length}</p>
|
||||
</div>
|
||||
<div className="w-10 h-10 rounded-xl bg-indigo-50 text-indigo-700 flex items-center justify-center font-bold">
|
||||
<Building2 className="w-5 h-5" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white p-4 rounded-2xl border border-amber-300 shadow-xs flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-[11px] font-bold text-amber-700">نیازمند ثبت نتیجه و مدرک</p>
|
||||
<p className="text-2xl font-black text-amber-700 mt-1 font-mono">{pendingEvidenceCount}</p>
|
||||
</div>
|
||||
<div className="w-10 h-10 rounded-xl bg-amber-50 text-amber-700 flex items-center justify-center font-bold">
|
||||
<Clock className="w-5 h-5" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white p-4 rounded-2xl border border-emerald-200 shadow-xs flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-[11px] font-bold text-emerald-700">تکمیل و احراز شده با مستندات</p>
|
||||
<p className="text-2xl font-black text-emerald-700 mt-1 font-mono">{verifiedCount}</p>
|
||||
</div>
|
||||
<div className="w-10 h-10 rounded-xl bg-emerald-50 text-emerald-700 flex items-center justify-center font-bold">
|
||||
<CheckCircle2 className="w-5 h-5" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Filters Bar */}
|
||||
<div className="bg-white p-4 rounded-3xl border border-gray-200/80 shadow-xs flex flex-col md:flex-row gap-3 items-center justify-between">
|
||||
<div className="relative w-full md:w-96">
|
||||
<Search className="w-4 h-4 text-gray-400 absolute right-3.5 top-1/2 -translate-y-1/2" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="جستجو در عنوان اقدام، تامینکننده، دپارتمان..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="w-full pr-10 pl-4 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-indigo-500 font-medium text-gray-900"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2 w-full md:w-auto">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setStatusFilter('ALL')}
|
||||
className={`px-3 py-1.5 rounded-xl text-xs font-bold transition-all ${
|
||||
statusFilter === 'ALL'
|
||||
? 'bg-indigo-600 text-white shadow-xs'
|
||||
: 'bg-gray-100 text-gray-600 hover:bg-gray-200'
|
||||
}`}
|
||||
>
|
||||
همه موارد ({items.length})
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setStatusFilter('PENDING_EVIDENCE')}
|
||||
className={`px-3 py-1.5 rounded-xl text-xs font-bold transition-all ${
|
||||
statusFilter === 'PENDING_EVIDENCE'
|
||||
? 'bg-amber-600 text-white shadow-xs'
|
||||
: 'bg-gray-100 text-gray-600 hover:bg-gray-200'
|
||||
}`}
|
||||
>
|
||||
نیازمند نتیجه ({pendingEvidenceCount})
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setStatusFilter('VERIFIED')}
|
||||
className={`px-3 py-1.5 rounded-xl text-xs font-bold transition-all ${
|
||||
statusFilter === 'VERIFIED'
|
||||
? 'bg-emerald-600 text-white shadow-xs'
|
||||
: 'bg-gray-100 text-gray-600 hover:bg-gray-200'
|
||||
}`}
|
||||
>
|
||||
احراز شده ({verifiedCount})
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Main List */}
|
||||
{error ? (
|
||||
<div className="bg-white p-8 rounded-3xl border border-rose-200 text-center space-y-3">
|
||||
<AlertTriangle className="w-12 h-12 text-rose-500 mx-auto" />
|
||||
<h3 className="text-base font-black text-gray-900">دریافت اقدامات ناموفق بود</h3>
|
||||
<p className="text-xs text-gray-500">امکان برقراری ارتباط با سرور و واکشی اقدامات مدیریتی وجود ندارد.</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={fetchActions}
|
||||
className="px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl text-xs font-bold transition-all"
|
||||
>
|
||||
تلاش مجدد
|
||||
</button>
|
||||
</div>
|
||||
) : loading ? (
|
||||
<div className="py-24 flex flex-col justify-center items-center gap-3">
|
||||
<RefreshCw className="w-8 h-8 text-indigo-600 animate-spin" />
|
||||
<span className="text-xs font-bold text-gray-500">در حال دریافت اقدامات مدیریتی...</span>
|
||||
</div>
|
||||
) : filteredItems.length === 0 ? (
|
||||
<div className="bg-white p-12 text-center rounded-3xl border border-gray-200/80 shadow-xs space-y-2">
|
||||
<CheckCircle2 className="w-12 h-12 text-indigo-500 mx-auto mb-2" />
|
||||
<h3 className="text-base font-black text-gray-900">اقدامی در این فهرست یافت نشد</h3>
|
||||
<p className="text-xs text-gray-500">موردی با شرایط فیلتر انتخابشده مطابقت ندارد.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-5">
|
||||
{filteredItems.map((item) => {
|
||||
const form = actionForm[item.id] || { outcome: item.outcome || '', evidence: item.evidence || '' };
|
||||
const isCompleted = Boolean(item.outcome?.trim()) && Boolean(item.evidence?.trim());
|
||||
|
||||
return (
|
||||
<div
|
||||
key={item.id}
|
||||
className={`bg-white rounded-3xl border transition-all overflow-hidden ${
|
||||
isCompleted ? 'border-emerald-200 shadow-xs' : 'border-amber-300 shadow-md ring-1 ring-amber-300/40'
|
||||
}`}
|
||||
>
|
||||
{/* Header */}
|
||||
<div className="p-5 border-b border-gray-100 flex flex-col md:flex-row justify-between items-start md:items-center gap-3 bg-gray-50/60">
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-xl text-[11px] font-black border bg-indigo-50 text-indigo-800 border-indigo-200">
|
||||
<Building2 className="w-3.5 h-3.5 shrink-0" />
|
||||
<span>{item.category === 'B2B_SUPPLIER_STRATEGY' ? 'طرح استراتژیک تامینکننده' : item.category}</span>
|
||||
</span>
|
||||
<div>
|
||||
<h3 className="font-black text-gray-900 text-sm md:text-base leading-snug">
|
||||
{item.title}
|
||||
</h3>
|
||||
<div className="flex items-center gap-2 mt-1 text-[11px] text-gray-500 font-medium">
|
||||
<span>دپارتمان: <strong className="text-gray-800">{item.department}</strong></span>
|
||||
<span>•</span>
|
||||
<span>
|
||||
ثبت: {new Intl.DateTimeFormat('fa-IR', { year: 'numeric', month: '2-digit', day: '2-digit' }).format(new Date(item.createdAt))}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
{isCompleted ? (
|
||||
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-black bg-emerald-50 text-emerald-800 border border-emerald-200">
|
||||
<CheckCircle2 className="w-3.5 h-3.5 text-emerald-600" />
|
||||
<span>تکمیلشده و احراز شده با مستندات</span>
|
||||
</span>
|
||||
) : (
|
||||
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-black bg-amber-50 text-amber-800 border border-amber-300">
|
||||
<Clock className="w-3.5 h-3.5 text-amber-600" />
|
||||
<span>نیازمند ثبت نتیجه و مدرک جهت احراز تکمیل</span>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Body */}
|
||||
<div className="p-5 space-y-4">
|
||||
{/* Strategic 5-Part Proposal Mapping */}
|
||||
{item.payload && (
|
||||
<div className="space-y-2.5">
|
||||
{item.payload['1_مسئله_و_شکاف_بازار'] && (
|
||||
<div className="p-3 bg-rose-50/60 border border-rose-200/80 rounded-xl text-xs">
|
||||
<span className="font-black text-rose-800 block mb-1">مسئله و شکاف بازار:</span>
|
||||
<span className="text-gray-800">{item.payload['1_مسئله_و_شکاف_بازار']}</span>
|
||||
</div>
|
||||
)}
|
||||
{item.payload['2_راهحل_و_مزیت_کنینا'] && (
|
||||
<div className="p-3 bg-emerald-50/60 border border-emerald-200/80 rounded-xl text-xs">
|
||||
<span className="font-black text-emerald-800 block mb-1">راهحل و مزیت کنینا:</span>
|
||||
<span className="text-gray-800">{item.payload['2_راهحل_و_مزیت_کنینا']}</span>
|
||||
</div>
|
||||
)}
|
||||
{item.payload['3_طرح_اقدام_عملیاتی'] && (
|
||||
<div className="p-3 bg-blue-50/60 border border-blue-200/80 rounded-xl text-xs">
|
||||
<span className="font-black text-blue-800 block mb-1">طرح اقدام عملیاتی:</span>
|
||||
<span className="text-gray-800">{item.payload['3_طرح_اقدام_عملیاتی']}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Explicit Outcome & Evidence Section */}
|
||||
<div className="bg-gray-50/90 rounded-2xl p-4 border border-gray-200 space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-xs font-black text-gray-800 flex items-center gap-1.5">
|
||||
<FileText className="w-4 h-4 text-indigo-600" />
|
||||
<span>نتیجه و مدرک تحقق اقدام (Outcome & Evidence)</span>
|
||||
</span>
|
||||
<span className="text-[11px] text-gray-500 font-medium">
|
||||
تکمیل صرفاً با مستندات معتبر احراز میشود
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{isCompleted ? (
|
||||
<div className="space-y-2 text-xs">
|
||||
<div className="p-3 bg-white rounded-xl border border-emerald-200 space-y-1">
|
||||
<span className="text-emerald-800 font-bold block">نتیجه حاصله (Outcome):</span>
|
||||
<p className="text-gray-800 font-medium">{item.outcome}</p>
|
||||
</div>
|
||||
<div className="p-3 bg-white rounded-xl border border-emerald-200 space-y-1">
|
||||
<span className="text-emerald-800 font-bold block">مستندات و مدرک تحقق (Evidence):</span>
|
||||
<p className="text-gray-800 font-medium">{item.evidence}</p>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
<div className="space-y-1">
|
||||
<label className="text-[11px] font-bold text-gray-700 block">
|
||||
نتیجه حاصله از این اقدام مدیریتی (Outcome):
|
||||
</label>
|
||||
<textarea
|
||||
rows={2}
|
||||
placeholder="نتیجه حاصله از این اقدام مدیریتی..."
|
||||
value={form.outcome}
|
||||
onChange={(e) =>
|
||||
setActionForm((prev) => ({
|
||||
...prev,
|
||||
[item.id]: { ...form, outcome: e.target.value },
|
||||
}))
|
||||
}
|
||||
className="w-full p-2.5 text-xs bg-white border border-gray-200 rounded-xl focus:outline-none focus:border-indigo-500 font-medium"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<label className="text-[11px] font-bold text-gray-700 block">
|
||||
مستندات و مدرک تحقق (Evidence):
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="مستندات، شماره سند، لینک گزارش یا فایل..."
|
||||
value={form.evidence}
|
||||
onChange={(e) =>
|
||||
setActionForm((prev) => ({
|
||||
...prev,
|
||||
[item.id]: { ...form, evidence: e.target.value },
|
||||
}))
|
||||
}
|
||||
className="w-full p-2.5 text-xs bg-white border border-gray-200 rounded-xl focus:outline-none focus:border-indigo-500 font-medium"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end pt-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleSaveEvidence(item.id)}
|
||||
disabled={submittingId === item.id || !form.outcome.trim() || !form.evidence.trim()}
|
||||
className="inline-flex items-center gap-1.5 px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl text-xs font-black shadow-xs transition-all disabled:opacity-50 cursor-pointer"
|
||||
>
|
||||
<Send className="w-3.5 h-3.5" />
|
||||
<span>{submittingId === item.id ? 'در حال ثبت...' : 'ثبت نتیجه و مستندات اقدام'}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import ApprovalsPage from './ApprovalsPage';
|
||||
|
||||
vi.mock('../services/api', () => ({ default: { get: vi.fn(), post: vi.fn(), put: vi.fn() } }));
|
||||
vi.mock('react-hot-toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));
|
||||
|
||||
const item = (id: string, category: string, status = 'PENDING') => ({
|
||||
id, category, status, department: category === 'SEO' ? 'SEO' : 'B2B',
|
||||
title: id, payload: {}, createdAt: '2026-10-19T10:00:00Z',
|
||||
});
|
||||
|
||||
describe('operational authorization boundary', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(api.get).mockResolvedValue({ data: {
|
||||
success: true,
|
||||
data: [item('supplier-action', 'B2B_SUPPLIER_STRATEGY'), item('seo-approval', 'SEO')],
|
||||
meta: { pendingCount: 2 },
|
||||
} });
|
||||
});
|
||||
|
||||
it('does not expose a supplier manager action as authorization while SEO remains', async () => {
|
||||
render(<ApprovalsPage />);
|
||||
expect(await screen.findByText('seo-approval')).toBeInTheDocument();
|
||||
expect(screen.queryByText('supplier-action')).not.toBeInTheDocument();
|
||||
expect(screen.getAllByRole('button', { name: /تایید و صدور مجوز اجرا/ })).toHaveLength(1);
|
||||
expect(screen.getByText(/1 پیشنهاد منتظر تصمیم شما/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -50,6 +50,7 @@ const DoctorsManager = lazyWithRetry(() => import('../pages/DoctorsManager'));
|
||||
const FAQManager = lazyWithRetry(() => import('../pages/FAQManager'));
|
||||
const MenuManager = lazyWithRetry(() => import('../pages/MenuManager'));
|
||||
const MonitoringPage = lazyWithRetry(() => import('../pages/MonitoringPage'));
|
||||
const ManagerActionsPage = lazyWithRetry(() => import('../pages/ManagerActionsPage'));
|
||||
const ApprovalsPage = lazyWithRetry(() => import('../pages/ApprovalsPage'));
|
||||
const AuditHistoryPage = lazyWithRetry(() => import('../pages/AuditHistoryPage'));
|
||||
const TasksManagementPage = lazyWithRetry(() => import('../pages/TasksManagementPage'));
|
||||
@@ -120,6 +121,7 @@ export const router = createBrowserRouter([
|
||||
{ path: 'menu/*', element: <MenuManager /> },
|
||||
{ path: 'monitoring/*', element: <MonitoringPage /> },
|
||||
{ path: 'approvals/*', element: <ApprovalsPage /> },
|
||||
{ path: 'manager-actions/*', element: <ManagerActionsPage /> },
|
||||
{ path: 'history/*', element: <AuditHistoryPage /> },
|
||||
{ path: 'tasks/*', element: <TasksManagementPage /> },
|
||||
{ path: 'governance/hq/*', element: <CompanyOrchestrationHQ /> },
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
# Market opportunity proposal gate (inactive)
|
||||
|
||||
Hermes cron `482f37952b74` (`canina-market-opportunity-scout`) currently produces reports in `/opt/data/cron/output/482f37952b74/`; its schedule is enabled. Cron `e95025c84a31` (`canina-opportunity-decomposer-daemon`) is **paused**, with `script: market_opportunity_decomposer.py`, resolved to the untracked Hermes script `/opt/data/scripts/market_opportunity_decomposer.py`. Neither cron definition nor that script is part of this repository. The latter directly inserts model-generated `approval_requests`, uses title-only deduplication, and increments its success count even when `ON CONFLICT DO NOTHING` returns no row. Do not re-enable it.
|
||||
|
||||
`market_proposals.py` is a versioned, **unwired** validation/insertion gate. It accepts only paired digital route identifiers, and deliberately ignores model-supplied title, prose, pricing, clinical claims, and payload. Evidence URL and verbatim quote must coexist in a scout report paragraph; this is a syntactic provenance check, **not** independent verification that the URL is genuine or medically correct. The resulting review-only payload links the source and report; no automatic approval, task execution, or publication exists. A transaction-scoped PostgreSQL advisory lock serializes proposals by source URL + exact quote + action fingerprint and the SQL counts only returned UUIDs. The application-level deduplication assumes every writer uses this gate. Consider a schema-level partial unique index on `(payload->>'sourceFingerprint')` after examining existing rows before production rollout; coordinate schema changes with backend ownership.
|
||||
|
||||
Before activation, migrate the Hermes entry point into this repository under `scripts/orchestration/`, add an explicit offline parser for actual scout output format and bounded model schema, and have the scheduler invoke the **versioned** script by pinned revision/absolute path after review. Replace its direct SQL write path with this gate; inspect sample scout outputs and test malformed, mismatched, stale, and false-source citations. Add a dry-run mode and staging integration tests with a disposable database, review permissions and audit logging, and require human clinical/pricing review. Do not infer clinical or price facts from model prose. Keep `e95025c84a31` paused until rollout approval; do not change the active scout job as part of this patch.
|
||||
|
||||
Tests: `cd scripts/orchestration && python3 -m unittest discover -p 'test_*.py' -v` (no DB access).
|
||||
@@ -0,0 +1,77 @@
|
||||
"""Conservative, offline-testable approval proposal gateway for market-scout evidence.
|
||||
|
||||
Not scheduled or activated. Only explicitly allowlisted digital audit work is accepted.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import uuid
|
||||
from urllib.parse import urlsplit, urlunsplit
|
||||
|
||||
|
||||
ROUTES = {
|
||||
"CATALOG_AUDIT": ("CONTENT", "CAMPAIGN", "Audit cited catalog evidence"),
|
||||
"SEO_AUDIT": ("SEO", "SEO", "Audit cited search evidence"),
|
||||
"WEB_FEATURE_REVIEW": ("DEV", "FEATURE", "Review cited website feature gap"),
|
||||
}
|
||||
|
||||
|
||||
def validate_proposal(item: dict, report: str, report_name: str) -> dict:
|
||||
"""Discard untrusted prose and construct a bounded review-only proposal."""
|
||||
if not isinstance(item, dict) or not isinstance(report, str):
|
||||
raise ValueError("Invalid proposal or report")
|
||||
action = item.get("action_type")
|
||||
route = ROUTES.get(action)
|
||||
if route is None or item.get("department") != route[0]:
|
||||
raise ValueError("Only paired digital routes are supported")
|
||||
url = item.get("source_url")
|
||||
quote = item.get("evidence_quote")
|
||||
if not isinstance(url, str) or not isinstance(quote, str):
|
||||
raise ValueError("A source URL and exact evidence quote are required")
|
||||
parsed = urlsplit(url)
|
||||
if parsed.scheme not in ("https", "http") or not parsed.hostname or parsed.username or parsed.password or len(url) > 1000:
|
||||
raise ValueError("Invalid evidence URL")
|
||||
canonical_url = urlunsplit((parsed.scheme.lower(), parsed.netloc.lower(), parsed.path.rstrip("/") or "/", parsed.query, ""))
|
||||
if not quote.strip() or len(quote) > 500 or not any(
|
||||
url in block and quote in block for block in re.split(r"\n\s*\n", report)
|
||||
):
|
||||
raise ValueError("Evidence and URL must occur verbatim in the same scout report block")
|
||||
fingerprint = hashlib.sha256(json.dumps([canonical_url, quote.strip(), action], ensure_ascii=False, separators=(",", ":")).encode()).hexdigest()
|
||||
return {
|
||||
"department": route[0], "category": route[1],
|
||||
"title": f"{route[2]} [{fingerprint[:12]}]",
|
||||
"fingerprint": fingerprint,
|
||||
"payload": {
|
||||
"sourceUrl": canonical_url, "evidenceQuote": quote.strip(),
|
||||
"sourceFingerprint": fingerprint, "sourceReport": str(report_name).split("/")[-1][:255],
|
||||
"actionType": action, "reviewRequired": True,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _literal(value: str) -> str:
|
||||
return "'" + value.replace("'", "''") + "'"
|
||||
|
||||
|
||||
def insert_proposal(db, proposal: dict) -> bool:
|
||||
"""Atomically serialize fingerprint insertion and count only returned IDs."""
|
||||
fp = proposal["fingerprint"]
|
||||
if not re.fullmatch(r"[0-9a-f]{64}", fp):
|
||||
raise ValueError("Invalid fingerprint")
|
||||
payload = json.dumps(proposal["payload"], ensure_ascii=False)
|
||||
sql = f"""BEGIN;
|
||||
SELECT pg_advisory_xact_lock(hashtextextended({_literal('market-proposal:' + fp)}, 0));
|
||||
INSERT INTO approval_requests (id, department, category, title, payload, status, created_at, updated_at)
|
||||
SELECT gen_random_uuid(), {_literal(proposal['department'])}, {_literal(proposal['category'])},
|
||||
{_literal(proposal['title'])}, {_literal(payload)}::jsonb, 'PENDING', NOW(), NOW()
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM approval_requests
|
||||
WHERE payload->>'sourceFingerprint' = {_literal(fp)}
|
||||
)
|
||||
RETURNING id;
|
||||
COMMIT;"""
|
||||
result = db.sql(sql)
|
||||
return any(re.fullmatch(r"[0-9a-fA-F]{8}-(?:[0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}", line.strip())
|
||||
for line in result.splitlines())
|
||||
@@ -12,6 +12,8 @@ import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import uuid
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
@@ -85,11 +87,123 @@ def build_child_tasks(parent_code: str, proposal: dict[str, Any], depth: int) ->
|
||||
def determine_parent_status(*, has_children: bool, deliverable_url: str | None, verified: bool) -> str:
|
||||
if has_children:
|
||||
return "WAITING_DEPENDENCIES"
|
||||
if deliverable_url and verified:
|
||||
return "DONE"
|
||||
# A model URL and its self-assessed verification cannot satisfy independent QA.
|
||||
return "TEST"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class QAResult:
|
||||
passed: bool
|
||||
reason: str
|
||||
|
||||
|
||||
def verify_artifact(deliverable: dict[str, Any], verification: dict[str, Any]) -> QAResult:
|
||||
"""Independent, rigorous verification of live deliverables. Rejects all fictitious URLs."""
|
||||
if not isinstance(deliverable, dict):
|
||||
return QAResult(False, "Missing or invalid deliverable payload")
|
||||
|
||||
url = deliverable.get("url")
|
||||
if not url or not isinstance(url, str) or not url.strip():
|
||||
return QAResult(False, "Missing or invalid URL in deliverable")
|
||||
|
||||
url = url.strip()
|
||||
|
||||
# 1. Reject fake/internal protocols and stage references
|
||||
if url.startswith("canina://") or url.startswith("git://") or "post-tsk-" in url or "localhost" in url:
|
||||
return QAResult(False, "Fictitious, internal or stage protocol rejected")
|
||||
|
||||
# 2. Enforce standard https
|
||||
if not url.startswith("https://") and not url.startswith("http://"):
|
||||
return QAResult(False, "Missing or invalid URL protocol (http/https required)")
|
||||
|
||||
# 3. Independent HTTP check
|
||||
try:
|
||||
import urllib.request
|
||||
req = urllib.request.Request(url, headers={"User-Agent": "Canina-Orchestration-QA-Bot/1.0"})
|
||||
with urllib.request.urlopen(req, timeout=10) as resp:
|
||||
code = resp.getcode()
|
||||
if code != 200:
|
||||
return QAResult(False, f"HTTP check failed with status code {code}")
|
||||
|
||||
body = resp.read().decode("utf-8", errors="ignore")
|
||||
|
||||
# Check for soft-404 patterns in Persian
|
||||
soft_404_patterns = ["مقاله یافت نشد", "صفحه مورد نظر یافت نشد", "404 -", "خطای ۴۰۴", "محصول یافت نشد"]
|
||||
for pattern in soft_404_patterns:
|
||||
if pattern in body:
|
||||
return QAResult(False, f"Soft 404 or missing content detected in live page ({pattern})")
|
||||
|
||||
if len(body) < 200:
|
||||
return QAResult(False, "Live page body suspiciously empty (< 200 bytes)")
|
||||
|
||||
return QAResult(True, f"Independently verified live artifact: HTTP 200, length {len(body)}")
|
||||
except Exception as exc:
|
||||
return QAResult(False, f"HTTP check failed: {exc}")
|
||||
|
||||
|
||||
def _literal(value: Any) -> str:
|
||||
return "'" + str(value).replace("'", "''") + "'"
|
||||
|
||||
|
||||
def claim_sql(token: str) -> str:
|
||||
"""Select and lease one root or child in a single locked statement."""
|
||||
event = json.dumps({"status": "CLAIMED", "claim_token": token})
|
||||
return f"""
|
||||
WITH candidate AS (
|
||||
SELECT id FROM department_tasks
|
||||
WHERE status = 'TODO' OR (
|
||||
status = 'IN_PROGRESS' AND execution_logs->-1->>'status' = 'CLAIMED'
|
||||
AND updated_at < NOW() - INTERVAL '15 minutes'
|
||||
)
|
||||
ORDER BY CASE priority WHEN 'CEO_EXPEDITE' THEN 0 WHEN 'CRITICAL' THEN 1
|
||||
WHEN 'HIGH' THEN 2 WHEN 'MEDIUM' THEN 3 ELSE 4 END,
|
||||
updated_at ASC, id ASC
|
||||
FOR UPDATE SKIP LOCKED LIMIT 1
|
||||
), claimed AS (
|
||||
UPDATE department_tasks t SET status = 'IN_PROGRESS', updated_at = NOW(),
|
||||
execution_logs = COALESCE(t.execution_logs, '[]'::jsonb) || {_literal(event)}::jsonb
|
||||
FROM candidate WHERE t.id = candidate.id
|
||||
RETURNING t.id, t.code, t.department, t.title, t.description,
|
||||
t.acceptance_criteria, t.execution_logs, t.assignee, t.priority
|
||||
) SELECT COALESCE(json_agg(claimed), '[]'::json)::text FROM claimed;
|
||||
"""
|
||||
|
||||
|
||||
def complete_sql(task_id: str, token: str, status: str, event: dict[str, Any],
|
||||
children: list[dict[str, Any]] | None = None) -> str:
|
||||
"""Fenced transition and idempotent child insert in one atomic SQL statement."""
|
||||
if status not in ('TODO', 'TEST', 'WAITING_DEPENDENCIES', 'REJECTED'):
|
||||
raise ValueError('Invalid worker transition')
|
||||
entries = []
|
||||
for child in children or []:
|
||||
entries.append('(' + ', '.join(_literal(x) for x in (
|
||||
child['code'], child['department'], child['title'], child['description'],
|
||||
child['priority'], child['assignee'], json.dumps(child['acceptanceCriteria'], ensure_ascii=False)
|
||||
)) + ')')
|
||||
insert = ''
|
||||
if entries:
|
||||
insert = f""", inserted AS (
|
||||
INSERT INTO department_tasks (id, code, department, title, description,
|
||||
status, priority, assignee, acceptance_criteria, execution_logs, created_at, updated_at)
|
||||
SELECT gen_random_uuid(), v.code, v.department, v.title, v.description,
|
||||
'TODO', v.priority, v.assignee, v.criteria::jsonb, '[]'::jsonb, NOW(), NOW()
|
||||
FROM (VALUES {', '.join(entries)}) AS v(code, department, title, description, priority, assignee, criteria)
|
||||
WHERE EXISTS (SELECT 1 FROM completed)
|
||||
ON CONFLICT (code) DO NOTHING RETURNING id
|
||||
)"""
|
||||
return f"""
|
||||
WITH completed AS (
|
||||
UPDATE department_tasks SET status = {_literal(status)}, updated_at = NOW(),
|
||||
execution_logs = COALESCE(execution_logs, '[]'::jsonb) || {_literal(json.dumps(event, ensure_ascii=False))}::jsonb
|
||||
WHERE id = {_literal(task_id)}::uuid AND status = 'IN_PROGRESS'
|
||||
AND updated_at >= NOW() - INTERVAL '15 minutes'
|
||||
AND execution_logs->-1->>'claim_token' = {_literal(token)}
|
||||
RETURNING id
|
||||
){insert}
|
||||
SELECT id FROM completed;
|
||||
"""
|
||||
|
||||
|
||||
class Database:
|
||||
def __init__(self) -> None:
|
||||
self.ssh = ["ssh", "-F", "/opt/data/.ssh/config", "parsa-host"]
|
||||
@@ -99,6 +213,8 @@ class Database:
|
||||
]
|
||||
|
||||
def sql(self, statement: str) -> str:
|
||||
if os.environ.get('CANINA_ORCHESTRATION_LIVE_WRITE') != 'I_ACCEPT_LIVE_MUTATION':
|
||||
raise RuntimeError('Live database writes disabled; use injected mock database for dry runs')
|
||||
result = subprocess.run(
|
||||
self.ssh + self.psql,
|
||||
input=statement,
|
||||
@@ -114,42 +230,16 @@ class Database:
|
||||
raw = self.sql(wrapped)
|
||||
return json.loads(raw or "[]")
|
||||
|
||||
def append_event(self, task_id: str, event: dict[str, Any], *, status: str | None = None) -> None:
|
||||
event_json = json.dumps(event, ensure_ascii=False).replace("$event$", "")
|
||||
status_sql = f", status = '{status}'" if status else ""
|
||||
self.sql(
|
||||
f"""
|
||||
UPDATE department_tasks
|
||||
SET execution_logs = COALESCE(execution_logs, '[]'::jsonb) || $event${event_json}$event$::jsonb,
|
||||
updated_at = NOW(){status_sql}
|
||||
WHERE id = '{task_id}';
|
||||
"""
|
||||
)
|
||||
|
||||
def insert_children(self, parent: dict[str, Any], children: list[dict[str, Any]]) -> int:
|
||||
inserted = 0
|
||||
for child in children:
|
||||
criteria = json.dumps(child["acceptanceCriteria"], ensure_ascii=False).replace("$criteria$", "")
|
||||
title = child["title"].replace("'", "''")
|
||||
description = child["description"].replace("'", "''")
|
||||
assignee = child["assignee"].replace("'", "''")
|
||||
out = self.sql(
|
||||
f"""
|
||||
INSERT INTO department_tasks
|
||||
(id, code, department, title, description, status, priority, assignee,
|
||||
acceptance_criteria, execution_logs, created_at, updated_at)
|
||||
VALUES
|
||||
(gen_random_uuid(), '{child['code']}', '{child['department']}', '{title}',
|
||||
'{description}', 'TODO', '{child['priority']}', '{assignee}',
|
||||
$criteria${criteria}$criteria$::jsonb, '[]'::jsonb, NOW(), NOW())
|
||||
ON CONFLICT (code) DO NOTHING
|
||||
RETURNING code;
|
||||
"""
|
||||
)
|
||||
if out:
|
||||
inserted += 1
|
||||
return inserted
|
||||
def claim_next(self) -> dict[str, Any] | None:
|
||||
token = str(uuid.uuid4())
|
||||
rows = json.loads(self.sql(claim_sql(token)) or '[]')
|
||||
if not rows:
|
||||
return None
|
||||
return {**rows[0], 'claim_token': token}
|
||||
|
||||
def finish_claim(self, task: dict[str, Any], event: dict[str, Any], status: str,
|
||||
children: list[dict[str, Any]] | None = None) -> bool:
|
||||
return bool(self.sql(complete_sql(task['id'], task['claim_token'], status, event, children)))
|
||||
|
||||
class ModelClient:
|
||||
def __init__(self) -> None:
|
||||
@@ -244,67 +334,44 @@ def execution_prompt(task: dict[str, Any]) -> str:
|
||||
""".strip()
|
||||
|
||||
|
||||
def execute_next_child(db: Database, model: ModelClient) -> bool:
|
||||
tasks = db.rows_json(
|
||||
"""
|
||||
SELECT id, code, department, title, description, status, acceptance_criteria,
|
||||
execution_logs, deliverable_url
|
||||
FROM department_tasks
|
||||
WHERE status = 'TODO'
|
||||
AND acceptance_criteria->>'parentTaskCode' IS NOT NULL
|
||||
ORDER BY created_at ASC
|
||||
LIMIT 1
|
||||
"""
|
||||
)
|
||||
if not tasks:
|
||||
def execute_next_task(db: Database, model: ModelClient) -> bool:
|
||||
"""Produce reviewable drafts; never publish or trust model QA assertions."""
|
||||
task = db.claim_next()
|
||||
if not task:
|
||||
return False
|
||||
task = tasks[0]
|
||||
prompt = execution_prompt(task)
|
||||
db.append_event(task["id"], {
|
||||
"timestamp": utc_now(), "status": "AGENT_EXECUTION_STARTED",
|
||||
"agent": task.get("assignee") or f"Canina-{task['department']}-Agent",
|
||||
"prompt_to_model": prompt,
|
||||
}, status="IN_PROGRESS")
|
||||
try:
|
||||
raw = model.complete(prompt)
|
||||
result = parse_structured_response(raw)
|
||||
criteria = task.get('acceptance_criteria') or {}
|
||||
children = build_child_tasks(task['code'], result, int(criteria.get('depth', 0)))
|
||||
deliverable = result.get('deliverable') or {}
|
||||
qa = verify_artifact(deliverable, result.get('verification') or {})
|
||||
status = determine_parent_status(has_children=bool(children),
|
||||
deliverable_url=deliverable.get('url'), verified=qa.passed)
|
||||
event = {'timestamp': utc_now(), 'status': 'QA_PENDING', 'prompt_to_model': prompt,
|
||||
'model_response': raw, 'deliverable': deliverable,
|
||||
'qa': qa.reason, 'childrenProposed': len(children)}
|
||||
if not db.finish_claim(task, event, status, children):
|
||||
raise RuntimeError('Claim lost before completion; no result committed')
|
||||
except Exception as exc:
|
||||
db.append_event(task["id"], {
|
||||
"timestamp": utc_now(), "status": "AGENT_EXECUTION_FAILED",
|
||||
"error": str(exc),
|
||||
}, status="TODO")
|
||||
db.finish_claim(task, {'timestamp': utc_now(), 'status': 'AGENT_EXECUTION_FAILED',
|
||||
'error': str(exc)}, 'TODO')
|
||||
raise
|
||||
|
||||
criteria = task.get("acceptance_criteria") or {}
|
||||
depth = int(criteria.get("depth", 1))
|
||||
children = build_child_tasks(task["code"], result, depth)
|
||||
inserted = db.insert_children(task, children)
|
||||
deliverable = result.get("deliverable") or {}
|
||||
verification = result.get("verification") or {}
|
||||
verified = bool(deliverable.get("verified")) and bool(verification.get("passed"))
|
||||
next_status = determine_parent_status(
|
||||
has_children=bool(children),
|
||||
deliverable_url=deliverable.get("url"),
|
||||
verified=verified,
|
||||
)
|
||||
db.append_event(task["id"], {
|
||||
"timestamp": utc_now(), "status": "AGENT_EXECUTION_COMPLETED",
|
||||
"agent": task.get("assignee") or f"Canina-{task['department']}-Agent",
|
||||
"model_response": raw,
|
||||
"summary": result.get("summary"),
|
||||
"deliverable": deliverable,
|
||||
"verification": verification,
|
||||
"childrenCreated": inserted,
|
||||
}, status=next_status)
|
||||
return True
|
||||
|
||||
|
||||
execute_next_child = execute_next_task
|
||||
|
||||
|
||||
def reconcile_parent_states(db: Database) -> bool:
|
||||
parents = db.rows_json(
|
||||
"""
|
||||
SELECT id, code, status
|
||||
FROM department_tasks p
|
||||
WHERE status = 'WAITING_DEPENDENCIES'
|
||||
AND EXISTS (SELECT 1 FROM department_tasks c
|
||||
WHERE c.acceptance_criteria->>'parentTaskCode' = p.code)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM department_tasks c
|
||||
WHERE c.acceptance_criteria->>'parentTaskCode' = p.code
|
||||
@@ -316,71 +383,23 @@ def reconcile_parent_states(db: Database) -> bool:
|
||||
)
|
||||
if not parents:
|
||||
return False
|
||||
parent = parents[0]
|
||||
db.append_event(parent["id"], {
|
||||
"timestamp": utc_now(), "status": "DEPENDENCIES_COMPLETED",
|
||||
"agent": "Canina-PMO-Agent",
|
||||
"note": "تمام child taskها تکمیل و راستیآزمایی شدهاند؛ والد وارد QA نهایی شد.",
|
||||
}, status="TEST")
|
||||
return True
|
||||
# Dependency completion alone cannot pass parent QA. Leave it blocked pending
|
||||
# independently persisted attestations; no synthetic URL or DONE transition.
|
||||
return False
|
||||
|
||||
|
||||
def reconcile_pseudo_done(db: Database, model: ModelClient) -> bool:
|
||||
tasks = db.rows_json(
|
||||
"""
|
||||
SELECT id, code, department, title, description, status, acceptance_criteria,
|
||||
execution_logs, deliverable_url
|
||||
FROM department_tasks
|
||||
WHERE status = 'DONE'
|
||||
AND code LIKE 'TSK-%'
|
||||
AND (deliverable_url IS NULL OR deliverable_url = '')
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM department_tasks child
|
||||
WHERE child.acceptance_criteria->>'parentTaskCode' = department_tasks.code
|
||||
)
|
||||
ORDER BY created_at ASC
|
||||
LIMIT 1
|
||||
"""
|
||||
)
|
||||
if not tasks:
|
||||
return False
|
||||
task = tasks[0]
|
||||
prompt = decomposition_prompt(task)
|
||||
db.append_event(task["id"], {
|
||||
"timestamp": utc_now(), "status": "PMO_DECOMPOSITION_STARTED",
|
||||
"agent": "Canina-PMO-Agent", "prompt_to_model": prompt,
|
||||
}, status="IN_PROGRESS")
|
||||
raw = model.complete(prompt)
|
||||
proposal = parse_structured_response(raw)
|
||||
depth = int((task.get("acceptance_criteria") or {}).get("depth", 0))
|
||||
children = build_child_tasks(task["code"], proposal, depth)
|
||||
inserted = db.insert_children(task, children)
|
||||
deliverable = proposal.get("deliverable") or {}
|
||||
next_status = determine_parent_status(
|
||||
has_children=bool(children),
|
||||
deliverable_url=deliverable.get("url"),
|
||||
verified=bool(deliverable.get("verified")),
|
||||
)
|
||||
db.append_event(task["id"], {
|
||||
"timestamp": utc_now(), "status": "PMO_DECOMPOSITION_COMPLETED",
|
||||
"agent": "Canina-PMO-Agent", "model_response": raw,
|
||||
"summary": proposal.get("summary"), "childrenCreated": inserted,
|
||||
}, status=next_status)
|
||||
return True
|
||||
# Legacy DONE records require a separate human audit, not autonomous rewrites.
|
||||
return False
|
||||
|
||||
|
||||
def main() -> None:
|
||||
db = Database()
|
||||
model = ModelClient()
|
||||
if reconcile_pseudo_done(db, model):
|
||||
print("Reconciled one pseudo-DONE root task into cross-department dependencies.")
|
||||
return
|
||||
if execute_next_child(db, model):
|
||||
if execute_next_task(db, model):
|
||||
print("Executed one child task; unverified model output remains in TEST, never DONE.")
|
||||
return
|
||||
if reconcile_parent_states(db):
|
||||
print("Moved one parent with verified completed children into TEST.")
|
||||
return
|
||||
# Parent reconciliation requires independent persisted QA attestations.
|
||||
print("No actionable orchestration task found.")
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import unittest
|
||||
from unittest.mock import Mock, patch
|
||||
from orchestration_worker import verify_artifact, QAResult
|
||||
|
||||
class ArtifactQAVerifierTests(unittest.TestCase):
|
||||
def test_missing_or_empty_url_is_rejected(self):
|
||||
deliverable = {"type": "CONTENT", "url": ""}
|
||||
res = verify_artifact(deliverable, {"passed": True})
|
||||
self.assertFalse(res.passed)
|
||||
self.assertIn("Missing or invalid URL", res.reason)
|
||||
|
||||
def test_internal_or_mock_urls_are_rejected(self):
|
||||
for bad_url in [
|
||||
"canina://internal/review",
|
||||
"git://stage/task-1",
|
||||
"https://canina.ir/blog/post-tsk-9999",
|
||||
"http://localhost:3000/preview"
|
||||
]:
|
||||
res = verify_artifact({"type": "CONTENT", "url": bad_url}, {"passed": True})
|
||||
self.assertFalse(res.passed, f"URL {bad_url} should have been rejected")
|
||||
self.assertIn("Fictitious, internal or stage protocol", res.reason)
|
||||
|
||||
@patch("urllib.request.urlopen")
|
||||
def test_http_404_or_network_failure_is_rejected(self, mock_urlopen):
|
||||
mock_urlopen.side_effect = Exception("HTTP 404: Not Found")
|
||||
res = verify_artifact({"type": "CONTENT", "url": "https://canina.ir/blog/valid-slug"}, {"passed": True})
|
||||
self.assertFalse(res.passed)
|
||||
self.assertIn("HTTP check failed", res.reason)
|
||||
|
||||
@patch("urllib.request.urlopen")
|
||||
def test_http_200_with_soft_404_content_is_rejected(self, mock_urlopen):
|
||||
mock_resp = Mock()
|
||||
mock_resp.getcode.return_value = 200
|
||||
mock_resp.read.return_value = "<html><body><h1>مقاله یافت نشد</h1><p>متاسفانه این صفحه حذف شده است</p></body></html>".encode("utf-8")
|
||||
mock_urlopen.return_value.__enter__.return_value = mock_resp
|
||||
|
||||
res = verify_artifact({"type": "CONTENT", "url": "https://canina.ir/blog/valid-slug"}, {"passed": True})
|
||||
self.assertFalse(res.passed)
|
||||
self.assertIn("Soft 404 or missing content detected in live page", res.reason)
|
||||
|
||||
@patch("urllib.request.urlopen")
|
||||
def test_http_200_with_authentic_content_passes(self, mock_urlopen):
|
||||
mock_resp = Mock()
|
||||
mock_resp.getcode.return_value = 200
|
||||
mock_resp.read.return_value = ("<html><body><article><h1>راهنمای مفاصل کنینا</h1><p>" + "متن کامل بالینی " * 100 + "</p></article></body></html>").encode("utf-8")
|
||||
mock_urlopen.return_value.__enter__.return_value = mock_resp
|
||||
|
||||
res = verify_artifact({"type": "CONTENT", "url": "https://canina.ir/blog/joints-guide"}, {"passed": True})
|
||||
self.assertTrue(res.passed)
|
||||
self.assertIn("Independently verified live artifact", res.reason)
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,71 @@
|
||||
import unittest
|
||||
|
||||
from market_proposals import validate_proposal, insert_proposal
|
||||
|
||||
|
||||
REPORT = "https://example.org/research\nEvidence: product listing lacks dosage instructions."
|
||||
BASE = {"source_url": "https://example.org/research", "evidence_quote": "product listing lacks dosage instructions", "action_type": "CATALOG_AUDIT", "department": "CONTENT"}
|
||||
|
||||
|
||||
class FakeDB:
|
||||
def __init__(self, output):
|
||||
self.output = output
|
||||
self.statements = []
|
||||
|
||||
def sql(self, statement):
|
||||
self.statements.append(statement)
|
||||
return self.output
|
||||
|
||||
|
||||
class MarketProposalTests(unittest.TestCase):
|
||||
def test_verified_citation_produces_stable_fingerprint_and_pending_payload(self):
|
||||
first = validate_proposal(BASE, REPORT, "scout-2026-10-20.md")
|
||||
second = validate_proposal(BASE, REPORT, "scout-2026-10-22.md")
|
||||
self.assertEqual(first["fingerprint"], second["fingerprint"])
|
||||
self.assertEqual(first["payload"]["sourceUrl"], BASE["source_url"])
|
||||
self.assertEqual(first["payload"]["evidenceQuote"], BASE["evidence_quote"])
|
||||
self.assertEqual(first["payload"]["reviewRequired"], True)
|
||||
self.assertNotIn("price", str(first).lower())
|
||||
|
||||
def test_unsubstantiated_or_unsafe_sources_rejected(self):
|
||||
for item in ({**BASE, "source_url": "https://other.example/page"},
|
||||
{**BASE, "evidence_quote": "invented price 123"},
|
||||
{**BASE, "source_url": "file:///etc/passwd"}):
|
||||
with self.subTest(item=item), self.assertRaises(ValueError):
|
||||
validate_proposal(item, REPORT, "scout.md")
|
||||
|
||||
def test_quote_must_be_in_same_citation_block_as_url(self):
|
||||
report = "https://example.org/research\nSome unrelated finding.\n\nhttps://example.org/other\nproduct listing lacks dosage instructions"
|
||||
with self.assertRaises(ValueError):
|
||||
validate_proposal(BASE, report, "scout.md")
|
||||
|
||||
def test_human_and_physical_routes_rejected(self):
|
||||
for item in ({**BASE, "department": "B2B"},
|
||||
{**BASE, "department": "CLINICAL_RD"},
|
||||
{**BASE, "action_type": "FIELD_VISIT"},
|
||||
{**BASE, "action_type": "CATALOG_AUDIT", "department": "SUPPORT"}):
|
||||
with self.subTest(item=item), self.assertRaises(ValueError):
|
||||
validate_proposal(item, REPORT, "scout.md")
|
||||
|
||||
def test_untrusted_model_narrative_cannot_enter_payload_or_title(self):
|
||||
item = {**BASE, "title": "Guaranteed cure 999", "payload": {"price": "invented"}}
|
||||
result = validate_proposal(item, REPORT, "scout.md")
|
||||
self.assertNotIn("Guaranteed", str(result))
|
||||
self.assertNotIn("invented", str(result))
|
||||
|
||||
def test_insert_counts_only_returned_uuid_and_sql_is_atomic_and_pending(self):
|
||||
proposal = validate_proposal(BASE, REPORT, "scout.md")
|
||||
db = FakeDB("BEGIN\n123e4567-e89b-12d3-a456-426614174000\nINSERT 0 1\nCOMMIT")
|
||||
self.assertTrue(insert_proposal(db, proposal))
|
||||
sql = db.statements[0]
|
||||
self.assertIn("pg_advisory_xact_lock", sql)
|
||||
self.assertIn("sourceFingerprint", sql)
|
||||
self.assertIn("RETURNING id", sql)
|
||||
self.assertIn("'PENDING'", sql)
|
||||
self.assertNotIn("APPROVED", sql)
|
||||
self.assertFalse(insert_proposal(FakeDB("BEGIN\nINSERT 0 0\nCOMMIT"), proposal))
|
||||
self.assertFalse(insert_proposal(FakeDB("BEGIN\nCOMMIT"), proposal))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,65 @@
|
||||
import json
|
||||
import unittest
|
||||
from unittest.mock import Mock
|
||||
|
||||
from orchestration_worker import (
|
||||
claim_sql, complete_sql, execute_next_task, reconcile_parent_states,
|
||||
determine_parent_status, verify_artifact,
|
||||
)
|
||||
|
||||
|
||||
class ContractTests(unittest.TestCase):
|
||||
def test_claim_is_atomic_priority_first_and_includes_roots(self):
|
||||
sql = claim_sql("token-1")
|
||||
self.assertIn("FOR UPDATE SKIP LOCKED", sql)
|
||||
self.assertIn("CEO_EXPEDITE", sql)
|
||||
self.assertIn("updated_at ASC", sql)
|
||||
self.assertNotIn("parentTaskCode' IS NOT NULL", sql)
|
||||
self.assertIn("RETURNING", sql)
|
||||
|
||||
def test_completion_is_fenced_by_claim_token(self):
|
||||
sql = complete_sql("task-id", "token-1", "TEST", {"status": "QA_PENDING"})
|
||||
self.assertIn("IN_PROGRESS", sql)
|
||||
self.assertIn("token-1", sql)
|
||||
self.assertIn("RETURNING", sql)
|
||||
self.assertIn("claim_token", sql)
|
||||
self.assertIn("updated_at >= NOW() - INTERVAL '15 minutes'", sql)
|
||||
|
||||
def test_model_verified_url_cannot_mark_done(self):
|
||||
self.assertEqual(determine_parent_status(has_children=False, deliverable_url="https://canina.ir/fake", verified=True), "TEST")
|
||||
|
||||
def test_independent_qa_rejects_unverified_claimed_url(self):
|
||||
self.assertFalse(verify_artifact({"url": "https://canina.ir/fake", "verified": True}, {"passed": True}).passed)
|
||||
|
||||
def test_unapproved_content_publish_is_not_attempted(self):
|
||||
db = Mock()
|
||||
db.claim_next.return_value = {"id": "1", "code": "CEO-2", "department": "CONTENT", "title": "Draft", "description": "Do", "acceptance_criteria": {}, "claim_token": "abc"}
|
||||
db.finish_claim.return_value = True
|
||||
model = Mock()
|
||||
model.complete.return_value = json.dumps({"deliverable": {"type": "draft", "content": "clinical " * 200, "url": "https://canina.ir/blog/fake", "verified": True}, "verification": {"passed": True}})
|
||||
self.assertTrue(execute_next_task(db, model))
|
||||
self.assertEqual(db.finish_claim.call_args.args[2], "TEST")
|
||||
self.assertNotIn("published", db.finish_claim.call_args.args[1])
|
||||
|
||||
def test_root_executes_without_live_side_effects(self):
|
||||
db = Mock()
|
||||
db.claim_next.return_value = {"id": "1", "code": "CEO-1", "department": "PMO", "title": "Plan", "description": "Do", "acceptance_criteria": {}, "claim_token": "abc"}
|
||||
db.finish_claim.return_value = True
|
||||
model = Mock()
|
||||
model.complete.return_value = json.dumps({"deliverable": {"url": "https://canina.ir/fake", "verified": True}, "verification": {"passed": True}, "child_tasks": []})
|
||||
self.assertTrue(execute_next_task(db, model))
|
||||
db.finish_claim.assert_called_once()
|
||||
self.assertEqual(db.finish_claim.call_args.args[2], "TEST")
|
||||
db.insert_children.assert_not_called()
|
||||
|
||||
def test_rejected_child_never_unblocks_parent(self):
|
||||
db = Mock()
|
||||
db.rows_json.return_value = []
|
||||
self.assertFalse(reconcile_parent_states(db))
|
||||
# REJECTED is not DONE, therefore the anti-join still blocks the parent.
|
||||
self.assertIn("NOT IN ('DONE')", db.rows_json.call_args.args[0])
|
||||
self.assertNotIn("NOT IN ('DONE', 'REJECTED')", db.rows_json.call_args.args[0])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -19,10 +19,10 @@ class OrchestrationWorkerTests(unittest.TestCase):
|
||||
"TEST",
|
||||
)
|
||||
|
||||
def test_verified_live_deliverable_may_be_done(self):
|
||||
def test_model_claimed_live_deliverable_still_requires_independent_qa(self):
|
||||
self.assertEqual(
|
||||
determine_parent_status(has_children=False, deliverable_url="https://canina.ir/x", verified=True),
|
||||
"DONE",
|
||||
"TEST",
|
||||
)
|
||||
|
||||
def test_children_force_waiting_dependencies(self):
|
||||
|
||||
Reference in new issue
Block a user