Compare commits
43
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
59d79a6f32 | ||
|
|
e6c705cef7 | ||
|
|
19c4bb451d | ||
|
|
f71b79a17f | ||
|
|
e3eb7ca205 | ||
|
|
2e54163d9e | ||
|
|
344f79039f | ||
|
|
02fe634944 | ||
|
|
7b1f64d727 | ||
|
|
d53e38a48f | ||
|
|
ee90284129 | ||
|
|
71dccbc590 | ||
|
|
bf082c59fe | ||
|
|
1651fd00a2 | ||
|
|
f59dd6ebec | ||
|
|
2f178db2c6 | ||
|
|
28485d51f7 | ||
|
|
24362b89d7 | ||
|
|
159e4a4cbf | ||
|
|
13a7919c91 | ||
|
|
d670690816 | ||
|
|
62c58c7c89 | ||
|
|
0b4d9a8463 | ||
|
|
51ca8c7e34 | ||
|
|
64047054b8 | ||
|
|
3f5258a76c | ||
|
|
3b93308b71 | ||
|
|
bf53f2e17c | ||
|
|
c2eca11a3b | ||
|
|
4c3f8de1fb | ||
|
|
b3e1869724 | ||
|
|
624f58c723 | ||
|
|
aedc0f6979 | ||
|
|
1e53ceeda6 | ||
|
|
f08ed0c22c | ||
|
|
ee0f877d97 | ||
|
|
b3d4e08914 | ||
|
|
ec9dd83e77 | ||
|
|
4930e2a870 | ||
|
|
5e21cc76fc | ||
|
|
529110a693 | ||
|
|
0b5f2a88cc | ||
|
|
ff6f04fe46 |
No files matched your search
@@ -2,6 +2,7 @@ FROM node:20-alpine AS builder
|
||||
USER root
|
||||
RUN http_proxy=http://172.17.0.1:8888 https_proxy=http://172.17.0.1:8888 apk add --no-cache openssl || apk add --no-cache openssl || true
|
||||
WORKDIR /app
|
||||
ENV PRISMA_HIDE_UPDATE_MESSAGE=true
|
||||
ENV PRISMA_SKIP_POSTINSTALL_GENERATE=true
|
||||
ENV PRISMA_ENGINES_MIRROR=https://registry.npmmirror.com/-/binary/prisma
|
||||
ENV DISABLE_OPENCOLLECTIVE=1
|
||||
@@ -33,6 +34,7 @@ USER root
|
||||
RUN http_proxy=http://172.17.0.1:8888 https_proxy=http://172.17.0.1:8888 apk add --no-cache openssl || apk add --no-cache openssl || true
|
||||
RUN mkdir -p /app/uploads && chown node:node /app/uploads
|
||||
WORKDIR /app
|
||||
ENV PRISMA_HIDE_UPDATE_MESSAGE=true
|
||||
COPY --chown=node:node --from=builder /app/package*.json ./
|
||||
COPY --chown=node:node --from=builder /app/tsconfig.json ./tsconfig.json
|
||||
COPY --chown=node:node --from=builder /app/eslint.config.mjs ./eslint.config.mjs
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
ALTER TABLE blogs ADD COLUMN IF NOT EXISTS author_team VARCHAR(200);
|
||||
ALTER TABLE blogs ADD COLUMN IF NOT EXISTS author_role VARCHAR(200);
|
||||
ALTER TABLE blogs ADD COLUMN IF NOT EXISTS content_updated_at TIMESTAMPTZ;
|
||||
@@ -0,0 +1,15 @@
|
||||
-- A server-issued attestation is persisted atomically with a DONE transition.
|
||||
CREATE TABLE "task_completion_attestations" (
|
||||
"id" UUID NOT NULL,
|
||||
"task_id" UUID NOT NULL,
|
||||
"artifact_type" VARCHAR(20) NOT NULL,
|
||||
"artifact_id" UUID NOT NULL,
|
||||
"artifact_url" VARCHAR(255) NOT NULL,
|
||||
"verifier" VARCHAR(50) NOT NULL,
|
||||
"verified_at" TIMESTAMPTZ NOT NULL,
|
||||
CONSTRAINT "task_completion_attestations_pkey" PRIMARY KEY ("id"),
|
||||
CONSTRAINT "task_completion_attestations_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "department_tasks"("id") ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT "task_completion_attestations_artifact_type_check" CHECK ("artifact_type" = 'BLOG'),
|
||||
CONSTRAINT "task_completion_attestations_verifier_check" CHECK ("verifier" = 'SERVER_ARTIFACT_VERIFIER')
|
||||
);
|
||||
CREATE INDEX "task_completion_attestations_task_id_idx" ON "task_completion_attestations"("task_id");
|
||||
@@ -179,6 +179,8 @@ model Blog {
|
||||
content String @db.Text
|
||||
excerpt String? @db.Text
|
||||
authorId String? @map("author_id") @db.Uuid
|
||||
authorTeam String? @map("author_team") @db.VarChar(200)
|
||||
authorRole String? @map("author_role") @db.VarChar(200)
|
||||
categoryId String? @map("category_id") @db.Uuid
|
||||
imageUrl String? @map("image_url") @db.Text
|
||||
imageAlt String? @map("image_alt") @db.VarChar(255)
|
||||
@@ -198,6 +200,7 @@ model Blog {
|
||||
isPublished Boolean @default(true) @map("is_published")
|
||||
publishedAt DateTime? @map("published_at") @db.Timestamptz()
|
||||
scheduledAt DateTime? @map("scheduled_at") @db.Timestamptz()
|
||||
contentUpdatedAt DateTime? @map("content_updated_at") @db.Timestamptz()
|
||||
readingTime Int @default(3) @map("reading_time")
|
||||
featured Boolean @default(false)
|
||||
allowComments Boolean @default(true) @map("allow_comments")
|
||||
@@ -1064,7 +1067,22 @@ model AuditLog {
|
||||
// ------------------------------------------------------------------------------
|
||||
// 7. DepartmentTask (Autonomous Corporate Task & Kanban Manager)
|
||||
// ------------------------------------------------------------------------------
|
||||
model TaskCompletionAttestation {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
taskId String @map("task_id") @db.Uuid
|
||||
artifactType String @map("artifact_type") @db.VarChar(20)
|
||||
artifactId String @map("artifact_id") @db.Uuid
|
||||
artifactUrl String @map("artifact_url") @db.VarChar(255)
|
||||
verifier String @db.VarChar(50)
|
||||
verifiedAt DateTime @map("verified_at") @db.Timestamptz()
|
||||
task DepartmentTask @relation(fields: [taskId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([taskId])
|
||||
@@map("task_completion_attestations")
|
||||
}
|
||||
|
||||
model DepartmentTask {
|
||||
completionAttestations TaskCompletionAttestation[]
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
code String @unique @db.VarChar(50)
|
||||
department String @db.VarChar(50) // devops, seo, content, vet, commerce, pmo
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -229,6 +229,15 @@ describe("BlogsController (Admin)", () => {
|
||||
expect(result).toEqual({ success: true, data: createdBlog });
|
||||
});
|
||||
|
||||
it("propagates create validation failures", async () => {
|
||||
const req = { user: { id: "admin-user-id" } };
|
||||
const body = { title: "Bad date", contentUpdatedAt: "invalid", createdAt: "2000-01-01" };
|
||||
mockBlogsService.createBlog.mockRejectedValueOnce(new Error("Invalid contentUpdatedAt"));
|
||||
|
||||
await expect(controller.createBlog(body, req)).rejects.toThrow("Invalid contentUpdatedAt");
|
||||
expect(service.createBlog).toHaveBeenCalledWith(body, req.user.id);
|
||||
});
|
||||
|
||||
it("updateBlog should update blog details and return success: true", async () => {
|
||||
const blogId = "blog-10";
|
||||
const body = {
|
||||
@@ -244,6 +253,14 @@ describe("BlogsController (Admin)", () => {
|
||||
expect(result).toEqual({ success: true, data: updatedBlog });
|
||||
});
|
||||
|
||||
it("propagates invalid content timestamp rejection without accepting createdAt", async () => {
|
||||
const body = { contentUpdatedAt: "invalid", createdAt: "2000-01-01" };
|
||||
mockBlogsService.updateBlog.mockRejectedValueOnce(new Error("Invalid contentUpdatedAt"));
|
||||
|
||||
await expect(controller.updateBlog("blog-10", body)).rejects.toThrow("Invalid contentUpdatedAt");
|
||||
expect(service.updateBlog).toHaveBeenCalledWith("blog-10", body);
|
||||
});
|
||||
|
||||
it("deleteBlog should delete blog and return success: true", async () => {
|
||||
const blogId = "blog-10";
|
||||
mockBlogsService.deleteBlog.mockResolvedValue(undefined);
|
||||
|
||||
@@ -203,6 +203,50 @@ describe("Admin BlogsService", () => {
|
||||
expect(result).toEqual(createdBlog);
|
||||
});
|
||||
|
||||
it("allowlists create fields and blocks server-owned and unknown fields", async () => {
|
||||
mockPrisma.blog.create.mockResolvedValue({ id: "created", slug: "safe-post" });
|
||||
|
||||
await service.createBlog(
|
||||
{
|
||||
title: "Safe post",
|
||||
slug: "safe-post",
|
||||
content: "Safe content",
|
||||
id: "client-id",
|
||||
createdAt: "2000-01-01T00:00:00.000Z",
|
||||
updatedAt: "2000-01-01T00:00:00.000Z",
|
||||
viewCount: 999999,
|
||||
serverOwned: "must-not-pass",
|
||||
},
|
||||
"user-admin-1",
|
||||
);
|
||||
|
||||
const payload = mockPrisma.blog.create.mock.calls[0][0].data;
|
||||
expect(payload).toEqual(expect.objectContaining({
|
||||
title: "Safe post",
|
||||
slug: "safe-post",
|
||||
content: "Safe content",
|
||||
}));
|
||||
expect(payload).not.toHaveProperty("id");
|
||||
expect(payload).not.toHaveProperty("createdAt");
|
||||
expect(payload).not.toHaveProperty("updatedAt");
|
||||
expect(payload).not.toHaveProperty("viewCount");
|
||||
expect(payload).not.toHaveProperty("serverOwned");
|
||||
});
|
||||
|
||||
it.each([
|
||||
["contentUpdatedAt", { contentUpdatedAt: "not-a-date" }, "Invalid contentUpdatedAt"],
|
||||
["publishedAt", { publishedAt: "not-a-date" }, "Invalid publishedAt"],
|
||||
["scheduledAt", { scheduledAt: "not-a-date" }, "Invalid scheduledAt"],
|
||||
])("rejects invalid explicit %s", async (_field, timestamps, message) => {
|
||||
await expect(
|
||||
service.createBlog(
|
||||
{ title: "Bad date", slug: "bad-date", content: "Content", ...timestamps },
|
||||
"user-admin-1",
|
||||
),
|
||||
).rejects.toThrow(message);
|
||||
expect(mockPrisma.blog.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should create a SCHEDULED blog if scheduledAt is in the future", async () => {
|
||||
const futureDate = new Date(Date.now() + 86400000).toISOString();
|
||||
const blogData = {
|
||||
@@ -274,6 +318,81 @@ describe("Admin BlogsService", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("material freshness and scheduled publishing", () => {
|
||||
it("sets contentUpdatedAt intentionally and never rewrites createdAt", async () => {
|
||||
mockPrisma.blog.findUnique.mockResolvedValue({ id: "b1", slug: "post", createdAt: new Date("2025-01-01") });
|
||||
mockPrisma.blog.update.mockResolvedValue({ id: "b1", slug: "post" });
|
||||
await service.updateBlog("b1", { title: "Material edit", markContentUpdated: true });
|
||||
const payload = mockPrisma.blog.update.mock.calls[0][0].data;
|
||||
expect(payload.contentUpdatedAt).toEqual(expect.any(Date));
|
||||
expect(payload).not.toHaveProperty("markContentUpdated");
|
||||
expect(payload).not.toHaveProperty("createdAt");
|
||||
});
|
||||
it("automatically marks freshness when material article content changes", async () => {
|
||||
mockPrisma.blog.findUnique.mockResolvedValue({ id: "b1", slug: "post", content: "Old content" });
|
||||
mockPrisma.blog.update.mockResolvedValue({ id: "b1", slug: "post" });
|
||||
await service.updateBlog("b1", { content: "Meaningfully revised content" });
|
||||
expect(mockPrisma.blog.update.mock.calls[0][0].data.contentUpdatedAt).toEqual(expect.any(Date));
|
||||
});
|
||||
it("does not mark freshness for attribution-only changes", async () => {
|
||||
mockPrisma.blog.findUnique.mockResolvedValue({ id: "b1", slug: "post", content: "Same content" });
|
||||
mockPrisma.blog.update.mockResolvedValue({ id: "b1", slug: "post" });
|
||||
await service.updateBlog("b1", { authorTeam: "Clinical team", authorRole: "Review" });
|
||||
expect(mockPrisma.blog.update.mock.calls[0][0].data).not.toHaveProperty("contentUpdatedAt");
|
||||
});
|
||||
it("allows explicitly clearing contentUpdatedAt", async () => {
|
||||
mockPrisma.blog.findUnique.mockResolvedValue({ id: "b1", slug: "post" });
|
||||
mockPrisma.blog.update.mockResolvedValue({ id: "b1", slug: "post" });
|
||||
await service.updateBlog("b1", { contentUpdatedAt: null });
|
||||
expect(mockPrisma.blog.update.mock.calls[0][0].data.contentUpdatedAt).toBeNull();
|
||||
});
|
||||
it("publishes due posts without rewriting createdAt", async () => {
|
||||
const scheduledAt = new Date("2025-02-01T10:00:00Z");
|
||||
mockPrisma.blog.findMany.mockResolvedValue([{ id: "b1", slug: "post", title: "Post", scheduledAt }]);
|
||||
mockPrisma.blog.update.mockResolvedValue({});
|
||||
await service.publishDueScheduledBlogs();
|
||||
expect(mockPrisma.blog.update).toHaveBeenCalledWith({ where: { id: "b1" }, data: { status: "PUBLISHED", isPublished: true, publishedAt: scheduledAt } });
|
||||
});
|
||||
});
|
||||
|
||||
describe("updateBlog security and freshness validation", () => {
|
||||
beforeEach(() => {
|
||||
mockPrisma.blog.findUnique.mockResolvedValue({ id: "blog-1", slug: "safe" });
|
||||
mockPrisma.blog.update.mockResolvedValue({ id: "blog-1", slug: "safe" });
|
||||
});
|
||||
|
||||
it("allowlists mutable fields and ignores createdAt and unrecognized fields", async () => {
|
||||
await service.updateBlog("blog-1", {
|
||||
title: "Allowed title",
|
||||
createdAt: "2000-01-01T00:00:00.000Z",
|
||||
serverOwned: "must-not-pass",
|
||||
});
|
||||
|
||||
const payload = mockPrisma.blog.update.mock.calls[0][0].data;
|
||||
expect(payload.title).toBe("Allowed title");
|
||||
expect(payload).not.toHaveProperty("createdAt");
|
||||
expect(payload).not.toHaveProperty("serverOwned");
|
||||
});
|
||||
|
||||
it("rejects an invalid explicit contentUpdatedAt", async () => {
|
||||
await expect(
|
||||
service.updateBlog("blog-1", { contentUpdatedAt: "not-a-date" }),
|
||||
).rejects.toThrow("Invalid contentUpdatedAt");
|
||||
expect(mockPrisma.blog.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("preserves explicit null clearing and markContentUpdated precedence", async () => {
|
||||
await service.updateBlog("blog-1", { contentUpdatedAt: null });
|
||||
expect(mockPrisma.blog.update.mock.calls[0][0].data.contentUpdatedAt).toBeNull();
|
||||
|
||||
await service.updateBlog("blog-1", {
|
||||
contentUpdatedAt: "not-a-date",
|
||||
markContentUpdated: true,
|
||||
});
|
||||
expect(mockPrisma.blog.update.mock.calls[1][0].data.contentUpdatedAt).toEqual(expect.any(Date));
|
||||
});
|
||||
});
|
||||
|
||||
describe("deleteBlog", () => {
|
||||
it("should throw NotFoundException if blog not found", async () => {
|
||||
mockPrisma.blog.findUnique.mockResolvedValue(null);
|
||||
@@ -468,7 +587,6 @@ describe("Admin BlogsService", () => {
|
||||
status: "PUBLISHED",
|
||||
isPublished: true,
|
||||
publishedAt: scheduledDate,
|
||||
createdAt: scheduledDate,
|
||||
},
|
||||
});
|
||||
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith(
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
OnModuleInit,
|
||||
@@ -141,16 +142,31 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
|
||||
async createBlog(data: any, currentUserId: string) {
|
||||
const {
|
||||
tags,
|
||||
tagNames,
|
||||
categoryId,
|
||||
authorId,
|
||||
publishedAt,
|
||||
scheduledAt,
|
||||
readingTime,
|
||||
...rest
|
||||
markContentUpdated,
|
||||
contentUpdatedAt,
|
||||
} = data;
|
||||
|
||||
const parseOptionalDate = (value: unknown, field: string): Date | null => {
|
||||
if (value === undefined || value === null || value === "") return null;
|
||||
const parsed = new Date(value as string | number | Date);
|
||||
if (!Number.isFinite(parsed.getTime())) {
|
||||
throw new BadRequestException(`Invalid ${field}`);
|
||||
}
|
||||
return parsed;
|
||||
};
|
||||
|
||||
const parsedPublishedAt = parseOptionalDate(publishedAt, "publishedAt");
|
||||
const parsedScheduledAt = parseOptionalDate(scheduledAt, "scheduledAt");
|
||||
const parsedContentUpdatedAt = markContentUpdated
|
||||
? new Date()
|
||||
: parseOptionalDate(contentUpdatedAt, "contentUpdatedAt");
|
||||
|
||||
// Connect or create tags
|
||||
const tagConnectOrCreate = [];
|
||||
if (Array.isArray(tagNames) && tagNames.length > 0) {
|
||||
@@ -171,13 +187,12 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
|
||||
const targetAuthorId = authorId || currentUserId;
|
||||
const now = new Date();
|
||||
const parsedScheduledAt = scheduledAt ? new Date(scheduledAt) : null;
|
||||
const isFutureSchedule = parsedScheduledAt && parsedScheduledAt > now;
|
||||
|
||||
let finalStatus = rest.status || "PUBLISHED";
|
||||
let finalStatus = data.status || "PUBLISHED";
|
||||
let finalIsPublished =
|
||||
rest.isPublished !== undefined ? rest.isPublished : true;
|
||||
let finalPublishedAt = publishedAt ? new Date(publishedAt) : null;
|
||||
data.isPublished !== undefined ? data.isPublished : true;
|
||||
let finalPublishedAt = parsedPublishedAt;
|
||||
|
||||
if (isFutureSchedule) {
|
||||
finalStatus = "SCHEDULED";
|
||||
@@ -191,19 +206,45 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
finalPublishedAt = now;
|
||||
}
|
||||
|
||||
const createPayload: Prisma.BlogCreateInput = {
|
||||
...rest,
|
||||
const createPayload = {
|
||||
title: data.title,
|
||||
slug: data.slug,
|
||||
content: data.content,
|
||||
excerpt: data.excerpt,
|
||||
authorTeam: data.authorTeam,
|
||||
authorRole: data.authorRole,
|
||||
imageUrl: data.imageUrl,
|
||||
imageAlt: data.imageAlt,
|
||||
imageCaption: data.imageCaption,
|
||||
metaTitle: data.metaTitle,
|
||||
metaDescription: data.metaDescription,
|
||||
keywords: data.keywords,
|
||||
focusKeywords: data.focusKeywords,
|
||||
canonicalUrl: data.canonicalUrl,
|
||||
noIndex: data.noIndex,
|
||||
noFollow: data.noFollow,
|
||||
schemaType: data.schemaType,
|
||||
ogTitle: data.ogTitle,
|
||||
ogDescription: data.ogDescription,
|
||||
ogImage: data.ogImage,
|
||||
status: finalStatus,
|
||||
isPublished: finalIsPublished,
|
||||
readingTime: readingTime ? Number(readingTime) : 3,
|
||||
featured: data.featured,
|
||||
allowComments: data.allowComments,
|
||||
showOnHome: data.showOnHome,
|
||||
homeDisplayMode: data.homeDisplayMode,
|
||||
relatedProductIds: data.relatedProductIds,
|
||||
relatedBlogIds: data.relatedBlogIds,
|
||||
readingTime: readingTime !== undefined ? Number(readingTime) : 3,
|
||||
publishedAt: finalPublishedAt,
|
||||
scheduledAt: parsedScheduledAt,
|
||||
contentUpdatedAt: parsedContentUpdatedAt,
|
||||
author: { connect: { id: targetAuthorId } },
|
||||
...(categoryId ? { category: { connect: { id: categoryId } } } : {}),
|
||||
...(tagConnectOrCreate.length > 0
|
||||
? { tags: { connectOrCreate: tagConnectOrCreate } }
|
||||
: {}),
|
||||
};
|
||||
} satisfies Prisma.BlogCreateInput;
|
||||
|
||||
const created = await this.prisma.blog.create({
|
||||
data: createPayload,
|
||||
@@ -223,19 +264,83 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
if (!blog) throw new NotFoundException("Blog not found");
|
||||
|
||||
const {
|
||||
tags,
|
||||
tagNames,
|
||||
categoryId,
|
||||
authorId,
|
||||
publishedAt,
|
||||
scheduledAt,
|
||||
readingTime,
|
||||
...rest
|
||||
markContentUpdated,
|
||||
contentUpdatedAt,
|
||||
} = data;
|
||||
|
||||
const mutableScalarFields = [
|
||||
"title",
|
||||
"slug",
|
||||
"content",
|
||||
"excerpt",
|
||||
"authorTeam",
|
||||
"authorRole",
|
||||
"imageUrl",
|
||||
"imageAlt",
|
||||
"imageCaption",
|
||||
"metaTitle",
|
||||
"metaDescription",
|
||||
"keywords",
|
||||
"focusKeywords",
|
||||
"canonicalUrl",
|
||||
"noIndex",
|
||||
"noFollow",
|
||||
"schemaType",
|
||||
"ogTitle",
|
||||
"ogDescription",
|
||||
"ogImage",
|
||||
"status",
|
||||
"isPublished",
|
||||
"featured",
|
||||
"allowComments",
|
||||
"showOnHome",
|
||||
"homeDisplayMode",
|
||||
"relatedProductIds",
|
||||
"relatedBlogIds",
|
||||
] as const;
|
||||
const updatePayload: Prisma.BlogUpdateInput = {};
|
||||
for (const field of mutableScalarFields) {
|
||||
if (data[field] !== undefined) {
|
||||
(updatePayload as Record<string, unknown>)[field] = data[field];
|
||||
}
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const updatePayload: Prisma.BlogUpdateInput = {
|
||||
...rest,
|
||||
const materialContentFields = [
|
||||
"title",
|
||||
"content",
|
||||
"excerpt",
|
||||
"imageUrl",
|
||||
"imageAlt",
|
||||
"imageCaption",
|
||||
] as const;
|
||||
const hasMaterialContentChange = materialContentFields.some(
|
||||
(field) => data[field] !== undefined && data[field] !== blog[field],
|
||||
);
|
||||
if (markContentUpdated || (contentUpdatedAt === undefined && hasMaterialContentChange)) {
|
||||
(updatePayload as Record<string, unknown>).contentUpdatedAt = now;
|
||||
} else if (contentUpdatedAt !== undefined) {
|
||||
if (contentUpdatedAt === null || contentUpdatedAt === "") {
|
||||
(updatePayload as Record<string, unknown>).contentUpdatedAt = null;
|
||||
} else {
|
||||
const parsedContentUpdatedAt = new Date(contentUpdatedAt);
|
||||
if (!Number.isFinite(parsedContentUpdatedAt.getTime())) {
|
||||
throw new BadRequestException("Invalid contentUpdatedAt");
|
||||
}
|
||||
(updatePayload as Record<string, unknown>).contentUpdatedAt = parsedContentUpdatedAt;
|
||||
}
|
||||
}
|
||||
|
||||
Object.assign(updatePayload, {
|
||||
...(readingTime !== undefined
|
||||
? { readingTime: Number(readingTime) }
|
||||
: {}),
|
||||
...(readingTime !== undefined
|
||||
? { readingTime: Number(readingTime) }
|
||||
: {}),
|
||||
@@ -245,7 +350,7 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
? { category: { connect: { id: categoryId } } }
|
||||
: { category: { disconnect: true } }
|
||||
: {}),
|
||||
};
|
||||
});
|
||||
|
||||
if (scheduledAt !== undefined) {
|
||||
const parsedScheduledAt = scheduledAt ? new Date(scheduledAt) : null;
|
||||
@@ -259,7 +364,6 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
updatePayload.status = "PUBLISHED";
|
||||
updatePayload.isPublished = true;
|
||||
updatePayload.publishedAt = parsedScheduledAt;
|
||||
updatePayload.createdAt = parsedScheduledAt;
|
||||
}
|
||||
} else if (publishedAt !== undefined) {
|
||||
updatePayload.publishedAt = publishedAt ? new Date(publishedAt) : null;
|
||||
@@ -472,7 +576,6 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
status: "PUBLISHED",
|
||||
isPublished: true,
|
||||
publishedAt: publishDate,
|
||||
createdAt: publishDate,
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import { BadRequestException } from "@nestjs/common";
|
||||
import { assertTaskCanComplete } from "./department-task-completion.policy";
|
||||
|
||||
describe("department task completion policy", () => {
|
||||
it("rejects model-only output without a live deliverable", () => {
|
||||
expect(() =>
|
||||
assertTaskCanComplete({
|
||||
deliverableUrl: null,
|
||||
acceptanceCriteria: { criteria: ["live URL responds 200"] },
|
||||
executionLogs: [{ status: "COMPLETED_BY_AGENT" }],
|
||||
}),
|
||||
).toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it("rejects completion without acceptance criteria", () => {
|
||||
expect(() =>
|
||||
assertTaskCanComplete({
|
||||
deliverableUrl: "https://canina.ir/blog/verified",
|
||||
acceptanceCriteria: null,
|
||||
executionLogs: [{ status: "QA_PASSED" }],
|
||||
}),
|
||||
).toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it("rejects completion without QA evidence", () => {
|
||||
expect(() =>
|
||||
assertTaskCanComplete({
|
||||
deliverableUrl: "https://canina.ir/blog/verified",
|
||||
acceptanceCriteria: { criteria: ["HTTP 200"] },
|
||||
executionLogs: [{ status: "COMPLETED_BY_AGENT" }],
|
||||
}),
|
||||
).toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it("does not trust caller-spoofable QA evidence even with URL and criteria", () => {
|
||||
expect(() => assertTaskCanComplete({
|
||||
deliverableUrl: "https://canina.ir/blog/verified",
|
||||
acceptanceCriteria: { criteria: ["HTTP 200"] },
|
||||
executionLogs: [{ status: "QA_PASSED" }],
|
||||
})).toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it("requires matching server-issued artifact identity", () => {
|
||||
expect(() => assertTaskCanComplete({
|
||||
id: "task-1", deliverableUrl: "https://canina.ir/blog/verified",
|
||||
acceptanceCriteria: { criteria: ["HTTP 200"] },
|
||||
attestation: { taskId: "task-1", artifactType: "BLOG", artifactId: "blog-1", artifactUrl: "https://canina.ir/blog/verified", verifier: "SERVER_ARTIFACT_VERIFIER" },
|
||||
})).not.toThrow();
|
||||
expect(() => assertTaskCanComplete({
|
||||
id: "task-2", deliverableUrl: "https://canina.ir/blog/verified",
|
||||
acceptanceCriteria: { criteria: ["HTTP 200"] },
|
||||
attestation: { taskId: "task-1", artifactType: "BLOG", artifactId: "blog-1", artifactUrl: "https://canina.ir/blog/verified", verifier: "SERVER_ARTIFACT_VERIFIER" },
|
||||
})).toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,70 @@
|
||||
import { BadRequestException } from "@nestjs/common";
|
||||
|
||||
export interface CompletableTask {
|
||||
code?: string | null;
|
||||
title?: string | null;
|
||||
deliverableUrl?: string | null;
|
||||
acceptanceCriteria?: unknown;
|
||||
executionLogs?: unknown;
|
||||
id?: string;
|
||||
attestation?: { taskId: string; artifactType: string; artifactId: string; artifactUrl: string; verifier: string };
|
||||
}
|
||||
|
||||
function hasAcceptanceCriteria(criteria: unknown): boolean {
|
||||
if (!criteria) return false;
|
||||
if (typeof criteria === "string") return criteria.trim().length > 0;
|
||||
if (Array.isArray(criteria)) return criteria.length > 0;
|
||||
if (typeof criteria === "object") {
|
||||
const value = criteria as Record<string, unknown>;
|
||||
const items = value.criteria;
|
||||
return Array.isArray(items) ? items.length > 0 : Object.keys(value).length > 0;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
const evidence = task.attestation;
|
||||
if (!task.id || !evidence || evidence.taskId !== task.id ||
|
||||
evidence.verifier !== "SERVER_ARTIFACT_VERIFIER" ||
|
||||
evidence.artifactType !== "BLOG" || !evidence.artifactId ||
|
||||
evidence.artifactUrl !== rawUrl) {
|
||||
throw new BadRequestException("DONE requires a matching server-verified artifact attestation");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
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: {
|
||||
taskCompletionAttestation: { create: jest.Mock };
|
||||
blog: { findUnique: jest.Mock };
|
||||
product: { findUnique: jest.Mock };
|
||||
$transaction: jest.Mock;
|
||||
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 = {
|
||||
taskCompletionAttestation: { create: jest.fn() },
|
||||
blog: { findUnique: jest.fn() },
|
||||
product: { findUnique: jest.fn() },
|
||||
$transaction: jest.fn(async (callback) => callback(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("trusted completion authorization", () => {
|
||||
const validTask = {
|
||||
id: "task-105", code: "TSK-100105", title: "Published blog", status: "TEST",
|
||||
acceptanceCriteria: { criteria: ["Published blog"] }, executionLogs: [{ status: "QA_PASSED" }],
|
||||
deliverableUrl: "https://canina.ir/blog/cat-food-nutrition",
|
||||
};
|
||||
|
||||
it("cannot create a DONE task even with caller-supplied QA logs", async () => {
|
||||
await expect(controller.create({ department: "content", title: "fake", status: "DONE", executionLogs: [{ status: "QA_PASSED" }] }))
|
||||
.rejects.toThrow(BadRequestException);
|
||||
expect(prisma.departmentTask.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects unknown statuses at creation and transition", async () => {
|
||||
await expect(controller.create({ department: "content", title: "fake", status: "DONE " })).rejects.toThrow(BadRequestException);
|
||||
prisma.departmentTask.findUnique.mockResolvedValue(validTask);
|
||||
await expect(controller.updateStatus(validTask.id, { status: "COMPLETE" })).rejects.toThrow(BadRequestException);
|
||||
expect(prisma.departmentTask.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects spoofed historical QA and requires independent verification", async () => {
|
||||
prisma.departmentTask.findUnique.mockResolvedValue(validTask);
|
||||
prisma.blog.findUnique.mockResolvedValue(null);
|
||||
await expect(controller.updateStatus(validTask.id, { status: "DONE" })).rejects.toThrow(BadRequestException);
|
||||
expect(prisma.departmentTask.update).not.toHaveBeenCalled();
|
||||
expect(prisma.taskCompletionAttestation.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects arbitrary hosts and changed deliverables before lookup", async () => {
|
||||
prisma.departmentTask.findUnique.mockResolvedValue(validTask);
|
||||
await expect(controller.updateStatus(validTask.id, { status: "DONE", deliverableUrl: "https://evil.example/blog/cat-food-nutrition" }))
|
||||
.rejects.toThrow(BadRequestException);
|
||||
expect(prisma.blog.findUnique).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects an unpublished artifact", async () => {
|
||||
prisma.departmentTask.findUnique.mockResolvedValue(validTask);
|
||||
prisma.blog.findUnique.mockResolvedValue({ id: "blog-1", slug: "cat-food-nutrition", status: "DRAFT", isPublished: false });
|
||||
await expect(controller.updateStatus(validTask.id, { status: "DONE" })).rejects.toThrow(BadRequestException);
|
||||
expect(prisma.departmentTask.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not write DONE if attestation persistence fails", async () => {
|
||||
prisma.departmentTask.findUnique.mockResolvedValue(validTask);
|
||||
prisma.blog.findUnique.mockResolvedValue({ id: "blog-1", slug: "cat-food-nutrition", status: "PUBLISHED", isPublished: true });
|
||||
prisma.taskCompletionAttestation.create.mockRejectedValue(new Error("attestation store unavailable"));
|
||||
await expect(controller.updateStatus(validTask.id, { status: "DONE" })).rejects.toThrow("attestation store unavailable");
|
||||
expect(prisma.departmentTask.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("persists a server-verifier attestation bound to the task and artifact before DONE", async () => {
|
||||
prisma.departmentTask.findUnique.mockResolvedValue(validTask);
|
||||
prisma.blog.findUnique.mockResolvedValue({ id: "blog-1", slug: "cat-food-nutrition", status: "PUBLISHED", isPublished: true });
|
||||
prisma.departmentTask.update.mockResolvedValue({ ...validTask, status: "DONE" });
|
||||
await controller.updateStatus(validTask.id, { status: "DONE", logNote: "QA_PASSED" });
|
||||
expect(prisma.taskCompletionAttestation.create).toHaveBeenCalledWith({ data: expect.objectContaining({
|
||||
taskId: validTask.id, artifactType: "BLOG", artifactId: "blog-1", artifactUrl: validTask.deliverableUrl,
|
||||
verifier: "SERVER_ARTIFACT_VERIFIER", verifiedAt: expect.any(Date),
|
||||
}) });
|
||||
expect(prisma.$transaction).toHaveBeenCalled();
|
||||
expect(prisma.departmentTask.update).toHaveBeenCalledWith({ where: { id: validTask.id }, data: expect.objectContaining({ status: "DONE" }) });
|
||||
});
|
||||
});
|
||||
|
||||
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.blog.findUnique.mockResolvedValue({ id: "blog-2", slug: "cat-food-nutrition", status: "PUBLISHED", isPublished: true });
|
||||
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),
|
||||
}),
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -9,7 +9,9 @@ import {
|
||||
Query,
|
||||
UseGuards,
|
||||
NotFoundException,
|
||||
BadRequestException,
|
||||
} 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";
|
||||
@@ -22,6 +24,16 @@ import { PrismaService } from "../prisma/prisma.service";
|
||||
@Roles("Admin", "SUPER_ADMIN")
|
||||
@Controller("admin/department-tasks")
|
||||
export class DepartmentTasksController {
|
||||
private readonly allowedStatuses = new Set([
|
||||
"BACKLOG", "TODO", "IN_PROGRESS", "TEST", "IN_REVIEW", "APPROVED", "DEPLOYING", "DONE",
|
||||
]);
|
||||
|
||||
private assertStatus(status: unknown): void {
|
||||
if (typeof status !== "string" || !this.allowedStatuses.has(status)) {
|
||||
throw new BadRequestException("Unknown task status");
|
||||
}
|
||||
}
|
||||
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
@Get()
|
||||
@@ -112,6 +124,9 @@ export class DepartmentTasksController {
|
||||
@Post()
|
||||
@ApiOperation({ summary: "ایجاد تسک جدید سازمانی" })
|
||||
async create(@Body() body: any) {
|
||||
this.assertStatus(body.status || "TODO");
|
||||
// Creation cannot attest its own work; require an existing task for verification.
|
||||
if (body.status === "DONE") throw new BadRequestException("Create task before completing it");
|
||||
const code = body.code || "TSK-" + Date.now().toString().slice(-6);
|
||||
const task = await (this.prisma as any).departmentTask.create({
|
||||
data: {
|
||||
@@ -129,7 +144,6 @@ export class DepartmentTasksController {
|
||||
},
|
||||
});
|
||||
|
||||
// ثبت در تاریخچه لاگها
|
||||
await (this.prisma as any).auditLog.create({
|
||||
data: {
|
||||
entity: "task",
|
||||
@@ -155,6 +169,7 @@ export class DepartmentTasksController {
|
||||
where: { id },
|
||||
});
|
||||
if (!existing) throw new NotFoundException(`Task ${id} not found`);
|
||||
this.assertStatus(body.status);
|
||||
|
||||
const logs = Array.isArray(existing.executionLogs) ? [...existing.executionLogs] : [];
|
||||
if (body.logNote) {
|
||||
@@ -165,6 +180,37 @@ export class DepartmentTasksController {
|
||||
});
|
||||
}
|
||||
|
||||
const candidateDeliverableUrl = body.deliverableUrl || existing.deliverableUrl;
|
||||
let attestation: { taskId: string; artifactType: string; artifactId: string; artifactUrl: string; verifier: string; verifiedAt: Date } | undefined;
|
||||
if (body.status === "DONE") {
|
||||
// Only a canonical first-party blog URL is an eligible identity. Never fetch
|
||||
// arbitrary caller URLs (SSRF), or accept claims in executionLogs as proof.
|
||||
let url: URL;
|
||||
try { url = new URL(candidateDeliverableUrl); }
|
||||
catch { throw new BadRequestException("DONE requires a canonical published blog URL"); }
|
||||
const match = /^\/blog\/([a-z0-9]+(?:-[a-z0-9]+)*)$/.exec(url.pathname);
|
||||
if (url.protocol !== "https:" || url.hostname !== "canina.ir" ||
|
||||
url.port || url.username || url.password || url.search || url.hash || !match ||
|
||||
/^post-tsk(?:-|$)/.test(match[1])) {
|
||||
throw new BadRequestException("DONE requires a canonical published blog URL");
|
||||
}
|
||||
const blog = await (this.prisma as any).blog.findUnique({ where: { slug: match[1] } });
|
||||
if (!blog || blog.status !== "PUBLISHED" || blog.isPublished !== true) {
|
||||
throw new BadRequestException("DONE requires an independently verified published artifact");
|
||||
}
|
||||
attestation = {
|
||||
taskId: id, artifactType: "BLOG", artifactId: blog.id,
|
||||
artifactUrl: candidateDeliverableUrl, verifier: "SERVER_ARTIFACT_VERIFIER",
|
||||
verifiedAt: new Date(),
|
||||
};
|
||||
assertTaskCanComplete({
|
||||
id, code: existing.code, title: existing.title,
|
||||
deliverableUrl: candidateDeliverableUrl,
|
||||
acceptanceCriteria: existing.acceptanceCriteria,
|
||||
attestation,
|
||||
});
|
||||
}
|
||||
|
||||
const updateData: any = {
|
||||
status: body.status,
|
||||
executionLogs: logs,
|
||||
@@ -172,17 +218,18 @@ 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;
|
||||
}
|
||||
|
||||
const updated = await (this.prisma as any).departmentTask.update({
|
||||
where: { id },
|
||||
data: updateData,
|
||||
});
|
||||
const updated = attestation
|
||||
? await (this.prisma as any).$transaction(async (tx: any) => {
|
||||
// Persist attestation and transition together: no DONE without its record.
|
||||
await tx.taskCompletionAttestation.create({ data: attestation });
|
||||
return tx.departmentTask.update({ where: { id }, data: updateData });
|
||||
})
|
||||
: await (this.prisma as any).departmentTask.update({ where: { id }, 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 {
|
||||
|
||||
@@ -50,7 +50,8 @@ describe("BlogsService", () => {
|
||||
expect(result.data).toEqual(blogs);
|
||||
expect(result.meta.total).toBe(1);
|
||||
const query = mockPrisma.blog.findMany.mock.calls[0][0];
|
||||
expect(query.include.author).toBeUndefined();
|
||||
expect(query.include.author).toEqual({ select: { id: true, firstName: true, lastName: true } });
|
||||
expect(query.orderBy).toEqual([{ publishedAt: "desc" }, { id: "asc" }]);
|
||||
});
|
||||
|
||||
it("should filter by categorySlug and search term", async () => {
|
||||
@@ -69,7 +70,19 @@ describe("BlogsService", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("selects the minimal public author identity for list results", async () => {
|
||||
mockPrisma.blog.findMany.mockResolvedValue([]); mockPrisma.blog.count.mockResolvedValue(0);
|
||||
await service.findAll({});
|
||||
expect(mockPrisma.blog.findMany.mock.calls[0][0].include.author).toEqual({ select: { id: true, firstName: true, lastName: true } });
|
||||
});
|
||||
|
||||
describe("findHomepage", () => {
|
||||
it("selects the minimal public author identity for homepage results", async () => {
|
||||
mockPrisma.blog.findMany.mockResolvedValueOnce([]).mockResolvedValueOnce([]);
|
||||
await service.findHomepage();
|
||||
for (const call of mockPrisma.blog.findMany.mock.calls.slice(0, 2)) expect(call[0].include.author).toEqual({ select: { id: true, firstName: true, lastName: true } });
|
||||
});
|
||||
|
||||
it("should return selected blogs if showOnHome posts exist", async () => {
|
||||
const selected = [{ id: "b1", title: "Hero Blog", showOnHome: true }];
|
||||
mockPrisma.blog.findMany.mockResolvedValueOnce(selected);
|
||||
@@ -92,6 +105,12 @@ describe("BlogsService", () => {
|
||||
});
|
||||
|
||||
describe("findOneBySlug", () => {
|
||||
it("selects the minimal public author identity for detail results", async () => {
|
||||
mockPrisma.blog.findFirst.mockResolvedValue(null);
|
||||
await expect(service.findOneBySlug("missing")).rejects.toThrow(NotFoundException);
|
||||
expect(mockPrisma.blog.findFirst.mock.calls[0][0].include.author).toEqual({ select: { id: true, firstName: true, lastName: true } });
|
||||
});
|
||||
|
||||
it("should throw NotFoundException if slug is empty or blog not found", async () => {
|
||||
mockPrisma.blog.findFirst.mockResolvedValue(null);
|
||||
await expect(service.findOneBySlug("unknown-slug")).rejects.toThrow(
|
||||
|
||||
@@ -64,10 +64,16 @@ export class BlogsService {
|
||||
where: whereClause,
|
||||
skip,
|
||||
take: Number(limit),
|
||||
orderBy: {
|
||||
[sortBy === "createdAt" ? "createdAt" : "publishedAt"]: sortOrder,
|
||||
},
|
||||
orderBy: [
|
||||
{
|
||||
[sortBy === "createdAt" ? "createdAt" : "publishedAt"]: sortOrder,
|
||||
},
|
||||
{ id: "asc" },
|
||||
],
|
||||
include: {
|
||||
author: {
|
||||
select: { id: true, firstName: true, lastName: true },
|
||||
},
|
||||
category: {
|
||||
select: { id: true, name: true, slug: true },
|
||||
},
|
||||
@@ -105,8 +111,11 @@ export class BlogsService {
|
||||
const selectedBlogs = await this.prisma.blog.findMany({
|
||||
where: { ...baseWhere, showOnHome: true },
|
||||
take: 4,
|
||||
orderBy: { publishedAt: "desc" },
|
||||
orderBy: [{ publishedAt: "desc" }, { id: "asc" }],
|
||||
include: {
|
||||
author: {
|
||||
select: { id: true, firstName: true, lastName: true },
|
||||
},
|
||||
category: { select: { id: true, name: true, slug: true } },
|
||||
tags: { select: { id: true, name: true, slug: true } },
|
||||
_count: { select: { comments: { where: { status: "APPROVED" } } } },
|
||||
@@ -121,8 +130,11 @@ export class BlogsService {
|
||||
const newestBlogs = await this.prisma.blog.findMany({
|
||||
where: baseWhere,
|
||||
take: 4,
|
||||
orderBy: { publishedAt: "desc" },
|
||||
orderBy: [{ publishedAt: "desc" }, { id: "asc" }],
|
||||
include: {
|
||||
author: {
|
||||
select: { id: true, firstName: true, lastName: true },
|
||||
},
|
||||
category: { select: { id: true, name: true, slug: true } },
|
||||
tags: { select: { id: true, name: true, slug: true } },
|
||||
_count: { select: { comments: { where: { status: "APPROVED" } } } },
|
||||
@@ -158,6 +170,7 @@ export class BlogsService {
|
||||
],
|
||||
},
|
||||
include: {
|
||||
author: { select: { id: true, firstName: true, lastName: true } },
|
||||
category: {
|
||||
select: { id: true, name: true, slug: true },
|
||||
},
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { CallHandler, ExecutionContext } from "@nestjs/common";
|
||||
import { of, lastValueFrom } from "rxjs";
|
||||
import { AdminRevalidationInterceptor } from "./admin-revalidation.interceptor";
|
||||
import { RevalidationService } from "./revalidation.service";
|
||||
|
||||
describe("AdminRevalidationInterceptor", () => {
|
||||
const revalidation = { revalidate: jest.fn().mockResolvedValue(true) } as unknown as RevalidationService;
|
||||
const interceptor = new AdminRevalidationInterceptor(revalidation);
|
||||
const next = { handle: () => of({ ok: true }) } as CallHandler;
|
||||
|
||||
beforeEach(() => jest.clearAllMocks());
|
||||
|
||||
function context(method: string, url: string): ExecutionContext {
|
||||
return { switchToHttp: () => ({ getRequest: () => ({ method, originalUrl: url }) }) } as unknown as ExecutionContext;
|
||||
}
|
||||
|
||||
it("invalidates blog list and detail after an admin blog mutation", async () => {
|
||||
await lastValueFrom(interceptor.intercept(context("PUT", "/api/admin/blogs/blog-1"), next));
|
||||
expect(revalidation.revalidate).toHaveBeenCalledWith(
|
||||
expect.arrayContaining(["blogs", "blog-categories", "blog-tags", "home-data"]),
|
||||
expect.arrayContaining(["/", "/blog"]),
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["/api/admin/products/p1", "products"],
|
||||
["/api/admin/categories/c1", "categories"],
|
||||
["/api/admin/wiki/glucosamine", "wiki"],
|
||||
["/api/admin/settings", "settings"],
|
||||
["/api/admin/cms/hero-banners/b1", "banners"],
|
||||
["/api/admin/cms/vet-testimonials/t1", "testimonials"],
|
||||
["/api/admin/reviews/r1", "products"],
|
||||
["/api/admin/media/m1", "products"],
|
||||
])("maps %s mutations to %s cache invalidation", async (url, expectedTag) => {
|
||||
await lastValueFrom(interceptor.intercept(context("DELETE", url), next));
|
||||
expect(revalidation.revalidate).toHaveBeenCalledWith(expect.arrayContaining([expectedTag]), expect.any(Array));
|
||||
});
|
||||
|
||||
it("does not invalidate cache for reads or internal-only admin CRUD", async () => {
|
||||
await lastValueFrom(interceptor.intercept(context("GET", "/api/admin/blogs"), next));
|
||||
await lastValueFrom(interceptor.intercept(context("PUT", "/api/admin/users/u1"), next));
|
||||
expect(revalidation.revalidate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["/api/banners/banner-1", "banners"],
|
||||
["/api/menu/menu-1", "menu"],
|
||||
["/api/videos/video-1", "videos"],
|
||||
["/api/testimonials/testimonial-1", "testimonials"],
|
||||
["/api/faq/faq-1", "faq"],
|
||||
["/api/ingredients/ingredient-1", "ingredients"],
|
||||
["/api/doctors/doctor-1", "doctors"],
|
||||
["/api/settings/seo", "seo-config"],
|
||||
["/api/settings/ui-texts/HERO_TITLE", "ui-texts"],
|
||||
["/api/contact/info", "settings"],
|
||||
["/api/smart-advisor/rules/rule-1", "smart-advisor"],
|
||||
])("maps storefront mutation %s to %s cache invalidation", async (url, expectedTag) => {
|
||||
await lastValueFrom(interceptor.intercept(context("PATCH", url), next));
|
||||
expect(revalidation.revalidate).toHaveBeenCalledWith(expect.arrayContaining([expectedTag]), expect.any(Array));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from "@nestjs/common";
|
||||
import { Observable, tap } from "rxjs";
|
||||
import { RevalidationService } from "./revalidation.service";
|
||||
|
||||
type Target = { tags: string[]; paths: string[] };
|
||||
|
||||
const TARGETS: Array<{ pattern: RegExp; target: Target }> = [
|
||||
{ pattern: /^\/api\/banners(?:\/|$)/, target: { tags: ["banners", "home-data"], paths: ["/"] } },
|
||||
{ pattern: /^\/api\/menu(?:\/|$)/, target: { tags: ["menu", "settings"], paths: ["/"] } },
|
||||
{ pattern: /^\/api\/videos(?:\/|$)/, target: { tags: ["videos", "home-data"], paths: ["/", "/videos"] } },
|
||||
{ pattern: /^\/api\/testimonials(?:\/|$)/, target: { tags: ["testimonials", "home-data"], paths: ["/"] } },
|
||||
{ pattern: /^\/api\/faq(?:\/|$)/, target: { tags: ["faq"], paths: ["/faq"] } },
|
||||
{ pattern: /^\/api\/ingredients(?:\/|$)/, target: { tags: ["ingredients", "products", "wiki"], paths: ["/shop", "/wiki"] } },
|
||||
{ pattern: /^\/api\/doctors(?:\/|$)/, target: { tags: ["doctors", "settings"], paths: ["/contact"] } },
|
||||
{ pattern: /^\/api\/settings\/seo(?:\/|$)/, target: { tags: ["seo-config", "settings"], paths: ["/", "/sitemap.xml"] } },
|
||||
{ pattern: /^\/api\/settings\/(?:ui-texts|system|financial)(?:\/|$)/, target: { tags: ["ui-texts", "settings", "home-data"], paths: ["/"] } },
|
||||
{ pattern: /^\/api\/contact\/info(?:\/|$)/, target: { tags: ["settings"], paths: ["/contact", "/"] } },
|
||||
{ pattern: /^\/api\/smart-advisor\/rules(?:\/|$)/, target: { tags: ["smart-advisor", "products"], paths: ["/smart-advisor"] } },
|
||||
{ pattern: /^\/api\/admin\/blogs(?:\/|$)/, target: { tags: ["blogs", "blog-categories", "blog-tags", "home-data"], paths: ["/", "/blog", "/sitemap.xml"] } },
|
||||
{ pattern: /^\/api\/admin\/categories(?:\/|$)/, target: { tags: ["products", "categories", "home-data"], paths: ["/", "/shop", "/sitemap.xml"] } },
|
||||
{ pattern: /^\/api\/admin\/wiki(?:\/|$)/, target: { tags: ["wiki", "scientific-terms"], paths: ["/wiki", "/sitemap.xml"] } },
|
||||
{ pattern: /^\/api\/admin\/(?:settings|pricing)(?:\/|$)/, target: { tags: ["settings", "ui-texts", "seo-config", "products", "home-data"], paths: ["/", "/shop"] } },
|
||||
{ pattern: /^\/api\/admin\/cms\/hero-banners(?:\/|$)/, target: { tags: ["banners", "home-data"], paths: ["/"] } },
|
||||
{ pattern: /^\/api\/admin\/cms\/vet-testimonials(?:\/|$)/, target: { tags: ["testimonials", "home-data"], paths: ["/"] } },
|
||||
{ pattern: /^\/api\/admin\/reviews(?:\/|$)/, target: { tags: ["products", "home-data"], paths: ["/", "/shop"] } },
|
||||
{ pattern: /^\/api\/admin\/media(?:\/|$)/, target: { tags: ["products", "blogs", "wiki", "home-data"], paths: ["/", "/shop", "/blog", "/wiki"] } },
|
||||
{ pattern: /^\/api\/admin\/products(?:\/|$)/, target: { tags: ["products", "home-data"], paths: ["/", "/shop", "/sitemap.xml"] } },
|
||||
];
|
||||
|
||||
@Injectable()
|
||||
export class AdminRevalidationInterceptor implements NestInterceptor {
|
||||
constructor(private readonly revalidation: RevalidationService) {}
|
||||
|
||||
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
|
||||
const request = context.switchToHttp().getRequest<{ method?: string; originalUrl?: string; url?: string }>();
|
||||
const method = (request.method || "GET").toUpperCase();
|
||||
const url = (request.originalUrl || request.url || "").split("?")[0];
|
||||
const target = method === "GET" || method === "HEAD" || method === "OPTIONS"
|
||||
? undefined
|
||||
: TARGETS.find((entry) => entry.pattern.test(url))?.target;
|
||||
|
||||
return next.handle().pipe(
|
||||
tap(() => {
|
||||
if (target) void this.revalidation.revalidate(target.tags, target.paths);
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
import { Global, Module } from "@nestjs/common";
|
||||
import { APP_INTERCEPTOR } from "@nestjs/core";
|
||||
import { AdminRevalidationInterceptor } from "./admin-revalidation.interceptor";
|
||||
import { RevalidationService } from "./revalidation.service";
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [RevalidationService],
|
||||
providers: [RevalidationService, { provide: APP_INTERCEPTOR, useClass: AdminRevalidationInterceptor }],
|
||||
exports: [RevalidationService],
|
||||
})
|
||||
export class RevalidationModule {}
|
||||
@@ -110,4 +110,22 @@ describe("RevalidationService", () => {
|
||||
expect(pathSpy).toHaveBeenCalledWith("/shop/ART-100");
|
||||
});
|
||||
});
|
||||
|
||||
describe("revalidate batch", () => {
|
||||
it("should send deduplicated tags and paths in one request", async () => {
|
||||
const mockFetch = jest.spyOn(global, "fetch" as any).mockResolvedValue({ ok: true, status: 200 } as any);
|
||||
|
||||
const result = await service.revalidate(["blogs", "blogs"], ["/blog", "/blog"]);
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
"http://frontend_mock:8080/api/revalidate",
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
body: JSON.stringify({ tags: ["blogs"], paths: ["/blog"] }),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -31,6 +31,32 @@ export class RevalidationService {
|
||||
return secret;
|
||||
}
|
||||
|
||||
async revalidate(tags: string[] = [], paths: string[] = []): Promise<boolean> {
|
||||
const cleanTags = [...new Set(tags.filter(Boolean))];
|
||||
const cleanPaths = [...new Set(paths.filter((path) => path.startsWith("/")))];
|
||||
if (!cleanTags.length && !cleanPaths.length) return true;
|
||||
|
||||
try {
|
||||
const url = `${this.frontendUrl}/api/revalidate`;
|
||||
const res = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"x-revalidate-secret": this.secret,
|
||||
},
|
||||
body: JSON.stringify({ tags: cleanTags, paths: cleanPaths }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
this.logger.warn(`Failed to revalidate cache batch: ${res.status} ${res.statusText}`);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} catch (err: any) {
|
||||
this.logger.debug(`Batch revalidation skipped or frontend offline: ${err?.message}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async revalidateTag(tag: string): Promise<boolean> {
|
||||
try {
|
||||
const url = `${this.frontendUrl}/api/revalidate`;
|
||||
|
||||
@@ -117,7 +117,9 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side
|
||||
title: 'حاکمیت، تاییدات و وظایف',
|
||||
icon: CheckSquare,
|
||||
items: [
|
||||
{ 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', 'بررسی نسخه'] },
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
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";
|
||||
|
||||
vi.mock("../services/api", () => {
|
||||
return {
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("react-hot-toast", () => ({
|
||||
default: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
describe("ApprovalsPage Component", () => {
|
||||
const mockApprovals = [
|
||||
{
|
||||
id: "app-1",
|
||||
department: "CONTENT",
|
||||
category: "CAMPAIGN",
|
||||
title: "کمپین تخصصی مفاصل: برتری بالینی صدف لبسبز کنینا نسبت به وتاکسپرت",
|
||||
status: "PENDING",
|
||||
createdAt: "2026-10-19T10:00:00Z",
|
||||
payload: {
|
||||
"1_مسئله_و_شکاف_بازار": "قیمت گزاف قرص مفاصل وتاکسپرت لهستان باعث شکست دورههای درمانی شده است.",
|
||||
"2_راهحل_و_مزیت_کنینا": "معرفی مکمل بیرقیب Velox Gelenkenergie ۱۰۰٪ عصاره صدف لبسبز با نصف قیمت رقیب.",
|
||||
"3_طرح_اقدام_عملیاتی": "تولید لندینگپیج جامع و سئومحور و اتصال مستقیم به ترب.",
|
||||
"4_دپارتمانهای_مسئول": "CONTENT, SEO, CLINICAL_RD",
|
||||
"5_معیار_پذیرش_و_تکمیل": "رندر شدن لندینگ بدون خطای SSR و افزایش ایمپرشن ارگانیک."
|
||||
}
|
||||
},
|
||||
{
|
||||
id: "app-2",
|
||||
department: "PRICING",
|
||||
category: "PRICE_CHANGE",
|
||||
title: "پیشنهاد اصلاح قیمت و همگامسازی با ترب: Canina Flexan 150g",
|
||||
status: "PENDING",
|
||||
createdAt: "2026-10-19T11:00:00Z",
|
||||
payload: {
|
||||
product_name: "Canina Flexan 150g",
|
||||
current_price: 34800000,
|
||||
suggested_price: 36500000,
|
||||
margin_percent: 20.5,
|
||||
competitor_min_torob: 37200000,
|
||||
reason: "افزایش قیمت تامینکننده و میانگین قیمت ترب روی ۳۷.۲ میلیون ریال است."
|
||||
}
|
||||
},
|
||||
{
|
||||
id: "app-3",
|
||||
department: "MARKETING",
|
||||
category: "SMS_CAMPAIGN",
|
||||
title: "کمپین یادآوری تمدید دوره مکملهای مفاصل و GAG",
|
||||
status: "APPROVED",
|
||||
createdAt: "2026-10-18T09:00:00Z",
|
||||
executedAt: "2026-10-18T10:00:00Z",
|
||||
ceoNotes: "تایید شد و پیامکها ارسال شدند.",
|
||||
payload: {
|
||||
campaign_name: "Refill GAG 60-Day Reminder",
|
||||
sms_pattern: "سلام {name} عزیز، دوره مکمل مفاصل کنینا رو به اتمام است.",
|
||||
target_count: 86,
|
||||
estimated_cost_irr: 860000,
|
||||
expected_revenue_irr: 54000000,
|
||||
expected_conversion_rate: "18%"
|
||||
}
|
||||
}
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
(api.get as any).mockResolvedValue({
|
||||
data: {
|
||||
success: true,
|
||||
data: mockApprovals,
|
||||
meta: {
|
||||
total: 3,
|
||||
pendingCount: 2,
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("renders header, KPI cards, and maps strategic 5-part proposal nicely", async () => {
|
||||
render(<ApprovalsPage />);
|
||||
|
||||
expect(await screen.findByText(/کارتابل حاکمیت سازمانی و تاییدات مدیرعامل/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/2 پیشنهاد منتظر تصمیم شما/i)).toBeInTheDocument();
|
||||
|
||||
// Verify 5-part structured fields are cleanly mapped
|
||||
expect(screen.getByText(/مسئله و شکاف شناساییشده در بازار:/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/قیمت گزاف قرص مفاصل وتاکسپرت لهستان/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/راهحل، محصول و مزیت رقابتی کنینا:/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/Velox Gelenkenergie/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders pricing payload with current price, suggested price, and margin", async () => {
|
||||
render(<ApprovalsPage />);
|
||||
|
||||
expect(await screen.findByText(/پیشنهاد اصلاح قیمت و همگامسازی با ترب/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/محاسبه قیمتگذاری و سود ناخالص:/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/20.5٪/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("approves a pending request with CEO directive note", async () => {
|
||||
(api.put as any).mockResolvedValue({
|
||||
data: { success: true },
|
||||
});
|
||||
|
||||
render(<ApprovalsPage />);
|
||||
|
||||
expect(await screen.findByText(/کمپین تخصصی مفاصل/i)).toBeInTheDocument();
|
||||
|
||||
const approveButtons = screen.getAllByRole("button", { name: /تایید و صدور مجوز اجرا/i });
|
||||
expect(approveButtons.length).toBeGreaterThan(0);
|
||||
|
||||
fireEvent.click(approveButtons[0]);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.put).toHaveBeenCalledWith(
|
||||
"/admin/approvals/app-2/decide",
|
||||
expect.objectContaining({ decision: "APPROVED" })
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("runs simulation test when clicking play button", async () => {
|
||||
(api.post as any).mockResolvedValue({
|
||||
data: {
|
||||
success: true,
|
||||
testResult: {
|
||||
status: "SIMULATION_SUCCESS",
|
||||
executionSafe: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
render(<ApprovalsPage />);
|
||||
|
||||
const runTestButtons = await screen.findAllByRole("button", { name: /اجرای تست و شبیهسازی/i });
|
||||
expect(runTestButtons.length).toBeGreaterThan(0);
|
||||
|
||||
fireEvent.click(runTestButtons[0]);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.post).toHaveBeenCalledWith("/admin/approvals/app-2/test");
|
||||
});
|
||||
|
||||
expect(await screen.findByText(/نتیجه تست سلامت و شبیهسازی:/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -251,6 +251,10 @@ describe("Blogs Page Component", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("submits authorship fields and intentional material update control", async () => {
|
||||
renderComponent(); await screen.findByText("راهنمای جامع نگهداری سگ پامرانین"); fireEvent.click(screen.getAllByTitle("ویرایش مقاله")[0]); fireEvent.change(screen.getByLabelText("تیم نویسندگی"),{target:{value:"Science"}}); fireEvent.change(screen.getByLabelText("نقش نویسنده"),{target:{value:"Vet"}}); fireEvent.click(screen.getByText("۳. زمانبندی و انتشار")); fireEvent.click(screen.getByLabelText("ثبت بهروزرسانی محتوایی مهم")); fireEvent.click(screen.getByTestId("blog-save-btn")); await waitFor(()=>expect(api.put).toHaveBeenCalledWith("/admin/blogs/blog-1",expect.objectContaining({authorTeam:"Science",authorRole:"Vet",markContentUpdated:true})));
|
||||
});
|
||||
|
||||
it("shows delete confirmation and deletes blog article", async () => {
|
||||
vi.mocked(api.delete).mockResolvedValueOnce({ data: { success: true } });
|
||||
|
||||
|
||||
@@ -70,6 +70,9 @@ export interface BlogPost {
|
||||
content: string;
|
||||
excerpt?: string;
|
||||
authorId?: string;
|
||||
authorTeam?: string;
|
||||
authorRole?: string;
|
||||
contentUpdatedAt?: string | null;
|
||||
author?: {
|
||||
id?: string;
|
||||
firstName?: string;
|
||||
@@ -168,6 +171,9 @@ export default function Blogs() {
|
||||
content: '',
|
||||
excerpt: '',
|
||||
authorId: '',
|
||||
authorTeam: '',
|
||||
authorRole: '',
|
||||
markContentUpdated: false,
|
||||
categoryId: '',
|
||||
tagNames: [] as string[],
|
||||
imageUrl: '',
|
||||
@@ -245,6 +251,9 @@ export default function Blogs() {
|
||||
content: blog.content || '',
|
||||
excerpt: blog.excerpt || '',
|
||||
authorId: blog.authorId || (blog.author?.id || ''),
|
||||
authorTeam: blog.authorTeam || '',
|
||||
authorRole: blog.authorRole || '',
|
||||
markContentUpdated: false,
|
||||
categoryId: blog.categoryId || '',
|
||||
tagNames: blog.tags ? blog.tags.map((t) => t.name) : [],
|
||||
imageUrl: blog.imageUrl || '',
|
||||
@@ -281,6 +290,9 @@ export default function Blogs() {
|
||||
content: '',
|
||||
excerpt: '',
|
||||
authorId: authors[0]?.id || '',
|
||||
authorTeam: '',
|
||||
authorRole: '',
|
||||
markContentUpdated: false,
|
||||
categoryId: '',
|
||||
tagNames: [],
|
||||
imageUrl: '',
|
||||
@@ -1003,6 +1015,11 @@ export default function Blogs() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div><label htmlFor="author-team" className="text-xs font-bold text-gray-700">تیم نویسندگی</label><input id="author-team" value={formData.authorTeam} onChange={(e)=>setFormData({...formData,authorTeam:e.target.value})} className="w-full px-3 py-2.5 rounded-2xl border border-gray-200 text-xs" /></div>
|
||||
<div><label htmlFor="author-role" className="text-xs font-bold text-gray-700">نقش نویسنده</label><input id="author-role" value={formData.authorRole} onChange={(e)=>setFormData({...formData,authorRole:e.target.value})} className="w-full px-3 py-2.5 rounded-2xl border border-gray-200 text-xs" /></div>
|
||||
</div>
|
||||
|
||||
{/* Chips Tag Input */}
|
||||
<div className="space-y-2 p-3.5 bg-gray-50/70 border border-gray-200 rounded-2xl">
|
||||
<label className="text-xs font-bold text-gray-700 block">برچسبها و تگهای مقاله (Tag Input)</label>
|
||||
@@ -1161,6 +1178,8 @@ export default function Blogs() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<label className="flex items-center gap-3 p-4 border border-blue-200 rounded-2xl bg-blue-50 cursor-pointer"><input type="checkbox" aria-label="ثبت بهروزرسانی محتوایی مهم" checked={formData.markContentUpdated} onChange={(e)=>setFormData({...formData,markContentUpdated:e.target.checked})}/><span className="text-xs font-black">ثبت بهروزرسانی محتوایی مهم</span></label>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
|
||||
<label className="flex items-center gap-3 p-4 border border-gray-200 rounded-2xl bg-white hover:bg-gray-50 transition-colors cursor-pointer">
|
||||
<input
|
||||
|
||||
@@ -0,0 +1,352 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import {
|
||||
Building2,
|
||||
CheckCircle2,
|
||||
Clock,
|
||||
AlertTriangle,
|
||||
ArrowUpRight,
|
||||
RefreshCw,
|
||||
ShieldCheck,
|
||||
Briefcase,
|
||||
FileText,
|
||||
Stethoscope,
|
||||
Search,
|
||||
Headphones,
|
||||
Cpu,
|
||||
Layers,
|
||||
Terminal,
|
||||
Activity,
|
||||
XCircle,
|
||||
} from 'lucide-react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import api from '../services/api';
|
||||
|
||||
interface DepartmentCard {
|
||||
id: string;
|
||||
name: string;
|
||||
role: string;
|
||||
agentName: string;
|
||||
avatarColor: string;
|
||||
icon: any;
|
||||
status: 'ACTIVE' | 'PROCESSING' | 'STANDBY';
|
||||
currentFocus: string;
|
||||
pendingApprovals: number;
|
||||
completedTasks: number;
|
||||
recentReasoningSnippet: string;
|
||||
}
|
||||
|
||||
const BASE_DEPARTMENTS: Omit<DepartmentCard, 'status' | 'pendingApprovals' | 'completedTasks' | 'recentReasoningSnippet' | 'currentFocus'>[] = [
|
||||
{
|
||||
id: 'CONTENT',
|
||||
name: 'واحد محتوا و وبلاگ تخصصی',
|
||||
role: 'تحقیق عمیق، مقالات بالینی، تولید تصویر و سئوی محتوایی',
|
||||
agentName: 'Canina-Content-Agent',
|
||||
avatarColor: 'from-blue-600 to-indigo-700',
|
||||
icon: FileText,
|
||||
},
|
||||
{
|
||||
id: 'CLINICAL_RD',
|
||||
name: 'واحد تحقیق و توسعه بالینی (R&D)',
|
||||
role: 'فکتچکینگ پزشکی، اعتبارسنجی دوزها و مراجع داروسازی آلمان',
|
||||
agentName: 'Canina-Medical-Agent',
|
||||
avatarColor: 'from-emerald-600 to-teal-700',
|
||||
icon: Stethoscope,
|
||||
},
|
||||
{
|
||||
id: 'SEO',
|
||||
name: 'واحد سئو و هوش بازار',
|
||||
role: 'پایش سرچ کنسول، شناسایی کلمات کلیدی، بهینهسازی اسکیما و فید ترب',
|
||||
agentName: 'Canina-SEO-Agent',
|
||||
avatarColor: 'from-amber-500 to-orange-600',
|
||||
icon: Search,
|
||||
},
|
||||
{
|
||||
id: 'B2B',
|
||||
name: 'واحد توسعه سازمانی و B2B',
|
||||
role: 'پایپلاین کلینیکها، بیمارستانهای دامپزشکی و بستههای نمایندگی',
|
||||
agentName: 'Canina-B2B-Agent',
|
||||
avatarColor: 'from-purple-600 to-violet-800',
|
||||
icon: Building2,
|
||||
},
|
||||
{
|
||||
id: 'DEVOPS',
|
||||
name: 'واحد مهندسی، زیرساخت و امنیت',
|
||||
role: 'پایش سلامت کانتینرها، مصرف دیسک، SSL و پایپلاین آزمونمحور TDD',
|
||||
agentName: 'Canina-DevOps-Agent',
|
||||
avatarColor: 'from-rose-600 to-red-700',
|
||||
icon: Cpu,
|
||||
},
|
||||
{
|
||||
id: 'SUPPORT',
|
||||
name: 'واحد پشتیبانی و مشاوره هوشمند',
|
||||
role: 'پاسخگویی به مشتریان، تریاژ پرسشهای پت و ثبت تیکتهای پیگیری',
|
||||
agentName: 'Canina-Support-Agent',
|
||||
avatarColor: 'from-cyan-600 to-blue-700',
|
||||
icon: Headphones,
|
||||
}
|
||||
];
|
||||
|
||||
export default function CompanyOrchestrationHQ() {
|
||||
const [departments, setDepartments] = useState<DepartmentCard[]>([]);
|
||||
const [totalPendingApprovals, setTotalPendingApprovals] = useState<number>(0);
|
||||
const [totalTasksCount, setTotalTasksCount] = useState<number>(0);
|
||||
const [isLoading, setIsLoading] = useState<boolean>(true);
|
||||
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'),
|
||||
api.get('/admin/department-tasks?limit=100'),
|
||||
api.get('/admin/approvals?limit=100')
|
||||
]);
|
||||
|
||||
const tasks = tasksRes.data?.data || [];
|
||||
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 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';
|
||||
}
|
||||
|
||||
let currentFocus = 'آمادهباش / بدون وظیفه فعال در حال حاضر';
|
||||
if (inProgress) currentFocus = inProgress.title;
|
||||
else if (latestTask) currentFocus = latestTask.title;
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
// 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: deptPendingCount,
|
||||
completedTasks: completedCount,
|
||||
recentReasoningSnippet: snippet
|
||||
};
|
||||
});
|
||||
|
||||
setDepartments(mapped);
|
||||
} catch (err) {
|
||||
console.error('Error fetching live orchestration telemetry:', err);
|
||||
setHasError(true);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchLiveStatus();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="space-y-6 font-vazir" dir="rtl">
|
||||
{/* 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-100 text-purple-700 rounded-2xl border border-purple-200">
|
||||
<Building2 className="w-8 h-8" />
|
||||
</div>
|
||||
<div>
|
||||
<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-500 mt-1 font-medium">
|
||||
پایش وظایف، وضعیت و خروجی عملیاتی دپارتمانها و ایجنتها بر اساس دادههای واقعی سرویس
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</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-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 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>
|
||||
|
||||
{/* 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>
|
||||
<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>
|
||||
|
||||
{/* 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-3 rounded-2xl bg-gradient-to-br ${dept.avatarColor} text-white shadow-xs`}>
|
||||
<dept.icon className="w-5 h-5" />
|
||||
</div>
|
||||
<div>
|
||||
<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>
|
||||
<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-xs text-gray-600 mt-3 font-medium leading-relaxed">
|
||||
{dept.role}
|
||||
</p>
|
||||
|
||||
<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>
|
||||
<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>
|
||||
</div>
|
||||
|
||||
<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>
|
||||
|
||||
<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>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -117,10 +117,10 @@ export default function Dashboard() {
|
||||
const COLORS = ['#8b5cf6', '#3b82f6', '#10b981'];
|
||||
|
||||
const stats = [
|
||||
{ title: 'درآمد کل', value: `${data.revenue.toLocaleString()} تومان`, icon: DollarSign, color: 'text-green-600', bg: 'bg-green-100', link: '/reports' },
|
||||
{ title: 'سفارشات جدید', value: data.newOrders.toString(), icon: ShoppingCart, color: 'text-blue-600', bg: 'bg-blue-100', link: '/orders' },
|
||||
{ title: 'کاربران فعال', value: data.users.toString(), icon: Users, color: 'text-purple-600', bg: 'bg-purple-100', link: '/users' },
|
||||
{ title: 'بازدید امروز', value: data.todayVisits.toString(), icon: Activity, color: 'text-orange-600', bg: 'bg-orange-100', link: '/reports' },
|
||||
{ title: 'درآمد کل', value: `${(data?.revenue || 0).toLocaleString()} تومان`, icon: DollarSign, color: 'text-green-600', bg: 'bg-green-100', link: '/reports' },
|
||||
{ title: 'سفارشات جدید', value: (data?.newOrders || 0).toString(), icon: ShoppingCart, color: 'text-blue-600', bg: 'bg-blue-100', link: '/orders' },
|
||||
{ title: 'کاربران فعال', value: (data?.users || 0).toString(), icon: Users, color: 'text-purple-600', bg: 'bg-purple-100', link: '/users' },
|
||||
{ title: 'بازدید امروز', value: (data?.todayVisits || 0).toString(), icon: Activity, color: 'text-orange-600', bg: 'bg-orange-100', link: '/reports' },
|
||||
];
|
||||
|
||||
return (
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -36,6 +36,7 @@ export default function TasksManagementPage() {
|
||||
const [tasks, setTasks] = useState<DepartmentTask[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
const [sortOrder, setSortOrder] = useState<'desc' | 'asc'>('desc');
|
||||
const [selectedDept, setSelectedDept] = useState('ALL');
|
||||
const [selectedStatus, setSelectedStatus] = useState('ALL');
|
||||
const [selectedPriority, setSelectedPriority] = useState('ALL');
|
||||
@@ -85,7 +86,12 @@ export default function TasksManagementPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const filteredTasks = tasks.filter((t) => {
|
||||
const sortedTasks = [...tasks].sort((a, b) => {
|
||||
const tA = new Date(a.createdAt || 0).getTime();
|
||||
const tB = new Date(b.createdAt || 0).getTime();
|
||||
return sortOrder === 'desc' ? tB - tA : tA - tB;
|
||||
});
|
||||
const filteredTasks = sortedTasks.filter((t) => {
|
||||
const matchesSearch =
|
||||
!searchTerm ||
|
||||
t.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
@@ -128,10 +134,22 @@ export default function TasksManagementPage() {
|
||||
۳. تست استیج و QA (TEST)
|
||||
</span>
|
||||
);
|
||||
case 'WAITING_DEPENDENCIES':
|
||||
return (
|
||||
<span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-violet-100 text-violet-800 border border-violet-200">
|
||||
۳. منتظر تکمیل اقدامات وابسته
|
||||
</span>
|
||||
);
|
||||
case 'DONE':
|
||||
return (
|
||||
<span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-emerald-100 text-emerald-800 border border-emerald-200">
|
||||
۴. مستقر پروداکشن (DONE)
|
||||
۴. خروجی راستیآزماییشده (DONE)
|
||||
</span>
|
||||
);
|
||||
case 'REJECTED':
|
||||
return (
|
||||
<span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-rose-100 text-rose-800 border border-rose-200">
|
||||
رد شده (REJECTED)
|
||||
</span>
|
||||
);
|
||||
default:
|
||||
@@ -139,8 +157,28 @@ export default function TasksManagementPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const getStatusTransitionsSummary = (logsRaw: any) => {
|
||||
const list = Array.isArray(logsRaw) ? logsRaw : (typeof logsRaw === 'object' && logsRaw ? [logsRaw] : []);
|
||||
let inProgressCount = 0;
|
||||
let testCount = 0;
|
||||
let qaRejectedCount = 0;
|
||||
let qaPassedCount = 0;
|
||||
|
||||
list.forEach((entry: any) => {
|
||||
const st = String(entry?.status || '');
|
||||
if (st.includes('STARTED') || st === 'IN_PROGRESS') inProgressCount += 1;
|
||||
if (st.includes('COMPLETED') || st === 'TEST') testCount += 1;
|
||||
if (st === 'QA_FAILED') qaRejectedCount += 1;
|
||||
if (st === 'QA_PASSED') qaPassedCount += 1;
|
||||
});
|
||||
|
||||
return { inProgressCount, testCount, qaRejectedCount, qaPassedCount, totalEvents: list.length };
|
||||
};
|
||||
|
||||
const getPriorityBadge = (priority: string) => {
|
||||
switch (priority) {
|
||||
case 'CEO_EXPEDITE':
|
||||
return <span className="px-1.5 py-0.5 text-[9px] font-black bg-purple-700 text-white rounded animate-pulse shadow-sm shadow-purple-300">⚡ فوری مدیرعامل</span>;
|
||||
case 'CRITICAL':
|
||||
return <span className="px-1.5 py-0.5 text-[9px] font-black bg-rose-600 text-white rounded">فوری / بحرانی</span>;
|
||||
case 'HIGH':
|
||||
@@ -248,11 +286,16 @@ export default function TasksManagementPage() {
|
||||
>
|
||||
<option value="ALL">همه دپارتمانها</option>
|
||||
<option value="DEV">مهندسی و توسعه (DEV)</option>
|
||||
<option value="DEVOPS">زیرساخت و سرور (DEVOPS)</option>
|
||||
<option value="SEO">سئو و مارکتپلیس (SEO)</option>
|
||||
<option value="CONTENT">محتوا و وبلاگ (CONTENT)</option>
|
||||
<option value="CLINICAL_RD">تحقیق و توسعه بالینی (CLINICAL_RD)</option>
|
||||
<option value="B2B">بازرگانی و توسعه کلینیکها (B2B)</option>
|
||||
<option value="SUPPORT">پشتیبانی مشتریان و CRM (SUPPORT)</option>
|
||||
<option value="QA">تضمین کیفیت و تست (QA)</option>
|
||||
<option value="COMMERCE">بازرگانی و مالی (COMMERCE)</option>
|
||||
<option value="PRODUCT">کاتالوگ و استوک (PRODUCT)</option>
|
||||
<option value="CONTENT">محتوا و وبلاگ (CONTENT)</option>
|
||||
<option value="SEO">سئو و مارکتپلیس (SEO)</option>
|
||||
<option value="PMO">مدیریت محصول و تضمین کیفیت (PMO)</option>
|
||||
<option value="PMO">مدیریت محصول و ارکستراسیون (PMO)</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
@@ -268,8 +311,10 @@ export default function TasksManagementPage() {
|
||||
<option value="ALL">همه وضعیتها</option>
|
||||
<option value="TODO">۱. صف اقدام (TODO)</option>
|
||||
<option value="IN_PROGRESS">۲. در حال اجرا (IN_PROGRESS)</option>
|
||||
<option value="TEST">۳. تست و QA (TEST)</option>
|
||||
<option value="DONE">۴. تکمیل شده (DONE)</option>
|
||||
<option value="TEST">۳. تست استیج و QA (TEST)</option>
|
||||
<option value="WAITING_DEPENDENCIES">۴. منتظر اقدامات وابسته (WAITING_DEPENDENCIES)</option>
|
||||
<option value="DONE">۵. تکمیل و راستیآزماییشده (DONE)</option>
|
||||
<option value="REJECTED">۶. رد شده (REJECTED)</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
@@ -283,6 +328,7 @@ export default function TasksManagementPage() {
|
||||
className="w-full px-3 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500 font-bold text-gray-700"
|
||||
>
|
||||
<option value="ALL">همه اولویتها</option>
|
||||
<option value="CEO_EXPEDITE">⚡ فوری مدیرعامل (CEO_EXPEDITE)</option>
|
||||
<option value="CRITICAL">بحرانی / فوری</option>
|
||||
<option value="HIGH">بالا</option>
|
||||
<option value="MEDIUM">متوسط</option>
|
||||
@@ -310,6 +356,12 @@ export default function TasksManagementPage() {
|
||||
<thead className="bg-gray-50/75 border-b border-gray-100 text-gray-500 font-black">
|
||||
<tr>
|
||||
<th className="py-3 px-4">کد تسک</th>
|
||||
<th className="py-3 px-4 cursor-pointer select-none hover:text-purple-700" onClick={() => setSortOrder(prev => prev === 'desc' ? 'asc' : 'desc')}>
|
||||
<div className="flex items-center gap-1">
|
||||
<span>تاریخ و ساعت (تهران)</span>
|
||||
<span className="text-[10px] text-purple-600">({sortOrder === 'desc' ? '▼ جدیدترین' : '▲ قدیمیترین'})</span>
|
||||
</div>
|
||||
</th>
|
||||
<th className="py-3 px-4">عنوان و شرح وظیفه</th>
|
||||
<th className="py-3 px-4">دپارتمان</th>
|
||||
<th className="py-3 px-4">اولویت</th>
|
||||
@@ -326,6 +378,16 @@ export default function TasksManagementPage() {
|
||||
{task.code}
|
||||
</span>
|
||||
</td>
|
||||
<td className="py-3.5 px-4 whitespace-nowrap text-xs text-gray-600 font-medium" dir="ltr">
|
||||
{task.createdAt ? new Intl.DateTimeFormat('fa-IR', {
|
||||
timeZone: 'Asia/Tehran',
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
}).format(new Date(task.createdAt)) : '-'}
|
||||
</td>
|
||||
<td className="py-3.5 px-4">
|
||||
<div className="font-black text-gray-900 text-xs mb-0.5">{task.title}</div>
|
||||
{task.description && (
|
||||
@@ -443,8 +505,8 @@ export default function TasksManagementPage() {
|
||||
{/* Status Update Options */}
|
||||
<div className="pt-2">
|
||||
<label className="block text-xs font-black text-gray-700 mb-2">تغییر وضعیت تسک به:</label>
|
||||
<div className="grid grid-cols-4 gap-2">
|
||||
{['TODO', 'IN_PROGRESS', 'TEST', 'DONE'].map((st) => (
|
||||
<div className="grid grid-cols-3 sm:grid-cols-6 gap-2">
|
||||
{['TODO', 'IN_PROGRESS', 'TEST', 'WAITING_DEPENDENCIES', 'DONE', 'REJECTED'].map((st) => (
|
||||
<button
|
||||
key={st}
|
||||
type="button"
|
||||
@@ -473,16 +535,52 @@ export default function TasksManagementPage() {
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Execution Logs */}
|
||||
{/* Status History & Transitions Summary */}
|
||||
{activeTaskModal.executionLogs && (() => {
|
||||
const summary = getStatusTransitionsSummary(activeTaskModal.executionLogs);
|
||||
return (
|
||||
<div className="p-3 bg-purple-50/50 rounded-2xl border border-purple-100 space-y-2">
|
||||
<div className="font-bold text-purple-900 text-[11px] flex items-center justify-between">
|
||||
<span>آمار چرخهها و وضعیتهای طیشده تسک:</span>
|
||||
<span className="font-mono text-[10px] text-purple-700 bg-white px-2 py-0.5 rounded-full border border-purple-200">
|
||||
{summary.totalEvents} رکورد ثبتی
|
||||
</span>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
|
||||
<div className="bg-white p-2 rounded-xl border border-blue-100 text-center shadow-xs">
|
||||
<span className="block text-[10px] text-gray-500 font-bold">دفعات ارجاع به اجرا</span>
|
||||
<span className="text-xs font-black text-blue-700 font-mono">{summary.inProgressCount} بار</span>
|
||||
</div>
|
||||
<div className="bg-white p-2 rounded-xl border border-amber-100 text-center shadow-xs">
|
||||
<span className="block text-[10px] text-gray-500 font-bold">بررسی تست و QA</span>
|
||||
<span className="text-xs font-black text-amber-700 font-mono">{summary.testCount} بار</span>
|
||||
</div>
|
||||
<div className="bg-white p-2 rounded-xl border border-rose-100 text-center shadow-xs">
|
||||
<span className="block text-[10px] text-gray-500 font-bold">عدم تایید QA</span>
|
||||
<span className="text-xs font-black text-rose-700 font-mono">{summary.qaRejectedCount} بار</span>
|
||||
</div>
|
||||
<div className="bg-white p-2 rounded-xl border border-emerald-100 text-center shadow-xs">
|
||||
<span className="block text-[10px] text-gray-500 font-bold">تاییدیه کیفی</span>
|
||||
<span className="text-xs font-black text-emerald-700">{summary.qaPassedCount > 0 ? 'دارد (تایید)' : 'در جریان'}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
|
||||
{/* Execution Logs Timeline */}
|
||||
{activeTaskModal.executionLogs && (
|
||||
<div className="pt-2 space-y-1">
|
||||
<div className="font-bold text-gray-600 text-[11px]">تاریخچه اقدامات انجامشده روی این تسک:</div>
|
||||
<div className="space-y-1 max-h-36 overflow-y-auto">
|
||||
<div className="pt-2 space-y-1.5">
|
||||
<div className="font-bold text-gray-600 text-[11px] flex items-center justify-between">
|
||||
<span>تایملاین رویدادها و تغییر وضعیتها:</span>
|
||||
<span className="text-[10px] text-gray-400">(به وقت تهران)</span>
|
||||
</div>
|
||||
<div className="space-y-1.5 max-h-48 overflow-y-auto p-1">
|
||||
{renderExecutionLogs(activeTaskModal.executionLogs).map((lg: any, i: number) => (
|
||||
<div key={i} className="text-[10px] p-2 bg-gray-50 rounded-lg flex items-center justify-between">
|
||||
<span className="font-bold text-gray-800">{lg.note || JSON.stringify(lg)}</span>
|
||||
<span className="text-gray-400 font-mono">
|
||||
{lg.timestamp ? new Date(lg.timestamp).toLocaleTimeString('fa-IR') : '-'}
|
||||
<div key={i} className="text-[10px] p-2.5 bg-gray-50 hover:bg-gray-100/70 rounded-xl flex items-start justify-between gap-3 border border-gray-100 transition-colors">
|
||||
<span className="font-bold text-gray-800 leading-relaxed text-right flex-1">{lg.note || JSON.stringify(lg)}</span>
|
||||
<span className="text-gray-400 font-mono text-[9px] whitespace-nowrap dir-ltr pt-0.5">
|
||||
{lg.timestamp ? new Date(lg.timestamp).toLocaleString('fa-IR', { hour: '2-digit', minute: '2-digit', second: '2-digit', day: '2-digit', month: '2-digit' }) : '-'}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
|
||||
@@ -50,9 +50,11 @@ 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'));
|
||||
const CompanyOrchestrationHQ = lazyWithRetry(() => import('../pages/CompanyOrchestrationHQ'));
|
||||
|
||||
export interface AdminRouteConfig {
|
||||
path: string;
|
||||
@@ -119,8 +121,10 @@ 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 /> },
|
||||
],
|
||||
},
|
||||
],
|
||||
|
||||
@@ -124,6 +124,19 @@ export default function ClientLayout({ children }: { children: React.ReactNode }
|
||||
}, [pathname]);
|
||||
|
||||
|
||||
|
||||
// Global listener for Smart Advisor / Consultation CTA to trigger Support Chat
|
||||
useEffect(() => {
|
||||
const handleGlobalClick = (e: MouseEvent) => {
|
||||
const target = (e.target as HTMLElement)?.closest('button');
|
||||
if (target && target.innerText && target.innerText.includes('مشاوره هوشمند دارویی')) {
|
||||
window.dispatchEvent(new CustomEvent('canina:open-support-chat'));
|
||||
}
|
||||
};
|
||||
document.addEventListener('click', handleGlobalClick);
|
||||
return () => document.removeEventListener('click', handleGlobalClick);
|
||||
}, []);
|
||||
|
||||
// Check Maintenance Mode (Admin / Partner bypass)
|
||||
const isMaintenanceMode = getText('MAINTENANCE_MODE', 'false') === 'true' || getText('maintenance_mode', 'false') === 'true';
|
||||
const isAdmin = role === 'User_Partner' || (typeof window !== 'undefined' && Boolean(localStorage.getItem('adminToken')));
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
import { revalidatePath, revalidateTag } from "next/cache";
|
||||
import { POST } from "./route";
|
||||
|
||||
vi.mock("next/cache", () => ({ revalidatePath: vi.fn(), revalidateTag: vi.fn() }));
|
||||
|
||||
describe("revalidation route", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
process.env.REVALIDATION_SECRET = "test-secret";
|
||||
});
|
||||
|
||||
it("revalidates deduplicated tag and path batches", async () => {
|
||||
const request = new NextRequest("http://localhost/api/revalidate", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", "x-revalidate-secret": "test-secret" },
|
||||
body: JSON.stringify({ tags: ["blogs", "blogs"], paths: ["/blog", "/blog"] }),
|
||||
});
|
||||
|
||||
const response = await POST(request);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(revalidateTag).toHaveBeenCalledTimes(1);
|
||||
expect(revalidateTag).toHaveBeenCalledWith("blogs", "default");
|
||||
expect(revalidatePath).toHaveBeenCalledTimes(1);
|
||||
expect(revalidatePath).toHaveBeenCalledWith("/blog", "page");
|
||||
});
|
||||
});
|
||||
@@ -12,69 +12,41 @@ export async function POST(request: NextRequest) {
|
||||
async function handleRevalidate(request: NextRequest) {
|
||||
const { searchParams } = new URL(request.url);
|
||||
let secret = searchParams.get('secret') || request.headers.get('x-revalidate-secret');
|
||||
let tag = searchParams.get('tag');
|
||||
let path = searchParams.get('path');
|
||||
let tags: unknown[] = searchParams.getAll('tag');
|
||||
let paths: unknown[] = searchParams.getAll('path');
|
||||
|
||||
// Check auth header if bearer token provided
|
||||
const authHeader = request.headers.get('authorization');
|
||||
if (authHeader && authHeader.startsWith('Bearer ')) {
|
||||
secret = authHeader.substring(7);
|
||||
}
|
||||
if (authHeader?.startsWith('Bearer ')) secret = authHeader.substring(7);
|
||||
|
||||
if (request.method === 'POST') {
|
||||
try {
|
||||
const body = await request.json().catch(() => ({}));
|
||||
if (body && typeof body === 'object') {
|
||||
if (body.secret) secret = body.secret;
|
||||
if (body.tag) tag = body.tag;
|
||||
if (body.path) path = body.path;
|
||||
}
|
||||
} catch {
|
||||
// Ignore body read error
|
||||
const body = await request.json().catch(() => ({}));
|
||||
if (body && typeof body === 'object') {
|
||||
if (body.secret) secret = body.secret;
|
||||
if (body.tag) tags = [body.tag];
|
||||
if (Array.isArray(body.tags)) tags = body.tags;
|
||||
if (body.path) paths = [body.path];
|
||||
if (Array.isArray(body.paths)) paths = body.paths;
|
||||
}
|
||||
}
|
||||
|
||||
const expectedSecret = process.env.REVALIDATION_SECRET;
|
||||
if (!expectedSecret) {
|
||||
return NextResponse.json(
|
||||
{ success: false, message: 'Revalidation service is not configured' },
|
||||
{ status: 503 }
|
||||
);
|
||||
return NextResponse.json({ success: false, message: 'Revalidation service is not configured' }, { status: 503 });
|
||||
}
|
||||
|
||||
if (!secret || secret !== expectedSecret) {
|
||||
return NextResponse.json(
|
||||
{ success: false, message: 'Invalid revalidation secret token' },
|
||||
{ status: 401 }
|
||||
);
|
||||
return NextResponse.json({ success: false, message: 'Invalid revalidation secret token' }, { status: 401 });
|
||||
}
|
||||
|
||||
if (!tag && !path) {
|
||||
return NextResponse.json(
|
||||
{ success: false, message: 'Missing tag or path parameter for cache revalidation' },
|
||||
{ status: 400 }
|
||||
);
|
||||
const cleanTags = [...new Set(tags.filter((value): value is string => typeof value === 'string' && value.length > 0))];
|
||||
const cleanPaths = [...new Set(paths.filter((value): value is string => typeof value === 'string' && value.startsWith('/')))];
|
||||
if (!cleanTags.length && !cleanPaths.length) {
|
||||
return NextResponse.json({ success: false, message: 'Missing tag or path parameter for cache revalidation' }, { status: 400 });
|
||||
}
|
||||
|
||||
const revalidated: { tag?: string; path?: string } = {};
|
||||
|
||||
if (tag) {
|
||||
revalidateTag(tag, 'default');
|
||||
revalidated.tag = tag;
|
||||
for (const tag of cleanTags) revalidateTag(tag, 'default');
|
||||
for (const path of cleanPaths) {
|
||||
try { revalidatePath(path, 'page'); } catch { revalidatePath(path); }
|
||||
}
|
||||
|
||||
if (path) {
|
||||
try {
|
||||
revalidatePath(path, 'page');
|
||||
} catch {
|
||||
revalidatePath(path);
|
||||
}
|
||||
revalidated.path = path;
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
revalidated: true,
|
||||
...revalidated,
|
||||
now: Date.now(),
|
||||
});
|
||||
return NextResponse.json({ revalidated: true, tags: cleanTags, paths: cleanPaths, now: Date.now() });
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import React from 'react';
|
||||
import BlogPostPage from './page';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import BlogPostPage, { generateMetadata } from './page';
|
||||
|
||||
vi.mock('../../../lib/seo', () => ({
|
||||
getSeoConfig: vi.fn().mockResolvedValue({
|
||||
@@ -15,7 +16,9 @@ vi.mock('../../../lib/seo', () => ({
|
||||
}));
|
||||
|
||||
vi.mock('../../../components/BlogPostClient', () => ({
|
||||
default: () => <div data-testid="blog-post-client" />,
|
||||
default: ({ authorName, authorTeam }: { authorName: string; authorTeam: string }) => (
|
||||
<div data-testid="blog-post-client">نویسنده: {authorName} تیم: {authorTeam}</div>
|
||||
),
|
||||
}));
|
||||
|
||||
describe('BlogPostPage FAQPage Schema injection (SEO-P1-07)', () => {
|
||||
@@ -74,6 +77,59 @@ describe('BlogPostPage FAQPage Schema injection (SEO-P1-07)', () => {
|
||||
expect(faqJson.mainEntity[0].name).toBe('آیا این مکمل برای سگ مسن مناسب است؟');
|
||||
});
|
||||
|
||||
it('uses explicit same-day material freshness for dateModified and ignores technical updatedAt', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ok:true,json:async()=>({slug:'fresh',title:'Fresh',content:'<p>x</p>',publishedAt:'2026-01-01T01:00:00Z',updatedAt:'2026-01-01T10:00:00Z',contentUpdatedAt:'2026-01-01T12:00:00Z'})}));
|
||||
const jsx=await BlogPostPage({params:Promise.resolve({slug:'fresh'})}); const script:any=React.Children.toArray(jsx.props.children)[0]; const json=JSON.parse(script.props.dangerouslySetInnerHTML.__html); expect(json.dateModified).toBe('2026-01-01T12:00:00.000Z'); expect(json.author['@type']).toBe('Organization'); expect(json.author.name).toBe('کنینا');
|
||||
});
|
||||
|
||||
it('omits dateModified when only technical updatedAt exists', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ok:true,json:async()=>({slug:'technical',title:'Technical',content:'<p>x</p>',publishedAt:'2026-01-01T01:00:00Z',updatedAt:'2026-01-01T12:00:00Z',contentUpdatedAt:null})}));
|
||||
const jsx=await BlogPostPage({params:Promise.resolve({slug:'technical'})}); const script:any=React.Children.toArray(jsx.props.children)[0]; const json=JSON.parse(script.props.dangerouslySetInnerHTML.__html); expect(json.dateModified).toBeUndefined();
|
||||
});
|
||||
|
||||
it('uses the stable Organization fallback visibly and in metadata', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: async () => ({
|
||||
slug: 'authorless', title: 'Authorless', content: '<p>x</p>', publishedAt: '2026-01-01T00:00:00Z', author: { firstName: '', lastName: '' },
|
||||
}) }));
|
||||
|
||||
const metadata = await generateMetadata({ params: Promise.resolve({ slug: 'authorless' }) });
|
||||
expect((metadata.openGraph as any)?.authors).toEqual(['کنینا']);
|
||||
|
||||
const jsx = await BlogPostPage({ params: Promise.resolve({ slug: 'authorless' }) });
|
||||
const children = React.Children.toArray(jsx.props.children) as any[];
|
||||
const client = children.find((child) => child?.props?.authorName);
|
||||
expect(client.props.authorName).toBe('کنینا');
|
||||
const article = JSON.parse(children[0].props.dangerouslySetInnerHTML.__html);
|
||||
expect(article.author).toMatchObject({
|
||||
'@type': 'Organization',
|
||||
name: 'کنینا',
|
||||
});
|
||||
});
|
||||
|
||||
it('uses a custom authorTeam as the authorless Organization identity in metadata and rendering', async () => {
|
||||
const organizationName = 'تیم دامپزشکی کنینا';
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: async () => ({
|
||||
slug: 'custom-team',
|
||||
title: 'Custom team article',
|
||||
content: '<p>x</p>',
|
||||
publishedAt: '2026-01-01T00:00:00Z',
|
||||
author: null,
|
||||
authorTeam: organizationName,
|
||||
}) }));
|
||||
|
||||
const metadata = await generateMetadata({ params: Promise.resolve({ slug: 'custom-team' }) });
|
||||
expect((metadata.openGraph as any)?.authors).toEqual(['کنینا']);
|
||||
|
||||
const jsx = await BlogPostPage({ params: Promise.resolve({ slug: 'custom-team' }) });
|
||||
const children = React.Children.toArray(jsx.props.children) as any[];
|
||||
const article = JSON.parse(children[0].props.dangerouslySetInnerHTML.__html);
|
||||
expect(article.author).toMatchObject({ '@type': 'Organization', name: 'کنینا' });
|
||||
|
||||
const html = renderToStaticMarkup(jsx);
|
||||
expect(html).toContain('نویسنده: کنینا');
|
||||
expect(html).toContain(`تیم: ${organizationName}`);
|
||||
});
|
||||
|
||||
it('does not inject FAQPage schema when article does not have FAQs', async () => {
|
||||
const blogData = {
|
||||
slug: 'nutrition',
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { validContentUpdatedAt } from "../../../lib/blogDates";
|
||||
import { resolveBlogAuthorIdentity } from "../../../lib/blogAuthor";
|
||||
import React from "react";
|
||||
import { notFound } from 'next/navigation';
|
||||
import type { Metadata } from 'next';
|
||||
@@ -90,12 +92,10 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str
|
||||
siteUrl.includes('test') ||
|
||||
siteUrl.includes('dev');
|
||||
|
||||
const authorName = blog.author
|
||||
? `${blog.author.firstName || ''} ${blog.author.lastName || ''}`.trim() || 'نویسنده کنینا'
|
||||
: 'نویسنده و پژوهشگر کنینا';
|
||||
const resolvedAuthor = resolveBlogAuthorIdentity(blog);
|
||||
|
||||
const publishedTime = safeIso(blog.publishedAt) || safeIso(blog.createdAt);
|
||||
const modifiedTime = safeIso(blog.updatedAt) || publishedTime;
|
||||
const modifiedTime = safeIso(validContentUpdatedAt(blog));
|
||||
|
||||
const keywordsList = blog.focusKeywords
|
||||
? blog.focusKeywords.split(',').map((k: string) => k.trim())
|
||||
@@ -147,8 +147,8 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str
|
||||
siteName: config.brandNameFa,
|
||||
type: "article",
|
||||
publishedTime,
|
||||
modifiedTime,
|
||||
authors: [authorName],
|
||||
...(modifiedTime ? { modifiedTime } : {}),
|
||||
authors: [resolvedAuthor.name],
|
||||
tags: blog.tags?.map((t: any) => typeof t === 'string' ? t : t?.name).filter(Boolean) || [],
|
||||
},
|
||||
twitter: {
|
||||
@@ -172,9 +172,7 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug:
|
||||
const rawSiteUrl = process.env.NEXT_PUBLIC_SITE_URL || config.canonicalBaseUrl || 'https://canina.ir';
|
||||
const siteUrl = rawSiteUrl.replace(/\/+$/, '');
|
||||
|
||||
const authorName = blog.author
|
||||
? `${blog.author.firstName || ''} ${blog.author.lastName || ''}`.trim() || 'نویسنده کنینا'
|
||||
: 'نویسنده و پژوهشگر کنینا';
|
||||
const resolvedAuthor = resolveBlogAuthorIdentity(blog);
|
||||
const publishedDate = safeLocalDate(blog.publishedAt) || safeLocalDate(blog.createdAt);
|
||||
|
||||
const canonicalUrl = blog.canonicalUrl
|
||||
@@ -182,20 +180,19 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug:
|
||||
: `${siteUrl}/blog/${slug}`;
|
||||
|
||||
const publishedIso = safeIso(blog.publishedAt) || safeIso(blog.createdAt) || new Date().toISOString();
|
||||
const modifiedIso = safeIso(blog.updatedAt) || publishedIso;
|
||||
const modifiedIso = safeIso(validContentUpdatedAt(blog));
|
||||
|
||||
const sanitizedContent = sanitizeBlogHtml(blog.content);
|
||||
const schemaType = blog.schemaType || 'BlogPosting';
|
||||
|
||||
const authorSchema = blog.author && (blog.author.firstName || blog.author.lastName)
|
||||
const authorSchema = resolvedAuthor.type === 'Person'
|
||||
? {
|
||||
'@type': 'Person',
|
||||
name: authorName,
|
||||
url: `${siteUrl}/about`,
|
||||
name: resolvedAuthor.name,
|
||||
}
|
||||
: {
|
||||
'@type': 'Organization',
|
||||
name: config.brandNameFa || 'کنینا ایران',
|
||||
name: resolvedAuthor.name,
|
||||
url: siteUrl,
|
||||
};
|
||||
|
||||
@@ -212,7 +209,7 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug:
|
||||
? [blog.imageUrl.startsWith('http') ? blog.imageUrl : `${siteUrl}${blog.imageUrl.startsWith('/') ? '' : '/'}${blog.imageUrl}`]
|
||||
: [config.ogImageUrl.startsWith('http') ? config.ogImageUrl : `${siteUrl}${config.ogImageUrl.startsWith('/') ? '' : '/'}${config.ogImageUrl}`],
|
||||
datePublished: publishedIso,
|
||||
dateModified: modifiedIso,
|
||||
...(modifiedIso ? { dateModified: modifiedIso } : {}),
|
||||
author: authorSchema,
|
||||
publisher: {
|
||||
'@type': 'Organization',
|
||||
@@ -292,7 +289,8 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug:
|
||||
<BlogPostClient
|
||||
blog={blog}
|
||||
publishedDate={publishedDate}
|
||||
authorName={authorName}
|
||||
authorName={resolvedAuthor.name}
|
||||
authorTeam={resolvedAuthor.teamName}
|
||||
sanitizedContent={sanitizedContent}
|
||||
/>
|
||||
</>
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import Blog from "./page";
|
||||
|
||||
const blogPageSpy = vi.fn();
|
||||
|
||||
vi.mock("../../components/BlogPage", () => ({
|
||||
default: (props: unknown) => {
|
||||
blogPageSpy(props);
|
||||
return null;
|
||||
},
|
||||
}));
|
||||
vi.mock("../../lib/seo", () => ({ getPageMetadata: vi.fn() }));
|
||||
vi.mock("../../lib/media", () => ({ getMediaUrl: (value: string) => value }));
|
||||
|
||||
describe("blog page author identity", () => {
|
||||
beforeEach(() => {
|
||||
blogPageSpy.mockClear();
|
||||
vi.stubGlobal("fetch", vi.fn()
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({ data: [{ id: "b1", slug: "post", title: "Post", content: "Body" }] }),
|
||||
})
|
||||
.mockResolvedValueOnce({ ok: true, json: async () => ({ data: [] }) }));
|
||||
});
|
||||
|
||||
it("uses the scientific content team for an authorless blog card", async () => {
|
||||
const element = await Blog({ searchParams: Promise.resolve({}) });
|
||||
element.type(element.props);
|
||||
|
||||
const props = blogPageSpy.mock.calls[0][0] as { blogs: Array<{ author: string }> };
|
||||
expect(props.blogs[0].author).toBe("کنینا");
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import BlogPage from "../../components/BlogPage";
|
||||
import type { Metadata } from 'next';
|
||||
import { getPageMetadata } from "../../lib/seo";
|
||||
import { getMediaUrl } from "../../lib/media";
|
||||
import { resolveBlogAuthor } from "../../lib/blogAuthor";
|
||||
|
||||
export async function generateMetadata(): Promise<Metadata> {
|
||||
return getPageMetadata('blog', {
|
||||
@@ -43,8 +44,7 @@ async function getBlogs() {
|
||||
const data = await res.json();
|
||||
const list = Array.isArray(data.data) ? data.data : Array.isArray(data) ? data : [];
|
||||
return list.map((b: any) => {
|
||||
const authorObj = b.author as Record<string, string> | undefined;
|
||||
const authorName = authorObj ? `${authorObj.firstName || ''} ${authorObj.lastName || ''}`.trim() : 'نویسنده کنینا';
|
||||
const authorName = resolveBlogAuthor(b.author);
|
||||
return {
|
||||
id: String(b.id || ''),
|
||||
slug: String(b.slug || ''),
|
||||
@@ -53,6 +53,11 @@ async function getBlogs() {
|
||||
category: b.category?.name || 'دانشنامه و سلامت',
|
||||
categoryId: b.categoryId || undefined,
|
||||
tags: b.tags || [],
|
||||
publishedAt: b.publishedAt,
|
||||
createdAt: b.createdAt,
|
||||
contentUpdatedAt: b.contentUpdatedAt,
|
||||
authorTeam: b.authorTeam,
|
||||
authorRole: b.authorRole,
|
||||
date: b.publishedAt
|
||||
? new Date(String(b.publishedAt)).toLocaleDateString('fa-IR')
|
||||
: b.createdAt
|
||||
@@ -61,7 +66,7 @@ async function getBlogs() {
|
||||
readingTime: b.readingTime || 3,
|
||||
image: getMediaUrl(String(b.imageUrl || b.coverImage || '/assets/images/blog-placeholder.png')),
|
||||
imageAlt: b.imageAlt || b.title,
|
||||
author: authorName || 'نویسنده کنینا',
|
||||
author: authorName,
|
||||
content: String(b.content || ''),
|
||||
featured: Boolean(b.featured),
|
||||
viewCount: Number(b.viewCount) || 0,
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
import { afterEach,describe,expect,it,vi } from "vitest";
|
||||
import { GET } from "./route";
|
||||
afterEach(()=>{vi.unstubAllGlobals();vi.unstubAllEnvs()});
|
||||
describe("blog RSS dates",()=>{it("keeps pubDate immutable and derives lastBuildDate from real valid dates",async()=>{vi.stubEnv("NEXT_PUBLIC_SITE_URL","https://canina.ir");vi.stubGlobal("fetch",vi.fn().mockResolvedValue({ok:true,json:async()=>({data:[{slug:"a",title:"A",status:"PUBLISHED",publishedAt:"2026-01-01T00:00:00Z",contentUpdatedAt:"2026-01-03T00:00:00Z",updatedAt:"2026-01-04T00:00:00Z"}]})}));const xml=await (await GET()).text();expect(xml).toContain(`<pubDate>${new Date("2026-01-01T00:00:00Z").toUTCString()}</pubDate>`);expect(xml).toContain(`<lastBuildDate>${new Date("2026-01-03T00:00:00Z").toUTCString()}</lastBuildDate>`);});it("uses the stable fallback author for authorless posts",async()=>{vi.stubGlobal("fetch",vi.fn().mockResolvedValue({ok:true,json:async()=>({data:[{slug:"a",title:"A",status:"PUBLISHED",publishedAt:"2026-01-01T00:00:00Z",author:{firstName:"",lastName:""}}]})}));const xml=await (await GET()).text();expect(xml).toContain("<author>کنینا</author>");});});
|
||||
@@ -1,3 +1,5 @@
|
||||
import { validContentUpdatedAt, publicationDate } from '../../../lib/blogDates';
|
||||
import { BLOG_AUTHOR_FALLBACK } from '../../../lib/blogAuthor';
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
@@ -23,8 +25,9 @@ export async function GET() {
|
||||
const title = escapeXml(b.title || '');
|
||||
const link = `${baseUrl}/blog/${b.slug}`;
|
||||
const description = escapeXml(b.excerpt || b.metaDescription || '');
|
||||
const pubDate = b.publishedAt ? new Date(b.publishedAt).toUTCString() : b.createdAt ? new Date(b.createdAt).toUTCString() : new Date().toUTCString();
|
||||
const author = escapeXml(b.author ? `${b.author.firstName || ''} ${b.author.lastName || ''}`.trim() : 'کنینا فارما');
|
||||
const pubDate = new Date(publicationDate(b)!).toUTCString();
|
||||
const personName = b.author ? `${b.author.firstName || ''} ${b.author.lastName || ''}`.trim() : '';
|
||||
const author = escapeXml(personName || BLOG_AUTHOR_FALLBACK);
|
||||
const category = escapeXml(b.category?.name || 'دانشنامه سلامت حیوانات');
|
||||
|
||||
return `
|
||||
@@ -41,6 +44,8 @@ export async function GET() {
|
||||
})
|
||||
.join('');
|
||||
|
||||
const realDates = blogs.map((b) => validContentUpdatedAt(b) || publicationDate(b)).filter((d): d is string => Boolean(d)).map((d) => new Date(d).getTime());
|
||||
const lastBuildDate = realDates.length ? new Date(Math.max(...realDates)).toUTCString() : undefined;
|
||||
const rssFeed = `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
|
||||
<channel>
|
||||
@@ -48,7 +53,7 @@ export async function GET() {
|
||||
<link>${baseUrl}/blog</link>
|
||||
<description>جدیدترین مقالات علمی در زمینه مکملهای تخصصی، تغذیه و سلامت سگ و گربه از داروسازی کنینا آلمان</description>
|
||||
<language>fa-ir</language>
|
||||
<lastBuildDate>${new Date().toUTCString()}</lastBuildDate>
|
||||
${lastBuildDate ? `<lastBuildDate>${lastBuildDate}</lastBuildDate>` : ""}
|
||||
<atom:link href="${baseUrl}/blog/rss.xml" rel="self" type="application/rss+xml"/>
|
||||
${itemsXml}
|
||||
</channel>
|
||||
|
||||
@@ -186,3 +186,21 @@
|
||||
.animate-marquee:hover {
|
||||
animation-play-state: paused;
|
||||
}
|
||||
|
||||
/* Article Links & Provenance Styling */
|
||||
.article-html-content a,
|
||||
.prose a {
|
||||
color: var(--color-canina-blue) !important;
|
||||
font-weight: 700 !important;
|
||||
text-decoration: underline !important;
|
||||
text-decoration-color: rgba(30, 64, 83, 0.4) !important;
|
||||
text-underline-offset: 4px !important;
|
||||
transition: all 0.2s ease-in-out !important;
|
||||
}
|
||||
|
||||
.article-html-content a:hover,
|
||||
.prose a:hover {
|
||||
color: #0052cc !important;
|
||||
text-decoration-color: #0052cc !important;
|
||||
opacity: 1 !important;
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { validContentUpdatedAt, publicationDate } from '../../lib/blogDates';
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
@@ -7,7 +8,8 @@ type SitemapBlog = {
|
||||
slug: string;
|
||||
noIndex?: boolean;
|
||||
status: string;
|
||||
updatedAt?: string;
|
||||
publishedAt?: string;
|
||||
contentUpdatedAt?: string;
|
||||
createdAt?: string;
|
||||
featured?: boolean;
|
||||
title?: string;
|
||||
@@ -47,11 +49,7 @@ export async function GET() {
|
||||
const urlsXml = blogRoutes
|
||||
.map((blog) => {
|
||||
const loc = `${baseUrl}/blog/${encodeURIComponent(blog.slug)}`;
|
||||
const lastmod = blog.updatedAt
|
||||
? new Date(blog.updatedAt).toISOString()
|
||||
: blog.createdAt
|
||||
? new Date(blog.createdAt).toISOString()
|
||||
: new Date().toISOString();
|
||||
const lastmod = new Date(validContentUpdatedAt(blog) || publicationDate(blog)!).toISOString();
|
||||
const priority = blog.featured ? '0.9' : '0.7';
|
||||
const primaryImg = blog.ogImage || blog.imageUrl;
|
||||
const title = blog.title || 'مقاله وبلاگ تخصصی کنینا';
|
||||
|
||||
@@ -16,7 +16,7 @@ describe('sitemap blog retrieval', () => {
|
||||
vi.stubEnv('NEXT_PUBLIC_SITE_URL', 'https://stage.canina.ir');
|
||||
const fetchMock = vi.fn()
|
||||
.mockResolvedValueOnce({ ok: true, json: async () => ({ data: [
|
||||
{ slug: 'first', status: 'PUBLISHED', updatedAt: '2026-10-01', featured: true },
|
||||
{ slug: 'first', status: 'PUBLISHED', publishedAt: '2026-10-01', contentUpdatedAt: '2026-10-02', updatedAt: '2026-10-03', featured: true },
|
||||
{ slug: 'hidden', status: 'PUBLISHED', noIndex: true },
|
||||
{ slug: 'draft', status: 'DRAFT' },
|
||||
], meta: { lastPage: 2 } }) })
|
||||
@@ -32,7 +32,7 @@ describe('sitemap blog retrieval', () => {
|
||||
const blogs = routes.filter(r => r.url.includes('/blog/'));
|
||||
expect(blogs.map(r => r.url)).toEqual(['https://stage.canina.ir/blog/first', 'https://stage.canina.ir/blog/last']);
|
||||
expect(blogs[0].priority).toBe(0.9);
|
||||
expect(blogs[0].lastModified).toEqual(new Date('2026-10-01'));
|
||||
expect(blogs[0].lastModified).toEqual(new Date('2026-10-02'));
|
||||
});
|
||||
|
||||
it('terminates on an empty page even when pagination metadata is stale', async () => {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { MetadataRoute } from 'next';
|
||||
import { validContentUpdatedAt, publicationDate } from '../lib/blogDates';
|
||||
import { productService } from '../lib/services/productService';
|
||||
|
||||
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
|
||||
@@ -86,7 +87,7 @@ export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
|
||||
const apiUrl = process.env.INTERNAL_API_URL || process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4001/api';
|
||||
const normalizedApiUrl = apiUrl.replace(/\/$/, '');
|
||||
const apiBase = normalizedApiUrl.endsWith('/api') ? normalizedApiUrl : `${normalizedApiUrl}/api`;
|
||||
type SitemapBlog = { slug: string; noIndex?: boolean; status: string; updatedAt?: string; featured?: boolean };
|
||||
type SitemapBlog = { slug:string; noIndex?:boolean; status:string; publishedAt?:string; createdAt?:string; contentUpdatedAt?:string; featured?:boolean };
|
||||
// The public list includes article bodies. Keep requests small and bypass
|
||||
// Next's 2MB per-entry data cache, even for an unusually large article.
|
||||
let page = 1;
|
||||
@@ -101,7 +102,7 @@ export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
|
||||
.filter((b) => !b.noIndex && b.status === 'PUBLISHED')
|
||||
.map((b): MetadataRoute.Sitemap[number] => ({
|
||||
url: `${baseUrl}/blog/${b.slug}`,
|
||||
lastModified: b.updatedAt ? new Date(b.updatedAt) : new Date(),
|
||||
lastModified: new Date(validContentUpdatedAt(b) || publicationDate(b)!),
|
||||
changeFrequency: 'weekly',
|
||||
priority: b.featured ? 0.9 : 0.7,
|
||||
})));
|
||||
|
||||
@@ -36,7 +36,9 @@ describe('Sub-sitemaps and robots.ts integration (SEO-P1-10)', () => {
|
||||
slug: 'puppy-nutrition',
|
||||
title: 'تغذیه توله سگ',
|
||||
status: 'PUBLISHED',
|
||||
updatedAt: '2026-10-10T12:00:00.000Z',
|
||||
updatedAt: '2026-10-12T12:00:00.000Z',
|
||||
publishedAt: '2026-10-10T12:00:00.000Z',
|
||||
contentUpdatedAt: '2026-10-11T12:00:00.000Z',
|
||||
featured: true,
|
||||
imageUrl: '/uploads/puppy.jpg',
|
||||
},
|
||||
@@ -57,6 +59,7 @@ describe('Sub-sitemaps and robots.ts integration (SEO-P1-10)', () => {
|
||||
|
||||
expect(xml).toContain('<loc>https://canina.ir/blog/puppy-nutrition</loc>');
|
||||
expect(xml).toContain('<priority>0.9</priority>');
|
||||
expect(xml).toContain('<lastmod>2026-10-11T12:00:00.000Z</lastmod>');
|
||||
expect(xml).toContain('<image:loc>https://canina.ir/uploads/puppy.jpg</image:loc>');
|
||||
expect(xml).toContain('تغذیه توله سگ');
|
||||
expect(xml).not.toContain('hidden-blog');
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect } from 'react';
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { usePathname } from 'next/navigation';
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
dataLayer?: any[];
|
||||
clarity?: any;
|
||||
gtag?: (...args: any[]) => void;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,12 +18,46 @@ interface AnalyticsDeferredProps {
|
||||
}
|
||||
|
||||
export default function AnalyticsDeferred({ gtmId, gaId, clarityId }: AnalyticsDeferredProps) {
|
||||
const pathname = usePathname();
|
||||
const loadedRef = useRef(false);
|
||||
const initialPathRef = useRef<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!initialPathRef.current && pathname) {
|
||||
initialPathRef.current = pathname;
|
||||
}
|
||||
}, [pathname]);
|
||||
|
||||
// Track client-side page views on Next.js route transitions
|
||||
useEffect(() => {
|
||||
if (!pathname || !loadedRef.current) return;
|
||||
if (pathname === initialPathRef.current) return;
|
||||
|
||||
// 1. Google Analytics 4 page_view event on client navigation
|
||||
if (gaId && typeof window !== 'undefined' && typeof window.gtag === 'function') {
|
||||
window.gtag('event', 'page_view', {
|
||||
page_path: pathname,
|
||||
page_location: window.location.href,
|
||||
page_title: typeof document !== 'undefined' ? document.title : '',
|
||||
});
|
||||
}
|
||||
|
||||
// 2. Google Tag Manager page_view event on client navigation
|
||||
if (gtmId && typeof window !== 'undefined' && Array.isArray(window.dataLayer)) {
|
||||
window.dataLayer.push({
|
||||
event: 'page_view',
|
||||
page_path: pathname,
|
||||
});
|
||||
}
|
||||
}, [pathname, gaId, gtmId]);
|
||||
|
||||
useEffect(() => {
|
||||
let loaded = false;
|
||||
|
||||
const loadAnalytics = () => {
|
||||
if (loaded) return;
|
||||
loaded = true;
|
||||
loadedRef.current = true;
|
||||
|
||||
// Clean up event listeners
|
||||
window.removeEventListener('scroll', loadAnalytics);
|
||||
@@ -42,10 +78,12 @@ export default function AnalyticsDeferred({ gtmId, gaId, clarityId }: AnalyticsD
|
||||
// 2. Google Analytics 4 (ensures GA4 hits fire directly even if GTM container lacks GA4 config tag)
|
||||
if (gaId) {
|
||||
window.dataLayer = window.dataLayer || [];
|
||||
function gtag(...args: any[]) {
|
||||
window.dataLayer?.push(args);
|
||||
function gtag(..._args: any[]) {
|
||||
// Note: Google's gtag.js specifically expects the native `arguments` object.
|
||||
// Pushing an ES6 Array causes gtag.js to silently ignore tracking commands.
|
||||
window.dataLayer?.push(arguments);
|
||||
}
|
||||
(window as any).gtag = gtag;
|
||||
window.gtag = gtag;
|
||||
gtag('js', new Date());
|
||||
gtag('config', gaId, { page_path: window.location.pathname });
|
||||
|
||||
@@ -94,6 +132,7 @@ export default function AnalyticsDeferred({ gtmId, gaId, clarityId }: AnalyticsD
|
||||
|
||||
return () => {
|
||||
loaded = true;
|
||||
loadedRef.current = false;
|
||||
clearTimeout(timer);
|
||||
if (idleId !== undefined) window.cancelIdleCallback(idleId);
|
||||
window.removeEventListener('scroll', loadAnalytics);
|
||||
|
||||
@@ -26,6 +26,7 @@ import { productService } from "../lib/services/productService";
|
||||
import { useRouter } from 'next/navigation';
|
||||
import Image from 'next/image';
|
||||
import SafeImage from './SafeImage';
|
||||
import { BLOG_TEAM_FALLBACK, publicationDate, validContentUpdatedAt, persianDate } from '../lib/blogDates';
|
||||
|
||||
export interface BlogCategory {
|
||||
id: string;
|
||||
@@ -42,6 +43,11 @@ export interface BlogPostItem {
|
||||
imageAlt?: string;
|
||||
date: string;
|
||||
author: string;
|
||||
authorTeam?: string;
|
||||
authorRole?: string;
|
||||
publishedAt?: string;
|
||||
createdAt?: string;
|
||||
contentUpdatedAt?: string;
|
||||
content: string;
|
||||
category?: string;
|
||||
categoryId?: string;
|
||||
@@ -324,10 +330,8 @@ export default function BlogPage({
|
||||
<div className="bg-canina-blue/10 px-3.5 py-1 rounded-full uppercase tracking-wider">
|
||||
{featuredPost.category || "پژوهش بالینی"}
|
||||
</div>
|
||||
<div className="flex items-center gap-1 text-medical-gray-400">
|
||||
<Calendar className="w-3.5 h-3.5" />
|
||||
{featuredPost.date}
|
||||
</div>
|
||||
<div className="flex items-center gap-1 text-medical-gray-400"><Calendar className="w-3.5 h-3.5" />تاریخ انتشار: <time dateTime={publicationDate(featuredPost)}>{persianDate(publicationDate(featuredPost))}</time></div>
|
||||
{validContentUpdatedAt(featuredPost) && <div className="text-medical-gray-400">آخرین بهروزرسانی: <time dateTime={validContentUpdatedAt(featuredPost)}>{persianDate(validContentUpdatedAt(featuredPost))}</time></div>}
|
||||
<div className="flex items-center gap-1 text-medical-gray-400">
|
||||
<Clock className="w-3.5 h-3.5" />
|
||||
{featuredPost.readingTime || 4} دقیقه مطالعه
|
||||
@@ -343,17 +347,18 @@ export default function BlogPage({
|
||||
<p className="text-sm sm:text-base text-medical-gray-500 mb-8 leading-relaxed line-clamp-3">
|
||||
{featuredPost.excerpt}
|
||||
</p>
|
||||
<div className="flex items-center justify-between pt-6 border-t border-medical-gray-100">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-10 h-10 bg-medical-gray-100 rounded-full flex items-center justify-center text-medical-gray-400">
|
||||
<div data-testid="featured-footer" className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-5 pt-6 border-t border-medical-gray-100">
|
||||
<div className="flex min-w-0 items-start gap-3">
|
||||
<div className="w-10 h-10 shrink-0 bg-medical-gray-100 rounded-full flex items-center justify-center text-medical-gray-400">
|
||||
<User className="w-5 h-5" />
|
||||
</div>
|
||||
<div className="text-xs">
|
||||
<div className="font-black text-medical-gray-900">{featuredPost.author}</div>
|
||||
<div className="font-bold text-medical-gray-400">تیم پژوهش کنینا</div>
|
||||
<div data-testid="featured-attribution" className="flex min-w-0 flex-col gap-1 text-xs">
|
||||
<div data-testid="featured-author-name" className="font-black text-medical-gray-900 whitespace-nowrap overflow-hidden text-ellipsis">نویسنده: {featuredPost.author}</div>
|
||||
<div data-testid="featured-team-name" className="font-bold text-medical-gray-400 whitespace-nowrap overflow-hidden text-ellipsis">تیم: {featuredPost.authorTeam || BLOG_TEAM_FALLBACK}</div>
|
||||
{featuredPost.authorRole && <div className="font-bold text-medical-gray-400 whitespace-nowrap overflow-hidden text-ellipsis">{featuredPost.authorRole}</div>}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 text-canina-blue font-black text-sm">
|
||||
<div data-testid="featured-read-more" className="flex shrink-0 items-center gap-2 self-end sm:self-auto text-canina-blue font-black text-sm whitespace-nowrap">
|
||||
<span>مطالعه مقاله کامل</span>
|
||||
<ArrowLeft className="w-4 h-4 group-hover:-translate-x-2 transition-transform" />
|
||||
</div>
|
||||
@@ -406,10 +411,8 @@ export default function BlogPage({
|
||||
</div>
|
||||
<div className="p-4 sm:p-7">
|
||||
<div className="flex items-center justify-between text-[11px] font-bold text-medical-gray-400 mb-3">
|
||||
<div className="flex items-center gap-1">
|
||||
<Calendar className="w-3 h-3" />
|
||||
{post.date}
|
||||
</div>
|
||||
<div className="flex items-center gap-1"><Calendar className="w-3 h-3" />تاریخ انتشار: <time dateTime={publicationDate(post)}>{persianDate(publicationDate(post))}</time></div>
|
||||
{validContentUpdatedAt(post) && <div>آخرین بهروزرسانی: <time dateTime={validContentUpdatedAt(post)}>{persianDate(validContentUpdatedAt(post))}</time></div>}
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex items-center gap-1">
|
||||
<Clock className="w-3 h-3" />
|
||||
@@ -430,12 +433,12 @@ export default function BlogPage({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="px-4 sm:px-7 pb-4 sm:pb-6 pt-2.5 border-t border-medical-gray-100 flex items-center justify-between">
|
||||
<div className="text-[11px] font-bold text-medical-gray-500 flex items-center gap-1.5">
|
||||
<User className="w-3.5 h-3.5 text-medical-gray-400" />
|
||||
<span>{post.author}</span>
|
||||
<div className="px-4 sm:px-7 pb-4 sm:pb-6 pt-2.5 border-t border-medical-gray-100 flex items-end justify-between gap-3">
|
||||
<div data-testid={`regular-attribution-${post.id}`} className="min-w-0 text-[11px] font-bold text-medical-gray-500 flex flex-col gap-1">
|
||||
<div className="flex min-w-0 items-center gap-1.5 whitespace-nowrap"><User className="w-3.5 h-3.5 shrink-0 text-medical-gray-400" /><span className="truncate">نویسنده: {post.author}</span></div>
|
||||
<div className="truncate whitespace-nowrap pr-5">تیم: {post.authorTeam || BLOG_TEAM_FALLBACK}</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-1 text-canina-blue font-black text-xs group-hover:underline">
|
||||
<div className="flex shrink-0 items-center gap-1 text-canina-blue font-black text-xs whitespace-nowrap group-hover:underline">
|
||||
<span>مطالعه</span>
|
||||
<ArrowLeft className="w-3.5 h-3.5 group-hover:-translate-x-1 transition-transform" />
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"use client";
|
||||
import { BLOG_TEAM_FALLBACK, publicationDate, validContentUpdatedAt, persianDate } from "../lib/blogDates";
|
||||
import React, { useState, useEffect } from "react";
|
||||
import {
|
||||
ChevronRight,
|
||||
@@ -25,10 +26,11 @@ interface BlogPostClientProps {
|
||||
blog: any;
|
||||
publishedDate: string;
|
||||
authorName: string;
|
||||
authorTeam?: string;
|
||||
sanitizedContent: string;
|
||||
}
|
||||
|
||||
export default function BlogPostClient({ blog, publishedDate, authorName, sanitizedContent }: BlogPostClientProps) {
|
||||
export default function BlogPostClient({ blog, publishedDate, authorName, authorTeam, sanitizedContent }: BlogPostClientProps) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [viewCount, setViewCount] = useState<number>(blog.viewCount || 0);
|
||||
const [commentName, setCommentName] = useState("");
|
||||
@@ -147,12 +149,8 @@ export default function BlogPostClient({ blog, publishedDate, authorName, saniti
|
||||
{blog.category.name}
|
||||
</span>
|
||||
)}
|
||||
{publishedDate && (
|
||||
<div className="flex items-center gap-1">
|
||||
<Calendar className="w-3.5 h-3.5 text-canina-blue" />
|
||||
<span>{publishedDate}</span>
|
||||
</div>
|
||||
)}
|
||||
{publishedDate && <div className="flex items-center gap-1"><Calendar className="w-3.5 h-3.5 text-canina-blue" />تاریخ انتشار: <time dateTime={publicationDate(blog)}>{publishedDate}</time></div>}
|
||||
{validContentUpdatedAt(blog) && <div>آخرین بهروزرسانی: <time dateTime={validContentUpdatedAt(blog)}>{persianDate(validContentUpdatedAt(blog))}</time></div>}
|
||||
<div className="flex items-center gap-1">
|
||||
<Clock className="w-3.5 h-3.5 text-canina-blue" />
|
||||
<span>{blog.readingTime || 4} دقیقه مطالعه</span>
|
||||
@@ -212,9 +210,9 @@ export default function BlogPostClient({ blog, publishedDate, authorName, saniti
|
||||
<User className="w-7 h-7" />
|
||||
</div>
|
||||
<div>
|
||||
<div className="font-black text-medical-gray-900 text-base">{authorName}</div>
|
||||
<div className="font-black text-medical-gray-900 text-base">نویسنده: {authorName}</div>
|
||||
<div className="font-bold text-xs text-medical-gray-400 mt-0.5">
|
||||
تیم تحقیق و توسعه علمی کنینا آلمان (Canina Pharma)
|
||||
تیم: {authorTeam || blog.authorTeam || BLOG_TEAM_FALLBACK}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -399,13 +397,18 @@ export default function BlogPostClient({ blog, publishedDate, authorName, saniti
|
||||
<p className="text-xs text-white/80 leading-relaxed">
|
||||
مشاوران علمی و دامپزشکان داروسازی کنینا آماده پاسخگویی به سوالات شما در مورد وضعیت سلامت پت شما هستند.
|
||||
</p>
|
||||
<Link
|
||||
href="/smart-advisor"
|
||||
className="inline-flex items-center justify-center gap-2 w-full py-3 rounded-2xl bg-canina-gold text-canina-dark text-xs font-black hover:bg-white transition-all shadow-lg"
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
if (typeof window !== 'undefined') {
|
||||
window.dispatchEvent(new CustomEvent('canina:open-support-chat'));
|
||||
}
|
||||
}}
|
||||
className="inline-flex items-center justify-center gap-2 w-full py-3 rounded-2xl bg-canina-gold text-canina-dark text-xs font-black hover:bg-white transition-all shadow-lg cursor-pointer"
|
||||
>
|
||||
<span>مشاوره هوشمند دارویی</span>
|
||||
<ArrowLeft className="w-4 h-4" />
|
||||
</Link>
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
|
||||
@@ -7,6 +7,8 @@ import SafeImage from "./SafeImage";
|
||||
import { useSettingsStore } from "../lib/store/settingsStore";
|
||||
import api, { BASE_DOMAIN } from "../lib/services/api";
|
||||
import { toPersian } from "../lib/utils";
|
||||
import { BLOG_TEAM_FALLBACK, publicationDate, validContentUpdatedAt, persianDate } from "../lib/blogDates";
|
||||
import { resolveBlogAuthor } from "../lib/blogAuthor";
|
||||
|
||||
export interface BlogPost {
|
||||
id: string;
|
||||
@@ -16,6 +18,10 @@ export interface BlogPost {
|
||||
imageUrl?: string;
|
||||
viewCount: number;
|
||||
createdAt: string;
|
||||
publishedAt?: string;
|
||||
contentUpdatedAt?: string;
|
||||
authorTeam?: string;
|
||||
authorRole?: string;
|
||||
author?: {
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
@@ -104,11 +110,9 @@ export default function BlogPreviewSection() {
|
||||
? `${BASE_DOMAIN}${blog.imageUrl}`
|
||||
: "/assets/images/blog-placeholder.png";
|
||||
|
||||
const authorName = blog.author
|
||||
? `${blog.author.firstName || ""} ${blog.author.lastName || ""}`.trim()
|
||||
: "تحریریه کنینا";
|
||||
const authorName = resolveBlogAuthor(blog.author);
|
||||
|
||||
|
||||
const formattedDate = new Date(blog.createdAt).toLocaleDateString("fa-IR");
|
||||
|
||||
const blogHref = `/blog/${encodeURIComponent(blog.slug || blog.id)}`;
|
||||
|
||||
@@ -134,10 +138,8 @@ export default function BlogPreviewSection() {
|
||||
<div className="p-3.5 sm:p-6 flex-1 flex flex-col justify-between space-y-3 sm:space-y-4">
|
||||
<div className="space-y-1.5 sm:space-y-2">
|
||||
<div className="flex items-center gap-2.5 sm:gap-4 text-[10px] sm:text-xs text-medical-gray-400 font-medium">
|
||||
<span className="flex items-center gap-1">
|
||||
<Calendar className="w-3 h-3 sm:w-3.5 sm:h-3.5" />
|
||||
{toPersian(formattedDate)}
|
||||
</span>
|
||||
<span className="flex items-center gap-1"><Calendar className="w-3 h-3 sm:w-3.5 sm:h-3.5" />تاریخ انتشار: <time dateTime={publicationDate(blog)}>{persianDate(publicationDate(blog))}</time></span>
|
||||
{validContentUpdatedAt(blog) && <span>آخرین بهروزرسانی: <time dateTime={validContentUpdatedAt(blog)}>{persianDate(validContentUpdatedAt(blog))}</time></span>}
|
||||
<span className="flex items-center gap-1">
|
||||
<Eye className="w-3 h-3 sm:w-3.5 sm:h-3.5" />
|
||||
{toPersian(blog.viewCount || 0)}
|
||||
@@ -157,8 +159,8 @@ export default function BlogPreviewSection() {
|
||||
|
||||
<div className="pt-2.5 sm:pt-4 border-t border-medical-gray-200/60 flex items-center justify-between">
|
||||
<span className="text-[10px] sm:text-xs font-bold text-medical-gray-500 truncate max-w-[100px] sm:max-w-none">
|
||||
{authorName}
|
||||
</span>
|
||||
نویسنده: {authorName}
|
||||
</span><span className="text-[10px] sm:text-xs font-bold text-medical-gray-500">تیم: {blog.authorTeam || BLOG_TEAM_FALLBACK}</span>
|
||||
<Link
|
||||
href={blogHref}
|
||||
aria-label={`مطالعه مقاله: ${blog.title}`}
|
||||
|
||||
@@ -43,6 +43,12 @@ export default function SupportChat() {
|
||||
return () => { active = false; clearInterval(timer); window.removeEventListener('focus', refresh); };
|
||||
}, []);
|
||||
const chatScrollRef = useRef<HTMLDivElement | null>(null);
|
||||
useEffect(() => {
|
||||
const handleOpenSupport = () => setOpen(true);
|
||||
window.addEventListener('canina:open-support-chat', handleOpenSupport);
|
||||
return () => window.removeEventListener('canina:open-support-chat', handleOpenSupport);
|
||||
}, []);
|
||||
|
||||
const historyKey = useRef('');
|
||||
const pathname = usePathname();
|
||||
const isPdpPage = pathname?.startsWith('/shop/') && pathname !== '/shop';
|
||||
|
||||
@@ -2,13 +2,123 @@ import React from 'react';
|
||||
import {render,fireEvent,act,cleanup} from '@testing-library/react';
|
||||
import {vi,beforeEach,afterEach,it,expect} from 'vitest';
|
||||
import AnalyticsDeferred from '../AnalyticsDeferred';
|
||||
beforeEach(()=>{vi.useFakeTimers();document.head.innerHTML='';delete window.dataLayer;delete window.clarity;});
|
||||
afterEach(()=>{cleanup();vi.useRealTimers();vi.unstubAllGlobals();});
|
||||
it('defers tags until interaction and loads only once',()=>{render(<AnalyticsDeferred gtmId="GTM-test" gaId="G-test" clarityId="test"/>);expect(document.scripts).toHaveLength(0);fireEvent.scroll(window);fireEvent.keyDown(window);act(()=>vi.advanceTimersByTime(3500));expect(document.scripts).toHaveLength(3);expect(window.dataLayer).toEqual(expect.arrayContaining([['config','G-test',{page_path:'/'}]]));});
|
||||
it.each(['scroll','touchstart','mousemove','keydown'])('loads on %s',event=>{render(<AnalyticsDeferred gtmId="GTM-test"/>);fireEvent(window,new Event(event));expect(document.scripts).toHaveLength(1);});
|
||||
it('loads clarity when no script exists',()=>{render(<AnalyticsDeferred clarityId="solo"/>);fireEvent.scroll(window);expect(document.querySelector('script')?.src).toBe('https://www.clarity.ms/tag/solo');});
|
||||
it('preserves the existing clarity implementation',()=>{const clarity=vi.fn();window.clarity=clarity;render(<AnalyticsDeferred clarityId="existing"/>);fireEvent.scroll(window);expect(window.clarity).toBe(clarity);expect(document.querySelector('script')?.src).toBe('https://www.clarity.ms/tag/existing');});
|
||||
it('queues clarity calls before its script initializes',()=>{render(<AnalyticsDeferred clarityId="queued"/>);fireEvent.scroll(window);window.clarity('event','checkout');expect(window.clarity.q).toEqual([['event','checkout']]);});
|
||||
it('falls back after 3500ms and reuses existing GA script',()=>{const s=document.createElement('script');s.src='https://www.googletagmanager.com/gtag/js?id=G-test';document.head.append(s);render(<AnalyticsDeferred gaId="G-test"/>);act(()=>vi.advanceTimersByTime(3499));expect(window.dataLayer).toBeUndefined();act(()=>vi.advanceTimersByTime(1));expect(document.scripts).toHaveLength(1);});
|
||||
it('cancels idle work on unmount',()=>{let cb:()=>void=()=>{};vi.stubGlobal('requestIdleCallback',vi.fn(fn=>{cb=fn;return 9;}));vi.stubGlobal('cancelIdleCallback',vi.fn());const v=render(<AnalyticsDeferred gtmId="GTM-test"/>);act(()=>vi.advanceTimersByTime(3500));v.unmount();act(()=>cb());expect(document.scripts).toHaveLength(0);expect(cancelIdleCallback).toHaveBeenCalledWith(9);});
|
||||
it('unmount removes event and timeout callbacks',()=>{const v=render(<AnalyticsDeferred gtmId="GTM-test"/>);v.unmount();fireEvent.scroll(window);act(()=>vi.advanceTimersByTime(4000));expect(document.scripts).toHaveLength(0);});
|
||||
|
||||
let mockPathname = '/';
|
||||
vi.mock('next/navigation', () => ({
|
||||
usePathname: () => mockPathname,
|
||||
}));
|
||||
|
||||
beforeEach(()=>{
|
||||
vi.useFakeTimers();
|
||||
mockPathname = '/';
|
||||
document.head.innerHTML='';
|
||||
delete (window as any).dataLayer;
|
||||
delete (window as any).clarity;
|
||||
delete (window as any).gtag;
|
||||
});
|
||||
afterEach(()=>{
|
||||
cleanup();
|
||||
vi.useRealTimers();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('pushes genuine native arguments object for gtag commands so gtag.js processes them',()=>{
|
||||
render(<AnalyticsDeferred gaId="G-test"/>);
|
||||
fireEvent.scroll(window);
|
||||
act(()=>vi.advanceTimersByTime(3500));
|
||||
expect(window.dataLayer).toBeDefined();
|
||||
const configEntry = window.dataLayer?.find(entry => {
|
||||
return Object.prototype.toString.call(entry) === '[object Arguments]' && entry[0] === 'config';
|
||||
});
|
||||
expect(configEntry).toBeDefined();
|
||||
expect(configEntry[1]).toBe('G-test');
|
||||
});
|
||||
|
||||
it('defers tags until interaction and loads only once',()=>{
|
||||
render(<AnalyticsDeferred gtmId="GTM-test" gaId="G-test" clarityId="test"/>);
|
||||
expect(document.scripts).toHaveLength(0);
|
||||
fireEvent.scroll(window);
|
||||
fireEvent.keyDown(window);
|
||||
act(()=>vi.advanceTimersByTime(3500));
|
||||
expect(document.scripts).toHaveLength(3);
|
||||
const hasConfig = window.dataLayer?.some(entry => entry[0] === 'config' && entry[1] === 'G-test');
|
||||
expect(hasConfig).toBe(true);
|
||||
});
|
||||
|
||||
it('tracks client-side route changes when pathname changes',()=>{
|
||||
const {rerender} = render(<AnalyticsDeferred gaId="G-test" gtmId="GTM-test"/>);
|
||||
fireEvent.scroll(window);
|
||||
act(()=>vi.advanceTimersByTime(3500));
|
||||
|
||||
// Simulate navigation to blog
|
||||
mockPathname = '/blog/test-article';
|
||||
rerender(<AnalyticsDeferred gaId="G-test" gtmId="GTM-test"/>);
|
||||
|
||||
const gtmPageView = window.dataLayer?.find(entry => entry.event === 'page_view' && entry.page_path === '/blog/test-article');
|
||||
expect(gtmPageView).toBeDefined();
|
||||
|
||||
const gaPageView = window.dataLayer?.find(entry => {
|
||||
return Object.prototype.toString.call(entry) === '[object Arguments]' && entry[0] === 'event' && entry[1] === 'page_view';
|
||||
});
|
||||
expect(gaPageView).toBeDefined();
|
||||
expect(gaPageView[2].page_path).toBe('/blog/test-article');
|
||||
});
|
||||
|
||||
it.each(['scroll','touchstart','mousemove','keydown'])('loads on %s',event=>{
|
||||
render(<AnalyticsDeferred gtmId="GTM-test"/>);
|
||||
fireEvent(window,new Event(event));
|
||||
expect(document.scripts).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('loads clarity when no script exists',()=>{
|
||||
render(<AnalyticsDeferred clarityId="solo"/>);
|
||||
fireEvent.scroll(window);
|
||||
expect(document.querySelector('script')?.src).toBe('https://www.clarity.ms/tag/solo');
|
||||
});
|
||||
|
||||
it('preserves the existing clarity implementation',()=>{
|
||||
const clarity=vi.fn();
|
||||
(window as any).clarity=clarity;
|
||||
render(<AnalyticsDeferred clarityId="existing"/>);
|
||||
fireEvent.scroll(window);
|
||||
expect((window as any).clarity).toBe(clarity);
|
||||
expect(document.querySelector('script')?.src).toBe('https://www.clarity.ms/tag/existing');
|
||||
});
|
||||
|
||||
it('queues clarity calls before its script initializes',()=>{
|
||||
render(<AnalyticsDeferred clarityId="queued"/>);
|
||||
fireEvent.scroll(window);
|
||||
(window as any).clarity('event','checkout');
|
||||
expect((window as any).clarity.q).toEqual([['event','checkout']]);
|
||||
});
|
||||
|
||||
it('falls back after 3500ms and reuses existing GA script',()=>{
|
||||
const s=document.createElement('script');
|
||||
s.src='https://www.googletagmanager.com/gtag/js?id=G-test';
|
||||
document.head.append(s);
|
||||
render(<AnalyticsDeferred gaId="G-test"/>);
|
||||
act(()=>vi.advanceTimersByTime(3499));
|
||||
expect(window.dataLayer).toBeUndefined();
|
||||
act(()=>vi.advanceTimersByTime(1));
|
||||
expect(document.scripts).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('cancels idle work on unmount',()=>{
|
||||
let cb:()=>void=()=>{};
|
||||
vi.stubGlobal('requestIdleCallback',vi.fn(fn=>{cb=fn;return 9;}));
|
||||
vi.stubGlobal('cancelIdleCallback',vi.fn());
|
||||
const v=render(<AnalyticsDeferred gtmId="GTM-test"/>);
|
||||
act(()=>vi.advanceTimersByTime(3500));
|
||||
v.unmount();
|
||||
act(()=>cb());
|
||||
expect(document.scripts).toHaveLength(0);
|
||||
expect(cancelIdleCallback).toHaveBeenCalledWith(9);
|
||||
});
|
||||
|
||||
it('unmount removes event and timeout callbacks',()=>{
|
||||
const v=render(<AnalyticsDeferred gtmId="GTM-test"/>);
|
||||
v.unmount();
|
||||
fireEvent.scroll(window);
|
||||
act(()=>vi.advanceTimersByTime(4000));
|
||||
expect(document.scripts).toHaveLength(0);
|
||||
});
|
||||
@@ -21,6 +21,9 @@ const categories=[{id:'joints',name:'Joints',slug:'joints'},{id:'skin',name:'Ski
|
||||
beforeEach(()=>vi.clearAllMocks());
|
||||
describe('BlogPage',()=>{
|
||||
it('renders featured and regular posts as semantic links',()=>{render(<BlogPage blogs={blogs} categories={categories}/>);expect(screen.getAllByRole('heading',{level:2})[0]).toHaveTextContent('Skin article');expect(screen.getByRole('link',{name:/Skin article/})).toHaveAttribute('href','/blog/skin');expect(screen.getByRole('link',{name:/Joint article/})).toHaveAttribute('href','/blog/joint');});
|
||||
it('labels publication, including a same-day material update, author and stable team on featured and regular cards',()=>{const fresh=[{...blogs[0],publishedAt:'2026-01-01T08:00:00Z',contentUpdatedAt:'2026-01-02T08:00:00Z',authorTeam:'Clinical'}, {...blogs[1],publishedAt:'2026-01-02T08:00:00Z',contentUpdatedAt:'2026-01-02T12:00:00Z'}];render(<BlogPage blogs={fresh} categories={categories}/>);expect(screen.getAllByText(/تاریخ انتشار/)).toHaveLength(2);expect(screen.getAllByText(/آخرین بهروزرسانی/)).toHaveLength(2);expect(screen.getAllByText(/نویسنده:/)).toHaveLength(2);expect(screen.getByText(/تیم: Clinical/)).toBeInTheDocument();expect(screen.getByText(/تیم: پژوهش و محتوای علمی کنینا/)).toBeInTheDocument();expect(document.querySelectorAll('time[datetime]').length).toBeGreaterThanOrEqual(4);});
|
||||
it('stacks author and team on separate non-wrapping rows and keeps featured action on one line',()=>{render(<BlogPage blogs={blogs} categories={categories}/>);const featuredMeta=screen.getByTestId('featured-attribution');expect(featuredMeta).toHaveClass('flex-col');expect(screen.getByTestId('featured-read-more')).toHaveClass('whitespace-nowrap');const regularMeta=screen.getByTestId('regular-attribution-1');expect(regularMeta).toHaveClass('flex-col');expect(regularMeta.children).toHaveLength(2);expect(regularMeta.children[0]).toHaveClass('whitespace-nowrap');expect(regularMeta.children[1]).toHaveClass('whitespace-nowrap');});
|
||||
it('keeps the featured footer responsive without forcing attribution or action to wrap',()=>{render(<BlogPage blogs={blogs} categories={categories}/>);expect(screen.getByTestId('featured-footer')).toHaveClass('flex-col','sm:flex-row');expect(screen.getByTestId('featured-author-name')).toHaveClass('whitespace-nowrap');expect(screen.getByTestId('featured-team-name')).toHaveClass('whitespace-nowrap');});
|
||||
it('combines category, excerpt search and tags then resets empty intersection',()=>{render(<BlogPage blogs={blogs} categories={categories}/>);fireEvent.click(screen.getByRole('button',{name:'Joints'}));expect(h.replace).toHaveBeenCalledWith('/blog?categoryId=joints',{scroll:false});expect(screen.queryByText('Skin article')).not.toBeInTheDocument();fireEvent.change(screen.getByPlaceholderText('جستجو در موضوعات، بیماریها، ویتامینها...'),{target:{value:'MOBILITY'}});expect(screen.getByText('Joint article')).toBeInTheDocument();fireEvent.click(screen.getByRole('button',{name:'#coat'}));expect(screen.getByText('هیچ مقالهای با معیارهای جستجوی شما یافت نشد.')).toBeInTheDocument();fireEvent.click(screen.getByRole('button',{name:'پاکسازی همه فیلترها'}));expect(screen.getByText('Skin article')).toBeInTheDocument();expect(screen.getByText('Joint article')).toBeInTheDocument();});
|
||||
it('syncs category with route props',()=>{const view=render(<BlogPage blogs={blogs} categories={categories} initialCategoryId="joints"/>);expect(screen.queryByText('Skin article')).not.toBeInTheDocument();view.rerender(<BlogPage blogs={blogs} categories={categories} initialCategoryId="skin"/>);expect(screen.queryByText('Joint article')).not.toBeInTheDocument();});
|
||||
it('clears search and toggles tags off',()=>{render(<BlogPage blogs={blogs}/>);fireEvent.click(screen.getByRole('button',{name:'#health'}));expect(screen.queryByText('Skin article')).not.toBeInTheDocument();fireEvent.click(screen.getByRole('button',{name:'#health'}));expect(screen.getByText('Skin article')).toBeInTheDocument();fireEvent.change(screen.getByPlaceholderText('جستجو در موضوعات، بیماریها، ویتامینها...'),{target:{value:'missing'}});fireEvent.click(screen.getByRole('button',{name:'پاک کردن'}));expect(screen.getByText('Skin article')).toBeInTheDocument();});
|
||||
|
||||
@@ -89,7 +89,7 @@ describe("BlogPostClient Component", () => {
|
||||
// Breadcrumb and headers
|
||||
expect(screen.getByRole("heading", { level: 1, name: /راهنمای جامع کانیهیدروکس GAG/ })).toBeInTheDocument();
|
||||
expect(screen.getAllByText("سلامت استخوان و مفاصل").length).toBeGreaterThan(0);
|
||||
expect(screen.getByText("دکتر توماس بکر")).toBeInTheDocument();
|
||||
expect(screen.getByText("نویسنده: دکتر توماس بکر")).toBeInTheDocument();
|
||||
expect(screen.getByText("۱۵ فروردین ۱۴۰۵")).toBeInTheDocument();
|
||||
expect(screen.getAllByText(/دقیقه مطالعه/).length).toBeGreaterThan(0);
|
||||
|
||||
@@ -110,6 +110,15 @@ describe("BlogPostClient Component", () => {
|
||||
expect(screen.getByText("بستهبندی قوطی کانیهیدروکس")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders semantic publication, valid update and explicit author/team labels", () => {
|
||||
render(<BlogPostClient blog={{...mockBlog,publishedAt:"2026-01-01T00:00:00Z",contentUpdatedAt:"2026-01-02T00:00:00Z",authorTeam:"Science"}} sanitizedContent={mockBlog.content} publishedDate="۱۲ دی ۱۴۰۴" authorName="دکتر بکر" />);
|
||||
expect(screen.getByText(/تاریخ انتشار/)).toBeInTheDocument();
|
||||
expect(screen.getByText(/آخرین بهروزرسانی/)).toBeInTheDocument();
|
||||
expect(screen.getByText(/نویسنده: دکتر بکر/)).toBeInTheDocument();
|
||||
expect(screen.getByText(/تیم: Science/)).toBeInTheDocument();
|
||||
expect(document.querySelectorAll("time[datetime]").length).toBe(2);
|
||||
});
|
||||
|
||||
it("registers blog view count on mount via API", async () => {
|
||||
render(
|
||||
<BlogPostClient
|
||||
@@ -153,10 +162,7 @@ describe("BlogPostClient Component", () => {
|
||||
|
||||
// Scientific Consultation CTA
|
||||
expect(screen.getByText("نیاز به راهنمایی و دوز درمانی دارید؟")).toBeInTheDocument();
|
||||
expect(screen.getByRole("link", { name: /مشاوره هوشمند دارویی/ })).toHaveAttribute(
|
||||
"href",
|
||||
"/smart-advisor"
|
||||
);
|
||||
expect(screen.getByRole("button", { name: /مشاوره هوشمند دارویی/ })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders existing comments and handles new comment submission successfully", async () => {
|
||||
|
||||
@@ -110,9 +110,10 @@ describe("BlogPreviewSection Component", () => {
|
||||
});
|
||||
|
||||
// Author display
|
||||
expect(screen.getByText("دکتر مریم اکبری")).toBeInTheDocument();
|
||||
expect(screen.getByText("نویسنده: دکتر مریم اکبری")).toBeInTheDocument();
|
||||
// Default fallback author
|
||||
expect(screen.getByText("تحریریه کنینا")).toBeInTheDocument();
|
||||
expect(screen.getByText("نویسنده: کنینا")).toBeInTheDocument();
|
||||
expect(screen.getAllByText("تیم: پژوهش و محتوای علمی کنینا")).toHaveLength(2);
|
||||
|
||||
// Verify aria-label links with full title context
|
||||
const link1 = screen.getByLabelText("مطالعه مقاله: اهمیت کلسیم و مفاصل در رشد توله سگ ژرمن شپرد");
|
||||
@@ -122,6 +123,15 @@ describe("BlogPreviewSection Component", () => {
|
||||
expect(link2).toHaveAttribute("href", "/blog/cat-hair-loss-solutions");
|
||||
});
|
||||
|
||||
it("uses publication freshness and explicit byline labels on homepage cards", async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: { blogs: [{ id:"b",slug:"b",title:"B",content:"",viewCount:0,createdAt:"2026-01-01T00:00:00Z",publishedAt:"2026-01-01T00:00:00Z",contentUpdatedAt:"2026-01-02T00:00:00Z",authorTeam:"Science" }] } });
|
||||
render(<BlogPreviewSection />);
|
||||
expect(await screen.findByText(/تاریخ انتشار/)).toBeInTheDocument();
|
||||
expect(screen.getByText(/آخرین بهروزرسانی/)).toBeInTheDocument();
|
||||
expect(screen.getByText(/نویسنده:/)).toBeInTheDocument();
|
||||
expect(screen.getByText(/تیم: Science/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("handles api errors gracefully and renders null", async () => {
|
||||
vi.mocked(api.get).mockRejectedValueOnce(new Error("Failed to load"));
|
||||
const { container } = render(<BlogPreviewSection />);
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { BLOG_TEAM_FALLBACK } from './blogDates';
|
||||
|
||||
export const BLOG_AUTHOR_FALLBACK = 'کنینا';
|
||||
|
||||
type BlogAuthor = {
|
||||
firstName?: string | null;
|
||||
lastName?: string | null;
|
||||
};
|
||||
|
||||
interface BlogAuthorInput {
|
||||
author?: BlogAuthor | null;
|
||||
authorTeam?: string | null;
|
||||
}
|
||||
|
||||
export interface ResolvedBlogAuthor {
|
||||
type: 'Person' | 'Organization';
|
||||
name: string;
|
||||
teamName: string;
|
||||
}
|
||||
|
||||
export function resolveBlogAuthor(author?: BlogAuthor | null): string {
|
||||
const name = author
|
||||
? `${author.firstName || ''} ${author.lastName || ''}`.trim()
|
||||
: '';
|
||||
return name || BLOG_AUTHOR_FALLBACK;
|
||||
}
|
||||
|
||||
export function resolveBlogAuthorIdentity(blog: BlogAuthorInput): ResolvedBlogAuthor {
|
||||
const personName = blog.author
|
||||
? `${blog.author.firstName || ''} ${blog.author.lastName || ''}`.trim()
|
||||
: '';
|
||||
const teamName = blog.authorTeam?.trim() || BLOG_TEAM_FALLBACK;
|
||||
|
||||
if (personName) {
|
||||
return { type: 'Person', name: personName, teamName };
|
||||
}
|
||||
|
||||
return { type: 'Organization', name: BLOG_AUTHOR_FALLBACK, teamName };
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { persianDate } from "./blogDates";
|
||||
|
||||
describe("persianDate", () => {
|
||||
it("uses the Persian calendar and Asia/Tehran at a UTC near-midnight boundary", () => {
|
||||
const value = "2026-03-20T21:00:00.000Z";
|
||||
const expected = new Intl.DateTimeFormat("fa-IR-u-ca-persian", {
|
||||
year: "numeric", month: "numeric", day: "numeric", timeZone: "Asia/Tehran",
|
||||
}).format(new Date(value));
|
||||
expect(persianDate(value)).toBe(expected);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,4 @@
|
||||
export const BLOG_TEAM_FALLBACK = "پژوهش و محتوای علمی کنینا";
|
||||
export function publicationDate(blog:any): string | undefined { return blog?.publishedAt || blog?.createdAt; }
|
||||
export function validContentUpdatedAt(blog:any): string | undefined { const published=publicationDate(blog), updated=blog?.contentUpdatedAt; if(!published||!updated) return undefined; const p=new Date(published),u=new Date(updated); return Number.isFinite(p.getTime())&&Number.isFinite(u.getTime())&&u>p?updated:undefined; }
|
||||
export function persianDate(value?:string): string { return value ? new Intl.DateTimeFormat("fa-IR-u-ca-persian", { year: "numeric", month: "numeric", day: "numeric", timeZone: "Asia/Tehran" }).format(new Date(value)) : ""; }
|
||||
+2
-2
@@ -146,9 +146,9 @@ sleep 15
|
||||
# fail-closed, and applies only migrations already reviewed and committed.
|
||||
echo "Applying committed database migrations..."
|
||||
if [ "$BRANCH" = "main" ]; then
|
||||
docker exec "${CONTAINER_PREFIX}" npx prisma migrate resolve --applied 20261013210253_add_admin_modules >/dev/null 2>&1 || true
|
||||
docker exec -e PRISMA_HIDE_UPDATE_MESSAGE=true "${CONTAINER_PREFIX}" npx prisma migrate resolve --applied 20261013210253_add_admin_modules >/dev/null 2>&1 || true
|
||||
fi
|
||||
docker exec "${CONTAINER_PREFIX}" npx prisma migrate deploy
|
||||
docker exec -e PRISMA_HIDE_UPDATE_MESSAGE=true "${CONTAINER_PREFIX}" npx prisma migrate deploy
|
||||
|
||||
# Code-only deployment: seed and destructive data changes are not performed here.
|
||||
|
||||
|
||||
@@ -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())
|
||||
@@ -0,0 +1,407 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Canina cross-department orchestration worker.
|
||||
|
||||
A model response is analysis, not delivery. The worker records the exact prompt and
|
||||
response, creates deterministic cross-department child tasks, and keeps the parent
|
||||
open until dependencies and acceptance evidence are satisfied.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
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
|
||||
|
||||
import requests
|
||||
|
||||
MAX_FANOUT_DEPTH = 2
|
||||
VALID_DEPARTMENTS = {
|
||||
"PMO", "DEV", "DEVOPS", "SEO", "CONTENT", "CLINICAL_RD", "B2B", "SUPPORT"
|
||||
}
|
||||
|
||||
|
||||
def utc_now() -> str:
|
||||
return datetime.now(timezone.utc).isoformat()
|
||||
|
||||
|
||||
def parse_structured_response(text: str) -> dict[str, Any]:
|
||||
cleaned = text.strip()
|
||||
fenced = re.search(r"```(?:json)?\s*(\{.*\})\s*```", cleaned, re.DOTALL)
|
||||
if fenced:
|
||||
cleaned = fenced.group(1)
|
||||
else:
|
||||
start, end = cleaned.find("{"), cleaned.rfind("}")
|
||||
if start >= 0 and end > start:
|
||||
cleaned = cleaned[start : end + 1]
|
||||
parsed = json.loads(cleaned, strict=False)
|
||||
if not isinstance(parsed, dict):
|
||||
raise ValueError("Model response must be a JSON object")
|
||||
parsed.setdefault("summary", "")
|
||||
parsed.setdefault("child_tasks", [])
|
||||
parsed.setdefault("deliverable", {})
|
||||
return parsed
|
||||
|
||||
|
||||
def _child_code(parent_code: str, department: str, title: str) -> str:
|
||||
digest = hashlib.sha256(f"{parent_code}|{department}|{title}".encode()).hexdigest()[:8].upper()
|
||||
return f"{parent_code}-{department[:4]}-{digest}"[:50]
|
||||
|
||||
|
||||
def build_child_tasks(parent_code: str, proposal: dict[str, Any], depth: int) -> list[dict[str, Any]]:
|
||||
if depth >= MAX_FANOUT_DEPTH:
|
||||
return []
|
||||
children: list[dict[str, Any]] = []
|
||||
for raw in proposal.get("child_tasks") or []:
|
||||
if not isinstance(raw, dict):
|
||||
continue
|
||||
department = str(raw.get("department") or "").upper().strip()
|
||||
title = str(raw.get("title") or "").strip()
|
||||
if department not in VALID_DEPARTMENTS or not title:
|
||||
continue
|
||||
criteria = raw.get("acceptance_criteria") or []
|
||||
children.append(
|
||||
{
|
||||
"code": _child_code(parent_code, department, title),
|
||||
"department": department,
|
||||
"title": title[:255],
|
||||
"description": str(raw.get("description") or title),
|
||||
"priority": str(raw.get("priority") or "HIGH").upper(),
|
||||
"assignee": f"Canina-{department}-Agent",
|
||||
"acceptanceCriteria": {
|
||||
"parentTaskCode": parent_code,
|
||||
"depth": depth + 1,
|
||||
"criteria": criteria if isinstance(criteria, list) else [str(criteria)],
|
||||
"requiredDeliverableType": raw.get("deliverable_type"),
|
||||
},
|
||||
}
|
||||
)
|
||||
return children
|
||||
|
||||
|
||||
def determine_parent_status(*, has_children: bool, deliverable_url: str | None, verified: bool) -> str:
|
||||
if has_children:
|
||||
return "WAITING_DEPENDENCIES"
|
||||
# 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"]
|
||||
self.psql = [
|
||||
"docker", "exec", "-i", "canino_db_prod", "psql",
|
||||
"-U", "canino_prod", "-d", "caninodb_prod", "-t", "-A",
|
||||
]
|
||||
|
||||
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,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
timeout=45,
|
||||
check=True,
|
||||
)
|
||||
return result.stdout.strip()
|
||||
|
||||
def rows_json(self, query: str) -> list[dict[str, Any]]:
|
||||
wrapped = f"SELECT COALESCE(json_agg(q), '[]'::json)::text FROM ({query}) q;"
|
||||
raw = self.sql(wrapped)
|
||||
return json.loads(raw or "[]")
|
||||
|
||||
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:
|
||||
config_path = Path(os.environ.get("HERMES_CONFIG", "/opt/data/config.yaml"))
|
||||
text = config_path.read_text(encoding="utf-8")
|
||||
match = re.search(r"name: 9router (?:Combo|Antigravity).*?api_key:\s*([^\s]+)", text, re.DOTALL)
|
||||
if not match:
|
||||
raise RuntimeError("9router API key not configured")
|
||||
self.api_key = match.group(1).strip()
|
||||
|
||||
def complete(self, prompt: str) -> str:
|
||||
response = requests.post(
|
||||
"https://nr.parsaaghayi.ir/v1/chat/completions",
|
||||
headers={"Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json"},
|
||||
json={
|
||||
"model": "Canina-content",
|
||||
"messages": [
|
||||
{"role": "system", "content": "You are Canina's cross-department PMO. Return strict JSON only."},
|
||||
{"role": "user", "content": prompt},
|
||||
],
|
||||
"temperature": 0.1,
|
||||
"stream": False,
|
||||
},
|
||||
timeout=180,
|
||||
)
|
||||
response.raise_for_status()
|
||||
try:
|
||||
return response.json()["choices"][0]["message"]["content"]
|
||||
except Exception:
|
||||
chunks: list[str] = []
|
||||
for line in response.text.splitlines():
|
||||
if not line.startswith("data: ") or line.endswith("[DONE]"):
|
||||
continue
|
||||
try:
|
||||
chunks.append(json.loads(line[6:])["choices"][0]["delta"].get("content", ""))
|
||||
except Exception:
|
||||
pass
|
||||
return "".join(chunks)
|
||||
|
||||
|
||||
def decomposition_prompt(task: dict[str, Any]) -> str:
|
||||
logs = task.get("execution_logs") or []
|
||||
raw_output = logs[-1].get("model_response", "") if logs else ""
|
||||
depth = int((task.get("acceptance_criteria") or {}).get("depth", 0))
|
||||
return f"""
|
||||
ماموریت {task['code']} در دپارتمان {task['department']} فقط یک تحلیل متنی تولید کرده و هنوز تحویل اجرایی تاییدشده ندارد.
|
||||
عنوان: {task['title']}
|
||||
خروجی خام واقعی مدل:
|
||||
{raw_output}
|
||||
|
||||
این خروجی را به یک برنامه اجرایی میاندپارتمانی تبدیل کن. پاسخ فقط JSON معتبر با این ساختار باشد:
|
||||
{{
|
||||
"summary": "نتیجه واقعی مرحله تحلیل، بدون ادعای انتشار یا استقرار",
|
||||
"deliverable": {{"type": "analysis", "url": null, "verified": false}},
|
||||
"child_tasks": [
|
||||
{{
|
||||
"department": "یکی از SEO,CONTENT,CLINICAL_RD,B2B,DEV,DEVOPS,SUPPORT,PMO",
|
||||
"title": "اقدام مستقل و قابل تحویل",
|
||||
"description": "شرح دقیق اجرا",
|
||||
"priority": "HIGH",
|
||||
"deliverable_type": "نوع خروجی قابل راستیآزمایی",
|
||||
"acceptance_criteria": ["معیار عینی اول", "معیار عینی دوم"]
|
||||
}}
|
||||
]
|
||||
}}
|
||||
قواعد: حداکثر ۶ child task؛ تکراری نساز؛ کار صرفاً تحلیلی را DONE ننام؛ انتشار، تماس، پیامک، تغییر کد یا پروداکشن را انجامشده فرض نکن؛ عمق فعلی {depth} است.
|
||||
""".strip()
|
||||
|
||||
|
||||
def execution_prompt(task: dict[str, Any]) -> str:
|
||||
criteria = task.get("acceptance_criteria") or {}
|
||||
return f"""
|
||||
شما ایجنت اجرایی دپارتمان {task['department']} کنینا هستید.
|
||||
کد: {task['code']}
|
||||
عنوان: {task['title']}
|
||||
شرح: {task.get('description') or ''}
|
||||
معیار پذیرش: {json.dumps(criteria, ensure_ascii=False)}
|
||||
|
||||
این مرحله را واقعاً تا حدی که بدون دسترسی به ابزار خارجی ممکن است انجام بده. پاسخ فقط JSON معتبر:
|
||||
{{
|
||||
"summary": "آنچه واقعاً تولید یا بررسی شد",
|
||||
"deliverable": {{
|
||||
"type": "draft|research|code_plan|contact_plan|clinical_review|seo_plan",
|
||||
"content": "خروجی کامل و قابل استفاده، نه خلاصه نمایشی",
|
||||
"url": null,
|
||||
"verified": false
|
||||
}},
|
||||
"verification": {{"passed": false, "evidence": []}},
|
||||
"child_tasks": []
|
||||
}}
|
||||
هیچ انتشار، تماس، دپلوی، تغییر سایت یا تایید بالینی را انجامشده فرض نکن. اگر نیازمند ابزار/دپارتمان دیگری است، child_tasks ساختاریافته بساز.
|
||||
""".strip()
|
||||
|
||||
|
||||
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
|
||||
prompt = execution_prompt(task)
|
||||
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.finish_claim(task, {'timestamp': utc_now(), 'status': 'AGENT_EXECUTION_FAILED',
|
||||
'error': str(exc)}, 'TODO')
|
||||
raise
|
||||
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
|
||||
AND c.status NOT IN ('DONE')
|
||||
)
|
||||
ORDER BY created_at ASC
|
||||
LIMIT 1
|
||||
"""
|
||||
)
|
||||
if not parents:
|
||||
return False
|
||||
# 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:
|
||||
# Legacy DONE records require a separate human audit, not autonomous rewrites.
|
||||
return False
|
||||
|
||||
|
||||
def main() -> None:
|
||||
db = Database()
|
||||
model = ModelClient()
|
||||
if execute_next_task(db, model):
|
||||
print("Executed one child task; unverified model output remains in TEST, never DONE.")
|
||||
return
|
||||
# Parent reconciliation requires independent persisted QA attestations.
|
||||
print("No actionable orchestration task found.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -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()
|
||||
@@ -0,0 +1,66 @@
|
||||
import json
|
||||
import unittest
|
||||
|
||||
from orchestration_worker import (
|
||||
build_child_tasks,
|
||||
determine_parent_status,
|
||||
parse_structured_response,
|
||||
)
|
||||
|
||||
|
||||
class OrchestrationWorkerTests(unittest.TestCase):
|
||||
def test_unverified_model_response_can_never_be_done(self):
|
||||
self.assertEqual(
|
||||
determine_parent_status(has_children=False, deliverable_url=None, verified=False),
|
||||
"TEST",
|
||||
)
|
||||
self.assertEqual(
|
||||
determine_parent_status(has_children=False, deliverable_url="https://canina.ir/x", verified=False),
|
||||
"TEST",
|
||||
)
|
||||
|
||||
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),
|
||||
"TEST",
|
||||
)
|
||||
|
||||
def test_children_force_waiting_dependencies(self):
|
||||
self.assertEqual(
|
||||
determine_parent_status(has_children=True, deliverable_url=None, verified=False),
|
||||
"WAITING_DEPENDENCIES",
|
||||
)
|
||||
|
||||
def test_parse_json_code_fence(self):
|
||||
payload = parse_structured_response('```json\n{"summary":"ok","child_tasks":[]}\n```')
|
||||
self.assertEqual(payload["summary"], "ok")
|
||||
|
||||
def test_parse_json_with_raw_control_character(self):
|
||||
payload = parse_structured_response('{"summary":"line one\nline two","child_tasks":[]}')
|
||||
self.assertEqual(payload["summary"], "line one\nline two")
|
||||
|
||||
def test_child_task_codes_are_deterministic_and_include_parent(self):
|
||||
proposal = {
|
||||
"child_tasks": [
|
||||
{
|
||||
"department": "CONTENT",
|
||||
"title": "تدوین مقاله",
|
||||
"description": "مقاله مستند",
|
||||
"priority": "HIGH",
|
||||
"acceptance_criteria": ["پیشنویس موجود باشد"],
|
||||
}
|
||||
]
|
||||
}
|
||||
first = build_child_tasks("TSK-390939", proposal, depth=0)
|
||||
second = build_child_tasks("TSK-390939", proposal, depth=0)
|
||||
self.assertEqual(first[0]["code"], second[0]["code"])
|
||||
self.assertEqual(first[0]["acceptanceCriteria"]["parentTaskCode"], "TSK-390939")
|
||||
self.assertEqual(first[0]["acceptanceCriteria"]["depth"], 1)
|
||||
|
||||
def test_depth_limit_blocks_recursive_fanout(self):
|
||||
proposal = {"child_tasks": [{"department": "SEO", "title": "x"}]}
|
||||
self.assertEqual(build_child_tasks("TSK-1", proposal, depth=2), [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user