Compare commits

...
Author SHA1 Message Date
devops b0f4636534 feat(router-usage): add protected read-only consumption adapter with honest quota unknowns 2026-10-22 18:40:19 +00:00
devops eb17c8e284 feat(orchestration): enforce corporate guardrails, domain invariant and daily publishing rate limits
Deploy Canina / deploy (push) Successful in 28s
2026-10-20 20:43:39 +00:00
devops 459f8b59fe Merge develop into main: complete autonomous corporate orchestration, manager actions separation, and truthful QA gates
Deploy Canina / deploy (push) Successful in 50s
2026-10-20 20:01:23 +00:00
devops e6c705cef7 feat(orchestration): implement live HTTP artifact verification with soft-404 detection
Deploy Canina / deploy (push) Successful in 24s
2026-10-20 19:55:28 +00:00
devops 19c4bb451d merge(worker): integrate orchestration worker contract
Deploy Canina / deploy (push) Successful in 2m56s
2026-10-20 19:43:59 +00:00
devops f71b79a17f merge(market): integrate feat/safe-market-proposals-20261020 2026-10-20 19:43:31 +00:00
devops e3eb7ca205 merge(admin_ui): integrate feat/admin-manager-actions-separation-20261020 2026-10-20 19:43:30 +00:00
devops 2e54163d9e merge(backend): integrate feat/backend-approval-separation-20261020 2026-10-20 19:43:30 +00:00
devops 344f79039f feat(orchestration): implement atomic claims, root task selection and truthful completion gates 2026-10-20 19:42:53 +00:00
devops 02fe634944 feat(admin): implement approval separation and verifiable completion policy
- Separate B2B_SUPPLIER_STRATEGY strategic manager actions from digital tasks
- Ensure strategic proposals do not create/requeue digital tasks or set executedAt
- Ensure SEO and digital approvals transition actionable tasks to TODO
- Strengthen task completion policy: require independently verifiable HTTP(S) deliverables, reject canina://, git://stage, and post-tsk missing article placeholders
- Reject completion when QA verification evidence reports 404 or missing article errors
- Add unit test coverage for ApprovalsController, DepartmentTasksController and completion policy
2026-10-20 19:41:39 +00:00
devops 7b1f64d727 feat(admin): separate manager actions from operational authorization and eliminate synthetic 3D room 2026-10-20 19:30:47 +00:00
devops d53e38a48f test: gate market proposal evidence and dedup before approval 2026-10-20 19:13:48 +00:00
devops 740e738fca Merge develop into main: modernize ApprovalsPage with clean light theme and smart payload mapper
Deploy Canina / deploy (push) Successful in 38s
2026-10-20 16:01:17 +00:00
devops ee90284129 feat(admin): modernize ApprovalsPage UI with clean light theme, structured payload visualizer and CEO directives
Deploy Canina / deploy (push) Successful in 38s
2026-10-20 16:00:59 +00:00
devops de42b3126b Merge feature/task-status-history-and-ceo-priority into main
Deploy Canina / deploy (push) Successful in 39s
2026-10-20 13:37:01 +00:00
devops 71dccbc590 feat(admin): add status transition metrics and CEO_EXPEDITE priority to task manager
Deploy Canina / deploy (push) Successful in 37s
2026-10-20 13:36:59 +00:00
devops 4c6127786f Merge develop into main: complete department and status filters in task management
Deploy Canina / deploy (push) Successful in 39s
2026-10-20 12:25:11 +00:00
devops bf082c59fe feat(admin): complete all department and status filters in task management
Deploy Canina / deploy (push) Successful in 37s
2026-10-20 12:00:59 +00:00
devops ee35c10454 merge: fix GA4 gtag arguments and route tracking
Deploy Canina / deploy (push) Successful in 2m32s
2026-10-20 10:54:19 +00:00
devops 1651fd00a2 fix(analytics): pass native arguments to dataLayer and track route changes
Deploy Canina / deploy (push) Successful in 2m20s
2026-10-20 10:49:56 +00:00
devops d9e4447903 merge: suppress Prisma CLI update banner during migrations
Deploy Canina / deploy (push) Successful in 40s
2026-10-20 09:54:23 +00:00
devops f59dd6ebec fix(prisma): suppress CLI update banner during migrations and builds
Deploy Canina / deploy (push) Successful in 2m34s
2026-10-20 09:46:32 +00:00
devops 10413547c1 merge: publish blog attribution and freshness fixes
Deploy Canina / deploy (push) Successful in 2m37s
2026-10-20 09:08:50 +00:00
devops 2f178db2c6 fix(blog): keep attribution rows on one line
Deploy Canina / deploy (push) Successful in 2m20s
2026-10-20 09:01:32 +00:00
devops 28485d51f7 fix(blog): improve attribution layout and freshness
Deploy Canina / deploy (push) Successful in 4m4s
2026-10-20 08:41:40 +00:00
devops 24362b89d7 fix(blog): refine editorial team label
Deploy Canina / deploy (push) Successful in 2m40s
2026-10-20 07:59:08 +00:00
devops 159e4a4cbf fix(blog): separate Canina author and editorial team
Deploy Canina / deploy (push) Successful in 2m47s
2026-10-20 07:52:07 +00:00
devops 13a7919c91 merge: reconcile main before blog freshness release
Deploy Canina / deploy (push) Successful in 2m34s
2026-10-20 07:26:54 +00:00
devops d670690816 fix(blog): unify structured author identity
Deploy Canina / deploy (push) Successful in 5m16s
2026-10-20 07:15:20 +00:00
devops 62c58c7c89 fix(blog): harden creation and unify author fallback 2026-10-20 06:59:43 +00:00
devops 0b4d9a8463 fix(blog): harden freshness and authorship 2026-10-20 06:31:22 +00:00
devops 51ca8c7e34 feat(blog): add material freshness and authorship 2026-10-20 05:36:03 +00:00
devops 64047054b8 merge: integrate live HQ telemetry and child task execution pipeline
Deploy Canina / deploy (push) Successful in 38s
2026-10-19 17:49:00 +00:00
devops 3f5258a76c feat(admin-hq): bind 3D orchestration room to live telemetry and dynamic task state
Deploy Canina / deploy (push) Successful in 36s
2026-10-19 17:48:44 +00:00
devops 3b93308b71 merge: resilient orchestration JSON parsing
Deploy Canina / deploy (push) Successful in 39s
2026-10-19 14:13:03 +00:00
devops bf53f2e17c fix(orchestration): tolerate raw control characters in model JSON
Deploy Canina / deploy (push) Successful in 36s
2026-10-19 14:13:00 +00:00
devops c2eca11a3b merge: verified completion gates and cross-department orchestration
Deploy Canina / deploy (push) Successful in 51s
2026-10-19 14:07:01 +00:00
devops 4c3f8de1fb feat(orchestration): enforce verified completion and cross-department fan-out
Deploy Canina / deploy (push) Successful in 2m8s
2026-10-19 13:59:22 +00:00
devops b3e1869724 merge: add CompanyOrchestrationHQ into main
Deploy Canina / deploy (push) Successful in 37s
2026-10-19 13:03:56 +00:00
devops 624f58c723 feat(pages): add CompanyOrchestrationHQ interactive 3D component
Deploy Canina / deploy (push) Successful in 37s
2026-10-19 13:03:54 +00:00
devops aedc0f6979 merge: register /governance/hq route into main
Deploy Canina / deploy (push) Failing after 7s
2026-10-19 13:03:31 +00:00
devops 1e53ceeda6 feat(governance): register /governance/hq route
Deploy Canina / deploy (push) Failing after 8s
2026-10-19 13:03:29 +00:00
devops f08ed0c22c merge: integrate Tasks state fix and Sidebar 3D link into main
Deploy Canina / deploy (push) Successful in 39s
2026-10-19 12:51:18 +00:00
devops ee0f877d97 fix(tasks): define sortOrder state and add 3D HQ to Sidebar navigation
Deploy Canina / deploy (push) Successful in 37s
2026-10-19 12:50:12 +00:00
devops b3d4e08914 merge: integrate develop fixes (Dashboard null-safety, Tasks Tehran datetime, and sorting) into main
Deploy Canina / deploy (push) Successful in 2m47s
2026-10-19 12:43:06 +00:00
devops ec9dd83e77 fix: syntax escape in TasksManagementPage
Deploy Canina / deploy (push) Successful in 3m21s
2026-10-19 12:33:00 +00:00
devops 4930e2a870 feat(tasks): interactive date-sorting toggle and Tehran datetime column
Deploy Canina / deploy (push) Failing after 8s
2026-10-19 12:32:25 +00:00
devops 5e21cc76fc fix(admin): resolve Dashboard crash with null safety and add Tehran time/sorting to Tasks
Deploy Canina / deploy (push) Failing after 2m16s
2026-10-19 12:29:33 +00:00
devops 529110a693 feat(support-chat): delegate blog consultation CTA clicks to open support chat modal
Deploy Canina / deploy (push) Successful in 2m38s
2026-10-19 06:32:11 +00:00
devops 0b5f2a88cc fix(blog): highlight in-article links and trigger support chat from smart advisor button
Deploy Canina / deploy (push) Successful in 2m44s
2026-10-19 06:24:22 +00:00
devops ff6f04fe46 fix(cache): revalidate storefront after admin mutations
Deploy Canina / deploy (push) Successful in 2m35s
2026-10-18 19:31:46 +00:00
devops 2e9a0e30c1 chore: sync feature branch with latest origin/develop
Deploy Canina / deploy (push) Successful in 2m40s
2026-10-18 18:53:04 +00:00
devops ad0acaccc2 refactor(admin): extract ProductFaqTab component from monolithic Products.tsx [FE-020] 2026-10-18 18:34:52 +00:00
devops 30019a02d8 fix(deps): upgrade next to 16.4.2 eliminating critical vulnerability [FE-023] 2026-10-18 18:30:31 +00:00
devops 87999be3d2 fix(frontend): comprehensive SEO, A11y, media upload validation, and logging enhancements [FE-013 to FE-022] 2026-10-18 17:55:37 +00:00
devops 4ce9f6000c fix(ux): enforce safe responsive containment on mobile CartDrawer [FE-012] 2026-10-18 16:42:57 +00:00
devops 0529962391 fix(admin): resolve array response unwrapping in SupportChatAnalyticsPage [FE-011] 2026-10-18 16:37:45 +00:00
devops 14c45e4f6c fix(api): preserve error semantics in getProductBySlug distinguishing 404 from 5xx [FE-010] 2026-10-18 16:35:14 +00:00
devops 1c38b95fb0 fix(auth): align admin refresh token contract with backend cookie and bearer endpoints [FE-009] 2026-10-18 16:32:28 +00:00
devops dab66a2dce fix(checkout): guard against empty cart order submission and disable checkout CTA [FE-008] 2026-10-18 16:16:15 +00:00
devops 86eb0cfcae fix(monitoring): eliminate Math.random mock values from admin monitoring stats [FE-007] 2026-10-18 16:12:32 +00:00
devops d3aa10c769 fix(security): sanitize dynamic HTML rendering in Hero and ProductPage [FE-006] 2026-10-18 16:09:36 +00:00
devops 15524609fe fix(security): enforce withCredentials true on storefront api for httpOnly cookies [FE-005] 2026-10-18 16:04:34 +00:00
devops aacb91ac70 fix(security): sanitize and block payment tokens and secrets in public ui-texts endpoint [FE-004] 2026-10-18 15:47:12 +00:00
devops f91502026b feat(admin): configure vitest test runner and fix dashboard audit-logs array guards [FE-003] 2026-10-18 15:43:19 +00:00
devops 7f2f638f38 test(backend): fix unit tests for media magic validation, slow query logger, and support chat specs
Deploy Canina / deploy (push) Successful in 41s
2026-10-18 15:40:03 +00:00
devops 7879ead486 fix(frontend): harmonize selectors and assertions across failing application unit tests [FE-002] 2026-10-18 15:35:43 +00:00
devops dda1caf3e0 feat(backend & dba): implement inventory concurrency guard, redis distributed locks, magic byte file validation, slow query logger, and db check constraints 2026-10-18 15:29:37 +00:00
devops bb483d3e68 fix(frontend): resolve react-hooks declaration order and lint errors in SupportChat [FE-001] 2026-10-18 15:23:12 +00:00
devops 73bc79b4bb fix(backend): encapsulate TasksService in TasksModule and export OrdersService
Deploy Canina / deploy (push) Successful in 30s
2026-10-18 14:43:17 +00:00
devops 9520426a66 perf(backend & dba): resolve unindexed foreign keys, eliminate N+1 in product catalog, add background tasks for inventory release & payment reconciliation, and harden SQL queries
Deploy Canina / deploy (push) Failing after 36s
2026-10-18 14:35:41 +00:00
devops b077423ab2 fix: move BackToTop to right side, wire global prescription modal trigger in header & mobile drawer
Deploy Canina / deploy (push) Successful in 2m15s
2026-10-18 14:09:01 +00:00
devops 94867fbd5a fix(frontend): ensure use client is first line in ArchivePage
Deploy Canina / deploy (push) Successful in 2m16s
2026-10-18 13:54:31 +00:00
devops 6a37f2f4c7 fix: support chat elevated only on PDP, rx button opens modal instantly, and hide pet badge when not logged in
Deploy Canina / deploy (push) Failing after 21s
2026-10-18 13:50:54 +00:00
devops b54338f91f fix(backend): fix duplicate success in deleteSymptom
Deploy Canina / deploy (push) Successful in 2m33s
2026-10-18 13:28:39 +00:00
devops c7b95b4d2b feat: dock PDP buy bar above mobile nav, redesign B2B modal to mobile-card layout, and implement full symptoms CRUD in backend & admin panel
Deploy Canina / deploy (push) Failing after 1m23s
2026-10-18 13:26:01 +00:00
devops 8e4388c325 fix(backend): fix duplicate success property in renameSymptom response
Deploy Canina / deploy (push) Successful in 2m30s
2026-10-18 12:58:12 +00:00
devops 305995cbe2 fix(backend): correct syntax for prisma transaction in renameSymptom
Deploy Canina / deploy (push) Failing after 1m15s
2026-10-18 12:55:11 +00:00
devops 468170349d feat(ux-fix): resolve wiki fallback 404, responsive B2B modal, clean badges, aligned bullets, mobile bottom nav on PDP and admin Rx/symptoms management
Deploy Canina / deploy (push) Failing after 1m14s
2026-10-18 12:51:04 +00:00
devops 52446592e7 fix(header): clean up prescription button navigation onClick handler
Deploy Canina / deploy (push) Successful in 2m16s
2026-10-18 11:35:43 +00:00
devops 7bca0ef335 feat(prescriptions): launch online veterinary prescription assessment portal with regression tests (B2B-03)
Deploy Canina / deploy (push) Failing after 1m6s
2026-10-18 11:31:49 +00:00
devops 80717680a1 feat(b2b): connect B2B landing inquiry form to public inquiry endpoint with regression test (B2B-01)
Deploy Canina / deploy (push) Successful in 2m14s
2026-10-18 11:19:51 +00:00
134 changed files with 6819 additions and 1097 deletions

No files matched your search

+2
View File
@@ -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;
+3
View File
@@ -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")
+33 -3
View File
@@ -57,7 +57,7 @@ export class AdminController {
@ApiQuery({ name: "search", required: false, description: "جستجو" })
async getUsers(@Query() query: AdminQueryDto) {
const result = await this.adminService.getUsers(query);
return { success: true, ...result };
return result;
}
@Post("users")
@@ -145,7 +145,7 @@ export class AdminController {
@ApiQuery({ name: "search", required: false, description: "جستجو" })
async getProducts(@Query() query: AdminQueryDto) {
const result = await this.adminService.getProducts(query);
return { success: true, ...result };
return result;
}
@Post("products")
@@ -206,7 +206,7 @@ export class AdminController {
@ApiQuery({ name: "status", required: false, description: "فیلتر وضعیت" })
async getOrders(@Query() query: AdminQueryDto) {
const result = await this.adminService.getOrders(query);
return { success: true, ...result };
return result;
}
@Get("orders/:id")
@@ -354,4 +354,34 @@ export class AdminController {
await this.settingsService.updateBulkUiTexts(body);
return { success: true, data: body };
}
@Get("symptoms")
@ApiOperation({ summary: "لیست کامل علائم درمانی با صفحه‌بندی، جستجو و متادیتا" })
async getSymptoms(@Query() query: { page?: number; limit?: number; search?: string }) {
const res = await this.adminService.getSymptoms(query);
return res;
}
@Post("symptoms")
@ApiOperation({ summary: "افزودن علامت درمانی جدید" })
async createSymptom(@Body() body: { name: string; slug?: string; description?: string; metaTitle?: string; metaDescription?: string; keywords?: string }) {
const res = await this.adminService.createSymptom(body);
return { success: true, data: res };
}
@Put("symptoms/:id")
@ApiOperation({ summary: "ویرایش کامل علامت درمانی و متادیتاهای سئو" })
async updateSymptom(@Param("id") id: string, @Body() body: any) {
const res = await this.adminService.updateSymptom(id, body);
return { success: true, data: res };
}
@Delete("symptoms/:id")
@ApiOperation({ summary: "حذف علامت درمانی" })
async deleteSymptom(@Param("id") id: string) {
const res = await this.adminService.deleteSymptom(id);
return res;
}
}
+160
View File
@@ -1869,4 +1869,164 @@ export class AdminService {
};
});
}
async getSymptoms(params?: { page?: number; limit?: number; search?: string }) {
const page = Math.max(1, Number(params?.page) || 1);
const limit = Math.max(1, Number(params?.limit) || 20);
const offset = (page - 1) * limit;
const search = params?.search?.trim() || '';
let items: any[] = [];
let total = 0;
if (search) {
const searchPattern = `%${search}%`;
const [listResult, countResult] = await Promise.all([
this.prisma.$queryRaw<any[]>`
SELECT
s.id,
s.name,
s.slug,
s.description,
s.meta_title as "metaTitle",
s.meta_description as "metaDescription",
s.keywords,
s.icon,
s.created_at as "createdAt",
COALESCE(COUNT(ps.product_id), 0)::int as "productsCount"
FROM symptoms s
LEFT JOIN product_symptoms ps ON ps.symptom = s.name
WHERE s.name ILIKE ${searchPattern} OR s.slug ILIKE ${searchPattern}
GROUP BY s.id, s.name, s.slug, s.description, s.meta_title, s.meta_description, s.keywords, s.icon, s.created_at
ORDER BY s.name ASC
LIMIT ${limit} OFFSET ${offset};
`,
this.prisma.$queryRaw<any[]>`
SELECT COUNT(*)::int as total
FROM symptoms s
WHERE s.name ILIKE ${searchPattern} OR s.slug ILIKE ${searchPattern};
`,
]);
items = listResult;
total = countResult[0]?.total || 0;
} else {
const [listResult, countResult] = await Promise.all([
this.prisma.$queryRaw<any[]>`
SELECT
s.id,
s.name,
s.slug,
s.description,
s.meta_title as "metaTitle",
s.meta_description as "metaDescription",
s.keywords,
s.icon,
s.created_at as "createdAt",
COALESCE(COUNT(ps.product_id), 0)::int as "productsCount"
FROM symptoms s
LEFT JOIN product_symptoms ps ON ps.symptom = s.name
GROUP BY s.id, s.name, s.slug, s.description, s.meta_title, s.meta_description, s.keywords, s.icon, s.created_at
ORDER BY s.name ASC
LIMIT ${limit} OFFSET ${offset};
`,
this.prisma.$queryRaw<any[]>`
SELECT COUNT(*)::int as total
FROM symptoms s;
`,
]);
items = listResult;
total = countResult[0]?.total || 0;
}
const lastPage = Math.ceil(total / limit) || 1;
return {
data: items,
meta: {
page,
limit,
total,
lastPage,
},
};
}
async createSymptom(dto: { name: string; slug?: string; description?: string; metaTitle?: string; metaDescription?: string; keywords?: string }) {
if (!dto.name?.trim()) throw new BadRequestException('نام علامت الزامی است');
const name = dto.name.trim();
const slug = dto.slug?.trim() || name.replace(/\s+/g, '-').toLowerCase();
return await this.prisma.$queryRawUnsafe(`
INSERT INTO symptoms (name, slug, description, meta_title, meta_description, keywords)
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING id, name, slug, description, meta_title as "metaTitle", meta_description as "metaDescription", keywords;
`, name, slug, dto.description || '', dto.metaTitle || '', dto.metaDescription || '', dto.keywords || '');
}
async updateSymptom(id: string, dto: { name?: string; slug?: string; description?: string; metaTitle?: string; metaDescription?: string; keywords?: string }) {
// 1. Get existing symptom
const existing = await this.prisma.$queryRawUnsafe<any[]>(`SELECT * FROM symptoms WHERE id = $1::uuid LIMIT 1`, id);
if (!existing || existing.length === 0) throw new NotFoundException('علامت یافت نشد');
const oldName = existing[0].name;
const newName = dto.name?.trim() || oldName;
const newSlug = dto.slug?.trim() || existing[0].slug;
return await this.prisma.$transaction(async (tx) => {
// Update symptoms table
const updated = await tx.$queryRawUnsafe(`
UPDATE symptoms
SET
name = $2,
slug = $3,
description = $4,
meta_title = $5,
meta_description = $6,
keywords = $7,
updated_at = CURRENT_TIMESTAMP
WHERE id = $1::uuid
RETURNING id, name, slug, description, meta_title as "metaTitle", meta_description as "metaDescription", keywords;
`, id, newName, newSlug, dto.description ?? existing[0].description, dto.metaTitle ?? existing[0].meta_title, dto.metaDescription ?? existing[0].meta_description, dto.keywords ?? existing[0].keywords);
// If name changed, cascade update across product_symptoms & products JSON
if (oldName !== newName) {
await tx.$executeRaw`UPDATE product_symptoms SET symptom = ${newName} WHERE symptom = ${oldName};`;
await tx.$executeRaw`
UPDATE products
SET dosage_config = jsonb_set(
dosage_config,
'{symptoms}',
(
SELECT jsonb_agg(
CASE
WHEN elem::text = to_jsonb(${oldName}::text)::text THEN to_jsonb(${newName}::text)
ELSE elem
END
)
FROM jsonb_array_elements(dosage_config->'symptoms') AS elem
)
)
WHERE dosage_config ? 'symptoms'
AND dosage_config->'symptoms' @> to_jsonb(${oldName}::text);
`;
}
return updated;
});
}
async deleteSymptom(id: string) {
const existing = await this.prisma.$queryRawUnsafe<any[]>(`SELECT * FROM symptoms WHERE id = $1::uuid LIMIT 1`, id);
if (!existing || existing.length === 0) throw new NotFoundException('علامت یافت نشد');
const name = existing[0].name;
return await this.prisma.$transaction(async (tx) => {
// Delete join links
await tx.$executeRaw`DELETE FROM product_symptoms WHERE symptom = ${name};`;
// Delete symptom row
await tx.$queryRawUnsafe(`DELETE FROM symptoms WHERE id = $1::uuid;`, id);
return { success: true, message: `علامت «${name}» با موفقیت حذف شد` };
});
}
}
@@ -0,0 +1,271 @@
import { Test, TestingModule } from "@nestjs/testing";
import { BadRequestException, NotFoundException } from "@nestjs/common";
import { ApprovalsController } from "./approvals.controller";
import { PrismaService } from "../prisma/prisma.service";
describe("ApprovalsController", () => {
let controller: ApprovalsController;
let prisma: {
approvalRequest: {
findUnique: jest.Mock;
findMany: jest.Mock;
count: jest.Mock;
create: jest.Mock;
update: jest.Mock;
delete: jest.Mock;
};
departmentTask: {
findFirst: jest.Mock;
findMany: jest.Mock;
create: jest.Mock;
update: jest.Mock;
deleteMany: jest.Mock;
updateMany: jest.Mock;
};
};
beforeEach(async () => {
prisma = {
approvalRequest: {
findUnique: jest.fn(),
findMany: jest.fn(),
count: jest.fn(),
create: jest.fn(),
update: jest.fn(),
delete: jest.fn(),
},
departmentTask: {
findFirst: jest.fn(),
findMany: jest.fn(),
create: jest.fn(),
update: jest.fn(),
deleteMany: jest.fn(),
updateMany: jest.fn(),
},
};
const module: TestingModule = await Test.createTestingModule({
controllers: [ApprovalsController],
providers: [
{
provide: PrismaService,
useValue: prisma,
},
],
}).compile();
controller = module.get<ApprovalsController>(ApprovalsController);
});
describe("decide - B2B_SUPPLIER_STRATEGY approval separation", () => {
it("B2B_SUPPLIER_STRATEGY approval must not create digital task nor set executedAt as physical action", async () => {
const approvalId = "b2b-strategy-uuid-1";
const approvalItem = {
id: approvalId,
department: "B2B",
category: "B2B_SUPPLIER_STRATEGY",
title: "[طرح استراتژیک تامین‌کننده] توسعه شبکه کلینیکی آلمان",
payload: { target: "German Suppliers", tier: "Direct" },
status: "PENDING",
};
prisma.approvalRequest.findUnique.mockResolvedValue(approvalItem);
prisma.approvalRequest.update.mockResolvedValue({
...approvalItem,
status: "APPROVED",
ceoNotes: "موافقت با مذاکره اولیه",
});
prisma.departmentTask.findFirst.mockResolvedValue(null);
const result = await controller.decide(approvalId, {
decision: "APPROVED",
ceoNotes: "موافقت با مذاکره اولیه",
});
expect(result.success).toBe(true);
expect(prisma.approvalRequest.update).toHaveBeenCalledWith({
where: { id: approvalId },
data: expect.objectContaining({
status: "APPROVED",
ceoNotes: "موافقت با مذاکره اولیه",
}),
});
// Verify executedAt is NOT set as physical action
const updateCall = prisma.approvalRequest.update.mock.calls[0][0];
expect(updateCall.data.executedAt).toBeUndefined();
// Verify NO digital task is created in departmentTask queue
expect(prisma.departmentTask.create).not.toHaveBeenCalled();
expect(prisma.departmentTask.update).not.toHaveBeenCalled();
});
it("B2B_SUPPLIER_STRATEGY approval must not requeue existing digital task", async () => {
const approvalId = "b2b-strategy-uuid-2";
const approvalItem = {
id: approvalId,
department: "B2B",
category: "B2B_SUPPLIER_STRATEGY",
title: "[طرح استراتژیک تامین‌کننده] پکیج نمونه دارویی",
payload: {},
status: "PENDING",
};
prisma.approvalRequest.findUnique.mockResolvedValue(approvalItem);
prisma.approvalRequest.update.mockResolvedValue({
...approvalItem,
status: "APPROVED",
});
prisma.departmentTask.findFirst.mockResolvedValue({
id: "task-existing-1",
status: "BACKLOG",
title: "Legacy task",
});
const result = await controller.decide(approvalId, {
decision: "APPROVED",
});
expect(result.success).toBe(true);
// Ensure existing task was NOT updated or requeued to TODO
expect(prisma.departmentTask.update).not.toHaveBeenCalled();
expect(prisma.departmentTask.create).not.toHaveBeenCalled();
});
});
describe("decide - SEO approval actionable digital task", () => {
it("SEO approval creates actionable digital task in TODO", async () => {
const approvalId = "seo-approval-uuid-1";
const approvalItem = {
id: approvalId,
department: "SEO",
category: "SEO",
title: "بهینه‌سازی متاتگ‌های صفحات دسته‌بندی گربه",
payload: { targetUrl: "/category/cat-food" },
status: "PENDING",
};
prisma.approvalRequest.findUnique.mockResolvedValue(approvalItem);
prisma.approvalRequest.update.mockResolvedValue({
...approvalItem,
status: "APPROVED",
ceoNotes: "در اولویت سئو قرار گیرد",
});
prisma.departmentTask.findFirst.mockResolvedValue(null);
prisma.departmentTask.create.mockResolvedValue({
id: "new-task-uuid",
code: "TSK-892110",
department: "SEO",
title: approvalItem.title,
status: "TODO",
priority: "HIGH",
assignee: "AI_AGENT",
approvalId: approvalId,
});
const result = await controller.decide(approvalId, {
decision: "APPROVED",
ceoNotes: "در اولویت سئو قرار گیرد",
});
expect(result.success).toBe(true);
expect(prisma.approvalRequest.update).toHaveBeenCalledWith({
where: { id: approvalId },
data: expect.objectContaining({
status: "APPROVED",
ceoNotes: "در اولویت سئو قرار گیرد",
}),
});
// Digital task MUST be created with status TODO
expect(prisma.departmentTask.create).toHaveBeenCalledWith({
data: expect.objectContaining({
department: "SEO",
title: approvalItem.title,
status: "TODO",
priority: "HIGH",
assignee: "AI_AGENT",
approvalId: approvalId,
}),
});
});
it("SEO approval requeues existing task to TODO when existing task found", async () => {
const approvalId = "seo-approval-uuid-2";
const approvalItem = {
id: approvalId,
department: "SEO",
category: "SEO",
title: "بررسی کنیبان سئو مقاله تغذیه سگ",
payload: {},
status: "PENDING",
};
const existingTask = {
id: "existing-task-99",
code: "TSK-112233",
status: "IN_REVIEW",
description: "Initial draft",
approvalId: approvalId,
};
prisma.approvalRequest.findUnique.mockResolvedValue(approvalItem);
prisma.approvalRequest.update.mockResolvedValue({
...approvalItem,
status: "APPROVED",
ceoNotes: "تایید نهایی جهت اقدام",
});
prisma.departmentTask.findFirst.mockResolvedValue(existingTask);
prisma.departmentTask.update.mockResolvedValue({
...existingTask,
status: "TODO",
});
const result = await controller.decide(approvalId, {
decision: "APPROVED",
ceoNotes: "تایید نهایی جهت اقدام",
});
expect(result.success).toBe(true);
expect(prisma.departmentTask.update).toHaveBeenCalledWith({
where: { id: existingTask.id },
data: expect.objectContaining({
status: "TODO",
}),
});
});
});
describe("decide - rejection handling", () => {
it("handles REJECTED decision cleanly without deleting approval audit history", async () => {
const approvalId = "approval-reject-uuid";
const approvalItem = {
id: approvalId,
department: "SEO",
category: "SEO",
title: "تغییر ساختار URL",
status: "PENDING",
};
prisma.approvalRequest.findUnique.mockResolvedValue(approvalItem);
prisma.approvalRequest.update.mockResolvedValue({
...approvalItem,
status: "REJECTED",
ceoNotes: "ریسک بالای افت رتبه سئو",
});
const result = await controller.decide(approvalId, {
decision: "REJECTED",
ceoNotes: "ریسک بالای افت رتبه سئو",
});
expect(result.success).toBe(true);
expect(prisma.approvalRequest.update).toHaveBeenCalledWith({
where: { id: approvalId },
data: expect.objectContaining({
status: "REJECTED",
ceoNotes: "ریسک بالای افت رتبه سئو",
}),
});
});
});
});
+56 -11
View File
@@ -106,7 +106,6 @@ export class ApprovalsController {
throw new NotFoundException(`Approval request ${id} not found`);
}
// شبیه‌سازی بسته به دسته‌بندی
let testResult: any = { status: "SIMULATION_SUCCESS" };
if (item.category === "PRICING") {
const payload = item.payload as any;
@@ -152,26 +151,70 @@ export class ApprovalsController {
}
if (dto.decision === "REJECTED") {
// 5. رد توسط مدیرعامل: تسک و درخواست کلاً از سیستم پاکسازی کامل می‌شوند
await (this.prisma as any).departmentTask.deleteMany({
where: { approvalId: id },
});
await (this.prisma as any).approvalRequest.delete({
const updated = await (this.prisma as any).approvalRequest.update({
where: { id },
data: {
status: "REJECTED",
ceoNotes: dto.ceoNotes || null,
},
});
if ((this.prisma as any).departmentTask?.updateMany) {
await (this.prisma as any).departmentTask.updateMany({
where: { approvalId: id },
data: { status: "REJECTED" },
});
}
return {
success: true,
message: "درخواست با موفقیت رد و از سیستم پاکسازی شد.",
message: "درخواست رد شد و در سوابق ممیزی ثبت گردید.",
data: updated,
};
}
// 1. تایید مدیرعامل: وضعیت درخواست APPROVED و وضعیت تسک در صف اقدام به TODO تغییر می‌یابد
// تفکیک اقدامات استراتژیک تامین‌کننده/مدیریتی از کارهای دیجیتال سایت
const isStrategicSupplierAction =
item.category === "B2B_SUPPLIER_STRATEGY" ||
item.category === "PARTNERSHIP" ||
(item.department === "B2B" && String(item.category || "").includes("STRATEGY"));
if (isStrategicSupplierAction) {
// طرح‌های B2B_SUPPLIER_STRATEGY منحصراً در سوابق مدیریتی تایید می‌شوند.
// هیچ تسک دیجیتالی ایجاد یا بازگشایی نمی‌شود و executedAt فیزیکی ثبت نمی‌گردد.
const updateData: any = {
status: "APPROVED",
ceoNotes: dto.ceoNotes || null,
};
if (dto.outcome || dto.evidence) {
const payload = typeof item.payload === "object" && item.payload !== null
? { ...(item.payload as Record<string, any>) }
: {};
if (dto.outcome) payload.outcome = dto.outcome;
if (dto.evidence) payload.evidence = dto.evidence;
updateData.payload = payload;
}
const updated = await (this.prisma as any).approvalRequest.update({
where: { id },
data: updateData,
});
return {
success: true,
message: "طرح استراتژیک تامین‌کننده تایید گردید و در سوابق مدیریتی ثبت شد.",
data: updated,
};
}
// کارهای دیجیتال (مانند SEO، محتوا، قیمت‌گذاری و فنی)
// تایید مجوز اجرای کار دیجیتال است و تسک متناظر را در صف TODO قرار می‌دهد
const updated = await (this.prisma as any).approvalRequest.update({
where: { id },
data: {
status: "APPROVED",
ceoNotes: dto.ceoNotes || null,
executedAt: new Date(),
},
});
@@ -185,14 +228,16 @@ export class ApprovalsController {
where: { id: existingTask.id },
data: {
status: "TODO",
description: dto.ceoNotes ? (existingTask.description || "") + "\n\n[یادداشت مدیرعامل]: " + dto.ceoNotes : existingTask.description,
description: dto.ceoNotes
? (existingTask.description || "") + "\n\n[یادداشت مدیرعامل]: " + dto.ceoNotes
: existingTask.description,
},
});
} else {
await (this.prisma as any).departmentTask.create({
data: {
code: "TSK-" + Date.now().toString().slice(-6),
department: item.department,
department: item.department || "SEO",
title: item.title,
description: dto.ceoNotes ? (item.title + "\n\n[یادداشت مدیرعامل]: " + dto.ceoNotes) : item.title,
status: "TODO",
@@ -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);
+119 -1
View File
@@ -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(
+120 -17
View File
@@ -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,84 @@
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("allows completion with URL, criteria and QA evidence", () => {
expect(() =>
assertTaskCanComplete({
deliverableUrl: "https://canina.ir/blog/verified",
acceptanceCriteria: { criteria: ["HTTP 200"] },
executionLogs: [{ status: "QA_PASSED" }],
}),
).not.toThrow();
});
it("rejects pseudo-protocol canina:// deliverable URLs", () => {
expect(() =>
assertTaskCanComplete({
deliverableUrl: "canina://blog/sample-article",
acceptanceCriteria: { criteria: ["HTTP 200"] },
executionLogs: [{ status: "QA_PASSED" }],
}),
).toThrow(BadRequestException);
});
it("rejects git://stage staging or repo URLs as verifiable deliverable", () => {
expect(() =>
assertTaskCanComplete({
deliverableUrl: "git://stage/canina-repo#commit123",
acceptanceCriteria: { criteria: ["HTTP 200"] },
executionLogs: [{ status: "QA_PASSED" }],
}),
).toThrow(BadRequestException);
});
it("rejects missing or placeholder post-tsk article deliverables", () => {
expect(() =>
assertTaskCanComplete({
deliverableUrl: "https://canina.ir/blog/post-tsk-49102",
acceptanceCriteria: { criteria: ["HTTP 200"] },
executionLogs: [{ status: "QA_PASSED" }],
}),
).toThrow(BadRequestException);
});
it("rejects completion when QA evidence reports missing article or 404 error", () => {
expect(() =>
assertTaskCanComplete({
deliverableUrl: "https://canina.ir/blog/verified-article",
acceptanceCriteria: { criteria: ["HTTP 200"] },
executionLogs: [{ status: "QA_PASSED", note: "HTTP 404 - مقاله یافت نشد" }],
}),
).toThrow(BadRequestException);
});
});
@@ -0,0 +1,93 @@
import { BadRequestException } from "@nestjs/common";
export interface CompletableTask {
code?: string | null;
title?: string | null;
deliverableUrl?: string | null;
acceptanceCriteria?: unknown;
executionLogs?: unknown;
}
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;
}
function hasValidQaEvidence(logs: unknown): boolean {
if (!Array.isArray(logs)) return false;
const validPassStatuses = ["QA_PASSED", "VERIFIED", "PRODUCTION_VERIFIED"];
let foundValidPass = false;
for (const log of logs) {
if (!log || typeof log !== "object") continue;
const entry = log as Record<string, unknown>;
const status = String(entry.status || "").toUpperCase();
const note = String(entry.note || "").toLowerCase();
// Rejection of invalid QA claims: 404, missing article, not found, post-tsk
if (
note.includes("404") ||
note.includes("مقاله یافت نشد") ||
note.includes("not found") ||
note.includes("missing article") ||
note.includes("post-tsk")
) {
return false;
}
if (validPassStatuses.includes(status)) {
foundValidPass = true;
}
}
return foundValidPass;
}
export function assertTaskCanComplete(task: CompletableTask): void {
const rawUrl = task.deliverableUrl?.trim();
if (!rawUrl) {
throw new BadRequestException("DONE requires a verifiable deliverable URL");
}
const lowerUrl = rawUrl.toLowerCase();
// Reject internal pseudo-protocols
if (lowerUrl.startsWith("canina://") || lowerUrl.includes("canina://")) {
throw new BadRequestException("Deliverable URL cannot use pseudo-protocol canina://; an independently verifiable HTTP(S) URL is required");
}
// Reject git repository pointers or staging branches as production deliverables
if (lowerUrl.startsWith("git://") || lowerUrl.includes("git://stage")) {
throw new BadRequestException("Deliverable URL cannot be a git staging reference; an independently verifiable HTTP(S) URL is required");
}
// Must be an HTTP or HTTPS URL
if (!lowerUrl.startsWith("http://") && !lowerUrl.startsWith("https://")) {
throw new BadRequestException("DONE requires an independently verifiable HTTP or HTTPS deliverable URL");
}
// Reject deleted or placeholder post-tsk articles
if (/post[-_]?tsk/i.test(rawUrl)) {
throw new BadRequestException("Deliverable URL references an unverified or deleted post-tsk placeholder article");
}
if (task.title && /post[-_]?tsk/i.test(task.title)) {
throw new BadRequestException("Task references an unverified or deleted post-tsk article");
}
if (task.code && /post[-_]?tsk/i.test(task.code)) {
throw new BadRequestException("Task references an unverified or deleted post-tsk code");
}
if (!hasAcceptanceCriteria(task.acceptanceCriteria)) {
throw new BadRequestException("DONE requires explicit acceptance criteria");
}
if (!hasValidQaEvidence(task.executionLogs)) {
throw new BadRequestException("DONE requires QA/production verification evidence");
}
}
@@ -0,0 +1,163 @@
import { Test, TestingModule } from "@nestjs/testing";
import { BadRequestException, NotFoundException } from "@nestjs/common";
import { DepartmentTasksController } from "./department-tasks.controller";
import { PrismaService } from "../prisma/prisma.service";
describe("DepartmentTasksController", () => {
let controller: DepartmentTasksController;
let prisma: {
departmentTask: {
findUnique: jest.Mock;
findMany: jest.Mock;
count: jest.Mock;
create: jest.Mock;
update: jest.Mock;
delete: jest.Mock;
};
auditLog: {
create: jest.Mock;
};
};
beforeEach(async () => {
prisma = {
departmentTask: {
findUnique: jest.fn(),
findMany: jest.fn(),
count: jest.fn(),
create: jest.fn(),
update: jest.fn(),
delete: jest.fn(),
},
auditLog: {
create: jest.fn().mockResolvedValue({ id: "audit-1" }),
},
};
const module: TestingModule = await Test.createTestingModule({
controllers: [DepartmentTasksController],
providers: [
{
provide: PrismaService,
useValue: prisma,
},
],
}).compile();
controller = module.get<DepartmentTasksController>(DepartmentTasksController);
});
describe("updateStatus - verifiable completion guards", () => {
it("rejects completion with pseudo-protocol canina://", async () => {
const taskId = "task-101";
prisma.departmentTask.findUnique.mockResolvedValue({
id: taskId,
code: "TSK-100101",
title: "Test Task",
status: "TEST",
acceptanceCriteria: { criteria: ["200 OK"] },
executionLogs: [{ status: "QA_PASSED" }],
deliverableUrl: null,
});
await expect(
controller.updateStatus(taskId, {
status: "DONE",
deliverableUrl: "canina://blog/fake-article",
}),
).rejects.toThrow(BadRequestException);
});
it("rejects completion with git://stage repository reference", async () => {
const taskId = "task-102";
prisma.departmentTask.findUnique.mockResolvedValue({
id: taskId,
code: "TSK-100102",
title: "Test Task",
status: "TEST",
acceptanceCriteria: { criteria: ["200 OK"] },
executionLogs: [{ status: "QA_PASSED" }],
deliverableUrl: null,
});
await expect(
controller.updateStatus(taskId, {
status: "DONE",
deliverableUrl: "git://stage/canina-repo#commit-xyz",
}),
).rejects.toThrow(BadRequestException);
});
it("rejects completion with post-tsk placeholder article", async () => {
const taskId = "task-103";
prisma.departmentTask.findUnique.mockResolvedValue({
id: taskId,
code: "TSK-100103",
title: "Test Task",
status: "TEST",
acceptanceCriteria: { criteria: ["200 OK"] },
executionLogs: [{ status: "QA_PASSED" }],
deliverableUrl: null,
});
await expect(
controller.updateStatus(taskId, {
status: "DONE",
deliverableUrl: "https://canina.ir/blog/post-tsk-998877",
}),
).rejects.toThrow(BadRequestException);
});
it("rejects completion when QA log reports missing article / 404", async () => {
const taskId = "task-104";
prisma.departmentTask.findUnique.mockResolvedValue({
id: taskId,
code: "TSK-100104",
title: "Test Task",
status: "TEST",
acceptanceCriteria: { criteria: ["200 OK"] },
executionLogs: [],
deliverableUrl: "https://canina.ir/blog/real-article",
});
await expect(
controller.updateStatus(taskId, {
status: "DONE",
logNote: "QA_PASSED but received 404 - مقاله یافت نشد",
}),
).rejects.toThrow(BadRequestException);
});
it("allows completion with valid HTTPS deliverable URL and verified QA evidence", async () => {
const taskId = "task-105";
const existingTask = {
id: taskId,
code: "TSK-100105",
title: "Optimized Cat Food Landing",
status: "TEST",
acceptanceCriteria: { criteria: ["HTTP 200", "Lighthouse > 90"] },
executionLogs: [{ status: "PRODUCTION_VERIFIED", note: "Live 200 verified on production" }],
deliverableUrl: "https://canina.ir/blog/cat-food-nutrition",
};
prisma.departmentTask.findUnique.mockResolvedValue(existingTask);
prisma.departmentTask.update.mockResolvedValue({
...existingTask,
status: "DONE",
completedAt: new Date(),
});
const res = await controller.updateStatus(taskId, {
status: "DONE",
});
expect(res.success).toBe(true);
expect(prisma.departmentTask.update).toHaveBeenCalledWith({
where: { id: taskId },
data: expect.objectContaining({
status: "DONE",
completedAt: expect.any(Date),
}),
});
});
});
});
@@ -10,6 +10,7 @@ import {
UseGuards,
NotFoundException,
} 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";
@@ -129,7 +130,6 @@ export class DepartmentTasksController {
},
});
// ثبت در تاریخچه لاگ‌ها
await (this.prisma as any).auditLog.create({
data: {
entity: "task",
@@ -165,6 +165,17 @@ export class DepartmentTasksController {
});
}
const candidateDeliverableUrl = body.deliverableUrl || existing.deliverableUrl;
if (body.status === "DONE") {
assertTaskCanComplete({
code: existing.code,
title: existing.title,
deliverableUrl: candidateDeliverableUrl,
acceptanceCriteria: existing.acceptanceCriteria,
executionLogs: logs,
});
}
const updateData: any = {
status: body.status,
executionLogs: logs,
@@ -172,7 +183,6 @@ export class DepartmentTasksController {
if (body.deliverableUrl) updateData.deliverableUrl = body.deliverableUrl;
if (body.status === "IN_PROGRESS" && !existing.startedAt) updateData.startedAt = new Date();
if (body.status === "DONE") updateData.completedAt = new Date();
// اگر تست QA ناموفق بود و به TODO برگشت، لاگ اصلاح ضمیمه می‌شود
if (body.status === "TODO" && body.logNote) {
updateData.description = (existing.description || "") + "\n\n[اصلاحات و تضمین کیفیت QA]: " + body.logNote;
}
@@ -182,7 +192,6 @@ export class DepartmentTasksController {
data: updateData,
});
// ثبت در تاریخچه
await (this.prisma as any).auditLog.create({
data: {
entity: "task",
@@ -33,6 +33,16 @@ export class DecideApprovalDto {
@IsOptional()
@IsString()
ceoNotes?: string;
@ApiPropertyOptional({ description: "نتیجه اقدام مدیریتی یا استراتژیک" })
@IsOptional()
@IsString()
outcome?: string;
@ApiPropertyOptional({ description: "مستندات و مدرک اقدام مدیریتی" })
@IsOptional()
@IsString()
evidence?: string;
}
export class QueryApprovalDto {
+1 -1
View File
@@ -76,7 +76,7 @@ describe("MediaService", () => {
const validFile = {
originalname: "product-cover.webp",
buffer: Buffer.from("dummy-image-bytes"),
buffer: Buffer.from([0x52, 0x49, 0x46, 0x46, 0x00, 0x00, 0x00, 0x00, 0x57, 0x45, 0x42, 0x50, 0x56, 0x50, 0x38]),
mimetype: "image/webp",
size: 5000,
} as any;
+22
View File
@@ -79,6 +79,28 @@ export class MediaService {
"پسوند فایل ارسالی مجاز نیست (فرمت SVG و فایل‌های اجرایی مسدود هستند).",
);
}
// SEC-01: Magic number verification for uploaded binary content
const buf = file.buffer;
if (!buf || buf.length < 4) {
throw new BadRequestException("فایل نامعتبر یا آسیب‌دیده است.");
}
const isJpeg = buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff;
const isPng = buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47;
const isGif = buf[0] === 0x47 && buf[1] === 0x49 && buf[2] === 0x46; // GIF87a or GIF89a
const isPdf = buf[0] === 0x25 && buf[1] === 0x50 && buf[2] === 0x44 && buf[3] === 0x46; // %PDF
const isWebp =
buf.length >= 12 &&
buf[0] === 0x52 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x46 && // RIFF
buf[8] === 0x57 && buf[9] === 0x45 && buf[10] === 0x42 && buf[11] === 0x50; // WEBP
if (!isJpeg && !isPng && !isGif && !isPdf && !isWebp) {
throw new BadRequestException(
"محتوای باینری فایل با پسوند یا هدر ادعایی همخوانی ندارد (اعتبارسنجی امضای فایل رد شد).",
);
}
const filename = `${uniqueSuffix}${ext}`;
const filePath = path.join(uploadDir, filename);
+2
View File
@@ -1,3 +1,4 @@
import { TasksModule } from './common/services/tasks.module';
import { Module, NestModule, MiddlewareConsumer } from "@nestjs/common";
import { PrismaModule } from "./prisma/prisma.module";
import { SupportChatModule } from './support-chat/support-chat.module';
@@ -79,6 +80,7 @@ import { Request, Response, NextFunction } from "express";
B2BModule,
FaqModule,
MenuModule,
TasksModule,
],
controllers: [MetricsController],
providers: [
+20 -1
View File
@@ -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(
+18 -5
View File
@@ -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`;
@@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { TasksService } from './tasks.service';
import { OrdersModule } from '../../orders/orders.module';
import { PaymentModule } from '../../payment/payment.module';
import { RedisModule } from '../../redis/redis.module';
@Module({
imports: [OrdersModule, PaymentModule, RedisModule],
providers: [TasksService],
exports: [TasksService],
})
export class TasksModule {}
@@ -0,0 +1,80 @@
import { Injectable, Logger, OnApplicationBootstrap, OnApplicationShutdown } from '@nestjs/common';
import { OrdersService } from '../../orders/orders.service';
import { RedisService } from '../../redis/redis.service';
import { PaymentService } from '../../payment/payment.service';
@Injectable()
export class TasksService implements OnApplicationBootstrap, OnApplicationShutdown {
private readonly logger = new Logger(TasksService.name);
private reservationTimer: NodeJS.Timeout | null = null;
private reconciliationTimer: NodeJS.Timeout | null = null;
constructor(
private readonly ordersService: OrdersService,
private readonly paymentService: PaymentService,
private readonly redisService: RedisService,
) {}
onApplicationBootstrap() {
this.logger.log('Starting background maintenance tasks...');
// 1. Release expired inventory reservations every 5 minutes (300,000 ms)
this.reservationTimer = setInterval(async () => {
const lockAcquired = await this.redisService.acquireLock('task:inventory_release', 240);
if (!lockAcquired) {
this.logger.debug('[Task:Inventory] Another instance holds the lock, skipping execution.');
return;
}
try {
const result = await this.ordersService.releaseExpiredInventoryReservations();
if (result.releasedCount > 0) {
this.logger.log(`[Task:Inventory] Automatically released ${result.releasedCount} expired inventory reservations.`);
}
} catch (err) {
this.logger.error('[Task:Inventory] Failed to release expired inventory reservations:', err);
} finally {
await this.redisService.releaseLock('task:inventory_release');
}
}, 5 * 60 * 1000);
// 2. Reconcile pending online payment transactions every 10 minutes (600,000 ms)
this.reconciliationTimer = setInterval(async () => {
const lockAcquired = await this.redisService.acquireLock('task:payment_reconciliation', 540);
if (!lockAcquired) {
this.logger.debug('[Task:PaymentReconciliation] Another instance holds the lock, skipping execution.');
return;
}
try {
const result = await this.paymentService.reconcilePendingTransactions();
if (result.total > 0) {
this.logger.log(`[Task:PaymentReconciliation] Checked ${result.total} transactions: ${result.verified} verified, ${result.failed} failed.`);
}
} catch (err) {
this.logger.error('[Task:PaymentReconciliation] Failed to reconcile pending payments:', err);
} finally {
await this.redisService.releaseLock('task:payment_reconciliation');
}
}, 10 * 60 * 1000);
// Initial check on startup after 30 seconds
setTimeout(async () => {
try {
await this.ordersService.releaseExpiredInventoryReservations();
} catch (err) {
this.logger.warn('[Task:Startup] Initial inventory check warning:', err);
}
}, 30 * 1000);
}
onApplicationShutdown() {
this.logger.log('Stopping background maintenance tasks...');
if (this.reservationTimer) {
clearInterval(this.reservationTimer);
this.reservationTimer = null;
}
if (this.reconciliationTimer) {
clearInterval(this.reconciliationTimer);
this.reconciliationTimer = null;
}
}
}
+1
View File
@@ -5,5 +5,6 @@ import { OrdersController } from "./orders.controller";
@Module({
controllers: [OrdersController],
providers: [OrdersService],
exports: [OrdersService],
})
export class OrdersModule {}
+1 -1
View File
@@ -39,7 +39,7 @@ describe("OrdersService", () => {
uiText: {
findFirst: jest.fn().mockResolvedValue(null),
},
$executeRaw: jest.fn(),
$executeRaw: jest.fn().mockResolvedValue(1),
$transaction: jest.fn(),
};
+2 -1
View File
@@ -346,13 +346,14 @@ export class OrdersService {
// Deduct inventory immediately for non-online orders (card to card)
if (!isOnline) {
for (const item of createOrderDto.items) {
// BE-05: Atomic decrement with inventory constraint guard
const updated = await tx.product.update({
where: { id: item.productId },
data: {
stock: { decrement: item.quantity },
},
});
if (updated.stock <= 0) {
if (updated && updated.stock <= 0) {
await tx.product.update({
where: { id: item.productId },
data: { stockStatus: "OUT_OF_STOCK" },
+24 -9
View File
@@ -447,17 +447,32 @@ export class PaymentService {
if (orderWithItems?.orderItems) {
for (const item of orderWithItems.orderItems) {
if (item.productId) {
const updated = await tx.product.update({
where: { id: item.productId },
data: {
stock: { decrement: item.quantity },
},
});
if (updated.stock <= 0) {
await tx.product.update({
// BE-05: Atomic decrement with inventory constraint guard
let updateCount = 1;
if (typeof (tx as any).$executeRaw === 'function') {
updateCount = await tx.$executeRaw`
UPDATE products
SET stock = stock - ${item.quantity},
stock_status = CASE WHEN stock - ${item.quantity} <= 0 THEN 'OUT_OF_STOCK'::"StockStatus" ELSE stock_status END
WHERE id = ${item.productId}::uuid AND stock >= ${item.quantity}
`;
} else {
const updated = await tx.product.update({
where: { id: item.productId },
data: { stockStatus: "OUT_OF_STOCK" },
data: { stock: { decrement: item.quantity } },
});
if (updated.stock <= 0) {
await tx.product.update({
where: { id: item.productId },
data: { stockStatus: "OUT_OF_STOCK" },
});
}
}
if (updateCount === 0) {
this.logger.error(
`[CriticalInventoryAlert] Product ${item.productId} lacked sufficient stock for paid order ${transaction.orderId} (requested ${item.quantity}). Manual inventory check required.`
);
}
}
}
+26
View File
@@ -1,13 +1,39 @@
import { Injectable, OnModuleInit, OnModuleDestroy } from "@nestjs/common";
import { PrismaClient } from "@prisma/client";
import { Logger } from "@nestjs/common";
@Injectable()
export class PrismaService
extends PrismaClient
implements OnModuleInit, OnModuleDestroy
{
private readonly logger = new Logger(PrismaService.name);
constructor() {
super({
log: [
{ emit: "event", level: "query" },
{ emit: "stdout", level: "error" },
{ emit: "stdout", level: "warn" },
],
});
}
async onModuleInit() {
await this.$connect();
// BE-07: Slow query logging interceptor (> 300ms)
if (typeof (this as any).$on === "function") {
(this as any).$on("query", (e: any) => {
if (e.duration >= 300) {
this.logger.warn(
`[SlowQueryAlert] Duration: ${e.duration}ms | Target: ${e.target} | Query: ${e.query.substring(0, 300)}...`,
);
}
});
}
await this.ensureTablesExist();
}
@@ -14,6 +14,9 @@ describe("ProductsService", () => {
findFirst: jest.fn(),
count: jest.fn(),
},
orderItem: {
groupBy: jest.fn().mockResolvedValue([]),
},
};
const mockRevalidationService = {
+25 -10
View File
@@ -87,6 +87,7 @@ export class ProductsService {
const skip = (page - 1) * limit;
// 1. Fetch products with lean relations (no heavy N+1 orderItems join)
const [rawProducts, total] = await Promise.all([
this.prisma.product.findMany({
where: whereClause,
@@ -96,15 +97,33 @@ export class ProductsService {
include: {
ingredientList: true,
symptoms: true,
orderItems: {
where: { order: { status: { not: "CANCELLED" } } },
select: { quantity: true },
},
},
}),
this.prisma.product.count({ where: whereClause }),
]);
// 2. Efficient single aggregate query for total sold counts for the current page slice
const productIds = rawProducts.map((p) => p.id);
let salesMap: Record<string, number> = {};
if (productIds.length > 0) {
const salesAgg = await this.prisma.orderItem.groupBy({
by: ['productId'],
_sum: { quantity: true },
where: {
productId: { in: productIds },
order: { status: { not: 'CANCELLED' } },
},
});
salesMap = salesAgg.reduce((acc, row) => {
if (row.productId) {
acc[row.productId] = Number(row._sum.quantity) || 0;
}
return acc;
}, {} as Record<string, number>);
}
const isWholesaleOrAdmin =
userRole === "User_Wholesale" ||
userRole === "User_Partner" ||
@@ -113,12 +132,8 @@ export class ProductsService {
const isAdmin = userRole === "ADMIN" || userRole === "SuperAdmin";
const data = rawProducts.map((p) => {
const totalSold =
p.orderItems?.reduce(
(acc, item) => acc + (Number(item.quantity) || 0),
0,
) || 0;
const { buyPrice, wholesalePrice, orderItems, ...publicProduct } = p;
const totalSold = salesMap[p.id] || 0;
const { buyPrice, wholesalePrice, ...publicProduct } = p;
void buyPrice;
void wholesalePrice;
if (!isWholesaleOrAdmin) {
+16
View File
@@ -45,4 +45,20 @@ export class RedisService implements OnModuleInit, OnModuleDestroy {
async ttl(key: string): Promise<number> {
return this.client.ttl(key);
}
/**
* Acquire a distributed lock using Redis SET NX EX
* Returns true if lock acquired, false otherwise
*/
async acquireLock(key: string, ttlSeconds: number = 60): Promise<boolean> {
const res = await this.client.set(`lock:${key}`, "1", "EX", ttlSeconds, "NX");
return res === "OK";
}
/**
* Release a distributed lock
*/
async releaseLock(key: string): Promise<void> {
await this.client.del(`lock:${key}`);
}
}
@@ -0,0 +1,71 @@
import { RouterUsageAdapter } from './router-usage.adapter';
const stats = {totalRequests:0,totalPromptTokens:0,totalCompletionTokens:0,totalCachedTokens:0,byModel:{},byProvider:{},byAccount:{}};
describe('bounded read-only adapter', () => {
afterEach(() => jest.restoreAllMocks());
it('uses only authenticated GET stats with a validated period and never follows redirects', async () => {
const fetcher = jest.spyOn(global, 'fetch').mockResolvedValue(new Response(JSON.stringify(stats)));
const adapter = new RouterUsageAdapter();
process.env.ROUTER_USAGE_BASE_URL = 'https://nr.parsaaghayi.ir';
process.env.ROUTER_USAGE_CLI_TOKEN = 'server-only-secret';
const result = await adapter.summary('24h');
expect(result.status).toBe('available');
expect(result.attribution).toEqual({scope:'9router_total',hermes:null,additive:false});
expect(fetcher).toHaveBeenCalledTimes(1);
expect(fetcher).toHaveBeenCalledWith('https://nr.parsaaghayi.ir/api/usage/stats?period=24h', expect.objectContaining({method:'GET',redirect:'error',headers:{'x-9r-cli-token':'server-only-secret',Accept:'application/json'}}));
expect(JSON.stringify(result)).not.toContain('server-only-secret');
});
it('rejects invalid time filters before IO', async () => {
const fetcher = jest.spyOn(global,'fetch');
await expect(new RouterUsageAdapter().summary('../providers')).rejects.toThrow();
expect(fetcher).not.toHaveBeenCalled();
});
it('fails closed when credential is missing', async () => {
delete process.env.ROUTER_USAGE_CLI_TOKEN;
const fetcher = jest.spyOn(global,'fetch');
const result = await new RouterUsageAdapter().summary('7d');
expect(result).toMatchObject({status:'unavailable',data:null,reason:'not_configured'});
expect(fetcher).not.toHaveBeenCalled();
});
it.each([401,403,429,500])('returns unknown data without upstream error text for %s', async status => {
process.env.ROUTER_USAGE_CLI_TOKEN='secret';
jest.spyOn(global,'fetch').mockResolvedValue(new Response('credential-secret',{status}));
const result = await new RouterUsageAdapter().summary('7d');
expect(result).toMatchObject({status:'unavailable',data:null,reason:'upstream_unavailable'});
expect(JSON.stringify(result)).not.toContain('credential-secret');
});
it('rejects oversized bodies even without content length', async () => {
process.env.ROUTER_USAGE_CLI_TOKEN='secret';
jest.spyOn(global,'fetch').mockResolvedValue(new Response('x'.repeat(1048577)));
expect(await new RouterUsageAdapter().summary('7d')).toMatchObject({status:'unavailable',data:null});
});
it('does not return stale last-good totals after a failure', async () => {
process.env.ROUTER_USAGE_CLI_TOKEN='secret';
jest.spyOn(global,'fetch').mockResolvedValueOnce(new Response(JSON.stringify(stats))).mockRejectedValueOnce(new Error('token-secret'));
const adapter=new RouterUsageAdapter();
expect((await adapter.summary('7d')).status).toBe('available');
expect(await adapter.summary('7d')).toMatchObject({status:'unavailable',data:null});
});
});
describe('transport boundaries', () => {
afterEach(()=>jest.restoreAllMocks());
it('never sends credentials to a configured alternate origin', async()=>{
process.env.ROUTER_USAGE_CLI_TOKEN='secret';
process.env.ROUTER_USAGE_BASE_URL='https://attacker.invalid';
const fetcher=jest.spyOn(global,'fetch');
expect(await new RouterUsageAdapter().summary()).toMatchObject({status:'unavailable',reason:'invalid_configuration'});
expect(fetcher).not.toHaveBeenCalled();
delete process.env.ROUTER_USAGE_BASE_URL;
});
it('bounds simultaneous upstream calls and exposes no stale totals', async()=>{
process.env.ROUTER_USAGE_CLI_TOKEN='secret';
let resolve!: (value: Response) => void;
const pending=new Promise<Response>(r=>{resolve=r;});
jest.spyOn(global,'fetch').mockReturnValue(pending);
const adapter=new RouterUsageAdapter();
const calls=Array.from({length:4},()=>adapter.summary());
expect(await adapter.summary()).toMatchObject({status:'unavailable',reason:'busy',data:null});
resolve(new Response('',{status:503}));
await Promise.all(calls);
});
});
@@ -0,0 +1,45 @@
import { BadRequestException, Injectable } from '@nestjs/common';
import { normalizeStats } from './router-usage.contract';
export const ROUTER_PERIODS = ['today','24h','7d','30d','60d','all'] as const;
@Injectable()
export class RouterUsageAdapter {
private active = 0;
async summary(period = '7d') {
if (!ROUTER_PERIODS.includes(period as typeof ROUTER_PERIODS[number])) throw new BadRequestException('Invalid period');
const base = {source:'9router' as const,period,attribution:{scope:'9router_total',hermes:null,additive:false},
capabilities:{errors:false,reasoningTokens:false,cacheWriteTokens:false,quota:false,customTimeRange:false},
freshness:{retrievedAt:null as string | null,sourceUpdatedAt:null,stale:null as boolean | null}};
const unavailable = (reason: string) => ({...base,status:'unavailable' as const,reason,data:null});
const token=process.env.ROUTER_USAGE_CLI_TOKEN;
if (!token) return unavailable('not_configured');
if (this.active >= 4) return unavailable('busy');
this.active++;
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(),5000);
try {
const url=new URL(process.env.ROUTER_USAGE_BASE_URL || 'https://nr.parsaaghayi.ir');
if (url.origin !== 'https://nr.parsaaghayi.ir' || url.username || url.password || url.pathname !== '/' || url.search || url.hash) return unavailable('invalid_configuration');
const response=await fetch(`${url.origin}/api/usage/stats?period=${period}`,{
method:'GET',redirect:'error',signal:controller.signal,
headers:{'x-9r-cli-token':token,Accept:'application/json'},
});
if (!response.ok || !response.body) throw new Error('Upstream unavailable');
const reader=response.body.getReader();
const chunks:Uint8Array[]=[];
let size=0;
try {
while (true) {
const {done,value}=await reader.read();
if (done) break;
size+=value.byteLength;
if (size>1048576) {await reader.cancel(); throw new Error('Response too large');}
chunks.push(value);
}
} finally { reader.releaseLock(); }
const data=normalizeStats(JSON.parse(Buffer.concat(chunks).toString('utf8')));
return {...base,status:'available' as const,reason:null,data,
freshness:{retrievedAt:new Date().toISOString(),sourceUpdatedAt:null,stale:null}};
} catch { return unavailable('upstream_unavailable'); }
finally { clearTimeout(timeout); this.active--; }
}
}
@@ -0,0 +1,37 @@
type RecordValue = Record<string, unknown>;
export function record(value: unknown): RecordValue {
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Invalid upstream schema');
return value as RecordValue;
}
function count(value: unknown): number | null {
return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : null;
}
function identifier(value: unknown): string | null {
return typeof value === 'string' && /^[a-zA-Z0-9_./:@()+ -]{1,180}$/.test(value) && !value.includes('@') && !/^(sk-|Bearer )/i.test(value) ? value : null;
}
function metrics(row: RecordValue, prefix = '') {
const key = (name: string) => prefix ? prefix + name[0].toUpperCase() + name.slice(1) : name;
return {
requests: count(row[key('requests')]), inputTokens: count(row[key('promptTokens')]),
outputTokens: count(row[key('completionTokens')]), cacheReadTokens: count(row[key('cachedTokens')]),
cacheWriteTokens: null, reasoningTokens: null, errors: null,
};
}
export function normalizeStats(value: unknown) {
const stats = record(value);
if (count(stats.totalRequests) === null) throw new Error('Invalid stats');
const rows = (key: string) => {
const entries = Object.entries(record(stats[key]));
if (entries.length > 2000) throw new Error('Too many aggregates');
return entries;
};
return {
totals: metrics(stats, 'total'),
providers: rows('byProvider').map(([id, row]) => ({provider: identifier(id), ...metrics(record(row))})),
models: rows('byModel').map(([, row]) => { const r = record(row); return {model: identifier(r.rawModel), provider: identifier(r.provider), ...metrics(r)}; }),
accounts: rows('byAccount').map(([, row]) => { const r = record(row); return {
accountId: identifier(r.connectionId), model: identifier(r.rawModel), provider: identifier(r.provider), ...metrics(r),
quota: {status: 'unknown' as const, remaining: null, resetAt: null, reason: 'upstream_quota_get_mutates_credentials'},
}; }),
};
}
@@ -0,0 +1,22 @@
import { Controller, Get, Header, Query, UseGuards, ValidationPipe } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { IsIn, IsOptional } from 'class-validator';
import { Roles } from '../common/decorators/roles.decorator';
import { RolesGuard } from '../common/guards/roles.guard';
import { ROUTER_PERIODS, RouterUsageAdapter } from './router-usage.adapter';
export class RouterUsageQuery {
@IsOptional()
@IsIn(ROUTER_PERIODS)
period?: string;
}
@Controller('admin/router-usage')
@UseGuards(AuthGuard('jwt'), RolesGuard)
@Roles('admin')
export class RouterUsageController {
constructor(private readonly adapter: RouterUsageAdapter) {}
@Get()
@Header('Cache-Control','private, no-store')
summary(@Query(new ValidationPipe({transform:true,whitelist:true,forbidNonWhitelisted:true})) query: RouterUsageQuery) {
return this.adapter.summary(query.period ?? '7d');
}
}
@@ -0,0 +1,36 @@
import { Test } from '@nestjs/testing';
import { INestApplication, ValidationPipe } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import request from 'supertest';
import { RouterUsageModule } from './router-usage.module';
import { RouterUsageAdapter } from './router-usage.adapter';
describe('protected router usage HTTP contract', () => {
let app: INestApplication;
const summary=jest.fn().mockResolvedValue({status:'available',data:{}});
beforeAll(async () => {
const module=await Test.createTestingModule({imports:[RouterUsageModule]})
.overrideProvider(RouterUsageAdapter).useValue({summary})
.overrideGuard(AuthGuard('jwt')).useValue({canActivate(context: any){
const req=context.switchToHttp().getRequest();
if (!req.headers.authorization) return false;
req.user={role:req.headers.authorization}; return true;
}}).compile();
app=module.createNestApplication();
app.useGlobalPipes(new ValidationPipe({transform:true,whitelist:true,forbidNonWhitelisted:true}));
await app.init();
});
afterAll(async()=>app.close());
it('blocks unauthenticated access', async()=>{ await request(app.getHttpServer()).get('/admin/router-usage').expect(403); });
it('blocks non-admin users', async()=>{ await request(app.getHttpServer()).get('/admin/router-usage').set('Authorization','customer').expect(403); });
it('permits admins and defaults to 7d', async()=>{
await request(app.getHttpServer()).get('/admin/router-usage').set('Authorization','admin').expect(200);
expect(summary).toHaveBeenCalledWith('7d');
});
it('rejects unsupported custom time range', async()=>{
await request(app.getHttpServer()).get('/admin/router-usage?from=2026-01-01').set('Authorization','admin').expect(400);
});
it('rejects invalid period', async()=>{
await request(app.getHttpServer()).get('/admin/router-usage?period=invalid').set('Authorization','admin').expect(400);
});
});
@@ -0,0 +1,6 @@
import { Module } from '@nestjs/common';
import { RouterUsageController } from './router-usage.controller';
import { RouterUsageAdapter } from './router-usage.adapter';
import { RolesGuard } from '../common/guards/roles.guard';
@Module({controllers:[RouterUsageController],providers:[RouterUsageAdapter,RolesGuard],exports:[RouterUsageAdapter]})
export class RouterUsageModule {}
@@ -0,0 +1,28 @@
import { normalizeStats } from './router-usage.contract';
describe('9router stats allowlist', () => {
it('maps real aggregate fields without leaking API-key map keys or account labels', () => {
const result = normalizeStats({totalRequests:2,totalPromptTokens:10,totalCompletionTokens:4,totalCachedTokens:3,
byProvider:{codex:{requests:2,promptTokens:10,completionTokens:4,cachedTokens:3}},
byModel:{'m (codex)':{rawModel:'m',provider:'codex',requests:2}},
byAccount:{'private@example.com':{rawModel:'m',provider:'codex',connectionId:'account-1',accountName:'private@example.com',requests:2}},
byApiKey:{'SECRET-KEY|m':{apiKey:'SECRET-KEY'}},accessToken:'SECRET-TOKEN'});
expect(result.totals).toEqual({requests:2,inputTokens:10,outputTokens:4,cacheReadTokens:3,cacheWriteTokens:null,reasoningTokens:null,errors:null});
expect(result.models[0]).toMatchObject({model:'m',provider:'codex',requests:2});
expect(result.accounts[0]).toMatchObject({accountId:'account-1',quota:{status:'unknown',remaining:null,resetAt:null,reason:'upstream_quota_get_mutates_credentials'}});
expect(JSON.stringify(result)).not.toMatch(/SECRET|private@|accountName|byApiKey/);
});
});
describe('unknown rather than fabricated metrics', () => {
const empty = {totalRequests:0,byProvider:{},byModel:{},byAccount:{}};
it('preserves known zero and unknown missing counters separately', () => {
expect(normalizeStats(empty).totals).toEqual({requests:0,inputTokens:null,outputTokens:null,cacheReadTokens:null,cacheWriteTokens:null,reasoningTokens:null,errors:null});
});
it.each([null,{},[],{...empty,totalRequests:-1},{...empty,byModel:null}])('rejects invalid schemas', value => {
expect(()=>normalizeStats(value)).toThrow();
});
it('rejects unsafe metric values instead of coercing them to zero', () => {
expect(normalizeStats({...empty,totalPromptTokens:'10',totalCompletionTokens:-4,totalCachedTokens:Infinity}).totals).toMatchObject({inputTokens:null,outputTokens:null,cacheReadTokens:null});
});
});
+23 -1
View File
@@ -94,4 +94,26 @@ describe("SettingsService", () => {
});
expect(result.key).toBe("k");
});
});
it("should never leak sensitive keys or tokens in getUiTexts", async () => {
mockPrisma.uiText.findMany.mockResolvedValue([
{ key: "SITE_NAME", value: "Canina Iran" },
{ key: "ZIBAL_EBANK_TOKEN", value: "secret_token_123" },
{ key: "zibal_api_key", value: "secret_api_key" },
{ key: "SMS_SECRET_PASSWORD", value: "sms_pass" },
]);
mockPrisma.setting.findMany.mockResolvedValue([
{ key: "PUBLIC_BANNER", value: "Welcome" },
{ key: "KAVENEGAR_API_KEY", value: "kavenegar_secret" },
]);
const result = await service.getUiTexts();
const returnedKeys = result.map((r) => r.key);
expect(returnedKeys).toContain("SITE_NAME");
expect(returnedKeys).toContain("PUBLIC_BANNER");
expect(returnedKeys).not.toContain("ZIBAL_EBANK_TOKEN");
expect(returnedKeys).not.toContain("zibal_api_key");
expect(returnedKeys).not.toContain("SMS_SECRET_PASSWORD");
expect(returnedKeys).not.toContain("KAVENEGAR_API_KEY");
});
});
+21 -4
View File
@@ -269,10 +269,27 @@ export class SettingsService implements OnModuleInit {
mergedMap.set("b2b_enabled", val);
}
return Array.from(mergedMap.entries()).map(([key, value]) => ({
key,
value,
}));
const SENSITIVE_KEY_PATTERNS = [
/token/i,
/secret/i,
/password/i,
/api_key/i,
/apikey/i,
/private/i,
/zibal/i,
/kavenegar/i,
/ghasedak/i,
/credential/i,
/account_id/i,
/access_key/i,
];
return Array.from(mergedMap.entries())
.filter(([key]) => !SENSITIVE_KEY_PATTERNS.some((pattern) => pattern.test(key)))
.map(([key, value]) => ({
key,
value,
}));
}
async updateUiText(key: string, value: string) {
@@ -13,7 +13,7 @@ class TestJwt extends PassportStrategy(Strategy) {
const selected = { enabled:true, provider:'configured-1234567890abcdef', model:'real-model', label:'پشتیبان تست', icon:'paw' };
describe('smart chat settings', () => {
let stored:any = null;
const prisma:any = { setting:{ findUnique:jest.fn(async()=>stored), upsert:jest.fn(async(q:any)=>{stored={value:q.create.value};return stored;}) }, product:{findMany:jest.fn(async()=>[])}, user:{findUnique:jest.fn()}, order:{findMany:jest.fn()} };
const prisma:any = { setting:{ findUnique:jest.fn(async()=>stored), upsert:jest.fn(async(q:any)=>{stored={value:q.create.value};return stored;}) }, product:{findMany:jest.fn(async()=>[])}, user:{findUnique:jest.fn()}, order:{findMany:jest.fn()}, supportConversation:{create:jest.fn(async(q:any)=>({id:q.data.id,messages:[]})),findUnique:jest.fn(async()=>null),update:jest.fn(async()=>({}))}, supportConversationMessage:{createMany:jest.fn(async()=>({count:2}))} };
let service:SupportChatSettingsService;
beforeEach(()=>{stored=null;jest.clearAllMocks();service=new SupportChatSettingsService(prisma);process.env.SUPPORT_CHAT_URL='http://internal/ask';process.env.SUPPORT_CHAT_KEY='key';});
afterEach(()=>jest.restoreAllMocks());
@@ -5,9 +5,9 @@ describe('model intent routing', () => {
let service: SupportChatService;
beforeEach(()=>{jest.clearAllMocks();process.env.SUPPORT_CHAT_URL='http://internal/ask';process.env.SUPPORT_CHAT_KEY='test';service=new SupportChatService(prisma, { read: async () => ({ enabled: true, provider: 'p', model: 'm' }) } as any);});
afterEach(()=>jest.restoreAllMocks());
function model(body:any) { return jest.spyOn(global,'fetch').mockResolvedValue({ok:true,json:async()=>body} as any); }
function model(body:any) { return jest.spyOn(global,'fetch').mockImplementation(async(url)=>({ok:true,json:async()=>String(url).endsWith('/classify')?body:(body.answer?body:{answer:'پاسخ تست'})} as any)); }
it('guest model wallet does not load private rows',async()=>{model({intent:'wallet'});expect((await service.ask({message:'cheghadr etebar daram'})).answer).toContain('وارد');expect(prisma.user.findUnique).not.toHaveBeenCalled();expect(prisma.order.findMany).not.toHaveBeenCalled();});
it('forwards only the authenticated user pet context',async()=>{const f=model({intent:'public'});prisma.pet={findMany:jest.fn().mockResolvedValue([{id:'pet-1',name:'RSL',type:'سگ',breed:'',age:2,weight:4,activityLevel:'متوسط',medicalConditions:[{condition:'حساسیت'}]}])};await service.ask({message:'جرم دندان RSL چیست؟'},{id:'alice'});const body=JSON.parse(f.mock.calls[0][1]!.body as string);expect(body.pet_context).toEqual([{id:'pet-1',name:'RSL',type:'سگ',breed:'',age:2,weight:4,activityLevel:'متوسط',medicalConditions:['حساسیت']}]);});
it('forwards only the authenticated user pet context',async()=>{const f=model({intent:'public'});prisma.pet={findMany:jest.fn().mockResolvedValue([{id:'pet-1',name:'RSL',type:'سگ',breed:'',age:2,weight:4,activityLevel:'متوسط',medicalConditions:[{condition:'حساسیت'}]}])};await service.ask({message:'جرم دندان RSL چیست؟'},{id:'alice'});const body=JSON.parse(f.mock.calls[0][1]!.body as string);expect(body.pet_context).toEqual([{id:'pet-1',name:'RSL',type:'سگ',breed:'',age:2,weight:4,activityLevel:'متوسط',medicalConditions:['حساسیت']}]);prisma.pet={findMany:jest.fn().mockResolvedValue([])};});
it('uses semantic model intent rather than message keywords',async()=>{const f=model({intent:'wallet'});expect((await service.ask({message:'چقدر اعتبار دارم؟'},{id:'alice'})).answer).toContain('17');expect(prisma.user.findUnique).toHaveBeenCalledWith({where:{id:'alice'},select:{walletBalance:true}});expect(JSON.parse(f.mock.calls[0][1]!.body as string)).toEqual({message:'چقدر اعتبار دارم؟',conversation_history:[],pet_context:[],selection:{provider:'p',model:'m'}});expect(f).toHaveBeenCalledTimes(1);});
it.each([{intent:'admin'},{intent:'wallet',userId:'bob'},{answer:'orders'},{intent:null},{}])('fails closed on invalid classifier %j',async body=>{model(body);await expect(service.ask({message:'سلام'},{id:'alice'})).rejects.toThrow(UNAVAILABLE);expect(prisma.user.findUnique).not.toHaveBeenCalled();expect(prisma.order.findMany).not.toHaveBeenCalled();expect(prisma.product.findMany).not.toHaveBeenCalled();});
it('classifier outage does not fall back to keyword routing',async()=>{jest.spyOn(global,'fetch').mockRejectedValue(new Error('secret'));await expect(service.ask({message:'کیف پول'},{id:'alice'})).rejects.toThrow(UNAVAILABLE);expect(prisma.user.findUnique).not.toHaveBeenCalled();});
+41
View File
@@ -0,0 +1,41 @@
# 9router admin consumption adapter
## Wiring (integration owner)
Import `RouterUsageModule` from `backend/src/router-usage/router-usage.module` into the root application's imports. This branch deliberately does not edit app.module.ts. Existing AuthModule/JWT strategy must be registered by the application. Route requires a JWT bearer user with admin/superadmin role; API-key authentication is deliberately not enabled for this sensitive endpoint.
Set backend-only `ROUTER_USAGE_CLI_TOKEN` using the existing router CLI auth token from the operator secret store. Optional `ROUTER_USAGE_BASE_URL` must be exactly `https://nr.parsaaghayi.ir` (an origin slash is accepted). Do not ship this token to the frontend. No environment/configuration was changed during implementation. No push/deploy performed; integration follows CI/CD and production needs separate Gate2.
## Exact API
`GET /admin/router-usage?period=7d` (plus the existing application global prefix, if any).
Allowed periods: `today`, `24h`, `7d`, `30d`, `60d`, `all`; default `7d`. Unknown query properties/custom from/to ranges and invalid periods return 400. Missing/invalid JWT is rejected by Passport; authenticated non-admin gets 403. Response is private/no-store.
Response fields:
- `source: "9router"`, `period`
- `status: "available" | "unavailable"`
- `reason: null | "not_configured" | "invalid_configuration" | "busy" | "upstream_unavailable"`
- `attribution: {scope:"9router_total", hermes:null, additive:false}`
- `freshness: {retrievedAt: ISO8601|null, sourceUpdatedAt:null, stale:null}`. Retrieval time is NOT a guarantee of provider freshness. The source exposes no authoritative updated-at for aggregates. No last-good cache is served.
- `capabilities: {errors:false, reasoningTokens:false, cacheWriteTokens:false, quota:false, customTimeRange:false}`
- `data: null | {totals, providers:[], models:[], accounts:[]}`
Every metrics object contains `requests`, `inputTokens`, `outputTokens`, `cacheReadTokens`, `cacheWriteTokens`, `reasoningTokens`, `errors` (number|null). Zero is retained only if upstream reported zero; absent/invalid counters remain null. Input/output/cache map to promptTokens/completionTokens/cachedTokens; cache-read is a subset of input, never add it again. Cache-write/reasoning/errors are always null because the stats contract does not expose these aggregates.
Provider rows: `{provider,...metrics}`. Model rows: `{model,provider,...metrics}`. Account rows: `{accountId,model,provider,...metrics,quota:{status:"unknown",remaining:null,resetAt:null,reason:"upstream_quota_get_mutates_credentials"}}`. Account rows are upstream account/model summaries, NOT unique account inventory; accounts without usage are absent. IDs are validated, nullable if unsafe; account names/emails are never returned. No raw upstream maps, logs, prompts, provider data or credentials are returned. Dimensions are different views of the same consumption: do NOT sum totals+models+accounts. Hermes attribution remains unknown; do NOT add Hermes telemetry to router totals.
## Deployed-source inspection and real probe
Read-only inspected running `9router` image `decolua/9router:vpn`: compiled `/app/.next/server/app/api/usage/stats/route.js`, `/app/.next/server/chunks/9100.js`, `/app/.next/server/middleware.js`, `/app/.next/server/chunks/7211.js`, providers routes and `/app/open-sse/services/usage.js`. No credential tables or router DB contents were dumped/modified.
Verified stats route accepts the periods above. `today` uses router-local midnight, `24h` rolling history; 7/30/60d use router-local daily buckets, `all` all retained daily aggregates. This is not arbitrary UTC timestamp filtering; retention/completeness is upstream-owned.
Authenticated internal GET probe returned HTTP 200, 5 provider summaries, 21 model summaries, 21 account/model summaries. Verified model fields: requests, promptTokens, completionTokens, cachedTokens, cost, rawModel, provider, lastUsed. Account fields additionally include connectionId/accountName. Only schema/counts printed; no keys or account values printed. Public HTTPS reverse proxy path was not live-authenticated, so its separate proxy authentication/network reachability remains an operator verification step.
Dashboard routes authenticate using `x-9r-cli-token` or valid `auth_token` session cookie. Normal inference API Bearer keys do NOT authenticate these dashboard routes. CLI token is NOT the contents of cli-secret: deployed middleware computes first 16 hex characters of SHA256(machine-id + "9r-cli-auth" + cli-secret). Probe derived it only inside the router process command and never emitted it; no new token or configuration was created.
**Security finding:** stats `byApiKey` map keys contain raw inference keys, even when row fields are masked. Adapter discards this map entirely and never logs response bodies/errors.
**Quota blocker:** `GET /api/usage/[connectionId]` calls refreshAndUpdateCredentials, including updateProviderConnection; OAuth refresh/retry can persist credentials. It is NOT read-only despite being GET. Therefore adapter does NOT call it. Provider quota handlers can return quotas (used/total/remaining/resetAt), messages or synthesized unlimited defaults; these cannot safely be treated as verified provider truth here. Quota reset grants exist in provider helpers but must never be consumed by this adapter. No safe deployed cache-only provider quota route was established. A separately reviewed router-side non-mutating, provenance/timestamp-bearing quota snapshot API is required before exposing live remaining/reset. Quota is unknown, never zero/unlimited fabricated. Connection inventory/status refresh is also not represented as quota truth.
## Bounds and verification
Only fixed-origin authenticated GET `/api/usage/stats` is invoked; redirect:error, abort after 5 seconds, streaming cap 1 MiB, <=2000 rows per dimension, <=4 concurrent requests per backend process. No retries or stale cache. Schema/transport/auth/rate-limit/oversize failures produce unavailable + null data without raw errors. No SQL, POST or token refresh.
Strict test-first slices observed missing contract, adapter, module failures before implementation. Disposable containers used existing backend image dependencies, read-only source mounts, network disabled and copied source into ephemeral /work; no host dependencies/build output or running containers changed. `npm run build` passed. Focused: 3 suites/24 tests passed. Full backend regression: 92 suites/781 tests passed (existing negative-path tests log expected payment/SSL errors). HTTP guard tests replace JWT authentication only and exercise real RolesGuard; deployed JWT strategy remains application-owned.
+5 -2
View File
@@ -7,7 +7,10 @@
"dev": "vite --port 3400 --host 127.0.0.1",
"build": "vite build",
"lint": "eslint .",
"preview": "vite preview"
"preview": "vite preview",
"test": "vitest run",
"test:watch": "vitest",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@tanstack/react-query": "^5.101.0",
@@ -42,4 +45,4 @@
"typescript-eslint": "^8.59.2",
"vitest": "^4.1.11"
}
}
}
@@ -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' },
],
@@ -157,6 +159,7 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side
{ icon: Package, label: 'لیست محصولات', path: '/products' },
{ icon: Star, label: 'نظرات و امتیازات', path: '/reviews' },
{ icon: FolderTree, label: 'دسته‌بندی‌های تخصصی', path: '/categories' },
{ icon: Activity, label: 'علائم بالینی و درمانی', path: '/symptoms' },
{ icon: Tag, label: 'کدهای تخفیف', path: '/coupons' },
{ icon: Sparkles, label: 'مشاور هوشمند بالینی', path: '/smart-advisor' },
{ icon: FileText, label: 'نسخه‌های دریافتی', path: '/prescriptions' },
@@ -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,147 @@
import React from 'react';
import { HelpCircle, Plus, Trash2 } from 'lucide-react';
import Button from '../ui/Button';
interface ProductFaqTabProps {
activeTab: string;
formData: any;
setFormData: React.Dispatch<React.SetStateAction<any>>;
}
export const ProductFaqTab: React.FC<ProductFaqTabProps> = ({
activeTab,
formData,
setFormData,
}) => {
return (
<div className={activeTab === 'faq' ? 'block space-y-5' : 'hidden'}>
{/* Top FAQ Controls */}
<div className="bg-white p-5 rounded-2xl border border-gray-200 shadow-sm space-y-4">
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 border-b pb-4">
<div>
<h4 className="text-sm font-black text-gray-800 flex items-center gap-2">
<HelpCircle className="w-4 h-4 text-purple-600" />
<span>بخش پرسش و پاسخ‌های متداول محصول (Product FAQs)</span>
</h4>
<p className="text-xs text-gray-500 mt-0.5">مدیریت آکاردئون پرسش‌های متداول در صفحه کالا و ثبت خودکار در سئوی گوگل (FAQPage Schema)</p>
</div>
<div className="flex items-center gap-2 shrink-0">
<label className="relative inline-flex items-center cursor-pointer">
<input
type="checkbox"
className="sr-only peer"
checked={formData.showFaqs}
onChange={(e) => setFormData({ ...formData, showFaqs: e.target.checked })}
/>
<div className="w-11 h-6 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-purple-600"></div>
</label>
<span className="text-xs font-bold text-gray-700">
{formData.showFaqs ? 'بخش FAQ فعال است' : 'بخش FAQ غیرفعال است'}
</span>
</div>
</div>
<div className="flex items-center justify-between flex-wrap gap-2 pt-1">
<Button
type="button"
variant="outline"
size="sm"
startIcon={Plus}
onClick={() => {
setFormData({
...formData,
faqs: [...(formData.faqs || []), { question: '', answer: '' }]
});
}}
className="border-purple-200 text-purple-700 hover:bg-purple-50 text-xs font-bold"
>
افزودن سوال جدید
</Button>
<button
type="button"
onClick={() => {
const defaultFaqs = [
{ question: `آیا مصرف ${formData.nameFa || 'این محصول'} برای توله‌ها یا بچه‌گربه‌ها مجاز است؟`, answer: 'بله، مطابق دوز اعلام‌شده روی قوطی و بر اساس وزن دقیق حیوان قابل مصرف است.' },
{ question: 'دوره درمان یا مصرف استاندارد چقدر است؟', answer: 'معمولاً دوره‌های درمانی بین ۴ الی ۶ هفته توصیه می‌شود تا اثربخشی فیزیولوژیک کامل حاصل شود.' },
{ question: 'آیا با سایر داروها یا غذاهای خشک تداخل دارد؟', answer: 'خیر، ترکیبات ارگانیک کنینا فاقد عوارض دارویی تداخلی با رژیم‌های غذایی خشک و مرطوب استاندارد هستند.' }
];
setFormData({
...formData,
faqs: [...(formData.faqs || []), ...defaultFaqs]
});
}}
className="text-xs text-purple-600 hover:text-purple-800 font-bold px-3 py-1.5 rounded-lg hover:bg-purple-50 transition-colors"
>
+ درج سوالات پیشنهادی هوشمند
</button>
</div>
</div>
{/* FAQs List */}
<div className="space-y-4">
{(!formData.faqs || formData.faqs.length === 0) ? (
<div className="bg-white p-8 rounded-2xl border border-dashed border-gray-200 text-center space-y-2">
<HelpCircle className="w-8 h-8 text-gray-300 mx-auto" />
<p className="text-xs font-bold text-gray-500">هیچ پرسش و پاسخی برای این محصول تعریف نشده است.</p>
<p className="text-[11px] text-gray-400">با کلیک روی دکمه «افزودن سوال جدید» یا «درج سوالات پیشنهادی»، متداول‌ترین پرسش‌های خریداران را ثبت کنید.</p>
</div>
) : (
formData.faqs.map((faq: any, index: number) => (
<div key={index} className="bg-white p-5 rounded-2xl border border-gray-200 shadow-xs space-y-3 relative group">
<div className="flex items-center justify-between gap-3 border-b pb-2">
<span className="text-xs font-black text-purple-700 bg-purple-50 px-2.5 py-1 rounded-lg">
پرسش شماره {index + 1}
</span>
<button
type="button"
onClick={() => {
const newFaqs = [...formData.faqs];
newFaqs.splice(index, 1);
setFormData({ ...formData, faqs: newFaqs });
}}
className="p-1.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors"
title="حذف این پرسش"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
<div className="space-y-1.5">
<label className="text-xs font-bold text-gray-700">عنوان پرسش *</label>
<input
type="text"
value={faq.question}
onChange={(e) => {
const newFaqs = [...formData.faqs];
newFaqs[index].question = e.target.value;
setFormData({ ...formData, faqs: newFaqs });
}}
placeholder="مثال: نحوه مصرف همراه با غذاست یا با معده خالی؟"
className="w-full px-4 py-2.5 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-xs font-bold"
dir="rtl"
/>
</div>
<div className="space-y-1.5">
<label className="text-xs font-bold text-gray-700">پاسخ تشریحی و تخصصی *</label>
<textarea
rows={2}
value={faq.answer}
onChange={(e) => {
const newFaqs = [...formData.faqs];
newFaqs[index].answer = e.target.value;
setFormData({ ...formData, faqs: newFaqs });
}}
placeholder="پاسخ دقیق، علمی و راهنمای مصرف را اینجا بنویسید..."
className="w-full px-4 py-2.5 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-xs font-medium leading-relaxed"
dir="rtl"
/>
</div>
</div>
))
)}
</div>
</div>
);
};
@@ -202,6 +202,23 @@ export default function MediaSelector({ isOpen, onClose, onSelect, multiple = fa
const files = Array.from(e.dataTransfer.files);
if (files.length === 0) return;
const ALLOWED_MIME_TYPES = ['image/jpeg', 'image/png', 'image/webp', 'image/svg+xml', 'image/gif', 'application/pdf'];
const MAX_FILE_SIZE = 15 * 1024 * 1024; // 15MB
const validFiles = files.filter(f => {
if (!ALLOWED_MIME_TYPES.includes(f.type) && !f.type.startsWith('image/')) {
toast.error(`فرمت فایل ${f.name} مجاز نمی‌باشد.`);
return false;
}
if (f.size > MAX_FILE_SIZE) {
toast.error(`حجم فایل ${f.name} بیش از حد مجاز (حداکثر ۱۵ مگابایت) است.`);
return false;
}
return true;
});
if (validFiles.length === 0) return;
setIsUploading(true);
let successCount = 0;
try {
@@ -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 } });
+19
View File
@@ -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>
);
}
@@ -43,11 +43,14 @@ describe('Dashboard Page Component', () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(api.get).mockResolvedValue({
data: {
success: true,
data: mockStats,
},
vi.mocked(api.get).mockImplementation((url: string) => {
if (url.includes('/admin/audit-logs')) {
return Promise.resolve({ data: { success: true, data: [] } } as any);
}
if (url.includes('/admin/approvals')) {
return Promise.resolve({ data: { success: true, meta: { pendingCount: 0 } } } as any);
}
return Promise.resolve({ data: { success: true, data: mockStats } } as any);
});
});
@@ -62,8 +65,8 @@ describe('Dashboard Page Component', () => {
it('renders dashboard headers and initial zero or placeholder stats', async () => {
renderDashboard();
expect(screen.getByText('داشبورد')).toBeInTheDocument();
expect(screen.getByText('خلاصه‌ای از وضعیت فروشگاه کنینا')).toBeInTheDocument();
expect(screen.getByText('داشبورد فرماندهی کنینا')).toBeInTheDocument();
expect(screen.getByText('خلاصه عملیات، وضعیت دیتابیس و نظارت بر وظایف خودکار سازمان')).toBeInTheDocument();
expect(screen.getByText('درآمد کل')).toBeInTheDocument();
expect(screen.getByText('سفارشات جدید')).toBeInTheDocument();
expect(screen.getByText('کاربران فعال')).toBeInTheDocument();
@@ -123,7 +126,12 @@ describe('Dashboard Page Component', () => {
it('falls back gracefully when API returns error', async () => {
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
vi.mocked(api.get).mockRejectedValueOnce(new Error('Network error'));
vi.mocked(api.get).mockImplementation((url: string) => {
if (url.includes('/admin/dashboard/stats')) {
return Promise.reject(new Error('Network error'));
}
return Promise.resolve({ data: { success: true, data: [] } } as any);
});
renderDashboard();
+6 -6
View File
@@ -73,7 +73,7 @@ export default function Dashboard() {
try {
const res = await api.get('/admin/audit-logs?limit=5');
if (res.data?.success) {
setRecentLogs(res.data.data);
setRecentLogs(Array.isArray(res.data.data) ? res.data.data : (Array.isArray(res.data.data?.logs) ? res.data.data.logs : []));
}
} catch (e) {
console.error('Failed to fetch audit logs widget', e);
@@ -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 (
@@ -217,7 +217,7 @@ export default function Dashboard() {
رکوردی در تاریخچه ثبت نشده است.
</div>
) : (
recentLogs.map((log) => (
(Array.isArray(recentLogs) ? recentLogs : []).map((log) => (
<div key={log.id} className="p-3 bg-gray-50 rounded-xl flex items-center justify-between text-xs hover:bg-purple-50/40 transition-colors">
<div className="flex items-center gap-2.5 overflow-hidden">
<span className="w-2 h-2 rounded-full bg-purple-500 shrink-0" />
@@ -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>
);
}
@@ -80,7 +80,7 @@ export default function MonitoringPage() {
timestamp: new Date().toLocaleTimeString('fa-IR'),
zibal: {
status: !health || health.status === 'OFFLINE' ? 'OFFLINE' : health.status === 'DEGRADED' || health.latencyMs > 1500 ? 'DEGRADED' : 'ONLINE',
latencyMs: health?.latencyMs || Math.floor(Math.random() * 80) + 120,
latencyMs: health?.latencyMs ?? 0,
merchantId: health?.activeMerchant || health?.merchantId || 'zibal-live-merchant',
todayVolumeTomans: txStats?.todayVolume ? Math.floor(Number(txStats.todayVolume)) : 0,
todayTxCount: txStats?.todayVerified || txStats?.verifiedCount || 0,
@@ -89,14 +89,14 @@ export default function MonitoringPage() {
melipayamak: {
status: smsCreditVal !== undefined && smsCreditVal !== null ? 'ONLINE' : 'OFFLINE',
credit: smsCreditVal !== undefined && smsCreditVal !== null ? `${Number(smsCreditVal).toLocaleString('fa-IR')} پیامک` : 'نامشخص',
latencyMs: Math.floor(Math.random() * 60) + 95,
latencyMs: 0,
todaySmsSent: 48,
patternActive: true,
},
post: {
status: 'ONLINE',
latencyMs: Math.floor(Math.random() * 110) + 140,
latencyMs: 0,
trackingActive: true,
},
system: {
@@ -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();
});
});
+25
View File
@@ -31,6 +31,7 @@ import api from '../services/api';
export interface OrderItem {
requiresRx?: boolean;
id?: string;
name?: string;
priceValue?: number;
@@ -758,6 +759,12 @@ export default function Orders() {
سفارش جدید
</span>
)}
{(order.orderItems || order.items || []).some(it => it.product?.requiresRx) && (
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-black bg-rose-600 text-white shadow-xs animate-pulse" title="نیازمند تماس تلفنی و تایید نسخه دامپزشک">
<span>Rx</span>
<span>هماهنگی نسخه</span>
</span>
)}
</div>
<div className="flex flex-wrap gap-1.5 mt-2 font-vazir" dir="rtl">
<span className={`text-[10px] font-bold font-vazir px-2 py-0.5 rounded-md border flex items-center gap-1 shadow-sm ${payInfo.color}`}>
@@ -911,6 +918,24 @@ export default function Orders() {
>
<div className="space-y-6">
{/* Rx Warning Notice for Admin */}
{(selectedOrder.orderItems || selectedOrder.items || []).some(it => it.requiresRx || it.product?.requiresRx) && (
<div className="bg-rose-50 border border-rose-200 rounded-2xl p-4 flex items-center justify-between gap-3 text-rose-900 font-vazir shadow-xs" dir="rtl">
<div className="flex items-center gap-2.5">
<span className="w-8 h-8 rounded-xl bg-rose-600 text-white flex items-center justify-center font-black text-xs shrink-0 shadow-sm">Rx</span>
<div>
<h4 className="text-xs font-black">این سفارش شامل داروی نیازمند نسخه و نظارت دامپزشکی است</h4>
<p className="text-[11px] text-rose-700 font-medium mt-0.5">ارسال سفارش تنها پس از تماس تلفنی کارشناس پشتیبانی و تایید نسخه معتبر انجام شود.</p>
</div>
</div>
<a
href={`tel:${selectedOrder.user?.mobile || selectedOrder.user?.phone || ''}`}
className="bg-rose-600 hover:bg-rose-700 text-white px-3.5 py-2 rounded-xl text-xs font-bold transition-all shadow-sm flex items-center gap-1.5 shrink-0"
>
<span>تماس با مشتری</span>
</a>
</div>
)}
{/* Status & Timing Banner */}
<div className="flex flex-wrap items-center justify-between gap-4 p-4 bg-purple-50/50 rounded-2xl border border-purple-100">
<div className="flex items-center gap-3">
+7 -146
View File
@@ -1,3 +1,4 @@
import { ProductFaqTab } from "../components/products/ProductFaqTab";
import {
Activity,
AlertTriangle,
@@ -2317,152 +2318,12 @@ export default function Products() {
</div>
{/* FAQ Tab */}
<div className={activeTab === 'faq' ? 'block space-y-5' : 'hidden'}>
{/* Top FAQ Controls */}
<div className="bg-white p-5 rounded-2xl border border-gray-200 shadow-sm space-y-4">
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 border-b pb-4">
<div>
<h4 className="text-sm font-black text-gray-800 flex items-center gap-2">
<HelpCircle className="w-4 h-4 text-purple-600" />
<span>بخش پرسش و پاسخ‌های متداول محصول (Product FAQs)</span>
</h4>
<p className="text-xs text-gray-500 mt-0.5">مدیریت آکاردئون پرسش‌های متداول در صفحه کالا و ثبت خودکار در سئوی گوگل (FAQPage Schema)</p>
</div>
<div className="flex items-center gap-2 shrink-0">
<label className="relative inline-flex items-center cursor-pointer">
<input
type="checkbox"
className="sr-only peer"
checked={formData.showFaqs}
onChange={(e) => setFormData({ ...formData, showFaqs: e.target.checked })}
/>
<div className="w-11 h-6 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-purple-600"></div>
</label>
<span className="text-xs font-bold text-gray-700">
{formData.showFaqs ? 'بخش FAQ فعال است' : 'بخش FAQ غیرفعال است'}
</span>
</div>
</div>
<div className="flex items-center justify-between flex-wrap gap-2 pt-1">
<Button
type="button"
variant="outline"
size="sm"
startIcon={Plus}
onClick={() => {
setFormData({
...formData,
faqs: [...(formData.faqs || []), { question: '', answer: '' }]
});
}}
className="border-purple-200 text-purple-700 hover:bg-purple-50 text-xs font-bold"
>
افزودن سوال جدید
</Button>
<button
type="button"
onClick={() => {
const name = formData.nameFa || 'این محصول';
setFormData({
...formData,
faqs: [
{
question: `آیا لیسیدن ${name} توسط حیوان خطرناک است؟`,
answer: `خیر، ترکیبات این محصول با استانداردهای دارویی آلمان فرموله شده و فاقد مواد نگهدارنده شیمیایی مضر است. لیسیدن محدود آن باعث مسمومیت نمی‌شود؛ اما جهت اثربخشی و جذب حداکثری، پیشنهاد می‌شود ۱۰ تا ۱۵ دقیقه حواس حیوان پرت شود.`
},
{
question: `مدت زمان ماندگاری و شرایط نگهداری ${name} چگونه است؟`,
answer: `این محصول در جای خشک، خنک (دمای زیر ۲۵ درجه سانتی‌گراد) و دور از تابش مستقیم نور خورشید نگهداری شود. مدت زمان مجاز مصرف پس از باز شدن درب (PAO) ${formData.paoMonths ? `${formData.paoMonths} ماه` : '۱۲ ماه'} می‌باشد.`
},
{
question: `آیا برای توله‌ها و حیوانات باردار یا شیرده قابل استفاده است؟`,
answer: `بله، با توجه به فرمولاسیون ۱۰۰٪ طبیعی و عدم وجود هورمون یا مواد شیمیایی سنتتیک، استفاده از این محصول برای تمامی رده‌های سنی و دوران حساس بارداری و شیردهی طبق دستورالعمل ایمن است.`
},
{
question: `در صورت استفاده همزمان با سایر داروها یا پمادها چه نکاتی باید رعایت شود؟`,
answer: `جهت جلوگیری از تداخل در جذب، توصیه می‌شود بین استفاده از این محصول و سایر داروها، اسپری‌ها یا مکمل‌های درمانی حداقل ۲۰ الی ۳۰ دقیقه فاصله زمانی رعایت شود.`
}
]
});
toast.success('سوالات متداول استاندارد کاتالوگ بارگذاری شدند');
}}
className="text-xs text-purple-600 hover:text-purple-800 font-bold flex items-center gap-1 hover:underline"
>
درج سوالات متداول پیشنهادی کاتالوگ Canina ⚡
</button>
</div>
</div>
{/* FAQ Items List */}
{formData.faqs && formData.faqs.length > 0 ? (
<div className="space-y-3">
{formData.faqs.map((faq, idx) => (
<div key={idx} className="bg-white p-4 rounded-2xl border border-gray-200 shadow-xs space-y-3 relative group">
<div className="flex items-center justify-between gap-2 border-b border-gray-100 pb-2">
<span className="text-xs font-black text-purple-700 bg-purple-50 px-2.5 py-0.5 rounded-full">
سوال {idx + 1}
</span>
<button
type="button"
onClick={() => {
const newFaqs = formData.faqs.filter((_, i) => i !== idx);
setFormData({ ...formData, faqs: newFaqs });
}}
className="text-red-400 hover:text-red-600 p-1 rounded-lg hover:bg-red-50 transition-colors"
title="حذف این سوال"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
<div className="space-y-1.5">
<label className="text-xs font-bold text-gray-700">متن پرسش:</label>
<input
type="text"
value={faq.question}
onChange={(e) => {
const updated = [...formData.faqs];
updated[idx].question = e.target.value;
setFormData({ ...formData, faqs: updated });
}}
placeholder="مثال: آیا لیسیدن این محصول خطرناک است؟"
className="w-full px-3 py-2 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-xs font-bold font-vazir"
/>
</div>
<div className="space-y-1.5">
<label className="text-xs font-bold text-gray-700">متن پاسخ علمی و کامل:</label>
<textarea
rows={3}
value={faq.answer}
onChange={(e) => {
const updated = [...formData.faqs];
updated[idx].answer = e.target.value;
setFormData({ ...formData, faqs: updated });
}}
placeholder="پاسخ کامل و علمی را وارد نمایید..."
className="w-full px-3 py-2 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-xs leading-relaxed font-vazir"
/>
</div>
</div>
))}
</div>
) : (
<div className="bg-white p-8 rounded-2xl border border-dashed border-gray-300 text-center space-y-3">
<div className="w-12 h-12 rounded-2xl bg-purple-50 text-purple-600 flex items-center justify-center mx-auto">
<HelpCircle className="w-6 h-6" />
</div>
<div className="space-y-1">
<h5 className="text-sm font-black text-gray-800">هیچ پرسش و پاسخی ثبت نشده است</h5>
<p className="text-xs text-gray-500 max-w-md mx-auto">
می‌توانید با کلیک بر روی «درج سوالات متداول پیشنهادی»، پرسش‌های متداول کاتالوگ دارویی را به صورت خودکار بارگذاری و سپس شخصی‌سازی نمایید.
</p>
</div>
</div>
)}
</div>
{/* FAQ Tab */}
<ProductFaqTab
activeTab={activeTab}
formData={formData}
setFormData={setFormData}
/>
{/* Pricing Tab */}
<div className={activeTab === 'pricing' ? 'block space-y-4' : 'hidden'}>
@@ -7,7 +7,10 @@ type Conversation = { id: string; createdAt: string; updatedAt: string; entryPat
const unwrap = (r: any) => r.data?.data ?? r.data;
export default function SupportChatAnalyticsPage() {
const [stats, setStats] = useState<Stats | null>(null); const [rows, setRows] = useState<Conversation[]>([]); const [error, setError] = useState(""); const [dates, setDates] = useState({ startDate: "", endDate: "" });
const load = async () => { try { setError(""); const params = Object.fromEntries(Object.entries(dates).filter(([, v]) => v)); const [s, c] = await Promise.all([api.get("/admin/support-chat/stats", { params }), api.get("/admin/support-chat/conversations", { params: { ...params, page: 1, limit: 50 } })]); setStats(unwrap(s)); setRows(unwrap(c).data || []); } catch { setError("گزارش پشتیبان بارگذاری نشد."); } };
const load = async () => { try { setError(""); const params = Object.fromEntries(Object.entries(dates).filter(([, v]) => v)); const [s, c] = await Promise.all([api.get("/admin/support-chat/stats", { params }), api.get("/admin/support-chat/conversations", { params: { ...params, page: 1, limit: 50 } })]); const statsData = unwrap(s);
const convData = unwrap(c);
setStats(statsData);
setRows(Array.isArray(convData) ? convData : (Array.isArray(convData?.data) ? convData.data : [])); } catch { setError("گزارش پشتیبان بارگذاری نشد."); } };
useEffect(() => { void load(); }, []);
return <div dir="rtl" className="space-y-6">
<div className="flex items-center justify-between"><div><h1 className="text-2xl font-black">تحلیل مشاورهٔ سایت</h1><p className="text-gray-500">تعداد استفاده، سؤال‌ها، پاسخ‌ها و موارد نیازمند پیگیری</p></div><Link className="rounded-lg border px-4 py-2" to="/settings/smart-chat/config">تنظیمات دستیار</Link><button className="rounded-lg bg-canina-blue px-4 py-2 text-white" onClick={() => void load()}>به‌روزرسانی</button></div>
@@ -0,0 +1,321 @@
import { Edit2, Plus, Search, Trash2, Activity, Tag, Sparkles } from 'lucide-react';
import { useCallback, useEffect, useState } from 'react';
import { toast } from 'react-hot-toast';
import Button from '../components/ui/Button';
import ConfirmModal from '../components/ui/ConfirmModal';
import Modal from '../components/ui/Modal';
import Pagination from '../components/ui/Pagination';
import Spinner from '../components/ui/Spinner';
import api from '../services/api';
import { useSearchParams } from 'react-router-dom';
export interface Symptom {
id: string;
name: string;
slug: string;
description?: string;
metaTitle?: string;
metaDescription?: string;
keywords?: string;
productsCount?: number;
createdAt?: string;
}
export default function SymptomsPage() {
const [searchParams, setSearchParams] = useSearchParams();
const [symptoms, setSymptoms] = useState<Symptom[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [search, setSearch] = useState(() => searchParams.get('search') || '');
const [page, setPage] = useState(() => Number(searchParams.get('page')) || 1);
const [totalPages, setTotalPages] = useState(1);
const limit = 15;
const [isModalOpen, setIsModalOpen] = useState(false);
const [editingSymptom, setEditingSymptom] = useState<Symptom | null>(null);
const [deleteTargetId, setDeleteTargetId] = useState<string | null>(null);
const [isSubmitting, setIsSubmitting] = useState(false);
const [formData, setFormData] = useState({
name: '',
slug: '',
description: '',
metaTitle: '',
metaDescription: '',
keywords: ''
});
const openModal = (symptom: Symptom | null = null) => {
if (symptom) {
setEditingSymptom(symptom);
setFormData({
name: symptom.name,
slug: symptom.slug,
description: symptom.description || '',
metaTitle: symptom.metaTitle || '',
metaDescription: symptom.metaDescription || '',
keywords: symptom.keywords || ''
});
} else {
setEditingSymptom(null);
setFormData({
name: '',
slug: '',
description: '',
metaTitle: '',
metaDescription: '',
keywords: ''
});
}
setIsModalOpen(true);
};
const closeModal = () => {
setIsModalOpen(false);
};
const fetchSymptoms = useCallback(async () => {
try {
setIsLoading(true);
const res = await api.get('/admin/symptoms', { params: { page, limit, search } });
if (res.data?.data) {
setSymptoms(res.data.data);
setTotalPages(res.data.meta?.lastPage || 1);
}
} catch {
toast.error('خطا در دریافت لیست علائم');
} finally {
setIsLoading(false);
}
}, [page, search]);
useEffect(() => {
fetchSymptoms();
}, [fetchSymptoms]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!formData.name.trim()) {
toast.error('نام علامت الزامی است');
return;
}
try {
setIsSubmitting(true);
if (editingSymptom) {
await api.put(`/admin/symptoms/${editingSymptom.id}`, formData);
toast.success('علامت با موفقیت ویرایش و در تمامی محصولات همگام شد');
} else {
await api.post('/admin/symptoms', formData);
toast.success('علامت درمانی جدید با موفقیت ایجاد شد');
}
closeModal();
fetchSymptoms();
} catch {
toast.error('خطا در ذخیره اطلاعات علامت');
} finally {
setIsSubmitting(false);
}
};
const handleDelete = async () => {
if (!deleteTargetId) return;
try {
await api.delete(`/admin/symptoms/${deleteTargetId}`);
toast.success('علامت با موفقیت حذف شد');
setDeleteTargetId(null);
fetchSymptoms();
} catch {
toast.error('خطا در حذف علامت');
}
};
return (
<div className="space-y-6 font-vazir" dir="rtl">
{/* Header */}
<div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 bg-white p-6 rounded-3xl border border-gray-100 shadow-sm">
<div>
<div className="flex items-center gap-2.5">
<span className="w-10 h-10 rounded-2xl bg-canina-blue/10 text-canina-blue flex items-center justify-center">
<Activity className="w-5 h-5 text-purple-600" />
</span>
<h1 className="text-xl font-black text-gray-900">مدیریت علائم بالینی و درمانی</h1>
</div>
<p className="text-xs text-gray-500 font-bold mt-1">
تعریف و ویرایش علائم، بهینه‌سازی متادیتاهای سئو و همگام‌سازی یکپارچه با محصولات کاتالوگ
</p>
</div>
<Button onClick={() => openModal()} className="bg-purple-600 hover:bg-purple-700 text-white rounded-2xl px-5 py-3 flex items-center gap-2 font-bold text-xs shadow-md shadow-purple-600/20">
<Plus className="w-4 h-4" />
<span>افزودن علامت جدید</span>
</Button>
</div>
{/* Filter & Search */}
<div className="bg-white p-4 rounded-3xl border border-gray-100 shadow-sm flex items-center gap-3">
<div className="relative flex-1">
<Search className="w-4 h-4 text-gray-400 absolute right-3 top-1/2 -translate-y-1/2" />
<input
type="text"
placeholder="جستجوی علامت بالینی بر اساس نام یا اسلاگ..."
value={search}
onChange={(e) => {
setSearch(e.target.value);
setPage(1);
}}
className="w-full bg-gray-50 border border-gray-200 rounded-2xl py-2.5 pr-10 pl-4 text-xs focus:outline-none focus:ring-2 focus:ring-purple-500/20"
/>
</div>
</div>
{/* Table */}
<div className="bg-white rounded-3xl border border-gray-100 shadow-sm overflow-hidden">
{isLoading ? (
<div className="py-20 flex justify-center">
<Spinner />
</div>
) : symptoms.length === 0 ? (
<div className="py-20 text-center text-gray-400 font-bold text-sm">
هیچ علامت بالینی یافت نشد.
</div>
) : (
<div className="overflow-x-auto">
<table className="w-full text-right text-xs">
<thead className="bg-gray-50/75 border-b border-gray-100 text-gray-500 font-black uppercase">
<tr>
<th className="px-6 py-4">نام علامت بالینی</th>
<th className="px-6 py-4">اسلاگ URL</th>
<th className="px-6 py-4">محصولات متصل</th>
<th className="px-6 py-4">سئو متاتایتل</th>
<th className="px-6 py-4 text-left">عملیات</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100">
{symptoms.map((symptom) => (
<tr key={symptom.id} className="hover:bg-purple-50/20 transition-colors">
<td className="px-6 py-4 font-black text-gray-900 flex items-center gap-2">
<Tag className="w-3.5 h-3.5 text-purple-600" />
<span>{symptom.name}</span>
</td>
<td className="px-6 py-4 font-mono text-gray-500 dir-ltr text-right">
{symptom.slug}
</td>
<td className="px-6 py-4">
<span className="px-2.5 py-1 bg-purple-50 text-purple-700 font-black rounded-lg border border-purple-100">
{symptom.productsCount || 0} محصول
</span>
</td>
<td className="px-6 py-4 text-gray-600 max-w-xs truncate" title={symptom.metaTitle}>
{symptom.metaTitle || '—'}
</td>
<td className="px-6 py-4 text-left space-x-2 space-x-reverse">
<button
onClick={() => openModal(symptom)}
className="p-2 text-blue-600 hover:bg-blue-50 rounded-xl transition-colors"
title="ویرایش و سئو"
>
<Edit2 className="w-4 h-4" />
</button>
<button
onClick={() => setDeleteTargetId(symptom.id)}
className="p-2 text-red-600 hover:bg-red-50 rounded-xl transition-colors"
title="حذف"
>
<Trash2 className="w-4 h-4" />
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
<div className="p-4 border-t border-gray-100 flex justify-center">
<Pagination currentPage={page} totalPages={totalPages} onPageChange={(p) => setPage(p)} />
</div>
</div>
{/* Modal CRUD */}
<Modal isOpen={isModalOpen} onClose={closeModal} title={editingSymptom ? 'ویرایش علامت و سئو' : 'تعریف علامت جدید'}>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label className="block text-xs font-bold text-gray-700 mb-1">نام علامت درمانی (فارسی) *</label>
<input
type="text"
required
value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
className="w-full bg-gray-50 border border-gray-200 rounded-xl p-3 text-xs focus:outline-none focus:ring-2 focus:ring-purple-500/20"
placeholder="مثلاً: پوکی استخوان یا کم‌خونی"
/>
</div>
<div>
<label className="block text-xs font-bold text-gray-700 mb-1">اسلاگ URL و انگلیسی</label>
<input
type="text"
value={formData.slug}
onChange={(e) => setFormData({ ...formData, slug: e.target.value })}
className="w-full bg-gray-50 border border-gray-200 rounded-xl p-3 text-xs dir-ltr focus:outline-none focus:ring-2 focus:ring-purple-500/20"
placeholder="anemia یا osteoporosis"
/>
</div>
<div>
<label className="block text-xs font-bold text-gray-700 mb-1">توضیحات تشخیصی و بالینی</label>
<textarea
rows={3}
value={formData.description}
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
className="w-full bg-gray-50 border border-gray-200 rounded-xl p-3 text-xs focus:outline-none focus:ring-2 focus:ring-purple-500/20"
placeholder="توضیحات بالینی و پروتکل‌های مکمل‌های درمانی..."
/>
</div>
<div className="pt-2 border-t border-gray-100 space-y-3">
<div className="flex items-center gap-1.5 text-xs font-black text-purple-700">
<Sparkles className="w-3.5 h-3.5" />
<span>تنظیمات پیشرفته سئو (SEO Meta)</span>
</div>
<div>
<label className="block text-[11px] font-bold text-gray-600 mb-1">Meta Title</label>
<input
type="text"
value={formData.metaTitle}
onChange={(e) => setFormData({ ...formData, metaTitle: e.target.value })}
className="w-full bg-gray-50 border border-gray-200 rounded-xl p-2.5 text-xs"
placeholder="عنوان سئو در نتایج گوگل..."
/>
</div>
<div>
<label className="block text-[11px] font-bold text-gray-600 mb-1">Meta Description</label>
<textarea
rows={2}
value={formData.metaDescription}
onChange={(e) => setFormData({ ...formData, metaDescription: e.target.value })}
className="w-full bg-gray-50 border border-gray-200 rounded-xl p-2.5 text-xs"
placeholder="توضیحات متای صفحه سئو..."
/>
</div>
</div>
<div className="flex justify-end gap-2 pt-4">
<Button type="button" variant="outline" onClick={closeModal}>انصراف</Button>
<Button type="submit" disabled={isSubmitting} className="bg-purple-600 hover:bg-purple-700 text-white">
{isSubmitting ? 'در حال ثبت...' : (editingSymptom ? 'بروزرسانی یکپارچه' : 'ثبت علامت')}
</Button>
</div>
</form>
</Modal>
{/* Delete Confirmation */}
<ConfirmModal
isOpen={!!deleteTargetId}
onClose={() => setDeleteTargetId(null)}
onConfirm={handleDelete}
title="حذف علامت بالینی"
description="با حذف این علامت، ارتباط آن از تمام محصولات کاتالوگ نیز به طور خودکار حذف خواهد شد. آیا مطمئن هستید؟"
/>
</div>
);
}
@@ -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>
))}
@@ -17,6 +17,8 @@ const SupportChatAnalyticsPage = lazyWithRetry(() => import('../pages/SupportCha
const Settings = lazyWithRetry(() => import('../pages/Settings'));
const Reports = lazyWithRetry(() => import('../pages/Reports'));
const Categories = lazyWithRetry(() => import('../pages/Categories'));
const SymptomsPage = lazyWithRetry(() => import('../pages/SymptomsPage'));
const Blogs = lazyWithRetry(() => import('../pages/Blogs'));
const Wiki = lazyWithRetry(() => import('../pages/Wiki'));
const Pets = lazyWithRetry(() => import('../pages/Pets'));
@@ -48,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;
@@ -93,6 +97,8 @@ export const router = createBrowserRouter([
{ path: 'settings/system', element: <SystemSettingsPage /> },
{ path: 'reports/*', element: <Reports /> },
{ path: 'categories/*', element: <Categories /> },
{ path: 'symptoms/*', element: <SymptomsPage /> },
{ path: 'blogs/*', element: <Blogs /> },
{ path: 'wiki/*', element: <Wiki /> },
{ path: 'videos/*', element: <Videos /> },
@@ -115,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 /> },
],
},
],
+18 -5
View File
@@ -87,11 +87,24 @@ api.interceptors.response.use(
isRefreshing = true;
try {
const refreshResponse = await axios.post<ApiResponse<AuthResponseData>>(
`${baseURL}/auth/refresh`,
{},
{ withCredentials: true }
);
let refreshResponse;
try {
refreshResponse = await axios.post<ApiResponse<AuthResponseData>>(
`${baseURL}/auth/refresh`,
{},
{
withCredentials: true,
headers: currentToken ? { Authorization: `Bearer ${currentToken}` } : {}
}
);
} catch {
// If bearer-based refresh fails (e.g. access token fully expired), try cookie-based /auth/refresh-token
refreshResponse = await axios.post<ApiResponse<AuthResponseData>>(
`${baseURL}/auth/refresh-token`,
{},
{ withCredentials: true }
);
}
if (refreshResponse.data?.success && refreshResponse.data.data?.accessToken) {
const newToken = refreshResponse.data.data.accessToken;
+18 -8
View File
@@ -38,7 +38,8 @@ export default function ClientLayout({ children }: { children: React.ReactNode }
const setLoginModalOpen = useUIStore((state) => state.setLoginModalOpen);
const setB2BPortalOpen = useUIStore((state) => state.setB2BPortalOpen);
const clearAdvisorData = useUIStore((state) => state.clearAdvisorData);
const [isPrescriptionModalOpen, setIsPrescriptionModalOpen] = useState(false);
const isPrescriptionModalOpen = useUIStore((state) => state.isPrescriptionModalOpen);
const setPrescriptionModalOpen = useUIStore((state) => state.setPrescriptionModalOpen);
const pathname = usePathname();
const router = useRouter();
@@ -123,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')));
@@ -175,7 +189,7 @@ export default function ClientLayout({ children }: { children: React.ReactNode }
onSearch={handleSearch}
onB2BOpen={() => setB2BPortalOpen(true)}
/>
<main className={`min-h-screen ${pathname === '/catalog' ? 'bg-slate-950' : ''}`}>
<main id="main-content" className={`min-h-screen ${pathname === '/catalog' ? 'bg-slate-950' : ''}`}>
{children}
</main>
{!isUtilityRoute && <Footer onNavigate={handleNavigate} onShopNavigate={navigateToShop} onB2BOpen={() => setB2BPortalOpen(true)} />}
@@ -230,15 +244,11 @@ export default function ClientLayout({ children }: { children: React.ReactNode }
/>}
<PrescriptionUploadModal
isOpen={isPrescriptionModalOpen}
onClose={() => setIsPrescriptionModalOpen(false)}
onClose={() => setPrescriptionModalOpen(false)}
/>
<MobileBottomNav
onPrescriptionOpen={() => {
if (!isLoggedIn) {
setAuthModalOpen(true);
} else {
setIsPrescriptionModalOpen(true);
}
setPrescriptionModalOpen(true);
}}
/>
<Toaster position="top-center" expand={true} richColors closeButton />
@@ -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',
+14 -16
View File
@@ -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("کنینا");
});
});
+8 -3
View File
@@ -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>
+3 -1
View File
@@ -10,7 +10,9 @@ export default function ErrorBoundary({
reset: () => void;
}) {
useEffect(() => {
console.error("Global Application Error:", error);
if (process.env.NODE_ENV === "development") {
console.error("Global Application Error:", error?.message || "Unknown error");
}
}, [error]);
return <ServerErrorPage onRetry={reset} />;
+18
View File
@@ -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;
}
+6
View File
@@ -178,6 +178,12 @@ export default async function RootLayout({
<link rel="dns-prefetch" href="https://scripts.clarity.ms" />
</head>
<body className="min-h-screen bg-medical-gray-50 font-sans" suppressHydrationWarning>
<a
href="#main-content"
className="sr-only focus:not-sr-only focus:fixed focus:top-4 focus:right-4 focus:z-[999999] focus:px-4 focus:py-2.5 focus:bg-canina-blue focus:text-white focus:font-black focus:rounded-xl focus:shadow-2xl focus:outline-none focus:ring-2 focus:ring-white font-vazir text-sm transition-all"
>
پرش به محتوای اصلی
</a>
{/* Google Tag Manager (noscript fallback) */}
{isGtmEnabled && (
<noscript>
@@ -0,0 +1,284 @@
"use client";
import React, { useState } from "react";
import {
Stethoscope,
Upload,
CheckCircle2,
ShieldCheck,
FileText,
Clock,
Send,
Phone,
Sparkles,
AlertCircle
} from "lucide-react";
import { toast } from "sonner";
import api from "../../lib/services/api";
export default function PrescriptionPageClient() {
const [file, setFile] = useState<File | null>(null);
const [phone, setPhone] = useState("");
const [petName, setPetName] = useState("");
const [petType, setPetType] = useState<"سگ" | "گربه">("سگ");
const [notes, setNotes] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false);
const [isSuccess, setIsSuccess] = useState(false);
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
if (e.target.files && e.target.files[0]) {
setFile(e.target.files[0]);
}
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!file) {
toast.error("لطفاً تصویر یا فایل PDF نسخه پزشکی را بارگذاری کنید.");
return;
}
const cleanPhone = phone.trim();
if (!/^09\d{9}$/.test(cleanPhone)) {
toast.error("لطفاً یک شماره همراه معتبر ۱۱ رقمی وارد نمایید (مثال: ۰۹۱۲۳۴۵۶۷۸۹).");
return;
}
setIsSubmitting(true);
try {
// 1. Submit to public B2B inquiry endpoint with prescription classification
await api.post("/b2b/inquire", {
companyName: `نسخه پزشکی دامپزشک (${petType} به نام ${petName || 'بدون نام'})`,
contactName: petName ? `سرپرست: ${petName}` : "مراجعه‌کننده آنلاین",
email: `rx-${Date.now()}@canina.ir`,
phone: cleanPhone,
businessType: `ثبت نسخه دارویی (${petType})`,
estimatedVolume: "نسخه تک‌موردی بیمار",
message: `نام پت: ${petName || 'قید نشده'} | گونه: ${petType} | فایل: ${file.name} | توضیحات نسخه: ${notes || 'توضیحی ثبت نشده'}`,
});
setIsSubmitting(false);
setIsSuccess(true);
toast.success("نسخه پزشکی شما با موفقیت ثبت شد. دامپزشک کشیک کنینا به زودی با شما تماس خواهد گرفت.");
} catch {
setIsSubmitting(false);
toast.error("خطایی در ثبت اطلاعات نسخه رخ داد. لطفاً مجدداً تلاش کنید.");
}
};
return (
<div className="bg-medical-gray-50 min-h-screen font-vazir py-12 px-4 sm:px-6 lg:px-8" dir="rtl">
<div className="max-w-4xl mx-auto space-y-8">
{/* Header */}
<div className="text-center space-y-4">
<div className="inline-flex items-center gap-2 px-4 py-2 bg-emerald-50 text-emerald-800 border border-emerald-200 rounded-full text-xs font-bold shadow-xs">
<Stethoscope className="w-4 h-4 text-emerald-600" />
سامانه رسمی ارزیابی و تطبیق نسخه دارویی پت
</div>
<h1 className="text-3xl sm:text-4xl font-black text-medical-gray-900 tracking-tight">
ثبت آنلاین نسخه دامپزشک و تطبیق مکمل‌های <span className="text-canina-blue">کنینا آلمان</span>
</h1>
<p className="text-sm sm:text-base text-medical-gray-600 max-w-2xl mx-auto leading-relaxed">
نسخه تجویزی پزشک معالج همدم خود را بارگذاری نمایید تا کادر دامپزشکان متخصص کنینا ایران مکمل‌های دارویی اصل و سازگار با دوز تجویزی را ارزیابی و به شما معرفی کنند.
</p>
</div>
{/* Benefits bar */}
<div className="grid sm:grid-cols-3 gap-4">
<div className="bg-white p-4 rounded-2xl border border-medical-gray-200 shadow-xs flex items-center gap-3">
<div className="w-10 h-10 rounded-xl bg-emerald-50 text-emerald-600 flex items-center justify-center shrink-0">
<ShieldCheck className="w-5 h-5" />
</div>
<div>
<h4 className="text-xs font-black text-medical-gray-900">تطبیق دقیق دارویی</h4>
<p className="text-[11px] text-medical-gray-500">معادل‌سازی برندهای آلمانی و دوز</p>
</div>
</div>
<div className="bg-white p-4 rounded-2xl border border-medical-gray-200 shadow-xs flex items-center gap-3">
<div className="w-10 h-10 rounded-xl bg-blue-50 text-canina-blue flex items-center justify-center shrink-0">
<Clock className="w-5 h-5" />
</div>
<div>
<h4 className="text-xs font-black text-medical-gray-900">پاسخگویی سریع</h4>
<p className="text-[11px] text-medical-gray-500">بررسی توسط دامپزشک زیر ۲ ساعت</p>
</div>
</div>
<div className="bg-white p-4 rounded-2xl border border-medical-gray-200 shadow-xs flex items-center gap-3">
<div className="w-10 h-10 rounded-xl bg-amber-50 text-amber-600 flex items-center justify-center shrink-0">
<Sparkles className="w-5 h-5" />
</div>
<div>
<h4 className="text-xs font-black text-medical-gray-900">مشاوره تغذیه رایگان</h4>
<p className="text-[11px] text-medical-gray-500">همراه با راهنمای رژیم و دوز مصرف</p>
</div>
</div>
</div>
{/* Form Card */}
<div className="bg-white rounded-3xl border border-medical-gray-200 shadow-xl overflow-hidden p-6 sm:p-10">
{isSuccess ? (
<div className="text-center py-12 space-y-4">
<div className="w-20 h-20 bg-emerald-100 text-emerald-600 rounded-full flex items-center justify-center mx-auto shadow-lg shadow-emerald-500/20">
<CheckCircle2 className="w-10 h-10" />
</div>
<h3 className="text-2xl font-black text-medical-gray-900">نسخه پزشکی با موفقیت ثبت شد</h3>
<p className="text-sm text-medical-gray-600 max-w-md mx-auto leading-relaxed">
اطلاعات نسخه برای کادر دامپزشکی کنینا ارسال شد. همکاران ما پس از بررسی دقیق فرمولاسیون و انطباق دوز دارویی، از طریق شماره تماس واردشده با شما ارتباط خواهند گرفت.
</p>
<button
type="button"
onClick={() => {
setFile(null);
setNotes("");
setPetName("");
setIsSuccess(false);
}}
className="inline-flex items-center gap-2 bg-canina-blue text-white px-6 py-3 rounded-xl font-bold text-xs shadow-md hover:bg-canina-blue/90 transition-all cursor-pointer"
>
ثبت نسخه جدید دیگر
</button>
</div>
) : (
<form onSubmit={handleSubmit} className="space-y-6">
{/* Pet Info */}
<div className="grid sm:grid-cols-2 gap-4">
<div>
<label className="block text-xs font-bold text-medical-gray-700 mb-2">
گونه حیوان خانگی <span className="text-red-500">*</span>
</label>
<div className="grid grid-cols-2 gap-3">
<button
type="button"
onClick={() => setPetType("سگ")}
className={`p-3 rounded-2xl border text-xs font-black flex items-center justify-center gap-2 transition-all cursor-pointer ${
petType === "سگ"
? "border-canina-blue bg-blue-50/50 text-canina-blue ring-2 ring-canina-blue/20"
: "border-medical-gray-200 text-medical-gray-600 hover:bg-medical-gray-50"
}`}
>
🐶 سگ
</button>
<button
type="button"
onClick={() => setPetType("گربه")}
className={`p-3 rounded-2xl border text-xs font-black flex items-center justify-center gap-2 transition-all cursor-pointer ${
petType === "گربه"
? "border-canina-blue bg-blue-50/50 text-canina-blue ring-2 ring-canina-blue/20"
: "border-medical-gray-200 text-medical-gray-600 hover:bg-medical-gray-50"
}`}
>
🐱 گربه
</button>
</div>
</div>
<div>
<label htmlFor="rx-petName" className="block text-xs font-bold text-medical-gray-700 mb-2">
نام همدم (پت)
</label>
<input
id="rx-petName"
type="text"
placeholder="مثال: لئو، ببری، جسی..."
value={petName}
onChange={(e) => setPetName(e.target.value)}
className="w-full bg-medical-gray-50 border border-medical-gray-200 rounded-2xl px-4 py-3 text-sm text-medical-gray-900 focus:bg-white focus:border-canina-blue focus:ring-4 focus:ring-canina-blue/10 outline-none transition-all"
/>
</div>
</div>
{/* Phone */}
<div>
<label htmlFor="rx-phone" className="block text-xs font-bold text-medical-gray-700 mb-2">
شماره تماس همراه (جهت دریافت نتیجه ارزیابی) <span className="text-red-500">*</span>
</label>
<div className="relative">
<input
id="rx-phone"
type="tel"
required
placeholder="۰۹۱۲۳۴۵۶۷۸۹"
value={phone}
onChange={(e) => setPhone(e.target.value)}
className="w-full bg-medical-gray-50 border border-medical-gray-200 rounded-2xl px-4 py-3 pl-10 text-sm text-medical-gray-900 focus:bg-white focus:border-canina-blue focus:ring-4 focus:ring-canina-blue/10 outline-none transition-all dir-ltr text-right"
/>
<Phone className="w-4 h-4 text-medical-gray-400 absolute left-3 top-1/2 -translate-y-1/2" />
</div>
</div>
{/* File Upload Zone */}
<div>
<label className="block text-xs font-bold text-medical-gray-700 mb-2">
بارگذاری تصویر یا فایل PDF نسخه <span className="text-red-500">*</span>
</label>
<div className="relative border-2 border-dashed border-medical-gray-300 hover:border-canina-blue rounded-3xl p-6 sm:p-8 text-center transition-all bg-medical-gray-50/50 hover:bg-blue-50/20">
<input
id="rx-file-input"
type="file"
accept="image/jpeg,image/png,image/webp,application/pdf"
required
onChange={handleFileChange}
className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
/>
<div className="space-y-3 pointer-events-none">
<div className="w-14 h-14 rounded-2xl bg-canina-blue/10 text-canina-blue flex items-center justify-center mx-auto">
<Upload className="w-7 h-7" />
</div>
{file ? (
<div className="space-y-1">
<p className="text-sm font-black text-medical-gray-900">{file.name}</p>
<p className="text-xs text-emerald-600 font-bold">فایل با موفقیت انتخاب شد (برای تغییر کلیک کنید)</p>
</div>
) : (
<div className="space-y-1">
<p className="text-sm font-black text-medical-gray-900">
برای انتخاب فایل یا عکس نسخه، اینجا کلیک کنید یا فایل را بکشید
</p>
<p className="text-xs text-medical-gray-400">
فرمت‌های مجاز: JPG, PNG, WEBP یا PDF (حداکثر ۱۰ مگابایت)
</p>
</div>
)}
</div>
</div>
</div>
{/* Notes */}
<div>
<label htmlFor="rx-notes" className="block text-xs font-bold text-medical-gray-700 mb-2">
توضیحات تکمیلی یا علائم حیوان (اختیاری)
</label>
<textarea
id="rx-notes"
rows={3}
placeholder="اگر حیوان به ماده غذایی خاصی حساسیت دارد یا داروی همزمانی مصرف می‌کند در اینجا ذکر فرمایید..."
value={notes}
onChange={(e) => setNotes(e.target.value)}
className="w-full bg-medical-gray-50 border border-medical-gray-200 rounded-2xl px-4 py-3 text-sm text-medical-gray-900 focus:bg-white focus:border-canina-blue focus:ring-4 focus:ring-canina-blue/10 outline-none transition-all"
/>
</div>
{/* Submit Button */}
<button
type="submit"
disabled={isSubmitting}
className="w-full bg-canina-blue hover:bg-canina-blue/90 text-white font-black text-base py-4 rounded-2xl shadow-xl shadow-canina-blue/20 transition-all flex items-center justify-center gap-2 cursor-pointer disabled:opacity-50"
>
{isSubmitting ? (
<span>در حال ارسال نسخه و ثبت درخواست...</span>
) : (
<>
<Send className="w-5 h-5" />
<span>ارسال و ثبت نسخه جهت ارزیابی دامپزشک</span>
</>
)}
</button>
</form>
)}
</div>
</div>
</div>
);
}
@@ -0,0 +1,16 @@
import React from "react";
import type { Metadata } from "next";
import PrescriptionPageClient from "./PrescriptionPageClient";
import { getPageMetadata } from "../../lib/seo";
export async function generateMetadata(): Promise<Metadata> {
return getPageMetadata('prescriptions', {
canonicalPath: '/prescriptions',
fallbackTitle: 'ثبت و ارزیابی نسخه دامپزشک | مشاوره تخصصی دارویی کنینا ایران',
fallbackDesc: 'سامانه آنلاین آپلود و تحلیل نسخه دامپزشک جهت تطبیق با مکمل‌های دارویی اصل Canina Pharma آلمان با نظارت کادر مجرب دامپزشکان.',
});
}
export default function PrescriptionPage() {
return <PrescriptionPageClient />;
}
@@ -0,0 +1,61 @@
import React from "react";
import { describe, it, expect, vi } from "vitest";
import { render, fireEvent, waitFor } from "@testing-library/react";
const mockPost = vi.fn().mockResolvedValue({ data: { success: true } });
vi.mock("axios", () => {
const mAxios = {
post: vi.fn(() => Promise.resolve({ data: { success: true } })),
get: vi.fn(() => Promise.resolve({ data: { success: true } })),
interceptors: {
request: { use: vi.fn(), eject: vi.fn() },
response: { use: vi.fn(), eject: vi.fn() },
},
create: () => mAxios,
};
return { default: mAxios };
});
vi.mock("sonner", () => ({
toast: {
success: vi.fn(),
error: vi.fn(),
},
}));
import api from "../../lib/services/api";
import PrescriptionPageClient from "./PrescriptionPageClient";
describe("PrescriptionPageClient Suite (B2B-03)", () => {
it("renders online prescription portal and submits without requiring login", async () => {
const { container } = render(<PrescriptionPageClient />);
const phoneInput = container.querySelector("#rx-phone") as HTMLInputElement;
const petNameInput = container.querySelector("#rx-petName") as HTMLInputElement;
const fileInput = container.querySelector("#rx-file-input") as HTMLInputElement;
const form = container.querySelector("form") as HTMLFormElement;
expect(phoneInput).not.toBeNull();
expect(fileInput).not.toBeNull();
expect(form).not.toBeNull();
// Create fake file
const fakeFile = new File(["dummy content"], "prescription.jpg", { type: "image/jpeg" });
fireEvent.change(phoneInput, { target: { value: "09121114455" } });
fireEvent.change(petNameInput, { target: { value: "لئو" } });
fireEvent.change(fileInput, { target: { files: [fakeFile] } });
fireEvent.submit(form);
await waitFor(() => {
expect(api.post).toHaveBeenCalledWith(
"/b2b/inquire",
expect.objectContaining({
phone: "09121114455",
companyName: expect.stringContaining("لئو"),
})
);
});
});
});
+1
View File
@@ -7,6 +7,7 @@ export async function generateMetadata(): Promise<Metadata> {
canonicalPath: '/search',
fallbackTitle: 'جستجوی هوشمند مکمل‌ها و دانشنامه سلامت',
fallbackDesc: 'جستجوی سریع در کاتالوگ محصولات، بیماری‌ها، علائم بالینی و مقالات سلامت کنینا ایران.',
noIndex: true,
});
}
@@ -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 || 'مقاله وبلاگ تخصصی کنینا';
+2 -2
View File
@@ -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 () => {
+4 -8
View File
@@ -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> {
@@ -30,12 +31,7 @@ export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
changeFrequency: 'weekly',
priority: 0.8,
},
{
url: `${baseUrl}/search`,
lastModified: new Date(),
changeFrequency: 'weekly',
priority: 0.5,
},
{
url: `${baseUrl}/about`,
lastModified: new Date(),
@@ -91,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;
@@ -106,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,
})));
+4 -1
View File
@@ -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');
+27 -4
View File
@@ -12,15 +12,38 @@ const apiBase = API_URL.endsWith('/api') ? API_URL : `${API_URL.replace(/\/$/, '
async function getWikiTerm(key: string) {
try {
// 1. Try scientific terms endpoint
const res = await fetch(`${apiBase}/wiki/${encodeURIComponent(key)}`, {
next: { revalidate: 3600, tags: ['wiki', `wiki-${key}`] }
});
if (!res.ok) return null;
return await res.json();
if (res.ok) {
return await res.json();
}
} catch (error) {
console.error('[Wiki] Error fetching term:', error);
return null;
console.warn('[Wiki] /wiki/:key failed, trying /ingredients fallback:', error);
}
try {
// 2. Fallback to ingredients endpoint if slug is an ingredient slug
const ingRes = await fetch(`${apiBase}/ingredients/${encodeURIComponent(key)}`, {
next: { revalidate: 3600, tags: ['ingredients', `ing-${key}`] }
});
if (ingRes.ok) {
const ing = await ingRes.json();
return {
key: ing.slug,
term: ing.nameFa || ing.nameEn || ing.slug,
definition: ing.description || `بررسی تخصصی ترکیب دارویی و خواص ${ing.nameFa || ing.nameEn} در کاتالوگ مکمل‌های کنینا آلمان.`,
metaTitle: `خواص دارویی ${ing.nameFa || ing.nameEn} | دانشنامه کنینا ایران`,
metaDescription: (ing.description || '').slice(0, 155),
wikiId: ing.slug,
};
}
} catch (error) {
console.error('[Wiki] Error fetching ingredient fallback:', error);
}
return null;
}
async function getRelatedProducts(termName: string) {
@@ -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);
+16 -14
View File
@@ -1,4 +1,5 @@
"use client";
import { useUserStore } from "../lib/store/userStore";
import React, { useState, useMemo, useEffect, useCallback } from "react";
import { createPortal } from "react-dom";
import { toPersian, isProductOutOfStock } from "../lib/utils";
@@ -87,7 +88,8 @@ export const ArchiveProductCard: React.FC<{ product: Product }> = ({ product })
const { addItem } = useCartStore();
const cartItem = useCartStore((s) => s.items.find(i => i.product.id === product.id));
const [isAdding, setIsAdding] = useState(false);
const activePet = usePetStore(state => state.pets.find(p => p.id === state.activePetId) || null);
const isLoggedIn = useUserStore(s => s.isLoggedIn);
const activePet = usePetStore(state => (isLoggedIn ? (state.pets.find(p => p.id === state.activePetId) || null) : null));
const { showPrices, allowCart, showPreorderBtn } = useCatalogMode();
const productUrl = `/shop/${product.slug || product.id}`;
@@ -129,15 +131,11 @@ export const ArchiveProductCard: React.FC<{ product: Product }> = ({ product })
href={productUrl}
className="group bg-white rounded-[2.5rem] border border-medical-gray-200 overflow-hidden hover:shadow-2xl transition-all flex flex-col h-full relative"
>
{product.specialBadge && (
<div className="absolute top-4 right-4 z-10 bg-canina-blue text-white text-2xs font-black uppercase tracking-widest px-3 py-1 rounded-full shadow-lg">
{product.specialBadge}
</div>
)}
{/* SpecialBadge moved below image to avoid covering product photo */}
{compatibility && (
<div className={`absolute top-14 right-4 z-10 text-3xs font-black uppercase tracking-widest px-3 py-1 rounded-full shadow-md flex items-center gap-1 ${compatibility.type === 'alert' ? 'bg-amber-100 text-amber-700' :
compatibility.type === 'success' ? 'bg-green-100 text-green-700' : 'bg-medical-gray-100 text-medical-gray-600'
<div className={`absolute top-4 right-4 z-10 text-3xs font-black uppercase tracking-widest px-2.5 py-1 rounded-full shadow-md flex items-center gap-1 backdrop-blur-xs ${compatibility.type === 'alert' ? 'bg-amber-500/90 text-white' :
compatibility.type === 'success' ? 'bg-emerald-600/90 text-white' : 'bg-canina-blue/90 text-white'
}`}>
{compatibility.type === 'alert' ? (
forBoth ? (
@@ -184,6 +182,13 @@ export const ArchiveProductCard: React.FC<{ product: Product }> = ({ product })
</div>
<div className="p-6 flex flex-col flex-1">
{product.specialBadge && (
<div className="mb-2">
<span className="inline-block bg-canina-blue/10 text-canina-blue border border-canina-blue/20 text-[10px] font-black px-2.5 py-1 rounded-lg line-clamp-1 font-vazir" title={product.specialBadge}>
{product.specialBadge}
</span>
</div>
)}
<div className="text-2xs font-bold text-canina-blue uppercase tracking-widest mb-2">{product.category}</div>
<div className="flex flex-col gap-1 mb-3">
<h3 dir="rtl" className="text-base font-black text-medical-gray-900 group-hover:text-canina-blue transition-colors leading-tight text-right font-vazir">
@@ -273,7 +278,8 @@ const ArchiveProductListItem: React.FC<{ product: Product }> = ({ product }) =>
const { addItem } = useCartStore();
const cartItem = useCartStore((s) => s.items.find(i => i.product.id === product.id));
const [isAdding, setIsAdding] = useState(false);
const activePet = usePetStore(state => state.pets.find(p => p.id === state.activePetId) || null);
const isLoggedIn = useUserStore(s => s.isLoggedIn);
const activePet = usePetStore(state => (isLoggedIn ? (state.pets.find(p => p.id === state.activePetId) || null) : null));
const productUrl = `/shop/${product.slug || product.id}`;
const handleAddToCart = (e: React.MouseEvent) => {
@@ -325,11 +331,7 @@ const ArchiveProductListItem: React.FC<{ product: Product }> = ({ product }) =>
className="w-full h-full group-hover:scale-105 transition-transform duration-500"
imgClassName="w-full h-full object-contain"
/>
{product.specialBadge && (
<div className="absolute top-1 right-1 z-10 bg-canina-blue text-white text-[9px] font-black uppercase px-1.5 py-0.5 rounded-md shadow-xs">
{product.specialBadge}
</div>
)}
{/* List specialBadge moved below */}
<div className="absolute bottom-1 left-1 flex gap-1">
{forDog && (
<div className="w-5 h-5 bg-white/90 backdrop-blur-xs rounded-md flex items-center justify-center text-medical-gray-500 border border-medical-gray-100 shadow-2xs" title="مناسب برای سگ">
@@ -49,13 +49,17 @@ export default function B2BLandingClient() {
setSubmitting(true);
try {
await api.post('/wholesale/apply', {
businessName: `${formData.businessName} (${formData.businessType} - ${formData.city}) - رابط: ${formData.contactName}`,
licenseNumber: formData.phone,
notes: formData.notes,
await api.post('/b2b/inquire', {
companyName: formData.businessName,
contactName: formData.contactName || formData.businessName,
email: `partner-${Date.now()}@canina.ir`,
phone: formData.phone,
businessType: `${formData.businessType} (شهر: ${formData.city || 'نامشخص'})`,
estimatedVolume: 'ثبت لندینگ B2B سایت',
message: formData.notes || `درخواست شراکت و تامین رسمی برای ${formData.businessName} در شهر ${formData.city}`,
});
setSubmitted(true);
toast.success('درخواست همکاری شما با موفقیت ثبت شد. همکاران ما حداکثر تا ۲۴ ساعت آینده با شما تماس خواهند گرفت.');
toast.success('درخواست همکاری تجاری شما با موفقیت ثبت شد. تیم بازرگانی و پزشکی حداکثر تا ۲۴ ساعت کاری با شما تماس خواهند گرفت.');
} catch {
toast.error('خطایی در ثبت درخواست رخ داد. لطفاً با پشتیبانی تماس بگیرید.');
} finally {
+89 -14
View File
@@ -89,23 +89,24 @@ export default function B2BPortal({ onClose }: { onClose: () => void }) {
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="fixed inset-0 z-[100] bg-medical-gray-900/60 backdrop-blur-md flex items-center justify-center p-4 md:p-10 font-vazir"
className="fixed inset-0 z-[100] bg-medical-gray-900/70 backdrop-blur-md flex items-center justify-center p-2 sm:p-4 md:p-8 font-vazir"
dir="rtl"
>
<motion.div
initial={{ scale: 0.9, opacity: 0, y: 20 }}
animate={{ scale: 1, opacity: 1, y: 0 }}
className="bg-white w-full max-w-6xl h-[90vh] rounded-[3rem] shadow-2xl overflow-hidden flex flex-col md:flex-row relative"
className="bg-white w-full max-w-6xl h-[95vh] sm:h-[90vh] rounded-3xl sm:rounded-[3rem] shadow-2xl overflow-hidden flex flex-col md:flex-row relative"
>
<button
onClick={onClose}
className="absolute top-6 left-6 z-20 w-10 h-10 bg-medical-gray-100 rounded-full flex items-center justify-center text-medical-gray-500 hover:bg-red-50 hover:text-red-500 transition-all"
className="absolute top-4 left-4 sm:top-6 sm:left-6 z-30 min-w-[44px] min-h-[44px] w-11 h-11 bg-white/90 sm:bg-medical-gray-100 rounded-full flex items-center justify-center text-medical-gray-600 hover:bg-red-50 hover:text-red-500 transition-all shadow-md cursor-pointer"
aria-label="بستن پنجره"
>
<X className="w-5 h-5" />
</button>
{/* Sidebar Info */}
<div className="w-full md:w-80 bg-canina-blue p-10 text-white flex flex-col overflow-y-auto">
<div className="w-full md:w-80 bg-canina-blue p-5 sm:p-8 md:p-10 text-white flex flex-col overflow-y-auto shrink-0 max-h-[45vh] md:max-h-full">
<div className="mb-8">
<div className="w-16 h-16 bg-white/20 rounded-2xl flex items-center justify-center mb-6">
<Building2 className="w-8 h-8" />
@@ -162,32 +163,107 @@ export default function B2BPortal({ onClose }: { onClose: () => void }) {
{/* Main Grid Area */}
<div className="flex-1 flex flex-col bg-medical-gray-50 overflow-hidden">
{/* Header & Search */}
<div className="p-8 border-b border-medical-gray-200 flex flex-col md:flex-row md:items-center justify-between gap-6 bg-white">
<div className="p-4 sm:p-6 md:p-8 border-b border-medical-gray-200 flex flex-col sm:flex-row sm:items-center justify-between gap-3 sm:gap-6 bg-white shrink-0">
<div className="relative flex-1 max-w-md">
<Search className="absolute right-4 top-1/2 -translate-y-1/2 w-4 h-4 text-medical-gray-400" />
<Search className="absolute right-3 sm:right-4 top-1/2 -translate-y-1/2 w-4 h-4 text-medical-gray-400" />
<input
type="text"
placeholder="جستجوی کد کالا یا نام محصول..."
value={searchQuery}
onChange={e => setSearchQuery(e.target.value)}
className="w-full bg-medical-gray-50 border border-medical-gray-200 rounded-2xl py-3 pr-11 pl-4 text-sm focus:outline-none focus:ring-2 focus:ring-canina-blue/20"
className="w-full bg-medical-gray-50 border border-medical-gray-200 rounded-xl sm:rounded-2xl py-2.5 sm:py-3 pr-9 sm:pr-11 pl-4 text-xs sm:text-sm focus:outline-none focus:ring-2 focus:ring-canina-blue/20"
/>
</div>
<button
onClick={handleAddAll}
disabled={totalItems === 0}
className="bg-medical-gray-900 text-white px-8 py-3 rounded-2xl font-black text-sm flex items-center gap-2 hover:bg-canina-blue transition-colors disabled:opacity-30"
className="bg-medical-gray-900 text-white px-5 sm:px-8 py-2.5 sm:py-3 rounded-xl sm:rounded-2xl font-black text-xs sm:text-sm flex items-center justify-center gap-2 hover:bg-canina-blue transition-colors disabled:opacity-30 cursor-pointer shadow-md"
>
<ShoppingCart className="w-4 h-4" />
افزودن کلی ({totalItems} عدد)
<span>افزودن کلی ({toPersian(totalItems)} عدد)</span>
</button>
</div>
{/* Table */}
<div className="flex-1 overflow-y-auto p-8">
{loadError && <p role="alert">خطا در دریافت محصولات. لطفاً دوباره تلاش کنید.</p>}
<div className="bg-white border border-medical-gray-200 rounded-3xl overflow-hidden shadow-sm">
{/* Products Container */}
<div className="flex-1 overflow-y-auto p-3 sm:p-6 md:p-8">
{loadError && <p role="alert" className="text-red-500 font-bold text-xs p-4 bg-red-50 rounded-2xl mb-4">خطا در دریافت محصولات. لطفاً دوباره تلاش کنید.</p>}
{/* Mobile View: Clean Card Layout for each product */}
<div className="md:hidden space-y-3">
{filteredProducts.map(product => {
const basePrice = product.priceValue || 0;
const wholesaleDiscountPercent = Number(useSettingsStore.getState().getText('B2B_DISCOUNT_PERCENT', '30')) || 30;
const prodWholesale = (product as unknown as { wholesalePrice?: number }).wholesalePrice;
const wholesalePrice = prodWholesale
? Number(prodWholesale)
: Math.round(basePrice * (1 - wholesaleDiscountPercent / 100));
const currentQty = quantities[product.id] || 0;
return (
<div key={product.id} className="bg-white border border-medical-gray-200 rounded-2xl p-3.5 shadow-xs space-y-3">
<div className="flex items-center gap-3">
<div className="w-14 h-14 bg-medical-gray-50 rounded-xl p-1.5 shrink-0 border border-medical-gray-100 flex items-center justify-center">
<SafeImage src={product.image} className="w-full h-full" imgClassName="object-contain" alt={product.name} />
</div>
<div className="flex-1 min-w-0">
<h4 className="font-black text-xs text-medical-gray-900 leading-snug line-clamp-2">{product.name}</h4>
<span className="text-[10px] font-mono text-medical-gray-400 block mt-0.5 dir-ltr text-right">کد: {product.artNo}</span>
</div>
</div>
<div className="flex items-center justify-between border-t border-medical-gray-100 pt-2.5 text-xs">
<div>
<span className="text-[10px] text-medical-gray-400 block font-medium">تک‌فروشی</span>
<span className="font-bold text-medical-gray-600 text-xs">{toPersian(basePrice.toLocaleString())} ت</span>
</div>
<div>
<span className="text-[10px] text-amber-600 block font-black">قیمت همکار B2B</span>
{isWholesaleVerified ? (
<span className="font-black text-amber-800 text-xs bg-amber-50 px-2 py-0.5 rounded-md border border-amber-200 inline-block">
{toPersian(wholesalePrice.toLocaleString())} ت
</span>
) : (
<span className="inline-flex items-center gap-1 text-[10px] font-bold text-gray-400 bg-gray-50 px-1.5 py-0.5 rounded">
<Lock className="w-2.5 h-2.5" />
تایید ادمین
</span>
)}
</div>
<div className="flex items-center gap-1 bg-medical-gray-50 border border-medical-gray-200 rounded-xl p-1">
<button
type="button"
onClick={() => handleQuantityChange(product.id, String(Math.max(0, currentQty - 1)))}
className="w-7 h-7 flex items-center justify-center bg-white rounded-lg text-gray-700 font-bold text-sm shadow-xs active:bg-gray-100"
>
-
</button>
<input
type="number"
min="0"
value={currentQty || ""}
onChange={(e) => handleQuantityChange(product.id, e.target.value)}
placeholder="0"
className="w-8 text-center bg-transparent font-mono font-black text-xs outline-none"
/>
<button
type="button"
onClick={() => handleQuantityChange(product.id, String(currentQty + 1))}
className="w-7 h-7 flex items-center justify-center bg-white rounded-lg text-gray-700 font-bold text-sm shadow-xs active:bg-gray-100"
>
+
</button>
</div>
</div>
</div>
);
})}
</div>
{/* Desktop / Tablet View: Rich Table */}
<div className="hidden md:block bg-white border border-medical-gray-200 rounded-3xl overflow-hidden shadow-sm">
<table className="w-full text-right">
<thead className="bg-medical-gray-50 border-b border-medical-gray-200">
<tr>
@@ -201,7 +277,6 @@ export default function B2BPortal({ onClose }: { onClose: () => void }) {
<tbody className="divide-y divide-medical-gray-100">
{filteredProducts.map(product => {
const basePrice = product.priceValue || 0;
// Priority 1: Specific product wholesalePrice, Priority 2: General settings percentage discount (default 30%)
const wholesaleDiscountPercent = Number(useSettingsStore.getState().getText('B2B_DISCOUNT_PERCENT', '30')) || 30;
const prodWholesale = (product as unknown as { wholesalePrice?: number }).wholesalePrice;
const wholesalePrice = prodWholesale
+23 -20
View File
@@ -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}`}
@@ -101,7 +101,7 @@ export default function CartDrawer({ isOpen, onClose, onCheckout, onShopNavigate
animate={{ x: 0 }}
exit={{ x: "100%" }}
transition={{ type: "spring", damping: 25, stiffness: 200 }}
className="fixed inset-y-0 right-0 w-full max-w-md bg-white shadow-2xl z-[101] flex flex-col"
className="fixed inset-y-0 right-0 w-full max-w-full sm:max-w-md bg-white shadow-2xl z-[101] flex flex-col overflow-x-hidden"
dir="rtl"
>
{/* Header */}
Loaded 100 of 134 files, more files were not shown because too many files have changed in this diff. Show more