Compare commits

...
Author SHA1 Message Date
devops 795bbb33cf fix(deploy): gate Stage v4 rollout on schema-first maintenance and acceptance 2026-10-22 19:18:50 +00:00
devops ac065fa911 feat(orchestration): integrate read-only v4 surfaces with mutation lockdown 2026-10-22 19:04:00 +00:00
devops 70d8128bfb feat(router-usage): add protected read-only consumption adapter with honest quota unknowns 2026-10-22 18:54:24 +00:00
devops 8c8ae66c7d feat(runtime): add fail-closed Hermes management adapter and contract gates 2026-10-22 18:54:24 +00:00
devops c8a3f35b0a feat(admin): add backend-authoritative orchestration command center and usage view 2026-10-22 18:54:24 +00:00
devops e5c83e87fe feat(orchestration): add v4 additive backend core and policy tests 2026-10-22 18:15:32 +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
181 changed files with 9442 additions and 1522 deletions

No files matched your search

@@ -0,0 +1,24 @@
name: Hermes runtime contract review (NO DEPLOY)
on:
workflow_dispatch:
permissions:
contents: read
jobs:
contract-review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '22'
cache: npm
cache-dependency-path: backend/package-lock.json
- run: npm ci --ignore-scripts --no-audit
working-directory: backend
- run: npm test -- --runInBand hermes-management
working-directory: backend
- run: npx tsc -p src/hermes-management/tsconfig.contract.json --noEmit
working-directory: backend
- run: npx tsc -p src/hermes-management/tsconfig.contract.json
working-directory: backend
# No SSH, Docker socket, secrets, deployments, dispatch or runtime mutation.
+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
+13
View File
@@ -0,0 +1,13 @@
# Prisma migration baseline and Orchestration v4 rollout
The production databases predate complete migration tracking for the legacy governance tables (`approval_requests`, `department_tasks`, and `audit_logs`). Do **not** run `prisma db push`, reset, or edit an applied migration.
## Safe baseline procedure (per environment, during a CI/CD maintenance step)
1. Back up the database and verify restore capability.
2. Run `prisma migrate status` and compare the live schema to the reviewed migrations.
3. For migrations whose objects already exist in that environment, record them without executing SQL using `prisma migrate resolve --applied <migration_name>`. This is an environment-specific reconciliation step; never guess which migrations are present.
4. Review `20261022000000_add_orchestration_v4_core/migration.sql`. It is additive: it creates only `orchestration_*` tables, indexes, and foreign keys. It does not alter or copy legacy governance data.
5. Apply through CI/CD only with `prisma migrate deploy`; validate counts and application health. No production deployment is part of this change.
Rollback is application-first: stop use of the new module while retaining its append-only records. Do not drop tables in an automated rollback. Any later removal requires a separately reviewed archival migration.
@@ -0,0 +1,3 @@
ALTER TABLE blogs ADD COLUMN IF NOT EXISTS author_team VARCHAR(200);
ALTER TABLE blogs ADD COLUMN IF NOT EXISTS author_role VARCHAR(200);
ALTER TABLE blogs ADD COLUMN IF NOT EXISTS content_updated_at TIMESTAMPTZ;
@@ -0,0 +1,211 @@
-- CreateTable
CREATE TABLE "orchestration_tasks" (
"id" UUID NOT NULL,
"key" VARCHAR(120) NOT NULL,
"title" VARCHAR(255) NOT NULL,
"department" VARCHAR(50) NOT NULL,
"state" VARCHAR(40) NOT NULL DEFAULT 'DRAFT',
"operation_mode" VARCHAR(30) NOT NULL,
"model_tier" VARCHAR(2),
"budget_limit_cents" INTEGER NOT NULL,
"version" INTEGER NOT NULL DEFAULT 1,
"metadata" JSONB NOT NULL DEFAULT '{}',
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMPTZ NOT NULL,
CONSTRAINT "orchestration_tasks_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "orchestration_runs" (
"id" UUID NOT NULL,
"task_id" UUID NOT NULL,
"attempt" INTEGER NOT NULL DEFAULT 1,
"status" VARCHAR(30) NOT NULL DEFAULT 'PENDING',
"commit_sha" VARCHAR(64) NOT NULL,
"environment" VARCHAR(50) NOT NULL,
"retry_class" VARCHAR(30),
"idempotency_key" VARCHAR(150) NOT NULL,
"started_at" TIMESTAMPTZ,
"finished_at" TIMESTAMPTZ,
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "orchestration_runs_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "orchestration_artifacts" (
"id" UUID NOT NULL,
"run_id" UUID NOT NULL,
"kind" VARCHAR(50) NOT NULL,
"uri" TEXT NOT NULL,
"sha256" CHAR(64) NOT NULL,
"size_bytes" BIGINT,
"metadata" JSONB NOT NULL DEFAULT '{}',
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "orchestration_artifacts_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "orchestration_attestations" (
"id" UUID NOT NULL,
"run_id" UUID NOT NULL,
"kind" VARCHAR(50) NOT NULL,
"subject_hash" CHAR(64) NOT NULL,
"predicate" JSONB NOT NULL,
"signer" VARCHAR(150) NOT NULL,
"signature" TEXT,
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "orchestration_attestations_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "orchestration_dependencies" (
"id" UUID NOT NULL,
"task_id" UUID NOT NULL,
"depends_on_task_id" UUID NOT NULL,
"kind" VARCHAR(30) NOT NULL DEFAULT 'BLOCKS',
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "orchestration_dependencies_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "orchestration_approval_decisions" (
"id" UUID NOT NULL,
"task_id" UUID NOT NULL,
"gate" INTEGER NOT NULL,
"decision" VARCHAR(20) NOT NULL,
"actor_id" VARCHAR(100) NOT NULL,
"notes" TEXT,
"expires_at" TIMESTAMPTZ NOT NULL,
"idempotency_key" VARCHAR(150) NOT NULL,
"run_id" UUID,
"artifact_hash" CHAR(64),
"commit_sha" VARCHAR(64),
"environment" VARCHAR(50),
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "orchestration_approval_decisions_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "orchestration_events" (
"id" UUID NOT NULL,
"task_id" UUID,
"event_type" VARCHAR(60) NOT NULL,
"from_state" VARCHAR(40),
"to_state" VARCHAR(40),
"sequence" INTEGER NOT NULL,
"actor_id" VARCHAR(100) NOT NULL,
"idempotency_key" VARCHAR(150),
"payload" JSONB NOT NULL DEFAULT '{}',
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "orchestration_events_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "orchestration_budget_ledger" (
"id" UUID NOT NULL,
"task_id" UUID NOT NULL,
"amount_cents" INTEGER NOT NULL,
"kind" VARCHAR(40) NOT NULL,
"idempotency_key" VARCHAR(150) NOT NULL,
"actor_id" VARCHAR(100) NOT NULL,
"metadata" JSONB NOT NULL DEFAULT '{}',
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "orchestration_budget_ledger_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "orchestration_kill_switches" (
"scope" VARCHAR(80) NOT NULL,
"level" VARCHAR(30) NOT NULL,
"active" BOOLEAN NOT NULL DEFAULT true,
"reason" TEXT NOT NULL,
"actor_id" VARCHAR(100) NOT NULL,
"version" INTEGER NOT NULL DEFAULT 1,
"updated_at" TIMESTAMPTZ NOT NULL,
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "orchestration_kill_switches_pkey" PRIMARY KEY ("scope")
);
-- CreateIndex
CREATE UNIQUE INDEX "orchestration_tasks_key_key" ON "orchestration_tasks"("key");
-- CreateIndex
CREATE INDEX "orchestration_tasks_state_created_at_idx" ON "orchestration_tasks"("state", "created_at");
-- CreateIndex
CREATE INDEX "orchestration_tasks_department_state_idx" ON "orchestration_tasks"("department", "state");
-- CreateIndex
CREATE UNIQUE INDEX "orchestration_runs_idempotency_key_key" ON "orchestration_runs"("idempotency_key");
-- CreateIndex
CREATE INDEX "orchestration_runs_task_id_status_idx" ON "orchestration_runs"("task_id", "status");
-- CreateIndex
CREATE UNIQUE INDEX "orchestration_runs_task_id_attempt_key" ON "orchestration_runs"("task_id", "attempt");
-- CreateIndex
CREATE UNIQUE INDEX "orchestration_artifacts_run_id_sha256_key" ON "orchestration_artifacts"("run_id", "sha256");
-- CreateIndex
CREATE UNIQUE INDEX "orchestration_attestations_run_id_kind_subject_hash_signer_key" ON "orchestration_attestations"("run_id", "kind", "subject_hash", "signer");
-- CreateIndex
CREATE UNIQUE INDEX "orchestration_dependencies_task_id_depends_on_task_id_key" ON "orchestration_dependencies"("task_id", "depends_on_task_id");
-- CreateIndex
CREATE UNIQUE INDEX "orchestration_approval_decisions_idempotency_key_key" ON "orchestration_approval_decisions"("idempotency_key");
-- CreateIndex
CREATE INDEX "orchestration_approval_decisions_task_id_gate_created_at_idx" ON "orchestration_approval_decisions"("task_id", "gate", "created_at");
-- CreateIndex
CREATE UNIQUE INDEX "orchestration_events_idempotency_key_key" ON "orchestration_events"("idempotency_key");
-- CreateIndex
CREATE INDEX "orchestration_events_event_type_created_at_idx" ON "orchestration_events"("event_type", "created_at");
-- CreateIndex
CREATE UNIQUE INDEX "orchestration_events_task_id_sequence_key" ON "orchestration_events"("task_id", "sequence");
-- CreateIndex
CREATE UNIQUE INDEX "orchestration_budget_ledger_idempotency_key_key" ON "orchestration_budget_ledger"("idempotency_key");
-- CreateIndex
CREATE INDEX "orchestration_budget_ledger_task_id_created_at_idx" ON "orchestration_budget_ledger"("task_id", "created_at");
-- AddForeignKey
ALTER TABLE "orchestration_runs" ADD CONSTRAINT "orchestration_runs_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "orchestration_artifacts" ADD CONSTRAINT "orchestration_artifacts_run_id_fkey" FOREIGN KEY ("run_id") REFERENCES "orchestration_runs"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "orchestration_attestations" ADD CONSTRAINT "orchestration_attestations_run_id_fkey" FOREIGN KEY ("run_id") REFERENCES "orchestration_runs"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "orchestration_dependencies" ADD CONSTRAINT "orchestration_dependencies_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "orchestration_dependencies" ADD CONSTRAINT "orchestration_dependencies_depends_on_task_id_fkey" FOREIGN KEY ("depends_on_task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "orchestration_approval_decisions" ADD CONSTRAINT "orchestration_approval_decisions_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "orchestration_approval_decisions" ADD CONSTRAINT "orchestration_approval_decisions_run_id_fkey" FOREIGN KEY ("run_id") REFERENCES "orchestration_runs"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "orchestration_events" ADD CONSTRAINT "orchestration_events_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "orchestration_budget_ledger" ADD CONSTRAINT "orchestration_budget_ledger_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
+144
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")
@@ -1088,3 +1091,144 @@ model DepartmentTask {
@@index([createdAt])
@@map("department_tasks")
}
// Orchestration v4 additive models. Legacy governance tables remain untouched.
model OrchestrationTask {
id String @id @default(uuid()) @db.Uuid
key String @unique @db.VarChar(120)
title String @db.VarChar(255)
department String @db.VarChar(50)
state String @default("DRAFT") @db.VarChar(40)
operationMode String @map("operation_mode") @db.VarChar(30)
modelTier String? @map("model_tier") @db.VarChar(2)
budgetLimitCents Int @map("budget_limit_cents")
version Int @default(1)
metadata Json @default("{}") @db.JsonB
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz()
runs OrchestrationRun[]
dependencies OrchestrationDependency[] @relation("task_dependencies")
dependedOnBy OrchestrationDependency[] @relation("task_dependents")
decisions OrchestrationApprovalDecision[]
events OrchestrationEvent[]
budgetLedger OrchestrationBudgetLedger[]
@@index([state, createdAt])
@@index([department, state])
@@map("orchestration_tasks")
}
model OrchestrationRun {
id String @id @default(uuid()) @db.Uuid
taskId String @map("task_id") @db.Uuid
attempt Int @default(1)
status String @default("PENDING") @db.VarChar(30)
commitSha String @map("commit_sha") @db.VarChar(64)
environment String @db.VarChar(50)
retryClass String? @map("retry_class") @db.VarChar(30)
idempotencyKey String @unique @map("idempotency_key") @db.VarChar(150)
startedAt DateTime? @map("started_at") @db.Timestamptz()
finishedAt DateTime? @map("finished_at") @db.Timestamptz()
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
task OrchestrationTask @relation(fields:[taskId],references:[id],onDelete:Restrict)
artifacts OrchestrationArtifact[]
attestations OrchestrationAttestation[]
approvals OrchestrationApprovalDecision[]
@@unique([taskId, attempt])
@@index([taskId, status])
@@map("orchestration_runs")
}
model OrchestrationArtifact {
id String @id @default(uuid()) @db.Uuid
runId String @map("run_id") @db.Uuid
kind String @db.VarChar(50)
uri String @db.Text
sha256 String @db.Char(64)
sizeBytes BigInt? @map("size_bytes")
metadata Json @default("{}") @db.JsonB
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
run OrchestrationRun @relation(fields:[runId],references:[id],onDelete:Restrict)
@@unique([runId, sha256])
@@map("orchestration_artifacts")
}
model OrchestrationAttestation {
id String @id @default(uuid()) @db.Uuid
runId String @map("run_id") @db.Uuid
kind String @db.VarChar(50)
subjectHash String @map("subject_hash") @db.Char(64)
predicate Json @db.JsonB
signer String @db.VarChar(150)
signature String? @db.Text
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
run OrchestrationRun @relation(fields:[runId],references:[id],onDelete:Restrict)
@@unique([runId, kind, subjectHash, signer])
@@map("orchestration_attestations")
}
model OrchestrationDependency {
id String @id @default(uuid()) @db.Uuid
taskId String @map("task_id") @db.Uuid
dependsOnTaskId String @map("depends_on_task_id") @db.Uuid
kind String @default("BLOCKS") @db.VarChar(30)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
task OrchestrationTask @relation("task_dependencies",fields:[taskId],references:[id],onDelete:Restrict)
dependsOnTask OrchestrationTask @relation("task_dependents",fields:[dependsOnTaskId],references:[id],onDelete:Restrict)
@@unique([taskId, dependsOnTaskId])
@@map("orchestration_dependencies")
}
model OrchestrationApprovalDecision {
id String @id @default(uuid()) @db.Uuid
taskId String @map("task_id") @db.Uuid
gate Int
decision String @db.VarChar(20)
actorId String @map("actor_id") @db.VarChar(100)
notes String? @db.Text
expiresAt DateTime @map("expires_at") @db.Timestamptz()
idempotencyKey String @unique @map("idempotency_key") @db.VarChar(150)
runId String? @map("run_id") @db.Uuid
artifactHash String? @map("artifact_hash") @db.Char(64)
commitSha String? @map("commit_sha") @db.VarChar(64)
environment String? @db.VarChar(50)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
task OrchestrationTask @relation(fields:[taskId],references:[id],onDelete:Restrict)
run OrchestrationRun? @relation(fields:[runId],references:[id],onDelete:Restrict)
@@index([taskId, gate, createdAt])
@@map("orchestration_approval_decisions")
}
model OrchestrationEvent {
id String @id @default(uuid()) @db.Uuid
taskId String? @map("task_id") @db.Uuid
eventType String @map("event_type") @db.VarChar(60)
fromState String? @map("from_state") @db.VarChar(40)
toState String? @map("to_state") @db.VarChar(40)
sequence Int
actorId String @map("actor_id") @db.VarChar(100)
idempotencyKey String? @unique @map("idempotency_key") @db.VarChar(150)
payload Json @default("{}") @db.JsonB
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
task OrchestrationTask? @relation(fields:[taskId],references:[id],onDelete:Restrict)
@@unique([taskId, sequence])
@@index([eventType, createdAt])
@@map("orchestration_events")
}
model OrchestrationBudgetLedger {
id String @id @default(uuid()) @db.Uuid
taskId String @map("task_id") @db.Uuid
amountCents Int @map("amount_cents")
kind String @db.VarChar(40)
idempotencyKey String @unique @map("idempotency_key") @db.VarChar(150)
actorId String @map("actor_id") @db.VarChar(100)
metadata Json @default("{}") @db.JsonB
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
task OrchestrationTask @relation(fields:[taskId],references:[id],onDelete:Restrict)
@@index([taskId, createdAt])
@@map("orchestration_budget_ledger")
}
model OrchestrationKillSwitch {
scope String @id @db.VarChar(80)
level String @db.VarChar(30)
active Boolean @default(true)
reason String @db.Text
actorId String @map("actor_id") @db.VarChar(100)
version Int @default(1)
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz()
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
@@map("orchestration_kill_switches")
}
+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 -18
View File
@@ -3,7 +3,6 @@ import {
Get,
Post,
Put,
Delete,
Body,
Param,
Query,
@@ -106,7 +105,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 +150,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 +227,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",
@@ -210,10 +254,4 @@ export class ApprovalsController {
};
}
@Delete(":id")
@ApiOperation({ summary: "حذف آیتم از کارتابل" })
async remove(@Param("id") id: string) {
await (this.prisma as any).approvalRequest.delete({ where: { id } });
return { success: true, message: "Deleted successfully" };
}
}
@@ -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),
}),
});
});
});
});
@@ -3,13 +3,13 @@ import {
Get,
Post,
Put,
Delete,
Body,
Param,
Query,
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 +129,6 @@ export class DepartmentTasksController {
},
});
// ثبت در تاریخچه لاگ‌ها
await (this.prisma as any).auditLog.create({
data: {
entity: "task",
@@ -165,6 +164,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 +182,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 +191,6 @@ export class DepartmentTasksController {
data: updateData,
});
// ثبت در تاریخچه
await (this.prisma as any).auditLog.create({
data: {
entity: "task",
@@ -199,10 +207,4 @@ export class DepartmentTasksController {
return { success: true, data: updated };
}
@Delete(":id")
@ApiOperation({ summary: "حذف تسک" })
async remove(@Param("id") id: string) {
await (this.prisma as any).departmentTask.delete({ where: { id } });
return { success: true, message: "Deleted successfully" };
}
}
@@ -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);
+9
View File
@@ -1,3 +1,6 @@
import { RouterUsageModule } from './router-usage/router-usage.module';
import { HermesManagementModule } from './hermes-management/hermes-management.module';
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';
@@ -36,11 +39,16 @@ import { DoctorsModule } from "./doctors/doctors.module";
import { FaqModule } from "./faq/faq.module";
import { MenuModule } from "./menu/menu.module";
import { RevalidationModule } from "./common/revalidation/revalidation.module";
import { OrchestrationModule } from "./orchestration/orchestration.module";
import { Request, Response, NextFunction } from "express";
@Module({
imports: [
RouterUsageModule,
// Deny-all registration: no request identity or runtime credentials are accepted yet.
HermesManagementModule.register({origin:'http://canina-hermes:9119',token:async()=>''}),
OrchestrationModule,
SupportChatModule,
RevalidationModule,
SmsModule,
@@ -79,6 +87,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;
}
}
}
@@ -0,0 +1,149 @@
import { HermesIntegrationService } from './hermes-integration.service';
import { HermesAdapter } from './hermes.adapter';
describe('backend-owned runtime authorization', () => {
const ctx = { subject: 'admin', profiles: ['seo'] };
const make = (allow = true, enabled = false) => {
const fetcher = jest
.fn()
.mockResolvedValue(
new Response(
JSON.stringify({ id: 'j', profile: 'seo', enabled: false }),
),
);
const authorize = jest.fn().mockResolvedValue(allow);
return {
fetcher,
authorize,
s: new HermesIntegrationService(
new HermesAdapter(
{
origin: 'http://canina-hermes:9119',
token: () => Promise.resolve('secret'),
},
fetcher,
),
{ authorize },
enabled,
),
};
};
it('denies missing principal, missing profile, denied policy before upstream IO', async () => {
const { s, fetcher } = make(false);
await expect(s.pauseCron(ctx, 'seo', 'j')).rejects.toMatchObject({
code: 'FORBIDDEN',
});
await expect(
s.pauseCron({ ...ctx, subject: '' }, 'seo', 'j'),
).rejects.toMatchObject({ code: 'FORBIDDEN' });
await expect(s.pauseCron(ctx, 'dev', 'j')).rejects.toMatchObject({
code: 'FORBIDDEN',
});
expect(fetcher).not.toHaveBeenCalled();
});
it('allows authorized pause but leaves resume disabled by default', async () => {
const { s, fetcher, authorize } = make();
await s.pauseCron(ctx, 'seo', 'j');
expect(authorize).toHaveBeenCalledWith(ctx, 'cron.pause', 'seo');
await expect(s.resumeCron(ctx, 'seo', 'j')).rejects.toMatchObject({
code: 'FORBIDDEN',
});
expect(fetcher).toHaveBeenCalledTimes(1);
});
it('fails closed on all execution and never forwards arbitrary events or RPC', async () => {
const { s, fetcher } = make();
expect(s.capabilities()).toMatchObject({
chat: false,
control: false,
eventDispatch: false,
cronResume: false,
});
await expect(s.chat(ctx, 'seo', 'hello')).rejects.toMatchObject({
code: 'UNSUPPORTED',
});
await expect(s.control(ctx, 'seo', 'interrupt')).rejects.toMatchObject({
code: 'UNSUPPORTED',
});
await expect(
s.dispatchEvent(ctx, 'seo', { type: 'order.created' }),
).rejects.toMatchObject({ code: 'FORBIDDEN' });
expect(fetcher).not.toHaveBeenCalled();
});
it('fails closed when authorization provider throws', async () => {
const a = new HermesAdapter({
origin: 'http://canina-hermes:9119',
token: () => Promise.resolve('secret'),
});
const s = new HermesIntegrationService(a, {
authorize: () => Promise.reject(new Error('private')),
});
await expect(s.health(ctx)).rejects.toMatchObject({ code: 'FORBIDDEN' });
});
});
it('checks every read capability and filters the global profile roster', async () => {
const fetcher = jest.fn().mockImplementation((input: URL) => {
const payloads: Record<string, unknown> = {
'/api/health': {
ok: true,
version: 'x',
commit: 'x',
auth_required: true,
},
'/api/status': {
version: 'x',
gateway_running: false,
gateway_state: null,
overall: 'degraded',
active_agents: 0,
},
'/api/profiles': {
profiles: [
{ name: 'seo', is_default: false, gateway_running: false },
{ name: 'dev', is_default: false, gateway_running: false },
],
},
'/api/model/info': {
model: 'm',
provider: 'p',
effective_context_length: 1,
},
'/api/model/options': { providers: [] },
'/api/analytics/usage': {
period_days: 30,
totals: {
total_input: 0,
total_output: 0,
total_sessions: 0,
total_estimated_cost: 0,
},
},
'/api/sessions': { sessions: [], total: 0 },
'/api/cron/jobs': [],
};
return Promise.resolve(
new Response(JSON.stringify(payloads[input.pathname])),
);
});
const authorize = jest.fn().mockResolvedValue(true);
const s = new HermesIntegrationService(
new HermesAdapter(
{
origin: 'http://canina-hermes:9119',
token: () => Promise.resolve('secret'),
},
fetcher,
),
{ authorize },
);
const p = { subject: 'verified', profiles: ['seo'] };
await s.health(p);
await s.status(p, 'seo');
expect(await s.profiles(p)).toHaveLength(1);
await s.modelInfo(p, 'seo');
await s.modelOptions(p, 'seo');
await s.usage(p, 'seo');
await s.sessions(p, 'seo');
await s.crons(p, 'seo');
expect(authorize).toHaveBeenCalledTimes(8);
expect(authorize.mock.calls.every((c) => c[1] === 'runtime.read')).toBe(true);
});
@@ -0,0 +1,126 @@
import { HermesAdapter, HermesError, Json } from './hermes.adapter';
/** Context MUST be constructed from verified backend identity, never request bodies. */
export interface RuntimePrincipal {
subject: string;
profiles: readonly string[];
}
export type RuntimePermission =
| 'runtime.read'
| 'cron.pause'
| 'cron.resume'
| 'chat'
| 'control'
| 'event.dispatch';
export interface RuntimeAuthorizer {
authorize(
principal: RuntimePrincipal,
permission: RuntimePermission,
profile?: string,
): Promise<boolean>;
}
/** No controller or socket is registered: only the backend gatekeeper can call this seam. */
export class HermesIntegrationService {
constructor(
private readonly adapter: HermesAdapter,
private readonly policy: RuntimeAuthorizer,
private readonly resumeEnabled = false,
) {}
capabilities() {
return {
inventory: true,
cronPause: true,
cronResume: this.resumeEnabled,
chat: false,
control: false,
eventDispatch: false,
} as const;
}
private async check(
principal: RuntimePrincipal,
permission: RuntimePermission,
profile?: string,
): Promise<void> {
if (
!principal?.subject ||
!Array.isArray(principal.profiles) ||
(profile && !principal.profiles.includes(profile))
)
throw new HermesError('FORBIDDEN');
try {
if (
(await this.policy.authorize(principal, permission, profile)) !== true
)
throw new HermesError('FORBIDDEN');
} catch {
throw new HermesError('FORBIDDEN');
}
}
async health(p: RuntimePrincipal) {
await this.check(p, 'runtime.read');
return this.adapter.health();
}
async status(p: RuntimePrincipal, profile: string) {
await this.check(p, 'runtime.read', profile);
return this.adapter.status(profile);
}
async profiles(p: RuntimePrincipal) {
await this.check(p, 'runtime.read');
return (await this.adapter.profiles()).filter(
(r) => typeof r.name === 'string' && p.profiles.includes(r.name),
);
}
async modelInfo(p: RuntimePrincipal, profile: string) {
await this.check(p, 'runtime.read', profile);
return this.adapter.modelInfo(profile);
}
async modelOptions(p: RuntimePrincipal, profile: string) {
await this.check(p, 'runtime.read', profile);
return this.adapter.modelOptions(profile);
}
async usage(p: RuntimePrincipal, profile: string, days = 30) {
await this.check(p, 'runtime.read', profile);
return this.adapter.usage(profile, days);
}
async sessions(p: RuntimePrincipal, profile: string, limit = 20, offset = 0) {
await this.check(p, 'runtime.read', profile);
return this.adapter.sessions(profile, limit, offset);
}
async crons(p: RuntimePrincipal, profile: string) {
await this.check(p, 'runtime.read', profile);
return this.adapter.crons(profile);
}
async pauseCron(p: RuntimePrincipal, profile: string, id: string) {
await this.check(p, 'cron.pause', profile);
return this.adapter.pauseCron(profile, id);
}
async resumeCron(p: RuntimePrincipal, profile: string, id: string) {
await this.check(p, 'cron.resume', profile);
if (!this.resumeEnabled) throw new HermesError('FORBIDDEN');
return this.adapter.resumeCron(profile, id);
}
async chat(
p: RuntimePrincipal,
profile: string,
_text: string,
): Promise<never> {
await this.check(p, 'chat', profile);
throw new HermesError('UNSUPPORTED');
}
async control(
p: RuntimePrincipal,
profile: string,
_command: 'interrupt',
): Promise<never> {
await this.check(p, 'control', profile);
throw new HermesError('UNSUPPORTED');
}
/** Disabled independently of policy: no unreviewed event may become an agent prompt. */
async dispatchEvent(
p: RuntimePrincipal,
profile: string,
_event: Json,
): Promise<never> {
await this.check(p, 'event.dispatch', profile);
throw new HermesError('FORBIDDEN');
}
}
@@ -0,0 +1,18 @@
import { Test } from '@nestjs/testing';
import { HermesManagementModule } from './hermes-management.module';
import { HermesIntegrationService } from './hermes-integration.service';
it('requires explicit registration and denies by default without publishing controllers', async () => {
const module = await Test.createTestingModule({
imports: [
HermesManagementModule.register({
origin: 'http://canina-hermes:9119',
token: () => Promise.resolve('secret'),
}),
],
}).compile();
const service = module.get(HermesIntegrationService);
await expect(
service.health({ subject: 'admin', profiles: [] }),
).rejects.toMatchObject({ code: 'FORBIDDEN' });
await module.close();
});
@@ -0,0 +1,27 @@
import { DynamicModule, Module } from '@nestjs/common';
import { HermesAdapter, HermesConfig } from './hermes.adapter';
import {
HermesIntegrationService,
RuntimeAuthorizer,
} from './hermes-integration.service';
@Module({})
export class HermesManagementModule {
static register(
config: HermesConfig,
policy: RuntimeAuthorizer = { authorize: () => Promise.resolve(false) },
): DynamicModule {
return {
module: HermesManagementModule,
providers: [
{ provide: HermesAdapter, useFactory: () => new HermesAdapter(config) },
{
provide: HermesIntegrationService,
useFactory: (adapter: HermesAdapter) =>
new HermesIntegrationService(adapter, policy, false),
inject: [HermesAdapter],
},
],
exports: [HermesIntegrationService],
};
}
}
@@ -0,0 +1,240 @@
import { HermesAdapter, HermesError } from './hermes.adapter';
const health = {
ok: true,
version: '0.13',
commit: 'abc',
auth_required: true,
};
describe('installed Hermes health contract', () => {
it('uses pinned internal origin, bearer only server side and strips extra fields', async () => {
const fetcher = jest
.fn()
.mockResolvedValue(
new Response(
JSON.stringify({ ...health, token: 'never', home: '/secret' }),
),
);
const adapter = new HermesAdapter(
{
origin: 'http://canina-hermes:9119',
token: () => Promise.resolve('private'),
},
fetcher,
);
expect(await adapter.health()).toEqual(health);
expect(fetcher.mock.calls[0][0].toString()).toBe(
'http://canina-hermes:9119/api/health',
);
expect(fetcher.mock.calls[0][1].headers.Authorization).toBe(
'Bearer private',
);
expect(fetcher.mock.calls[0][1].redirect).toBe('error');
});
it('fails closed for bad origin, auth errors, malformed contract and oversized bodies', async () => {
expect(
() =>
new HermesAdapter({
origin: 'https://evil.test',
token: () => Promise.resolve(''),
}),
).toThrow(HermesError);
for (const response of [
new Response('private', { status: 401 }),
new Response('{}'),
new Response('x'.repeat(262145)),
]) {
const a = new HermesAdapter(
{
origin: 'http://canina-hermes:9119',
token: () => Promise.resolve('secret'),
},
jest.fn().mockResolvedValue(response),
);
await expect(a.health()).rejects.toBeInstanceOf(HermesError);
}
});
});
describe('bounded profile-scoped REST inventory', () => {
const create = (payload: unknown) => {
const fetcher = jest
.fn()
.mockResolvedValue(new Response(JSON.stringify(payload)));
return {
a: new HermesAdapter(
{
origin: 'http://canina-hermes:9119',
token: () => Promise.resolve('secret'),
},
fetcher,
),
fetcher,
};
};
it('projects status, profiles, models and usage without raw paths, prompts or credentials', async () => {
expect(
await create({
version: 'x',
gateway_running: false,
gateway_state: null,
overall: 'degraded',
active_agents: 0,
}).a.status('seo'),
).toEqual({
version: 'x',
gateway_running: false,
gateway_state: null,
overall: 'degraded',
active_agents: 0,
});
expect(
await create({
profiles: [
{
name: 'seo',
is_default: false,
gateway_running: false,
path: '/private',
description: 'token=secret',
},
],
}).a.profiles(),
).toEqual([{ name: 'seo', is_default: false, gateway_running: false }]);
expect(
await create({
model: 'm',
provider: 'p',
effective_context_length: 0,
api_key: 'secret',
}).a.modelInfo('seo'),
).toEqual({ model: 'm', provider: 'p', effective_context_length: 0 });
expect(
await create({
providers: [
{ slug: 'p', name: 'Provider', models: ['m'], api_key: 'secret' },
],
current: { api_key: 'secret' },
}).a.modelOptions('seo'),
).toEqual([{ slug: 'p', name: 'Provider', models: ['m'] }]);
expect(
await create({
period_days: 7,
totals: {
total_input: 0,
total_output: 2,
total_sessions: 1,
total_estimated_cost: 0,
},
tools: { secret: 1 },
}).a.usage('seo', 7),
).toEqual({
period_days: 7,
totals: {
total_input: 0,
total_output: 2,
total_sessions: 1,
total_estimated_cost: 0,
},
});
});
it('uses scoped list contract and rejects unbounded queries or profile escape', async () => {
const { a, fetcher } = create({
sessions: [
{
id: 's',
profile: 'seo',
is_active: false,
source: 'cron',
title: 'secret',
},
],
total: 1,
storage: {},
});
expect(await a.sessions('seo', 20, 0)).toEqual({
sessions: [{ id: 's', profile: 'seo', is_active: false, source: 'cron' }],
total: 1,
});
expect(fetcher.mock.calls[0][0].pathname).toBe('/api/sessions');
expect(fetcher.mock.calls[0][0].searchParams.get('full')).toBe('false');
await expect(a.sessions('../escape', 20, 0)).rejects.toThrow();
await expect(a.sessions('seo', 101, 0)).rejects.toThrow();
await expect(a.usage('seo', 366)).rejects.toThrow();
await expect(
create({
sessions: [],
total: 0,
storage: { seo: 'corrupt' },
}).a.sessions('seo'),
).rejects.toThrow();
await expect(
create({
sessions: [
{ id: 's', profile: 'dev', source: 'cli', is_active: false },
],
total: 1,
}).a.sessions('seo'),
).rejects.toThrow();
});
it('lists scoped cron array; pause/resume use exact POST routes without triggers', async () => {
expect(
await create([
{ id: 'j', profile: 'seo', enabled: false, prompt: 'secret' },
]).a.crons('seo'),
).toEqual([{ id: 'j', profile: 'seo', enabled: false }]);
const { a, fetcher } = create({ id: 'j', profile: 'seo', enabled: false });
expect(await a.pauseCron('seo', 'j')).toEqual({
id: 'j',
profile: 'seo',
enabled: false,
});
expect(fetcher.mock.calls[0][0].pathname).toBe('/api/cron/jobs/j/pause');
expect(fetcher.mock.calls[0][1].method).toBe('POST');
const resume = create({ id: 'j', profile: 'seo', enabled: true });
await resume.a.resumeCron('seo', 'j');
expect(resume.fetcher.mock.calls[0][0].pathname).toBe(
'/api/cron/jobs/j/resume',
);
await expect(a.pauseCron('seo', '../trigger')).rejects.toThrow();
});
});
describe('resource budgets and safe errors', () => {
it('does not leak upstream errors or tokens and limits credential waits', async () => {
jest.useFakeTimers();
const a = new HermesAdapter({
origin: 'http://canina-hermes:9119',
token: () => new Promise(() => {}),
});
const result = expect(a.health()).rejects.toMatchObject({
code: 'UNAVAILABLE',
message: 'Hermes unavailable',
});
await jest.advanceTimersByTimeAsync(5001);
await result;
jest.useRealTimers();
});
it('caps concurrency before upstream IO', async () => {
const resolvers: ((r: Response) => void)[] = [];
const fetcher = jest.fn(
() =>
new Promise<Response>((r) => {
resolvers.push(r);
}),
);
const a = new HermesAdapter(
{
origin: 'http://canina-hermes:9119',
token: () => Promise.resolve('secret'),
},
fetcher,
);
const calls = Array.from({ length: 4 }, () => a.health());
const denied = expect(a.health()).rejects.toMatchObject({ code: 'LIMIT' });
await Promise.resolve();
await Promise.resolve();
resolvers.forEach((r) => r(new Response(JSON.stringify(health))));
await denied;
await Promise.all(calls);
});
});
@@ -0,0 +1,267 @@
export type Json =
| null
| boolean
| number
| string
| Json[]
| { [key: string]: Json };
export type Row = Record<string, Json>;
export type HermesErrorCode =
| 'CONFIGURATION'
| 'AUTH_REQUIRED'
| 'UNAVAILABLE'
| 'CONTRACT'
| 'LIMIT'
| 'FORBIDDEN'
| 'UNSUPPORTED';
export class HermesError extends Error {
constructor(readonly code: HermesErrorCode) {
super(`Hermes ${code.toLowerCase()}`);
}
}
export interface HermesConfig {
origin: string;
token: () => Promise<string>;
}
export interface Health {
ok: boolean;
version: string;
commit: string;
auth_required: boolean;
}
function object(value: unknown): Record<string, unknown> {
if (!value || typeof value !== 'object' || Array.isArray(value))
throw new HermesError('CONTRACT');
return value as Record<string, unknown>;
}
function fields(
value: unknown,
schema: Record<string, 'string' | 'boolean' | 'number'>,
): Row {
const source = object(value);
const result: Row = {};
for (const [key, type] of Object.entries(schema)) {
if (
typeof source[key] !== type ||
(type === 'number' && !Number.isFinite(source[key]))
)
throw new HermesError('CONTRACT');
result[key] = source[key] as Json;
}
return result;
}
export class HermesAdapter {
private readonly origin: string;
private inflight = 0;
constructor(
private readonly config: HermesConfig,
private readonly fetcher: typeof fetch = fetch,
) {
if (config.origin !== 'http://canina-hermes:9119')
throw new HermesError('CONFIGURATION');
this.origin = config.origin;
}
private async request(
path: string,
profile?: string,
method = 'GET',
params: Record<string, string> = {},
): Promise<unknown> {
if (
profile !== undefined &&
!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(profile)
)
throw new HermesError('FORBIDDEN');
const url = new URL(path, this.origin);
if (profile) url.searchParams.set('profile', profile);
for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
if (this.inflight >= 4) throw new HermesError('LIMIT');
this.inflight++;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 5000);
try {
const token = await Promise.race([
this.config.token(),
new Promise<never>((_, reject) =>
controller.signal.addEventListener(
'abort',
() => reject(new HermesError('UNAVAILABLE')),
{ once: true },
),
),
]);
if (!token || /[\r\n]/.test(token))
throw new HermesError('AUTH_REQUIRED');
const response = await this.fetcher(url, {
method,
headers: {
Authorization: `Bearer ${token}`,
Accept: 'application/json',
},
signal: controller.signal,
redirect: 'error',
});
if ([401, 403].includes(response.status))
throw new HermesError('AUTH_REQUIRED');
if (response.status === 404) throw new HermesError('UNSUPPORTED');
if (!response.ok) throw new HermesError('UNAVAILABLE');
if (Number(response.headers.get('content-length')) > 262144)
throw new HermesError('LIMIT');
const reader = response.body?.getReader();
if (!reader) throw new HermesError('CONTRACT');
let bytes = 0;
const chunks: Uint8Array[] = [];
try {
for (;;) {
const { done, value } = await reader.read();
if (done) break;
bytes += value.byteLength;
if (bytes > 262144) throw new HermesError('LIMIT');
chunks.push(value);
}
} finally {
await reader.cancel().catch(() => undefined);
}
return JSON.parse(Buffer.concat(chunks).toString('utf8')) as unknown;
} catch (error) {
if (error instanceof HermesError) throw error;
throw new HermesError('UNAVAILABLE');
} finally {
clearTimeout(timer);
this.inflight--;
}
}
async health(): Promise<Health> {
return fields(await this.request('/api/health'), {
ok: 'boolean',
version: 'string',
commit: 'string',
auth_required: 'boolean',
}) as unknown as Health;
}
async status(profile: string): Promise<Row> {
const raw = object(await this.request('/api/status', profile));
const row = fields(raw, {
version: 'string',
gateway_running: 'boolean',
overall: 'string',
active_agents: 'number',
});
if (raw.gateway_state !== null && typeof raw.gateway_state !== 'string')
throw new HermesError('CONTRACT');
return { ...row, gateway_state: raw.gateway_state as Json };
}
async profiles(): Promise<Row[]> {
return list(object(await this.request('/api/profiles')).profiles).map((r) =>
fields(r, {
name: 'string',
is_default: 'boolean',
gateway_running: 'boolean',
}),
);
}
async modelInfo(profile: string): Promise<Row> {
return fields(await this.request('/api/model/info', profile), {
model: 'string',
provider: 'string',
effective_context_length: 'number',
});
}
async modelOptions(profile: string): Promise<Row[]> {
return list(
object(await this.request('/api/model/options', profile)).providers,
).map((r) => {
const row = fields(r, { slug: 'string', name: 'string' });
const models = list(object(r).models);
if (models.some((m) => typeof m !== 'string'))
throw new HermesError('CONTRACT');
return { ...row, models: models as string[] };
});
}
async usage(profile: string, days = 30): Promise<Row> {
bound(days, 1, 365);
const raw = object(
await this.request('/api/analytics/usage', profile, 'GET', {
days: String(days),
}),
);
return {
...fields(raw, { period_days: 'number' }),
totals: fields(raw.totals, {
total_input: 'number',
total_output: 'number',
total_sessions: 'number',
total_estimated_cost: 'number',
}),
};
}
async sessions(profile: string, limit = 20, offset = 0): Promise<Row> {
bound(limit, 1, 100);
bound(offset, 0, 10000);
const raw = object(
await this.request('/api/sessions', profile, 'GET', {
limit: String(limit),
offset: String(offset),
full: 'false',
order: 'recent',
}),
);
if (raw.storage && Object.keys(object(raw.storage)).length)
throw new HermesError('UNAVAILABLE');
const rows = list(raw.sessions).map((r) =>
scoped(r, profile, {
id: 'string',
profile: 'string',
source: 'string',
is_active: 'boolean',
}),
);
return { ...fields(raw, { total: 'number' }), sessions: rows };
}
async crons(profile: string): Promise<Row[]> {
return list(await this.request('/api/cron/jobs', profile)).map((r) =>
scoped(r, profile, {
id: 'string',
profile: 'string',
enabled: 'boolean',
}),
);
}
private async cron(
profile: string,
id: string,
action: 'pause' | 'resume',
): Promise<Row> {
if (!/^[a-zA-Z0-9_-]{1,128}$/.test(id)) throw new HermesError('FORBIDDEN');
return scoped(
await this.request(`/api/cron/jobs/${id}/${action}`, profile, 'POST'),
profile,
{ id: 'string', profile: 'string', enabled: 'boolean' },
);
}
pauseCron(profile: string, id: string): Promise<Row> {
return this.cron(profile, id, 'pause');
}
resumeCron(profile: string, id: string): Promise<Row> {
return this.cron(profile, id, 'resume');
}
}
function list(value: unknown): unknown[] {
if (!Array.isArray(value) || value.length > 1000)
throw new HermesError('CONTRACT');
return value;
}
function bound(value: number, min: number, max: number): void {
if (!Number.isInteger(value) || value < min || value > max)
throw new HermesError('LIMIT');
}
function scoped(
value: unknown,
profile: string,
schema: Record<string, 'string' | 'boolean' | 'number'>,
): Row {
const row = fields(value, schema);
if (row.profile !== profile) throw new HermesError('FORBIDDEN');
return row;
}
@@ -0,0 +1,50 @@
import { createServer } from 'node:http';
import type { AddressInfo } from 'node:net';
import { HermesAdapter } from './hermes.adapter';
it('exercises bounded HTTP transport against an isolated server', async () => {
const seen: string[] = [];
const server = createServer((req, res) => {
seen.push(`${req.method} ${req.url}`);
if (req.headers.authorization !== 'Bearer local-test') {
res.writeHead(401).end();
return;
}
res.setHeader('Content-Type', 'application/json');
res.end(
JSON.stringify({
ok: true,
version: 'test',
commit: 'test',
auth_required: true,
api_key: 'redacted',
}),
);
});
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
try {
const port = (server.address() as AddressInfo).port;
const transport: typeof fetch = (input, init) =>
fetch(
`http://127.0.0.1:${port}${new URL(input instanceof URL ? input.href : typeof input === 'string' ? input : input.url).pathname}`,
init,
);
const adapter = new HermesAdapter(
{
origin: 'http://canina-hermes:9119',
token: () => Promise.resolve('local-test'),
},
transport,
);
expect(await adapter.health()).toEqual({
ok: true,
version: 'test',
commit: 'test',
auth_required: true,
});
expect(seen).toEqual(['GET /api/health']);
} finally {
await new Promise<void>((resolve, reject) =>
server.close((e) => (e ? reject(e) : resolve())),
);
}
});
@@ -0,0 +1,11 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"rootDir": ".",
"outDir": "../../../.hermes-contract-build",
"incremental": false,
"strict": true
},
"include": ["./*.ts"],
"exclude": []
}
@@ -0,0 +1,8 @@
import { Type } from "class-transformer";
import { IsEnum, IsHash, IsIn, IsInt, IsISO8601, IsNotEmpty, IsOptional, IsString, Max, Min } from "class-validator";
import { OperationMode, WorkflowState } from "../orchestration.domain";
export class CreateOrchestrationTaskDto { @IsString() @IsNotEmpty() key!:string; @IsString() @IsNotEmpty() title!:string; @IsString() @IsNotEmpty() department!:string; @IsEnum(OperationMode) operationMode!:OperationMode; @Type(()=>Number) @IsInt() @Min(0) budgetLimitCents!:number; @IsOptional() metadata?:Record<string,unknown>; }
export class TransitionTaskDto { @IsEnum(WorkflowState) toState!:WorkflowState; @Type(()=>Number) @IsInt() @Min(1) expectedVersion!:number; @IsString() @IsNotEmpty() idempotencyKey!:string; @IsOptional() @IsString() reason?:string; }
export class GateDecisionDto { @IsIn(["APPROVED","REJECTED"]) decision!:"APPROVED"|"REJECTED"; @Type(()=>Number) @IsInt() @Min(1) expectedVersion!:number; @IsString() @IsNotEmpty() idempotencyKey!:string; @IsISO8601() expiresAt!:string; @IsOptional() @IsString() notes?:string; @IsOptional() @IsString() runId?:string; @IsOptional() @IsHash("sha256") artifactHash?:string; @IsOptional() @IsString() commitSha?:string; @IsOptional() @IsString() environment?:string; }
export class RecordBudgetDto { @Type(()=>Number) @IsInt() @Min(1) amountCents!:number; @IsString() @IsNotEmpty() idempotencyKey!:string; @IsString() @IsNotEmpty() kind!:string; @IsOptional() metadata?:Record<string,unknown>; }
export class SetKillSwitchDto { @IsIn(["FREEZE_NEW_WORK","STOP_AGENTS","DISABLE_MUTATIONS","EMERGENCY_HALT"]) level!:string; @IsString() @IsNotEmpty() reason!:string; }
@@ -0,0 +1,24 @@
import { ForbiddenException } from "@nestjs/common";
import { KillSwitchService } from "./kill-switch.service";
describe("KillSwitchService", () => {
const prisma = { orchestrationKillSwitch: { findUnique: jest.fn() } };
const service = new KillSwitchService(prisma as never);
beforeEach(() => jest.resetAllMocks());
it.each([
["FREEZE_NEW_WORK", "CREATE_TASK"],
["STOP_AGENTS", "RUN_AGENT"],
["DISABLE_MUTATIONS", "MUTATE_PRODUCTION"],
["EMERGENCY_HALT", "OBSERVE"],
])("blocks %s at its policy boundary", async (level, action) => {
prisma.orchestrationKillSwitch.findUnique.mockResolvedValue({ scope: "GLOBAL", level, active: true });
await expect(service.assertAllowed(action as never)).rejects.toThrow(ForbiddenException);
});
it("allows observation while production mutations are disabled", async () => {
prisma.orchestrationKillSwitch.findUnique.mockResolvedValue({ scope: "GLOBAL", level: "DISABLE_MUTATIONS", active: true });
await expect(service.assertAllowed("OBSERVE")).resolves.toBeUndefined();
});
});
@@ -0,0 +1,9 @@
import { ForbiddenException, Injectable } from "@nestjs/common";
import { PrismaService } from "../prisma/prisma.service";
import { KillSwitchLevel } from "./orchestration.domain";
export type GuardedAction="CREATE_TASK"|"RUN_AGENT"|"MUTATE_PRODUCTION"|"OBSERVE";
@Injectable()
export class KillSwitchService {
constructor(private readonly prisma:PrismaService){}
async assertAllowed(action:GuardedAction):Promise<void>{ const state=await (this.prisma as any).orchestrationKillSwitch.findUnique({where:{scope:"GLOBAL"}}); if(!state?.active)return; const blocked:Record<KillSwitchLevel,GuardedAction[]>={FREEZE_NEW_WORK:["CREATE_TASK"],STOP_AGENTS:["CREATE_TASK","RUN_AGENT"],DISABLE_MUTATIONS:["CREATE_TASK","RUN_AGENT","MUTATE_PRODUCTION"],EMERGENCY_HALT:["CREATE_TASK","RUN_AGENT","MUTATE_PRODUCTION","OBSERVE"]}; if(blocked[state.level as KillSwitchLevel]?.includes(action)) throw new ForbiddenException(`Orchestration kill switch ${state.level} blocks ${action}`); }
}
@@ -0,0 +1,3 @@
import { readFileSync } from "node:fs";
import { join } from "node:path";
describe("orchestration migration safety",()=>{it("is additive and never mutates legacy governance tables",()=>{const sql=readFileSync(join(process.cwd(),"prisma/migrations/20261022000000_add_orchestration_v4_core/migration.sql"),"utf8");expect(sql).not.toMatch(/^\s*(DROP|TRUNCATE|DELETE|UPDATE)\b/im);expect(sql).not.toMatch(/ALTER TABLE "(approval_requests|department_tasks|audit_logs)"/i);expect(sql.match(/CREATE TABLE "orchestration_/g)).toHaveLength(9);});});
@@ -0,0 +1,21 @@
import { BadRequestException } from "@nestjs/common";
import { ModelTierPolicyService } from "./model-tier-policy.service";
describe("ModelTierPolicyService", () => {
const policy = new ModelTierPolicyService();
it.each([
[{ complexity: 0, risk: 0, operationMode: "OBSERVE", remainingBudgetCents: 1 }, "L0"],
[{ complexity: 2, risk: 1, operationMode: "PREPARE", remainingBudgetCents: 100 }, "L1"],
[{ complexity: 5, risk: 4, operationMode: "PREPARE", remainingBudgetCents: 500 }, "L2"],
[{ complexity: 7, risk: 7, operationMode: "PREPARE", remainingBudgetCents: 1500 }, "L3"],
[{ complexity: 9, risk: 9, operationMode: "MUTATE_PRODUCTION", remainingBudgetCents: 5000 }, "L4"],
])("selects a deterministic tier for policy inputs", (input, expected) => {
expect(policy.select(input as never)).toBe(expected);
expect(policy.select(input as never)).toBe(expected);
});
it("fails closed when the selected tier exceeds the remaining hard budget", () => {
expect(() => policy.select({ complexity: 9, risk: 9, operationMode: "MUTATE_PRODUCTION", remainingBudgetCents: 100 })).toThrow(BadRequestException);
});
});
@@ -0,0 +1,13 @@
import { BadRequestException, Injectable } from "@nestjs/common";
import { OperationMode } from "./orchestration.domain";
export type ModelTier="L0"|"L1"|"L2"|"L3"|"L4";
@Injectable()
export class ModelTierPolicyService {
select(input:{complexity:number;risk:number;operationMode:OperationMode|string;remainingBudgetCents:number}):ModelTier {
const score=Math.max(input.complexity,input.risk)+(input.operationMode===OperationMode.MUTATE_PRODUCTION?1:0);
const tier:ModelTier=score<=1?"L0":score<=3?"L1":score<=5?"L2":score<=8?"L3":"L4";
const floor:Record<ModelTier,number>={L0:1,L1:25,L2:100,L3:500,L4:2000};
if(input.remainingBudgetCents<floor[tier]) throw new BadRequestException(`Hard budget cannot fund selected model tier ${tier}`);
return tier;
}
}
@@ -0,0 +1,151 @@
import { Test } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import request from 'supertest';
import { OrchestrationController } from './orchestration.controller';
import { OrchestrationService } from './orchestration.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { RolesGuard } from '../common/guards/roles.guard';
describe('integration read boundary', () => {
let app: INestApplication;
const task = {
id: 't1',
key: 'k',
title: 'Review',
department: 'SEO',
state: 'GATE2_APPROVED',
version: 1,
operationMode: 'PREPARE',
budgetLimitCents: 0,
metadata: { token: 'secret' },
runs: [
{
id: 'r',
status: 'VERIFIED',
commitSha: 'abc',
environment: 'stage',
artifacts: [
{
id: 'a',
sha256: 'f'.repeat(64),
sizeBytes: 1n,
uri: 'secret-uri',
metadata: { token: 'secret' },
},
],
},
],
events: [
{
id: 'e',
eventType: 'CREATED',
sequence: 1,
payload: { token: 'secret' },
},
],
};
const service = {
findAll: jest.fn(() => Promise.resolve([task])),
findOne: jest.fn(() => Promise.resolve(task)),
createTask: jest.fn(),
transition: jest.fn(),
decideGate: jest.fn(),
recordBudget: jest.fn(),
setKillSwitch: jest.fn(),
};
beforeAll(async () => {
const m = await Test.createTestingModule({
controllers: [OrchestrationController],
providers: [
{ provide: OrchestrationService, useValue: service },
RolesGuard,
],
})
.overrideGuard(JwtAuthGuard)
.useValue({
canActivate(c: any) {
const req = c.switchToHttp().getRequest();
if (!req.headers.authorization) return false;
req.user = { id: 'verified-user', role: req.headers.authorization };
return true;
},
})
.compile();
app = m.createNestApplication();
await app.init();
});
afterAll(async () => app.close());
it('denies every mutation before legacy core is invoked', async () => {
for (const [method, path] of [
['post', 'tasks'],
['put', 'tasks/t1/transition'],
['post', 'tasks/t1/gates/2/decide'],
['post', 'tasks/t1/budget'],
['put', 'kill-switch'],
['post', 'chat/messages'],
] as const) {
await request(app.getHttpServer())
[method]('/admin/orchestration/' + path)
.set('Authorization', 'Admin')
.send({})
.expect(403);
}
for (const name of [
'createTask',
'transition',
'decideGate',
'recordBudget',
'setKillSwitch',
] as const)
expect(service[name]).not.toHaveBeenCalled();
});
it('projects list and detail with no actions, arbitrary secrets or BigInt transport failures', async () => {
for (const path of ['tasks', 'tasks/t1']) {
const r = await request(app.getHttpServer())
.get('/admin/orchestration/' + path)
.set('Authorization', 'Admin')
.expect(200);
const t = Array.isArray(r.body) ? r.body[0] : r.body;
expect(t.availableActions).toEqual([]);
expect(t.budgetLimitCents).toBe(0);
expect(JSON.stringify(t)).not.toMatch(/secret|sizeBytes|payload|token/);
}
});
it('returns actual inventory overview and explicit unavailable runtime resources', async () => {
const r = await request(app.getHttpServer())
.get('/admin/orchestration/overview')
.set('Authorization', 'Admin')
.expect(200);
expect(r.body.items).toEqual([
expect.objectContaining({ id: 'tasks', count: 1 }),
]);
expect(r.body.capabilities).toMatchObject({
mutations: false,
chat: false,
runtime: false,
});
for (const path of ['agents', 'schedules', 'model-policy'])
await request(app.getHttpServer())
.get('/admin/orchestration/' + path)
.set('Authorization', 'Admin')
.expect(503);
const releases = await request(app.getHttpServer())
.get('/admin/orchestration/releases')
.set('Authorization', 'Admin')
.expect(200);
expect(releases.body.items[0]).toMatchObject({
id: 'r',
commitSha: 'abc',
environment: 'stage',
});
});
it('protects read surfaces from anonymous and customer access', async () => {
await request(app.getHttpServer())
.get('/admin/orchestration/overview')
.expect(403);
await request(app.getHttpServer())
.get('/admin/orchestration/tasks')
.set('Authorization', 'CUSTOMER')
.expect(403);
});
});
@@ -0,0 +1,147 @@
import {
Controller,
Get,
Param,
Post,
Put,
UseGuards,
ForbiddenException,
ServiceUnavailableException,
} from '@nestjs/common';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { RolesGuard } from '../common/guards/roles.guard';
import { Roles } from '../common/decorators/roles.decorator';
import { OrchestrationService } from './orchestration.service';
// Explicit response allowlists: never serialize arbitrary JSON, signatures, URIs or BigInt.
function pick(row: any, keys: string[]) {
return Object.fromEntries(
keys.filter((k) => row[k] !== undefined).map((k) => [k, row[k]]),
);
}
function project(row: any) {
return {
...pick(row, [
'id',
'key',
'title',
'department',
'state',
'version',
'operationMode',
'budgetLimitCents',
]),
availableActions: [],
runs: (row.runs ?? []).map((run: any) => ({
...pick(run, ['id', 'commitSha', 'environment', 'status']),
artifacts: (run.artifacts ?? []).map((a: any) =>
pick(a, ['id', 'kind', 'sha256']),
),
})),
decisions: (row.decisions ?? []).map((d: any) =>
pick(d, [
'id',
'gate',
'decision',
'expiresAt',
'runId',
'artifactHash',
'commitSha',
'environment',
'createdAt',
]),
),
events: (row.events ?? []).map((e: any) =>
pick(e, [
'id',
'eventType',
'fromState',
'toState',
'sequence',
'createdAt',
]),
),
budgetLedger: (row.budgetLedger ?? []).map((b: any) =>
pick(b, ['id', 'amountCents', 'kind', 'createdAt']),
),
};
}
@ApiTags('Admin - Orchestration v4')
@ApiBearerAuth()
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('Admin', 'SUPER_ADMIN')
@Controller('admin/orchestration')
export class OrchestrationController {
constructor(private readonly service: OrchestrationService) {}
@Get('tasks') async all() {
return (await this.service.findAll()).map(project);
}
@Get('tasks/:id') async one(@Param('id') id: string) {
return project(await this.service.findOne(id));
}
@Get('overview') async overview() {
const tasks = await this.service.findAll();
return {
items: [
{ id: 'tasks', title: 'Persisted task inventory', count: tasks.length },
],
measuredAt: new Date().toISOString(),
capabilities: { mutations: false, chat: false, runtime: false },
reason: 'security_hardening_pending',
};
}
@Get('releases') async releases() {
const tasks = await this.service.findAll();
const details = await Promise.all(
tasks.map((t: any) => this.service.findOne(t.id)),
);
return {
items: details.flatMap((t: any) =>
(t.runs ?? []).map((run: any) =>
pick(run, ['id', 'status', 'commitSha', 'environment']),
),
),
measuredAt: new Date().toISOString(),
};
}
@Get('agents') agents() {
throw new ServiceUnavailableException(
'Hermes runtime unavailable: trusted identity and runtime authentication not configured',
);
}
@Get('schedules') schedules() {
throw new ServiceUnavailableException(
'Hermes schedules unavailable; runtime remains disabled',
);
}
@Get('model-policy') models() {
throw new ServiceUnavailableException(
'No persisted model policy read contract available',
);
}
// The committed legacy core is not safe to expose. No env switch or role may bypass this boundary.
@Post('tasks') create() {
return this.deny();
}
@Put('tasks/:id/transition') transition() {
return this.deny();
}
@Post('tasks/:id/gates/:gate/decide') decide() {
return this.deny();
}
@Post('tasks/:id/budget') budget() {
return this.deny();
}
@Put('kill-switch') kill() {
return this.deny();
}
@Post('chat/messages') chat() {
return this.deny();
}
private deny(): never {
throw new ForbiddenException(
'Orchestration mutations and chat disabled pending hardened core and trusted runtime integration',
);
}
}
@@ -0,0 +1,24 @@
import { BadRequestException, ConflictException, ForbiddenException } from "@nestjs/common";
import { assertTransition, nextStateForGateDecision, OperationMode, WorkflowState } from "./orchestration.domain";
describe("orchestration domain", () => {
it("allows only declared workflow transitions", () => {
expect(() => assertTransition(WorkflowState.DRAFT, WorkflowState.GATE1_PENDING)).not.toThrow();
expect(() => assertTransition(WorkflowState.DRAFT, WorkflowState.RUNNING)).toThrow(BadRequestException);
});
it("keeps gate 1 as execution authorization rather than release authorization", () => {
expect(nextStateForGateDecision(1, "APPROVED")).toBe(WorkflowState.GATE1_APPROVED);
expect(nextStateForGateDecision(2, "APPROVED")).toBe(WorkflowState.GATE2_APPROVED);
});
it("rejects an unsupported gate decision", () => {
expect(() => nextStateForGateDecision(1, "PENDING" as never)).toThrow(BadRequestException);
});
it("classifies production mutation separately from observe and prepare", () => {
expect(OperationMode.OBSERVE).toBe("OBSERVE");
expect(OperationMode.PREPARE).toBe("PREPARE");
expect(OperationMode.MUTATE_PRODUCTION).toBe("MUTATE_PRODUCTION");
});
});
@@ -0,0 +1,12 @@
import { BadRequestException } from "@nestjs/common";
export enum WorkflowState { DRAFT="DRAFT", GATE1_PENDING="GATE1_PENDING", GATE1_APPROVED="GATE1_APPROVED", READY="READY", CLAIMED="CLAIMED", RUNNING="RUNNING", VERIFYING="VERIFYING", GATE2_PENDING="GATE2_PENDING", GATE2_APPROVED="GATE2_APPROVED", RELEASING="RELEASING", PRODUCTION_VERIFYING="PRODUCTION_VERIFYING", LIVE_VERIFIED="LIVE_VERIFIED", MEASURING="MEASURING", CLOSED="CLOSED", REJECTED="REJECTED", BLOCKED="BLOCKED", CANCELLED="CANCELLED", FAILED="FAILED", EXPIRED="EXPIRED" }
export enum OperationMode { OBSERVE="OBSERVE", PREPARE="PREPARE", MUTATE_PRODUCTION="MUTATE_PRODUCTION" }
export enum RetryClass { TRANSIENT="TRANSIENT", RATE_LIMITED="RATE_LIMITED", DEPENDENCY="DEPENDENCY", VALIDATION="VALIDATION", POLICY="POLICY", PERMANENT="PERMANENT" }
export enum KillSwitchLevel { FREEZE_NEW_WORK="FREEZE_NEW_WORK", STOP_AGENTS="STOP_AGENTS", DISABLE_MUTATIONS="DISABLE_MUTATIONS", EMERGENCY_HALT="EMERGENCY_HALT" }
const transitions: Record<WorkflowState, WorkflowState[]> = {
DRAFT:[WorkflowState.GATE1_PENDING,WorkflowState.CANCELLED], GATE1_PENDING:[WorkflowState.GATE1_APPROVED,WorkflowState.REJECTED,WorkflowState.EXPIRED], GATE1_APPROVED:[WorkflowState.READY,WorkflowState.CANCELLED], READY:[WorkflowState.CLAIMED,WorkflowState.BLOCKED,WorkflowState.CANCELLED], CLAIMED:[WorkflowState.RUNNING,WorkflowState.READY,WorkflowState.CANCELLED], RUNNING:[WorkflowState.VERIFYING,WorkflowState.FAILED,WorkflowState.BLOCKED], VERIFYING:[WorkflowState.GATE2_PENDING,WorkflowState.FAILED,WorkflowState.RUNNING], GATE2_PENDING:[WorkflowState.GATE2_APPROVED,WorkflowState.REJECTED,WorkflowState.EXPIRED], GATE2_APPROVED:[WorkflowState.RELEASING,WorkflowState.CANCELLED], RELEASING:[WorkflowState.PRODUCTION_VERIFYING,WorkflowState.FAILED], PRODUCTION_VERIFYING:[WorkflowState.LIVE_VERIFIED,WorkflowState.FAILED], LIVE_VERIFIED:[WorkflowState.MEASURING,WorkflowState.CLOSED], MEASURING:[WorkflowState.CLOSED,WorkflowState.FAILED], CLOSED:[], REJECTED:[], BLOCKED:[WorkflowState.READY,WorkflowState.CANCELLED], CANCELLED:[], FAILED:[WorkflowState.READY,WorkflowState.CANCELLED], EXPIRED:[WorkflowState.GATE1_PENDING,WorkflowState.GATE2_PENDING,WorkflowState.CANCELLED]
};
export function assertTransition(from: WorkflowState, to: WorkflowState): void { if (!transitions[from]?.includes(to)) throw new BadRequestException(`Invalid orchestration transition ${from} -> ${to}`); }
export function nextStateForGateDecision(gate: 1|2, decision: "APPROVED"|"REJECTED"): WorkflowState { if (!(["APPROVED","REJECTED"] as string[]).includes(decision)) throw new BadRequestException("Decision must be APPROVED or REJECTED"); return decision === "REJECTED" ? WorkflowState.REJECTED : gate === 1 ? WorkflowState.GATE1_APPROVED : WorkflowState.GATE2_APPROVED; }
@@ -0,0 +1,2 @@
import { Module } from "@nestjs/common"; import { PrismaModule } from "../prisma/prisma.module"; import { KillSwitchService } from "./kill-switch.service"; import { ModelTierPolicyService } from "./model-tier-policy.service"; import { OrchestrationController } from "./orchestration.controller"; import { OrchestrationService } from "./orchestration.service";
@Module({imports:[PrismaModule],controllers:[OrchestrationController],providers:[OrchestrationService,KillSwitchService,ModelTierPolicyService],exports:[OrchestrationService,KillSwitchService,ModelTierPolicyService]}) export class OrchestrationModule{}
@@ -0,0 +1,73 @@
import { BadRequestException, ConflictException, ForbiddenException } from "@nestjs/common";
import { OrchestrationService } from "./orchestration.service";
function mockPrisma() {
const tx: any = {
orchestrationTask: { findUnique: jest.fn(), create: jest.fn(), updateMany: jest.fn() },
orchestrationRun: { findUnique: jest.fn(), create: jest.fn() },
orchestrationArtifact: { findFirst: jest.fn(), create: jest.fn() },
orchestrationAttestation: { create: jest.fn() },
orchestrationApprovalDecision: { findUnique: jest.fn(), create: jest.fn() },
orchestrationEvent: { create: jest.fn() },
orchestrationBudgetLedger: { aggregate: jest.fn(), create: jest.fn() },
orchestrationKillSwitch: { findUnique: jest.fn(), upsert: jest.fn() },
};
tx.$transaction = jest.fn(async (cb: any) => cb(tx));
return tx;
}
describe("OrchestrationService", () => {
let prisma: any;
let service: OrchestrationService;
beforeEach(() => { prisma = mockPrisma(); service = new OrchestrationService(prisma, { assertAllowed: jest.fn() } as never); });
it("creates a task and append-only event transactionally", async () => {
prisma.orchestrationTask.create.mockResolvedValue({ id: "task-1", state: "DRAFT", version: 1 });
const result = await service.createTask({ key: "seo-1", title: "SEO", department: "SEO", operationMode: "PREPARE" as never, budgetLimitCents: 1000 }, "actor-1");
expect(prisma.$transaction).toHaveBeenCalledTimes(1);
expect(prisma.orchestrationTask.create).toHaveBeenCalledWith({ data: expect.objectContaining({ state: "DRAFT", version: 1 }) });
expect(prisma.orchestrationEvent.create).toHaveBeenCalledWith({ data: expect.objectContaining({ eventType: "TASK_CREATED", sequence: 1 }) });
expect(result.id).toBe("task-1");
});
it("uses compare-and-swap versioning for transitions", async () => {
prisma.orchestrationTask.findUnique.mockResolvedValue({ id: "task-1", state: "DRAFT", version: 3 });
prisma.orchestrationTask.updateMany.mockResolvedValue({ count: 0 });
await expect(service.transition("task-1", { toState: "GATE1_PENDING" as never, expectedVersion: 3, idempotencyKey: "i-1" }, "actor")).rejects.toThrow(ConflictException);
});
it("makes gate decisions immutable and idempotent", async () => {
prisma.orchestrationApprovalDecision.findUnique.mockResolvedValue({ id: "d1", decision: "APPROVED", gate: 1, taskId: "task-1" });
await expect(service.decideGate("task-1", 1, { decision: "APPROVED", expectedVersion: 2, idempotencyKey: "gate-1", expiresAt: new Date(Date.now()+10000).toISOString() }, "ceo")).resolves.toMatchObject({ id: "d1" });
expect(prisma.orchestrationApprovalDecision.create).not.toHaveBeenCalled();
});
it("rejects an expired approval", async () => {
await expect(service.decideGate("task-1", 1, { decision: "APPROVED", expectedVersion: 2, idempotencyKey: "gate-expired", expiresAt: new Date(0).toISOString() }, "ceo")).rejects.toThrow(BadRequestException);
});
it("binds gate 2 approval to run, artifact hash, commit and environment", async () => {
prisma.orchestrationApprovalDecision.findUnique.mockResolvedValue(null);
prisma.orchestrationTask.findUnique.mockResolvedValue({ id: "task-1", state: "GATE2_PENDING", version: 7 });
prisma.orchestrationRun.findUnique.mockResolvedValue({ id: "run-1", taskId: "task-1", commitSha: "abc123", environment: "staging" });
prisma.orchestrationArtifact.findFirst.mockResolvedValue({ id: "artifact-1", runId: "run-1", sha256: "f".repeat(64) });
prisma.orchestrationTask.updateMany.mockResolvedValue({ count: 1 });
prisma.orchestrationApprovalDecision.create.mockResolvedValue({ id: "decision-2", gate: 2 });
await service.decideGate("task-1", 2, { decision: "APPROVED", expectedVersion: 7, idempotencyKey: "gate-2", expiresAt: new Date(Date.now()+10000).toISOString(), runId: "run-1", artifactHash: "f".repeat(64), commitSha: "abc123", environment: "staging" }, "ceo");
expect(prisma.orchestrationApprovalDecision.create).toHaveBeenCalledWith({ data: expect.objectContaining({ runId: "run-1", artifactHash: "f".repeat(64), commitSha: "abc123", environment: "staging" }) });
});
it("refuses gate 2 when binding does not match the immutable run", async () => {
prisma.orchestrationApprovalDecision.findUnique.mockResolvedValue(null);
prisma.orchestrationTask.findUnique.mockResolvedValue({ id: "task-1", state: "GATE2_PENDING", version: 7 });
prisma.orchestrationRun.findUnique.mockResolvedValue({ id: "run-1", taskId: "task-1", commitSha: "real", environment: "staging" });
await expect(service.decideGate("task-1", 2, { decision: "APPROVED", expectedVersion: 7, idempotencyKey: "gate-bad", expiresAt: new Date(Date.now()+10000).toISOString(), runId: "run-1", artifactHash: "f".repeat(64), commitSha: "wrong", environment: "staging" }, "ceo")).rejects.toThrow(ForbiddenException);
});
it("enforces hard task budget atomically", async () => {
prisma.orchestrationTask.findUnique.mockResolvedValue({ id: "task-1", budgetLimitCents: 1000 });
prisma.orchestrationBudgetLedger.aggregate.mockResolvedValue({ _sum: { amountCents: 900 } });
await expect(service.recordBudget("task-1", { amountCents: 101, idempotencyKey: "cost-1", kind: "MODEL" }, "agent")).rejects.toThrow(ForbiddenException);
expect(prisma.orchestrationBudgetLedger.create).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,17 @@
import { BadRequestException, ConflictException, ForbiddenException, Injectable, NotFoundException } from "@nestjs/common";
import { PrismaService } from "../prisma/prisma.service";
import { CreateOrchestrationTaskDto, GateDecisionDto, RecordBudgetDto, TransitionTaskDto } from "./dto/orchestration.dto";
import { assertTransition, nextStateForGateDecision, OperationMode, WorkflowState } from "./orchestration.domain";
import { KillSwitchService } from "./kill-switch.service";
@Injectable()
export class OrchestrationService {
constructor(private readonly prisma:PrismaService,private readonly killSwitch:KillSwitchService){}
async createTask(dto:CreateOrchestrationTaskDto,actorId:string){ await this.killSwitch.assertAllowed("CREATE_TASK"); return (this.prisma as any).$transaction(async(tx:any)=>{const task=await tx.orchestrationTask.create({data:{key:dto.key,title:dto.title,department:dto.department,operationMode:dto.operationMode,budgetLimitCents:dto.budgetLimitCents,metadata:dto.metadata??{},state:WorkflowState.DRAFT,version:1}});await tx.orchestrationEvent.create({data:{taskId:task.id,eventType:"TASK_CREATED",fromState:null,toState:WorkflowState.DRAFT,sequence:1,actorId,payload:{key:dto.key}}});return task;}); }
async transition(id:string,dto:TransitionTaskDto,actorId:string){return (this.prisma as any).$transaction(async(tx:any)=>{const existing=await tx.orchestrationTask.findUnique({where:{id}});if(!existing)throw new NotFoundException(`Orchestration task ${id} not found`);assertTransition(existing.state,dto.toState);if(existing.operationMode===OperationMode.MUTATE_PRODUCTION&&dto.toState===WorkflowState.RELEASING)await this.killSwitch.assertAllowed("MUTATE_PRODUCTION");const changed=await tx.orchestrationTask.updateMany({where:{id,version:dto.expectedVersion,state:existing.state},data:{state:dto.toState,version:{increment:1}}});if(changed.count!==1)throw new ConflictException("Task version or state changed; reload before retrying");await tx.orchestrationEvent.create({data:{taskId:id,eventType:"STATE_TRANSITION",fromState:existing.state,toState:dto.toState,sequence:dto.expectedVersion+1,actorId,idempotencyKey:dto.idempotencyKey,payload:{reason:dto.reason??null}}});return {...existing,state:dto.toState,version:dto.expectedVersion+1};});}
async decideGate(taskId:string,gate:1|2,dto:GateDecisionDto,actorId:string){if(new Date(dto.expiresAt)<=new Date())throw new BadRequestException("Approval decision has expired");return (this.prisma as any).$transaction(async(tx:any)=>{const prior=await tx.orchestrationApprovalDecision.findUnique({where:{idempotencyKey:dto.idempotencyKey}});if(prior){if(prior.taskId!==taskId||prior.gate!==gate||prior.decision!==dto.decision)throw new ConflictException("Idempotency key already belongs to another approval decision");return prior;}const task=await tx.orchestrationTask.findUnique({where:{id:taskId}});if(!task)throw new NotFoundException(`Orchestration task ${taskId} not found`);const expected=gate===1?WorkflowState.GATE1_PENDING:WorkflowState.GATE2_PENDING;if(task.state!==expected)throw new ConflictException(`Gate ${gate} requires ${expected}`);if(gate===2&&dto.decision==="APPROVED"){if(!dto.runId||!dto.artifactHash||!dto.commitSha||!dto.environment)throw new BadRequestException("Gate 2 requires runId, artifactHash, commitSha and environment");const run=await tx.orchestrationRun.findUnique({where:{id:dto.runId}});if(!run||run.taskId!==taskId||run.commitSha!==dto.commitSha||run.environment!==dto.environment)throw new ForbiddenException("Gate 2 binding does not match immutable run");const artifact=await tx.orchestrationArtifact.findFirst({where:{runId:dto.runId,sha256:dto.artifactHash}});if(!artifact)throw new ForbiddenException("Gate 2 artifact hash is not registered for run");}
const next=nextStateForGateDecision(gate,dto.decision);const changed=await tx.orchestrationTask.updateMany({where:{id:taskId,version:dto.expectedVersion,state:expected},data:{state:next,version:{increment:1}}});if(changed.count!==1)throw new ConflictException("Task version or state changed; approval not applied");const decision=await tx.orchestrationApprovalDecision.create({data:{taskId,gate,decision:dto.decision,actorId,notes:dto.notes,expiresAt:new Date(dto.expiresAt),idempotencyKey:dto.idempotencyKey,runId:dto.runId,artifactHash:dto.artifactHash,commitSha:dto.commitSha,environment:dto.environment}});await tx.orchestrationEvent.create({data:{taskId,eventType:`GATE${gate}_${dto.decision}`,fromState:expected,toState:next,sequence:dto.expectedVersion+1,actorId,idempotencyKey:`event:${dto.idempotencyKey}`,payload:{decisionId:decision.id}}});return decision;});}
async recordBudget(taskId:string,dto:RecordBudgetDto,actorId:string){return (this.prisma as any).$transaction(async(tx:any)=>{const task=await tx.orchestrationTask.findUnique({where:{id:taskId}});if(!task)throw new NotFoundException(`Orchestration task ${taskId} not found`);const sum=await tx.orchestrationBudgetLedger.aggregate({where:{taskId},_sum:{amountCents:true}});if((sum._sum.amountCents??0)+dto.amountCents>task.budgetLimitCents)throw new ForbiddenException("Hard task budget exceeded");return tx.orchestrationBudgetLedger.create({data:{taskId,amountCents:dto.amountCents,kind:dto.kind,idempotencyKey:dto.idempotencyKey,actorId,metadata:dto.metadata??{}}});});}
async findAll(){return (this.prisma as any).orchestrationTask.findMany({orderBy:{createdAt:"desc"}})}
async findOne(id:string){const task=await (this.prisma as any).orchestrationTask.findUnique({where:{id},include:{runs:{include:{artifacts:true,attestations:true}},dependencies:true,decisions:true,events:{orderBy:{sequence:"asc"}},budgetLedger:true}});if(!task)throw new NotFoundException(`Orchestration task ${id} not found`);return task;}
async setKillSwitch(level:string,reason:string,actorId:string){return (this.prisma as any).$transaction(async(tx:any)=>{const value=await tx.orchestrationKillSwitch.upsert({where:{scope:"GLOBAL"},create:{scope:"GLOBAL",level,active:true,reason,actorId},update:{level,active:true,reason,actorId,version:{increment:1}}});await tx.orchestrationEvent.create({data:{eventType:"KILL_SWITCH_CHANGED",sequence:value.version??1,actorId,payload:{scope:"GLOBAL",level,reason}}});return value;});}
}
+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();});
+69
View File
@@ -0,0 +1,69 @@
# Orchestration v4: Hermes runtime seam (review-only)
## Installed evidence / compatibility
Read-only inspection of `canina-hermes` source at `/opt/hermes` and Docker metadata:
- Running image ID: `sha256:373ddd5e6649f525b17993e1c885cdf1352127f8e98fd329140a73237125e52f`.
- Registry digest (pinned template): `nousresearch/hermes-agent@sha256:9774f4f39a9bb8c2f68ce728ed5e99ddbad282163be56764afacf88ed952b784`.
- Current command is `gateway run`, **not** `serve`. Loopback 9119 connection refused. This implementation does not claim a live dashboard integration or start one.
- Existing `/opt/data` mount is external volume `canina-hermes_canina_hermes_data`; preserve it. Read-only cron JSON count: **17 jobs, 0 enabled**. Paused state is `enabled:false`, not a `paused` boolean. No cron/runtime/config mutation was made.
- Existing untracked `/opt/services/ai/canina-hermes/compose.yml` remains untouched.
Sources inspected: `hermes_cli/web_routers/{status,profiles,models,sessions,analytics,cron,chat_ws}.py`, cron scoping helpers, `cron/jobs.py`, `hermes_cli/inventory.py`, `hermes_cli/dashboard_auth/{routes,middleware}.py`, `hermes_cli/web_server{,_chat}.py`, `tui_gateway/ws.py`.
## Supported allowlist
| Service method | Installed upstream contract | Public projection |
|---|---|---|
| health | GET /api/health | ok/version/commit/auth_required |
| status | GET /api/status?profile= | version/gateway_running/gateway_state/overall/active_agents |
| profiles | GET /api/profiles -> {profiles:[]} | name/is_default/gateway_running, filtered by backend scope |
| modelInfo | GET /api/model/info?profile= | model/provider/effective_context_length |
| modelOptions | GET /api/model/options?profile= | provider slug/name + model ID strings |
| usage | GET /api/analytics/usage?profile=&days= | period_days and four numeric totals |
| sessions | GET /api/sessions?profile=&limit=&offset=&full=false&order=recent | ID/profile/source/is_active, total |
| crons | GET /api/cron/jobs?profile= -> array | ID/profile/enabled |
| pauseCron | POST /api/cron/jobs/{id}/pause?profile= | ID/profile/enabled |
| resumeCron | POST /api/cron/jobs/{id}/resume?profile= | implemented adapter; **disabled in registered service** |
No generic route/HTTP/RPC proxy. No model setter, config, secrets, PTY, trigger, deletion, raw transcript or raw logs. Status is not fabricated if unavailable. Numeric nulls/malformed/missing required fields produce CONTRACT (some empty analytics stores may therefore be unavailable). Unknown upstream fields are dropped, never forwarded; this is intentional forward-compatible redaction, not raw JSON passthrough. Scope mismatch is forbidden. Arrays cap at 1000, upstream bytes at 256 KiB, in-flight requests at 4, whole request/token budget at 5 seconds, no retries, redirects forbidden. The production fetch honors AbortSignal. Error messages never include upstream response/URL/token/exception. Do not log request headers or config objects.
Upstream GET /api/sessions can auto-archive internally; we inspected source only and did not call it against production. Some model inventory endpoints warm caches/probe providers. Classify these as managed reads, not guaranteed filesystem-pure operations.
## Authentication and WS discovery
- Non-loopback dashboard binds engage the provider-verified auth gate. REST supports provider-verified Bearer session tokens. Legacy loopback accepts session header/Bearer; **a Canina JWT or API_SERVER_KEY is not interchangeable**.
- POST `/api/auth/ws-ticket` needs verified `request.state.session`; response `{ticket,ttl_seconds}` is single-use / 30 seconds. Do not mint tickets for a browser or copy credentials into browser URLs.
- Installed WS: `/api/ws`, `/api/console`, `/api/events`, `/api/pub`, `/api/pty`; **no assumed `/api/chat/ws`**.
- `/api/ws` uses newline-delimited JSON-RPC and `gateway.ready`; same dispatcher as TUI, broad privilege. Gated admission supports a ticket, including subprotocols `hermes-gateway-v1` and `hermes-gateway-ticket.<ticket>`; legacy process token is rejected in gated mode. Internal process credentials must never be extracted.
- We deliberately do not bridge a powerful socket without a verified session/run ownership and event allowlist contract. `chat`/`control` return UNSUPPORTED after policy; event dispatch returns FORBIDDEN even with policy approval. No WS dependency, background connection, reconnect, or ticket endpoint is exposed.
## Wiring (owner integration step, no app.module.ts changes here)
Import `HermesManagementModule.register(config, authorizer)` in the owning backend module, then inject **HermesIntegrationService**, never the adapter into browser controllers. Registration exports the service only and defaults to deny-all policy. Example configuration:
```ts
HermesManagementModule.register({
origin: 'http://canina-hermes:9119',
token: () => secretStore.read('hermes_dashboard_access_token'),
}, backendRuntimeAuthorizer)
```
Supply a provider-verified, short-lived Hermes token through backend secret storage (template references `/run/secrets/hermes_dashboard_access_token` only). Provision/refresh is an operator responsibility; this change neither extracts existing runtime secrets nor invents a login flow. No token in database/UI/env templates.
Controllers must verify Canina admin JWT, resolve subject/profile scopes from trusted backend data (not request DTO), enforce permission and rate limit/audit, translate HermesError codes to safe API errors (AUTH_REQUIRED/UNAVAILABLE -> 503, FORBIDDEN ->403, LIMIT ->429, CONTRACT/UNSUPPORTED ->502/501). Never forward upstream errors. `RuntimePrincipal` is an internal context, not a user input DTO. Authorizer must independently verify subject/action/profile. Missing/throwing authorizer denies. Registered module hard-disables resume; enabling requires an explicit reviewed code change. Resume can immediately make overdue recurring jobs due: never test it on production.
## Disabled event dispatch design
No listener, cron, poller, outbox consumer or webhook is registered. A future dispatcher must use backend-verified event identity, durable outbox and idempotency, server-resolved department/profile/run ownership, permission per action, payload minimization/redaction, budget and approval policy. Then use a tested narrow execution transport; never map arbitrary event text to TUI RPC or `/api/pub`. Unknown event/schema/principal/approval/ownership -> reject with no IO. Do not enable before isolated acceptance proves interruption, stream bounds and safe tool-output projection.
## Manifests and verification
`infra/hermes-runtime/compose.template.yml` is **not a deployable replacement yet**: manual-only profile, no automatic restart/public ports/socket/credentials, preserves external data volume, dedicated external backend network. It intentionally retains `gateway run`; dashboard/auth/network topology and gateway egress need an approved migration design. Do not run alongside current service sharing the same writable state. Never `down -v`.
`.gitea/workflows/hermes-runtime-contract.yml` is manual contract review only, no deploy job, SSH, runtime secret or event dispatch. Existing deploy workflow untouched. Compose parsed with `docker compose ... config --quiet`; no containers deployed.
Tests: `cd backend && npm test -- --runInBand hermes-management` (14 assertions across 4 suites); strict isolated typecheck/build `npx tsc -p src/hermes-management/tsconfig.contract.json [--noEmit]`; full backend `npm run build` after isolated `npx prisma generate`. All passed. Local HTTP transport is exercised on ephemeral loopback, not production. TDD failures were observed for missing adapter, inventory methods, integration service, module and concurrency limit before implementations. No live authenticated dashboard or WS execution was exercised. Host has no Node; disposable node:22-bookworm runners used. Initial shared dependency resolution and offline Prisma binary download failed; fresh worktree dependencies and isolated network-enabled Prisma generation resolved them, without DB connection/migration.
Final verification: full backend Jest regression **93 suites / 771 tests passed**; scoped ESLint and strict typecheck passed, full `tsc -b` build passed. Existing SSL/payment negative tests print expected error logs despite passing. No deploy or production action performed.
@@ -0,0 +1,22 @@
# Orchestration v4 read-only integration verification
Base e5c83e87fe2d52d06eb36532fa9e354570678c43 plus cherry-picks admin a34c2a9, runtime bd58cc4, router b0f4636. Separate remote worktree; no dirty core edits, pushes, deploys, DB access or runtime changes.
## RED → GREEN proof
- New backend HTTP boundary suite initially failed 4/4: mutation returned 201, BigInt serialization returned 500, overview missing (404). After integration: 4/4 pass, covering all mutation routes, anonymous/customer rejection, secret projection, actual overview and unavailable resources.
- New UI fail-closed capability test initially failed because Create bounded work was visible without authorization. After capability gating: 7/7 command-center tests pass. Existing explicit action/binding/retry tests retained.
## Disposable remote validation
Node 22 bookworm, network none, userns host (host Docker remapping prevents normal bind mounts), worktree source mounts, read-only sibling dependency cache. Vite cache directories are ephemeral tmpfs; no existing dependency trees changed.
- Backend focused aggregate: **13 suites, 65 tests pass** (orchestration, Hermes, router usage).
- Backend `tsc --noEmit`: exit 0. `npm run build`: exit 0.
- Backend changed controller/HTTP spec ESLint: exit 0, 8 unsafe-argument warnings (7 test harness, 1 existing any-typed Prisma result). Baseline subsystem lint had 256 errors/8 warnings largely inherited formatting; no full lint pass claimed.
- Admin focused aggregate: **5 files, 19 tests pass** (command center, orchestration/router adapters, creation, navigation).
- Admin `npm run build`: exit 0, existing unresolved font warning remains.
- Admin `tsc --noEmit -p tsconfig.app.json`: exit 2 with **33 inherited diagnostics** outside this change: legacy Approvals/Audit/HQ/Dashboard/ManagerActions/Tasks unused imports, Orders requiresRx missing, Symptoms ConfirmModal props/unused setter. No changed-file diagnostics. Full admin typecheck is NOT green.
## Security/release blockers
The committed legacy core permits gate-state bypass through generic transitions and lacks hardened replay/authorization/budget/kill-switch boundaries. It is retained unchanged for parent integration; every exposed v4 mutation is unconditionally denied by controller. Do not restore controller calls or enable execution until hardened core is merged and reverified.
Runtime dashboard not listening per parent investigation; no fabricated health or live availability claim. No trusted runtime identity/profile policy or runtime auth configured. Chat, cron mutations, execution/event dispatch, release execution stay disabled. Read-only inventory still requires orchestration schema migration through approved CI/CD, never manual DB changes. Backend read queries are currently full inventory and release evidence uses per-task reads; pagination/scaling remains future work.
Parent must inspect this commit and reconcile hardened core before any mutation milestone. No Stage promotion performed by this worker; admin typecheck failures remain explicit verification blockers for parent decision.
+44
View File
@@ -0,0 +1,44 @@
# Stage v4 rollout safety
## Scope and deployment boundary
Only a push to `develop` followed by the existing Gitea workflow may roll out this change. Do not run `deploy.sh` manually. Its CI marker is an accident guard, not an authentication boundary: runner permissions remain the security boundary. `main`, unknown branches and the former `stage-backend-only` bypass fail before Docker operations. Production is intentionally blocked pending separate review; no silent baseline/resolve is permitted.
## Tracked sequence
1. Acquire the Stage rollout lock (same lock as the retired backend-only path).
2. Fetch the branch and build images using the existing workflow. Build failure leaves old applications running.
3. Stop Stage frontend and backend (maintenance/outage; no promise of a custom 503 page).
4. Run the newly built backend image as an isolated one-off Prisma CLI job (`compose run --rm --no-deps --entrypoint ... migrate deploy`). No app command, published service ports or automatic baseline. Existing DB must already be running.
5. Only on migration success start backend. Require all nine v4 tables, the successful tracked migration receipt and an actual HTTP catalog response with the catalog envelope. HTTP acceptance has bounded retries and timeouts; no response body is logged.
6. On backend acceptance failure stop both applications and fail. Only after acceptance start frontend. CI success marker follows these gates. The shared support bot is not rebuilt/replaced by this Stage rollout.
Migration failure leaves maintenance in place; do not auto-restart old apps against a partly migrated schema. Diagnose from CI logs, restore from an authorized backup or ship a reviewed forward fix through CI/CD. Never `db push`, seed, silently `migrate resolve`, or manually apply live DDL.
## Verification (2026-10-22)
Strict RED/GREEN cycles captured missing rollout function, migration failure ordering, missing backend acceptance and missing CI/Production guard before implementation. `python3 scripts/tests/test_stage_rollout.py`: 3 passed. Shell tests simulate Docker failures to prove sequencing only; they do NOT certify a healthy release. `node --test scripts/tests/test_rollout_health.cjs`: 4 passed using a local HTTP server (503, HTML, incorrect envelope rejected; valid empty catalog shape accepted). These fixtures are not live health evidence.
`python3 scripts/tests/rehearse_rollout.py` performs only schema-only `pg_dump` and migration-history-only data dump from Stage. It restores into a fresh PostgreSQL 16 container with no network, no host ports, no persistent volume, and no customer rows. Prisma runs in that disposable container's network namespace using an existing generated v4 client/dependencies read-only from the core test worktree. Dumps have a private temporary directory and are removed on exit.
Observed output:
```
Applying migration `20261022000000_add_orchestration_v4_core`
All migrations have been successfully applied.
No pending migrations to apply.
PASS: actual Prisma legacy catalog/support and v4 relation queries
Restored 61 legacy tables; all business tables empty
PASS: unchanged legacy column definitions; 61 legacy queries; 9 v4 tables; migrate deploy repeatable
Disposable database/container removed; no live DDL performed
```
The first rehearsal hit a read-only nested mount creation error, cleaned up, and was corrected to mount only `prisma/` plus dependencies; subsequent rehearsals passed.
## Remaining acceptance constraints
- No push, actual deployment, live DDL, customer export, or Production change was performed. No live v4 health success is claimed.
- Schema-only rehearsal proves schema/query compatibility, not row-volume performance, locks under traffic, or business-data backfill behavior. All 61 legacy business tables were verified empty.
- Full image build/start and public frontend/admin/API acceptance still require the authorized CI rollout. The gate currently covers backend schema/catalog; frontend start success is not browser acceptance.
- Existing workflow downloads branch-tip script and resets target checkout to branch-tip, rather than pinning a triggering SHA. This pre-existing provenance limitation needs a separate reviewed workflow change before strong release attestation.
- Existing compose credentials are out of scope; no new credentials are added. Continue restricting runner access and runtime env files. Orchestration mutation/chat/runtime remain disabled in the integration base; this rollout does not enable them.
+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.
@@ -0,0 +1,46 @@
# Integration milestone: read-only v4
This integration supersedes mutation/chat expectations below. All orchestration POST/PUT routes return 403 **before calling legacy services**, including task creation, transitions, gate decisions, budget writes, kill-switch and chat. No feature flag can enable them. `availableActions` is always `[]`. Do not enable mutation controls until hardened core is merged and independently verified.
GET `/admin/orchestration/overview` returns `{items:[{id:"tasks",title:"Persisted task inventory",count:number}], measuredAt, capabilities:{mutations:false,chat:false,runtime:false},reason:"security_hardening_pending"}`. The timestamp describes this DB inventory observation, not runtime health. Frontend capability fetch defaults to all false on failure or missing fields.
GET tasks and detail use explicit allowlists: task identity/state/version/mode/budget; run identity/status/commit/environment; artifact identity/kind/hash; decision identity/gate/decision/expiry/bindings; event identity/type/states/sequence/time; ledger identity/amount/kind/time. Arbitrary metadata, notes, event payloads, artifact URI/signature and BigInt size are not exposed. Scope/acceptance metadata remains withheld pending a reviewed structured schema.
GET `/releases` is persisted run evidence only, not a claim of release authorization or deployment. GET `/agents`, `/schedules`, `/model-policy` return 503 with explicit unavailable reasons: there are no trusted runtime identity/auth or persisted model policy read contracts. HermesManagementModule is registered deny-all with an empty token and no HTTP controllers; no runtime calls or cron changes occur. RouterUsageModule is registered with its admin-protected read-only endpoint and returns unavailable when credentials are absent. No new secrets are configured.
## Historical component contract (mutation proposals disabled)
# Admin orchestration v4 adapter contract
All client traffic uses existing authenticated Axios client (`src/services/api.ts`). Relative `/admin/...` paths are served below `/api`. No runtime secrets, Hermes tokens, PTY, terminal websocket or direct gateway credentials may enter these DTOs. Backend must project/redact task metadata, artifacts, audit payloads and chat text before returning them. Browser does not enforce authorization.
## Implemented core API observed in sibling core worktree
- GET `/admin/orchestration/tasks`: bare Task[] or `{success:true,data:Task[]}`.
- GET `/admin/orchestration/tasks/:id`: immutable task detail with runs/artifacts, decisions, events and budgetLedger.
- POST `/admin/orchestration/tasks`: key,title,department,operationMode,budgetLimitCents,metadata {scope,acceptanceCriteria[]} (no execution authorization).
- PUT `/admin/orchestration/tasks/:id/transition`: toState,expectedVersion,idempotencyKey,reason.
- POST `/admin/orchestration/tasks/:id/gates/{1|2}/decide`: decision,expectedVersion,idempotencyKey,expiresAt,notes. Gate2 APPROVED additionally binds runId,artifactHash,commitSha,environment to registered immutable run and artifact.
- PUT `/admin/orchestration/kill-switch`: level,reason. Levels FREEZE_NEW_WORK,STOP_AGENTS,DISABLE_MUTATIONS,EMERGENCY_HALT. No invented reset/resume route.
Task fields and optional service DTOs are declared in `src/services/orchestration.ts`.
## Required integration additions (fail closed until backend provides)
Task `availableActions: {id,label,toState?,gate?:1|2,decision?:APPROVED|REJECTED,disabledReason?}[]` must be advertised by backend after permission, state, gate, policy and kill-switch evaluation. Browser never derives transitions from state. Missing actions means read-only, not an invitation to synthesize controls. Backend core inspected initially did not advertise these actions. This is an integration blocker for execution.
Optional read-only resources GET `/admin/orchestration/{agents|model-policy|schedules|releases}` return `{items:[{id,title?,status?,department?,readiness?,model?,budgetLimitCents?,spentCents?,cron?,timezone?,environment?,commitSha?,reason?}],measuredAt:ISO8601}`. May be wrapped in `{success:true,data:...}`. 404/403/network/malformed replies render unavailable, not mock cards. These endpoint contracts are proposals requiring backend reconciliation, not claims that endpoints exist. Schedule editing, model policy editing, budget adjustments, agent start/stop and release execution require separately advertised typed backend commands; intentionally not implemented against guessed routes. Existing task run/evidence, decisions, ledger and ordered events remain inspectable independent of optional feeds.
POST `/admin/orchestration/chat/messages`: {sessionId,message,idempotencyKey} -> {id,role:'assistant',content}. Advisory-only bridge; no browser runtime connection or auto-execution of text. Backend must bind sessions to authenticated user and redact sensitive output.
## Retry and concurrency
Command dialog snapshots immutable task version and allocates one key. On first attempt inputs lock; failed retries use identical payload/key. Cancel and refresh to reconcile 409 conflict; refresh invalidates selection and dialog. Successful command refetches authoritative tasks; no optimistic status. Backend must enforce idempotency transactionally, compare payload bindings and versions; frontend is not a safety boundary. Task creation is keyed by unique business key; reconcile ambiguous failures by refreshing before retry.
## 9router usage concrete contract (aligned with backend worker b0f4636)
GET `/admin/router-usage?period=today|24h|7d|30d|60d|all` default7d; authenticated admin. Response: source,period,status available|unavailable,reason,data null|{totals,providers[],models[],accounts[]},freshness {retrievedAt,sourceUpdatedAt,stale},attribution {scope:9router_total,hermes:null,additive:false}.
Metrics: requests,inputTokens,outputTokens,cacheReadTokens,cacheWriteTokens,reasoningTokens,errors. Last three unsupported=null. Account quota {status:unknown,remaining:null,resetAt:null,reason:upstream_quota_get_mutates_credentials}. No upstream quota GET because it refreshes credentials. No estimates or raw credentials. Nullable provider/model/account IDs are sanitized by backend.
Breakdowns overlap and are never summed. Hermes attribution unknown, not zero and not added. Retrieved timestamp is not source freshness. SourceUpdatedAt and stale remain explicitly unknown. Frontend explicitly projects DTO fields and rejects malformed/unavailable replies. No direct gateway connection.
## Monitoring
Existing payment stats/health and SMS credit are read independently. Only returned values displayed. Request failures remain unknown with source and client observation timestamp. Database/Redis/Post/OCR/uptime/environment/agent runtime remain unknown without measured endpoints. No fabricated 14-day uptime, Production label, derived DB ping, SMS count or healthy post service.
## Verification caveats
All verification uses disposable node:22-bookworm Docker runners against this worktree. Plain `npm run typecheck` uses solution-style config and does not verify app files. `tsc --noEmit -p tsconfig.app.json` exposes pre-existing errors in legacy Approvals/Audit/HQ/Tasks imports and Orders/Symptoms types; report these separately, not as a green full application typecheck. Build warning: unresolved existing Shabnam font remains runtime-resolved.
@@ -0,0 +1,21 @@
# Verification and remaining integration work
Remote branch: feature/orchestration-v4-admin. All source changes limited to frontend/admin-panel. No push, deployment, production container command, or live operational mutation performed.
Disposable node:22-bookworm runners, --userns=host:
- Full `vitest run --maxWorkers=2`: 57 files, 326 tests passed, zero failed.
- Scoped ESLint for all new services/components/tests plus Monitoring: exit 0.
- `npm run typecheck` (solution config): exit 0, not an app check.
- `tsc --noEmit -p tsconfig.app.json`: exit 2, 33 pre-existing diagnostics (legacy unused imports/locals, Orders requiresRx type, Symptoms ConfirmModal props). No diagnostics in new files or Monitoring. Baseline captured before implementation had same legacy errors.
- `npm run build`: exit 0; pre-existing unresolved Shabnam font warning.
TDD red/green cycles exercised adapter missing exports, unadvertised actions, incomplete/expired Gate2 bindings, exact version/idempotency payloads and retry lock, task creation bounds, UI explicit confirmation, monitoring fake values and failures, navigation, router usage contract migration/unavailable state. Full UI tests use mocked HTTP boundary with realistic backend DTOs; they are not a live backend integration test. Additional UI tests cover immutable artifact binding, kill authorization failure, readiness BLOCKED response, chat escaping and typed bridge. Router usage aligned to concrete backend b0f4636 contract.
Remaining gaps / do not claim full end-to-end operation:
- Backend must advertise availableActions. Initial core worktree lacks them; client intentionally fails closed read-only without actions.
- Agents/model-policy/schedules/releases snapshots and typed chat bridge are proposed contracts, not initially present core routes. UI displays explicit unavailable errors, never synthetic content. Mutating model policy/schedules/agent operations not implemented against guessed endpoints.
- Kill switch current level cannot be read until backend exposes a status contract. No invented resume command.
- No live auth credentials used; endpoint auth/RBAC and cross-worker DTO integration still need isolated stack smoke tests.
- Legacy Approvals/Tasks/HQ/Audit pages remain separately available and unchanged. New v4 control center is at /orchestration inside existing protected layout; these legacy pages are not v4 authority and should be retired/migrated during integration.
- Full app typecheck is not green due existing errors listed above.
- Browser chat is advisory; no Hermes terminal or raw runtime connection.
+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"
}
}
}
@@ -0,0 +1,14 @@
import {fireEvent,render,screen} from '@testing-library/react';
import {it,expect,vi} from 'vitest';
import api from '../services/api';
import CreateOrchestrationTask from './CreateOrchestrationTask';
vi.mock('../services/api',()=>({default:{post:vi.fn()}}));
it('submits explicit bounded scope and acceptance criteria, only after valid input',async()=>{
vi.mocked(api.post).mockResolvedValue({data:{id:'new'}});const done=vi.fn();render(<CreateOrchestrationTask onCreated={done}/>);
expect(screen.getByRole('button',{name:'Create bounded task'})).toBeDisabled();
for(const [label,value] of Object.entries({'Task key':'audit-1','Title':'Audit schema','Department':'SEO','Bounded scope':'Staging schema audit only','Acceptance criteria (one per line)':'Report all failures','Budget cap in cents':'500'}))fireEvent.change(screen.getByLabelText(label),{target:{value}});
fireEvent.click(screen.getByRole('button',{name:'Create bounded task'}));
await screen.findByText('Task created by backend.');
expect(api.post).toHaveBeenCalledWith('/admin/orchestration/tasks',expect.objectContaining({operationMode:'PREPARE',budgetLimitCents:500,metadata:{scope:'Staging schema audit only',acceptanceCriteria:['Report all failures']}}));
expect(done).toHaveBeenCalledOnce();
});
@@ -0,0 +1,14 @@
import {useState} from 'react';
import Button from './ui/Button';
import {orchestration} from '../services/orchestration';
import type {CreateTaskInput} from '../services/orchestration';
export default function CreateOrchestrationTask({onCreated}:{onCreated:()=>void}){
const [fields,setFields]=useState({key:'',title:'',department:'',scope:'',criteria:'',budget:''});
const [mode,setMode]=useState<CreateTaskInput['operationMode']>('PREPARE');const [busy,setBusy]=useState(false);const [error,setError]=useState('');const [success,setSuccess]=useState('');
const valid=Object.values(fields).every(value=>value.trim())&&Number.isSafeInteger(Number(fields.budget))&&Number(fields.budget)>=0;
return <details className="bg-white border rounded-2xl p-5"><summary className="font-bold cursor-pointer">Create bounded work</summary><form className="space-y-3 mt-4" onSubmit={async e=>{e.preventDefault();if(!valid||busy)return;setBusy(true);setError('');setSuccess('');try{await orchestration.create({key:fields.key,title:fields.title,department:fields.department,operationMode:mode,budgetLimitCents:Number(fields.budget),metadata:{scope:fields.scope,acceptanceCriteria:fields.criteria.split('\n').map(s=>s.trim()).filter(Boolean)}});setSuccess('Task created by backend.');onCreated()}catch(error){setError(error instanceof Error?error.message:'Create failed; reconcile task key before retry')}finally{setBusy(false)}}}>
{([['key','Task key'],['title','Title'],['department','Department'],['scope','Bounded scope'],['criteria','Acceptance criteria (one per line)'],['budget','Budget cap in cents']] as const).map(([key,label])=><label key={key} className="block">{label}<textarea aria-label={label} disabled={busy} required value={fields[key]} onChange={e=>setFields(prev=>({...prev,[key]:e.target.value}))} className="block border p-2 w-full rounded-lg"/></label>)}
<label>Operation mode<select aria-label="Operation mode" value={mode} disabled={busy} onChange={e=>setMode(e.target.value as CreateTaskInput['operationMode'])}>{['OBSERVE','PREPARE','MUTATE_PRODUCTION'].map(m=><option key={m}>{m}</option>)}</select></label><p>Creation does not authorize work. Gate1 is a separate immutable decision.</p>
{error&&<p role="alert">{error}</p>}{success&&<p role="status">{success}</p>}<Button type="submit" disabled={!valid||busy}>Create bounded task</Button>
</form></details>;
}
@@ -0,0 +1,9 @@
import { render,screen } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { it,expect,vi } from 'vitest';
import Sidebar from './Sidebar';
vi.mock('../services/api',()=>({default:{get:vi.fn().mockResolvedValue({data:{success:true,data:{}}})}}));
it('exposes command center inside existing authenticated navigation',async()=>{
render(<MemoryRouter initialEntries={['/orchestration']}><Sidebar isOpen setIsOpen={vi.fn()}/></MemoryRouter>);
expect(await screen.findByRole('link',{name:'Orchestration command center'})).toHaveAttribute('href','/orchestration');
});
@@ -0,0 +1,19 @@
import {useEffect,useState} from 'react';
import Button from './ui/Button';
import {routerUsage,usagePeriods} from '../services/routerUsage';
import type {RouterUsageSnapshot,UsageCounters,UsagePeriod} from '../services/routerUsage';
const shown=(value:unknown)=>value===null||value===undefined?'Unknown — not reported':String(value);
function Counters({data}:{data:UsageCounters|null}) {return <dl className="grid grid-cols-2 gap-2">{(['requests','inputTokens','outputTokens','cacheReadTokens','cacheWriteTokens','reasoningTokens','errors'] as const).map(key=><div key={key}><dt>{key}</dt><dd>{shown(data?.[key])}</dd></div>)}</dl>}
export default function RouterUsagePanel(){
const [data,setData]=useState<RouterUsageSnapshot|null>(null);const [error,setError]=useState('');const [revision,setRevision]=useState(0);const [loading,setLoading]=useState(false);const [period,setPeriod]=useState<UsagePeriod>('7d');
useEffect(()=>{let active=true;setLoading(true);setError('');setData(null);routerUsage.snapshot(period).then(value=>{if(active)setData(value)}).catch(e=>{if(active)setError(e instanceof Error?e.message:'Usage unavailable')}).finally(()=>{if(active)setLoading(false)});return()=>{active=false}},[revision,period]);
return <section className="bg-white border rounded-2xl p-5 space-y-4"><header className="flex justify-between"><h2 className="font-bold">9router usage & provider-reported quota</h2><Button disabled={loading} onClick={()=>setRevision(n=>n+1)}>Refresh usage</Button></header>
<label>Usage period<select aria-label="Usage period" value={period} onChange={e=>setPeriod(e.target.value as UsagePeriod)}>{usagePeriods.map(p=><option key={p}>{p}</option>)}</select></label>
<p>Gateway totals include all clients. Provider/model/account breakdowns overlap; never add them together. Cache/reasoning counters may overlap token counts. No derived totals or quota estimates.</p>
<p>Hermes attribution: Unknown — not reported; do not add to gateway totals.</p>
{loading&&<p role="status">Loading gateway usage…</p>}{error&&<p role="alert">Unknown / unavailable: {error}</p>}
{data&&<><dl><dt>Source</dt><dd>{data.source}</dd><dt>Retrieved at (not source freshness)</dt><dd>{shown(data.freshness.retrievedAt)}</dd><dt>Source updated at</dt><dd>{shown(data.freshness.sourceUpdatedAt)}</dd><dt>Stale</dt><dd>{shown(data.freshness.stale)}</dd><dt>Reported period</dt><dd>{data.period}</dd></dl><article className="border p-4 rounded-xl"><h3>Gateway totals (includes Hermes)</h3><Counters data={data.data.totals}/></article>
{(['providers','models','accounts'] as const).map(group=><section key={group}><h3 className="font-bold">{group}</h3>{!data.data[group].length&&<p>No {group} reported.</p>}<div className="grid md:grid-cols-2 gap-4">{data.data[group].map((row,i)=><article key={i} className="border p-4 rounded-xl"><h4>{shown(row.provider)} · {shown(row.model)}</h4>{row.accountId&&<p>{row.accountId}</p>}<Counters data={row}/>{group==='accounts'&&<dl><dt>Provider-reported quota remaining</dt><dd>{shown(row.quota?.remaining)}</dd><dt>Provider-reported quota reset</dt><dd>{shown(row.quota?.resetAt)}</dd><dt>Quota availability reason</dt><dd>{shown(row.quota?.reason)}</dd></dl>}</article>)}</div></section>)}
<p>Quota is unknown: upstream quota GET refreshes credentials, so this read-only adapter does not call it.</p></>}
</section>;
}
@@ -117,7 +117,10 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side
title: 'حاکمیت، تاییدات و وظایف',
icon: CheckSquare,
items: [
{ icon: CheckSquare, label: 'کارتابل تاییدات مدیریت', path: '/approvals' },
{ icon: Building2, label: 'Orchestration command center', path: '/orchestration' },
{ 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 +160,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>
);
}
@@ -2,17 +2,30 @@ import { act,fireEvent,render,screen } from '@testing-library/react';
import { afterEach,beforeEach,describe,expect,it,vi } from 'vitest';
import api from '../services/api';
import MonitoringPage from './MonitoringPage';
vi.mock('../services/api', () => ({ default: { get: vi.fn(), patch: vi.fn(), put: vi.fn(), post: vi.fn() } }));
vi.mock('react-hot-toast', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
describe('MonitoringPage', () => {
beforeEach(() => { vi.resetAllMocks(); vi.mocked(api.get).mockImplementation(async (url) => ({ data: url === '/payment/admin/stats' ? { todayVolume: '125000', todayVerified: 4, successRate: 0 } : url === '/payment/admin/health' ? { status: 'ONLINE', latencyMs: 250 } : { credit: 0 } })); });
afterEach(() => vi.useRealTimers());
const load = async () => { render(<MonitoringPage />); await screen.findByText('1 رویداد ثبت شده'); };
it('renders real volume and preserves zero success rate and SMS balance', async () => { await load(); expect(screen.getByText('۱۲۵٬۰۰۰ تومان')).toBeInTheDocument(); expect(screen.getByText('0%')).toBeInTheDocument(); expect(screen.getAllByText(/۰ پیامک/).length).toBeGreaterThan(0); });
it('shows offline gateway and SMS on rejected endpoints instead of false healthy states', async () => { vi.mocked(api.get).mockRejectedValue(new Error('offline')); await load(); expect(screen.getAllByText('غیرفعال / قطعی')).toHaveLength(2); expect(screen.queryByText('98.4%')).not.toBeInTheDocument(); });
it('honors explicit offline health response even when latency is low', async () => { vi.mocked(api.get).mockImplementation(async (url) => ({ data: url.includes('health') ? { status: 'OFFLINE', latencyMs: 10 } : { credit: 12 } })); await load(); expect(screen.getByText('غیرفعال / قطعی')).toBeInTheDocument(); });
it('shows slow gateway warning and refreshes all three read-only endpoints', async () => { vi.mocked(api.get).mockImplementation(async (url) => ({ data: url.includes('health') ? { latencyMs: 2000 } : { credit: 12 } })); await load(); expect(screen.getByText('کاهش سرعت / هشدار')).toBeInTheDocument(); fireEvent.click(screen.getByRole('button', { name: /بروزرسانی زنده/ })); await screen.findByText('2 رویداد ثبت شده'); expect(api.get).toHaveBeenCalledTimes(6); expect(api.post).not.toHaveBeenCalled(); });
it('polls after 30 seconds and cleans timer on unmount', async () => { vi.useFakeTimers(); const view = render(<MonitoringPage />); await act(async () => { await Promise.resolve(); }); expect(api.get).toHaveBeenCalledTimes(3); for (let i=0; i<30; i++) await act(async () => { vi.advanceTimersByTime(1000); }); expect(api.get).toHaveBeenCalledTimes(6); view.unmount(); await act(async () => { vi.advanceTimersByTime(60000); }); expect(api.get).toHaveBeenCalledTimes(6); });
vi.mock('../services/api',()=>({default:{get:vi.fn()}}));
describe('measured monitoring',()=>{
beforeEach(()=>{vi.resetAllMocks();vi.mocked(api.get).mockImplementation(async url=>({data:url.includes('/stats')?{todayVolume:0,todayVerified:0,successRate:0}:url.includes('/health')?{status:'ONLINE',latencyMs:0}:{credit:0}}))});
afterEach(()=>vi.useRealTimers());
it('preserves measured zero but never manufactures database health, post latency, uptime or environment',async()=>{
render(<MonitoringPage/>);await screen.findByText('0%');
expect(screen.getByText('0 ms')).toBeInTheDocument();
expect(screen.getByText('۰ پیامک')).toBeInTheDocument();
expect(screen.getByText('Database: Unknown — no measured endpoint')).toBeInTheDocument();
expect(screen.getByText('Environment: Unknown — no measured endpoint')).toBeInTheDocument();
expect(screen.queryByText('Production')).not.toBeInTheDocument();
expect(screen.queryByText(/۱۴ روز/)).not.toBeInTheDocument();
});
it('marks failures unknown rather than online and permits measured refresh',async()=>{
vi.mocked(api.get).mockRejectedValue(new Error('connection refused'));
render(<MonitoringPage/>);expect(await screen.findAllByText(/connection refused/)).toHaveLength(3);
expect(screen.queryByText('ONLINE')).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button',{name:'Refresh measurements'}));
await screen.findAllByText(/connection refused/);expect(api.get).toHaveBeenCalledTimes(6);
});
it('polls and cancels on unmount',async()=>{
vi.useFakeTimers();const view=render(<MonitoringPage/>);await act(async()=>{});
expect(api.get).toHaveBeenCalledTimes(3);
await act(async()=>{vi.advanceTimersByTime(30000)});expect(api.get).toHaveBeenCalledTimes(6);
view.unmount();await act(async()=>{vi.advanceTimersByTime(60000)});expect(api.get).toHaveBeenCalledTimes(6);
});
});
+27 -360
View File
@@ -1,364 +1,31 @@
import {
Activity,
CheckCircle2,
Clock,
CreditCard,
Database,
FileText,
MessageSquare,
RefreshCw,
Truck
} from 'lucide-react';
import { useCallback,useEffect,useState } from 'react';
import { toast } from 'react-hot-toast';
import Badge from '../components/ui/Badge';
import { useCallback, useEffect, useRef, useState } from 'react';
import Button from '../components/ui/Button';
import Skeleton from '../components/ui/Skeleton';
import api from '../services/api';
interface MonitoringStats {
timestamp: string;
zibal: {
status: 'ONLINE' | 'DEGRADED' | 'OFFLINE';
latencyMs: number;
merchantId?: string;
todayVolumeTomans: number;
todayTxCount: number;
successRate: number;
};
melipayamak: {
status: 'ONLINE' | 'DEGRADED' | 'OFFLINE';
credit: number | string;
latencyMs: number;
todaySmsSent: number;
patternActive: boolean;
};
post: {
status: 'ONLINE' | 'DEGRADED' | 'OFFLINE';
latencyMs: number;
trackingActive: boolean;
};
system: {
backendStatus: 'HEALTHY' | 'DEGRADED';
dbStatus: 'CONNECTED' | 'DISCONNECTED';
dbLatencyMs: number;
uptimeSeconds: number;
environment: string;
};
}
type Measurement = {data:Record<string,unknown>|null;error:string|null;observedAt:string};
const endpoints = ['/payment/admin/stats','/payment/admin/health','/settings/sms/credit'] as const;
const value=(v:unknown,suffix='') => v===null||v===undefined ? 'Unknown — not measured' : String(v)+suffix;
export default function MonitoringPage() {
const [stats, setStats] = useState<MonitoringStats | null>(null);
const [, setIsLoading] = useState(true);
const [isRefreshing, setIsRefreshing] = useState(false);
const [autoRefresh] = useState(true);
const [refreshInterval] = useState(30); // seconds
const [countdown, setCountdown] = useState(30);
const [logs, setLogs] = useState<any[]>([]);
const fetchMonitoringData = useCallback(async (silent = false) => {
try {
if (!silent) setIsRefreshing(true);
const startTime = Date.now();
// Parallel real queries to live endpoints
const [txStatsRes, healthRes, smsRes] = await Promise.allSettled([
api.get('/payment/admin/stats').catch(() => ({ data: null })),
api.get('/payment/admin/health').catch(() => ({ data: null })),
api.get('/settings/sms/credit').catch(() => ({ data: null })),
]);
const roundTripMs = Date.now() - startTime;
const txStats = txStatsRes.status === 'fulfilled' ? txStatsRes.value?.data : null;
const health = healthRes.status === 'fulfilled' ? healthRes.value?.data : null;
const sms = smsRes.status === 'fulfilled' ? smsRes.value?.data : null;
const smsCreditVal = typeof sms === 'object' && sms !== null ? sms.credit ?? sms.balance ?? sms.data : sms;
const newStats: MonitoringStats = {
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,
merchantId: health?.activeMerchant || health?.merchantId || 'zibal-live-merchant',
todayVolumeTomans: txStats?.todayVolume ? Math.floor(Number(txStats.todayVolume)) : 0,
todayTxCount: txStats?.todayVerified || txStats?.verifiedCount || 0,
successRate: txStats?.successRate ?? 0,
},
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,
todaySmsSent: 48,
patternActive: true,
},
post: {
status: 'ONLINE',
latencyMs: Math.floor(Math.random() * 110) + 140,
trackingActive: true,
},
system: {
backendStatus: 'HEALTHY',
dbStatus: 'CONNECTED',
dbLatencyMs: Math.max(12, roundTripMs - 120),
uptimeSeconds: 86400 * 14 + 3600 * 5,
environment: 'Production',
},
};
setStats(newStats);
// Append live log
setLogs((prev) => [
{
id: Date.now(),
time: new Date().toLocaleTimeString('fa-IR'),
service: 'HealthCheck',
type: 'INFO',
message: `پایش بلادرنگ انجام شد. زیبال: ${newStats.zibal.latencyMs}ms | پیامک: ${newStats.melipayamak.credit} | سیستم: ${newStats.system.dbLatencyMs}ms`,
},
...prev.slice(0, 19),
]);
} catch (e) {
console.error('Failed to load monitoring data', e);
if (!silent) toast.error('خطا در دریافت وضعیت سرور و سرویس‌های واسط');
} finally {
setIsLoading(false);
setIsRefreshing(false);
setCountdown(refreshInterval);
}
}, [refreshInterval]);
useEffect(() => {
fetchMonitoringData();
}, [fetchMonitoringData]);
// Auto-refresh countdown ticker
useEffect(() => {
if (!autoRefresh) return;
const interval = setInterval(() => {
setCountdown((prev) => {
if (prev <= 1) {
fetchMonitoringData(true);
return refreshInterval;
}
return prev - 1;
});
}, 1000);
return () => clearInterval(interval);
}, [autoRefresh, refreshInterval, fetchMonitoringData]);
const getStatusBadge = (status: 'ONLINE' | 'DEGRADED' | 'OFFLINE' | 'HEALTHY' | 'CONNECTED' | 'DISCONNECTED') => {
switch (status) {
case 'ONLINE':
case 'HEALTHY':
case 'CONNECTED':
return <Badge variant="success" size="sm">آنلاین و فعال</Badge>;
case 'DEGRADED':
return <Badge variant="warning" size="sm">کاهش سرعت / هشدار</Badge>;
case 'OFFLINE':
case 'DISCONNECTED':
return <Badge variant="danger" size="sm">غیرفعال / قطعی</Badge>;
default:
return <Badge variant="slate" size="sm">نامشخص</Badge>;
}
};
return (
<div className="space-y-6 font-vazir pb-12" dir="rtl">
{/* Top Action Header */}
<div className="bg-white p-5 sm:p-6 rounded-3xl border border-gray-100 shadow-xs flex flex-col md:flex-row md:items-center justify-between gap-4">
<div className="flex items-center gap-3.5">
<div className="w-12 h-12 rounded-2xl bg-gradient-to-tr from-purple-600 to-indigo-600 text-white flex items-center justify-center shadow-lg shadow-purple-500/20 shrink-0">
<Activity className="w-6 h-6 animate-pulse" />
</div>
<div>
<h1 className="text-xl font-black text-gray-900 flex items-center gap-2">
مرکز مانیتورینگ بلادرنگ سیستم و درگاه‌ها
<span className="w-2.5 h-2.5 rounded-full bg-emerald-500 animate-ping inline-block" />
</h1>
<p className="text-xs text-gray-500 font-medium mt-1">
پایش آنلاین وضعیت اتصالات بانکی زیبال، سامانه پیامک ملی‌پیامک، وب‌سرویس پستی و دیتابیس
</p>
</div>
</div>
<div className="flex items-center gap-2.5 self-end md:self-center">
<div className="flex items-center gap-2 bg-gray-50 border border-gray-200 px-3 py-1.5 rounded-2xl text-xs font-bold text-gray-600">
<Clock className="w-3.5 h-3.5 text-purple-600" />
<span>بروزرسانی بعدی: {countdown} ثانیه</span>
</div>
<Button
variant="outline"
size="sm"
startIcon={RefreshCw}
isLoading={isRefreshing}
onClick={() => fetchMonitoringData(false)}
>
بروزرسانی زنده
</Button>
</div>
</div>
{/* Main Service Cards Grid */}
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4">
{/* Zibal Payment Gateway */}
<div className="bg-white p-5 rounded-3xl border border-gray-100 shadow-xs space-y-4 hover:border-purple-200 transition-all">
<div className="flex items-center justify-between">
<div className="w-10 h-10 rounded-2xl bg-blue-50 text-blue-600 flex items-center justify-center">
<CreditCard className="w-5 h-5" />
</div>
{stats ? getStatusBadge(stats.zibal.status) : <Skeleton className="w-16 h-6 rounded-full" />}
</div>
<div>
<h3 className="font-black text-gray-900 text-sm">درگاه پرداخت زیبال (شاپرک)</h3>
<p className="text-[11px] text-gray-400 font-medium">سرویس پرداخت و استرداد آنلاین</p>
</div>
<div className="bg-gray-50 p-3.5 rounded-2xl space-y-2 text-xs">
<div className="flex justify-between">
<span className="text-gray-500">تاخیر پاسخگویی (Latency):</span>
<span className="font-mono font-black text-blue-600">{stats?.zibal.latencyMs || 142} ms</span>
</div>
<div className="flex justify-between">
<span className="text-gray-500">حجم تراکنش‌های امروز:</span>
<span className="font-mono font-bold text-gray-900">{stats ? `${stats.zibal.todayVolumeTomans.toLocaleString('fa-IR')} تومان` : '...'}</span>
</div>
<div className="flex justify-between">
<span className="text-gray-500">درصد موفقیت (Success Rate):</span>
<span className="font-mono font-bold text-emerald-600">{stats?.zibal.successRate ?? 0}%</span>
</div>
</div>
</div>
{/* Melipayamak SMS Gateway */}
<div className="bg-white p-5 rounded-3xl border border-gray-100 shadow-xs space-y-4 hover:border-purple-200 transition-all">
<div className="flex items-center justify-between">
<div className="w-10 h-10 rounded-2xl bg-emerald-50 text-emerald-600 flex items-center justify-center">
<MessageSquare className="w-5 h-5" />
</div>
{stats ? getStatusBadge(stats.melipayamak.status) : <Skeleton className="w-16 h-6 rounded-full" />}
</div>
<div>
<h3 className="font-black text-gray-900 text-sm">سامانه پیامک (ملی‌پیامک)</h3>
<p className="text-[11px] text-gray-400 font-medium">ارسال پترن کد تایید و لاگ وضعیت سفارش</p>
</div>
<div className="bg-gray-50 p-3.5 rounded-2xl space-y-2 text-xs">
<div className="flex justify-between">
<span className="text-gray-500">موجودی پنل:</span>
<span className="font-mono font-black text-emerald-700">{stats?.melipayamak.credit || '...'}</span>
</div>
<div className="flex justify-between">
<span className="text-gray-500">تاخیر وب‌سرویس SOAP:</span>
<span className="font-mono font-black text-emerald-600">{stats?.melipayamak.latencyMs || 88} ms</span>
</div>
<div className="flex justify-between">
<span className="text-gray-500">ارسال‌های امروز:</span>
<span className="font-mono font-bold text-gray-900">{stats?.melipayamak.todaySmsSent || 48} پیامک</span>
</div>
</div>
</div>
{/* Postal Tracking Service */}
<div className="bg-white p-5 rounded-3xl border border-gray-100 shadow-xs space-y-4 hover:border-purple-200 transition-all">
<div className="flex items-center justify-between">
<div className="w-10 h-10 rounded-2xl bg-amber-50 text-amber-600 flex items-center justify-center">
<Truck className="w-5 h-5" />
</div>
{stats ? getStatusBadge(stats.post.status) : <Skeleton className="w-16 h-6 rounded-full" />}
</div>
<div>
<h3 className="font-black text-gray-900 text-sm">سامانه رهگیری پستی و تیپاکس</h3>
<p className="text-[11px] text-gray-400 font-medium">استعلام آنلاین وضعیت بارنامه و مرسولات</p>
</div>
<div className="bg-gray-50 p-3.5 rounded-2xl space-y-2 text-xs">
<div className="flex justify-between">
<span className="text-gray-500">وضعیت اتصال:</span>
<span className="font-bold text-amber-700">برقرار و فعال</span>
</div>
<div className="flex justify-between">
<span className="text-gray-500">پاسخگویی سرور پست:</span>
<span className="font-mono font-black text-amber-600">{stats?.post.latencyMs || 155} ms</span>
</div>
<div className="flex justify-between">
<span className="text-gray-500">سرویس بارکدخوان:</span>
<span className="font-bold text-emerald-600">فعال (OCR / Text)</span>
</div>
</div>
</div>
{/* Database & Core System */}
<div className="bg-white p-5 rounded-3xl border border-gray-100 shadow-xs space-y-4 hover:border-purple-200 transition-all">
<div className="flex items-center justify-between">
<div className="w-10 h-10 rounded-2xl bg-purple-50 text-purple-600 flex items-center justify-center">
<Database className="w-5 h-5" />
</div>
{stats ? getStatusBadge(stats.system.dbStatus) : <Skeleton className="w-16 h-6 rounded-full" />}
</div>
<div>
<h3 className="font-black text-gray-900 text-sm">پایگاه داده و سرور اصلی</h3>
<p className="text-[11px] text-gray-400 font-medium">PostgreSQL / Redis Cache</p>
</div>
<div className="bg-gray-50 p-3.5 rounded-2xl space-y-2 text-xs">
<div className="flex justify-between">
<span className="text-gray-500">پینگ دیتابیس:</span>
<span className="font-mono font-black text-purple-600">{stats?.system.dbLatencyMs || 18} ms</span>
</div>
<div className="flex justify-between">
<span className="text-gray-500">محیط استقرار:</span>
<span className="font-bold text-gray-900">{stats?.system.environment || 'Production'}</span>
</div>
<div className="flex justify-between">
<span className="text-gray-500">آپتایم سرور:</span>
<span className="font-mono font-bold text-emerald-600">۱۴ روز و ۵ ساعت</span>
</div>
</div>
</div>
</div>
{/* Live Activity & Inspection Feed */}
<div className="bg-white rounded-3xl p-6 border border-gray-100 shadow-xs space-y-4">
<div className="flex items-center justify-between border-b border-gray-100 pb-4">
<h3 className="font-black text-gray-900 text-sm flex items-center gap-2">
<FileText className="w-4 h-4 text-purple-600" />
لاگ بلادرنگ بررسی سلامت سرویس‌ها (Live Health Inspection Log)
</h3>
<span className="text-xs text-gray-400 font-bold">{logs.length} رویداد ثبت شده</span>
</div>
<div className="space-y-2 overflow-x-auto">
{logs.length === 0 ? (
<div className="text-center py-6 text-xs text-gray-400">در حال دریافت لاگ‌های زنده...</div>
) : (
logs.map((log) => (
<div
key={log.id}
className="flex items-center justify-between p-3 rounded-2xl bg-gray-50 border border-gray-100 text-xs gap-3"
>
<div className="flex items-center gap-3">
<span className="font-mono font-bold text-gray-400">{log.time}</span>
<Badge variant="blue" size="sm">{log.service}</Badge>
<span className="font-medium text-gray-700">{log.message}</span>
</div>
<span className="font-bold text-emerald-600 flex items-center gap-1 shrink-0">
<CheckCircle2 className="w-3.5 h-3.5" />
موفق
</span>
</div>
))
)}
</div>
</div>
</div>
);
const [measurements,setMeasurements]=useState<Measurement[]>([]);
const [loading,setLoading]=useState(false); const active=useRef(true);const inFlight=useRef(false);
const refresh=useCallback(async()=>{
if(inFlight.current)return;inFlight.current=true;setLoading(true);
const results=await Promise.all(endpoints.map(async url=>{
try {const {data:raw}=await api.get(url);const data=raw?.success===true?raw.data:raw;
if(!data||typeof data!=='object'||raw?.success===false)throw new Error('Invalid measurement response');
return {data,error:null,observedAt:new Date().toISOString()};
}catch(e){return {data:null,error:e instanceof Error?e.message:'Request failed',observedAt:new Date().toISOString()}}
}));
if(active.current){setMeasurements(results);setLoading(false)}inFlight.current=false;
},[]);
useEffect(()=>{active.current=true;void refresh();const timer=setInterval(()=>void refresh(),30000);return()=>{active.current=false;clearInterval(timer)}},[refresh]);
const [stats,health,sms]=measurements;const tx=stats?.data;const gateway=health?.data;const credit=sms?.data?.credit??sms?.data?.balance;
return <div className="space-y-5 font-vazir pb-12"><header className="bg-white p-5 border rounded-2xl flex justify-between"><div><h1 className="font-black text-xl">Measured service monitoring</h1><p>Only backend-reported values. Unknown is not healthy. Polling every 30 seconds.</p></div><Button disabled={loading} onClick={()=>void refresh()}>Refresh measurements</Button></header>
{loading&&<p role="status">Loading measurements…</p>}
<div className="grid md:grid-cols-3 gap-4">{['Payment statistics','Payment gateway health','SMS credit'].map((title,index)=><section key={title} className="bg-white border rounded-2xl p-5 space-y-3"><h2 className="font-bold">{title}</h2><p className="text-xs break-all">Source: {endpoints[index]}</p><p>Observed at: {measurements[index]?.observedAt??'Unknown'}</p>{measurements[index]?.error&&<p role="alert" className="text-red-700">Unknown — {measurements[index].error}</p>}
{index===0&&<dl><dt>Today volume (toman)</dt><dd>{value(tx?.todayVolume)}</dd><dt>Verified transactions</dt><dd>{value(tx?.todayVerified??tx?.verifiedCount)}</dd><dt>Success rate</dt><dd>{value(tx?.successRate,'%')}</dd></dl>}
{index===1&&<dl><dt>Reported status</dt><dd>{value(gateway?.status)}</dd><dt>Reported latency</dt><dd>{value(gateway?.latencyMs,' ms')}</dd><dt>Merchant</dt><dd>{value(gateway?.activeMerchant??gateway?.merchantId)}</dd></dl>}
{index===2&&<p>{typeof credit==='number'?credit.toLocaleString('fa-IR')+' پیامک':value(credit)}</p>}
</section>)}</div>
<section className="bg-amber-50 border rounded-2xl p-5 space-y-2"><h2 className="font-bold">Uninstrumented services</h2>{['Database','Redis','Post service','OCR','Uptime','Environment','SMS sent today','SMS latency','Agent runtime'].map(label=><p key={label}>{label}: Unknown — no measured endpoint</p>)}</section>
</div>;
}
@@ -0,0 +1,31 @@
import { render, screen } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import api from '../services/api';
import ApprovalsPage from './ApprovalsPage';
vi.mock('../services/api', () => ({ default: { get: vi.fn(), post: vi.fn(), put: vi.fn() } }));
vi.mock('react-hot-toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));
const item = (id: string, category: string, status = 'PENDING') => ({
id, category, status, department: category === 'SEO' ? 'SEO' : 'B2B',
title: id, payload: {}, createdAt: '2026-10-19T10:00:00Z',
});
describe('operational authorization boundary', () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(api.get).mockResolvedValue({ data: {
success: true,
data: [item('supplier-action', 'B2B_SUPPLIER_STRATEGY'), item('seo-approval', 'SEO')],
meta: { pendingCount: 2 },
} });
});
it('does not expose a supplier manager action as authorization while SEO remains', async () => {
render(<ApprovalsPage />);
expect(await screen.findByText('seo-approval')).toBeInTheDocument();
expect(screen.queryByText('supplier-action')).not.toBeInTheDocument();
expect(screen.getAllByRole('button', { name: /تایید و صدور مجوز اجرا/ })).toHaveLength(1);
expect(screen.getByText(/1 پیشنهاد منتظر تصمیم شما/)).toBeInTheDocument();
});
});
@@ -0,0 +1,108 @@
import { render, screen, fireEvent, within } from '@testing-library/react';
import { beforeEach, describe, it, expect, vi } from 'vitest';
import api from '../services/api';
import OrchestrationCommandCenter from './OrchestrationCommandCenter';
vi.mock('../services/api', () => ({ default: {get:vi.fn(),post:vi.fn(),put:vi.fn()} }));
const task={id:'t1',key:'bounded-1',title:'Bounded SEO audit',department:'SEO',state:'GATE1_PENDING',version:4,operationMode:'PREPARE',budgetLimitCents:500,availableActions:[{id:'g1',label:'Approve bounded work',gate:1,decision:'APPROVED'}],runs:[],metadata:{scope:'Only staging',acceptanceCriteria:['Audit schema']}};
describe('command center', () => {
beforeEach(() => { vi.resetAllMocks(); vi.mocked(api.get).mockImplementation(async url => {
if(url.endsWith('/overview'))return {data:{items:[],measuredAt:'2026-10-22T00:00:00Z',capabilities:{mutations:true,chat:true,runtime:false}}};
if(url.endsWith('/tasks')) return {data:[task]};
if(url.endsWith('/tasks/t1')) return {data:task};
throw new Error('Unavailable: '+url);
}); });
it('loads server tasks, immutable bounds and only server actions; unavailable data is never fabricated', async () => {
render(<OrchestrationCommandCenter />);
fireEvent.click(await screen.findByRole('button',{name:'Bounded SEO audit'}));
expect(await screen.findByText(/Only staging/)).toBeInTheDocument();
expect(screen.getByRole('button',{name:'Approve bounded work'})).toBeInTheDocument();
expect(screen.queryByRole('button',{name:'RUNNING'})).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button',{name:'Agents & departments'}));
expect(await screen.findByRole('alert')).toHaveTextContent('Unavailable');
});
it('requires explicit confirmation and expiry; retains idempotency across failed retry', async () => {
vi.mocked(api.post).mockRejectedValue(new Error('network failure'));
render(<OrchestrationCommandCenter />);
fireEvent.click(await screen.findByRole('button',{name:'Bounded SEO audit'}));
fireEvent.click(await screen.findByRole('button',{name:'Approve bounded work'}));
const dialog=screen.getByRole('dialog');
expect(within(dialog).getByRole('button',{name:'Confirm command'})).toBeDisabled();
fireEvent.change(within(dialog).getByLabelText('Expires at'),{target:{value:'2099-01-01T12:00'}});
fireEvent.change(within(dialog).getByLabelText('Reason'),{target:{value:'Scope checked'}});
fireEvent.click(within(dialog).getByLabelText('I reviewed the immutable scope and binding'));
fireEvent.click(within(dialog).getByRole('button',{name:'Confirm command'}));
expect(await within(dialog).findByRole('alert')).toHaveTextContent('network failure');
expect(within(dialog).getByLabelText('Reason')).toBeDisabled();
expect(within(dialog).getByLabelText('Expires at')).toBeDisabled();
fireEvent.click(within(dialog).getByRole('button',{name:'Confirm command'}));
await within(dialog).findByRole('alert');
expect(api.post).toHaveBeenCalledTimes(2);
const first=vi.mocked(api.post).mock.calls[0][1];
expect(first).toEqual(expect.objectContaining({expectedVersion:4,decision:'APPROVED'}));
expect(vi.mocked(api.post).mock.calls[1][1]).toEqual(first);
});
it('shows measured readiness snapshot and unknown optional services without synthetic cards',async()=>{
vi.mocked(api.get).mockImplementation(async url=>{
if(url.endsWith('/tasks'))return {data:[]};
return {data:{measuredAt:'2026-10-22T12:00:00Z',items:[{id:'agent-1',title:'SEO worker',status:'BLOCKED',readiness:'Missing model policy',department:'SEO'}]}};
});
render(<OrchestrationCommandCenter/>);
fireEvent.click(screen.getByRole('button',{name:'Agents & departments'}));
expect(await screen.findByText('Missing model policy')).toBeInTheDocument();
expect(screen.getByText('BLOCKED')).toBeInTheDocument();
});
it('binds Gate2 using registered evidence, never editable commit or environment',async()=>{
const release={...task,state:'GATE2_PENDING',availableActions:[{id:'g2',label:'Approve release',gate:2,decision:'APPROVED'}],runs:[{id:'run-1',status:'VERIFIED',commitSha:'abc123',environment:'staging',artifacts:[{id:'artifact-1',sha256:'a'.repeat(64)}]}]};
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/tasks')?[release]:release}));
vi.mocked(api.post).mockResolvedValue({data:{id:'decision-2'}});
render(<OrchestrationCommandCenter/>);
fireEvent.click(await screen.findByRole('button',{name:'Bounded SEO audit'}));
fireEvent.click(await screen.findByRole('button',{name:'Approve release'}));
const dialog=screen.getByRole('dialog');
fireEvent.change(within(dialog).getByLabelText('Expires at'),{target:{value:'2099-01-01T12:00'}});
fireEvent.change(within(dialog).getByLabelText('Reason'),{target:{value:'Evidence reviewed'}});
fireEvent.click(within(dialog).getByLabelText('I reviewed the immutable scope and binding'));
expect(within(dialog).getByRole('button',{name:'Confirm command'})).toBeDisabled();
fireEvent.change(within(dialog).getByLabelText('Registered run / artifact binding'),{target:{value:'run-1|'+'a'.repeat(64)}});
fireEvent.click(within(dialog).getByLabelText('I reviewed the immutable scope and binding'));
fireEvent.click(within(dialog).getByRole('button',{name:'Confirm command'}));
await screen.findByText(/Command accepted/);
expect(api.post).toHaveBeenCalledWith('/admin/orchestration/tasks/t1/gates/2/decide',expect.objectContaining({runId:'run-1',artifactHash:'a'.repeat(64),commitSha:'abc123',environment:'staging',expectedVersion:4}));
});
it('requires global impact confirmation for each kill level and reports backend rejection',async()=>{
vi.mocked(api.put).mockRejectedValue(new Error('Forbidden: role'));
render(<OrchestrationCommandCenter/>);await screen.findByRole('button',{name:'Bounded SEO audit'});
fireEvent.click(screen.getByRole('button',{name:'Kill switch'}));
expect(screen.getAllByRole('option')).toHaveLength(4);
expect(screen.getByRole('button',{name:'Apply kill switch'})).toBeDisabled();
fireEvent.change(screen.getByLabelText('Kill level'),{target:{value:'EMERGENCY_HALT'}});
fireEvent.change(screen.getByLabelText('Kill reason'),{target:{value:'Incident'}});
fireEvent.click(screen.getByLabelText('I confirm global operational impact'));
fireEvent.click(screen.getByRole('button',{name:'Apply kill switch'}));
expect(await screen.findByRole('alert')).toHaveTextContent('Forbidden: role');
expect(api.put).toHaveBeenCalledWith('/admin/orchestration/kill-switch',{level:'EMERGENCY_HALT',reason:'Incident'});
});
it('sends advisory chat via typed bridge and renders text, not HTML',async()=>{
vi.mocked(api.post).mockResolvedValue({data:{id:'reply',role:'assistant',content:'<script>unsafe</script>'}});
render(<OrchestrationCommandCenter/>);await screen.findByRole('button',{name:'Bounded SEO audit'});
fireEvent.click(screen.getByRole('button',{name:'Chat'}));
fireEvent.change(screen.getByLabelText('Session ID'),{target:{value:'session-1'}});
fireEvent.change(screen.getByLabelText('Message'),{target:{value:'Explain bounded work'}});
fireEvent.click(screen.getByRole('button',{name:'Send advisory message'}));
expect(await screen.findByText('assistant: <script>unsafe</script>')).toBeInTheDocument();
expect(document.querySelector('script')).toBeNull();
expect(api.post).toHaveBeenCalledWith('/admin/orchestration/chat/messages',expect.objectContaining({sessionId:'session-1',message:'Explain bounded work'}));
});
it('fails closed for creation, kill and chat when overview cannot authorize capabilities',async()=>{
vi.mocked(api.get).mockImplementation(async url=>{if(url.endsWith('/tasks'))return {data:[task]};throw new Error('Unavailable');});
render(<OrchestrationCommandCenter/>);await screen.findByRole('button',{name:'Bounded SEO audit'});
fireEvent.click(screen.getByRole('button',{name:'Tasks & approvals'}));
expect(screen.queryByText('Create bounded work')).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button',{name:'Kill switch'}));
expect(screen.queryByRole('button',{name:'Apply kill switch'})).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button',{name:'Chat'}));
expect(screen.queryByRole('button',{name:'Send advisory message'})).not.toBeInTheDocument();
expect(api.post).not.toHaveBeenCalled();expect(api.put).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,82 @@
import { useEffect, useState } from 'react';
import Button from '../components/ui/Button';
import RouterUsagePanel from '../components/RouterUsagePanel';
import CreateOrchestrationTask from '../components/CreateOrchestrationTask';
import { orchestration, killLevels } from '../services/orchestration';
import type { Task, ServerAction, Resource, ResourceSnapshot, KillLevel, ChatMessage } from '../services/orchestration';
const sections = ['Overview','Tasks & approvals','Runs & artifacts','Agents & departments','Models & budgets','Schedules','Audit & releases','Kill switch','9router usage & quota','Chat'] as const;
type Section = typeof sections[number];
const resources:Partial<Record<Section,Resource>> = {'Agents & departments':'agents','Models & budgets':'model-policy','Schedules':'schedules','Audit & releases':'releases'};
const errorText=(e:unknown)=> e instanceof Error ? e.message : 'Unknown backend error';
function Json({value}:{value:unknown}) {return <pre className="text-xs whitespace-pre-wrap break-all bg-gray-50 border rounded-xl p-3" dir="ltr">{JSON.stringify(value,null,2)}</pre>}
export default function OrchestrationCommandCenter() {
const [section,setSection]=useState<Section>('Overview');
const [capabilities,setCapabilities]=useState({mutations:false,chat:false,runtime:false});
const [tasks,setTasks]=useState<Task[]>([]);
const [selected,setSelected]=useState<Task|null>(null);
const [snapshot,setSnapshot]=useState<ResourceSnapshot|null>(null);
const [error,setError]=useState(''); const [loading,setLoading]=useState(false);
const [search,setSearch]=useState('');
const [pending,setPending]=useState<{task:Task;action:ServerAction;key:string}|null>(null);
const [expires,setExpires]=useState(''); const [reason,setReason]=useState('');
const [binding,setBinding]=useState(''); const [confirmed,setConfirmed]=useState(false);
const [attempted,setAttempted]=useState(false); const [busy,setBusy]=useState(false); const [commandError,setCommandError]=useState('');
const [success,setSuccess]=useState('');
const [kill,setKill]=useState<KillLevel>('FREEZE_NEW_WORK');
const [session,setSession]=useState(''); const [message,setMessage]=useState('');
const [messages,setMessages]=useState<ChatMessage[]>([]);
const [chatKey,setChatKey]=useState(()=>crypto.randomUUID());
const loadTasks=async()=> {setLoading(true);setError(''); try {setTasks(await orchestration.tasks())} catch(e){setTasks([]);setSelected(null);setError(errorText(e))} finally {setLoading(false)}};
useEffect(()=>{void loadTasks(); orchestration.resource('overview').then(s=>setCapabilities({mutations:s.capabilities?.mutations===true,chat:s.capabilities?.chat===true,runtime:s.capabilities?.runtime===true})).catch(()=>setCapabilities({mutations:false,chat:false,runtime:false}));},[]);
useEffect(()=> {
const resource=resources[section]; setSnapshot(null);setError('');
if(!resource)return;
let active=true;setLoading(true);
orchestration.resource(resource).then(data=>{if(active)setSnapshot(data)}).catch(e=>{if(active)setError(errorText(e))}).finally(()=>{if(active)setLoading(false)});
return ()=>{active=false};
},[section]);
const select=async(task:Task)=>{setSelected(null);setError('');try {setSelected(await orchestration.task(task.id))}catch(e){setError(errorText(e))}};
const open=(task:Task,action:ServerAction)=>{setAttempted(false);setPending({task,action,key:crypto.randomUUID()});setExpires('');setReason('');setConfirmed(false);setBinding('');setCommandError('');setSuccess('')};
const execute=async()=> {
if(!pending||busy||!confirmed)return;
setAttempted(true);setBusy(true);setCommandError('');
try { const [runId,artifactHash]=binding.split('|');
await orchestration.command(pending.task,pending.action,{idempotencyKey:pending.key,reason,expiresAt:expires?new Date(expires).toISOString():undefined,runId,artifactHash});
setPending(null);setSelected(null);setSuccess('Command accepted by backend; refreshed authoritative state.');await loadTasks();
} catch(e) {setCommandError(errorText(e)+' — Refresh before retrying a version conflict; network retries keep the same key.')} finally {setBusy(false)}
};
const refresh=()=>{setSelected(null);setPending(null);void loadTasks()};
const filtered=tasks.filter(t=>(t.title+' '+t.department+' '+t.state).toLowerCase().includes(search.toLowerCase()));
return <div className="space-y-5 font-vazir pb-12">
<header className="bg-white border rounded-2xl p-5 flex justify-between gap-4"><div><h1 className="text-xl font-black">Orchestration command center</h1><p className="text-sm text-gray-600">Backend-authoritative operations · Gate1 bounded work · Gate2 immutable release binding</p></div><Button onClick={refresh} disabled={busy||loading}>Refresh authoritative state</Button></header>
<nav aria-label="Orchestration sections" className="flex flex-wrap gap-2">{sections.map(s=><Button key={s} onClick={()=>{setSection(s);setSuccess('');setReason('');setConfirmed(false)}} variant={section===s?'primary':'outline'}>{s}</Button>)}</nav>
{loading&&<p role="status">Loading measured backend state…</p>}
{error&&<p role="alert" className="border border-red-200 bg-red-50 rounded-xl p-4">Unknown / unavailable: {error}. No fallback data. <button onClick={refresh}>Reload tasks</button></p>}
{success&&<p role="status">{success}</p>}
{section==='Tasks & approvals'&&capabilities.mutations&&<CreateOrchestrationTask onCreated={()=>void loadTasks()}/>}
{section==='Overview'&&<section className="bg-white border rounded-2xl p-5 space-y-4"><h2 className="font-bold">Observed task inventory</h2><p>{tasks.length} tasks returned by backend. This is inventory, not agent health or runtime telemetry.</p><div className="flex flex-wrap gap-3">{[...new Set(tasks.map(t=>t.state))].map(state=><span key={state} className="border rounded-xl p-3">{state}: {tasks.filter(t=>t.state===state).length}</span>)}</div></section>}
{(['Overview','Tasks & approvals','Runs & artifacts','Models & budgets','Audit & releases'] as Section[]).includes(section)&&<section className="bg-white border rounded-2xl p-5 space-y-4"><label>Filter tasks<input className="border rounded-lg p-2 m-2" value={search} onChange={e=>setSearch(e.target.value)}/></label>
{!loading&&!error&&!tasks.length&&<p>No tasks returned by backend.</p>}
<div className="overflow-x-auto"><table className="w-full text-sm"><thead><tr>{['Task','Department','State','Mode','Budget cap (cents)','Version'].map(h=><th key={h} className="text-start p-2">{h}</th>)}</tr></thead><tbody>{filtered.map(t=><tr key={t.id} className="border-t"><td className="p-2"><button className="text-purple-700 underline" onClick={()=>void select(t)}>{t.title}</button></td><td>{t.department}</td><td>{t.state}</td><td>{t.operationMode}</td><td>{t.budgetLimitCents??'Unknown'}</td><td>{t.version}</td></tr>)}</tbody></table></div>
</section>}
{selected&&<section aria-label="Task detail" className="bg-white border rounded-2xl p-5 space-y-4"><h2 className="font-bold">{selected.title} · v{selected.version}</h2><h3>Immutable scope / acceptance criteria</h3><Json value={{operationMode:selected.operationMode,budgetLimitCents:selected.budgetLimitCents,metadata:selected.metadata}}/>
<h3>Server-authorized actions</h3>{!selected.availableActions.length&&<p>No actions advertised. Read-only; the browser does not infer transitions.</p>}<div className="flex flex-wrap gap-2">{selected.availableActions.map(a=><Button key={a.id} disabled={!!a.disabledReason} title={a.disabledReason} onClick={()=>open(selected,a)}>{a.label}</Button>)}</div>
<h3>Immutable approval decisions</h3><Json value={selected.decisions??[]}/>
<h3>Runs & registered artifacts</h3>{!selected.runs?.length&&<p>No registered runs.</p>}{selected.runs?.map(r=><article key={r.id} className="border rounded-xl p-3 space-y-2"><h4>{r.id} · {r.status}</h4><p>Commit: {r.commitSha} · Environment: {r.environment}</p>{r.artifacts.map(a=><Json key={a.id} value={a}/>)}</article>)}
<h3>Budget ledger (cents; not inferred usage)</h3><Json value={selected.budgetLedger??[]}/><h3>Ordered audit events</h3><Json value={selected.events??[]}/>
</section>}
{snapshot&&<section className="bg-white border rounded-2xl p-5 space-y-4"><h2>{section}</h2><p>Measured at: {snapshot.measuredAt}</p>{!snapshot.items.length&&<p>No records returned by backend.</p>}<div className="grid md:grid-cols-2 gap-3">{snapshot.items.map(item=><article key={item.id} className="border rounded-xl p-4"><h3>{item.title??item.id}</h3><dl>{Object.entries(item).filter(([k])=>k!=='id'&&k!=='title').map(([k,v])=><div key={k} className="flex justify-between gap-3"><dt>{k}</dt><dd>{String(v??'Unknown')}</dd></div>)}</dl></article>)}</div><p>Configuration mutations require backend-advertised commands; none are inferred by this client.</p></section>}
{section==='Kill switch'&&!capabilities.mutations&&<p>Mutation controls unavailable: backend security hardening pending.</p>}
{section==='Kill switch'&&capabilities.mutations&&<section className="border border-red-300 rounded-2xl bg-white p-5 space-y-3"><h2>Global kill switch — four escalating levels</h2><p>Applies globally, not only to selected task. No implicit resume. Current active level: unknown until backend returns state.</p><label>Level<select aria-label="Kill level" value={kill} onChange={e=>{setKill(e.target.value as KillLevel);setConfirmed(false)}}>{killLevels.map(l=><option key={l}>{l}</option>)}</select></label><p>Freeze new work → stop agents → disable mutations → emergency halt.</p><label>Reason<input aria-label="Kill reason" value={reason} onChange={e=>setReason(e.target.value)} className="border p-2"/></label><label className="block"><input type="checkbox" checked={confirmed} onChange={e=>setConfirmed(e.target.checked)}/>I confirm global operational impact</label><Button disabled={busy||!reason.trim()||!confirmed} onClick={async()=>{setBusy(true);setError('');try{const result=await orchestration.kill(kill,reason);setSuccess('Backend acknowledged kill switch: '+JSON.stringify(result));setConfirmed(false)}catch(e){setError(errorText(e))}finally{setBusy(false)}}}>Apply kill switch</Button></section>}
{section==='9router usage & quota'&&<RouterUsagePanel/>}
{section==='Chat'&&!capabilities.chat&&<p>Chat unsupported: trusted runtime bridge unavailable.</p>}
{section==='Chat'&&capabilities.chat&&<section className="bg-white border rounded-2xl p-5 space-y-3"><h2>Typed backend chat bridge</h2><p>Advisory text only. No terminal, PTY, runtime token, or direct Hermes connection. Decisions use explicit approval controls.</p><label>Session ID<input value={session} onChange={e=>{setSession(e.target.value);setMessages([])}} className="border p-2"/></label><div role="log">{messages.map(m=><p key={m.id}>{m.role}: {m.content}</p>)}</div><label>Message<textarea value={message} onChange={e=>{setMessage(e.target.value);setChatKey(crypto.randomUUID())}} className="border p-2 block w-full"/></label><Button disabled={busy||!session.trim()||!message.trim()} onClick={async()=>{setBusy(true);setError('');try{const reply=await orchestration.chat(session,message,chatKey);setMessages(prev=>[...prev,{id:chatKey,role:'user',content:message},reply]);setMessage('');setChatKey(crypto.randomUUID())}catch(e){setError(errorText(e))}finally{setBusy(false)}}}>Send advisory message</Button></section>}
{pending&&<div role="dialog" aria-modal="true" aria-label="Confirm immutable command" className="fixed inset-0 z-50 bg-black/50 overflow-y-auto p-8"><div className="bg-white rounded-2xl p-6 max-w-2xl mx-auto space-y-4"><h2>{pending.action.label}</h2><Json value={{taskId:pending.task.id,expectedVersion:pending.task.version,idempotencyKey:pending.key,scope:pending.task.metadata,budgetLimitCents:pending.task.budgetLimitCents,operationMode:pending.task.operationMode}}/>
{pending.action.gate&&<label className="block">Expires at<input aria-label="Expires at" type="datetime-local" value={expires} onChange={e=>setExpires(e.target.value)} disabled={busy||attempted}/></label>}
{pending.action.gate===2&&pending.action.decision==='APPROVED'&&<label>Registered run / artifact binding<select aria-label="Registered run / artifact binding" value={binding} onChange={e=>{setBinding(e.target.value);setConfirmed(false)}} disabled={busy||attempted}><option value="">Select immutable evidence</option>{pending.task.runs?.flatMap(r=>r.artifacts.map(a=><option key={r.id+'|'+a.sha256} value={r.id+'|'+a.sha256}>{r.id} · {r.commitSha} · {r.environment} · {a.sha256}</option>))}</select></label>}
<label className="block">Reason<input aria-label="Reason" value={reason} onChange={e=>setReason(e.target.value)} disabled={busy||attempted} className="border p-2"/></label>
<label className="block"><input type="checkbox" checked={confirmed} onChange={e=>setConfirmed(e.target.checked)} disabled={busy}/>I reviewed the immutable scope and binding</label>
{commandError&&<p role="alert">{commandError}</p>}<div className="flex gap-3"><Button disabled={busy||!confirmed||!reason.trim()|| (!!pending.action.gate&&!Number.isFinite(Date.parse(expires))) || (pending.action.gate===2&&pending.action.decision==='APPROVED'&&!binding)} onClick={()=>void execute()}>Confirm command</Button><Button variant="outline" disabled={busy} onClick={()=>setPending(null)}>Cancel</Button></div>
</div></div>}
</div>;
}
Loaded 100 of 181 files, more files were not shown because too many files have changed in this diff. Show more