diff --git a/backend/prisma/MIGRATION_BASELINE.md b/backend/prisma/MIGRATION_BASELINE.md index 2f072470..9d7796f2 100644 --- a/backend/prisma/MIGRATION_BASELINE.md +++ b/backend/prisma/MIGRATION_BASELINE.md @@ -1,13 +1,28 @@ -# Prisma migration baseline and Orchestration v4 rollout +# Prisma migration history and Orchestration v4 rollout boundary -The production databases predate complete migration tracking for the legacy governance tables (`approval_requests`, `department_tasks`, and `audit_logs`). Do **not** run `prisma db push`, reset, or edit an applied migration. +The checked-in history is **not a complete baseline of the current Prisma schema**. Do not assume that replaying it into an empty database can recreate the application, or that existing production tables imply corresponding migration records. Never use `prisma db push`, reset, or edit applied SQL to reconcile this. -## Safe baseline procedure (per environment, during a CI/CD maintenance step) +## Actual tracked history -1. Back up the database and verify restore capability. -2. Run `prisma migrate status` and compare the live schema to the reviewed migrations. -3. For migrations whose objects already exist in that environment, record them without executing SQL using `prisma migrate resolve --applied `. This is an environment-specific reconciliation step; never guess which migrations are present. -4. Review `20261022000000_add_orchestration_v4_core/migration.sql`. It is additive: it creates only `orchestration_*` tables, indexes, and foreign keys. It does not alter or copy legacy governance data. -5. Apply through CI/CD only with `prisma migrate deploy`; validate counts and application health. No production deployment is part of this change. +| Migration | What its SQL actually does | +| --- | --- | +| `20260526145407_init` | Creates users, addresses, wallets, products, product ingredients/symptoms, pets and medical conditions, reminders/completions, health logs, coupons, orders and order items, with their indexes/foreign keys. | +| `20260526160916_add_ui_texts_and_scientific_terms` | Creates `ui_texts` and `scientific_terms`. | +| `20261013210253_add_admin_modules` | Creates only `competitor_price_logs`, `b2b_leads`, `price_suggestions`, and `sms_campaigns`, with indexes and product foreign keys. It does **not** create legacy approvals, department tasks or audit logs. | +| `20261015000000_add_support_conversations` | Creates support conversations/messages and their foreign keys. | +| `20261020000000_add_blog_freshness_authorship` | Adds three columns to an assumed-existing `blogs` table. No earlier tracked migration creates `blogs`; fresh replay is therefore incomplete before v4. | +| `20261022000000_add_orchestration_v4_core` | Additively creates nine `orchestration_*` tables, indexes and internal foreign keys; it neither creates nor copies legacy governance tables. | -Rollback is application-first: stop use of the new module while retaining its append-only records. Do not drop tables in an automated rollback. Any later removal requires a separately reviewed archival migration. +There is no checked-in CREATE TABLE migration for `approval_requests`, `department_tasks`, or `audit_logs`. Their models/controllers are not evidence that either live environment has these tables, nor proof of how any historical database acquired them. The broader missing legacy schema must be reconciled separately. This document does not certify live table existence or migration status. + +## Required rollout safeguards (not authorization to deploy) + +1. Back up each environment and verify restore capability. Capture its actual schema and `_prisma_migrations` history read-only; compare those independently against all tracked SQL, including prerequisites such as `blogs`. +2. Rehearse the exact planned chain on a disposable database restored from a reviewed baseline. A failed empty replay is a legacy-history gap, not evidence that the additive v4 SQL alone is faulty. Resolve the missing baseline through a separately reviewed migration/baseline plan, never by skipping errors. +3. `prisma migrate resolve --applied ` only records history; it creates no objects. Use it only for a specifically verified, fully matching existing migration and reviewed environment-specific plan. Never mark the whole chain applied or mark missing tables as applied. +4. After baseline reconciliation and rehearsal pass, apply reviewed pending migrations through CI/CD only using `prisma migrate deploy`. Verify all nine v4 tables, constraints, migration records and application health before considering the read surface ready. +5. Keep v4 mutations, chat and runtime capabilities denied. Retiring legacy mutation routes does not authorize a replacement execution path. + +No deployment, live DDL, baseline resolution or migration SQL change is part of this hardening milestone. Schema rollout remains a separate gate, not full-system completion. + +Rollback is application-first: stop use of the new module while retaining append-only records. Do not drop tables in automated rollback; removal requires separately reviewed archival migration. diff --git a/backend/src/admin/approvals.controller.spec.ts b/backend/src/admin/approvals.controller.spec.ts index a61501d4..d16721a1 100644 --- a/backend/src/admin/approvals.controller.spec.ts +++ b/backend/src/admin/approvals.controller.spec.ts @@ -1,271 +1,25 @@ -import { Test, TestingModule } from "@nestjs/testing"; -import { BadRequestException, NotFoundException } from "@nestjs/common"; -import { ApprovalsController } from "./approvals.controller"; -import { PrismaService } from "../prisma/prisma.service"; +import { GoneException } 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); - }); - - 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: "ریسک بالای افت رتبه سئو", - }), - }); - }); - }); +describe('ApprovalsController retired mutation boundary',()=>{ + const access=jest.fn(); + const prisma=new Proxy({},{get:(_target,key)=>{access(key);throw new Error('Database access forbidden');}}); + const controller=new ApprovalsController(prisma as PrismaService); + beforeEach(()=>access.mockClear()); + it('create {department:SEO,category:SEO,title:Legacy,payload:{}} returns 410 without reading or writing persistence',async()=>{ + await expect(controller.create({department:'SEO',category:'SEO',title:'Legacy',payload:{}})).rejects.toBeInstanceOf(GoneException); + await expect(controller.create({department:'SEO',category:'SEO',title:'Legacy',payload:{}})).rejects.toMatchObject({status:410}); + expect(access).not.toHaveBeenCalled(); + }); + it('decide missing, {decision:APPROVED} returns 410 without reading or writing persistence',async()=>{ + await expect(controller.decide('missing', {decision:'APPROVED'})).rejects.toBeInstanceOf(GoneException); + await expect(controller.decide('missing', {decision:'APPROVED'})).rejects.toMatchObject({status:410}); + expect(access).not.toHaveBeenCalled(); + }); + it('decide missing, {decision:REJECTED} returns 410 without reading or writing persistence',async()=>{ + await expect(controller.decide('missing', {decision:'REJECTED'})).rejects.toBeInstanceOf(GoneException); + await expect(controller.decide('missing', {decision:'REJECTED'})).rejects.toMatchObject({status:410}); + expect(access).not.toHaveBeenCalled(); + }); }); diff --git a/backend/src/admin/approvals.controller.ts b/backend/src/admin/approvals.controller.ts index ad0337e6..ce0ce6f3 100644 --- a/backend/src/admin/approvals.controller.ts +++ b/backend/src/admin/approvals.controller.ts @@ -8,7 +8,7 @@ import { Query, UseGuards, NotFoundException, - BadRequestException, + GoneException, } from "@nestjs/common"; import { ApiTags, ApiBearerAuth, ApiOperation } from "@nestjs/swagger"; import { JwtAuthGuard } from "../auth/jwt-auth.guard"; @@ -82,17 +82,7 @@ export class ApprovalsController { @Post() @ApiOperation({ summary: "ثبت آیتم جدید جهت تایید مدیریت (از طرف سیستم یا دپارتمان‌ها)" }) async create(@Body() dto: CreateApprovalRequestDto) { - const item = await (this.prisma as any).approvalRequest.create({ - data: { - department: dto.department, - category: dto.category, - title: dto.title, - payload: dto.payload, - testContext: dto.testContext || {}, - status: "PENDING", - }, - }); - return { success: true, data: item }; + throw new GoneException("Legacy orchestration mutations are retired. Orchestration v4 remains read-only; no replacement mutation is enabled."); } @Post(":id/test") @@ -138,120 +128,7 @@ export class ApprovalsController { @Put(":id/decide") @ApiOperation({ summary: "تصمیم‌گیری مدیرعامل (تایید یا رد همراه با یادداشت)" }) async decide(@Param("id") id: string, @Body() dto: DecideApprovalDto) { - if (!["APPROVED", "REJECTED"].includes(dto.decision)) { - throw new BadRequestException("Decision must be either APPROVED or REJECTED"); - } - - const item = await (this.prisma as any).approvalRequest.findUnique({ - where: { id }, - }); - if (!item) { - throw new NotFoundException(`Approval request ${id} not found`); - } - - if (dto.decision === "REJECTED") { - const updated = await (this.prisma as any).approvalRequest.update({ - where: { id }, - data: { - status: "REJECTED", - ceoNotes: dto.ceoNotes || null, - }, - }); - - if ((this.prisma as any).departmentTask?.updateMany) { - await (this.prisma as any).departmentTask.updateMany({ - where: { approvalId: id }, - data: { status: "REJECTED" }, - }); - } - - return { - success: true, - message: "درخواست رد شد و در سوابق ممیزی ثبت گردید.", - data: updated, - }; - } - - // تفکیک اقدامات استراتژیک تامین‌کننده/مدیریتی از کارهای دیجیتال سایت - const isStrategicSupplierAction = - item.category === "B2B_SUPPLIER_STRATEGY" || - item.category === "PARTNERSHIP" || - (item.department === "B2B" && String(item.category || "").includes("STRATEGY")); - - if (isStrategicSupplierAction) { - // طرح‌های B2B_SUPPLIER_STRATEGY منحصراً در سوابق مدیریتی تایید می‌شوند. - // هیچ تسک دیجیتالی ایجاد یا بازگشایی نمی‌شود و executedAt فیزیکی ثبت نمی‌گردد. - const updateData: any = { - status: "APPROVED", - ceoNotes: dto.ceoNotes || null, - }; - - if (dto.outcome || dto.evidence) { - const payload = typeof item.payload === "object" && item.payload !== null - ? { ...(item.payload as Record) } - : {}; - if (dto.outcome) payload.outcome = dto.outcome; - if (dto.evidence) payload.evidence = dto.evidence; - updateData.payload = payload; - } - - const updated = await (this.prisma as any).approvalRequest.update({ - where: { id }, - data: updateData, - }); - - return { - success: true, - message: "طرح استراتژیک تامین‌کننده تایید گردید و در سوابق مدیریتی ثبت شد.", - data: updated, - }; - } - - // کارهای دیجیتال (مانند SEO، محتوا، قیمت‌گذاری و فنی) - // تایید مجوز اجرای کار دیجیتال است و تسک متناظر را در صف TODO قرار می‌دهد - const updated = await (this.prisma as any).approvalRequest.update({ - where: { id }, - data: { - status: "APPROVED", - ceoNotes: dto.ceoNotes || null, - }, - }); - - // جستجو یا ایجاد تسک متناظر با استاتوس TODO - const existingTask = await (this.prisma as any).departmentTask.findFirst({ - where: { approvalId: id }, - }); - - if (existingTask) { - await (this.prisma as any).departmentTask.update({ - where: { id: existingTask.id }, - data: { - status: "TODO", - description: dto.ceoNotes - ? (existingTask.description || "") + "\n\n[یادداشت مدیرعامل]: " + dto.ceoNotes - : existingTask.description, - }, - }); - } else { - await (this.prisma as any).departmentTask.create({ - data: { - code: "TSK-" + Date.now().toString().slice(-6), - department: item.department || "SEO", - title: item.title, - description: dto.ceoNotes ? (item.title + "\n\n[یادداشت مدیرعامل]: " + dto.ceoNotes) : item.title, - status: "TODO", - priority: "HIGH", - assignee: "AI_AGENT", - approvalId: item.id, - }, - }); - } - - return { - success: true, - message: "درخواست تایید شد و مأموریت به صف اقدام (TODO) دپارتمان منتقل گردید.", - data: updated, - }; + throw new GoneException("Legacy orchestration mutations are retired. Orchestration v4 remains read-only; no replacement mutation is enabled."); } } diff --git a/backend/src/admin/department-tasks.controller.spec.ts b/backend/src/admin/department-tasks.controller.spec.ts index 24a7e6c1..7217d46e 100644 --- a/backend/src/admin/department-tasks.controller.spec.ts +++ b/backend/src/admin/department-tasks.controller.spec.ts @@ -1,163 +1,25 @@ -import { Test, TestingModule } from "@nestjs/testing"; -import { BadRequestException, NotFoundException } from "@nestjs/common"; -import { DepartmentTasksController } from "./department-tasks.controller"; -import { PrismaService } from "../prisma/prisma.service"; +import { GoneException } 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); - }); - - 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), - }), - }); - }); - }); +describe('DepartmentTasksController retired mutation boundary',()=>{ + const access=jest.fn(); + const prisma=new Proxy({},{get:(_target,key)=>{access(key);throw new Error('Database access forbidden');}}); + const controller=new DepartmentTasksController(prisma as PrismaService); + beforeEach(()=>access.mockClear()); + it('create {department:SEO,title:Legacy} returns 410 without reading or writing persistence',async()=>{ + await expect(controller.create({department:'SEO',title:'Legacy'})).rejects.toBeInstanceOf(GoneException); + await expect(controller.create({department:'SEO',title:'Legacy'})).rejects.toMatchObject({status:410}); + expect(access).not.toHaveBeenCalled(); + }); + it('updateStatus missing, {status:DONE} returns 410 without reading or writing persistence',async()=>{ + await expect(controller.updateStatus('missing', {status:'DONE'})).rejects.toBeInstanceOf(GoneException); + await expect(controller.updateStatus('missing', {status:'DONE'})).rejects.toMatchObject({status:410}); + expect(access).not.toHaveBeenCalled(); + }); + it('updateStatus missing, {status:TODO} returns 410 without reading or writing persistence',async()=>{ + await expect(controller.updateStatus('missing', {status:'TODO'})).rejects.toBeInstanceOf(GoneException); + await expect(controller.updateStatus('missing', {status:'TODO'})).rejects.toMatchObject({status:410}); + expect(access).not.toHaveBeenCalled(); + }); }); diff --git a/backend/src/admin/department-tasks.controller.ts b/backend/src/admin/department-tasks.controller.ts index e497dfac..25c92d55 100644 --- a/backend/src/admin/department-tasks.controller.ts +++ b/backend/src/admin/department-tasks.controller.ts @@ -8,8 +8,8 @@ import { Query, UseGuards, NotFoundException, + GoneException, } from "@nestjs/common"; -import { assertTaskCanComplete } from "./department-task-completion.policy"; import { ApiTags, ApiBearerAuth, ApiOperation } from "@nestjs/swagger"; import { JwtAuthGuard } from "../auth/jwt-auth.guard"; import { RolesGuard } from "../common/guards/roles.guard"; @@ -112,36 +112,7 @@ export class DepartmentTasksController { @Post() @ApiOperation({ summary: "ایجاد تسک جدید سازمانی" }) async create(@Body() body: any) { - const code = body.code || "TSK-" + Date.now().toString().slice(-6); - const task = await (this.prisma as any).departmentTask.create({ - data: { - code, - department: body.department, - title: body.title, - description: body.description || null, - status: body.status || "TODO", - priority: body.priority || "MEDIUM", - assignee: body.assignee || "AI_AGENT", - acceptanceCriteria: body.acceptanceCriteria || null, - executionLogs: body.executionLogs || [], - deliverableUrl: body.deliverableUrl || null, - startedAt: body.status === "IN_PROGRESS" ? new Date() : null, - }, - }); - - await (this.prisma as any).auditLog.create({ - data: { - entity: "task", - entityId: task.id, - action: "CREATE", - department: task.department, - actor: task.assignee || "SYSTEM", - summary: "تسک جدید " + task.code + " (" + task.title + ") ایجاد شد.", - newValues: task, - }, - }); - - return { success: true, data: task }; + throw new GoneException("Legacy orchestration mutations are retired. Orchestration v4 remains read-only; no replacement mutation is enabled."); } @Put(":id/status") @@ -150,61 +121,7 @@ export class DepartmentTasksController { @Param("id") id: string, @Body() body: { status: string; logNote?: string; deliverableUrl?: string } ) { - const existing = await (this.prisma as any).departmentTask.findUnique({ - where: { id }, - }); - if (!existing) throw new NotFoundException(`Task ${id} not found`); - - const logs = Array.isArray(existing.executionLogs) ? [...existing.executionLogs] : []; - if (body.logNote) { - logs.push({ - timestamp: new Date().toISOString(), - status: body.status, - note: body.logNote, - }); - } - - const candidateDeliverableUrl = body.deliverableUrl || existing.deliverableUrl; - if (body.status === "DONE") { - assertTaskCanComplete({ - code: existing.code, - title: existing.title, - deliverableUrl: candidateDeliverableUrl, - acceptanceCriteria: existing.acceptanceCriteria, - executionLogs: logs, - }); - } - - const updateData: any = { - status: body.status, - executionLogs: logs, - }; - 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(); - if (body.status === "TODO" && body.logNote) { - updateData.description = (existing.description || "") + "\n\n[اصلاحات و تضمین کیفیت QA]: " + body.logNote; - } - - const updated = await (this.prisma as any).departmentTask.update({ - where: { id }, - data: updateData, - }); - - await (this.prisma as any).auditLog.create({ - data: { - entity: "task", - entityId: updated.id, - action: "UPDATE", - department: updated.department, - actor: "SYSTEM", - summary: "وضعیت تسک " + updated.code + " به " + body.status + " تغییر یافت.", - oldValues: { status: existing.status }, - newValues: { status: updated.status, note: body.logNote }, - }, - }); - - return { success: true, data: updated }; + throw new GoneException("Legacy orchestration mutations are retired. Orchestration v4 remains read-only; no replacement mutation is enabled."); } } diff --git a/backend/src/admin/legacy-orchestration.http.spec.ts b/backend/src/admin/legacy-orchestration.http.spec.ts new file mode 100644 index 00000000..af779f33 --- /dev/null +++ b/backend/src/admin/legacy-orchestration.http.spec.ts @@ -0,0 +1,52 @@ +import { Test } from '@nestjs/testing'; +import { INestApplication } from '@nestjs/common'; +import request from 'supertest'; +import { ApprovalsController } from './approvals.controller'; +import { DepartmentTasksController } from './department-tasks.controller'; +import { PrismaService } from '../prisma/prisma.service'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { RolesGuard } from '../common/guards/roles.guard'; + +describe('retired legacy orchestration HTTP boundary', () => { + let app: INestApplication; + const dbAccess = jest.fn(); + const prisma = new Proxy({}, {get: (_target, key) => { + // Nest inspects provider thenables and lifecycle hooks during setup. + if (["then", "onModuleInit", "onApplicationBootstrap", "onModuleDestroy", "beforeApplicationShutdown", "onApplicationShutdown"].includes(String(key))) return undefined; + dbAccess(key); + throw new Error('Persistence must not be accessed'); + }}); + const routes = [ + ['post', '/admin/approvals'], + ['put', '/admin/approvals/missing/decide'], + ['post', '/admin/department-tasks'], + ['put', '/admin/department-tasks/missing/status'], + ] as const; + beforeAll(async () => { + const module = await Test.createTestingModule({ + controllers: [ApprovalsController, DepartmentTasksController], + providers: [{provide: PrismaService, useValue: prisma}, RolesGuard], + }).overrideGuard(JwtAuthGuard).useValue({canActivate(context: any) { + const req = context.switchToHttp().getRequest(); + if (!req.headers.authorization) return false; + req.user = {id: 'test-admin', role: req.headers.authorization}; + return true; + }}).compile(); + app = module.createNestApplication(); + await app.init(); + dbAccess.mockClear(); + }); + beforeEach(() => dbAccess.mockClear()); + afterAll(async () => app?.close()); + it.each(routes)('%s %s returns explicit 410 for authorized callers before database access', async (method, path) => { + const response = await request(app.getHttpServer())[method](path) + .set('Authorization', 'Admin').send({decision:'APPROVED',status:'DONE'}).expect(410); + expect(response.body.message).toContain('retired'); + expect(dbAccess).not.toHaveBeenCalled(); + }); + it.each(routes)('%s %s retains anonymous and customer authorization guards', async (method, path) => { + await request(app.getHttpServer())[method](path).send({}).expect(403); + await request(app.getHttpServer())[method](path).set('Authorization','CUSTOMER').send({}).expect(403); + expect(dbAccess).not.toHaveBeenCalled(); + }); +}); diff --git a/frontend/admin-panel/src/pages/ApprovalsPage.test.tsx b/frontend/admin-panel/src/pages/ApprovalsPage.test.tsx index ad5fba30..94f91b75 100644 --- a/frontend/admin-panel/src/pages/ApprovalsPage.test.tsx +++ b/frontend/admin-panel/src/pages/ApprovalsPage.test.tsx @@ -1,6 +1,5 @@ import { fireEvent, render, screen, waitFor } from "@testing-library/react"; import { beforeEach, describe, expect, it, vi } from "vitest"; -import toast from "react-hot-toast"; import api from "../services/api"; import ApprovalsPage from "./ApprovalsPage"; diff --git a/frontend/admin-panel/src/pages/ApprovalsPage.tsx b/frontend/admin-panel/src/pages/ApprovalsPage.tsx index 6b6c491f..772cc526 100755 --- a/frontend/admin-panel/src/pages/ApprovalsPage.tsx +++ b/frontend/admin-panel/src/pages/ApprovalsPage.tsx @@ -1,9 +1,8 @@ -import React, { useState, useEffect, useMemo } from 'react'; +import { useState, useEffect, useMemo } from 'react'; import { CheckCircle2, XCircle, Play, - AlertTriangle, RefreshCw, DollarSign, ShoppingCart, @@ -14,10 +13,8 @@ import { MessageSquare, FileText, Search, - ArrowUpDown, ArrowUpRight, Briefcase, - Filter, CheckCheck, Building2, TrendingUp, @@ -31,12 +28,10 @@ import { ShieldCheck, Stethoscope, Cpu, - Headphones, MessageCircle, BarChart3, AlertCircle, Info, - Tag, Layers, Clock } from 'lucide-react'; @@ -114,8 +109,6 @@ function StructuredPayloadViewer({ payload }: { payload: any }) { // 6. Detect Competitor Intelligence / Benchmark Pattern const hasCompetitorBenchmark = ('key_findings' in payload || 'scraped_sources' in payload); - // 7. Detect B2B Clinical Targets Pattern - const hasB2BTargets = ('top_tier_targets' in payload || 'target_clinics_identified' in payload); return (
diff --git a/frontend/admin-panel/src/pages/AuditHistoryPage.tsx b/frontend/admin-panel/src/pages/AuditHistoryPage.tsx index 40824e35..758c94dc 100644 --- a/frontend/admin-panel/src/pages/AuditHistoryPage.tsx +++ b/frontend/admin-panel/src/pages/AuditHistoryPage.tsx @@ -1,20 +1,12 @@ -import React, { useState, useEffect } from 'react'; +import { useState, useEffect } from 'react'; import { History, Search, - Filter, RefreshCw, Clock, User, Database, - ArrowRight, - Shield, - Layers, - ChevronDown, - Calendar, - AlertCircle, Eye, - CheckCircle2 } from 'lucide-react'; import api from '../services/api'; diff --git a/frontend/admin-panel/src/pages/CompanyOrchestrationHQ.tsx b/frontend/admin-panel/src/pages/CompanyOrchestrationHQ.tsx index fbeb5422..ddff80c5 100644 --- a/frontend/admin-panel/src/pages/CompanyOrchestrationHQ.tsx +++ b/frontend/admin-panel/src/pages/CompanyOrchestrationHQ.tsx @@ -1,9 +1,6 @@ -import React, { useEffect, useState } from 'react'; +import { useEffect, useState } from 'react'; import { Building2, - CheckCircle2, - Clock, - AlertTriangle, ArrowUpRight, RefreshCw, ShieldCheck, @@ -13,7 +10,6 @@ import { Search, Headphones, Cpu, - Layers, Terminal, Activity, XCircle, diff --git a/frontend/admin-panel/src/pages/Dashboard.tsx b/frontend/admin-panel/src/pages/Dashboard.tsx index 8e30e10e..3ffebb9a 100755 --- a/frontend/admin-panel/src/pages/Dashboard.tsx +++ b/frontend/admin-panel/src/pages/Dashboard.tsx @@ -1,4 +1,4 @@ -import { Activity, DollarSign, ShoppingCart, Users, ShieldAlert, ArrowLeft, History, Briefcase, Clock, Database } from "lucide-react"; +import { Activity, DollarSign, ShoppingCart, Users, ShieldAlert, ArrowLeft, History, Briefcase, Database } from "lucide-react"; import { useEffect, useState } from "react"; import { Link } from "react-router-dom"; import { CartesianGrid, Cell, Line, LineChart, Pie, PieChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts"; diff --git a/frontend/admin-panel/src/pages/ManagerActionsPage.tsx b/frontend/admin-panel/src/pages/ManagerActionsPage.tsx index 668e1ad8..a99e0316 100644 --- a/frontend/admin-panel/src/pages/ManagerActionsPage.tsx +++ b/frontend/admin-panel/src/pages/ManagerActionsPage.tsx @@ -1,4 +1,4 @@ -import React, { useState, useEffect, useMemo } from 'react'; +import { useState, useEffect, useMemo } from 'react'; import { Building2, Briefcase, diff --git a/frontend/admin-panel/src/pages/MonitoringPage.test.tsx b/frontend/admin-panel/src/pages/MonitoringPage.test.tsx index adb0f9f7..42321e27 100644 --- a/frontend/admin-panel/src/pages/MonitoringPage.test.tsx +++ b/frontend/admin-panel/src/pages/MonitoringPage.test.tsx @@ -15,6 +15,12 @@ describe('measured monitoring',()=>{ expect(screen.queryByText('Production')).not.toBeInTheDocument(); expect(screen.queryByText(/۱۴ روز/)).not.toBeInTheDocument(); }); + it.each([0,125])('accepts the real flat SMS success response with credit %s',async credit=>{ + vi.mocked(api.get).mockResolvedValue({data:{success:true,credit,message:'اعتبار پیامک'}}); + render(); + expect(await screen.findByText(credit.toLocaleString('fa-IR')+' پیامک')).toBeInTheDocument(); + expect(screen.queryByText(/Invalid measurement response/)).not.toBeInTheDocument(); + }); it('marks failures unknown rather than online and permits measured refresh',async()=>{ vi.mocked(api.get).mockRejectedValue(new Error('connection refused')); render();expect(await screen.findAllByText(/connection refused/)).toHaveLength(3); diff --git a/frontend/admin-panel/src/pages/MonitoringPage.tsx b/frontend/admin-panel/src/pages/MonitoringPage.tsx index a96c3306..60ef97dd 100644 --- a/frontend/admin-panel/src/pages/MonitoringPage.tsx +++ b/frontend/admin-panel/src/pages/MonitoringPage.tsx @@ -10,7 +10,7 @@ export default function MonitoringPage() { const refresh=useCallback(async()=>{ if(inFlight.current)return;inFlight.current=true;setLoading(true); const results=await Promise.all(endpoints.map(async url=>{ - try {const {data:raw}=await api.get(url);const data=raw?.success===true?raw.data:raw; + try {const {data:raw}=await api.get(url);const data=raw?.success===true&&Object.hasOwn(raw,'data')?raw.data:raw; if(!data||typeof data!=='object'||raw?.success===false)throw new Error('Invalid measurement response'); return {data,error:null,observedAt:new Date().toISOString()}; }catch(e){return {data:null,error:e instanceof Error?e.message:'Request failed',observedAt:new Date().toISOString()}} diff --git a/frontend/admin-panel/src/pages/OrchestrationCommandCenter.test.tsx b/frontend/admin-panel/src/pages/OrchestrationCommandCenter.test.tsx index 01f196a4..99105576 100644 --- a/frontend/admin-panel/src/pages/OrchestrationCommandCenter.test.tsx +++ b/frontend/admin-panel/src/pages/OrchestrationCommandCenter.test.tsx @@ -20,6 +20,14 @@ describe('command center', () => { fireEvent.click(screen.getByRole('button',{name:'Agents & departments'})); expect(await screen.findByRole('alert')).toHaveTextContent('Unavailable'); }); + it('labels deliberately omitted scope metadata unavailable, not immutable scope',async()=>{ + const {metadata:_metadata,...safeTask}=task; + vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/tasks')?[safeTask]:safeTask})); + render(); + fireEvent.click(await screen.findByRole('button',{name:'Bounded SEO audit'})); + expect(await screen.findByText('Scope / acceptance criteria unavailable — omitted by the safe backend projection.')).toBeInTheDocument(); + expect(screen.queryByText('Immutable scope / acceptance criteria')).not.toBeInTheDocument(); + }); it('requires explicit confirmation and expiry; retains idempotency across failed retry', async () => { vi.mocked(api.post).mockRejectedValue(new Error('network failure')); render(); diff --git a/frontend/admin-panel/src/pages/OrchestrationCommandCenter.tsx b/frontend/admin-panel/src/pages/OrchestrationCommandCenter.tsx index 8675078e..f0ac2f76 100644 --- a/frontend/admin-panel/src/pages/OrchestrationCommandCenter.tsx +++ b/frontend/admin-panel/src/pages/OrchestrationCommandCenter.tsx @@ -59,7 +59,7 @@ export default function OrchestrationCommandCenter() { {!loading&&!error&&!tasks.length&&

No tasks returned by backend.

}
{['Task','Department','State','Mode','Budget cap (cents)','Version'].map(h=>)}{filtered.map(t=>)}
{h}
{t.department}{t.state}{t.operationMode}{t.budgetLimitCents??'Unknown'}{t.version}
} - {selected&&

{selected.title} · v{selected.version}

Immutable scope / acceptance criteria

+ {selected&&

{selected.title} · v{selected.version}

{selected.metadata?

Backend-reported scope / acceptance criteria

:

Scope / acceptance criteria unavailable — omitted by the safe backend projection.

}

Server-authorized actions

{!selected.availableActions.length&&

No actions advertised. Read-only; the browser does not infer transitions.

}
{selected.availableActions.map(a=>)}

Immutable approval decisions

Runs & registered artifacts

{!selected.runs?.length&&

No registered runs.

}{selected.runs?.map(r=>

{r.id} · {r.status}

Commit: {r.commitSha} · Environment: {r.environment}

{r.artifacts.map(a=>)}
)} diff --git a/frontend/admin-panel/src/pages/Orders.tsx b/frontend/admin-panel/src/pages/Orders.tsx index c2e322e7..f681c6c9 100644 --- a/frontend/admin-panel/src/pages/Orders.tsx +++ b/frontend/admin-panel/src/pages/Orders.tsx @@ -37,6 +37,7 @@ export interface OrderItem { priceValue?: number; quantity?: number; product?: { + requiresRx?: boolean; id?: string; nameFa?: string; name?: string; diff --git a/frontend/admin-panel/src/pages/SymptomsPage.test.tsx b/frontend/admin-panel/src/pages/SymptomsPage.test.tsx new file mode 100644 index 00000000..1c933c9b --- /dev/null +++ b/frontend/admin-panel/src/pages/SymptomsPage.test.tsx @@ -0,0 +1,24 @@ +import { fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { MemoryRouter } from "react-router-dom"; +import { beforeEach, expect, it, vi } from "vitest"; +import api from "../services/api"; +import SymptomsPage from "./SymptomsPage"; +vi.mock("../services/api", () => ({default: {get: vi.fn(), delete: vi.fn()}})); +beforeEach(() => { + vi.resetAllMocks(); + vi.mocked(api.get).mockResolvedValue({data: {data: [{id:"symptom-1", name:"Anemia", slug:"anemia"}], meta:{lastPage:1}}}); + vi.mocked(api.delete).mockResolvedValue({data:{}}); +}); +it("shows deletion consequences and cancels without deleting, then confirms the selected symptom", async () => { + render(); + await screen.findByText("Anemia"); + fireEvent.click(screen.getByTitle("حذف")); + expect(screen.getByText(/با حذف این علامت، ارتباط آن/)).toBeInTheDocument(); + fireEvent.click(screen.getByRole("button",{name:"لغو"})); + expect(screen.queryByText(/با حذف این علامت، ارتباط آن/)).not.toBeInTheDocument(); + expect(api.delete).not.toHaveBeenCalled(); + fireEvent.click(screen.getByTitle("حذف")); + fireEvent.click(screen.getByRole("button",{name:"تایید"})); + await waitFor(() => expect(api.delete).toHaveBeenCalledWith("/admin/symptoms/symptom-1")); + await waitFor(() => expect(screen.queryByText(/با حذف این علامت، ارتباط آن/)).not.toBeInTheDocument()); +}); diff --git a/frontend/admin-panel/src/pages/SymptomsPage.tsx b/frontend/admin-panel/src/pages/SymptomsPage.tsx index fa41dc63..ee9587cf 100644 --- a/frontend/admin-panel/src/pages/SymptomsPage.tsx +++ b/frontend/admin-panel/src/pages/SymptomsPage.tsx @@ -22,7 +22,7 @@ export interface Symptom { } export default function SymptomsPage() { - const [searchParams, setSearchParams] = useSearchParams(); + const [searchParams] = useSearchParams(); const [symptoms, setSymptoms] = useState([]); const [isLoading, setIsLoading] = useState(true); const [search, setSearch] = useState(() => searchParams.get('search') || ''); @@ -311,10 +311,10 @@ export default function SymptomsPage() { {/* Delete Confirmation */} setDeleteTargetId(null)} + onCancel={() => setDeleteTargetId(null)} onConfirm={handleDelete} title="حذف علامت بالینی" - description="با حذف این علامت، ارتباط آن از تمام محصولات کاتالوگ نیز به طور خودکار حذف خواهد شد. آیا مطمئن هستید؟" + message="با حذف این علامت، ارتباط آن از تمام محصولات کاتالوگ نیز به طور خودکار حذف خواهد شد. آیا مطمئن هستید؟" />
); diff --git a/frontend/admin-panel/src/pages/TasksManagementPage.tsx b/frontend/admin-panel/src/pages/TasksManagementPage.tsx index e279a97b..50a64717 100644 --- a/frontend/admin-panel/src/pages/TasksManagementPage.tsx +++ b/frontend/admin-panel/src/pages/TasksManagementPage.tsx @@ -1,4 +1,4 @@ -import React, { useState, useEffect } from 'react'; +import { useState, useEffect } from 'react'; import { Search, RefreshCw, @@ -7,10 +7,6 @@ import { ChevronDown, ChevronLeft, ChevronRight, - Play, - CheckCircle, - Clock, - Filter } from 'lucide-react'; import api from '../services/api'; import toast from 'react-hot-toast'; diff --git a/frontend/admin-panel/vite.config.ts b/frontend/admin-panel/vite.config.ts index 5b38569d..23e513a7 100644 --- a/frontend/admin-panel/vite.config.ts +++ b/frontend/admin-panel/vite.config.ts @@ -1,4 +1,4 @@ -import { defineConfig } from 'vite' +import { defineConfig } from 'vitest/config' import react from '@vitejs/plugin-react' // https://vite.dev/config/