Compare commits

..
Author SHA1 Message Date
Canina Automation a7f7d40562 fix(hermes): enable installed delivery gate via supported CLI
Canina Hermes reliability / reliability (push) Successful in 2m33s
2026-11-06 10:13:09 +00:00
Canina Automation d1eb86f74f fix(hermes): gate unverified release reports and enable execution verification
Canina Hermes reliability / reliability (push) Has been cancelled
2026-11-06 10:12:24 +00:00
devops 209339dc57 fix(hermes): scope existing Git identity to raw repository host via CI
Repair Canina Hermes Git route / routing (push) Successful in 3s
2026-11-06 08:32:42 +00:00
Canina Hermes dc34c57a0c ci: route exact limited timestamp release branch to Stage
Deploy Canina / deploy (push) Successful in 2m51s
2026-10-30 13:28:55 +00:00
Canina Hermes c97ea01ba9 fix(blog): project truthful publication and substantive edit timestamps 2026-10-30 13:21:07 +00:00
197 changed files with 554 additions and 12771 deletions

No files matched your search

+15 -1
View File
@@ -5,6 +5,7 @@ on:
branches:
- main
- develop
- release/blog-timestamp-limited-20261030
jobs:
deploy:
@@ -12,10 +13,23 @@ jobs:
steps:
- name: Run deploy.sh from within the scripts folder
env:
BRANCH: ${{ github.ref_name }}
DEPLOY_REF: ${{ github.ref }}
DEPLOY_SHA: ${{ github.sha }}
GITHUB_ACTIONS: 'true'
run: |
set -eu
case "${DEPLOY_REF}" in
refs/heads/main) BRANCH=main; STAGE_SOURCE_REF= ;;
refs/heads/develop|refs/heads/release/blog-timestamp-limited-20261030)
BRANCH=develop; STAGE_SOURCE_REF="$DEPLOY_REF" ;;
*) printf 'Unsupported deployment ref\n' >&2; exit 2 ;;
esac
# Bind downloads and both release dispatchers to the exact event commit.
case "$DEPLOY_SHA" in
*[!0-9a-f]*|'') exit 2 ;;
esac
[ "${#DEPLOY_SHA}" -eq 40 ] || exit 2
export BRANCH STAGE_SOURCE_REF
# 1. رفع مشکل DNS و غیرفعال کردن پروکسی برای دامنه محلی
echo "87.248.133.138 git.parsaaghayi.ir" >> /etc/hosts
export http_proxy=""
+24
View File
@@ -0,0 +1,24 @@
name: Repair Canina Hermes Git route
on:
push:
branches:
- ops/hermes-git-routing-20261106
jobs:
routing:
runs-on: canina
steps:
- name: Apply scoped runtime routing without restart
env:
REPAIR_SHA: ${{ github.sha }}
REPAIR_REF: ${{ github.ref }}
run: |
set -eu
[ "$REPAIR_REF" = refs/heads/ops/hermes-git-routing-20261106 ]
case "$REPAIR_SHA" in *[!0-9a-f]*|'') exit 2 ;; esac
[ "${#REPAIR_SHA}" -eq 40 ]
export http_proxy= https_proxy= HTTP_PROXY= HTTPS_PROXY=
wget --no-proxy -qO repair.py "https://git.parsaaghayi.ir/parsa/canina/raw/commit/${REPAIR_SHA}/infra/hermes-git-routing/repair.py"
python3 repair.py
docker exec -i -u 10000 -e HOME=/opt/data -e HERMES_HOME=/opt/data canina-hermes python3 - --apply < repair.py
docker exec -u 10000 -e HOME=/opt/data -e HERMES_HOME=/opt/data canina-hermes git ls-remote ssh://git@git.parsaaghayi.ir:222/parsa/canina.git refs/heads/develop
docker exec -u 10000 -e HOME=/opt/data -e HERMES_HOME=/opt/data canina-hermes git ls-remote canina-gitea:parsa/canina.git refs/heads/develop
+29
View File
@@ -0,0 +1,29 @@
name: Canina Hermes reliability
on:
push:
branches:
- ops/hermes-reliability-20261106
jobs:
reliability:
runs-on: canina
steps:
- name: Test and install default-only reliability policy
env:
REPAIR_SHA: ${{ github.sha }}
REPAIR_REF: ${{ github.ref }}
run: |
set -eu
[ "$REPAIR_REF" = refs/heads/ops/hermes-reliability-20261106 ]
case "$REPAIR_SHA" in *[!0-9a-f]*|'') exit 2 ;; esac
[ "${#REPAIR_SHA}" -eq 40 ]
export http_proxy= https_proxy= HTTP_PROXY= HTTPS_PROXY=
mkdir -p reliability
for f in __init__.py plugin.yaml test_guard.py install.py; do
wget --no-proxy -qO "reliability/$f" "https://git.parsaaghayi.ir/parsa/canina/raw/commit/${REPAIR_SHA}/infra/hermes-reliability/$f"
done
python3 reliability/test_guard.py
docker exec -u 10000 canina-hermes mkdir -p /opt/data/cache/scratch/reliability-managed
for f in __init__.py plugin.yaml install.py; do
docker exec -i -u 10000 canina-hermes sh -c "umask 077; tee /opt/data/cache/scratch/reliability-managed/$f >/dev/null" < "reliability/$f"
done
docker exec -u 10000 -e HOME=/opt/data -e HERMES_HOME=/opt/data canina-hermes python3 /opt/data/cache/scratch/reliability-managed/install.py /opt/data/cache/scratch/reliability-managed
@@ -1,42 +0,0 @@
name: Stage author bootstrap (dedicated repair)
on:
push:
branches:
- ops/author-bootstrap-stage-rehearse
- ops/author-bootstrap-stage-apply
jobs:
bootstrap:
runs-on: canina
steps:
- name: Exact SHA build then isolated rehearsal and authorized repair
env:
GITHUB_SHA: ${{ github.sha }}
GITHUB_REF: ${{ github.ref }}
GITHUB_ACTIONS: 'true'
STAGE_AUTHOR_BOOTSTRAP_REVIEWED_SHA: ${{ secrets.STAGE_AUTHOR_BOOTSTRAP_REVIEWED_SHA }}
# Path only, NOT a token value. Parent supplies an existing private file
# visible to the runner; absent file blocks repair AFTER image build.
AUTHOR_BOOTSTRAP_TOKEN_FILE: ${{ secrets.STAGE_AUTHOR_BOOTSTRAP_TOKEN_FILE }}
run: |
set -eu
set +x
umask 077
case "$GITHUB_REF" in
refs/heads/ops/author-bootstrap-stage-rehearse|refs/heads/ops/author-bootstrap-stage-apply) ;;
*) exit 2 ;;
esac
test "$STAGE_AUTHOR_BOOTSTRAP_REVIEWED_SHA" = "$GITHUB_SHA"
export no_proxy="git.parsaaghayi.ir,localhost,127.0.0.1,87.248.133.138"
echo "87.248.133.138 git.parsaaghayi.ir" >> /etc/hosts
unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY
root=$(mktemp -d)
chmod 700 "$root"
git init "$root/source"
git -C "$root/source" fetch --depth=1 https://git.parsaaghayi.ir/parsa/canina.git "$GITHUB_SHA"
git -C "$root/source" checkout --detach FETCH_HEAD
test "$(git -C "$root/source" rev-parse HEAD)" = "$GITHUB_SHA"
export AUTHOR_BOOTSTRAP_EVIDENCE="$root/evidence"
printf 'Private Stage evidence directory (retained on failure): %s\n' "$root/evidence"
python3 "$root/source/scripts/stage-author-bootstrap/ci.py"
# Retain private dumps locally; never upload archive or credential files.
printf 'Private Stage evidence directory: %s\n' "$root/evidence"
-35
View File
@@ -1,35 +0,0 @@
name: Stage SEO schema operation
on:
push:
branches:
- ops/seo-schema-stage-rehearse
- ops/seo-schema-stage-apply
jobs:
schema:
runs-on: canina
steps:
- name: Exact immutable Stage operation
env:
GITHUB_SHA: ${{ github.sha }}
GITHUB_REF: ${{ github.ref }}
GITHUB_ACTIONS: 'true'
STAGE_SCHEMA_REVIEWED_SHA: ${{ secrets.STAGE_SCHEMA_REVIEWED_SHA }}
run: |
set -eu
case "$GITHUB_REF" in
refs/heads/ops/seo-schema-stage-rehearse) mode=rehearse ;;
refs/heads/ops/seo-schema-stage-apply) mode=apply ;;
*) exit 2 ;;
esac
export no_proxy="git.parsaaghayi.ir,localhost,127.0.0.1,87.248.133.138"
echo "87.248.133.138 git.parsaaghayi.ir" >> /etc/hosts
unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY
root=$(mktemp -d)
chmod 700 "$root"
git init "$root/source"
git -C "$root/source" fetch --depth=1 https://git.parsaaghayi.ir/parsa/canina.git "$GITHUB_SHA"
git -C "$root/source" checkout --detach FETCH_HEAD
test "$(git -C "$root/source" rev-parse HEAD)" = "$GITHUB_SHA"
python3 "$root/source/scripts/stage-schema/operation.py" "$mode" --sha "$GITHUB_SHA" --evidence "$root/evidence"
# Private backups remain in this restricted runner directory; never upload dumps.
printf 'Private Stage evidence directory: %s\n' "$root/evidence"
@@ -1,89 +0,0 @@
-- SEO models existed in schema.prisma without a tracked CREATE migration.
-- Create only missing SEO objects, then additively upgrade existing SEO tables.
-- This does not reconcile the repository's broader incomplete baseline: blogs
-- must already exist (see prisma/MIGRATION_BASELINE.md). No live SQL is run here.
DO $$ BEGIN
CREATE TYPE "ResearchFindingStatus" AS ENUM ('RESEARCHED', 'ACTIONED', 'EVALUATING', 'SCALED', 'PRUNED');
EXCEPTION
WHEN duplicate_object THEN NULL;
END $$;
CREATE TABLE IF NOT EXISTS "content_research_findings" (
"id" UUID NOT NULL,
"title" VARCHAR(255) NOT NULL,
"hypothesis" TEXT NOT NULL,
"target_keywords" TEXT[],
"primary_keyword" VARCHAR(128) NOT NULL,
"expected_outcome" TEXT NOT NULL,
"status" "ResearchFindingStatus" NOT NULL DEFAULT 'RESEARCHED',
"blog_id" UUID,
"ceo_feedback" TEXT,
"feedback_submitted_at" TIMESTAMPTZ,
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMPTZ NOT NULL,
CONSTRAINT "content_research_findings_pkey" PRIMARY KEY ("id"),
CONSTRAINT "content_research_findings_blog_id_fkey" FOREIGN KEY ("blog_id") REFERENCES "blogs"("id") ON DELETE SET NULL ON UPDATE CASCADE
);
ALTER TABLE "content_research_findings"
ADD COLUMN IF NOT EXISTS "version" INTEGER NOT NULL DEFAULT 0,
ADD COLUMN IF NOT EXISTS "feedback_version" INTEGER NOT NULL DEFAULT 0,
ADD COLUMN IF NOT EXISTS "search_text" TEXT NOT NULL DEFAULT '',
ADD COLUMN IF NOT EXISTS "goal_metric" TEXT,
ADD COLUMN IF NOT EXISTS "goal_target" DOUBLE PRECISION,
ADD COLUMN IF NOT EXISTS "action_id" TEXT;
-- action_id is a plain external reference, deliberately without a foreign key.
CREATE UNIQUE INDEX IF NOT EXISTS "content_research_findings_blog_id_key" ON "content_research_findings"("blog_id");
CREATE INDEX IF NOT EXISTS "content_research_findings_status_idx" ON "content_research_findings"("status");
CREATE INDEX IF NOT EXISTS "content_research_findings_primary_keyword_idx" ON "content_research_findings"("primary_keyword");
CREATE TABLE IF NOT EXISTS "content_performance_snapshots" (
"id" UUID NOT NULL,
"finding_id" UUID NOT NULL,
"snapshot_date" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
"gsc_impressions" INTEGER,
"gsc_clicks" INTEGER,
"gsc_position" DOUBLE PRECISION,
"ga4_active_users" INTEGER,
"ga4_avg_engagement_sec" DOUBLE PRECISION,
"ga4_bounce_rate" DOUBLE PRECISION,
"ga4_scroll_depth_rate" DOUBLE PRECISION,
"attributed_orders_count" INTEGER,
"attributed_sales_value" DECIMAL(15,2),
"action_recommendation" VARCHAR(64),
"analysis_notes" TEXT,
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "content_performance_snapshots_pkey" PRIMARY KEY ("id"),
CONSTRAINT "content_performance_snapshots_finding_id_fkey" FOREIGN KEY ("finding_id") REFERENCES "content_research_findings"("id") ON DELETE CASCADE ON UPDATE CASCADE
);
ALTER TABLE "content_performance_snapshots"
ADD COLUMN IF NOT EXISTS "period_start" TIMESTAMPTZ,
ADD COLUMN IF NOT EXISTS "period_end" TIMESTAMPTZ,
ADD COLUMN IF NOT EXISTS "source_metadata" JSONB,
ADD COLUMN IF NOT EXISTS "ingestion_key" TEXT,
ALTER COLUMN "gsc_impressions" DROP NOT NULL,
ALTER COLUMN "gsc_impressions" DROP DEFAULT,
ALTER COLUMN "gsc_clicks" DROP NOT NULL,
ALTER COLUMN "gsc_clicks" DROP DEFAULT,
ALTER COLUMN "gsc_position" DROP NOT NULL,
ALTER COLUMN "gsc_position" DROP DEFAULT,
ALTER COLUMN "ga4_active_users" DROP NOT NULL,
ALTER COLUMN "ga4_active_users" DROP DEFAULT,
ALTER COLUMN "ga4_avg_engagement_sec" DROP NOT NULL,
ALTER COLUMN "ga4_avg_engagement_sec" DROP DEFAULT,
ALTER COLUMN "ga4_bounce_rate" DROP NOT NULL,
ALTER COLUMN "ga4_bounce_rate" DROP DEFAULT,
ALTER COLUMN "ga4_scroll_depth_rate" DROP NOT NULL,
ALTER COLUMN "ga4_scroll_depth_rate" DROP DEFAULT,
ALTER COLUMN "attributed_orders_count" DROP NOT NULL,
ALTER COLUMN "attributed_orders_count" DROP DEFAULT,
ALTER COLUMN "attributed_sales_value" DROP NOT NULL,
ALTER COLUMN "attributed_sales_value" DROP DEFAULT;
-- Do not rewrite historical metrics: old zeros remain zeros, not proven measures.
-- Newly added metadata/period/key columns remain SQL NULL for legacy snapshots;
-- no provenance, observation period, or idempotency key can be inferred safely.
CREATE INDEX IF NOT EXISTS "content_performance_snapshots_finding_id_snapshot_date_idx" ON "content_performance_snapshots"("finding_id", "snapshot_date");
-- PostgreSQL permits multiple NULL keys, preserving all historical snapshots.
CREATE UNIQUE INDEX IF NOT EXISTS "content_performance_snapshots_finding_id_ingestion_key_key" ON "content_performance_snapshots"("finding_id", "ingestion_key");
@@ -1,244 +0,0 @@
-- CreateEnum
CREATE TYPE "CorporateTaskStatus" AS ENUM ('TODO', 'IN_PROGRESS', 'TEST', 'DONE', 'BLOCKED', 'REJECTED', 'CANCELLED');
-- CreateEnum
CREATE TYPE "CorporatePriority" AS ENUM ('CEO_EXPEDITE', 'CRITICAL', 'HIGH', 'MEDIUM', 'LOW');
-- CreateTable
CREATE TABLE "corporate_tasks" (
"id" UUID NOT NULL,
"taskCode" TEXT NOT NULL,
"title" TEXT NOT NULL,
"normalizedTitle" TEXT NOT NULL,
"normalizedCode" TEXT NOT NULL,
"description" TEXT NOT NULL,
"department" TEXT NOT NULL,
"priority" "CorporatePriority" NOT NULL DEFAULT 'CEO_EXPEDITE',
"status" "CorporateTaskStatus" NOT NULL DEFAULT 'TODO',
"actionType" TEXT NOT NULL DEFAULT 'CEO_DIRECTIVE',
"dueCycle" TEXT,
"parentId" UUID,
"goalId" UUID,
"assignedAgent" TEXT,
"claimToken" UUID,
"leasedUntil" TIMESTAMPTZ,
"executionCount" INTEGER NOT NULL DEFAULT 0,
"qaCount" INTEGER NOT NULL DEFAULT 0,
"rejectionCount" INTEGER NOT NULL DEFAULT 0,
"createdBy" TEXT NOT NULL,
"createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMPTZ NOT NULL,
CONSTRAINT "corporate_tasks_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "corporate_events" (
"id" UUID NOT NULL,
"taskId" UUID NOT NULL,
"speaker" TEXT NOT NULL,
"speakerName" TEXT NOT NULL,
"step" TEXT NOT NULL,
"content" TEXT NOT NULL,
"payload" JSONB,
"timestamp" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "corporate_events_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "corporate_evidence" (
"id" UUID NOT NULL,
"taskId" UUID NOT NULL,
"claimToken" UUID NOT NULL,
"executor" TEXT NOT NULL,
"artifactUri" TEXT NOT NULL,
"sha256" TEXT NOT NULL,
"summary" TEXT NOT NULL,
"tool" TEXT NOT NULL,
"result" TEXT NOT NULL,
"createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "corporate_evidence_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "corporate_reviews" (
"id" UUID NOT NULL,
"taskId" UUID NOT NULL,
"evidenceId" UUID NOT NULL,
"reviewer" TEXT NOT NULL,
"passed" BOOLEAN NOT NULL,
"findings" TEXT NOT NULL,
"verification" JSONB NOT NULL,
"createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "corporate_reviews_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "corporate_research" (
"id" UUID NOT NULL,
"title" TEXT NOT NULL,
"category" TEXT NOT NULL,
"source" TEXT NOT NULL,
"opportunity" TEXT NOT NULL,
"impact" TEXT NOT NULL,
"recommendedAction" TEXT NOT NULL,
"status" TEXT NOT NULL DEFAULT 'DISCOVERED',
"cadence" TEXT NOT NULL,
"provenance" JSONB NOT NULL,
"createdBy" TEXT NOT NULL,
"createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "corporate_research_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "corporate_sources" (
"id" UUID NOT NULL,
"researchId" UUID NOT NULL,
"url" TEXT NOT NULL,
"title" TEXT NOT NULL,
"excerpt" TEXT NOT NULL,
"retrievedAt" TIMESTAMPTZ NOT NULL,
"sha256" TEXT NOT NULL,
CONSTRAINT "corporate_sources_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "corporate_roadmaps" (
"id" UUID NOT NULL,
"researchId" UUID NOT NULL,
"cycleName" TEXT NOT NULL,
"month" TEXT NOT NULL,
"seasonalTheme" TEXT NOT NULL,
"strategicGoals" TEXT[],
"plannedArticlesCount" INTEGER NOT NULL,
"plannedRefreshesCount" INTEGER NOT NULL,
"plannedCatalogEnrichments" INTEGER NOT NULL,
"isActive" BOOLEAN NOT NULL DEFAULT false,
"createdBy" TEXT NOT NULL,
"createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "corporate_roadmaps_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "corporate_goals" (
"id" UUID NOT NULL,
"roadmapId" UUID NOT NULL,
"title" TEXT NOT NULL,
"department" TEXT NOT NULL,
"acceptanceCriteria" TEXT NOT NULL,
"metric" TEXT NOT NULL,
"target" DOUBLE PRECISION,
"createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "corporate_goals_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "corporate_effects" (
"id" UUID NOT NULL,
"taskId" UUID NOT NULL,
"metric" TEXT NOT NULL,
"availability" TEXT NOT NULL,
"baseline" DOUBLE PRECISION,
"observed" DOUBLE PRECISION,
"source" TEXT NOT NULL,
"observedAt" TIMESTAMPTZ NOT NULL,
"recordedBy" TEXT NOT NULL,
"createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "corporate_effects_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "corporate_reports" (
"id" UUID NOT NULL,
"day" TEXT NOT NULL,
"summary" TEXT NOT NULL,
"snapshot" JSONB NOT NULL,
"createdBy" TEXT NOT NULL,
"createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "corporate_reports_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "corporate_operations" (
"key" TEXT NOT NULL,
"payloadHash" TEXT NOT NULL,
"response" JSONB NOT NULL,
"createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "corporate_operations_pkey" PRIMARY KEY ("key")
);
-- CreateIndex
CREATE UNIQUE INDEX "corporate_tasks_taskCode_key" ON "corporate_tasks"("taskCode");
-- CreateIndex
CREATE INDEX "corporate_tasks_status_priority_updatedAt_idx" ON "corporate_tasks"("status", "priority", "updatedAt");
-- CreateIndex
CREATE INDEX "corporate_tasks_parentId_idx" ON "corporate_tasks"("parentId");
-- CreateIndex
CREATE INDEX "corporate_tasks_goalId_idx" ON "corporate_tasks"("goalId");
-- CreateIndex
CREATE INDEX "corporate_events_taskId_timestamp_idx" ON "corporate_events"("taskId", "timestamp");
-- CreateIndex
CREATE INDEX "corporate_evidence_taskId_idx" ON "corporate_evidence"("taskId");
-- CreateIndex
CREATE INDEX "corporate_reviews_taskId_idx" ON "corporate_reviews"("taskId");
-- CreateIndex
CREATE INDEX "corporate_sources_researchId_idx" ON "corporate_sources"("researchId");
-- CreateIndex
CREATE INDEX "corporate_roadmaps_month_idx" ON "corporate_roadmaps"("month");
-- CreateIndex
CREATE INDEX "corporate_goals_roadmapId_idx" ON "corporate_goals"("roadmapId");
-- CreateIndex
CREATE INDEX "corporate_effects_taskId_idx" ON "corporate_effects"("taskId");
-- CreateIndex
CREATE UNIQUE INDEX "corporate_reports_day_key" ON "corporate_reports"("day");
-- AddForeignKey
ALTER TABLE "corporate_tasks" ADD CONSTRAINT "corporate_tasks_parentId_fkey" FOREIGN KEY ("parentId") REFERENCES "corporate_tasks"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "corporate_tasks" ADD CONSTRAINT "corporate_tasks_goalId_fkey" FOREIGN KEY ("goalId") REFERENCES "corporate_goals"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "corporate_events" ADD CONSTRAINT "corporate_events_taskId_fkey" FOREIGN KEY ("taskId") REFERENCES "corporate_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "corporate_evidence" ADD CONSTRAINT "corporate_evidence_taskId_fkey" FOREIGN KEY ("taskId") REFERENCES "corporate_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "corporate_reviews" ADD CONSTRAINT "corporate_reviews_taskId_fkey" FOREIGN KEY ("taskId") REFERENCES "corporate_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "corporate_reviews" ADD CONSTRAINT "corporate_reviews_evidenceId_fkey" FOREIGN KEY ("evidenceId") REFERENCES "corporate_evidence"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "corporate_sources" ADD CONSTRAINT "corporate_sources_researchId_fkey" FOREIGN KEY ("researchId") REFERENCES "corporate_research"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "corporate_roadmaps" ADD CONSTRAINT "corporate_roadmaps_researchId_fkey" FOREIGN KEY ("researchId") REFERENCES "corporate_research"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "corporate_goals" ADD CONSTRAINT "corporate_goals_roadmapId_fkey" FOREIGN KEY ("roadmapId") REFERENCES "corporate_roadmaps"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "corporate_effects" ADD CONSTRAINT "corporate_effects_taskId_fkey" FOREIGN KEY ("taskId") REFERENCES "corporate_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
@@ -1,22 +0,0 @@
-- Reviewed attribution-only storage; no business data or historical ledger writes.
DO $$ BEGIN
IF current_database() NOT IN ('caninodb_stage', 'rehearsal') THEN
RAISE EXCEPTION 'public author bootstrap is Stage-only';
END IF;
END $$;
ALTER TABLE public.users ADD COLUMN IF NOT EXISTS is_public_author BOOLEAN NOT NULL DEFAULT false;
ALTER TABLE public.users ALTER COLUMN is_public_author SET NOT NULL;
ALTER TABLE public.users ALTER COLUMN is_public_author SET DEFAULT false;
ALTER TABLE public.users ALTER COLUMN mobile DROP NOT NULL;
-- Repeated application is transactional and revalidates every existing row.
ALTER TABLE public.users DROP CONSTRAINT IF EXISTS users_public_author_identity_check;
ALTER TABLE public.users ADD CONSTRAINT users_public_author_identity_check CHECK (
(is_public_author = false AND mobile IS NOT NULL)
OR
(is_public_author = true
AND mobile IS NULL AND email IS NULL AND password IS NULL
AND role = 'User_PetOwner'
AND auth_expires_at IS NULL
AND stage_test_generation IS NULL AND stage_test_session IS NULL
AND wallet_balance = 0 AND charity_donation_total = 0)
);
+1 -279
View File
@@ -1,202 +1,3 @@
enum CorporateTaskStatus {
TODO
IN_PROGRESS
TEST
DONE
BLOCKED
REJECTED
CANCELLED
}
enum CorporatePriority {
CEO_EXPEDITE
CRITICAL
HIGH
MEDIUM
LOW
}
model CorporateTask {
id String @id @default(uuid()) @db.Uuid
taskCode String @unique
title String
normalizedTitle String
normalizedCode String
description String
department String
priority CorporatePriority @default(CEO_EXPEDITE)
status CorporateTaskStatus @default(TODO)
actionType String @default("CEO_DIRECTIVE")
dueCycle String?
parentId String? @db.Uuid
parent CorporateTask? @relation("TaskChildren", fields: [parentId], references: [id])
children CorporateTask[] @relation("TaskChildren")
goalId String? @db.Uuid
goal CorporateGoal? @relation(fields: [goalId], references: [id])
assignedAgent String?
claimToken String? @db.Uuid
leasedUntil DateTime? @db.Timestamptz()
executionCount Int @default(0)
qaCount Int @default(0)
rejectionCount Int @default(0)
createdBy String
createdAt DateTime @default(now()) @db.Timestamptz()
updatedAt DateTime @updatedAt @db.Timestamptz()
logs CorporateEvent[]
evidence CorporateEvidence[]
reviews CorporateReview[]
effects CorporateEffect[]
@@index([status, priority, updatedAt])
@@index([parentId])
@@index([goalId])
@@map("corporate_tasks")
}
model CorporateEvent {
id String @id @default(uuid()) @db.Uuid
taskId String @db.Uuid
task CorporateTask @relation(fields: [taskId], references: [id])
speaker String
speakerName String
step String
content String
payload Json?
timestamp DateTime @default(now()) @db.Timestamptz()
@@index([taskId, timestamp])
@@map("corporate_events")
}
model CorporateEvidence {
id String @id @default(uuid()) @db.Uuid
taskId String @db.Uuid
task CorporateTask @relation(fields: [taskId], references: [id])
claimToken String @db.Uuid
executor String
artifactUri String
sha256 String
summary String
tool String
result String
createdAt DateTime @default(now()) @db.Timestamptz()
reviews CorporateReview[]
@@index([taskId])
@@map("corporate_evidence")
}
model CorporateReview {
id String @id @default(uuid()) @db.Uuid
taskId String @db.Uuid
task CorporateTask @relation(fields: [taskId], references: [id])
evidenceId String @db.Uuid
evidence CorporateEvidence @relation(fields: [evidenceId], references: [id])
reviewer String
passed Boolean
findings String
verification Json
createdAt DateTime @default(now()) @db.Timestamptz()
@@index([taskId])
@@map("corporate_reviews")
}
model CorporateResearch {
id String @id @default(uuid()) @db.Uuid
title String
category String
source String
opportunity String
impact String
recommendedAction String
status String @default("DISCOVERED")
cadence String
provenance Json
createdBy String
createdAt DateTime @default(now()) @db.Timestamptz()
sources CorporateSource[]
roadmaps CorporateRoadmap[]
@@map("corporate_research")
}
model CorporateSource {
id String @id @default(uuid()) @db.Uuid
researchId String @db.Uuid
research CorporateResearch @relation(fields: [researchId], references: [id])
url String
title String
excerpt String
retrievedAt DateTime @db.Timestamptz()
sha256 String
@@index([researchId])
@@map("corporate_sources")
}
model CorporateRoadmap {
id String @id @default(uuid()) @db.Uuid
researchId String @db.Uuid
research CorporateResearch @relation(fields: [researchId], references: [id])
cycleName String
month String
seasonalTheme String
strategicGoals String[]
plannedArticlesCount Int
plannedRefreshesCount Int
plannedCatalogEnrichments Int
isActive Boolean @default(false)
createdBy String
createdAt DateTime @default(now()) @db.Timestamptz()
goals CorporateGoal[]
@@index([month])
@@map("corporate_roadmaps")
}
model CorporateGoal {
id String @id @default(uuid()) @db.Uuid
roadmapId String @db.Uuid
roadmap CorporateRoadmap @relation(fields: [roadmapId], references: [id])
title String
department String
acceptanceCriteria String
metric String
target Float?
createdAt DateTime @default(now()) @db.Timestamptz()
tasks CorporateTask[]
@@index([roadmapId])
@@map("corporate_goals")
}
model CorporateEffect {
id String @id @default(uuid()) @db.Uuid
taskId String @db.Uuid
task CorporateTask @relation(fields: [taskId], references: [id])
metric String
availability String
baseline Float?
observed Float?
source String
observedAt DateTime @db.Timestamptz()
recordedBy String
createdAt DateTime @default(now()) @db.Timestamptz()
@@index([taskId])
@@map("corporate_effects")
}
model CorporateReport {
id String @id @default(uuid()) @db.Uuid
day String @unique
summary String
snapshot Json
createdBy String
createdAt DateTime @default(now()) @db.Timestamptz()
@@map("corporate_reports")
}
model CorporateOperation {
key String @id
payloadHash String
response Json
createdAt DateTime @default(now()) @db.Timestamptz()
@@map("corporate_operations")
}
generator client {
provider = "prisma-client-js"
binaryTargets = ["native", "linux-musl-openssl-3.0.x"]
@@ -212,8 +13,7 @@ model User {
firstName String @map("first_name") @db.VarChar(100)
lastName String @map("last_name") @db.VarChar(100)
email String? @unique @db.VarChar(150)
mobile String? @unique @db.VarChar(15)
isPublicAuthor Boolean @default(false) @map("is_public_author")
mobile String @unique @db.VarChar(15)
password String? @db.VarChar(255)
role String @default("User_PetOwner") @db.VarChar(30)
authExpiresAt DateTime? @map("auth_expires_at") @db.Timestamptz()
@@ -419,7 +219,6 @@ model Blog {
category BlogCategory? @relation(fields: [categoryId], references: [id], onDelete: SetNull)
tags BlogTag[]
comments BlogComment[]
researchFinding ContentResearchFinding?
@@index([categoryId])
@@index([status])
@@ -1221,80 +1020,3 @@ model SmsCampaign {
@@map("sms_campaigns")
}
// ------------------------------------------------------------------------------
// 5. SEO & Performance Tracking Models
// ------------------------------------------------------------------------------
enum ResearchFindingStatus {
RESEARCHED
ACTIONED
EVALUATING
SCALED
PRUNED
}
model ContentResearchFinding {
id String @id @default(uuid()) @db.Uuid
title String @db.VarChar(255)
hypothesis String @db.Text
targetKeywords String[] @map("target_keywords")
primaryKeyword String @map("primary_keyword") @db.VarChar(128)
expectedOutcome String @map("expected_outcome") @db.Text
status ResearchFindingStatus @default(RESEARCHED)
version Int @default(0)
feedbackVersion Int @default(0) @map("feedback_version")
searchText String @default("") @map("search_text") @db.Text
goalMetric String? @map("goal_metric")
goalTarget Float? @map("goal_target")
// External action reference only; no orchestration relation or foreign key.
actionId String? @map("action_id")
blogId String? @unique @map("blog_id") @db.Uuid
blog Blog? @relation(fields: [blogId], references: [id], onDelete: SetNull)
ceoFeedback String? @map("ceo_feedback") @db.Text
feedbackSubmittedAt DateTime? @map("feedback_submitted_at") @db.Timestamptz()
snapshots ContentPerformanceSnapshot[]
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz()
@@index([status])
@@index([primaryKeyword])
@@map("content_research_findings")
}
model ContentPerformanceSnapshot {
id String @id @default(uuid()) @db.Uuid
findingId String @map("finding_id") @db.Uuid
finding ContentResearchFinding @relation(fields: [findingId], references: [id], onDelete: Cascade)
snapshotDate DateTime @default(now()) @map("snapshot_date") @db.Timestamptz()
periodStart DateTime? @map("period_start") @db.Timestamptz()
periodEnd DateTime? @map("period_end") @db.Timestamptz()
sourceMetadata Json? @map("source_metadata")
ingestionKey String? @map("ingestion_key")
gscImpressions Int? @map("gsc_impressions")
gscClicks Int? @map("gsc_clicks")
gscPosition Float? @map("gsc_position")
ga4ActiveUsers Int? @map("ga4_active_users")
ga4AvgEngagementSec Float? @map("ga4_avg_engagement_sec")
ga4BounceRate Float? @map("ga4_bounce_rate")
ga4ScrollDepthRate Float? @map("ga4_scroll_depth_rate")
attributedOrdersCount Int? @map("attributed_orders_count")
attributedSalesValue Decimal? @map("attributed_sales_value") @db.Decimal(15, 2)
actionRecommendation String? @map("action_recommendation") @db.VarChar(64)
analysisNotes String? @map("analysis_notes") @db.Text
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
@@index([findingId, snapshotDate])
@@unique([findingId, ingestionKey])
@@map("content_performance_snapshots")
}
@@ -1,7 +0,0 @@
npm notice run backend@0.0.1 test
npm notice run jest --runInBand api-keys.integration.spec
Test Suites: 1 passed, 1 total
Tests: 5 passed, 5 total
Snapshots: 0 total
Time: 4.044 s
Ran all test suites matching api-keys.integration.spec.
@@ -1,104 +0,0 @@
npm notice run backend@0.0.1 test
npm notice run jest --runInBand api-keys.integration.spec
FAIL src/admin/api-keys.integration.spec.ts
● human-only key administration / real key authentication and PostgreSQL › denies get to authenticated admin API key without mutating keys
expected 403 "Forbidden", got 200 "OK"
34 | const before = await db.apiKey.count();
35 | const path = '/admin/api-keys' + (method === 'patch' ? `/${target}/toggle` : method === 'delete' ? `/${target}` : '');
> 36 | await request(app.getHttpServer())[method](path).set('x-api-key', rawKey).send(method === 'post' ? { name: 'security-fixture-forged-reviewer', scopes: ['admin'] } : {}).expect(403);
| ^
37 | expect(await db.apiKey.count()).toBe(before);
38 | expect((await db.apiKey.findUniqueOrThrow({ where: { id: target } })).status).toBe('ACTIVE');
39 | });
at admin/api-keys.integration.spec.ts:36:174
----
at Test._assertStatus (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:309:14)
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:365:13
at Test._assertFunction (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:342:13)
at Test.assert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:195:23)
at localAssert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:138:14)
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:156:7
at Test.fn [as callback] (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:892:12)
at callback (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:1183:18)
at IncomingMessage.fn (../../../corporate-backend/backend/node_modules/superagent/src/node/parsers/json.js:19:7)
● human-only key administration / real key authentication and PostgreSQL › denies post to authenticated admin API key without mutating keys
expected 403 "Forbidden", got 201 "Created"
34 | const before = await db.apiKey.count();
35 | const path = '/admin/api-keys' + (method === 'patch' ? `/${target}/toggle` : method === 'delete' ? `/${target}` : '');
> 36 | await request(app.getHttpServer())[method](path).set('x-api-key', rawKey).send(method === 'post' ? { name: 'security-fixture-forged-reviewer', scopes: ['admin'] } : {}).expect(403);
| ^
37 | expect(await db.apiKey.count()).toBe(before);
38 | expect((await db.apiKey.findUniqueOrThrow({ where: { id: target } })).status).toBe('ACTIVE');
39 | });
at admin/api-keys.integration.spec.ts:36:174
----
at Test._assertStatus (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:309:14)
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:365:13
at Test._assertFunction (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:342:13)
at Test.assert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:195:23)
at localAssert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:138:14)
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:156:7
at Test.fn [as callback] (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:892:12)
at callback (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:1183:18)
at IncomingMessage.fn (../../../corporate-backend/backend/node_modules/superagent/src/node/parsers/json.js:19:7)
● human-only key administration / real key authentication and PostgreSQL › denies patch to authenticated admin API key without mutating keys
expected 403 "Forbidden", got 200 "OK"
34 | const before = await db.apiKey.count();
35 | const path = '/admin/api-keys' + (method === 'patch' ? `/${target}/toggle` : method === 'delete' ? `/${target}` : '');
> 36 | await request(app.getHttpServer())[method](path).set('x-api-key', rawKey).send(method === 'post' ? { name: 'security-fixture-forged-reviewer', scopes: ['admin'] } : {}).expect(403);
| ^
37 | expect(await db.apiKey.count()).toBe(before);
38 | expect((await db.apiKey.findUniqueOrThrow({ where: { id: target } })).status).toBe('ACTIVE');
39 | });
at admin/api-keys.integration.spec.ts:36:174
----
at Test._assertStatus (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:309:14)
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:365:13
at Test._assertFunction (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:342:13)
at Test.assert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:195:23)
at localAssert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:138:14)
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:156:7
at Test.fn [as callback] (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:892:12)
at callback (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:1183:18)
at IncomingMessage.fn (../../../corporate-backend/backend/node_modules/superagent/src/node/parsers/json.js:19:7)
● human-only key administration / real key authentication and PostgreSQL › denies delete to authenticated admin API key without mutating keys
expected 403 "Forbidden", got 200 "OK"
34 | const before = await db.apiKey.count();
35 | const path = '/admin/api-keys' + (method === 'patch' ? `/${target}/toggle` : method === 'delete' ? `/${target}` : '');
> 36 | await request(app.getHttpServer())[method](path).set('x-api-key', rawKey).send(method === 'post' ? { name: 'security-fixture-forged-reviewer', scopes: ['admin'] } : {}).expect(403);
| ^
37 | expect(await db.apiKey.count()).toBe(before);
38 | expect((await db.apiKey.findUniqueOrThrow({ where: { id: target } })).status).toBe('ACTIVE');
39 | });
at admin/api-keys.integration.spec.ts:36:174
----
at Test._assertStatus (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:309:14)
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:365:13
at Test._assertFunction (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:342:13)
at Test.assert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:195:23)
at localAssert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:138:14)
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:156:7
at Test.fn [as callback] (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:892:12)
at callback (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:1183:18)
at IncomingMessage.fn (../../../corporate-backend/backend/node_modules/superagent/src/node/parsers/json.js:19:7)
Test Suites: 1 failed, 1 total
Tests: 4 failed, 1 passed, 5 total
Snapshots: 0 total
Time: 3.608 s
Ran all test suites matching api-keys.integration.spec.
@@ -1,207 +0,0 @@
npm notice run backend@0.0.1 test
npm notice run jest --runInBand
[Nest] 3987292 - 10/28/2026, 12:44:07 PM  ERROR [ZibalEBankService] [Zibal EBank API] Error requesting /ebank/v1/account/list/: transport failed
[Nest] 3987292 - 10/28/2026, 12:44:07 PM  ERROR [ZibalEBankService] [Zibal EBank API] Error requesting /ebank/v1/account/list/: transport failed
[Nest] 3987292 - 10/28/2026, 12:44:22 PM  ERROR [ZibalEBankService] [Zibal EBank API] Error requesting /ebank/v1/account/list/: aborted
[Nest] 3987292 - 10/28/2026, 12:44:07 PM  ERROR [ZibalEBankService] [Zibal EBank API] Error requesting /ebank/v1/account/list/: Zibal EBank HTTP 503
[Nest] 3987292 - 10/28/2026, 12:44:08 PM  ERROR [SslService] Failed to parse SSL certificate
[Nest] 3987292 - 10/28/2026, 12:44:08 PM  ERROR [SslService] Error: error:0480006C:PEM routines::no start line
 at new X509Certificate (node:internal/crypto/x509:121:21)
at SslService.getStatus (/opt/data/cache/scratch/corporate-hardening-base/backend/src/admin/ssl.service.ts:104:20)
at Object.<anonymous> (/opt/data/cache/scratch/corporate-hardening-base/backend/src/admin/ssl.service.spec.ts:179:30)
at Promise.finally.completed (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/jestAdapterInit.js:1561:28)
at new Promise (<anonymous>)
at callAsyncCircusFn (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/jestAdapterInit.js:1501:10)
at _callCircusTest (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/jestAdapterInit.js:1011:40)
at _runTest (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/jestAdapterInit.js:951:3)
at /opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/jestAdapterInit.js:853:7
at _runTestsForDescribeBlock (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/jestAdapterInit.js:866:11)
at _runTestsForDescribeBlock (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/jestAdapterInit.js:861:11)
at _runTestsForDescribeBlock (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/jestAdapterInit.js:861:11)
at run (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/jestAdapterInit.js:765:3)
at runAndTransformResultsToJestFormat (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/jestAdapterInit.js:1993:21)
at jestAdapter (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/runner.js:111:19)
at runTestInternal (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-runner/build/index.js:276:16)
at runTest (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-runner/build/index.js:344:7) {
library: 'PEM routines',
reason: 'no start line',
code: 'ERR_OSSL_PEM_NO_START_LINE'
}
[Nest] 3987292 - 10/28/2026, 12:44:12 PM  ERROR [PaymentService] Security Alert: Amount mismatch on trackId=tr-1! Zibal reported 1000000 Rials, but expected 5000000 Rials in DB.
FAIL src/seo-tracking/publication.postgres.spec.ts
● Test suite failed to run
PrismaClientConstructorValidationError: Invalid value undefined for datasource "db" provided to PrismaClient constructor.
It should have this form: { url: "CONNECTION_STRING" }
Read more at https://pris.ly/d/client-constructor
20 | const deferred = () => { let resolve!: () => void; const promise = new Promise<void>(r => resolve = r); return { promise, resolve }; };
21 | (url ? describe : describe.skip)('atomic publication: real PostgreSQL row ordering', () => {
> 22 | const db = new PrismaClient({ datasources: { db: { url } } });
| ^
23 | let user: any;
24 | const cache = { revalidateBlog: jest.fn(async () => false) };
25 | const service = new SeoTrackingService(db as any, cache as any);
at Object.datasources (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:124:86)
at Gl (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:126:2527)
at new t (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:130:748)
at seo-tracking/publication.postgres.spec.ts:22:14
at Object.<anonymous> (seo-tracking/publication.postgres.spec.ts:21:33)
[Nest] 3987292 - 10/28/2026, 12:44:18 PM  WARN [BlogsService] Cache revalidation failed for updated blog [post]: cache down
FAIL src/wiki/wiki.service.spec.ts
● WikiService › findAll › should paginate and filter terms with fallback to default sortBy
expect(jest.fn()).toHaveBeenCalledWith(...expected)
- Expected
+ Received
@@ -1,21 +1,39 @@
Object {
"orderBy": Object {
"term": "desc",
},
- "skip": 0,
- "take": 10,
+ "skip": undefined,
+ "take": 100,
"where": Object {
"OR": Array [
Object {
"term": Object {
"contains": "مفصل",
"mode": "insensitive",
},
},
Object {
+ "key": Object {
+ "contains": "مفصل",
+ "mode": "insensitive",
+ },
+ },
+ Object {
"definition": Object {
+ "contains": "مفصل",
+ "mode": "insensitive",
+ },
+ },
+ Object {
+ "term": Object {
+ "contains": "مفصل",
+ "mode": "insensitive",
+ },
+ },
+ Object {
+ "key": Object {
"contains": "مفصل",
"mode": "insensitive",
},
},
],,
Number of calls: 1
56 | });
57 |
> 58 | expect(mockPrisma.scientificTerm.findMany).toHaveBeenCalledWith({
| ^
59 | where: {
60 | OR: [
61 | { term: { contains: "مفصل", mode: "insensitive" } },
at Object.<anonymous> (wiki/wiki.service.spec.ts:58:50)
Summary of all failing tests
FAIL seo-tracking/publication.postgres.spec.ts
● Test suite failed to run
PrismaClientConstructorValidationError: Invalid value undefined for datasource "db" provided to PrismaClient constructor.
It should have this form: { url: "CONNECTION_STRING" }
Read more at https://pris.ly/d/client-constructor
20 | const deferred = () => { let resolve!: () => void; const promise = new Promise<void>(r => resolve = r); return { promise, resolve }; };
21 | (url ? describe : describe.skip)('atomic publication: real PostgreSQL row ordering', () => {
> 22 | const db = new PrismaClient({ datasources: { db: { url } } });
| ^
23 | let user: any;
24 | const cache = { revalidateBlog: jest.fn(async () => false) };
25 | const service = new SeoTrackingService(db as any, cache as any);
at Object.datasources (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:124:86)
at Gl (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:126:2527)
at new t (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:130:748)
at seo-tracking/publication.postgres.spec.ts:22:14
at Object.<anonymous> (seo-tracking/publication.postgres.spec.ts:21:33)
FAIL wiki/wiki.service.spec.ts
● WikiService › findAll › should paginate and filter terms with fallback to default sortBy
expect(jest.fn()).toHaveBeenCalledWith(...expected)
- Expected
+ Received
@@ -1,21 +1,39 @@
Object {
"orderBy": Object {
"term": "desc",
},
- "skip": 0,
- "take": 10,
+ "skip": undefined,
+ "take": 100,
"where": Object {
"OR": Array [
Object {
"term": Object {
"contains": "مفصل",
"mode": "insensitive",
},
},
Object {
+ "key": Object {
+ "contains": "مفصل",
+ "mode": "insensitive",
+ },
+ },
+ Object {
"definition": Object {
+ "contains": "مفصل",
+ "mode": "insensitive",
+ },
+ },
+ Object {
+ "term": Object {
+ "contains": "مفصل",
+ "mode": "insensitive",
+ },
+ },
+ Object {
+ "key": Object {
"contains": "مفصل",
"mode": "insensitive",
},
},
],,
Number of calls: 1
56 | });
57 |
> 58 | expect(mockPrisma.scientificTerm.findMany).toHaveBeenCalledWith({
| ^
59 | where: {
60 | OR: [
61 | { term: { contains: "مفصل", mode: "insensitive" } },
at Object.<anonymous> (wiki/wiki.service.spec.ts:58:50)
Test Suites: 2 failed, 5 skipped, 95 passed, 97 of 102 total
Tests: 1 failed, 13 skipped, 818 passed, 832 total
Snapshots: 0 total
Time: 55.893 s
Ran all test suites.
@@ -1,44 +0,0 @@
npm notice run backend@0.0.1 test
npm notice run jest --runInBand corporate.integration.spec -t bounds detail|oversized
FAIL src/admin/hermes/corporate.integration.spec.ts
● corporate API / disposable PostgreSQL › bounds detail relations and report snapshots with explicit truncation and immutable replay
expect(received).toHaveLength(expected)
Expected length: 100
Received length: 106
Received array: [[Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object], …]
153 | await db.corporateEvent.createMany({ data: Array.from({ length: 105 }, () => ({ taskId: task.id, speaker: 'SYSTEM', speakerName: 'fixture', step: 'FIXTURE', content: 'x'.repeat(10000), payload: { nested: ['x'.repeat(10000)] } })) });
154 | const detail = await request(app.getHttpServer()).get('/admin/hermes/tasks/' + task.id).set('x-api-key', 'executor').expect(200);
> 155 | expect(detail.body.logs).toHaveLength(100);
| ^
156 | expect(detail.body.relationsMeta.logs).toEqual({ total: 106, returned: 100, limit: 100, truncated: true });
157 | const op = key(), body = { day: new Date().toISOString().slice(0, 10), summary: 'bounded' };
158 | const report = (await post('reports', body, 'executor', op).expect(201)).body;
at Object.<anonymous> (admin/hermes/corporate.integration.spec.ts:155:30)
● corporate API / disposable PostgreSQL › rolls back oversized mutation responses instead of persisting huge idempotency values
expect(received).rejects.toThrow()
Received promise resolved instead of rejected
Resolved to value: {"value": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
168 | const service = app.get(CorporateService) as any;
169 | const before = await db.corporateTask.count();
> 170 | await expect(service.operation('fixture', 'oversize', key(), {}, async (tx: any) => {
| ^
171 | await tx.corporateTask.create({ data: { title: 'rollback', description: 'fixture', taskCode: key(), normalizedTitle: 'rollback', normalizedCode: key(), department: 'CONTENT_SEO', createdBy: 'fixture' } });
172 | return { value: 'x'.repeat(1100000) };
173 | })).rejects.toThrow('Operation response exceeds limit');
at expect (../../../corporate-backend/backend/node_modules/expect/build/index.js:2116:15)
at Object.<anonymous> (admin/hermes/corporate.integration.spec.ts:170:11)
Test Suites: 1 failed, 1 total
Tests: 2 failed, 10 skipped, 12 total
Snapshots: 0 total
Time: 4.583 s
Ran all test suites matching corporate.integration.spec with tests matching "bounds detail|oversized".
@@ -1,2 +0,0 @@
npm notice run backend@0.0.1 build
npm notice run tsc -b
@@ -1,8 +0,0 @@
npm notice run backend@0.0.1 test
npm notice run jest --runInBand corporate.integration.spec corporate-policy.spec api-keys.integration.spec
Test Suites: 3 passed, 3 total
Tests: 20 passed, 20 total
Snapshots: 0 total
Time: 9.263 s
Ran all test suites matching corporate.integration.spec|corporate-policy.spec|api-keys.integration.spec.
@@ -1,207 +0,0 @@
npm notice run backend@0.0.1 test
npm notice run jest --runInBand
[Nest] 3985069 - 10/28/2026, 12:42:14 PM  ERROR [ZibalEBankService] [Zibal EBank API] Error requesting /ebank/v1/account/list/: transport failed
[Nest] 3985069 - 10/28/2026, 12:42:14 PM  ERROR [ZibalEBankService] [Zibal EBank API] Error requesting /ebank/v1/account/list/: transport failed
[Nest] 3985069 - 10/28/2026, 12:42:29 PM  ERROR [ZibalEBankService] [Zibal EBank API] Error requesting /ebank/v1/account/list/: aborted
[Nest] 3985069 - 10/28/2026, 12:42:14 PM  ERROR [ZibalEBankService] [Zibal EBank API] Error requesting /ebank/v1/account/list/: Zibal EBank HTTP 503
[Nest] 3985069 - 10/28/2026, 12:42:15 PM  ERROR [SslService] Failed to parse SSL certificate
[Nest] 3985069 - 10/28/2026, 12:42:15 PM  ERROR [SslService] Error: error:0480006C:PEM routines::no start line
 at new X509Certificate (node:internal/crypto/x509:121:21)
at SslService.getStatus (/opt/data/cache/scratch/corporate-hardening/backend/src/admin/ssl.service.ts:104:20)
at Object.<anonymous> (/opt/data/cache/scratch/corporate-hardening/backend/src/admin/ssl.service.spec.ts:179:30)
at Promise.finally.completed (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/jestAdapterInit.js:1561:28)
at new Promise (<anonymous>)
at callAsyncCircusFn (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/jestAdapterInit.js:1501:10)
at _callCircusTest (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/jestAdapterInit.js:1011:40)
at _runTest (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/jestAdapterInit.js:951:3)
at /opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/jestAdapterInit.js:853:7
at _runTestsForDescribeBlock (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/jestAdapterInit.js:866:11)
at _runTestsForDescribeBlock (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/jestAdapterInit.js:861:11)
at _runTestsForDescribeBlock (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/jestAdapterInit.js:861:11)
at run (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/jestAdapterInit.js:765:3)
at runAndTransformResultsToJestFormat (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/jestAdapterInit.js:1993:21)
at jestAdapter (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-circus/build/runner.js:111:19)
at runTestInternal (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-runner/build/index.js:276:16)
at runTest (/opt/data/cache/scratch/corporate-backend/backend/node_modules/jest-runner/build/index.js:344:7) {
library: 'PEM routines',
reason: 'no start line',
code: 'ERR_OSSL_PEM_NO_START_LINE'
}
[Nest] 3985069 - 10/28/2026, 12:42:19 PM  ERROR [PaymentService] Security Alert: Amount mismatch on trackId=tr-1! Zibal reported 1000000 Rials, but expected 5000000 Rials in DB.
FAIL src/seo-tracking/publication.postgres.spec.ts
● Test suite failed to run
PrismaClientConstructorValidationError: Invalid value undefined for datasource "db" provided to PrismaClient constructor.
It should have this form: { url: "CONNECTION_STRING" }
Read more at https://pris.ly/d/client-constructor
20 | const deferred = () => { let resolve!: () => void; const promise = new Promise<void>(r => resolve = r); return { promise, resolve }; };
21 | (url ? describe : describe.skip)('atomic publication: real PostgreSQL row ordering', () => {
> 22 | const db = new PrismaClient({ datasources: { db: { url } } });
| ^
23 | let user: any;
24 | const cache = { revalidateBlog: jest.fn(async () => false) };
25 | const service = new SeoTrackingService(db as any, cache as any);
at Object.datasources (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:124:86)
at Gl (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:126:2527)
at new t (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:130:748)
at seo-tracking/publication.postgres.spec.ts:22:14
at Object.<anonymous> (seo-tracking/publication.postgres.spec.ts:21:33)
[Nest] 3985069 - 10/28/2026, 12:42:26 PM  WARN [BlogsService] Cache revalidation failed for updated blog [post]: cache down
FAIL src/wiki/wiki.service.spec.ts
● WikiService › findAll › should paginate and filter terms with fallback to default sortBy
expect(jest.fn()).toHaveBeenCalledWith(...expected)
- Expected
+ Received
@@ -1,21 +1,39 @@
Object {
"orderBy": Object {
"term": "desc",
},
- "skip": 0,
- "take": 10,
+ "skip": undefined,
+ "take": 100,
"where": Object {
"OR": Array [
Object {
"term": Object {
"contains": "مفصل",
"mode": "insensitive",
},
},
Object {
+ "key": Object {
+ "contains": "مفصل",
+ "mode": "insensitive",
+ },
+ },
+ Object {
"definition": Object {
+ "contains": "مفصل",
+ "mode": "insensitive",
+ },
+ },
+ Object {
+ "term": Object {
+ "contains": "مفصل",
+ "mode": "insensitive",
+ },
+ },
+ Object {
+ "key": Object {
"contains": "مفصل",
"mode": "insensitive",
},
},
],,
Number of calls: 1
56 | });
57 |
> 58 | expect(mockPrisma.scientificTerm.findMany).toHaveBeenCalledWith({
| ^
59 | where: {
60 | OR: [
61 | { term: { contains: "مفصل", mode: "insensitive" } },
at Object.<anonymous> (wiki/wiki.service.spec.ts:58:50)
Summary of all failing tests
FAIL seo-tracking/publication.postgres.spec.ts
● Test suite failed to run
PrismaClientConstructorValidationError: Invalid value undefined for datasource "db" provided to PrismaClient constructor.
It should have this form: { url: "CONNECTION_STRING" }
Read more at https://pris.ly/d/client-constructor
20 | const deferred = () => { let resolve!: () => void; const promise = new Promise<void>(r => resolve = r); return { promise, resolve }; };
21 | (url ? describe : describe.skip)('atomic publication: real PostgreSQL row ordering', () => {
> 22 | const db = new PrismaClient({ datasources: { db: { url } } });
| ^
23 | let user: any;
24 | const cache = { revalidateBlog: jest.fn(async () => false) };
25 | const service = new SeoTrackingService(db as any, cache as any);
at Object.datasources (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:124:86)
at Gl (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:126:2527)
at new t (../../../corporate-backend/backend/node_modules/@prisma/client/runtime/library.js:130:748)
at seo-tracking/publication.postgres.spec.ts:22:14
at Object.<anonymous> (seo-tracking/publication.postgres.spec.ts:21:33)
FAIL wiki/wiki.service.spec.ts
● WikiService › findAll › should paginate and filter terms with fallback to default sortBy
expect(jest.fn()).toHaveBeenCalledWith(...expected)
- Expected
+ Received
@@ -1,21 +1,39 @@
Object {
"orderBy": Object {
"term": "desc",
},
- "skip": 0,
- "take": 10,
+ "skip": undefined,
+ "take": 100,
"where": Object {
"OR": Array [
Object {
"term": Object {
"contains": "مفصل",
"mode": "insensitive",
},
},
Object {
+ "key": Object {
+ "contains": "مفصل",
+ "mode": "insensitive",
+ },
+ },
+ Object {
"definition": Object {
+ "contains": "مفصل",
+ "mode": "insensitive",
+ },
+ },
+ Object {
+ "term": Object {
+ "contains": "مفصل",
+ "mode": "insensitive",
+ },
+ },
+ Object {
+ "key": Object {
"contains": "مفصل",
"mode": "insensitive",
},
},
],,
Number of calls: 1
56 | });
57 |
> 58 | expect(mockPrisma.scientificTerm.findMany).toHaveBeenCalledWith({
| ^
59 | where: {
60 | OR: [
61 | { term: { contains: "مفصل", mode: "insensitive" } },
at Object.<anonymous> (wiki/wiki.service.spec.ts:58:50)
Test Suites: 2 failed, 6 skipped, 95 passed, 97 of 103 total
Tests: 1 failed, 25 skipped, 818 passed, 844 total
Snapshots: 0 total
Time: 56.587 s
Ran all test suites.
@@ -1,7 +0,0 @@
npm notice run backend@0.0.1 test
npm notice run jest --runInBand corporate.integration.spec
Test Suites: 1 passed, 1 total
Tests: 7 passed, 7 total
Snapshots: 0 total
Time: 6.041 s
Ran all test suites matching corporate.integration.spec.
@@ -1,25 +0,0 @@
npm notice run backend@0.0.1 test
npm notice run jest --runInBand corporate.integration.spec -t rejects children
FAIL src/admin/hermes/corporate.integration.spec.ts
● corporate API / disposable PostgreSQL › rejects children after a parent claim commits while child creation waits on its row lock
expect(received).toBe(expected) // Object.is equality
Expected: 409
Received: 201
103 | expect(waiting).toBe(true);
104 | } finally { release(); await claiming; }
> 105 | expect((await pending).status).toBe(409);
| ^
106 | expect(await db.corporateTask.count({ where: { parentId: parent.id } })).toBe(0);
107 | });
108 | it('accepts children on TODO and BLOCKED, which prevents parent claiming', async () => {
at Object.<anonymous> (admin/hermes/corporate.integration.spec.ts:105:36)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 6 skipped, 7 total
Snapshots: 0 total
Time: 4.263 s
Ran all test suites matching corporate.integration.spec with tests matching "rejects children".
@@ -1,7 +0,0 @@
npm notice run backend@0.0.1 test
npm notice run jest --runInBand corporate.integration.spec -t public reads
Test Suites: 1 passed, 1 total
Tests: 9 skipped, 1 passed, 10 total
Snapshots: 0 total
Time: 4.131 s
Ran all test suites matching corporate.integration.spec with tests matching "public reads".
@@ -1,25 +0,0 @@
npm notice run backend@0.0.1 test
npm notice run jest --runInBand corporate.integration.spec -t public reads
FAIL src/admin/hermes/corporate.integration.spec.ts
● corporate API / disposable PostgreSQL › public reads strip claim tokens recursively while claim and replay retain ownership token
expect(received).not.toContain(expected) // indexOf
Expected substring: not "claimToken"
Received string: "{\"data\":[{\"id\":\"df2e8641-026a-4ed0-80ca-36fc10db3b3c\",\"taskCode\":\"TSK-257421eb-e384-403f-837c-f09345000cf2\",\"title\":\"كيك ۱۲۳\",\"normalizedTitle\":\"کیک 123\",\"normalizedCode\":\"tsk-257421eb-e384-403f-837c-f09345000cf2\",\"description\":\"integration fixture\",\"department\":\"CONTENT_SEO\",\"priority\":\"CEO_EXPEDITE\",\"status\":\"TEST\",\"actionType\":\"CEO_DIRECTIVE\",\"dueCycle\":null,\"parentId\":\"cb3407eb-35f4-4a02-9c5e-993e2b5924f1\",\"goalId\":null,\"assignedAgent\":\"apikey:executor\",\"claimToken\":\"b57fc669-e7c8-41c3-8904-f3bc60d2dc51\",\"leasedUntil\":null,\"executionCount\":1,\"qaCount\":0,\"rejectionCount\":0,\"createdBy\":\"apikey:executor\",\"createdAt\":\"2026-10-28T12:37:42.198Z\",\"updatedAt\":\"2026-10-28T12:37:42.296Z\"},{\"id\":\"cb3407eb-35f4-4a02-9c5e-993e2b5924f1\",\"taskCode\":\"TSK-40ee89e7-7127-4e85-aac2-dad7ea156be6\",\"title\":\"كيك ۱۲۳\",\"normalizedTitle\":\"کیک 123\",\"normalizedCode\":\"tsk-40ee89e7-7127-4
145 | for (const path of ['tasks', 'tasks/' + child.id, 'tasks/' + parent.id]) {
146 | const r = await request(app.getHttpServer()).get('/admin/hermes/' + path).set('x-api-key', 'competitor').expect(200);
> 147 | expect(JSON.stringify(r.body)).not.toContain('claimToken');
| ^
148 | expect(JSON.stringify(r.body)).not.toContain(claim.claimToken);
149 | }
150 | });
at Object.<anonymous> (admin/hermes/corporate.integration.spec.ts:147:42)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 9 skipped, 10 total
Snapshots: 0 total
Time: 3.842 s, estimated 6 s
Ran all test suites matching corporate.integration.spec with tests matching "public reads".
@@ -1,32 +0,0 @@
npm notice run backend@0.0.1 test
npm notice run jest --runInBand corporate.integration.spec -t malformed
FAIL src/admin/hermes/corporate.integration.spec.ts
● corporate API / disposable PostgreSQL › rejects malformed artifact locators and mismatched digest URNs before persistence
expected 400 "Bad Request", got 201 "Created"
166 | 'urn:sha256:' + 'b'.repeat(64),
167 | ]) {
> 168 | await post(`tasks/${task.id}/evidence`, { ...body, artifactUri }).expect(
| ^
169 | 400,
170 | );
171 | }
at Object.<anonymous> (admin/hermes/corporate.integration.spec.ts:168:73)
----
at Test._assertStatus (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:309:14)
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:365:13
at Test._assertFunction (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:342:13)
at Test.assert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:195:23)
at localAssert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:138:14)
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:156:7
at Test.fn [as callback] (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:892:12)
at callback (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:1183:18)
at IncomingMessage.fn (../../../corporate-backend/backend/node_modules/superagent/src/node/parsers/json.js:19:7)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 11 skipped, 12 total
Snapshots: 0 total
Time: 3.923 s, estimated 8 s
Ran all test suites matching corporate.integration.spec with tests matching "malformed".
@@ -1,8 +0,0 @@
npm notice run backend@0.0.1 test
npm notice run jest --runInBand corporate.integration.spec corporate-policy.spec
Test Suites: 2 passed, 2 total
Tests: 12 passed, 12 total
Snapshots: 0 total
Time: 6.595 s
Ran all test suites matching corporate.integration.spec|corporate-policy.spec.
@@ -1,50 +0,0 @@
npm notice run backend@0.0.1 test
npm notice run jest --runInBand corporate.integration.spec -t malformed|coercions
FAIL src/admin/hermes/corporate.integration.spec.ts
● corporate API / disposable PostgreSQL › rejects malformed artifact locators and mismatched digest URNs before persistence
expected 400 "Bad Request", got 201 "Created"
119 | const body = { claimToken: claim.claimToken, artifactUri: '', sha256: 'a'.repeat(64), summary: 'receipt', tool: 'jest', result: 'passed' };
120 | for (const artifactUri of ['https://', 'https://?x', 'https://bad host/x', 'https://user:pass@host.org/a', 'https://localhost/a', 'https://127.1/a', 'https://[::1]/a', 'urn:sha256:', 'urn:sha256:' + 'b'.repeat(64)]) {
> 121 | await post(`tasks/${task.id}/evidence`, { ...body, artifactUri }).expect(400);
| ^
122 | }
123 | expect(await db.corporateEvidence.count()).toBe(0);
124 | await post(`tasks/${task.id}/evidence`, { ...body, artifactUri: 'https://pubmed.ncbi.nlm.nih.gov/123/' }).expect(201);
at Object.<anonymous> (admin/hermes/corporate.integration.spec.ts:121:73)
----
at Test._assertStatus (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:309:14)
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:365:13
at Test._assertFunction (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:342:13)
at Test.assert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:195:23)
at localAssert (../../../corporate-backend/backend/node_modules/supertest/lib/test.js:138:14)
at ../../../corporate-backend/backend/node_modules/supertest/lib/test.js:156:7
at Test.fn [as callback] (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:892:12)
at callback (../../../corporate-backend/backend/node_modules/superagent/src/node/index.js:1183:18)
at IncomingMessage.fn (../../../corporate-backend/backend/node_modules/superagent/src/node/parsers/json.js:19:7)
● corporate API / disposable PostgreSQL › rejects implicit timestamp coercions in source and effect inputs
expect(received).rejects.toThrow()
Received promise resolved instead of rejected
Resolved to value: {"cadence": "MONTHLY", "category": "TREND", "createdAt": "2026-10-28T12:34:28.558Z", "createdBy": "fixture", "id": "8c847ae0-ff80-4ba2-9986-26a2abdd167a", "impact": "LOW", "opportunity": "investigate", "provenance": {"collector": "fixture", "context": "isolated", "method": "test"}, "recommendedAction": "measure", "source": "receipt", "sources": [{"excerpt": "receipt", "id": "108f61d9-0e90-4d53-804e-0330d129a299", "researchId": "8c847ae0-ff80-4ba2-9986-26a2abdd167a", "retrievedAt": "1970-01-01T00:00:00.000Z", "sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "title": "source", "url": "https://pubmed.ncbi.nlm.nih.gov/"}], "status": "DISCOVERED", "title": "research"}
128 | const research = { title: 'research', category: 'TREND', source: 'receipt', opportunity: 'investigate', impact: 'LOW', recommendedAction: 'measure', cadence: 'MONTHLY', provenance: { method: 'test', collector: 'fixture', context: 'isolated' }, sources: [{ url: 'https://pubmed.ncbi.nlm.nih.gov/', title: 'source', excerpt: 'receipt', retrievedAt: '', sha256: 'a'.repeat(64) }] };
129 | for (const time of [null, 0, false, [], '2026-01-01', '2026-02-30T00:00:00Z']) {
> 130 | await expect(service.research('fixture', key(), { ...research, sources: [{ ...research.sources[0], retrievedAt: time }] })).rejects.toThrow();
| ^
131 | await expect(service.effect('fixture', key(), key(), { metric: 'views', availability: 'UNAVAILABLE', source: 'none', observedAt: time })).rejects.toThrow('Invalid observation time');
132 | }
133 | for (const url of ['https://', 'https://?bad', 'https://bad host'])
at expect (../../../corporate-backend/backend/node_modules/expect/build/index.js:2116:15)
at Object.<anonymous> (admin/hermes/corporate.integration.spec.ts:130:13)
Test Suites: 1 failed, 1 total
Tests: 2 failed, 7 skipped, 9 total
Snapshots: 0 total
Time: 3.997 s, estimated 6 s
Ran all test suites matching corporate.integration.spec with tests matching "malformed|coercions".
@@ -1,3 +0,0 @@
# Plan
Dedicated human-principal guard after authentication and role guard. Keep scope rules unchanged. Reuse parent row lock. Centralize locator/time validation and public projection. Bound detail/report queries with deterministic ordering, counts and metadata; cap serialized operation responses.
Graph navigation: graphify-out/graph.json sha256 6a73473cee9e207543fdeeb668bea544f766200a1b16b8a3a9ce18d4e42e51af, 4304 nodes, build provenance unverified (navigation only). ApiKeysController -> JwtAuthGuard -> ApiKeysService verified directly at cc365bc; CorporateController -> CorporateService -> Prisma verified directly (corporate absent from stale map).
@@ -1,2 +0,0 @@
# Corporate hardening
Base cc365bc. Backend only, no push/deploy. Humans retain admin key management; API keys cannot manage keys. Children attach only to TODO/BLOCKED under parent lock. Validate HTTPS locators/digest URNs and explicit ISO timestamp strings. Public reads omit claimToken recursively; claim retains it. Detail relations and report snapshots bounded with truncation metadata and idempotency response size guard. Acceptance: real disposable PG HTTP tests, ordering tests, backend build.
@@ -1,7 +0,0 @@
# Tasks
- [x] RED/GREEN human key-admin gate with real key authentication
- [x] RED/GREEN parent ordering on PostgreSQL
- [x] RED/GREEN locator/time validation
- [x] RED/GREEN public token projection
- [x] RED/GREEN bounded reads/report/replay
- [x] regression suite, backend build, commit (no push)
@@ -1,14 +0,0 @@
# Verification
Base cc365bc; backend isolated branch hardening/corporate-security. No push/deploy/runtime changes.
Real PostgreSQL 16.2 started locally on 127.0.0.1:55439, corporate_test. Prisma db push applied only to disposable fixture (existing fixture lacked api_keys); tests use explicit opt-in, never runtime DATABASE_URL. Dependencies symlinked from corporate-backend/backend/node_modules, unchanged lockfile.
- RED auth: four key-management verbs returned 200/201 instead of 403 with real ApiKeysService validation against PG. GREEN 5 tests. Human path uses signed test-only Passport strategy (does not claim production JWT user lookup).
- RED parent: child HTTP request observed waiting on PostgreSQL parent row lock; after IN_PROGRESS commit returned 201 instead of 409. GREEN includes TODO/BLOCKED child-first gating, existing SKIP LOCKED coverage.
- RED validation: malformed HTTPS accepted, null timestamp persisted as epoch. GREEN malformed hosts, userinfo, loopback, malformed/mismatched digest URN, numeric/null/boolean/array/date-only/invalid calendar timestamp rejected.
- RED projection: public reads exposed claimToken. GREEN list/detail/evidence/children omit it; claim and immutable claim replay retain ownership token.
- RED bounds: detail returned 106 logs and oversized response persisted. GREEN limits 100 for each detail relation/report section, counts/truncation metadata, report 1000-character fields and omitted payloads; immutable report replay after source deletion; oversized operation rolls back task and operation.
- Final targeted: 3 suites / 20 tests passed with real PG enabled. Backend tsc -b passed.
- Full suite without opt-in: 95 passed suites, 2 failed, 6 skipped; 818 passed tests, 1 failed, 25 skipped. Exact clean cc365bc same dependencies: 95 passed suites, same 2 failed (publication.postgres undefined datasource in skipped describe; wiki stale pagination/search expectation), 5 skipped; 818 passed, same 1 failed, 13 skipped. Extra skips are new/expanded opt-in security tests, not regressions.
Report snapshot is intentionally partial, not a complete daily export. Relation metadata supports explicit partial display; no frontend changes owned here. Public detail relation count is capped, not arbitrary legacy JSON field bytes. All newly created idempotency responses capped at 1,000,000 UTF-8 bytes before durable save; rejection rolls back transaction. Existing legacy idempotency records are unchanged.
@@ -1,53 +0,0 @@
import { Test, TestingModule } from "@nestjs/testing";
import { AdminController } from "./admin.controller";
import { AdminService } from "./admin.service";
import { SettingsService } from "../settings/settings.service";
import { StageAuthorRestorationService } from "./stage-author-restoration.service";
describe("AdminController - Stage Author Restoration endpoint", () => {
let controller: AdminController;
let mockStageAuthorRestorationService: any;
beforeEach(async () => {
mockStageAuthorRestorationService = {
restoreStageAuthors: jest.fn().mockResolvedValue({
success: true,
totalConfigured: 5,
restoredCount: 5,
existingCount: 0,
authors: [],
}),
};
const module: TestingModule = await Test.createTestingModule({
controllers: [AdminController],
providers: [
{ provide: AdminService, useValue: {} },
{ provide: SettingsService, useValue: {} },
{
provide: StageAuthorRestorationService,
useValue: mockStageAuthorRestorationService,
},
],
}).compile();
controller = module.get<AdminController>(AdminController);
});
it.each([undefined, "10.0.0.2", "127.0.0.1.evil", "::ffff:10.0.0.2"])("denies non-loopback socket %s despite forwarded headers", async (remoteAddress) => {
await expect(controller.restoreStageAuthors({ socket: { remoteAddress }, headers: { "x-forwarded-for": "127.0.0.1" }, ip: "127.0.0.1" } as any)).rejects.toThrow();
expect(mockStageAuthorRestorationService.restoreStageAuthors).not.toHaveBeenCalled();
});
it.each(["::1", "::ffff:127.0.0.1"])("accepts loopback socket %s", async remoteAddress => {
await controller.restoreStageAuthors({ socket: { remoteAddress } } as any);
expect(mockStageAuthorRestorationService.restoreStageAuthors).toHaveBeenCalledTimes(1);
});
it("delegates restoreStageAuthors to StageAuthorRestorationService", async () => {
const result = await controller.restoreStageAuthors({ socket: { remoteAddress: "127.0.0.1" } } as any);
expect(mockStageAuthorRestorationService.restoreStageAuthors).toHaveBeenCalledTimes(1);
expect(result.success).toBe(true);
expect(result.restoredCount).toBe(5);
});
});
@@ -2,7 +2,6 @@ import { Test, TestingModule } from "@nestjs/testing";
import { AdminController } from "./admin.controller";
import { AdminService } from "./admin.service";
import { SettingsService } from "../settings/settings.service";
import { StageAuthorRestorationService } from "./stage-author-restoration.service";
describe("AdminController", () => {
let controller: AdminController;
@@ -13,7 +12,6 @@ describe("AdminController", () => {
providers: [
{ provide: AdminService, useValue: {} },
{ provide: SettingsService, useValue: {} },
{ provide: StageAuthorRestorationService, useValue: {} },
],
}).compile();
-19
View File
@@ -10,7 +10,6 @@ import {
Req,
UseGuards,
BadRequestException,
ForbiddenException,
} from "@nestjs/common";
import { AdminService, CouponInput } from "./admin.service";
import { ProductDto } from "./dto/product.dto";
@@ -31,7 +30,6 @@ import {
import { CreateUserDto, UpdateUserDto } from "./dto/user.dto";
import type { UserAdminActor } from "./user-role-policy";
import { SettingsService } from "../settings/settings.service";
import { StageAuthorRestorationService } from "./stage-author-restoration.service";
import { RolesGuard } from "../common/guards/roles.guard";
import { Roles } from "../common/decorators/roles.decorator";
@@ -45,7 +43,6 @@ export class AdminController {
constructor(
private readonly adminService: AdminService,
private readonly settingsService: SettingsService,
private readonly stageAuthorRestorationService?: StageAuthorRestorationService,
) {}
@Get("dashboard/stats")
@@ -76,22 +73,6 @@ export class AdminController {
};
}
@Post("users/stage-author-restoration")
@ApiOperation({
summary:
"بازیابی شناسه و مشخصات عمومی پنج نویسنده اورجینال مقالات در محیط استیج",
})
async restoreStageAuthors(@Req() req: { socket?: { remoteAddress?: string } }) {
const peer = req?.socket?.remoteAddress;
if (!peer || !["127.0.0.1", "::1", "::ffff:127.0.0.1"].includes(peer)) {
throw new ForbiddenException("Stage author restoration requires a loopback socket");
}
if (!this.stageAuthorRestorationService) {
throw new Error("StageAuthorRestorationService not initialized");
}
return this.stageAuthorRestorationService.restoreStageAuthors();
}
@Get("users/:id")
@ApiOperation({ summary: "جزئیات کاربر" })
async getUserDetails(@Param("id") id: string) {
-6
View File
@@ -1,5 +1,3 @@
import { CorporateController } from "./hermes/corporate.controller";
import { CorporateService } from "./hermes/corporate.service";
import { Module } from "@nestjs/common";
import { AdminController } from "./admin.controller";
import { AdminService } from "./admin.service";
@@ -28,12 +26,10 @@ import { RedisModule } from "../redis/redis.module";
import { SettingsModule } from "../settings/settings.module";
import { SupportChatAnalyticsController } from "./support-chat-analytics.controller";
import { SupportChatAnalyticsService } from "./support-chat-analytics.service";
import { StageAuthorRestorationService } from "./stage-author-restoration.service";
@Module({
imports: [PrismaModule, RedisModule, SettingsModule],
controllers: [
CorporateController,
AdminController,
ReportsController,
MediaController,
@@ -50,7 +46,6 @@ import { StageAuthorRestorationService } from "./stage-author-restoration.servic
SupportChatAnalyticsController,
],
providers: [
CorporateService,
AdminService,
ReportsService,
MediaService,
@@ -61,7 +56,6 @@ import { StageAuthorRestorationService } from "./stage-author-restoration.servic
SslService,
ApiKeysService,
SupportChatAnalyticsService,
StageAuthorRestorationService,
],
exports: [ApiKeysService, MediaService],
})
+24 -25
View File
@@ -8,34 +8,33 @@ import {
Param,
UseGuards,
HttpStatus,
} from '@nestjs/common';
import { ApiKeysService } from './api-keys.service';
import { CreateApiKeyDto } from './dto/api-key.dto';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
} from "@nestjs/common";
import { ApiKeysService } from "./api-keys.service";
import { CreateApiKeyDto } from "./dto/api-key.dto";
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
import {
ApiTags,
ApiBearerAuth,
ApiOperation,
ApiResponse,
} from '@nestjs/swagger';
} from "@nestjs/swagger";
import { RolesGuard } from '../common/guards/roles.guard';
import { HumanAdminGuard } from '../common/guards/human-admin.guard';
import { Roles } from '../common/decorators/roles.decorator';
import { RolesGuard } from "../common/guards/roles.guard";
import { Roles } from "../common/decorators/roles.decorator";
@ApiTags('Admin - مدیریت کلیدهای دسترسی (API Keys)')
@ApiTags("Admin - مدیریت کلیدهای دسترسی (API Keys)")
@ApiBearerAuth()
@UseGuards(JwtAuthGuard, RolesGuard, HumanAdminGuard)
@Roles('Admin', 'SUPER_ADMIN')
@Controller('admin/api-keys')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles("Admin", "SUPER_ADMIN")
@Controller("admin/api-keys")
export class ApiKeysController {
constructor(private readonly apiKeysService: ApiKeysService) {}
@Get()
@ApiOperation({ summary: 'دریافت لیست کلیدهای دسترسی API' })
@ApiOperation({ summary: "دریافت لیست کلیدهای دسترسی API" })
@ApiResponse({
status: HttpStatus.OK,
description: 'لیست کلیدها با موفقیت دریافت شد',
description: "لیست کلیدها با موفقیت دریافت شد",
})
async findAll() {
const keys = await this.apiKeysService.findAll();
@@ -46,39 +45,39 @@ export class ApiKeysController {
}
@Post()
@ApiOperation({ summary: 'ایجاد یک API Key جدید' })
@ApiOperation({ summary: "ایجاد یک API Key جدید" })
@ApiResponse({
status: HttpStatus.CREATED,
description: 'کلید جدید با موفقیت ایجاد شد',
description: "کلید جدید با موفقیت ایجاد شد",
})
async create(@Body() dto: CreateApiKeyDto) {
const result = await this.apiKeysService.create(dto);
return {
success: true,
message:
'کلید دسترسی با موفقیت ایجاد شد. لطفاً آن را در جای امن ذخیره نمایید.',
"کلید دسترسی با موفقیت ایجاد شد. لطفاً آن را در جای امن ذخیره نمایید.",
data: result,
};
}
@Patch(':id/toggle')
@ApiOperation({ summary: 'تغییر وضعیت فعال/غیرفعال کلید' })
async toggleStatus(@Param('id') id: string) {
@Patch(":id/toggle")
@ApiOperation({ summary: "تغییر وضعیت فعال/غیرفعال کلید" })
async toggleStatus(@Param("id") id: string) {
const updated = await this.apiKeysService.toggleStatus(id);
return {
success: true,
message: 'وضعیت کلید با موفقیت به‌روزرسانی شد',
message: "وضعیت کلید با موفقیت به‌روزرسانی شد",
data: updated,
};
}
@Delete(':id')
@ApiOperation({ summary: 'حذف کلید دسترسی' })
async delete(@Param('id') id: string) {
@Delete(":id")
@ApiOperation({ summary: "حذف کلید دسترسی" })
async delete(@Param("id") id: string) {
await this.apiKeysService.delete(id);
return {
success: true,
message: 'کلید دسترسی با موفقیت حذف شد',
message: "کلید دسترسی با موفقیت حذف شد",
};
}
}
@@ -1,127 +0,0 @@
import passport from 'passport';
import { Strategy, ExtractJwt } from 'passport-jwt';
import { sign } from 'jsonwebtoken';
import { PrismaClient } from '@prisma/client';
import { Test } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import request from 'supertest';
import { PrismaService } from '../prisma/prisma.service';
import { ApiKeysController } from './api-keys.controller';
import { ApiKeysService } from './api-keys.service';
const integration = process.env.CORPORATE_TEST_DATABASE_URL
? describe
: describe.skip;
integration(
'human-only key administration / real key authentication and PostgreSQL',
() => {
let app: INestApplication, db: PrismaService, service: ApiKeysService;
let rawKey: string, target: string;
const secret = 'isolated-test-jwt';
beforeAll(async () => {
const url = new URL(process.env.CORPORATE_TEST_DATABASE_URL!);
if (url.hostname !== '127.0.0.1' || url.pathname !== '/corporate_test')
throw new Error('Disposable DB required');
db = new PrismaClient({
datasources: { db: { url: url.toString() } },
}) as PrismaService;
passport.use(
'jwt',
new Strategy(
{
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: secret,
},
(p, done) => done(null, { id: p.sub, role: p.role }),
),
);
const module = await Test.createTestingModule({
controllers: [ApiKeysController],
providers: [ApiKeysService, { provide: PrismaService, useValue: db }],
}).compile();
service = module.get(ApiKeysService);
app = module.createNestApplication();
await app.listen(0, '127.0.0.1');
rawKey = (
await service.create({
name: 'security-fixture-admin',
scopes: ['admin'],
})
).rawKey;
target = (
await service.create({
name: 'security-fixture-target',
scopes: ['read'],
})
).apiKey.id;
});
afterAll(async () => {
await db?.apiKey.deleteMany({
where: { name: { startsWith: 'security-fixture' } },
});
await app?.close();
await db?.$disconnect();
passport.unuse('jwt');
});
it.each(['get', 'post', 'patch', 'delete'] as const)(
'denies %s to authenticated admin API key without mutating keys',
async (method) => {
const before = await db.apiKey.count();
const path =
'/admin/api-keys' +
(method === 'patch'
? `/${target}/toggle`
: method === 'delete'
? `/${target}`
: '');
await request(app.getHttpServer())
[method](path)
.set('x-api-key', rawKey)
.send(
method === 'post'
? { name: 'security-fixture-forged-reviewer', scopes: ['admin'] }
: {},
)
.expect(403);
expect(await db.apiKey.count()).toBe(before);
expect(
(await db.apiKey.findUniqueOrThrow({ where: { id: target } })).status,
).toBe('ACTIVE');
},
);
it('retains human admin CRUD and rejects nonadmin humans and wildcard keys', async () => {
const auth =
'Bearer ' + sign({ sub: 'fixture-human', role: 'Admin' }, secret);
const created = await request(app.getHttpServer())
.post('/admin/api-keys')
.set('Authorization', auth)
.send({ name: 'security-fixture-human', scopes: ['read'] })
.expect(201);
const id = created.body.data.apiKey.id;
await request(app.getHttpServer())
.get('/admin/api-keys')
.set('Authorization', auth)
.expect(200);
await request(app.getHttpServer())
.patch(`/admin/api-keys/${id}/toggle`)
.set('Authorization', auth)
.expect(200);
await request(app.getHttpServer())
.delete(`/admin/api-keys/${id}`)
.set('Authorization', auth)
.expect(200);
await request(app.getHttpServer())
.get('/admin/api-keys')
.set(
'Authorization',
'Bearer ' + sign({ sub: 'fixture-user', role: 'USER' }, secret),
)
.expect(403);
const wildcard = await service.create({
name: 'security-fixture-wildcard',
scopes: ['*'],
});
expect((await service.validateKey(wildcard.rawKey)).role).toBe('USER');
});
},
);
@@ -1,32 +0,0 @@
import { normalizeSearch, pagination, taskInput } from './corporate-policy';
describe('corporate contract policy', () => {
it('normalizes Persian letters, digits and separators', () => {
expect(normalizeSearch('كيك ۱۲۳ (ة)‌')).toBe('کیک 123 ه');
});
it('bounds pagination and sort keys', () => {
expect(pagination({ limit: '100' }).limit).toBe(100);
expect(() => pagination({ limit: '101' })).toThrow();
expect(() => pagination({ page: '-1' })).toThrow();
expect(() => pagination({ sortBy: 'password' })).toThrow();
});
it('defaults CEO priority and rejects status/command injection', () => {
expect(
taskInput({
title: 'عنوان',
description: 'کار',
department: 'CONTENT_SEO',
}).priority,
).toBe('CEO_EXPEDITE');
expect(() =>
taskInput({
title: 'x',
description: 'x',
department: 'CONTENT_SEO',
status: 'DONE',
}),
).toThrow();
expect(() =>
taskInput({ title: '', description: 'x', department: 'CONTENT_SEO' }),
).toThrow();
});
});
@@ -1,220 +0,0 @@
import { BadRequestException } from '@nestjs/common';
export const departments = [
'CONTENT_SEO',
'CATALOG_COMMERCE',
'WIKI_SCIENTIFIC',
'TECH_DEVOPS',
'MARKET_INTELLIGENCE',
];
export const priorities = ['CEO_EXPEDITE', 'CRITICAL', 'HIGH', 'MEDIUM', 'LOW'];
export const statuses = [
'TODO',
'IN_PROGRESS',
'TEST',
'DONE',
'BLOCKED',
'REJECTED',
'CANCELLED',
];
export function object(value: unknown, keys: string[]): Record<string, any> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
Object.keys(value).some((k) => !keys.includes(k))
)
throw new BadRequestException('Invalid fields');
return value as Record<string, any>;
}
export function text(value: unknown, max = 10000): string {
if (typeof value !== 'string' || !value.trim() || value.length > max)
throw new BadRequestException('Invalid text');
return value.trim();
}
export function uuid(value: unknown): string {
const id = text(value, 36);
if (
!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(
id,
)
)
throw new BadRequestException('Invalid UUID');
return id;
}
export function choice(value: unknown, values: string[]): string {
if (typeof value !== 'string' || !values.includes(value))
throw new BadRequestException('Invalid enum');
return value;
}
export function normalizeSearch(value: string): string {
return value
.normalize('NFKC')
.toLowerCase()
.replace(/[يى]/g, 'ی')
.replace(/ك/g, 'ک')
.replace(/ة/g, 'ه')
.replace(/[۰-۹٠-٩]/g, (c) =>
String(
'۰۱۲۳۴۵۶۷۸۹'.includes(c)
? '۰۱۲۳۴۵۶۷۸۹'.indexOf(c)
: '٠١٢٣٤٥٦٧٨٩'.indexOf(c),
),
)
.replace(/[\u200c\u200d()()]/g, ' ')
.replace(/[\u064b-\u065f]/g, '')
.replace(/\s+/g, ' ')
.trim();
}
export function pagination(q: Record<string, any>) {
const page = Number(q.page ?? 1),
limit = Number(q.limit ?? 20);
if (
!Number.isSafeInteger(page) ||
page < 1 ||
page > 1000000 ||
!Number.isInteger(limit) ||
limit < 1 ||
limit > 100
)
throw new BadRequestException('Invalid pagination');
const sortBy = choice(q.sortBy ?? 'createdAt', [
'createdAt',
'updatedAt',
'title',
'taskCode',
'priority',
'status',
]);
const sortOrder = choice(q.sortOrder ?? 'desc', ['asc', 'desc']) as
| 'asc'
| 'desc';
return { page, limit, skip: (page - 1) * limit, sortBy, sortOrder };
}
export function meta(total: number, page: number, limit: number) {
const totalPages = Math.ceil(total / limit);
return {
total,
page,
limit,
totalPages,
hasNextPage: page < totalPages,
hasPrevPage: page > 1,
};
}
export function taskInput(input: unknown) {
const b = object(input, [
'title',
'department',
'description',
'priority',
'parentId',
'goalId',
'actionType',
'dueCycle',
]);
return {
title: text(b.title, 300),
description: text(b.description),
department: choice(b.department, departments),
priority: choice(b.priority ?? 'CEO_EXPEDITE', priorities),
parentId: b.parentId === undefined ? undefined : uuid(b.parentId),
goalId: b.goalId === undefined ? undefined : uuid(b.goalId),
actionType: choice(b.actionType ?? 'CEO_DIRECTIVE', [
'CEO_DIRECTIVE',
'BLOG_NEW',
'BLOG_UPDATE',
'CATALOG_ENRICH',
'RESEARCH',
'ENGINEERING',
]),
dueCycle: b.dueCycle === undefined ? undefined : text(b.dueCycle, 40),
};
}
export function canonical(value: any): string {
if (Array.isArray(value)) return '[' + value.map(canonical).join(',') + ']';
if (value && typeof value === 'object')
return (
'{' +
Object.keys(value)
.sort()
.map((k) => JSON.stringify(k) + ':' + canonical(value[k]))
.join(',') +
'}'
);
return JSON.stringify(value);
}
/** Public projection must also cover nested evidence and child records. */
export function publicData(value: any): any {
if (value instanceof Date) return value;
if (Array.isArray(value)) return value.map(publicData);
if (value && typeof value === 'object')
return Object.fromEntries(
Object.entries(value)
.filter(([key]) => key !== 'claimToken')
.map(([key, item]) => [key, publicData(item)]),
);
return value;
}
export function httpsUrl(value: unknown): string {
const raw = text(value, 2000);
try {
if (!/^https:\/\/[a-z0-9]/i.test(raw) || /[\s\\]/.test(raw)) throw new Error();
const u = new URL(raw);
const host = u.hostname.toLowerCase();
if (
u.protocol !== 'https:' ||
u.username ||
u.password ||
!/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/.test(host) ||
host === 'localhost' ||
host.endsWith('.localhost') ||
/(^|\.)example\.(com|org|net)$/.test(host)
)
throw new Error();
return raw;
} catch {
throw new BadRequestException('Valid HTTPS host URL required');
}
}
export function timestamp(value: unknown, message: string): Date {
if (
typeof value !== 'string' ||
!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/.test(value)
)
throw new BadRequestException(message);
const date = new Date(value);
if (
!Number.isFinite(date.getTime()) ||
date.getTime() > Date.now() ||
date.toISOString().slice(0, 19) !== value.slice(0, 19)
)
throw new BadRequestException(message);
return date;
}
export function evidenceInput(input: unknown) {
const b = object(input, [
'claimToken',
'artifactUri',
'sha256',
'summary',
'tool',
'result',
]);
const uri = text(b.artifactUri, 2000);
const sha = text(b.sha256, 64);
if (!/^[a-f0-9]{64}$/.test(sha))
throw new BadRequestException('Invalid digest');
if (uri.startsWith('urn:')) {
if (uri !== 'urn:sha256:' + sha)
throw new BadRequestException('Digest locator mismatch');
} else httpsUrl(uri);
return {
claimToken: uuid(b.claimToken),
artifactUri: uri,
sha256: sha,
summary: text(b.summary),
tool: text(b.tool, 100),
result: text(b.result),
};
}
@@ -1,121 +0,0 @@
import {
Body,
Controller,
Get,
Headers,
Param,
Post,
Query,
Req,
UnauthorizedException,
UseGuards,
} from '@nestjs/common';
import { JwtAuthGuard } from '../../auth/jwt-auth.guard';
import { RolesGuard } from '../../common/guards/roles.guard';
import { Roles } from '../../common/decorators/roles.decorator';
import { CorporateService } from './corporate.service';
import { randomUUID } from 'crypto';
import { text } from './corporate-policy';
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('Admin', 'SUPER_ADMIN')
@Controller('admin/hermes')
export class CorporateController {
constructor(private readonly service: CorporateService) {}
private actor(req: any) {
// API keys must use their authenticated key identity, not an editable worker label.
const user = req.user;
const id = user?.id ?? user?.sub;
if (!id) throw new UnauthorizedException('Authenticated subject required');
return (user.isApiKey ? 'apikey:' : 'user:') + text(String(id), 200);
}
private key(key?: string) {
return text(key, 200);
}
@Get('runtime') runtime() {
return {
mode: 'MANUAL_DORMANT',
schedulesEnabled: false,
externalExecutionEnabled: false,
};
}
@Get('tasks') tasks(@Query() query: Record<string, any>) {
return this.service.tasks(query);
}
@Get('tasks/:id') detail(@Param('id') id: string) {
return this.service.detail(id);
}
@Post('tasks') create(
@Req() req: any,
@Headers('idempotency-key') key: string,
@Body() body: unknown,
) {
return this.service.create(this.actor(req), key ?? randomUUID(), body);
}
@Post('claims') claim(
@Req() req: any,
@Headers('idempotency-key') key: string,
@Body() body: unknown,
) {
return this.service.claim(this.actor(req), this.key(key), body);
}
@Post('tasks/:id/evidence') evidence(
@Req() req: any,
@Headers('idempotency-key') key: string,
@Param('id') id: string,
@Body() body: unknown,
) {
return this.service.submitEvidence(
this.actor(req),
this.key(key),
id,
body,
);
}
@Post('tasks/:id/reviews') review(
@Req() req: any,
@Headers('idempotency-key') key: string,
@Param('id') id: string,
@Body() body: unknown,
) {
return this.service.review(this.actor(req), this.key(key), id, body);
}
@Post('tasks/:id/effects') effect(
@Req() req: any,
@Headers('idempotency-key') key: string,
@Param('id') id: string,
@Body() body: unknown,
) {
return this.service.effect(this.actor(req), this.key(key), id, body);
}
@Get('market-insights') insights(@Query() q: Record<string, any>) {
return this.service.collection('market-insights', q);
}
@Post('market-insights') research(
@Req() req: any,
@Headers('idempotency-key') key: string,
@Body() body: unknown,
) {
return this.service.research(this.actor(req), this.key(key), body);
}
@Get('monthly-roadmap') roadmaps(@Query() q: Record<string, any>) {
return this.service.collection('monthly-roadmap', q);
}
@Post('monthly-roadmap') roadmap(
@Req() req: any,
@Headers('idempotency-key') key: string,
@Body() body: unknown,
) {
return this.service.roadmap(this.actor(req), this.key(key), body);
}
@Get('reports') reports(@Query() q: Record<string, any>) {
return this.service.collection('reports', q);
}
@Post('reports') report(
@Req() req: any,
@Headers('idempotency-key') key: string,
@Body() body: unknown,
) {
return this.service.report(this.actor(req), this.key(key), body);
}
}
@@ -1,561 +0,0 @@
import passport from 'passport';
import { Strategy, ExtractJwt } from 'passport-jwt';
import { PrismaClient } from '@prisma/client';
import { Test } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import { randomUUID } from 'crypto';
import request from 'supertest';
import { PrismaService } from '../../prisma/prisma.service';
import { CorporateController } from './corporate.controller';
import { CorporateService } from './corporate.service';
import { ApiKeysService } from '../api-keys.service';
const integration = process.env.CORPORATE_TEST_DATABASE_URL
? describe
: describe.skip;
integration('corporate API / disposable PostgreSQL', () => {
let app: INestApplication, db: PrismaService;
const key = () => randomUUID();
const post = (path: string, body: any, actor = 'executor', op = key()) =>
request(app.getHttpServer())
.post('/admin/hermes/' + path)
.set('x-api-key', actor)
.set('Idempotency-Key', op)
.send(body);
const input = {
title: 'كيك ۱۲۳',
description: 'integration fixture',
department: 'CONTENT_SEO',
};
beforeAll(async () => {
// Explicit disposable loopback opt-in only; never consumes runtime DATABASE_URL.
const url = new URL(process.env.CORPORATE_TEST_DATABASE_URL!);
if (url.hostname !== '127.0.0.1' || url.pathname !== '/corporate_test')
throw new Error('Disposable loopback corporate_test DB required');
passport.use(
'jwt',
new Strategy(
{
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: 'test-only-not-runtime',
},
(_payload, done) => done(null, false),
),
);
db = new PrismaClient({
datasources: { db: { url: process.env.CORPORATE_TEST_DATABASE_URL } },
}) as PrismaService;
const module = await Test.createTestingModule({
controllers: [CorporateController],
providers: [
CorporateService,
{ provide: PrismaService, useValue: db },
{
provide: ApiKeysService,
useValue: {
validateKey: async (id: string) => ({
id,
isApiKey: true,
role: 'Admin',
scopes: id === 'unscoped' ? [] : ['admin'],
}),
},
},
],
}).compile();
app = module.createNestApplication();
await app.listen(0, '127.0.0.1');
});
afterAll(async () => {
if (db)
await db.$executeRawUnsafe(
'TRUNCATE corporate_operations, corporate_reports, corporate_effects, corporate_reviews, corporate_evidence, corporate_events, corporate_tasks, corporate_goals, corporate_roadmaps, corporate_sources, corporate_research CASCADE',
);
await app?.close();
await db?.$disconnect();
passport.unuse('jwt');
});
beforeEach(async () => {
await db.$executeRawUnsafe(
'TRUNCATE corporate_operations, corporate_reports, corporate_effects, corporate_reviews, corporate_evidence, corporate_events, corporate_tasks, corporate_goals, corporate_roadmaps, corporate_sources, corporate_research CASCADE',
);
});
it('rejects children after a parent claim commits while child creation waits on its row lock', async () => {
const parent = (await post('tasks', input).expect(201)).body;
let release!: () => void, locked!: () => void;
const ready = new Promise<void>((r) => (locked = r));
const hold = new Promise<void>((r) => (release = r));
const claiming = db.$transaction(async (tx) => {
await tx.$queryRaw`SELECT id FROM corporate_tasks WHERE id=${parent.id}::uuid FOR UPDATE`;
await tx.corporateTask.update({
where: { id: parent.id },
data: {
status: 'IN_PROGRESS',
claimToken: key(),
assignedAgent: 'executor',
leasedUntil: new Date(Date.now() + 60000),
},
});
locked();
await hold;
});
await ready;
const pending = post('tasks', { ...input, parentId: parent.id }).then(
(r) => r,
);
try {
// Observe actual competing PostgreSQL lock wait, not a timing-only race.
let waiting = false;
for (let i = 0; i < 100; i++) {
const rows = await db.$queryRaw<
any[]
>`SELECT pid FROM pg_stat_activity WHERE datname=current_database() AND wait_event_type='Lock' AND query LIKE '%corporate_tasks%'`;
if (rows.length) {
waiting = true;
break;
}
await new Promise((r) => setTimeout(r, 10));
}
expect(waiting).toBe(true);
} finally {
release();
await claiming;
}
expect((await pending).status).toBe(409);
expect(
await db.corporateTask.count({ where: { parentId: parent.id } }),
).toBe(0);
});
it('accepts children on TODO and BLOCKED, which prevents parent claiming', async () => {
for (const status of ['TODO', 'BLOCKED'] as const) {
const parent = (await post('tasks', input).expect(201)).body;
await db.corporateTask.update({
where: { id: parent.id },
data: { status },
});
const child = (
await post('tasks', { ...input, parentId: parent.id }).expect(201)
).body;
expect((await post('claims', {}).expect(201)).body.task.id).toBe(
child.id,
);
}
});
it('rejects malformed artifact locators and mismatched digest URNs before persistence', async () => {
const task = (await post('tasks', input).expect(201)).body;
const claim = (await post('claims', {}).expect(201)).body.task;
const body = {
claimToken: claim.claimToken,
artifactUri: '',
sha256: 'a'.repeat(64),
summary: 'receipt',
tool: 'jest',
result: 'passed',
};
for (const artifactUri of [
'https://',
'https://?x',
'https:///pubmed.ncbi.nlm.nih.gov/x',
'https://pubmed.ncbi.nlm.nih.gov./x',
'https://bad host/x',
'https://user:pass@host.org/a',
'https://localhost/a',
'https://127.1/a',
'https://[::1]/a',
'urn:sha256:',
'urn:sha256:' + 'b'.repeat(64),
]) {
await post(`tasks/${task.id}/evidence`, { ...body, artifactUri }).expect(
400,
);
}
expect(await db.corporateEvidence.count()).toBe(0);
await post(`tasks/${task.id}/evidence`, {
...body,
artifactUri: 'https://pubmed.ncbi.nlm.nih.gov/123/',
}).expect(201);
});
it('rejects implicit timestamp coercions in source and effect inputs', async () => {
const service = app.get(CorporateService);
const research = {
title: 'research',
category: 'TREND',
source: 'receipt',
opportunity: 'investigate',
impact: 'LOW',
recommendedAction: 'measure',
cadence: 'MONTHLY',
provenance: { method: 'test', collector: 'fixture', context: 'isolated' },
sources: [
{
url: 'https://pubmed.ncbi.nlm.nih.gov/',
title: 'source',
excerpt: 'receipt',
retrievedAt: '',
sha256: 'a'.repeat(64),
},
],
};
for (const time of [
null,
0,
false,
[],
'2026-01-01',
'2026-02-30T00:00:00Z',
]) {
await expect(
Promise.resolve().then(() =>
service.research('fixture', key(), {
...research,
sources: [{ ...research.sources[0], retrievedAt: time }],
}),
),
).rejects.toThrow();
await expect(
Promise.resolve().then(() =>
service.effect('fixture', key(), key(), {
metric: 'views',
availability: 'UNAVAILABLE',
source: 'none',
observedAt: time,
}),
),
).rejects.toThrow('Invalid observation time');
}
for (const url of ['https://', 'https://?bad', 'https://bad host'])
await expect(
Promise.resolve().then(() =>
service.research('fixture', key(), {
...research,
sources: [
{
...research.sources[0],
retrievedAt: '2026-01-01T00:00:00Z',
url,
},
],
}),
),
).rejects.toThrow();
expect(await db.corporateResearch.count()).toBe(0);
});
it('public reads strip claim tokens recursively while claim and replay retain ownership token', async () => {
const parent = (await post('tasks', input).expect(201)).body;
const child = (
await post('tasks', { ...input, parentId: parent.id }).expect(201)
).body;
const op = key();
const claim = (await post('claims', {}, 'executor', op).expect(201)).body
.task;
expect(claim.claimToken).toBeTruthy();
expect(
(await post('claims', {}, 'executor', op).expect(201)).body.task
.claimToken,
).toBe(claim.claimToken);
await post(`tasks/${child.id}/evidence`, {
claimToken: claim.claimToken,
artifactUri: 'urn:sha256:' + 'a'.repeat(64),
sha256: 'a'.repeat(64),
summary: 'receipt',
tool: 'jest',
result: 'passed',
}).expect(201);
for (const path of ['tasks', 'tasks/' + child.id, 'tasks/' + parent.id]) {
const r = await request(app.getHttpServer())
.get('/admin/hermes/' + path)
.set('x-api-key', 'competitor')
.expect(200);
expect(JSON.stringify(r.body)).not.toContain('claimToken');
expect(JSON.stringify(r.body)).not.toContain(claim.claimToken);
}
});
it('bounds detail relations and report snapshots with explicit truncation and immutable replay', async () => {
const task = (await post('tasks', input).expect(201)).body;
await db.corporateEvent.createMany({
data: Array.from({ length: 105 }, () => ({
taskId: task.id,
speaker: 'SYSTEM',
speakerName: 'fixture',
step: 'FIXTURE',
content: 'x'.repeat(10000),
payload: { nested: ['x'.repeat(10000)] },
})),
});
const detail = await request(app.getHttpServer())
.get('/admin/hermes/tasks/' + task.id)
.set('x-api-key', 'executor')
.expect(200);
expect(detail.body.logs).toHaveLength(100);
expect(detail.body.relationsMeta.logs).toEqual({
total: 106,
returned: 100,
limit: 100,
truncated: true,
});
const op = key(),
body = { day: new Date().toISOString().slice(0, 10), summary: 'bounded' };
const report = (await post('reports', body, 'executor', op).expect(201))
.body;
expect(report.snapshot.events).toHaveLength(100);
expect(report.snapshot.meta.events).toEqual({
total: 106,
returned: 100,
limit: 100,
truncated: true,
});
expect(report.snapshot.events.every((e: any) => !('payload' in e))).toBe(
true,
);
expect(report.snapshot.meta.fieldsTruncated).toBe(true);
expect(
Buffer.byteLength(JSON.stringify(report.body ?? report)),
).toBeLessThan(1000000);
await db.corporateEvent.deleteMany();
expect(
(await post('reports', body, 'executor', op).expect(201)).body,
).toEqual(report);
});
it('rolls back oversized mutation responses instead of persisting huge idempotency values', async () => {
const service = app.get(CorporateService) as any;
const before = await db.corporateTask.count();
await expect(
service.operation('fixture', 'oversize', key(), {}, async (tx: any) => {
await tx.corporateTask.create({
data: {
title: 'rollback',
description: 'fixture',
taskCode: key(),
normalizedTitle: 'rollback',
normalizedCode: key(),
department: 'CONTENT_SEO',
createdBy: 'fixture',
},
});
return { value: 'x'.repeat(1100000) };
}),
).rejects.toThrow('Operation response exceeds limit');
expect(await db.corporateTask.count()).toBe(before);
expect(await db.corporateOperation.count()).toBe(0);
});
it('auth, UI list contract, normalized search, immutable idempotent replay', async () => {
await request(app.getHttpServer()).get('/admin/hermes/tasks').expect(401);
await post('tasks', input, 'unscoped').expect(403);
const op = key(),
a = await post('tasks', input, 'executor', op).expect(201);
const b = await post('tasks', input, 'executor', op).expect(201);
expect(b.body.id).toBe(a.body.id);
await post('tasks', { ...input, title: 'changed' }, 'executor', op).expect(
409,
);
const list = await request(app.getHttpServer())
.get('/admin/hermes/tasks?search=کیک%20123&limit=1')
.set('x-api-key', 'executor')
.expect(200);
expect(list.body.meta).toEqual({
total: 1,
page: 1,
limit: 1,
totalPages: 1,
hasNextPage: false,
hasPrevPage: false,
});
expect(list.body.data[0].priority).toBe('CEO_EXPEDITE');
await request(app.getHttpServer())
.get('/admin/hermes/tasks?limit=101')
.set('x-api-key', 'executor')
.expect(400);
await request(app.getHttpServer())
.get('/admin/hermes/tasks?sortBy=password')
.set('x-api-key', 'executor')
.expect(400);
});
it('claims exclusively, expires/reclaims, fences stale executor, requires independent QA', async () => {
const task = (await post('tasks', input).expect(201)).body;
const claims = await Promise.all([
post('claims', {}, 'executor'),
post('claims', {}, 'competitor'),
]);
expect(claims.filter((x) => x.body.task !== null)).toHaveLength(1);
const claimed = claims.find((x) => x.body.task !== null)!.body.task;
const oldActor = claimed.assignedAgent.replace('apikey:', '');
await db.$executeRaw`UPDATE corporate_tasks SET "leasedUntil"=clock_timestamp()-interval '1 second' WHERE id=${task.id}::uuid`;
const renewed = (await post('claims', {}, 'new-executor').expect(201)).body
.task;
expect(renewed.claimToken).not.toBe(claimed.claimToken);
const evidence = {
claimToken: claimed.claimToken,
artifactUri: 'urn:sha256:' + 'a'.repeat(64),
sha256: 'a'.repeat(64),
summary: 'receipt',
tool: 'jest',
result: 'passed',
};
await post(`tasks/${task.id}/evidence`, evidence, oldActor).expect(409);
const e = (
await post(
`tasks/${task.id}/evidence`,
{ ...evidence, claimToken: renewed.claimToken },
'new-executor',
).expect(201)
).body;
const review = {
evidenceId: e.id,
passed: true,
findings: 'verified',
verification: {
artifactUri: e.artifactUri,
sha256: e.sha256,
method: 'digest readback',
result: 'match',
},
};
await post(`tasks/${task.id}/reviews`, review, 'new-executor').expect(409);
await post(`tasks/${task.id}/reviews`, review, 'reviewer').expect(201);
const detail = await request(app.getHttpServer())
.get('/admin/hermes/tasks/' + task.id)
.set('x-api-key', 'reviewer')
.expect(200);
expect(detail.body.status).toBe('DONE');
expect(detail.body.logs.map((x: any) => x.step)).toContain('QA_PASSED');
await post(`tasks/${task.id}/effects`, {
metric: 'engagement',
availability: 'UNAVAILABLE',
observed: 0,
source: 'provider unavailable',
observedAt: new Date().toISOString(),
}).expect(400);
});
it('skips a held row lock and gives CEO priority before lower priorities', async () => {
const urgent = (await post('tasks', input).expect(201)).body;
const low = (await post('tasks', { ...input, priority: 'LOW' }).expect(201))
.body;
let release!: () => void, locked!: () => void;
const ready = new Promise<void>((r) => (locked = r)),
hold = new Promise<void>((r) => (release = r));
const locking = db.$transaction(async (tx) => {
await tx.$queryRaw`SELECT id FROM corporate_tasks WHERE id=${urgent.id}::uuid FOR UPDATE`;
locked();
await hold;
});
await ready;
try {
const claim = (await post('claims', {}).expect(201)).body.task;
expect(claim.id).toBe(low.id);
} finally {
release();
await locking;
}
const next = (await post('claims', {}, 'other').expect(201)).body.task;
expect(next.id).toBe(urgent.id);
});
it('serializes simultaneous duplicate mutations into one durable record', async () => {
const op = key();
const responses = await Promise.all([
post('tasks', input, 'executor', op),
post('tasks', input, 'executor', op),
]);
expect(responses.map((r) => r.status)).toEqual([201, 201]);
expect(responses[0].body.id).toBe(responses[1].body.id);
expect(await db.corporateTask.count()).toBe(1);
});
it('gates parents on children, persists provenance, roadmap/goals and reports', async () => {
const parent = (await post('tasks', input).expect(201)).body;
const child = (
await post('tasks', { ...input, parentId: parent.id }).expect(201)
).body;
const claim = (await post('claims', {}).expect(201)).body.task;
expect(claim.id).toBe(child.id);
const e = (
await post(`tasks/${child.id}/evidence`, {
claimToken: claim.claimToken,
artifactUri: 'urn:sha256:' + 'b'.repeat(64),
sha256: 'b'.repeat(64),
summary: 'child artifact',
tool: 'jest',
result: 'receipt',
}).expect(201)
).body;
await post(
`tasks/${child.id}/reviews`,
{
evidenceId: e.id,
passed: false,
findings: 'needs correction',
verification: {
artifactUri: e.artifactUri,
sha256: e.sha256,
method: 'readback',
result: 'failed',
},
},
'reviewer',
).expect(201);
expect(
(await db.corporateTask.findUniqueOrThrow({ where: { id: parent.id } }))
.status,
).toBe('BLOCKED');
expect((await post('claims', {}).expect(201)).body.task.id).toBe(child.id);
const research = (
await post('market-insights', {
title: 'fixture research',
category: 'TREND',
source: 'study receipt',
opportunity: 'investigate',
impact: 'LOW',
recommendedAction: 'measure',
cadence: 'MONTHLY',
provenance: {
method: 'test fixture',
collector: 'integration',
context: 'disposable',
},
sources: [
{
url: 'https://pubmed.ncbi.nlm.nih.gov/',
title: 'fixture',
excerpt: 'test-only',
retrievedAt: '2026-01-01T00:00:00Z',
sha256: 'a'.repeat(64),
},
],
}).expect(201)
).body;
const roadmap = (
await post('monthly-roadmap', {
researchId: research.id,
cycleName: 'test',
month: '2026-10',
seasonalTheme: 'evidence pending seasonal analysis',
strategicGoals: ['measure'],
plannedArticlesCount: 31,
plannedRefreshesCount: 0,
plannedCatalogEnrichments: 0,
goals: [
{
title: 'goal',
department: 'CONTENT_SEO',
acceptanceCriteria: 'QA',
metric: 'engagement',
},
],
}).expect(201)
).body;
expect(roadmap.goals).toHaveLength(1);
await post('tasks', { ...input, goalId: roadmap.goals[0].id }).expect(201);
for (const path of ['market-insights', 'monthly-roadmap']) {
const r = await request(app.getHttpServer())
.get('/admin/hermes/' + path)
.set('x-api-key', 'executor')
.expect(200);
expect(r.body.meta.total).toBe(1);
}
const report = (
await post('reports', {
day: new Date().toISOString().slice(0, 10),
summary: 'test fixture daily report',
}).expect(201)
).body;
expect(report.snapshot.tasks).toHaveLength(3);
});
});
@@ -1,704 +0,0 @@
import {
Injectable,
BadRequestException,
ConflictException,
NotFoundException,
} from '@nestjs/common';
import { Prisma, CorporatePriority } from '@prisma/client';
import { createHash, randomUUID } from 'crypto';
import { PrismaService } from '../../prisma/prisma.service';
import {
canonical,
publicData,
choice,
departments,
evidenceInput,
httpsUrl,
timestamp,
meta,
normalizeSearch,
object,
pagination,
priorities,
statuses,
taskInput,
text,
uuid,
} from './corporate-policy';
type Tx = Prisma.TransactionClient;
@Injectable()
export class CorporateService {
constructor(private readonly db: PrismaService) {}
private async operation(
actor: string,
op: string,
key: string,
body: unknown,
fn: (tx: Tx) => Promise<any>,
) {
text(key, 200);
const scoped = createHash('sha256')
.update(canonical([actor, op, key]))
.digest('hex');
const hash = createHash('sha256').update(canonical(body)).digest('hex');
return this.db.$transaction(
async (tx) => {
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${scoped}, 0))`;
const prior = await tx.corporateOperation.findUnique({
where: { key: scoped },
});
if (prior) {
if (prior.payloadHash !== hash)
throw new ConflictException('Idempotency key payload mismatch');
return prior.response;
}
const result = await fn(tx);
const serialized = JSON.stringify(result);
if (Buffer.byteLength(serialized, 'utf8') > 1000000)
throw new BadRequestException('Operation response exceeds limit');
const response = JSON.parse(serialized);
await tx.corporateOperation.create({
data: { key: scoped, payloadHash: hash, response },
});
return response;
},
{ maxWait: 10000, timeout: 20000 },
);
}
private event(
tx: Tx,
taskId: string,
actor: string,
step: string,
content: string,
speaker = 'SYSTEM',
payload?: any,
) {
return tx.corporateEvent.create({
data: { taskId, speaker, speakerName: actor, step, content, payload },
});
}
private async lock(tx: Tx, id: string) {
uuid(id);
const rows = await tx.$queryRaw<
{ id: string }[]
>`SELECT id FROM corporate_tasks WHERE id=${id}::uuid FOR UPDATE`;
if (!rows.length) throw new NotFoundException('Task not found');
return tx.corporateTask.findUniqueOrThrow({ where: { id } });
}
private async fenced(tx: Tx, id: string, token: string, actor: string) {
const t = await this.lock(tx, id);
const rows = await tx.$queryRaw<
{ id: string }[]
>`SELECT id FROM corporate_tasks WHERE id=${id}::uuid AND "claimToken"=${token}::uuid AND "assignedAgent"=${actor} AND "leasedUntil">clock_timestamp() AND status='IN_PROGRESS'`;
if (!rows.length) throw new ConflictException('Stale lease or owner');
return t;
}
async tasks(q: Record<string, any>) {
const p = pagination(q),
where: Prisma.CorporateTaskWhereInput = {};
if (q.department) where.department = choice(q.department, departments);
if (q.priority)
where.priority = choice(q.priority, priorities) as CorporatePriority;
if (q.status) where.status = choice(q.status, statuses) as any;
if (q.search) {
const search = normalizeSearch(text(q.search, 300));
where.OR = [
{ normalizedTitle: { contains: search } },
{ normalizedCode: { contains: search } },
];
}
if (q.goalId) where.goalId = uuid(q.goalId);
return this.db.$transaction(
async (tx) => {
const total = await tx.corporateTask.count({ where });
const data = await tx.corporateTask.findMany({
where,
skip: p.skip,
take: p.limit,
orderBy: [{ [p.sortBy]: p.sortOrder }, { id: 'asc' }],
});
return publicData({ data, meta: meta(total, p.page, p.limit) });
},
{ isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead },
);
}
async detail(id: string) {
uuid(id);
return this.db.$transaction(
async (tx) => {
const order = { id: 'asc' as const };
const task = await tx.corporateTask.findUnique({
where: { id },
include: {
logs: { take: 100, orderBy: [{ timestamp: 'asc' }, order] },
evidence: { take: 100, orderBy: order },
reviews: { take: 100, orderBy: order },
effects: { take: 100, orderBy: order },
children: { take: 100, orderBy: order },
_count: {
select: {
logs: true,
evidence: true,
reviews: true,
effects: true,
children: true,
},
},
},
});
if (!task) throw new NotFoundException('Task not found');
const { _count, ...data } = task;
const relationsMeta = Object.fromEntries(
Object.entries(_count).map(([name, total]) => [
name,
{
total,
returned: Math.min(total, 100),
limit: 100,
truncated: total > 100,
},
]),
);
return publicData({ ...data, relationsMeta });
},
{ isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead },
);
}
create(actor: string, key: string, input: unknown) {
const b = taskInput(input);
return this.operation(actor, 'create-task', key, b, async (tx) => {
if (b.parentId) {
const parent = await this.lock(tx, b.parentId);
if (!['TODO', 'BLOCKED'].includes(parent.status))
throw new ConflictException('Parent no longer accepts children');
}
const code = 'TSK-' + randomUUID();
const task = await tx.corporateTask.create({
data: {
...b,
priority: b.priority as CorporatePriority,
taskCode: code,
normalizedCode: normalizeSearch(code),
normalizedTitle: normalizeSearch(b.title),
createdBy: actor,
},
});
await this.event(tx, task.id, actor, 'CREATED', b.description, 'CEO');
return task;
});
}
claim(actor: string, key: string, input: unknown) {
const b = object(input, ['department', 'leaseSeconds']);
const department =
b.department === undefined ? null : choice(b.department, departments);
const seconds = Number(b.leaseSeconds ?? 300);
if (!Number.isInteger(seconds) || seconds < 30 || seconds > 900)
throw new BadRequestException('Lease must be 30..900 seconds');
return this.operation(
actor,
'claim',
key,
{ department, seconds },
async (tx) => {
const candidates = await tx.$queryRaw<
{ id: string }[]
>`SELECT t.id FROM corporate_tasks t
WHERE (t.status='TODO' OR (t.status='BLOCKED' AND EXISTS (SELECT 1 FROM corporate_tasks c WHERE c."parentId"=t.id)) OR (t.status='IN_PROGRESS' AND t."leasedUntil"<=clock_timestamp()))
AND (${department}::text IS NULL OR t.department=${department})
AND NOT EXISTS (SELECT 1 FROM corporate_tasks c WHERE c."parentId"=t.id AND c.status<>'DONE')
ORDER BY t.priority ASC,t."updatedAt" ASC,t.id ASC FOR UPDATE OF t SKIP LOCKED LIMIT 1`;
if (!candidates.length) return { task: null };
const id = candidates[0].id,
token = randomUUID();
await tx.$executeRaw`UPDATE corporate_tasks SET status='IN_PROGRESS', "assignedAgent"=${actor}, "claimToken"=${token}::uuid, "leasedUntil"=clock_timestamp()+make_interval(secs=>${seconds}::int), "executionCount"="executionCount"+1,"updatedAt"=clock_timestamp() WHERE id=${id}::uuid`;
await this.event(tx, id, actor, 'CLAIMED', 'Manual lease acquired');
return {
task: await tx.corporateTask.findUniqueOrThrow({ where: { id } }),
};
},
);
}
submitEvidence(actor: string, key: string, id: string, input: unknown) {
const b = evidenceInput(input);
return this.operation(actor, 'evidence:' + id, key, b, async (tx) => {
await this.fenced(tx, id, b.claimToken, actor);
const e = await tx.corporateEvidence.create({
data: { ...b, taskId: id, executor: actor },
});
await tx.corporateTask.update({
where: { id },
data: { status: 'TEST', leasedUntil: null },
});
await this.event(
tx,
id,
actor,
'EVIDENCE_SUBMITTED',
b.summary,
'AGENT',
{ evidenceId: e.id },
);
return e;
});
}
review(actor: string, key: string, id: string, input: unknown) {
const b = object(input, [
'evidenceId',
'passed',
'findings',
'verification',
]);
const evidenceId = uuid(b.evidenceId),
findings = text(b.findings);
if (typeof b.passed !== 'boolean')
throw new BadRequestException('passed must be boolean');
const v = object(b.verification, [
'artifactUri',
'sha256',
'method',
'result',
]);
const verification = {
artifactUri: text(v.artifactUri, 2000),
sha256: text(v.sha256, 64),
method: text(v.method, 1000),
result: text(v.result),
};
return this.operation(actor, 'review:' + id, key, b, async (tx) => {
uuid(id);
const relation = await tx.corporateTask.findUnique({
where: { id },
select: { parentId: true },
});
if (relation?.parentId) await this.lock(tx, relation.parentId);
const task = await this.lock(tx, id);
const evidence = await tx.corporateEvidence.findUnique({
where: { id: evidenceId },
});
if (
task.status !== 'TEST' ||
!evidence ||
evidence.taskId !== id ||
evidence.claimToken !== task.claimToken
)
throw new ConflictException('Current execution evidence required');
if (evidence.executor === actor)
throw new ConflictException('Independent reviewer required');
if (
verification.sha256 !== evidence.sha256 ||
verification.artifactUri !== evidence.artifactUri
)
throw new ConflictException('QA must verify exact artifact');
if (
b.passed &&
(await tx.corporateTask.count({
where: { parentId: id, status: { not: 'DONE' } },
}))
)
throw new ConflictException('Unfinished children');
const r = await tx.corporateReview.create({
data: {
taskId: id,
evidenceId,
reviewer: actor,
passed: b.passed,
findings,
verification,
},
});
await tx.corporateTask.update({
where: { id },
data: {
status: b.passed ? 'DONE' : 'TODO',
claimToken: null,
leasedUntil: null,
qaCount: { increment: 1 },
rejectionCount: { increment: b.passed ? 0 : 1 },
},
});
if (!b.passed && task.parentId) {
await tx.corporateTask.update({
where: { id: task.parentId },
data: { status: 'BLOCKED' },
});
await this.event(
tx,
task.parentId,
actor,
'CHILD_QA_REJECTED',
'Parent blocked pending child correction',
'QA',
{ childId: id },
);
}
await this.event(
tx,
id,
actor,
b.passed ? 'QA_PASSED' : 'QA_REJECTED',
findings,
'QA',
{ reviewId: r.id },
);
return r;
});
}
async collection(
kind: 'market-insights' | 'monthly-roadmap' | 'reports',
q: Record<string, any>,
) {
const p = pagination(q);
return this.db.$transaction(
async (tx) => {
const model =
kind === 'market-insights'
? tx.corporateResearch
: kind === 'monthly-roadmap'
? tx.corporateRoadmap
: tx.corporateReport;
const where: any = {};
if (kind === 'market-insights' && q.category)
where.category = choice(q.category, [
'TREND',
'COMPETITOR',
'NEW_CHANNEL',
'CATALOG_GAP',
]);
if (kind === 'monthly-roadmap' && q.month)
where.month = text(q.month, 40);
const delegate = model as any;
const total = await delegate.count({ where });
const data = await delegate.findMany({
where,
skip: p.skip,
take: p.limit,
orderBy: [{ createdAt: 'desc' }, { id: 'asc' }],
...(kind === 'market-insights'
? { include: { sources: true } }
: kind === 'monthly-roadmap'
? { include: { goals: true } }
: {}),
});
return publicData({ data, meta: meta(total, p.page, p.limit) });
},
{ isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead },
);
}
research(actor: string, key: string, input: unknown) {
const b = object(input, [
'title',
'category',
'source',
'opportunity',
'impact',
'recommendedAction',
'cadence',
'provenance',
'sources',
]);
if (!Array.isArray(b.sources) || !b.sources.length || b.sources.length > 30)
throw new BadRequestException('1..30 sources required');
const sources = b.sources.map((raw) => {
const s = object(raw, [
'url',
'title',
'excerpt',
'retrievedAt',
'sha256',
]);
const url = httpsUrl(s.url),
sha256 = text(s.sha256, 64),
retrievedAt = timestamp(s.retrievedAt, 'Invalid source time');
if (
!url.startsWith('https://') ||
!/^[a-f0-9]{64}$/.test(sha256) ||
!Number.isFinite(retrievedAt.getTime()) ||
retrievedAt.getTime() > Date.now()
)
throw new BadRequestException('Invalid source');
return {
url,
sha256,
retrievedAt,
title: text(s.title, 300),
excerpt: text(s.excerpt),
};
});
const provenance = object(b.provenance, ['method', 'collector', 'context']);
const data = {
title: text(b.title, 300),
category: choice(b.category, [
'TREND',
'COMPETITOR',
'NEW_CHANNEL',
'CATALOG_GAP',
]),
source: text(b.source, 2000),
opportunity: text(b.opportunity),
impact: choice(b.impact, ['HIGH', 'MEDIUM', 'LOW']),
recommendedAction: text(b.recommendedAction),
cadence: choice(b.cadence, ['MONTHLY', 'EVENT']),
provenance: {
method: text(provenance.method),
collector: text(provenance.collector, 300),
context: text(provenance.context),
},
createdBy: actor,
};
return this.operation(actor, 'research', key, b, (tx) =>
tx.corporateResearch.create({
data: { ...data, sources: { create: sources } },
include: { sources: true },
}),
);
}
roadmap(actor: string, key: string, input: unknown) {
const b = object(input, [
'researchId',
'cycleName',
'month',
'seasonalTheme',
'strategicGoals',
'plannedArticlesCount',
'plannedRefreshesCount',
'plannedCatalogEnrichments',
'isActive',
'goals',
]);
if (
!Array.isArray(b.strategicGoals) ||
!b.strategicGoals.length ||
b.strategicGoals.length > 30 ||
!Array.isArray(b.goals) ||
!b.goals.length ||
b.goals.length > 100
)
throw new BadRequestException('Goals required');
for (const k of [
'plannedArticlesCount',
'plannedRefreshesCount',
'plannedCatalogEnrichments',
])
if (!Number.isInteger(b[k]) || b[k] < 0 || b[k] > 10000)
throw new BadRequestException('Invalid counts');
if (b.isActive !== undefined && typeof b.isActive !== 'boolean')
throw new BadRequestException('Invalid active flag');
const goals = b.goals.map((raw) => {
const g = object(raw, [
'title',
'department',
'acceptanceCriteria',
'metric',
'target',
]);
if (
g.target !== undefined &&
(typeof g.target !== 'number' || !Number.isFinite(g.target))
)
throw new BadRequestException('Invalid target');
return {
title: text(g.title, 300),
department: choice(g.department, departments),
acceptanceCriteria: text(g.acceptanceCriteria),
metric: text(g.metric, 300),
target: g.target,
};
});
const data = {
researchId: uuid(b.researchId),
cycleName: text(b.cycleName, 300),
month: text(b.month, 40),
seasonalTheme: text(b.seasonalTheme),
strategicGoals: b.strategicGoals.map((g) => text(g, 1000)),
plannedArticlesCount: b.plannedArticlesCount,
plannedRefreshesCount: b.plannedRefreshesCount,
plannedCatalogEnrichments: b.plannedCatalogEnrichments,
isActive: b.isActive ?? false,
createdBy: actor,
};
return this.operation(actor, 'roadmap', key, b, async (tx) => {
const research = await tx.corporateResearch.findUnique({
where: { id: data.researchId },
include: { sources: true },
});
if (!research || !research.sources.length)
throw new ConflictException('Evidence-backed research required');
const result = await tx.corporateRoadmap.create({
data: { ...data, goals: { create: goals } },
include: { goals: true },
});
await tx.corporateResearch.update({
where: { id: research.id },
data: { status: 'IN_BACKLOG' },
});
return result;
});
}
effect(actor: string, key: string, id: string, input: unknown) {
const b = object(input, [
'metric',
'availability',
'baseline',
'observed',
'source',
'observedAt',
]);
const availability = choice(b.availability, [
'MEASURED',
'UNAVAILABLE',
'UNINSTRUMENTED',
'BUSINESS_DISABLED',
]);
for (const k of ['baseline', 'observed'])
if (
b[k] !== undefined &&
b[k] !== null &&
(typeof b[k] !== 'number' || !Number.isFinite(b[k]))
)
throw new BadRequestException('Invalid metric');
if (availability === 'MEASURED' && typeof b.observed !== 'number')
throw new BadRequestException('Measured value required');
if (
availability !== 'MEASURED' &&
(b.observed != null || b.baseline != null)
)
throw new BadRequestException('Unavailable is not zero');
const observedAt = timestamp(b.observedAt, 'Invalid observation time');
if (
!Number.isFinite(observedAt.getTime()) ||
observedAt.getTime() > Date.now()
)
throw new BadRequestException('Invalid observation time');
return this.operation(actor, 'effect:' + id, key, b, async (tx) => {
const task = await this.lock(tx, id);
if (task.status !== 'DONE')
throw new ConflictException('Effects require completed QA');
const e = await tx.corporateEffect.create({
data: {
taskId: id,
metric: text(b.metric, 300),
availability,
baseline: b.baseline,
observed: b.observed,
source: text(b.source, 2000),
observedAt,
recordedBy: actor,
},
});
await this.event(tx, id, actor, 'EFFECT_RECORDED', e.metric, 'SYSTEM', {
effectId: e.id,
});
return e;
});
}
report(actor: string, key: string, input: unknown) {
const b = object(input, ['day', 'summary']);
const day = text(b.day, 10),
summary = text(b.summary);
if (
!/^\d{4}-\d{2}-\d{2}$/.test(day) ||
!Number.isFinite(Date.parse(day + 'T00:00:00Z'))
)
throw new BadRequestException('ISO day required');
return this.operation(actor, 'report', key, b, async (tx) => {
const start = new Date(day + 'T00:00:00Z'),
end = new Date(start.getTime() + 86400000);
const taskWhere = { updatedAt: { gte: start, lt: end } };
const eventWhere = { timestamp: { gte: start, lt: end } };
const effectWhere = { createdAt: { gte: start, lt: end } };
const totals = {
tasks: await tx.corporateTask.count({ where: taskWhere }),
events: await tx.corporateEvent.count({ where: eventWhere }),
effects: await tx.corporateEffect.count({ where: effectWhere }),
};
const tasks = await tx.corporateTask.findMany({
where: taskWhere,
take: 100,
orderBy: [{ updatedAt: 'asc' }, { id: 'asc' }],
select: {
id: true,
taskCode: true,
title: true,
status: true,
department: true,
updatedAt: true,
},
});
const events = await tx.corporateEvent.findMany({
where: eventWhere,
take: 100,
orderBy: [{ timestamp: 'asc' }, { id: 'asc' }],
select: {
id: true,
taskId: true,
timestamp: true,
speaker: true,
speakerName: true,
step: true,
content: true,
},
});
const effects = await tx.corporateEffect.findMany({
where: effectWhere,
take: 100,
orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],
select: {
id: true,
taskId: true,
metric: true,
availability: true,
baseline: true,
observed: true,
source: true,
observedAt: true,
createdAt: true,
},
});
let fieldsTruncated = false;
const project = (rows: any[]) =>
rows.map((row) =>
Object.fromEntries(
Object.entries(row).map(([name, value]) => {
if (typeof value === 'string' && value.length > 1000) {
fieldsTruncated = true;
return [name, value.slice(0, 1000)];
}
return [name, value];
}),
),
);
const bounded = {
tasks: project(tasks),
events: project(events),
effects: project(effects),
};
const counts = Object.fromEntries(
Object.entries(totals).map(([name, total]) => [
name,
{
total,
returned: Math.min(total, 100),
limit: 100,
truncated: total > 100,
},
]),
);
const snapshot = JSON.parse(
JSON.stringify({
timezone: 'UTC',
...bounded,
meta: {
...counts,
fieldsTruncated,
stringLimit: 1000,
eventPayloadsOmitted: true,
},
}),
);
return tx.corporateReport.create({
data: { day, summary, snapshot, createdBy: actor },
});
});
}
}
@@ -1,274 +0,0 @@
import {
ConflictException,
ForbiddenException,
} from "@nestjs/common";
import {
StageAuthorRestorationService,
GENUINE_STAGE_AUTHORS,
STAGE_AUTHOR_ROLE,
assertStageScope,
} from "./stage-author-restoration.service";
import { Prisma } from "@prisma/client";
describe("StageAuthorRestorationService (Unit & TDD)", () => {
let service: StageAuthorRestorationService;
let mockPrisma: any;
let mockTx: any;
beforeEach(() => {
mockTx = {
$queryRaw: jest.fn().mockResolvedValue(GENUINE_STAGE_AUTHORS.map((a, i) => ({ authorId: a.id, count: BigInt([16, 2, 3, 14, 17][i]) }))),
user: {
findUnique: jest.fn(),
create: jest.fn(),
},
};
mockPrisma = {
$transaction: jest.fn(async (cb) => cb(mockTx)),
};
service = new StageAuthorRestorationService(mockPrisma as any);
});
describe("assertStageScope environment gating", () => {
it("denies execution in default production environment", () => {
expect(() =>
assertStageScope({ NODE_ENV: "production", APP_ENV: "production" }),
).toThrow(ForbiddenException);
});
it("denies execution when neither APP_ENV nor STAGE flag is set", () => {
expect(() => assertStageScope({})).toThrow(ForbiddenException);
});
it("denies execution with only APP_ENV is stage", () => {
expect(() => assertStageScope({ APP_ENV: "stage" })).toThrow(ForbiddenException);
});
it("denies execution with only STAGE_AUTHOR_RESTORATION_ENABLED is true", () => {
expect(() =>
assertStageScope({ STAGE_AUTHOR_RESTORATION_ENABLED: "true" }),
).toThrow(ForbiddenException);
});
it("denies execution with only DATABASE_URL points to caninodb_stage", () => {
expect(() =>
assertStageScope({
DATABASE_URL: "postgresql://user:pass@db:5432/caninodb_stage",
}),
).toThrow(ForbiddenException);
});
});
describe("restoreStageAuthors TDD lifecycle", () => {
const stageEnv = { APP_ENV: "stage", STAGE_AUTHOR_RESTORATION_ENABLED: "true", STAGE_AUTHOR_RESTORATION_MODE: "maintenance", DATABASE_URL: "postgresql://user@canino_db_stage:5432/caninodb_stage" };
it("rejects a partial existing set before any writes", async () => {
mockTx.user.findUnique.mockResolvedValueOnce({ ...GENUINE_STAGE_AUTHORS[0], role: STAGE_AUTHOR_ROLE });
mockTx.user.findUnique.mockResolvedValue(null);
await expect(service.restoreStageAuthors(stageEnv)).rejects.toThrow(ConflictException);
expect(mockTx.user.create).not.toHaveBeenCalled();
});
it("does not allow enabled production scope", () => {
expect(() => assertStageScope({ ...stageEnv, APP_ENV: "production" })).toThrow(ForbiddenException);
});
it("rejects a stage-looking substring in the database identity", () => {
expect(() => assertStageScope({ ...stageEnv, DATABASE_URL: "postgresql://user@evil/caninodb_stage_prod" })).toThrow(ForbiddenException);
});
it("requires explicit mode", () => {
expect(() => assertStageScope({ ...stageEnv, STAGE_AUTHOR_RESTORATION_MODE: undefined })).toThrow(ForbiddenException);
});
it("rejects unsafe replay even with identical names", async () => {
mockTx.user.findUnique.mockImplementation(async ({ where }: any) => ({ ...GENUINE_STAGE_AUTHORS.find(a => a.id === where.id), role: "Admin" }));
await expect(service.restoreStageAuthors(stageEnv)).rejects.toThrow(ConflictException);
expect(mockTx.user.create).not.toHaveBeenCalled();
});
it("uses a Serializable transaction", async () => {
mockTx.user.findUnique.mockResolvedValue(null);
try { await service.restoreStageAuthors(stageEnv); } catch {}
expect(mockPrisma.$transaction).toHaveBeenCalledWith(expect.any(Function), { isolationLevel: Prisma.TransactionIsolationLevel.Serializable });
});
it("rejects unexpected orphan distribution without writing", async () => {
mockTx.user.findUnique.mockResolvedValue(null);
mockTx.$queryRaw = jest.fn().mockResolvedValue([{ authorId: GENUINE_STAGE_AUTHORS[0].id, count: 52n }]);
await expect(service.restoreStageAuthors(stageEnv)).rejects.toThrow(ConflictException);
expect(mockTx.user.create).not.toHaveBeenCalled();
});
it("rejects replay with remaining orphans", async () => {
mockTx.user.findUnique.mockImplementation(async ({ where }: any) => ({ ...GENUINE_STAGE_AUTHORS.find(a => a.id === where.id), role: STAGE_AUTHOR_ROLE, isPublicAuthor: true, mobile: null, email: null, password: null, authExpiresAt: null, walletBalance: new Prisma.Decimal(0), charityDonationTotal: new Prisma.Decimal(0), stageTestGeneration: null, stageTestSession: null }));
mockTx.$queryRaw = jest.fn().mockResolvedValue([{ authorId: GENUINE_STAGE_AUTHORS[0].id, count: 1n }]);
await expect(service.restoreStageAuthors(stageEnv)).rejects.toThrow(ConflictException);
});
it("accepts a loopback rehearsal database only in rehearsal mode", () => {
expect(() => assertStageScope({ ...stageEnv, STAGE_AUTHOR_RESTORATION_MODE: "rehearsal", DATABASE_URL: "postgresql://user@127.0.0.1:5432/rehearsal" })).not.toThrow();
});
it("rejects rehearsal database in maintenance mode", () => {
expect(() => assertStageScope({ ...stageEnv, DATABASE_URL: "postgresql://user@127.0.0.1:5432/rehearsal" })).toThrow(ForbiddenException);
});
it("requires both stage identity and enable flag", () => {
expect(() => assertStageScope({ ...stageEnv, STAGE_AUTHOR_RESTORATION_ENABLED: undefined })).toThrow(ForbiddenException);
});
it("rejects a URL with conflicting host override", () => {
expect(() => assertStageScope({ ...stageEnv, DATABASE_URL: "postgresql://user@canino_db_stage/caninodb_stage?host=prod" })).toThrow(ForbiddenException);
});
it("requires the public-author marker on replay", async () => {
mockTx.user.findUnique.mockImplementation(async ({ where }: any) => ({ ...GENUINE_STAGE_AUTHORS.find(a => a.id === where.id), role: STAGE_AUTHOR_ROLE, mobile: null, email: null, password: null, isPublicAuthor: false }));
await expect(service.restoreStageAuthors(stageEnv)).rejects.toThrow(ConflictException);
expect(mockTx.user.create).not.toHaveBeenCalled();
});
it("rejects malformed URL without database work", async () => {
await expect(service.restoreStageAuthors({ ...stageEnv, DATABASE_URL: "not-a-url" })).rejects.toThrow(ForbiddenException);
expect(mockPrisma.$transaction).not.toHaveBeenCalled();
});
it("rejects unexpected scheme", () => {
expect(() => assertStageScope({ ...stageEnv, DATABASE_URL: "https://canino_db_stage/caninodb_stage" })).toThrow(ForbiddenException);
});
it("does not allow a production database with a stage query string", () => {
expect(() => assertStageScope({ ...stageEnv, DATABASE_URL: "postgresql://user@db/prod?stage=caninodb_stage" })).toThrow(ForbiddenException);
});
it("rejects a credential-bearing replay", async () => {
mockTx.user.findUnique.mockImplementation(async ({ where }: any) => ({ ...GENUINE_STAGE_AUTHORS.find(a => a.id === where.id), role: STAGE_AUTHOR_ROLE, isPublicAuthor: true, password: "hash", mobile: null, email: null }));
await expect(service.restoreStageAuthors(stageEnv)).rejects.toThrow(ConflictException);
expect(mockTx.user.create).not.toHaveBeenCalled();
});
it("rejects no-orphan initial state", async () => {
mockTx.user.findUnique.mockResolvedValue(null);
mockTx.$queryRaw = jest.fn().mockResolvedValue([]);
await expect(service.restoreStageAuthors(stageEnv)).rejects.toThrow(ConflictException);
expect(mockTx.user.create).not.toHaveBeenCalled();
});
it("writes the public-author marker", async () => {
mockTx.user.findUnique.mockResolvedValue(null);
mockTx.user.create.mockImplementation(async ({ data }: any) => data);
mockTx.$queryRaw = jest.fn().mockResolvedValue(GENUINE_STAGE_AUTHORS.map((a, i) => ({ authorId: a.id, count: BigInt([16, 2, 3, 14, 17][i]) })));
await service.restoreStageAuthors(stageEnv);
for (const [call] of mockTx.user.create.mock.calls) expect(call.data.isPublicAuthor).toBe(true);
});
// Legacy lifecycle assertions below also exercise the stricter preflight.
it("restores all 5 genuine authors when none exist in Stage", async () => {
mockTx.user.findUnique.mockResolvedValue(null);
mockTx.user.create.mockImplementation(async ({ data }: any) => ({
id: data.id,
firstName: data.firstName,
lastName: data.lastName,
role: data.role,
}));
const res = await service.restoreStageAuthors(stageEnv);
expect(res.success).toBe(true);
expect(res.totalConfigured).toBe(5);
expect(res.restoredCount).toBe(5);
expect(res.existingCount).toBe(0);
expect(mockTx.user.create).toHaveBeenCalledTimes(5);
// Verify safe non-login fields: no credentials, no contact, no elevated role
for (const call of mockTx.user.create.mock.calls) {
const payload = call[0].data;
expect(payload.role).toBe(STAGE_AUTHOR_ROLE);
expect(payload.mobile).toBeNull();
expect(payload.email).toBeNull();
expect(payload.password).toBeNull();
expect(payload.walletBalance).toEqual(new Prisma.Decimal(0));
// Verify genuine author ID is preserved
const match = GENUINE_STAGE_AUTHORS.find((a) => a.id === payload.id);
expect(match).toBeDefined();
expect(payload.firstName).toBe(match!.firstName);
expect(payload.lastName).toBe(match!.lastName);
}
});
it("is strictly idempotent: repeated calls report existing and perform no creates", async () => {
mockTx.$queryRaw.mockResolvedValue([]);
mockTx.user.findUnique.mockImplementation(async ({ where }: any) => {
const match = GENUINE_STAGE_AUTHORS.find((a) => a.id === where.id);
if (!match) return null;
return {
id: match.id,
firstName: match.firstName,
lastName: match.lastName,
role: STAGE_AUTHOR_ROLE,
mobile: null,
email: null,
password: null,
isPublicAuthor: true,
authExpiresAt: null,
stageTestGeneration: null,
stageTestSession: null,
walletBalance: new Prisma.Decimal(0),
charityDonationTotal: new Prisma.Decimal(0),
};
});
const res = await service.restoreStageAuthors(stageEnv);
expect(res.success).toBe(true);
expect(res.totalConfigured).toBe(5);
expect(res.restoredCount).toBe(0);
expect(res.existingCount).toBe(5);
expect(mockTx.user.create).not.toHaveBeenCalled();
});
it("fails closed with 409 Conflict when existing record has conflicting name", async () => {
mockTx.user.findUnique.mockImplementation(async ({ where }: any) => {
if (where.id === GENUINE_STAGE_AUTHORS[0].id) {
return {
id: where.id,
firstName: "Fake",
lastName: "Impersonator",
role: "Admin",
};
}
return null;
});
await expect(service.restoreStageAuthors(stageEnv)).rejects.toThrow(
ConflictException,
);
expect(mockTx.user.create).not.toHaveBeenCalled();
});
it("handles partial restoration: restores only missing authors and retains existing identical ones", async () => {
mockTx.user.findUnique.mockImplementation(async ({ where }: any) => {
if (where.id === GENUINE_STAGE_AUTHORS[0].id) {
return {
id: where.id,
firstName: GENUINE_STAGE_AUTHORS[0].firstName,
lastName: GENUINE_STAGE_AUTHORS[0].lastName,
role: STAGE_AUTHOR_ROLE,
};
}
return null;
});
mockTx.user.create.mockImplementation(async ({ data }: any) => ({
id: data.id,
firstName: data.firstName,
lastName: data.lastName,
role: data.role,
}));
await expect(service.restoreStageAuthors(stageEnv)).rejects.toThrow(ConflictException);
expect(mockTx.user.create).not.toHaveBeenCalled();
});
});
});
@@ -1,183 +0,0 @@
import {
ConflictException,
ForbiddenException,
Injectable,
} from "@nestjs/common";
import { PrismaService } from "../prisma/prisma.service";
import { Prisma } from "@prisma/client";
export const GENUINE_STAGE_AUTHORS = [
{
id: "14490d36-52fc-40be-8637-b7b04b8302f8",
firstName: "کارشناس",
lastName: "تغذیه تیم کنینا",
},
{
id: "4e0d830c-0125-4f08-8cb7-c5ae0a38cee7",
firstName: "آرزو",
lastName: "فراشیانی",
},
{
id: "63d38117-f864-4af6-afa0-ae5b05255f57",
firstName: "کارشناس",
lastName: "تحقیقات و کنترل کیفیت کنینا",
},
{
id: "7b1e51d1-8c32-4a3c-804f-948d706aef36",
firstName: "کارشناس",
lastName: "رفتار و نگهداری تیم کنینا",
},
{
id: "f57e0f98-efee-4fa1-90ef-67bf84cafad4",
firstName: "دکتر",
lastName: "دامپزشک تیم کنینا",
},
] as const;
export const STAGE_AUTHOR_ROLE = "User_PetOwner";
export function assertStageScope(env: NodeJS.ProcessEnv = process.env): void {
let identityAllowed = false;
try {
const url = new URL(env.DATABASE_URL || "");
const mode = env.STAGE_AUTHOR_RESTORATION_MODE;
identityAllowed =
["postgresql:", "postgres:"].includes(url.protocol) &&
!url.search && !url.hash &&
((mode === "maintenance" && (!url.port || url.port === "5432") && url.hostname === "canino_db_stage" && url.pathname === "/caninodb_stage") ||
(mode === "rehearsal" && url.hostname === "127.0.0.1" && url.pathname === "/rehearsal"));
} catch {
// Malformed and absent URLs are denied without exposing credentials.
}
if (env.APP_ENV !== "stage" || env.STAGE_AUTHOR_RESTORATION_ENABLED !== "true" || !identityAllowed) {
throw new ForbiddenException(
"Stage author restoration is strictly restricted to authorized Stage environments",
);
}
}
export interface StageAuthorRestoreResult {
success: boolean;
totalConfigured: number;
restoredCount: number;
existingCount: number;
authors: Array<{
id: string;
firstName: string;
lastName: string;
role: string;
status: "restored" | "already_present";
}>;
}
@Injectable()
export class StageAuthorRestorationService {
constructor(private readonly prisma: PrismaService) {}
async restoreStageAuthors(
env: NodeJS.ProcessEnv = process.env,
): Promise<StageAuthorRestoreResult> {
assertStageScope(env);
return this.prisma.$transaction(async (tx) => {
const results: StageAuthorRestoreResult["authors"] = [];
let restoredCount = 0;
let existingCount = 0;
// Read the entire candidate set and every dangling reference before writing.
const candidates = await Promise.all(GENUINE_STAGE_AUTHORS.map(author => tx.user.findUnique({ where: { id: author.id } })));
const orphans = await tx.$queryRaw<Array<{ authorId: string; count: bigint }>>`
SELECT b.author_id AS "authorId", COUNT(*) AS count
FROM blogs b LEFT JOIN users u ON u.id = b.author_id
WHERE b.author_id IS NOT NULL AND u.id IS NULL
GROUP BY b.author_id
`;
const present = candidates.filter(Boolean).length;
if (present !== 0 && present !== GENUINE_STAGE_AUTHORS.length) {
throw new ConflictException("Partial author restoration is not permitted");
}
if (present === 0) {
const counts = [16, 2, 3, 14, 17];
if (orphans.length !== 5 || !GENUINE_STAGE_AUTHORS.every((a, i) =>
orphans.filter(o => o.authorId === a.id && Number(o.count) === counts[i]).length === 1)) {
throw new ConflictException("Expected exactly 52 orphan blogs with the reviewed author distribution");
}
} else {
if (orphans.length !== 0 || !candidates.every((row, i) => row &&
row.id === GENUINE_STAGE_AUTHORS[i].id &&
row.firstName === GENUINE_STAGE_AUTHORS[i].firstName &&
row.lastName === GENUINE_STAGE_AUTHORS[i].lastName &&
row.role === STAGE_AUTHOR_ROLE && row.isPublicAuthor === true &&
row.mobile === null && row.email === null && row.password === null &&
row.authExpiresAt === null && row.stageTestGeneration === null && row.stageTestSession === null &&
row.walletBalance.equals(0) && row.charityDonationTotal.equals(0))) {
throw new ConflictException("Replay requires all five exact safe author rows and zero orphan blogs");
}
}
for (const [index, author] of GENUINE_STAGE_AUTHORS.entries()) {
const existing = candidates[index];
// Candidate identity was validated atomically above.
if (existing) {
if (
existing.firstName !== author.firstName ||
existing.lastName !== author.lastName
) {
throw new ConflictException(
`Identity conflict for author UUID ${author.id}: existing name '${existing.firstName} ${existing.lastName}' conflicts with genuine name '${author.firstName} ${author.lastName}'`,
);
}
results.push({
id: existing.id,
firstName: existing.firstName,
lastName: existing.lastName,
role: existing.role,
status: "already_present",
});
existingCount++;
} else {
// Create author with safe non-login profile fields only
// No synthetic mobile, no synthetic email, no password, no admin privileges
const created = await tx.user.create({
data: {
id: author.id,
firstName: author.firstName,
lastName: author.lastName,
role: STAGE_AUTHOR_ROLE,
isPublicAuthor: true,
mobile: null,
email: null,
password: null,
walletBalance: new Prisma.Decimal(0),
},
select: {
id: true,
firstName: true,
lastName: true,
role: true,
},
});
results.push({
id: created.id,
firstName: created.firstName,
lastName: created.lastName,
role: created.role,
status: "restored",
});
restoredCount++;
}
}
return {
success: true,
totalConfigured: GENUINE_STAGE_AUTHORS.length,
restoredCount,
existingCount,
authors: results,
};
}, { isolationLevel: Prisma.TransactionIsolationLevel.Serializable });
}
}
-2
View File
@@ -38,12 +38,10 @@ import { FaqModule } from "./faq/faq.module";
import { MenuModule } from "./menu/menu.module";
import { RevalidationModule } from "./common/revalidation/revalidation.module";
import { SeoTrackingModule } from "./seo-tracking/seo-tracking.module";
import { Request, Response, NextFunction } from "express";
@Module({
imports: [
SeoTrackingModule,
SupportChatModule,
RevalidationModule,
SmsModule,
+1 -1
View File
@@ -233,7 +233,7 @@ export class AuthController {
async refresh(
@Req()
req: {
user: { id: string; email?: string; role?: string; mobile?: string | null };
user: { id: string; email?: string; role?: string; mobile?: string };
},
@Res({ passthrough: true }) res?: Response,
) {
+8 -20
View File
@@ -69,8 +69,6 @@ export class AuthService {
async sendOtp(sendOtpDto: SendOtpDto) {
const phoneNumber = normalizeMobile(sendOtpDto.phoneNumber);
const user = await this.prisma.user.findUnique({ where: { mobile: phoneNumber } });
if (user) assertPrincipalActive(user);
// 1. Check 60-second cooldown per phone number
const cooldownKey = `otp:cooldown:${phoneNumber}`;
@@ -222,7 +220,6 @@ export class AuthService {
const firstName = registerDto.firstName.trim();
const lastName = registerDto.lastName.trim();
const mobile = normalizeMobile(registerDto.mobile);
if (!mobile) throw new BadRequestException("شماره موبایل الزامی است");
const email = registerDto.email
? registerDto.email.trim().toLowerCase()
: null;
@@ -322,15 +319,15 @@ export class AuthService {
}
async adminLogin(body: AdminLoginInput) {
// Resolve email before checking roles so public authors cannot enter the env fallback.
// First check database for user with role 'Admin' or 'SUPER_ADMIN'
const dbAdmin = await this.prisma.user.findFirst({
where: { email: body.email },
where: {
email: body.email,
role: { in: ["Admin", "SUPER_ADMIN", "ADMIN"] },
},
});
// Reject before credential/fallback evaluation, including accidentally assigned admin roles.
if (dbAdmin) assertPrincipalActive(dbAdmin);
if (dbAdmin && ["Admin", "SUPER_ADMIN", "ADMIN"].includes(dbAdmin.role) && dbAdmin.password && body.password) {
if (dbAdmin && dbAdmin.password && body.password) {
const isMatch = await bcrypt.compare(body.password, dbAdmin.password);
if (isMatch) {
assertPrincipalActive(dbAdmin);
@@ -496,21 +493,12 @@ export class AuthService {
async refresh(user: {
id: string;
email?: string | null;
email?: string;
role?: string;
mobile?: string | null;
isPublicAuthor?: boolean;
mobile?: string;
stageTestSession?: string | null;
stageTestGeneration?: string | null;
}) {
// Re-resolve rather than trusting a stale or partially projected request principal.
const current = await this.prisma.user.findUnique({ where: { id: user.id } });
if (!current) throw new UnauthorizedException("کاربر یافت نشد");
assertPrincipalActive(current);
assertPrincipalActive(user);
if (current.stageTestSession && (!current.stageTestGeneration || user.stageTestGeneration !== current.stageTestGeneration || user.stageTestSession !== current.stageTestSession)) throw new UnauthorizedException("Stage session revoked");
const { password: _password, ...safeUser } = current;
user = safeUser;
const payload = {
sub: user.id,
email: user.email,
-3
View File
@@ -6,7 +6,6 @@ import {
forwardRef,
} from "@nestjs/common";
import { AuthGuard } from "@nestjs/passport";
import { assertPrincipalActive } from "./stage-test-principal";
import { ApiKeysService } from "../admin/api-keys.service";
@Injectable()
@@ -29,7 +28,6 @@ export class JwtAuthGuard extends AuthGuard("jwt") {
if (apiKeyHeader && this.apiKeysService) {
try {
const apiKeyUser = await this.apiKeysService.validateKey(apiKeyHeader);
assertPrincipalActive(apiKeyUser as { isPublicAuthor?: boolean });
request.user = apiKeyUser;
return true;
} catch (err: unknown) {
@@ -54,7 +52,6 @@ export class JwtAuthGuard extends AuthGuard("jwt") {
)
);
}
assertPrincipalActive(user as { isPublicAuthor?: boolean });
return user;
}
}
+1 -1
View File
@@ -62,7 +62,7 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
if (!user) {
throw new UnauthorizedException("کاربر یافت نشد");
}
try { assertPrincipalActive(user); } catch { throw new UnauthorizedException("Principal unavailable"); }
try { assertPrincipalActive(user); } catch { throw new UnauthorizedException("Principal expired"); }
if (user.stageTestSession) {
if (!user.stageTestGeneration || payload.stageTestGeneration !== user.stageTestGeneration || payload.stageTestSession !== user.stageTestSession) throw new UnauthorizedException("Stage session revoked");
const path = req.originalUrl?.split('?')[0] || '';
-133
View File
@@ -1,133 +0,0 @@
import { UnauthorizedException, ForbiddenException } from '@nestjs/common';
import { validate } from 'class-validator';
import * as bcrypt from 'bcryptjs';
import { readFileSync } from 'fs';
import { join } from 'path';
import { AuthService } from './auth.service';
import { JwtStrategy } from './jwt.strategy';
import { JwtAuthGuard } from './jwt-auth.guard';
import { RolesGuard } from '../common/guards/roles.guard';
import { HumanAdminGuard } from '../common/guards/human-admin.guard';
import { assertPrincipalActive } from './stage-test-principal';
import { RegisterDto } from './dto/register.dto';
import { LoginDto } from './dto/login.dto';
describe('Public authors are attribution only, never principals', () => {
const password = 'test-password';
const author = { id: 'author-id', mobile: '09123456789', email: 'author@example.invalid', password: bcrypt.hashSync(password, 4), role: 'SUPER_ADMIN', isPublicAuthor: true };
let prisma: any, jwt: any, redis: any, sms: any, service: AuthService;
const env = { ...process.env };
beforeEach(() => {
process.env.JWT_SECRET = 'isolated-public-author-test-secret';
process.env.JWT_REFRESH_SECRET = 'isolated-public-author-refresh-secret';
prisma = { user: { findUnique: jest.fn().mockResolvedValue(author), findFirst: jest.fn().mockResolvedValue(author), create: jest.fn() } };
jwt = { sign: jest.fn().mockReturnValue('token'), verify: jest.fn().mockReturnValue({ sub: author.id, jti: 'old-token' }) };
redis = { get: jest.fn(async (key: string) => key.startsWith('otp_attempts:') ? null : key === `otp:${author.mobile}` ? '12345' : key.startsWith('refresh_token:') ? '1' : null), set: jest.fn(), del: jest.fn(), incr: jest.fn().mockResolvedValue(1) };
sms = { sendOtp: jest.fn().mockResolvedValue(true) };
service = new AuthService(prisma, jwt, redis, sms);
});
afterEach(() => { process.env = { ...env }; });
it('shared principal assertion rejects the marker independent of role/mobile', () => {
expect(() => assertPrincipalActive(author)).toThrow(UnauthorizedException);
const withoutMobile = { ...author, mobile: null };
expect(() => assertPrincipalActive(withoutMobile)).toThrow(UnauthorizedException);
});
it.each(['User_PetOwner', 'Admin', 'ADMIN', 'SUPER_ADMIN'])('blocks password login even with role %s', async role => {
prisma.user.findUnique.mockResolvedValue({ ...author, role });
await expect(service.login({ mobile: author.mobile, password })).rejects.toThrow(UnauthorizedException);
expect(jwt.sign).not.toHaveBeenCalled();
});
it('does not send or store an OTP for a public author', async () => {
await expect(service.sendOtp({ phoneNumber: author.mobile })).rejects.toThrow(UnauthorizedException);
expect(sms.sendOtp).not.toHaveBeenCalled();
expect(redis.set).not.toHaveBeenCalled();
});
it('blocks a previously issued valid OTP without creating an alternate account', async () => {
await expect(service.verifyOtp({ phoneNumber: author.mobile, code: '12345' })).rejects.toThrow(UnauthorizedException);
expect(prisma.user.create).not.toHaveBeenCalled();
expect(jwt.sign).not.toHaveBeenCalled();
});
it.each(['Admin', 'ADMIN', 'SUPER_ADMIN'])('blocks email/admin login including nonproduction fallback for %s', async role => {
process.env.NODE_ENV = 'test';
process.env.ADMIN_EMAIL = author.email;
process.env.ADMIN_PASSWORD = password;
prisma.user.findFirst.mockResolvedValue({ ...author, role, password: null });
await expect(service.adminLogin({ email: author.email, password })).rejects.toThrow(UnauthorizedException);
expect(jwt.sign).not.toHaveBeenCalled();
});
it('blocks email/admin login with a valid stored password', async () => {
await expect(service.adminLogin({ email: author.email, password })).rejects.toThrow(UnauthorizedException);
expect(jwt.sign).not.toHaveBeenCalled();
});
it('email lookup cannot hide a public author behind a non-admin role and enter fallback', async () => {
process.env.ADMIN_EMAIL = author.email;
process.env.ADMIN_PASSWORD = password;
prisma.user.findFirst.mockResolvedValue({ ...author, role: 'User_PetOwner' });
await expect(service.adminLogin({ email: author.email, password })).rejects.toThrow(UnauthorizedException);
expect(prisma.user.findFirst).toHaveBeenCalledWith({ where: { email: author.email } });
expect(jwt.sign).not.toHaveBeenCalled();
});
it('blocks refresh-token rotation for an existing author account', async () => {
await expect(service.refreshToken('previous-token')).rejects.toThrow(UnauthorizedException);
expect(jwt.sign).not.toHaveBeenCalled();
});
it('blocks legacy refresh even when supplied principal omits the marker', async () => {
await expect(service.refresh({ id: author.id, role: 'SUPER_ADMIN' })).rejects.toThrow(UnauthorizedException);
expect(jwt.sign).not.toHaveBeenCalled();
});
it.each(['Bearer old-token', 'cookie'])('rejects existing JWT via %s using database marker, not token claims', async transport => {
const strategy = new JwtStrategy({ findById: jest.fn().mockResolvedValue(author) } as any, redis);
const headers = transport === 'cookie' ? { cookie: 'accessToken=old-token' } : { authorization: transport };
await expect(strategy.validate({ headers } as any, { sub: author.id, role: 'SUPER_ADMIN' })).rejects.toThrow(UnauthorizedException);
});
it('JWT guard rejects an accidentally supplied author principal', () => {
expect(() => new JwtAuthGuard().handleRequest(null, author)).toThrow(UnauthorizedException);
});
it('API-key guard rejects an accidentally marked principal', async () => {
const guard = new JwtAuthGuard({ validateKey: jest.fn().mockResolvedValue({ ...author, isApiKey: true, scopes: ['admin'] }) } as any);
const request = { headers: { 'x-api-key': 'test-key' } };
await expect(guard.canActivate({ switchToHttp: () => ({ getRequest: () => request }) } as any)).rejects.toThrow(UnauthorizedException);
});
it.each([{ roles: ['Admin'] }, { roles: [] }])('role guard rejects author even for roles %j', ({ roles }) => {
const guard = new RolesGuard({ getAllAndOverride: () => roles } as any);
const ctx = { getHandler: () => null, getClass: () => null, switchToHttp: () => ({ getRequest: () => ({ user: author }) }) } as any;
expect(() => guard.canActivate(ctx)).toThrow(ForbiddenException);
});
it.each(['Admin', 'ADMIN', 'SUPER_ADMIN'])('human admin guard accepts actual human role %s', role => {
const ctx = { switchToHttp: () => ({ getRequest: () => ({ user: { role } }) }) } as any;
expect(new HumanAdminGuard().canActivate(ctx)).toBe(true);
});
it.each(['User_PetOwner', 'adminsuper', '', undefined])('human admin guard denies nonallowlisted role %s', role => {
const ctx = { switchToHttp: () => ({ getRequest: () => ({ user: { role } }) }) } as any;
expect(() => new HumanAdminGuard().canActivate(ctx)).toThrow(ForbiddenException);
});
it('human admin guard rejects author with admin role', () => {
const ctx = { switchToHttp: () => ({ getRequest: () => ({ user: author }) }) } as any;
expect(() => new HumanAdminGuard().canActivate(ctx)).toThrow(ForbiddenException);
});
it.each([undefined, null, '', ' '])('registration still requires mobile %j before any database write', async mobile => {
prisma.user.findUnique.mockResolvedValue(null);
prisma.user.create.mockResolvedValue({ ...author, mobile, isPublicAuthor: false });
await expect(service.register({ firstName: 'Real', lastName: 'User', mobile } as any)).rejects.toThrow();
expect(prisma.user.create).not.toHaveBeenCalled();
});
it.each([RegisterDto, LoginDto])('real-user DTO retains required mobile validation', async Dto => {
const dto = Object.assign(new Dto(), { firstName: 'Real', lastName: 'User', password });
expect((await validate(dto)).some(error => error.property === 'mobile')).toBe(true);
});
it('real users can still login, verify OTP and refresh', async () => {
const real = { ...author, isPublicAuthor: false };
prisma.user.findUnique.mockResolvedValue(real);
await expect(service.login({ mobile: real.mobile, password })).resolves.toMatchObject({ success: true });
await expect(service.verifyOtp({ phoneNumber: real.mobile, code: '12345' })).resolves.toMatchObject({ success: true });
await expect(service.refreshToken('previous-token')).resolves.toMatchObject({ success: true });
await expect(service.refresh({ id: real.id })).resolves.toMatchObject({ success: true });
});
it('Prisma author storage permits absent mobile and defaults marker false', () => {
const schema = readFileSync(join(__dirname, '../../prisma/schema.prisma'), 'utf8');
const user = schema.match(/model User \{([\s\S]*?)\n\}/)![1];
expect(user).toMatch(/mobile\s+String\?\s+@unique/);
expect(user).toMatch(/isPublicAuthor\s+Boolean\s+@default\(false\)\s+@map\("is_public_author"\)/);
});
});
+1 -4
View File
@@ -1,5 +1,3 @@
import { UnauthorizedException } from "@nestjs/common";
// Internal seed authority only. No controller, JWT actor, or owner impersonation.
export const STAGE_TEST_ID = 'e876e7a0-738f-4e59-b6db-e270512ababc';
export const STAGE_TEST_EMAIL = 'stage-editorial-reviewer@ci.canina.invalid';
@@ -10,7 +8,6 @@ export function authorizeStageSession(env: NodeJS.ProcessEnv, artifactSha: strin
if (!Number.isInteger(ttl) || ttl < 60 || ttl > 3600) throw new Error('Bounded TTL required');
return {ttl, session:env.STAGE_TEST_SESSION!, sha:artifactSha};
}
export function assertPrincipalActive(user: { authExpiresAt?: Date | null; isPublicAuthor?: boolean }, now = Date.now()) {
if (user.isPublicAuthor) throw new UnauthorizedException("Public authors cannot authenticate");
export function assertPrincipalActive(user: { authExpiresAt?: Date | null }, now = Date.now()) {
if (user.authExpiresAt && user.authExpiresAt.getTime() <= now) throw new Error('Principal expired');
}
@@ -23,7 +23,7 @@ describe('Stage credentials remain fenced to their creation session', () => {
});
it('includes session fencing in newly issued credentials',async()=>{
const jwt=new JwtService({secret:process.env.JWT_SECRET});
const auth=new AuthService({user:{findUnique:async()=>current}} as any,jwt,redis,undefined as any);
const auth=new AuthService({} as any,jwt,redis,undefined as any);
const result=await auth.refresh(current);
expect(jwt.verify(result.data.accessToken).stageTestGeneration).toBe('fresh-generation');
expect(jwt.verify(result.data.accessToken).stageTestSession).toBe('new-session');
@@ -1,17 +0,0 @@
import {
CanActivate,
ExecutionContext,
ForbiddenException,
Injectable,
} from '@nestjs/common';
/** Key management is a human-only control plane, never delegated by API scope. */
@Injectable()
export class HumanAdminGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean {
const user = context.switchToHttp().getRequest().user;
if (!user || user.isPublicAuthor || user.isApiKey || !['Admin', 'ADMIN', 'SUPER_ADMIN'].includes(user.role))
throw new ForbiddenException('Human administrator required');
return true;
}
}
+2 -5
View File
@@ -12,7 +12,6 @@ interface RequestWithUser {
role?: string;
isApiKey?: boolean;
scopes?: string[];
isPublicAuthor?: boolean;
};
}
@@ -26,14 +25,12 @@ export class RolesGuard implements CanActivate {
[context.getHandler(), context.getClass()],
);
const request = context.switchToHttp().getRequest<RequestWithUser>();
const user = request.user;
if (user?.isPublicAuthor) throw new ForbiddenException("Public authors have no permissions");
if (!requiredRoles || requiredRoles.length === 0) {
return true;
}
const request = context.switchToHttp().getRequest<RequestWithUser>();
const user = request.user;
if (!user || !user.role) {
throw new ForbiddenException("شما دسترسی لازم برای این بخش را ندارید");
}
-30
View File
@@ -1,30 +0,0 @@
import 'reflect-metadata';
import { NestFactory } from '@nestjs/core';
import { MaintenanceModule } from './maintenance.module';
import { assertStageScope } from '../admin/stage-author-restoration.service';
/** Exported for startup-contract testing; importing never starts a listener. */
export async function startMaintenance(
env: NodeJS.ProcessEnv = process.env,
create = (module: typeof MaintenanceModule) => NestFactory.create(module),
) {
// Deny before connecting to any infrastructure.
assertStageScope(env);
const port = Number(env.PORT);
if (!/^\d+$/.test(env.PORT || '') || !Number.isInteger(port) || port < 1 || port > 65535) {
throw new Error('Explicit valid maintenance PORT required');
}
const app = await create(MaintenanceModule);
app.setGlobalPrefix('api');
app.enableShutdownHooks();
await app.listen(port, '127.0.0.1');
return app;
}
if (require.main === module) {
startMaintenance().catch(() => {
// Do not emit connection strings or credentials on startup failure.
console.error('Maintenance startup failed');
process.exitCode = 1;
});
}
@@ -1,10 +0,0 @@
import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
/** Connection lifecycle only: deliberately bypass PrismaService's startup DDL. */
@Injectable()
export class MaintenancePrismaService extends PrismaService {
async onModuleInit(): Promise<void> {
await this.$connect();
}
}
@@ -1,23 +0,0 @@
import { Controller, ForbiddenException, Post, Req, UseGuards } from '@nestjs/common';
import type { Request } from 'express';
import { StageAuthorRestorationService } from '../admin/stage-author-restoration.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { Roles } from '../common/decorators/roles.decorator';
import { RolesGuard } from '../common/guards/roles.guard';
import { HumanAdminGuard } from '../common/guards/human-admin.guard';
@Controller('admin/users')
@UseGuards(JwtAuthGuard, RolesGuard, HumanAdminGuard)
@Roles('Admin', 'SUPER_ADMIN')
export class MaintenanceController {
constructor(private readonly restoration: StageAuthorRestorationService) {}
@Post('stage-author-restoration')
async restoreStageAuthors(@Req() req: Request) {
// Never trust proxy headers for this administrative operation.
if (!['127.0.0.1', '::1', '::ffff:127.0.0.1'].includes(req.socket?.remoteAddress || '')) {
throw new ForbiddenException('Loopback maintenance endpoint only');
}
return this.restoration.restoreStageAuthors();
}
}
@@ -1,35 +0,0 @@
import { Module, UnauthorizedException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { PrismaService } from '../prisma/prisma.service';
import { RedisService } from '../redis/redis.service';
import { UsersService } from '../users/users.service';
import { JwtStrategy } from '../auth/jwt.strategy';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { ApiKeysService } from '../admin/api-keys.service';
import { RolesGuard } from '../common/guards/roles.guard';
import { HumanAdminGuard } from '../common/guards/human-admin.guard';
import { StageAuthorRestorationService } from '../admin/stage-author-restoration.service';
import { MaintenancePrismaService } from './maintenance-prisma.service';
import { MaintenanceController } from './maintenance.controller';
/** No App/Auth/Admin/Prisma modules: their lifecycles are not maintenance-safe. */
@Module({
controllers: [MaintenanceController],
providers: [
{ provide: PrismaService, useClass: MaintenancePrismaService },
RedisService,
UsersService,
Reflector,
JwtStrategy,
// JwtAuthGuard requires this token. Reject rather than instantiate the
// API-key service or allow API keys to enter this JWT-only control plane.
{ provide: ApiKeysService, useValue: {
validateKey: async () => { throw new UnauthorizedException('JWT required'); },
} },
JwtAuthGuard,
RolesGuard,
HumanAdminGuard,
StageAuthorRestorationService,
],
})
export class MaintenanceModule {}
-109
View File
@@ -1,109 +0,0 @@
import { Test } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import { MODULE_METADATA } from '@nestjs/common/constants';
import { JwtService } from '@nestjs/jwt';
import request from 'supertest';
import { MaintenanceModule } from './maintenance.module';
import { MaintenancePrismaService } from './maintenance-prisma.service';
import { MaintenanceController } from './maintenance.controller';
import { PrismaService } from '../prisma/prisma.service';
import { RedisService } from '../redis/redis.service';
import { StageAuthorRestorationService } from '../admin/stage-author-restoration.service';
import { getJwtSecret } from '../auth/auth.constants';
import { startMaintenance } from './main';
describe('isolated maintenance runtime', () => {
let app: INestApplication;
const user = { id: 'admin-test', role: 'Admin', isPublicAuthor: false };
const prisma = { user: { findUnique: jest.fn() }, $connect: jest.fn(), $disconnect: jest.fn() };
const redis = { get: jest.fn() };
const restoration = { restoreStageAuthors: jest.fn() };
const jwt = new JwtService();
const token = (payload: Record<string, unknown> = {}, secret = getJwtSecret()) => jwt.sign({ sub: user.id, ...payload }, { secret, expiresIn: '5m' });
const post = (bearer?: string) => {
const req = request(app.getHttpServer()).post('/api/admin/users/stage-author-restoration');
return bearer ? req.set('Authorization', 'Bearer ' + bearer) : req;
};
beforeEach(async () => {
jest.clearAllMocks();
prisma.user.findUnique.mockResolvedValue(user);
redis.get.mockResolvedValue(null);
restoration.restoreStageAuthors.mockResolvedValue({ success: true });
const module = await Test.createTestingModule({ imports: [MaintenanceModule] })
.overrideProvider(PrismaService).useValue(prisma)
.overrideProvider(RedisService).useValue(redis)
.overrideProvider(StageAuthorRestorationService).useValue(restoration).compile();
app = module.createNestApplication();
app.setGlobalPrefix('api');
await app.listen(0, '127.0.0.1');
});
afterEach(async () => { await app?.close(); });
it('has no module imports, and exactly one small controller', () => {
expect(Reflect.getMetadata(MODULE_METADATA.IMPORTS, MaintenanceModule) || []).toEqual([]);
expect(Reflect.getMetadata(MODULE_METADATA.CONTROLLERS, MaintenanceModule)).toEqual([MaintenanceController]);
});
it('connects Prisma without invoking its DDL lifecycle', async () => {
const connect = jest.fn().mockResolvedValue(undefined);
const ddl = jest.fn();
await MaintenancePrismaService.prototype.onModuleInit.call({ $connect: connect, ensureTablesExist: ddl });
expect(connect).toHaveBeenCalledTimes(1);
expect(ddl).not.toHaveBeenCalled();
});
it('entrypoint only binds IPv4 loopback and uses env PORT', async () => {
const isolatedApp = { setGlobalPrefix: jest.fn(), enableShutdownHooks: jest.fn(), listen: jest.fn() };
const create = jest.fn().mockResolvedValue(isolatedApp);
await startMaintenance({ APP_ENV: 'stage', STAGE_AUTHOR_RESTORATION_ENABLED: 'true', STAGE_AUTHOR_RESTORATION_MODE: 'rehearsal', DATABASE_URL: 'postgresql://postgres@127.0.0.1:5432/rehearsal', PORT: '39071' }, create);
expect(create).toHaveBeenCalledWith(MaintenanceModule);
expect(isolatedApp.listen).toHaveBeenCalledWith(39071, '127.0.0.1');
await expect(startMaintenance({ PORT: '39071' }, create)).rejects.toThrow();
expect(create).toHaveBeenCalledTimes(1);
});
it('uses the real strategy and guards over loopback HTTP', async () => {
await post().expect(401);
await post('invalid').expect(401);
await post(token({}, 'wrong-secret')).expect(401);
expect(restoration.restoreStageAuthors).not.toHaveBeenCalled();
const access = token();
await post(access).expect(201, { success: true });
expect(redis.get).toHaveBeenCalledWith('bl_token:' + access);
expect(prisma.user.findUnique).toHaveBeenCalled();
expect(restoration.restoreStageAuthors).toHaveBeenCalledTimes(1);
expect(app.getHttpServer().address().address).toBe('127.0.0.1');
});
it('rejects expired and blacklisted sessions', async () => {
await post(jwt.sign({ sub: user.id }, { secret: getJwtSecret(), expiresIn: -1 })).expect(401);
redis.get.mockResolvedValue('revoked');
await post(token()).expect(401);
expect(restoration.restoreStageAuthors).not.toHaveBeenCalled();
});
it.each([
[{ ...user, role: 'User_PetOwner' }, 403],
[{ ...user, isPublicAuthor: true }, 401],
[{ ...user, isApiKey: true, scopes: ['admin'] }, 403],
[{ ...user, stageTestSession: 'test', stageTestGeneration: 'gen' }, 401],
[null, 401],
])('rejects unauthorized database principal %j', async (principal, status) => {
prisma.user.findUnique.mockResolvedValue(principal);
await post(token({ stageTestSession: 'test', stageTestGeneration: 'gen' })).expect(status);
expect(restoration.restoreStageAuthors).not.toHaveBeenCalled();
});
it('accepts SUPER_ADMIN but never accepts an API key', async () => {
prisma.user.findUnique.mockResolvedValue({ ...user, role: 'SUPER_ADMIN' });
await post(token()).expect(201);
restoration.restoreStageAuthors.mockClear();
await post().set('x-api-key', 'not-a-jwt').expect(401);
expect(restoration.restoreStageAuthors).not.toHaveBeenCalled();
});
it('exposes no ordinary app routes', async () => {
await request(app.getHttpServer()).get('/api/admin/users').expect(404);
await request(app.getHttpServer()).post('/api/auth/login').expect(404);
await request(app.getHttpServer()).get('/api/admin/users/stage-author-restoration').expect(404);
});
it.each([undefined, '10.0.0.2', '127.0.0.1.evil', '::ffff:10.0.0.2'])('ignores forwarded headers for non-loopback socket %s', async remoteAddress => {
const controller = new MaintenanceController(restoration as any);
await expect(controller.restoreStageAuthors({ socket: { remoteAddress }, headers: { 'x-forwarded-for': '127.0.0.1' } } as any)).rejects.toThrow();
expect(restoration.restoreStageAuthors).not.toHaveBeenCalled();
});
});
+1 -1
View File
@@ -46,7 +46,7 @@ export class ReviewsService {
"کاربر کنینا";
}
if (!resolvedPhone) {
resolvedPhone = user.mobile ?? undefined;
resolvedPhone = user.mobile;
}
}
}
-27
View File
@@ -1,27 +0,0 @@
# SEO tracking backend local acceptance
Base: develop 13f4fdc58dff96f192c612a8d38f33d314f70fad. Original unrelated .specify/ and evidence/ untracked. Concurrent frontend changes excluded.
Spec intent: `/opt/data/engineering/canina-spec-baseline/specs/002-seo-performance-tracking/{spec,plan,tasks}.md`; constitution v1.1.0. Contract refinement: `/opt/data/analytics-engine/contract.md`. Pagination/validation/auth, nullable provenance-aware snapshots, retry integrity, atomic directive versions are local acceptance scope. Worker scheduling and publisher integration are separate acceptance gates.
Graphify query: `seo tracking authentication snapshots models impact`, 4304 nodes, truncated 1800-token traversal. Graph SHA256 `6a73473cee9e207543fdeeb668bea544f766200a1b16b8a3a9ce18d4e42e51af`; graph build/source binding unknown, discovery only. Directly inspected controller, DTO, service, Prisma models, JwtAuthGuard, JwtStrategy, RolesGuard, search utility. Query modified only graph cache timestamp; excluded from commit.
## Receipts (local /opt/data/analytics-engine/)
- backend-red.log: 9 validation assertions failed against naive implementation (exit 1).
- backend-green.log: 3 suites / 15 tests passed: validation, real HTTP Passport JWT/role pipeline, disposable PostgreSQL persistence/concurrent feedback fencing, stale action fencing, concurrent snapshot deduplication, changed-payload conflicts, null unavailable versus actual zero.
- backend-build.log: `npm run build`, exit 0.
- backend-db-setup.log: `prisma db push --skip-generate` only on fresh local PostgreSQL 16.2 port 55439, exit 0.
- backend-migration.log: actual additive migration SQL executed successfully against that disposable database after schema push. This verifies upgrade/idempotence against current schema, NOT full repository migrations-from-empty or historical migration baseline.
- backend-full-suite.log: 94 suites pass, 1 fails, 3 skip; 815 tests pass, 1 fails, 7 skip. Integration intentionally skipped without SEO_TEST_DATABASE_URL.
- backend-base-full-suite.log: equivalent clean base SHA, same node_modules: 93 suites pass, 1 fails, 2 skip; 809 tests pass, 1 fails, 3 skip. Both fail the same unrelated WikiService pagination test.
Docker daemon unavailable and no system postgres binaries; downloaded Zonky PostgreSQL 16.2 binary archive from Maven Central into scratch and initialized a new unprivileged local cluster. No existing server/database used. HTTP tests use an isolated local JWT strategy and real shared guards, not production user lookup/Redis or real API-key credentials.
## Remaining gates / limitations
- No push, CI, Stage, deployment, production SQL, real analytics ingestion or autonomous run claimed.
- Existing blog/content writers must call the action endpoint with current finding version and feedbackVersion. This endpoint fences both atomically, but cannot enforce arbitrary free-text directive semantics or protect writers bypassing it. No end-to-end publisher integration claimed.
- New findings have normalized title/keyword searchText; old rows default empty and need an authorized API backfill (not silently invented in SQL). Search excludes long hypothesis text.
- actionId is an external reference, not a validated task FK. Goals are stored as optional metric/target and not an automatic business-decision engine.
- Snapshot freshness is recorded by source fetchedAt with future-date sanity check; no business freshness SLA was invented. Source proof remains producer-supplied; actual commerce attribution requires instrumentation and is not inferred from aggregate sales.
- Historical metric zeros retained with null provenance; consumers must treat these as unverified legacy values.
- Wider repository migration baseline incomplete; migration assumes blogs exists. Validate release migration against a representative authorized Stage clone before release.
@@ -1,83 +0,0 @@
import { Type, Transform } from 'class-transformer';
import {
IsString,
IsArray,
IsOptional,
IsEnum,
IsUUID,
ArrayNotEmpty,
ArrayMaxSize,
MaxLength,
MinLength,
IsInt,
Min,
Max,
IsIn,
IsNumber,
IsISO8601,
IsObject,
} from 'class-validator';
import { ResearchFindingStatus } from '@prisma/client';
export class CreateFindingDto {
@IsString() @MinLength(1) @MaxLength(255) title: string;
@IsString() @MinLength(1) @MaxLength(20000) hypothesis: string;
@IsArray()
@ArrayNotEmpty()
@ArrayMaxSize(50)
@IsString({ each: true })
@MaxLength(128, { each: true })
targetKeywords: string[];
@IsString() @MinLength(1) @MaxLength(128) primaryKeyword: string;
@IsString() @MinLength(1) @MaxLength(20000) expectedOutcome: string;
@IsOptional() @IsEnum(ResearchFindingStatus) status?: ResearchFindingStatus;
@IsOptional() @IsUUID() blogId?: string;
@IsOptional() @IsString() @MaxLength(128) actionId?: string;
@IsOptional() @IsString() @MaxLength(64) goalMetric?: string;
@IsOptional() @IsNumber() @Min(0) goalTarget?: number;
}
export class UpdateCeoFeedbackDto {
@IsString() @MaxLength(20000) feedback: string;
@IsInt() @Min(0) expectedVersion: number;
}
export class ActionFindingDto {
@IsInt() @Min(0) expectedVersion: number;
@IsInt() @Min(0) feedbackVersion: number;
@IsOptional() @IsUUID() blogId?: string;
@IsOptional() @IsString() @MaxLength(128) actionId?: string;
@IsOptional() @IsEnum(ResearchFindingStatus) status?: ResearchFindingStatus;
}
export class PublishFindingDto {
@IsInt() @Min(0) expectedVersion: number;
@IsInt() @Min(0) feedbackVersion: number;
@IsString() @MinLength(1) @MaxLength(128) actionId: string;
@IsObject() blog: Record<string, any>;
}
export class QueryFindingsDto {
@IsOptional() @Type(() => Number) @IsInt() @Min(1) @Max(100000) page?: number;
@IsOptional() @Type(() => Number) @IsInt() @Min(1) @Max(100) limit?: number;
@IsOptional() @IsString() @MaxLength(255) search?: string;
@IsOptional() @IsEnum(ResearchFindingStatus) status?: ResearchFindingStatus;
@IsOptional()
@IsIn(['createdAt', 'updatedAt', 'title', 'status'])
sortBy?: string;
@IsOptional() @IsIn(['asc', 'desc']) sortOrder?: 'asc' | 'desc';
}
export class CreateSnapshotDto {
@IsString() @MinLength(1) @MaxLength(128) ingestionKey: string;
@IsISO8601({ strict: true }) periodStart: string;
@IsISO8601({ strict: true }) periodEnd: string;
@IsObject() sourceMetadata: Record<string, any>;
@IsOptional() @IsInt() @Min(0) gscImpressions?: number | null;
@IsOptional() @IsInt() @Min(0) gscClicks?: number | null;
@IsOptional() @IsNumber() @Min(0) gscPosition?: number | null;
@IsOptional() @IsInt() @Min(0) ga4ActiveUsers?: number | null;
@IsOptional() @IsNumber() @Min(0) ga4AvgEngagementSec?: number | null;
@IsOptional() @IsNumber() @Min(0) @Max(1) ga4BounceRate?: number | null;
@IsOptional() @IsNumber() @Min(0) @Max(1) ga4ScrollDepthRate?: number | null;
@IsOptional() @IsInt() @Min(0) attributedOrdersCount?: number | null;
@IsOptional() @IsNumber() @Min(0) attributedSalesValue?: number | null;
@IsOptional()
@IsIn(['SCALE', 'REFINE', 'HOLD', 'PRUNE'])
actionRecommendation?: string;
@IsOptional() @IsString() @MaxLength(20000) analysisNotes?: string;
}
@@ -1,15 +0,0 @@
import { Prisma } from '@prisma/client';
import { BlogsService } from '../admin/blogs.service';
import { PrismaService } from '../prisma/prisma.service';
import { RevalidationService } from '../common/revalidation/revalidation.service';
/** Reuse the admin create rules with the transaction client. Never run network
* revalidation (or the scheduler lifecycle) before the outer commit. */
export async function createPublicationBlog(
tx: Prisma.TransactionClient, data: Record<string, any>, userId: string,
) {
const deferred = { revalidateBlog: async () => false } as unknown as RevalidationService;
const service = new BlogsService(tx as PrismaService, deferred);
const { cacheRevalidation: _deferred, ...blog } = await service.createBlog(data, userId);
return blog;
}
@@ -1,106 +0,0 @@
import { Test } from '@nestjs/testing';
import { PassportModule, PassportStrategy } from '@nestjs/passport';
import { Strategy, ExtractJwt } from 'passport-jwt';
import { JwtService } from '@nestjs/jwt';
import { spawn } from 'child_process';
import { resolve } from 'path';
import { SeoTrackingModule } from './seo-tracking.module';
import { PrismaService } from '../prisma/prisma.service';
import { RevalidationService } from '../common/revalidation/revalidation.service';
import { PrismaClient } from '@prisma/client';
import { SeoTrackingService } from './seo-tracking.service';
class PublicationStrategy extends PassportStrategy(Strategy) {
constructor() { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), secretOrKey: 'publication-disposable-only' }); }
validate(payload: any) { return payload; }
}
const url = process.env.PUBLICATION_TEST_DATABASE_URL;
if (url && !url.startsWith('postgresql://publication_test:disposable-only@127.0.0.1:55447/'))
throw new Error('Disposable publication database only');
const deferred = () => { let resolve!: () => void; const promise = new Promise<void>(r => resolve = r); return { promise, resolve }; };
(url ? describe : describe.skip)('atomic publication: real PostgreSQL row ordering', () => {
const db = new PrismaClient({ datasources: { db: { url } } });
let user: any;
const cache = { revalidateBlog: jest.fn(async () => false) };
const service = new SeoTrackingService(db as any, cache as any);
const ids: string[] = [];
it('dormant Python entrypoint uses authenticated real HTTP publication endpoint', async () => {
const module = await Test.createTestingModule({ imports: [PassportModule, SeoTrackingModule], providers: [PublicationStrategy] })
.overrideProvider(PrismaService).useValue(db).compile();
const app = module.createNestApplication({ logger: false }); app.setGlobalPrefix('api');
try {
await app.listen(0, '127.0.0.1');
const jwt = new JwtService({ secret: 'publication-disposable-only' });
const token = jwt.sign({ id: user.id, role: 'admin' }, { expiresIn: '5m' });
const origin = `http://127.0.0.1:${app.getHttpServer().address().port}`;
const child = spawn('python3', [resolve(__dirname, '../../../scripts/content-research/verify_real_http.py')], { env: { ...process.env, PUBLICATION_LOCAL_ORIGIN: origin, PUBLICATION_LOCAL_TOKEN: token } });
let output = ''; child.stdout.on('data', d => output += d); child.stderr.on('data', d => output += d);
const code = await new Promise(resolve => child.on('close', resolve));
expect({ code, output }).toEqual({ code: 0, output: 'PUBLICATION_REAL_HTTP_PASSED\n' });
const fixtures = await db.contentResearchFinding.findMany({ where: { title: 'publication-http-fixture' } });
ids.push(...fixtures.map(f => f.id));
} finally { await app.close(); }
}, 30000);
beforeAll(async () => { user = await db.user.create({ data: { firstName: 'Test', lastName: 'Fixture', mobile: String(Date.now()), role: 'admin' } }); });
afterAll(async () => {
await db.contentResearchFinding.deleteMany({ where: { id: { in: ids } } });
await db.blog.deleteMany({ where: { slug: { startsWith: 'publication-fixture-' } } });
await db.user.delete({ where: { id: user.id } }); await db.$disconnect();
});
async function finding() {
const f = await service.createFinding({ title: 'fixture', hypothesis: 'fixture', targetKeywords: ['test'], primaryKeyword: 'test', expectedOutcome: 'fixture' });
ids.push(f.id); return f;
}
const payload = () => ({ title: 'fixture', slug: 'publication-fixture-' + Math.random(), content: '<p>reviewed fixture</p>', tagNames: ['publication-fixture-tag'] });
function barrierClient(entered: ReturnType<typeof deferred>, release: ReturnType<typeof deferred>, pids: number[]) {
return new Proxy(db, { get(target, prop) {
if (prop === '$transaction') return (fn: any) => db.$transaction(async tx => {
pids.push((await tx.$queryRaw<any[]>`SELECT pg_backend_pid() AS pid`)[0].pid);
return fn(new Proxy(tx, { get(t, key) {
if (key === 'blog') return new Proxy(t.blog, { get(model, method) {
if (method === 'create') return async (args: any) => { entered.resolve(); await release.promise; return model.create(args); };
return (model as any)[method];
} });
return (t as any)[key];
} }));
}, { timeout: 10000 });
return (target as any)[prop];
} });
}
it('feedback committed during draft/preflight rejects publication and creates no Blog', async () => {
const f = await finding(), blog = payload();
await service.updateCeoFeedback(f.id, { expectedVersion: f.version, feedback: 'changed during preflight' });
await expect(service.publishFinding(f.id, { expectedVersion: f.version, feedbackVersion: f.feedbackVersion, actionId: 'stale', blog }, user.id)).rejects.toMatchObject({ status: 409 });
expect(await db.blog.count({ where: { slug: blog.slug } })).toBe(0);
});
it('publication lock blocks concurrent feedback; stale writer conflicts after commit; fresh feedback applies next', async () => {
const f = await finding(), entered = deferred(), release = deferred(), pids: number[] = [];
const publishing = new SeoTrackingService(barrierClient(entered, release, pids) as any, cache as any);
const publish = publishing.publishFinding(f.id, { expectedVersion: 0, feedbackVersion: 0, actionId: 'winner', blog: payload() }, user.id);
await entered.promise;
let settled = false;
// Separate Prisma connection/transaction; actual row lock wait proved with pg_stat_activity.
const feedback = service.updateCeoFeedback(f.id, { expectedVersion: 0, feedback: 'concurrent' }).then(v => { settled = true; return v; }, e => { settled = true; return e; });
let waiting = false;
for (let i = 0; i < 100; i++) {
const rows = await db.$queryRaw<any[]>`SELECT pid FROM pg_stat_activity WHERE wait_event_type = 'Lock' AND pid <> ${pids[0]}`;
if (rows.length) { waiting = true; expect(rows[0].pid).not.toBe(pids[0]); break; }
await new Promise(r => setTimeout(r, 10));
}
expect(waiting).toBe(true); expect(settled).toBe(false); release.resolve();
const result = await publish; expect((await feedback).status).toBe(409);
expect(result.finding.blogId).toBe(result.blog.id); expect(result.consumedFeedbackVersion).toBe(0);
const next = await service.updateCeoFeedback(f.id, { expectedVersion: result.finding.version, feedback: 'next action' });
expect(next.feedbackVersion).toBe(1); expect(next.blogId).toBe(result.blog.id);
});
it('invalid author/relation rolls back both claim and Blog; duplicate request cannot create twice', async () => {
const f = await finding(), blog = payload();
await expect(service.publishFinding(f.id, { expectedVersion: 0, feedbackVersion: 0, actionId: 'rollback', blog }, '00000000-0000-4000-8000-000000000000')).rejects.toBeTruthy();
expect((await service.findOne(f.id)).version).toBe(0);
expect(await db.blog.count({ where: { slug: blog.slug } })).toBe(0);
const r = await service.publishFinding(f.id, { expectedVersion: 0, feedbackVersion: 0, actionId: 'once', blog }, user.id);
await expect(service.publishFinding(f.id, { expectedVersion: 0, feedbackVersion: 0, actionId: 'once', blog }, user.id)).rejects.toMatchObject({ status: 409 });
expect(await db.blog.count({ where: { slug: blog.slug } })).toBe(1);
expect(r.cacheRevalidation).toBe('failed');
});
});
@@ -1,38 +0,0 @@
import 'reflect-metadata';
import { plainToInstance } from 'class-transformer';
import { validate } from 'class-validator';
import {
QueryFindingsDto,
CreateSnapshotDto,
UpdateCeoFeedbackDto,
} from './dto/seo-tracking.dto';
describe('SEO ingress contract', () => {
it.each([
{ page: '1.5' },
{ page: '0' },
{ limit: '101' },
{ sortBy: 'hypothesis' },
{ sortOrder: 'wrong' },
])('rejects unsafe query %j', async (value) => {
expect(
(await validate(plainToInstance(QueryFindingsDto, value))).length,
).toBeGreaterThan(0);
});
it('requires optimistic version', async () => {
expect(
(
await validate(
plainToInstance(UpdateCeoFeedbackDto, { feedback: 'new' }),
)
).length,
).toBeGreaterThan(0);
});
it.each([{ gscClicks: -1 }, { ga4BounceRate: 2 }, { gscClicks: 1.5 }])(
'rejects invalid metrics %j',
async (value) => {
expect(
(await validate(plainToInstance(CreateSnapshotDto, value))).length,
).toBeGreaterThan(0);
},
);
});
@@ -1,86 +0,0 @@
import 'reflect-metadata';
import { Test } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import request from 'supertest';
import { PassportModule, PassportStrategy } from '@nestjs/passport';
import { Strategy, ExtractJwt } from 'passport-jwt';
import { JwtService } from '@nestjs/jwt';
import { SeoTrackingController } from './seo-tracking.controller';
import { SeoTrackingService } from './seo-tracking.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { RolesGuard } from '../common/guards/roles.guard';
class LocalStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: 'local-disposable-test-secret',
ignoreExpiration: false,
});
}
validate(payload: any) {
return payload;
}
}
describe('SEO HTTP security and validation', () => {
let app: INestApplication;
const jwt = new JwtService({ secret: 'local-disposable-test-secret' });
const service = {
findAll: jest.fn().mockResolvedValue({ data: [], meta: { total: 0 } }),
findOne: jest.fn(),
};
beforeAll(async () => {
const mod = await Test.createTestingModule({
imports: [PassportModule],
controllers: [SeoTrackingController],
providers: [
LocalStrategy,
JwtAuthGuard,
RolesGuard,
{ provide: SeoTrackingService, useValue: service },
],
}).compile();
app = mod.createNestApplication();
app.setGlobalPrefix('api');
await app.init();
});
afterAll(async () => {
await app.close();
});
it('rejects missing, invalid, expired credentials and nonadmins', async () => {
const route = '/api/admin/seo-tracking';
await request(app.getHttpServer()).get(route).expect(401);
await request(app.getHttpServer())
.get(route)
.set('Authorization', 'Bearer invalid')
.expect(401);
await request(app.getHttpServer())
.get(route)
.set(
'Authorization',
'Bearer ' + jwt.sign({ role: 'admin' }, { expiresIn: -1 }),
)
.expect(401);
await request(app.getHttpServer())
.get(route)
.set('Authorization', 'Bearer ' + jwt.sign({ role: 'customer' }))
.expect(403);
});
it('accepts lowercase admin and rejects query injection / malformed UUID', async () => {
const token = 'Bearer ' + jwt.sign({ role: 'admin' });
await request(app.getHttpServer())
.get('/api/admin/seo-tracking?page=2&limit=3')
.set('Authorization', token)
.expect(200);
expect(service.findAll).toHaveBeenCalledWith(
expect.objectContaining({ page: 2, limit: 3 }),
);
await request(app.getHttpServer())
.get('/api/admin/seo-tracking?sortBy=ceoFeedback')
.set('Authorization', token)
.expect(400);
await request(app.getHttpServer())
.get('/api/admin/seo-tracking/not-a-uuid')
.set('Authorization', token)
.expect(400);
});
});
@@ -1,88 +0,0 @@
import {
Controller,
Request,
Get,
Post,
Patch,
Body,
Param,
Query,
UseGuards,
ParseUUIDPipe,
UsePipes,
ValidationPipe,
} from '@nestjs/common';
import { SeoTrackingService } from './seo-tracking.service';
import {
ActionFindingDto,
PublishFindingDto,
CreateFindingDto,
QueryFindingsDto,
UpdateCeoFeedbackDto,
CreateSnapshotDto,
} from './dto/seo-tracking.dto';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { RolesGuard } from '../common/guards/roles.guard';
import { Roles } from '../common/decorators/roles.decorator';
@Controller('admin/seo-tracking')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('admin', 'superadmin')
@UsePipes(
new ValidationPipe({
transform: true,
whitelist: true,
forbidNonWhitelisted: true,
}),
)
export class SeoTrackingController {
constructor(private readonly seoTrackingService: SeoTrackingService) {}
@Post()
async createFinding(@Body() dto: CreateFindingDto) {
return this.seoTrackingService.createFinding(dto);
}
@Get()
async findAll(@Query() query: QueryFindingsDto) {
return this.seoTrackingService.findAll(query);
}
@Get(':id')
async findOne(@Param('id', new ParseUUIDPipe()) id: string) {
return this.seoTrackingService.findOne(id);
}
@Patch(':id/feedback')
async updateCeoFeedback(
@Param('id', new ParseUUIDPipe()) id: string,
@Body() dto: UpdateCeoFeedbackDto,
) {
return this.seoTrackingService.updateCeoFeedback(id, dto);
}
@Patch(':id/action')
async actionFinding(
@Param('id', new ParseUUIDPipe()) id: string,
@Body() dto: ActionFindingDto,
) {
return this.seoTrackingService.actionFinding(id, dto);
}
@Post(':id/publication')
async publishFinding(
@Param('id', new ParseUUIDPipe()) id: string,
@Body() dto: PublishFindingDto,
@Request() req: { user: { id: string } },
) {
return this.seoTrackingService.publishFinding(id, dto, req.user.id);
}
@Post(':id/snapshots')
async addSnapshot(
@Param('id', new ParseUUIDPipe()) id: string,
@Body() dto: CreateSnapshotDto,
) {
return this.seoTrackingService.addSnapshot(id, dto);
}
}
@@ -1,12 +0,0 @@
import { Module } from '@nestjs/common';
import { SeoTrackingController } from './seo-tracking.controller';
import { SeoTrackingService } from './seo-tracking.service';
import { PrismaModule } from '../prisma/prisma.module';
@Module({
imports: [PrismaModule],
controllers: [SeoTrackingController],
providers: [SeoTrackingService],
exports: [SeoTrackingService],
})
export class SeoTrackingModule {}
@@ -1,120 +0,0 @@
import { PrismaClient } from '@prisma/client';
import { SeoTrackingService } from './seo-tracking.service';
const testUrl = process.env.SEO_TEST_DATABASE_URL;
if (testUrl && !/^postgresql:\/\/seo_test@127\.0\.0\.1:55439\/postgres$/.test(testUrl)) {
throw new Error('Integration tests require the dedicated disposable local database');
}
const run = testUrl ? describe : describe.skip;
run('SEO disposable PostgreSQL integration', () => {
const db = new PrismaClient({
datasources: {
db: {
url:
process.env.SEO_TEST_DATABASE_URL ||
'postgresql://disabled@127.0.0.1:1/disabled',
},
},
});
const service = new SeoTrackingService(db as any);
let id: string;
beforeAll(async () => {
const f = await service.createFinding({
title: 'كليه ۱۲',
hypothesis: 'integration fixture',
primaryKeyword: 'كليه',
targetKeywords: ['كليه'],
expectedOutcome: 'test',
});
id = f.id;
});
afterAll(async () => {
await db.contentResearchFinding.deleteMany();
await db.$disconnect();
});
it('normalizes both stored text and search with filtered pagination', async () => {
const result = await service.findAll({ search: 'کلیه 12', limit: 1 });
expect(result.meta.total).toBe(1);
expect(result.data[0].id).toBe(id);
});
it('permits only one competing version writer and fences stale actions', async () => {
const writes = await Promise.allSettled([
service.updateCeoFeedback(id, { feedback: 'A', expectedVersion: 0 }),
service.updateCeoFeedback(id, { feedback: 'B', expectedVersion: 0 }),
]);
expect(writes.filter((w) => w.status === 'fulfilled')).toHaveLength(1);
await expect(
service.actionFinding(id, {
expectedVersion: 1,
feedbackVersion: 0,
status: 'ACTIONED',
}),
).rejects.toMatchObject({ status: 409 });
const row = await service.actionFinding(id, {
expectedVersion: 1,
feedbackVersion: 1,
status: 'ACTIONED',
});
expect(row.version).toBe(2);
});
const metadata = Object.fromEntries(
['gsc', 'ga4', 'commerce'].map((k) => [
k,
{
status: 'unavailable',
source: 'integration fixture',
fetchedAt: '2026-01-03T00:00:00Z',
},
]),
);
const snapshot = {
ingestionKey: 'fixture-window',
periodStart: '2026-01-01T00:00:00Z',
periodEnd: '2026-01-02T00:00:00Z',
sourceMetadata: metadata,
};
it('preserves null unavailable, idempotent concurrent retries, and conflicts', async () => {
const [a, b] = await Promise.all([
service.addSnapshot(id, snapshot),
service.addSnapshot(id, snapshot),
]);
expect(a.id).toBe(b.id);
expect(a.gscClicks).toBeNull();
expect(a.attributedSalesValue).toBeNull();
expect(
await db.contentPerformanceSnapshot.count({ where: { findingId: id } }),
).toBe(1);
await expect(
service.addSnapshot(id, { ...snapshot, analysisNotes: 'different' }),
).rejects.toMatchObject({ status: 409 });
});
it('retains genuine zero and rejects forged partial metrics', async () => {
const sourceMetadata = {
...metadata,
gsc: { ...metadata.gsc, status: 'available' },
};
const row = await service.addSnapshot(id, {
...snapshot,
ingestionKey: 'zero',
sourceMetadata,
gscImpressions: 0,
gscClicks: 0,
gscPosition: 0,
});
expect(row.gscClicks).toBe(0);
expect(row.ga4ActiveUsers).toBeNull();
await expect(
service.addSnapshot(id, {
...snapshot,
ingestionKey: 'bad',
gscClicks: 0,
}),
).rejects.toMatchObject({ status: 400 });
await expect(
service.addSnapshot(id, {
...snapshot,
ingestionKey: 'bad',
actionRecommendation: 'SCALE',
}),
).rejects.toMatchObject({ status: 400 });
});
});
@@ -1,291 +0,0 @@
import {
Injectable,
Optional,
NotFoundException,
BadRequestException,
ConflictException,
} from '@nestjs/common';
import { createPublicationBlog } from './publication-blog.adapter';
import { RevalidationService } from '../common/revalidation/revalidation.service';
import { PrismaService } from '../prisma/prisma.service';
import {
CreateFindingDto,
QueryFindingsDto,
UpdateCeoFeedbackDto,
CreateSnapshotDto,
ActionFindingDto,
PublishFindingDto,
} from './dto/seo-tracking.dto';
import {
createPaginationMeta,
normalizeSearchText,
} from '../common/utils/search.utils';
import { Prisma } from '@prisma/client';
import { validateSync } from 'class-validator';
import { plainToInstance } from 'class-transformer';
const groups = {
gsc: ['gscImpressions', 'gscClicks', 'gscPosition'],
ga4: [
'ga4ActiveUsers',
'ga4AvgEngagementSec',
'ga4BounceRate',
'ga4ScrollDepthRate',
],
commerce: ['attributedOrdersCount', 'attributedSalesValue'],
};
function checked<T extends object>(type: new () => T, value: T): T {
const dto = plainToInstance(type, value);
if (validateSync(dto, { whitelist: true, forbidNonWhitelisted: true }).length)
throw new BadRequestException('Invalid SEO tracking input');
return dto;
}
@Injectable()
export class SeoTrackingService {
constructor(
private prisma: PrismaService,
@Optional() private revalidation?: RevalidationService,
) {}
async createFinding(input: CreateFindingDto) {
const dto = checked(CreateFindingDto, input);
if (
![
dto.title,
dto.primaryKeyword,
dto.hypothesis,
dto.expectedOutcome,
...dto.targetKeywords,
].every((v) => v.trim())
)
throw new BadRequestException('Blank text');
return this.prisma.contentResearchFinding.create({
data: {
...dto,
searchText: normalizeSearchText(
[dto.title, dto.primaryKeyword, ...dto.targetKeywords].join(' '),
),
},
include: {
blog: { select: { id: true, title: true, slug: true, status: true } },
},
});
}
async findAll(input: QueryFindingsDto) {
const {
page = 1,
limit = 10,
search,
status,
sortBy = 'createdAt',
sortOrder = 'desc',
} = checked(QueryFindingsDto, input);
const where: Prisma.ContentResearchFindingWhereInput = {};
if (status) where.status = status;
const normalized = normalizeSearchText(search);
if (normalized)
where.searchText = { contains: normalized, mode: 'insensitive' };
const [data, total] = await this.prisma.$transaction(
[
this.prisma.contentResearchFinding.findMany({
where,
skip: (page - 1) * limit,
take: limit,
orderBy: [{ [sortBy]: sortOrder }, { id: 'asc' }],
include: {
blog: { select: { id: true, title: true, slug: true } },
snapshots: { orderBy: { snapshotDate: 'desc' }, take: 1 },
},
}),
this.prisma.contentResearchFinding.count({ where }),
],
{ isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead },
);
return { data, meta: createPaginationMeta(total, page, limit) };
}
async findOne(id: string) {
const finding = await this.prisma.contentResearchFinding.findUnique({
where: { id },
include: {
blog: true,
snapshots: { orderBy: { snapshotDate: 'desc' }, take: 30 },
},
});
if (!finding) throw new NotFoundException('Research finding not found');
return finding;
}
async updateCeoFeedback(id: string, input: UpdateCeoFeedbackDto) {
const dto = checked(UpdateCeoFeedbackDto, input);
return this.prisma.$transaction(async (tx) => {
const claim = await tx.contentResearchFinding.updateMany({
where: { id, version: dto.expectedVersion },
data: {
ceoFeedback: dto.feedback,
feedbackSubmittedAt: new Date(),
version: { increment: 1 },
feedbackVersion: { increment: 1 },
},
});
if (!claim.count) {
if (!(await tx.contentResearchFinding.findUnique({ where: { id } })))
throw new NotFoundException();
throw new ConflictException('Finding version changed');
}
return tx.contentResearchFinding.findUniqueOrThrow({ where: { id } });
});
}
async actionFinding(id: string, input: ActionFindingDto) {
const { expectedVersion, feedbackVersion, ...data } = checked(
ActionFindingDto,
input,
);
return this.prisma.$transaction(async (tx) => {
const claim = await tx.contentResearchFinding.updateMany({
where: { id, version: expectedVersion, feedbackVersion },
data: { ...data, version: { increment: 1 } },
});
if (!claim.count) {
if (!(await tx.contentResearchFinding.findUnique({ where: { id } })))
throw new NotFoundException();
throw new ConflictException('Finding/directive version changed');
}
return tx.contentResearchFinding.findUniqueOrThrow({ where: { id } });
});
}
async publishFinding(id: string, input: PublishFindingDto, userId: string) {
const dto = checked(PublishFindingDto, input);
if (!userId || !dto.actionId.trim())
throw new BadRequestException('Authenticated author and action required');
// updateMany is a row-locking CAS. Feedback writes use the same row and
// version: whichever writer wins forces the other stale request to 409.
const result = await this.prisma.$transaction(async (tx) => {
const claim = await tx.contentResearchFinding.updateMany({
where: { id, version: dto.expectedVersion,
feedbackVersion: dto.feedbackVersion, blogId: null },
data: { actionId: dto.actionId, version: { increment: 1 } },
});
if (!claim.count) {
if (!(await tx.contentResearchFinding.findUnique({ where: { id } })))
throw new NotFoundException('Research finding not found');
throw new ConflictException('Finding/directive changed or already published');
}
const blog = await createPublicationBlog(tx, dto.blog, userId);
const finding = await tx.contentResearchFinding.update({
where: { id }, data: { blogId: blog.id },
});
return { blog, finding, consumedFeedbackVersion: dto.feedbackVersion };
});
// Network/cache failures cannot roll back or turn a committed Blog into an
// ambiguous error. No external content generation runs inside the lock.
let cacheRevalidation: 'success' | 'failed' = 'failed';
try {
if (await (this.revalidation ?? new RevalidationService()).revalidateBlog(result.blog.slug))
cacheRevalidation = 'success';
} catch { /* return committed identity even on cache failure */ }
return { ...result, cacheRevalidation };
}
async addSnapshot(findingId: string, input: CreateSnapshotDto) {
const dto = checked(CreateSnapshotDto, input);
const periodStart = new Date(dto.periodStart),
periodEnd = new Date(dto.periodEnd);
if (periodStart >= periodEnd || periodEnd > new Date())
throw new BadRequestException('Invalid measurement period');
const metrics: Record<string, number | null> = {};
for (const [source, fields] of Object.entries(groups)) {
const meta = dto.sourceMetadata[source];
if (
!meta ||
!['available', 'unavailable', 'error'].includes(meta.status) ||
typeof meta.source !== 'string' ||
!meta.source.trim() ||
typeof meta.fetchedAt !== 'string' ||
!Number.isFinite(Date.parse(meta.fetchedAt)) ||
Date.parse(meta.fetchedAt) > Date.now() + 60000
)
throw new BadRequestException('Missing source provenance');
for (const field of fields) {
const value =
(dto as unknown as Record<string, number | null>)[field] ?? null;
if (meta.status !== 'available' && value !== null)
throw new BadRequestException('Unavailable metrics must be null');
if (
meta.status === 'available' &&
value === null &&
field !== 'ga4ScrollDepthRate'
)
throw new BadRequestException('Available source missing metrics');
metrics[field] = value;
}
}
if (
dto.actionRecommendation &&
Object.keys(groups).some(
(k) => dto.sourceMetadata[k].status !== 'available',
)
)
throw new BadRequestException(
'Incomplete evidence cannot recommend actions',
);
const data = {
findingId,
ingestionKey: dto.ingestionKey,
periodStart,
periodEnd,
sourceMetadata: dto.sourceMetadata as Prisma.InputJsonObject,
...metrics,
actionRecommendation: dto.actionRecommendation ?? null,
analysisNotes: dto.analysisNotes ?? null,
};
const existing = await this.prisma.contentPerformanceSnapshot.findUnique({
where: {
findingId_ingestionKey: { findingId, ingestionKey: dto.ingestionKey },
},
});
const same = (row: any) => {
const canonical = (v: any): string =>
JSON.stringify(
v && typeof v === 'object' && !(v instanceof Date)
? Object.keys(v)
.sort()
.reduce(
(o, k) => ((o[k] = JSON.parse(canonical(v[k]))), o),
{} as Record<string, any>,
)
: v,
);
return Object.entries(data).every(([k, v]) =>
k === 'sourceMetadata'
? canonical(row[k]) === canonical(v)
: k === 'periodStart' || k === 'periodEnd'
? new Date(row[k]).getTime() === (v as Date).getTime()
: k === 'attributedSalesValue'
? row[k] === null
? v === null
: Number(row[k]) === Number(v)
: row[k] === v,
);
};
if (existing) {
if (!same(existing))
throw new ConflictException('Ingestion key reused with different data');
return existing;
}
await this.findOne(findingId);
try {
return await this.prisma.contentPerformanceSnapshot.create({ data });
} catch (error) {
if ((error as any).code === 'P2002') {
const row =
await this.prisma.contentPerformanceSnapshot.findUniqueOrThrow({
where: {
findingId_ingestionKey: {
findingId,
ingestionKey: dto.ingestionKey,
},
},
});
if (same(row)) return row;
throw new ConflictException('Ingestion key reused with different data');
}
throw error;
}
}
}
@@ -1,66 +0,0 @@
import 'reflect-metadata';
import { Test } from '@nestjs/testing';
import { PassportModule, PassportStrategy } from '@nestjs/passport';
import { Strategy, ExtractJwt } from 'passport-jwt';
import { JwtService } from '@nestjs/jwt';
import { PrismaClient } from '@prisma/client';
import { spawn } from 'child_process';
import { resolve } from 'path';
import { SeoTrackingModule } from './seo-tracking.module';
import { PrismaService } from '../prisma/prisma.service';
class DisposableStrategy extends PassportStrategy(Strategy) {
constructor() {
super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: 'disposable-worker-http-only', ignoreExpiration: false });
}
validate(payload: any) { return payload; }
}
const url = process.env.SEO_TEST_DATABASE_URL;
if (url && url !== 'postgresql://seo_test@127.0.0.1:55439/postgres') {
throw new Error('Only the disposable local PostgreSQL cluster is permitted');
}
(url ? describe : describe.skip)('Worker -> actual Nest module -> disposable PostgreSQL', () => {
it('exercises Python worker over real TCP, shared guards, version fencing and immutable history', async () => {
const db = new PrismaClient({ datasources: { db: { url } } });
const module = await Test.createTestingModule({
imports: [PassportModule, SeoTrackingModule], providers: [DisposableStrategy],
}).overrideProvider(PrismaService).useValue(db).compile();
const app = module.createNestApplication({ logger: false });
app.setGlobalPrefix('api');
let blog: any;
try {
await app.listen(0, '127.0.0.1');
blog = await db.blog.create({ data: {
title: 'Disposable integration fixture: blackseed article URL',
slug: 'dog-black-seed-nigella-sativa', content: 'Local integration fixture, never published',
status: 'DRAFT', isPublished: false,
canonicalUrl: 'https://canina.ir/blog/dog-black-seed-nigella-sativa',
} });
const jwt = new JwtService({ secret: 'disposable-worker-http-only' });
const worker = resolve(__dirname, '../../../scripts/seo-performance/verify_real_http.py');
const output = await new Promise<string>((ok, fail) => {
const child = spawn('python3', [worker], { env: {
...process.env, SEO_LOCAL_BASE: `http://127.0.0.1:${app.getHttpServer().address().port}`,
SEO_FIXTURE_BLOG_ID: blog.id,
CANINA_ADMIN_TOKEN: jwt.sign({ role: 'admin', sub: 'disposable-http-fixture' }, { expiresIn: '5m' }),
SEO_CUSTOMER_TOKEN: jwt.sign({ role: 'customer' }, { expiresIn: '5m' }),
} });
let text = '';
child.stdout.on('data', (chunk) => { text += chunk; });
child.stderr.on('data', (chunk) => { text += chunk; });
child.on('error', fail);
child.on('close', (code) => code === 0 ? ok(text) : fail(new Error(text)));
});
console.log(output);
expect(output).toContain('REAL_HTTP_ACCEPTANCE_PASSED');
} finally {
if (blog) {
await db.contentResearchFinding.deleteMany({ where: { blogId: blog.id } });
await db.blog.delete({ where: { id: blog.id } });
}
await app.close();
await db.$disconnect();
}
}, 180000);
});
+1 -1
View File
@@ -36,7 +36,7 @@ export class TicketsService {
const ticketNumber = this.generateTicketNumber();
const senderName =
`${user.firstName || ""} ${user.lastName || ""}`.trim() || user.mobile || "کاربر";
`${user.firstName || ""} ${user.lastName || ""}`.trim() || user.mobile;
const ticket = await this.prisma.ticket.create({
data: {
@@ -1,20 +0,0 @@
# SEO tracking UI local verification
Scope: admin-panel only; no push, deployment, migration, scheduling or production writes. Reviewed specification/plan/tasks: `/opt/data/engineering/canina-spec-baseline/specs/002-seo-performance-tracking/`; contract: `/opt/data/analytics-engine/contract.md` v2. Source at start: develop `13f4fdc58dff96f192c612a8d38f33d314f70fad`; unrelated .specify/evidence existed. Shared worktree backend agent changes excluded from frontend commit.
Graphify navigation query: `SeoTrackingPage seoTrackingApi adminRoutes Sidebar`, graph hash `6a73473cee9e207543fdeeb668bea544f766200a1b16b8a3a9ce18d4e42e51af` (4304 nodes, 287 matches; truncated query). Graph SHA binding not established, therefore navigation only; direct source verified route/sidebar, API interceptor, backend global DecimalInterceptor, controller, DTO and service. Axios preserves response, server returns raw bodies, not a success/data wrapper.
Acceptance/implementation: server-driven page/search/status/sort with page reset; distinct loading/empty/error and retained stale rows after failed refetch; read cancellation and late-response guards; portal modal with labels, initial focus, inert page content, Tab wrap, Escape and focus restoration. Detail shows latest 30 stored snapshots, newest first, Tehran dates, source status/fetchedAt/period metadata. Null, unavailable and provenance-free legacy metrics never become measured zeros. Feedback is optional, requires expectedVersion, preserves snapshots and drafts after failure, rejects stale 409 save until explicit reload. Text does not claim downstream directive enforcement or live source queries.
RED: 7 UI tests failed with missing labels/sort/dialog/error handling and null metric crash (3 unhandled errors); `/opt/data/cache/scratch/seo-ui-red.log`. Service RED: 12 failed / 6 passed before implementation, exercised missing cancellation/version/response validation.
Final commands, all exit 0 (2026-10-28 UTC):
- `npm test -- --maxWorkers=2`: 53 files, 341 tests passed, 149.46s. Includes 10 SEO interaction tests plus 21 real Axios adapter/interceptor contract tests.
- `npx tsc -p tsconfig.app.json --noEmit`: passes actual application project. Root npm typecheck alone uses references and is not sufficient.
- `npm run lint`: 0 errors, 147 repository warnings; no lint errors introduced.
- `npm run build`: successful Vite production build.
- `git diff --check`: passes before commit.
Command logs: `/opt/data/cache/scratch/seo-admin-{full-tests,typecheck,lint,build}.log`.
Removed three unused Sidebar icon imports that prevented application typecheck. Route/sidebar SEO entry already existed and is unchanged. Verification uses mocked network fixtures, not live API/Google data; no browser/end-to-end or deployed acceptance is asserted. Backend version/schema rollout and legacy backfill remain backend/release responsibilities.
@@ -1,10 +0,0 @@
import type { PageMeta } from '../services/hermesApi';
export default function HermesPagination({ meta, loading, onPage }: { meta: PageMeta | null; loading: boolean; onPage: (page: number) => void }) {
if (!meta) return null;
return <nav aria-label="صفحه‌بندی" className="flex flex-wrap items-center gap-4 rounded-xl border p-4 bg-white">
<span>تعداد کل: {meta.total}</span>
<button disabled={loading || !meta.hasPrevPage} onClick={() => onPage(meta.page - 1)}>قبلی</button>
<span>صفحه {meta.page} از {meta.totalPages}</span>
<button disabled={loading || !meta.hasNextPage} onClick={() => onPage(meta.page + 1)}>بعدی</button>
</nav>;
}
@@ -1,10 +0,0 @@
import { cleanup, render, screen } from '@testing-library/react';
import { afterEach, expect, it } from 'vitest';
import HermesSource, { safeHttpUrl } from './HermesSource';
afterEach(cleanup);
it.each(['javascript:alert(1)', 'data:text/html,hi', 'canina://internal/1', 'not a URL'])('does not link unsafe/unavailable source %s', (source) => {
expect(safeHttpUrl(source)).toBeUndefined();
render(<HermesSource source={source} />);
expect(screen.queryByRole('link')).toBeNull();
expect(screen.getByText(/پیوند منبع در دسترس نیست/)).toBeDefined();
});
@@ -1,9 +0,0 @@
export function safeHttpUrl(value?: string): string | undefined {
if (!value) return undefined;
try { const url = new URL(value); return ['http:', 'https:'].includes(url.protocol) ? url.href : undefined; }
catch { return undefined; }
}
export default function HermesSource({ source }: { source?: string }) {
const url = safeHttpUrl(source);
return <span>منبع داده: {source || 'ناموجود'} — {url ? <a href={url} target="_blank" rel="noopener noreferrer" className="text-blue-700 underline">مشاهده منبع</a> : 'پیوند منبع در دسترس نیست'}</span>;
}
@@ -1,10 +1,9 @@
import {
Activity,
CheckSquare,
BookOpen,
Building2,
Calendar,
ChevronDown,
Compass,
CreditCard,
DollarSign,
FileText,
@@ -18,7 +17,6 @@ import {
Languages,
Layers,
LayoutDashboard,
ListOrdered,
Menu,
MessageSquare,
MessageSquareQuote,
@@ -38,6 +36,8 @@ import {
UserCheck,
Users,
Video,
History,
Briefcase
} from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
import { Link, useLocation } from 'react-router-dom';
@@ -112,17 +112,6 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side
{ icon: MessageSquare, label: 'تحلیل مشاوره سایت', path: '/settings/smart-chat' },
],
},
{
id: 'hermes',
title: 'هرمس | هوش و ارکستراسیون',
icon: Sparkles,
items: [
{ icon: ListOrdered, label: 'مدیریت و پایش وظایف', path: '/hermes/tasks' },
{ icon: TrendingUp, label: 'پایش عملکرد سئو و آمار', path: '/hermes/seo-tracking' },
{ icon: Compass, label: 'رصد بازار و رقبا', path: '/hermes/market-intelligence' },
{ icon: Calendar, label: 'نقشه راه استراتژیک ماهانه', path: '/hermes/monthly-roadmap' },
],
},
{
id: 'monitoring',
title: 'مرکز مانیتورینگ و سلامت',
@@ -1,131 +0,0 @@
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import CorporateTasksPage from './CorporateTasksPage';
import { hermesApi, type TasksResponse } from '../services/hermesApi';
vi.mock('../services/hermesApi', () => ({
hermesApi: {
getTasks: vi.fn(),
getTaskById: vi.fn(),
createCeoTask: vi.fn(),
},
}));
const mockTaskResponse: TasksResponse = {
data: [
{
id: 't-1',
taskCode: 'TSK-1001',
title: 'انتشار مقاله بالینی تائورین',
department: 'CONTENT_SEO',
priority: 'CEO_EXPEDITE',
status: 'DONE',
actionType: 'BLOG_NEW',
description: 'تدوین مقاله تائورین',
createdAt: '2026-10-28T00:00:00Z',
updatedAt: '2026-10-28T01:00:00Z',
logs: [
{
id: 'log-1',
speaker: 'PMO',
speakerName: 'ارکستراتور PMO',
step: 'TASK_ALLOCATION',
content: 'ارجاع تسک به واحد محتوا',
timestamp: '2026-10-28T00:00:00Z',
},
],
},
],
meta: {
total: 1,
page: 1,
limit: 10,
totalPages: 1,
hasNextPage: false,
hasPrevPage: false,
},
};
describe('CorporateTasksPage', () => {
beforeEach(() => {
vi.resetAllMocks();
vi.mocked(hermesApi.getTasks).mockResolvedValue(mockTaskResponse);
vi.mocked(hermesApi.getTaskById).mockResolvedValue(mockTaskResponse.data[0]);
});
afterEach(cleanup);
it('loads authoritative task detail from the API', async () => {
render(<CorporateTasksPage />);
fireEvent.click(await screen.findByRole('button', { name: /جزئیات و مکالمات/ }));
await waitFor(() => expect(hermesApi.getTaskById).toHaveBeenCalledWith('t-1', expect.any(AbortSignal)));
});
it('shows creation failure and retains entered directive', async () => {
vi.mocked(hermesApi.createCeoTask).mockRejectedValue(new Error('not saved'));
render(<CorporateTasksPage />);
fireEvent.click(await screen.findByRole('button', { name: /ثبت دستور فوری مدیرعامل/ }));
fireEvent.change(screen.getByPlaceholderText(/مثال: آپدیت فوری/), {target:{value:'retained directive'}});
fireEvent.change(screen.getByPlaceholderText(/دقیقاً چه کاری/), {target:{value:'acceptance'}});
fireEvent.click(screen.getByRole('button', {name:/ثبت با اولویت فوری صف/}));
expect(await screen.findByRole('alert')).toHaveTextContent('ثبت دستور ناموفق');
expect(screen.getByPlaceholderText(/مثال: آپدیت فوری/)).toHaveValue('retained directive');
});
it('renders task list with department badges, task codes, and filter elements', async () => {
render(<CorporateTasksPage />);
expect(await screen.findByText('مدیریت و پایش وظایف دپارتمان‌ها')).toBeDefined();
expect((await screen.findAllByText('TSK-1001')).length).toBeGreaterThan(0);
expect(screen.getByText('انتشار مقاله بالینی تائورین')).toBeDefined();
});
it('opens details modal and displays agent conversation history on click', async () => {
render(<CorporateTasksPage />);
const detailBtn = await screen.findByRole('button', { name: /جزئیات و مکالمات/ });
fireEvent.click(detailBtn);
expect(await screen.findByText('ریز مکالمات و تاریخچه اجرای ایجنت‌ها')).toBeDefined();
expect(screen.getByText('ارجاع تسک به واحد محتوا')).toBeDefined();
expect(screen.getByText('ارکستراتور PMO')).toBeDefined();
});
it('opens CEO expedite directive modal and submits new task', async () => {
vi.mocked(hermesApi.createCeoTask).mockResolvedValue({
id: 't-new',
taskCode: 'TSK-9999',
title: 'دستور تست مدیرعامل',
department: 'CONTENT_SEO',
priority: 'CEO_EXPEDITE',
status: 'TODO',
actionType: 'CEO_DIRECTIVE',
description: 'توضیحات تست',
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
});
render(<CorporateTasksPage />);
const expediteBtn = await screen.findByRole('button', { name: /ثبت دستور فوری مدیرعامل/ });
fireEvent.click(expediteBtn);
expect(await screen.findByText('ثبت مستقیم دستور مدیرعامل (CEO_EXPEDITE)')).toBeDefined();
const titleInput = screen.getByPlaceholderText(/مثال: آپدیت فوری/);
const descInput = screen.getByPlaceholderText(/دقیقاً چه کاری باید انجام شود/);
fireEvent.change(titleInput, { target: { value: 'دستور تست مدیرعامل' } });
fireEvent.change(descInput, { target: { value: 'توضیحات تست' } });
const submitBtn = screen.getByRole('button', { name: /ثبت با اولویت فوری صف/ });
fireEvent.click(submitBtn);
await waitFor(() => {
expect(hermesApi.createCeoTask).toHaveBeenCalledWith(
expect.objectContaining({
title: 'دستور تست مدیرعامل',
description: 'توضیحات تست',
priority: 'CEO_EXPEDITE',
})
);
});
});
});
@@ -1,684 +0,0 @@
import { useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { safeHttpUrl } from '../components/HermesSource';
import {
ListOrdered,
Search,
RefreshCw,
Eye,
Calendar,
FileText,
X,
ExternalLink,
MessageSquare,
ChevronLeft,
ChevronRight,
Zap,
Bot,
} from 'lucide-react';
import {
hermesApi,
type CorporateTaskItem,
type TaskDepartment,
type TaskPriority,
type TaskStatus,
} from '../services/hermesApi';
const deptConfig: Record<TaskDepartment, { label: string; bg: string; text: string; border: string }> = {
CONTENT_SEO: { label: 'محتوا و سئو', bg: 'bg-blue-50', text: 'text-blue-700', border: 'border-blue-200' },
CATALOG_COMMERCE: { label: 'کاتالوگ و انبار', bg: 'bg-amber-50', text: 'text-amber-700', border: 'border-amber-200' },
WIKI_SCIENTIFIC: { label: 'دانشنامه و علمی', bg: 'bg-purple-50', text: 'text-purple-700', border: 'border-purple-200' },
TECH_DEVOPS: { label: 'فنی و دواپس', bg: 'bg-slate-100', text: 'text-slate-700', border: 'border-slate-200' },
MARKET_INTELLIGENCE: { label: 'رصد بازار و رقبا', bg: 'bg-emerald-50', text: 'text-emerald-700', border: 'border-emerald-200' },
};
const statusConfig: Record<TaskStatus, { label: string; bg: string; text: string; border: string }> = {
TODO: { label: 'در صف نوبت', bg: 'bg-slate-100', text: 'text-slate-600', border: 'border-slate-200' },
IN_PROGRESS: { label: 'در حال انجام', bg: 'bg-sky-50', text: 'text-sky-700', border: 'border-sky-200' },
DONE: { label: 'انجام‌شده', bg: 'bg-emerald-50', text: 'text-emerald-700', border: 'border-emerald-200' },
BLOCKED: { label: 'مسدود', bg: 'bg-rose-50', text: 'text-rose-700', border: 'border-rose-200' },
CANCELLED: { label: 'لغوشده', bg: 'bg-gray-100', text: 'text-gray-500', border: 'border-gray-200' },
};
const priorityConfig: Record<TaskPriority, { label: string; badge: string }> = {
CEO_EXPEDITE: { label: 'اولویت ۱ مدیرعامل', badge: 'bg-rose-100 text-rose-800 border-rose-300 font-black' },
CRITICAL: { label: 'بحرانی', badge: 'bg-red-50 text-red-700 border-red-200 font-bold' },
HIGH: { label: 'بالا', badge: 'bg-amber-50 text-amber-800 border-amber-200 font-semibold' },
MEDIUM: { label: 'متوسط', badge: 'bg-slate-100 text-slate-700 border-slate-200' },
LOW: { label: 'عادی', badge: 'bg-gray-50 text-gray-500 border-gray-200' },
};
const date = (val?: string | null) =>
val && Number.isFinite(Date.parse(val))
? new Date(val).toLocaleString('fa-IR', { timeZone: 'Asia/Tehran' })
: 'نامشخص';
export default function CorporateTasksPage() {
const [tasks, setTasks] = useState<CorporateTaskItem[]>([]);
const [page, setPage] = useState(1);
const [meta, setMeta] = useState({ total: 0, totalPages: 0, hasNextPage: false, hasPrevPage: false });
const [search, setSearch] = useState('');
const [department, setDepartment] = useState('');
const [status, setStatus] = useState('');
const [priority, setPriority] = useState('');
const [reload, setReload] = useState(0);
const [error, setError] = useState(false);
const [createError, setCreateError] = useState(false);
const [loading, setLoading] = useState(true);
// Detail Modal
const [selectedTask, setSelectedTask] = useState<CorporateTaskItem | null>(null);
const [detailId, setDetailId] = useState<string | null>(null);
const [detailLoading, setDetailLoading] = useState(false);
const [detailError, setDetailError] = useState(false);
useEffect(() => {
if (!detailId) return;
const controller = new AbortController();
setDetailLoading(true);
setDetailError(false);
setSelectedTask(null);
hermesApi.getTaskById(detailId, controller.signal)
.then((item) => { if (!controller.signal.aborted) setSelectedTask(item); })
.catch(() => { if (!controller.signal.aborted) setDetailError(true); })
.finally(() => { if (!controller.signal.aborted) setDetailLoading(false); });
return () => controller.abort();
}, [detailId]);
// Fast-track CEO Directive Modal
const [ceoModalOpen, setCeoModalOpen] = useState(false);
const [ceoTitle, setCeoTitle] = useState('');
const [ceoDept, setCeoDept] = useState<TaskDepartment>('CONTENT_SEO');
const [ceoDesc, setCeoDesc] = useState('');
const [submittingCeo, setSubmittingCeo] = useState(false);
const pageContent = useRef<HTMLDivElement>(null);
useEffect(() => {
const controller = new AbortController();
setLoading(true);
setError(false);
setTasks([]);
hermesApi
.getTasks(
{ page, limit: 10, search: search.trim() || undefined, department: department || undefined, status: status || undefined, priority: priority || undefined },
controller.signal
)
.then((res) => {
if (!controller.signal.aborted) {
setTasks(res.data);
setMeta(res.meta);
}
})
.catch(() => { if (!controller.signal.aborted) setError(true); })
.finally(() => {
if (!controller.signal.aborted) setLoading(false);
});
return () => controller.abort();
}, [page, search, department, status, priority, reload]);
const handleCreateCeoDirective = async () => {
if (!ceoTitle.trim() || !ceoDesc.trim() || submittingCeo) return;
setSubmittingCeo(true);
setCreateError(false);
try {
await hermesApi.createCeoTask({
title: ceoTitle.trim(),
department: ceoDept,
description: ceoDesc.trim(),
priority: 'CEO_EXPEDITE',
});
setCeoModalOpen(false);
setCeoTitle('');
setCeoDesc('');
setReload((n) => n + 1);
} catch {
setCreateError(true);
} finally {
setSubmittingCeo(false);
}
};
const inputClass =
'w-full text-sm border border-slate-300 rounded-xl px-3 py-2 bg-white text-slate-800 placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-amber-500/20 focus:border-amber-500 transition-all';
return (
<div ref={pageContent} className="p-4 sm:p-6 lg:p-8 space-y-6 max-w-7xl mx-auto" dir="rtl">
{/* هدر صفحه */}
<header className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 pb-2 border-b border-slate-200">
<div>
<div className="flex items-center gap-2.5">
<div className="w-10 h-10 rounded-xl bg-amber-500 text-slate-950 flex items-center justify-center font-bold shadow-sm">
<ListOrdered className="w-5 h-5" />
</div>
<div>
<h1 className="text-xl sm:text-2xl font-black text-slate-900 tracking-tight">
مدیریت و پایش وظایف دپارتمان‌ها
</h1>
<p className="text-xs sm:text-sm text-slate-500 mt-0.5">
ارکستراسیون خودکار هرمس؛ رهگیری وظایف، تصمیمات میان‌بخشی و تاریخچه مکالمات ایجنت‌ها
</p>
</div>
</div>
</div>
<div className="flex items-center gap-3">
<button
className="inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-black text-slate-950 bg-amber-400 hover:bg-amber-500 shadow-sm active:scale-[0.98] transition-all cursor-pointer"
onClick={() => setCeoModalOpen(true)}
>
<Zap className="w-4 h-4 fill-slate-950" />
<span>ثبت دستور فوری مدیرعامل</span>
</button>
<button
className="inline-flex items-center justify-center gap-2 px-3.5 py-2.5 rounded-xl text-sm font-semibold text-slate-700 bg-white hover:bg-slate-50 border border-slate-200 shadow-sm active:scale-[0.98] transition-all cursor-pointer"
onClick={() => setReload((n) => n + 1)}
>
<RefreshCw className={`w-4 h-4 text-slate-500 ${loading ? 'animate-spin' : ''}`} />
</button>
</div>
</header>
{error && <p role="alert">وظایف در دسترس نیست؛ دریافت از سرور ناموفق بود.</p>}
{/* خلاصه ظرفیت دپارتمان‌ها */}
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3">
{(Object.keys(deptConfig) as TaskDepartment[]).map((dept) => {
const cfg = deptConfig[dept];
const count = tasks.filter((t) => t.department === dept).length;
return (
<div
key={dept}
onClick={() => {
setDepartment((prev) => (prev === dept ? '' : dept));
setPage(1);
}}
className={`p-3.5 rounded-2xl border transition-all cursor-pointer ${
department === dept
? 'bg-amber-50/70 border-amber-300 ring-2 ring-amber-400/30'
: 'bg-white border-slate-200/80 hover:border-slate-300'
}`}
>
<div className="flex items-center justify-between">
<span className="text-xs font-bold text-slate-600">{cfg.label} (این صفحه)</span>
<span className={`text-xs px-2 py-0.5 rounded-md font-bold ${cfg.bg} ${cfg.text}`}>
{error || loading ? 'ناموجود' : count}
</span>
</div>
</div>
);
})}
</div>
{/* فیلترها و جستجو */}
<div className="bg-white rounded-2xl p-4 sm:p-5 border border-slate-200/80 shadow-sm">
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3.5">
<div>
<label className="block text-xs font-semibold text-slate-600 mb-1.5">
جستجو
<div className="relative mt-1">
<input
className={`${inputClass} pl-9`}
placeholder="عنوان، کد یا شرح تسک..."
value={search}
onChange={(e) => {
setSearch(e.target.value);
setPage(1);
}}
/>
<Search className="w-4 h-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2 pointer-events-none" />
</div>
</label>
</div>
<div>
<label className="block text-xs font-semibold text-slate-600 mb-1.5">
دپارتمان
<select
className={`${inputClass} mt-1`}
value={department}
onChange={(e) => {
setDepartment(e.target.value);
setPage(1);
}}
>
<option value="">همه دپارتمان‌ها</option>
{Object.entries(deptConfig).map(([k, v]) => (
<option key={k} value={k}>
{v.label}
</option>
))}
</select>
</label>
</div>
<div>
<label className="block text-xs font-semibold text-slate-600 mb-1.5">
وضعیت
<select
className={`${inputClass} mt-1`}
value={status}
onChange={(e) => {
setStatus(e.target.value);
setPage(1);
}}
>
<option value="">همه وضعیت‌ها</option>
{Object.entries(statusConfig).map(([k, v]) => (
<option key={k} value={k}>
{v.label}
</option>
))}
</select>
</label>
</div>
<div>
<label className="block text-xs font-semibold text-slate-600 mb-1.5">
اولویت
<select
className={`${inputClass} mt-1`}
value={priority}
onChange={(e) => {
setPriority(e.target.value);
setPage(1);
}}
>
<option value="">همه اولویت‌ها</option>
{Object.entries(priorityConfig).map(([k, v]) => (
<option key={k} value={k}>
{v.label}
</option>
))}
</select>
</label>
</div>
</div>
</div>
{/* وضعیت لودینگ */}
{loading && (
<div className="flex items-center justify-center p-8 text-slate-500 text-sm gap-2">
<RefreshCw className="w-5 h-5 animate-spin text-amber-500" />
<span>در حال دریافت لیست وظایف...</span>
</div>
)}
{/* لیست وظایف (سازگار با موبایل و دسکتاپ) */}
<div className="bg-white rounded-2xl border border-slate-200/90 shadow-sm overflow-hidden">
<table className="w-full text-right" aria-busy={loading}>
<caption className="sr-only">وظایف دپارتمان‌های کنینا</caption>
<thead className="hidden md:table-header-group bg-slate-50/80 border-b border-slate-200 text-slate-700 text-xs font-bold uppercase tracking-wider">
<tr>
{['کد و عنوان تسک', 'دپارتمان', 'اولویت', 'وضعیت', 'ستون موضوعی', 'تاریخ ثبت', 'عملیات'].map(
(text) => (
<th scope="col" key={text} className="p-3.5 first:pr-5 last:pl-5">
{text}
</th>
)
)}
</tr>
</thead>
<tbody className="divide-y divide-slate-100 block md:table-row-group">
{!loading && !error && tasks.length === 0 && (
<tr className="block md:table-row">
<td colSpan={7} className="p-12 text-center text-slate-500 text-sm block md:table-cell">
<div className="max-w-xs mx-auto space-y-2">
<FileText className="w-8 h-8 text-slate-300 mx-auto" />
<p className="font-semibold text-slate-700">تسک فعالی با این فیلترها یافت نشد.</p>
</div>
</td>
</tr>
)}
{tasks.map((task) => {
const dept = deptConfig[task.department] ?? {
label: task.department,
bg: 'bg-slate-100',
text: 'text-slate-700',
border: 'border-slate-200',
};
const stat = statusConfig[task.status] ?? {
label: task.status,
bg: 'bg-slate-100',
text: 'text-slate-700',
border: 'border-slate-200',
};
const prio = priorityConfig[task.priority] ?? {
label: task.priority,
badge: 'bg-slate-100 text-slate-700 border-slate-200',
};
return (
<tr
key={task.id}
className="block md:table-row p-4 sm:p-5 md:p-0 border-b md:border-b-0 border-slate-100 hover:bg-slate-50/60 transition-colors"
>
{/* کد و عنوان */}
<td className="block md:table-cell p-0 md:p-3.5 md:pr-5 pb-2 md:pb-3.5 align-top">
<div className="space-y-1">
<div className="flex flex-wrap items-center gap-2 mb-1.5 md:hidden">
<span className="font-mono text-xs font-bold text-slate-500 bg-slate-100 px-2 py-0.5 rounded">
{task.taskCode}
</span>
<span
className={`text-xs px-2.5 py-0.5 rounded-full font-semibold border ${dept.bg} ${dept.text} ${dept.border}`}
>
{dept.label}
</span>
<span
className={`text-xs px-2.5 py-0.5 rounded-full border ${prio.badge}`}
>
{prio.label}
</span>
</div>
<div className="hidden md:flex items-center gap-2 mb-1">
<span className="font-mono text-[11px] font-bold text-slate-500 bg-slate-100 px-1.5 py-0.5 rounded">
{task.taskCode}
</span>
</div>
<strong className="block text-sm sm:text-base font-bold text-slate-900 leading-snug">
{task.title}
</strong>
<p className="text-xs text-slate-500 line-clamp-2 md:line-clamp-1">{task.description}</p>
</div>
</td>
{/* دپارتمان (دسکتاپ) */}
<td className="hidden md:table-cell p-3.5 align-top">
<span
className={`inline-flex items-center px-2.5 py-1 rounded-full text-xs font-semibold border ${dept.bg} ${dept.text} ${dept.border}`}
>
{dept.label}
</span>
</td>
{/* اولویت (دسکتاپ) */}
<td className="hidden md:table-cell p-3.5 align-top">
<span
className={`inline-flex items-center px-2.5 py-1 rounded-full text-xs border ${prio.badge}`}
>
{prio.label}
</span>
</td>
{/* وضعیت */}
<td className="block md:table-cell p-0 md:p-3.5 py-2 md:py-3.5 align-top">
<div className="flex items-center gap-2">
<span
className={`inline-flex items-center px-2.5 py-1 rounded-full text-xs font-semibold border ${stat.bg} ${stat.text} ${stat.border}`}
>
{stat.label}
</span>
</div>
</td>
{/* ستون موضوعی */}
<td className="block md:table-cell p-0 md:p-3.5 py-1 md:py-3.5 align-top text-xs text-slate-600">
<span className="md:hidden font-semibold text-slate-400 ml-1">ستون: </span>
<span>{task.targetPillar || 'عمومی'}</span>
</td>
{/* تاریخ ثبت */}
<td className="block md:table-cell p-0 md:p-3.5 py-1 md:py-3.5 align-top text-xs text-slate-500">
<div className="flex items-center gap-1">
<Calendar className="w-3.5 h-3.5 text-slate-400 md:hidden" />
<span>{date(task.createdAt)}</span>
</div>
</td>
{/* دکمه عملیات */}
<td className="block md:table-cell p-0 md:p-3.5 md:pl-5 pt-3 md:pt-3.5 align-top">
<button
className="w-full md:w-auto inline-flex items-center justify-center gap-2 px-3.5 py-2 rounded-xl text-xs sm:text-sm font-semibold text-slate-700 bg-slate-100 hover:bg-slate-200 border border-slate-200 shadow-sm active:scale-[0.98] transition-all cursor-pointer"
onClick={() => setDetailId(task.id)}
>
<Eye className="w-4 h-4 text-slate-600" />
<span>جزئیات و مکالمات</span>
</button>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
{/* صفحه‌بندی */}
{!error && !loading && <nav
aria-label="صفحه‌بندی"
className="flex flex-col sm:flex-row items-center justify-between gap-4 p-4 bg-white rounded-2xl border border-slate-200/90 shadow-sm text-sm text-slate-600"
>
<span className="font-medium text-xs sm:text-sm">تعداد کل: {meta.total} تسک</span>
<div className="flex items-center gap-2">
<button
className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl border border-slate-200 font-semibold text-xs sm:text-sm bg-white hover:bg-slate-50 disabled:opacity-40 disabled:pointer-events-none transition-all cursor-pointer shadow-sm"
disabled={loading || !meta.hasPrevPage}
onClick={() => setPage((p) => Math.max(1, p - 1))}
>
<ChevronRight className="w-4 h-4" />
<span>قبلی</span>
</button>
<span className="px-3 py-1 rounded-lg bg-slate-100 font-bold text-xs sm:text-sm text-slate-800">
صفحه {page} از {meta.totalPages || 1}
</span>
<button
className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl border border-slate-200 font-semibold text-xs sm:text-sm bg-white hover:bg-slate-50 disabled:opacity-40 disabled:pointer-events-none transition-all cursor-pointer shadow-sm"
disabled={loading || !meta.hasNextPage}
onClick={() => setPage((p) => p + 1)}
>
<span>بعدی</span>
<ChevronLeft className="w-4 h-4" />
</button>
</div>
</nav>}
{detailLoading && <p role="status">در حال دریافت جزئیات تسک...</p>}
{detailError && <div role="alert">جزئیات در دسترس نیست. <button onClick={() => { setDetailId(null); setDetailError(false); }}>بستن</button></div>}
{/* مودال جزئیات و ریز مکالمات ایجنت‌ها */}
{selectedTask &&
createPortal(
<div className="fixed inset-0 z-50 bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-3 sm:p-6" dir="rtl">
<div className="bg-white rounded-3xl shadow-2xl w-full max-w-4xl max-h-[92vh] flex flex-col overflow-hidden border border-slate-200">
{/* هدر مودال */}
<div className="flex items-center justify-between gap-4 px-6 py-4 border-b border-slate-200 bg-slate-50/70">
<div className="flex items-center gap-3">
<div className="w-9 h-9 rounded-xl bg-amber-100 text-amber-700 flex items-center justify-center shadow-xs">
<Bot className="w-5 h-5" />
</div>
<div>
<div className="flex items-center gap-2">
<span className="font-mono text-xs font-bold text-slate-500 bg-slate-200 px-2 py-0.5 rounded">
{selectedTask.taskCode}
</span>
<h2 className="font-black text-base sm:text-lg text-slate-900 leading-snug">
{selectedTask.title}
</h2>
</div>
<p className="text-xs text-slate-500 mt-0.5">
دپارتمان: {deptConfig[selectedTask.department]?.label} — تاریخ ایجاد: {date(selectedTask.createdAt)}
</p>
</div>
</div>
<button
className="p-2 rounded-xl text-slate-500 hover:text-slate-800 hover:bg-slate-200/80 transition-colors cursor-pointer"
onClick={() => { setSelectedTask(null); setDetailId(null); }}
>
<X className="w-5 h-5" />
</button>
</div>
{/* بدنه اسکرولی */}
<div className="p-6 overflow-y-auto space-y-6">
{/* اطلاعات کلی تسک */}
<div className="bg-slate-50 rounded-2xl p-4 border border-slate-200 space-y-2">
<h3 className="text-xs font-bold text-slate-600">هدف و شرح اقدام:</h3>
<p className="text-sm text-slate-800 leading-relaxed">{selectedTask.description}</p>
{safeHttpUrl(selectedTask.deliverableUrl) && (
<div className="pt-2 border-t border-slate-200/60 flex items-center gap-2">
<span className="text-xs font-bold text-slate-600">خروجی زنده:</span>
<a
href={safeHttpUrl(selectedTask.deliverableUrl)}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 text-xs font-bold text-blue-700 underline"
>
<span>{selectedTask.deliverableUrl}</span>
<ExternalLink className="w-3 h-3" />
</a>
</div>
)}
</div>
{/* تایم‌لاین ریز مکالمات و لاگ اقدام ایجنت‌ها */}
<div className="space-y-4">
<div className="flex items-center gap-2 pb-2 border-b border-slate-100">
<MessageSquare className="w-5 h-5 text-amber-600" />
<h3 className="font-black text-sm sm:text-base text-slate-900">
ریز مکالمات و تاریخچه اجرای ایجنت‌ها
</h3>
</div>
<div className="space-y-3">
{selectedTask.logs && selectedTask.logs.length > 0 ? (
selectedTask.logs.map((log, idx) => {
const isCeo = log.speaker === 'CEO';
const isPmo = log.speaker === 'PMO';
const isQa = log.speaker === 'QA';
return (
<div
key={log.id || idx}
className={`p-4 rounded-2xl border transition-all ${
isCeo
? 'bg-amber-50/70 border-amber-200'
: isPmo
? 'bg-blue-50/70 border-blue-200'
: isQa
? 'bg-purple-50/70 border-purple-200'
: 'bg-white border-slate-200 shadow-xs'
}`}
>
<div className="flex items-center justify-between pb-2 mb-2 border-b border-slate-100 text-xs">
<div className="flex items-center gap-2">
<span
className={`px-2 py-0.5 rounded font-black text-[11px] ${
isCeo
? 'bg-amber-200 text-amber-900'
: isPmo
? 'bg-blue-200 text-blue-900'
: isQa
? 'bg-purple-200 text-purple-900'
: 'bg-slate-200 text-slate-800'
}`}
>
{log.speakerName || log.speaker}
</span>
{log.step && (
<span className="font-mono text-[10px] text-slate-400 bg-slate-100 px-1.5 py-0.5 rounded">
{log.step}
</span>
)}
</div>
<span className="text-slate-400 text-[11px]">{date(log.timestamp)}</span>
</div>
<p className="text-xs sm:text-sm text-slate-800 leading-relaxed font-medium">
{log.content}
</p>
</div>
);
})
) : (
<p className="text-xs text-slate-500 bg-slate-50 p-4 rounded-xl text-center">
هنوز لاگ اجرایی برای این تسک ثبت نشده است.
</p>
)}
</div>
</div>
</div>
</div>
</div>,
document.body
)}
{/* مودال ثبت مستقیم دستور مدیرعامل */}
{ceoModalOpen &&
createPortal(
<div className="fixed inset-0 z-50 bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-3 sm:p-6" dir="rtl">
<div className="bg-white rounded-3xl shadow-2xl w-full max-w-lg p-6 border border-slate-200 space-y-4">
<div className="flex items-center justify-between pb-3 border-b border-slate-200">
<div className="flex items-center gap-2 text-rose-700">
<Zap className="w-5 h-5 fill-rose-600" />
<h2 className="font-black text-base text-slate-900">ثبت مستقیم دستور مدیرعامل (CEO_EXPEDITE)</h2>
</div>
<button
className="p-1 rounded-lg text-slate-400 hover:text-slate-700"
onClick={() => setCeoModalOpen(false)}
>
<X className="w-5 h-5" />
</button>
</div>
{createError && <p role="alert">ثبت دستور ناموفق بود؛ ثبت در سرور تأیید نشد.</p>}
<div className="space-y-3">
<div>
<label className="block text-xs font-bold text-slate-700 mb-1">عنوان دستور یا تسک</label>
<input
className={inputClass}
placeholder="مثال: آپدیت فوری مشخصات دارویی Canina GAG"
value={ceoTitle}
onChange={(e) => setCeoTitle(e.target.value)}
/>
</div>
<div>
<label className="block text-xs font-bold text-slate-700 mb-1">دپارتمان مجری</label>
<select
className={inputClass}
value={ceoDept}
onChange={(e) => setCeoDept(e.target.value as TaskDepartment)}
>
{Object.entries(deptConfig).map(([k, v]) => (
<option key={k} value={k}>
{v.label}
</option>
))}
</select>
</div>
<div>
<label className="block text-xs font-bold text-slate-700 mb-1">توضیحات و معیارهای پذیرش</label>
<textarea
rows={4}
className={inputClass}
placeholder="دقیقاً چه کاری باید انجام شود و چه نتیجه‌ای مدنظر است؟"
value={ceoDesc}
onChange={(e) => setCeoDesc(e.target.value)}
/>
</div>
</div>
<div className="flex items-center justify-end gap-3 pt-3 border-t border-slate-100">
<button
className="px-4 py-2 rounded-xl text-xs font-semibold text-slate-600 hover:bg-slate-100 cursor-pointer"
onClick={() => setCeoModalOpen(false)}
>
انصراف
</button>
<button
className="px-5 py-2.5 rounded-xl font-bold text-xs sm:text-sm bg-rose-600 hover:bg-rose-700 text-white shadow-sm active:scale-[0.98] transition-all cursor-pointer disabled:opacity-50"
disabled={submittingCeo || !ceoTitle.trim() || !ceoDesc.trim()}
onClick={handleCreateCeoDirective}
>
{submittingCeo ? 'در حال ثبت...' : 'ثبت با اولویت فوری صف'}
</button>
</div>
</div>
</div>,
document.body
)}
</div>
);
}
@@ -1,27 +0,0 @@
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import Market from './MarketIntelligencePage';
import Roadmap from './MonthlyRoadmapPage';
import { hermesApi } from '../services/hermesApi';
vi.mock('../services/hermesApi', () => ({ hermesApi: { getMarketInsights: vi.fn(), getMonthlyRoadmap: vi.fn() } }));
afterEach(cleanup);
const meta = { total: 42, page: 1, limit: 10, totalPages: 5, hasNextPage: true, hasPrevPage: false };
beforeEach(() => vi.resetAllMocks());
it.each([{ Component: Market, method: 'getMarketInsights' as const }, { Component: Roadmap, method: 'getMonthlyRoadmap' as const }])('uses server metadata and requests next page for $method', async ({ Component, method }) => {
vi.mocked(hermesApi[method]).mockResolvedValue({ data: [], meta });
render(<Component />);
expect(await screen.findByText(/تعداد کل: 42/)).toBeDefined();
fireEvent.click(screen.getByRole('button', { name: 'بعدی' }));
await waitFor(() => expect(hermesApi[method]).toHaveBeenLastCalledWith(expect.objectContaining({ page: 2, limit: 10 }), expect.any(AbortSignal)));
});
it('shows explicit unavailable state with no fake summary', async () => {
vi.mocked(hermesApi.getMarketInsights).mockRejectedValue(new Error('offline'));
render(<Market />);
expect(await screen.findByRole('alert')).toBeDefined();
expect(screen.queryByText('مکمل مفاصل و ضدآرتروز')).toBeNull();
});
it('links only a supplied HTTP source', async () => {
vi.mocked(hermesApi.getMarketInsights).mockResolvedValue({data:[{id:'1',title:'real',category:'TREND',source:'https://example.org/evidence',opportunity:'evidence',impact:'HIGH',recommendedAction:'review',status:'DISCOVERED',createdAt:'2026-10-28'}],meta});
render(<Market />);
expect((await screen.findByRole('link', {name:'مشاهده منبع'})).getAttribute('href')).toBe('https://example.org/evidence');
});
@@ -1,168 +0,0 @@
import { useEffect, useState } from 'react';
import HermesPagination from '../components/HermesPagination';
import type { PageMeta } from '../services/hermesApi';
import HermesSource from '../components/HermesSource';
import {
Compass,
RefreshCw,
} from 'lucide-react';
import { hermesApi, type MarketInsightItem } from '../services/hermesApi';
const categoryLabels: Record<string, { label: string; bg: string; text: string }> = {
TREND: { label: 'ترند صعودی بازار', bg: 'bg-emerald-50', text: 'text-emerald-700' },
CATALOG_GAP: { label: 'شکاف محتوا و کاتالوگ', bg: 'bg-amber-50', text: 'text-amber-700' },
NEW_CHANNEL: { label: 'کانال توزیع جدید', bg: 'bg-blue-50', text: 'text-blue-700' },
COMPETITOR: { label: 'رصد رقبا و ترب', bg: 'bg-purple-50', text: 'text-purple-700' },
};
const impactBadges: Record<string, string> = {
HIGH: 'bg-rose-100 text-rose-800 border-rose-300 font-bold',
MEDIUM: 'bg-amber-50 text-amber-800 border-amber-200',
LOW: 'bg-slate-100 text-slate-700 border-slate-200',
};
const date = (val?: string | null) =>
val && Number.isFinite(Date.parse(val))
? new Date(val).toLocaleString('fa-IR', { timeZone: 'Asia/Tehran' })
: 'نامشخص';
export default function MarketIntelligencePage() {
const [insights, setInsights] = useState<MarketInsightItem[]>([]);
const [category, setCategory] = useState('');
const [error, setError] = useState(false);
const [loading, setLoading] = useState(true);
const [reload, setReload] = useState(0);
const [page, setPage] = useState(1);
const [meta, setMeta] = useState<PageMeta | null>(null);
useEffect(() => {
const controller = new AbortController();
setLoading(true);
setError(false);
setMeta(null);
setInsights([]);
hermesApi
.getMarketInsights({ page, limit: 10, category: category || undefined }, controller.signal)
.then((data) => {
if (!controller.signal.aborted) { setInsights(data.data); setMeta(data.meta); }
})
.catch(() => { if (!controller.signal.aborted) setError(true); })
.finally(() => {
if (!controller.signal.aborted) setLoading(false);
});
return () => controller.abort();
}, [reload, page, category]);
const filtered = insights;
return (
<div className="p-4 sm:p-6 lg:p-8 space-y-6 max-w-7xl mx-auto" dir="rtl">
{/* هدر صفحه */}
<header className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 pb-2 border-b border-slate-200">
<div>
<div className="flex items-center gap-2.5">
<div className="w-10 h-10 rounded-xl bg-emerald-500 text-white flex items-center justify-center shadow-sm">
<Compass className="w-5 h-5" />
</div>
<div>
<h1 className="text-xl sm:text-2xl font-black text-slate-900 tracking-tight">
رصد هوشمند بازار و رقبا
</h1>
<p className="text-xs sm:text-sm text-slate-500 mt-0.5">
شناسایی ترندهای تقاضای پت در ایران، شکاف‌های کاتالوگ و فرصت‌های توسعه فراتر از ترب
</p>
</div>
</div>
</div>
<button
className="inline-flex items-center justify-center gap-2 px-3.5 py-2.5 rounded-xl text-sm font-semibold text-slate-700 bg-white hover:bg-slate-50 border border-slate-200 shadow-sm active:scale-[0.98] transition-all cursor-pointer"
onClick={() => setReload((n) => n + 1)}
>
<RefreshCw className={`w-4 h-4 text-slate-500 ${loading ? 'animate-spin' : ''}`} />
<span>به‌روزرسانی داده‌ها</span>
</button>
</header>
{loading && <p role="status">در حال دریافت داده‌ها...</p>}
{error && <p role="alert">داده‌ها در دسترس نیست؛ دریافت از سرور ناموفق بود.</p>}
{!loading && !error && insights.length === 0 && <p>هنوز داده‌ای ثبت نشده است.</p>}
{/* فیلتر دسته‌بندی */}
<div className="flex flex-wrap gap-2">
<button
onClick={() => { setCategory(''); setPage(1); }}
className={`px-3 py-1.5 rounded-xl text-xs font-bold border transition-all cursor-pointer ${
category === ''
? 'bg-slate-900 text-white border-slate-900 shadow-xs'
: 'bg-white text-slate-600 border-slate-200 hover:bg-slate-50'
}`}
>
همه بینش‌ها
</button>
{Object.entries(categoryLabels).map(([k, v]) => (
<button
key={k}
onClick={() => { setCategory(k); setPage(1); }}
className={`px-3 py-1.5 rounded-xl text-xs font-bold border transition-all cursor-pointer ${
category === k
? 'bg-slate-900 text-white border-slate-900 shadow-xs'
: 'bg-white text-slate-600 border-slate-200 hover:bg-slate-50'
}`}
>
{v.label}
</button>
))}
</div>
{/* لیست فرصت‌ها و بینش‌ها */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{filtered.map((item) => {
const cat = categoryLabels[item.category] ?? {
label: item.category,
bg: 'bg-slate-100',
text: 'text-slate-700',
};
const imp = impactBadges[item.impact] ?? 'bg-slate-100 text-slate-700';
return (
<div
key={item.id}
className="bg-white rounded-2xl p-5 border border-slate-200/90 shadow-sm space-y-4 hover:border-slate-300 transition-all flex flex-col justify-between"
>
<div className="space-y-2">
<div className="flex items-center justify-between gap-2">
<span
className={`text-xs px-2.5 py-0.5 rounded-full font-bold ${cat.bg} ${cat.text}`}
>
{cat.label}
</span>
<span className={`text-[11px] px-2 py-0.5 rounded-full border ${imp}`}>
اثرگذاری: {item.impact === 'HIGH' ? 'بالا' : item.impact === 'MEDIUM' ? 'متوسط' : 'عادی'}
</span>
</div>
<h3 className="font-bold text-base text-slate-900 leading-snug">{item.title}</h3>
<div className="bg-slate-50 p-3 rounded-xl border border-slate-100 text-xs text-slate-700 space-y-1">
<span className="font-bold text-slate-500 block">شرح فرصت:</span>
<p className="leading-relaxed">{item.opportunity}</p>
</div>
<div className="bg-emerald-50/70 p-3 rounded-xl border border-emerald-100 text-xs text-emerald-950 space-y-1">
<span className="font-bold text-emerald-800 block">اقدام پیشنهادی به شرکت:</span>
<p className="leading-relaxed font-medium">{item.recommendedAction}</p>
</div>
</div>
<div className="pt-3 border-t border-slate-100 flex items-center justify-between text-[11px] text-slate-400">
<HermesSource source={item.source} />
<span>ثبت: {date(item.createdAt)}</span>
</div>
</div>
);
})}
</div>
<HermesPagination meta={meta} loading={loading} onPage={setPage} />
</div>
);
}
@@ -1,170 +0,0 @@
import { useEffect, useState } from 'react';
import HermesPagination from '../components/HermesPagination';
import type { PageMeta } from '../services/hermesApi';
import {
Calendar,
CheckCircle2,
Sparkles,
FileText,
RotateCcw,
Package,
RefreshCw,
Target,
ThermometerSnowflake,
} from 'lucide-react';
import { hermesApi, type MonthlyRoadmapItem } from '../services/hermesApi';
export default function MonthlyRoadmapPage() {
const [roadmap, setRoadmap] = useState<MonthlyRoadmapItem[]>([]);
const [error, setError] = useState(false);
const [loading, setLoading] = useState(true);
const [reload, setReload] = useState(0);
const [page, setPage] = useState(1);
const [meta, setMeta] = useState<PageMeta | null>(null);
useEffect(() => {
const controller = new AbortController();
setLoading(true);
setError(false);
setMeta(null);
setRoadmap([]);
hermesApi
.getMonthlyRoadmap({ page, limit: 10 }, controller.signal)
.then((data) => {
if (!controller.signal.aborted) { setRoadmap(data.data); setMeta(data.meta); }
})
.catch(() => { if (!controller.signal.aborted) setError(true); })
.finally(() => {
if (!controller.signal.aborted) setLoading(false);
});
return () => controller.abort();
}, [reload, page]);
// Render every persisted cycle in the selected server page, not just the first.
return (
<div className="p-4 sm:p-6 lg:p-8 space-y-6 max-w-7xl mx-auto" dir="rtl">
{/* هدر صفحه */}
<header className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 pb-2 border-b border-slate-200">
<div>
<div className="flex items-center gap-2.5">
<div className="w-10 h-10 rounded-xl bg-purple-500 text-white flex items-center justify-center shadow-sm">
<Calendar className="w-5 h-5" />
</div>
<div>
<h1 className="text-xl sm:text-2xl font-black text-slate-900 tracking-tight">
نقشه راه استراتژیک ماهانه (Discovery Blueprint)
</h1>
<p className="text-xs sm:text-sm text-slate-500 mt-0.5">
تخصیص ظرفیت سازمانی؛ هماهنگی تولید محتوای جدید، بازنگری مقالات قبلی و غنی‌سازی کاتالوگ
</p>
</div>
</div>
</div>
<button
className="inline-flex items-center justify-center gap-2 px-3.5 py-2.5 rounded-xl text-sm font-semibold text-slate-700 bg-white hover:bg-slate-50 border border-slate-200 shadow-sm active:scale-[0.98] transition-all cursor-pointer"
onClick={() => setReload((n) => n + 1)}
>
<RefreshCw className={`w-4 h-4 text-slate-500 ${loading ? 'animate-spin' : ''}`} />
<span>به‌روزرسانی برنامه</span>
</button>
</header>
{loading && <p role="status">در حال دریافت داده‌ها...</p>}
{error && <p role="alert">داده‌ها در دسترس نیست؛ دریافت از سرور ناموفق بود.</p>}
{!loading && !error && roadmap.length === 0 && <p>هنوز داده‌ای ثبت نشده است.</p>}
{roadmap.map((activePlan) => <section key={activePlan.id} className="space-y-6">
{/* بنر چرخه فعال */}
{activePlan && (
<div className="bg-gradient-to-l from-purple-900 to-indigo-900 text-white rounded-3xl p-6 sm:p-8 shadow-xl relative overflow-hidden">
<div className="relative z-10 space-y-4 max-w-3xl">
<div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-white/10 backdrop-blur-md text-xs font-semibold text-purple-200 border border-white/15">
<Sparkles className="w-3.5 h-3.5 text-amber-300" />
<span>چرخه استراتژیک {activePlan.isActive ? 'فعال' : 'بایگانی'}: {activePlan.month}</span>
</div>
<h2 className="text-2xl sm:text-3xl font-black tracking-tight">{activePlan.cycleName}</h2>
<div className="flex items-start gap-2.5 bg-white/10 backdrop-blur-md p-4 rounded-2xl border border-white/10 text-xs sm:text-sm text-purple-100">
<ThermometerSnowflake className="w-5 h-5 text-sky-300 shrink-0 mt-0.5" />
<p className="leading-relaxed font-medium">
<strong>رویکرد فصلی و اقلیمی ایران:</strong> {activePlan.seasonalTheme}
</p>
</div>
</div>
</div>
)}
{/* ماتریس ظرفیت کارهای ماهانه */}
{activePlan && (
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<div className="bg-white rounded-2xl p-5 border border-slate-200 shadow-xs space-y-3">
<div className="flex items-center justify-between">
<span className="text-xs font-bold text-slate-500">تولید محتوای جدید</span>
<div className="w-8 h-8 rounded-xl bg-blue-50 text-blue-600 flex items-center justify-center">
<FileText className="w-4 h-4" />
</div>
</div>
<div className="text-3xl font-black text-slate-900">{typeof activePlan.plannedArticlesCount === 'number' ? activePlan.plannedArticlesCount : 'ناموجود'} <span className="text-sm font-normal text-slate-500">مقاله</span></div>
<p className="text-xs text-slate-500 leading-relaxed">
هدف: روزانه یک مقاله جدید؛ بازنگری مقالات جایگزین این هدف نیست.
</p>
</div>
<div className="bg-white rounded-2xl p-5 border border-slate-200 shadow-xs space-y-3">
<div className="flex items-center justify-between">
<span className="text-xs font-bold text-slate-500">بازنگری مقالات موجود</span>
<div className="w-8 h-8 rounded-xl bg-emerald-50 text-emerald-600 flex items-center justify-center">
<RotateCcw className="w-4 h-4" />
</div>
</div>
<div className="text-3xl font-black text-slate-900">بر اساس نیاز</div>
<p className="text-xs text-slate-500 leading-relaxed">
بازنگری جدا از هدف انتشار روزانه مقاله جدید و بدون سهمیه ثابت انجام می‌شود.
</p>
</div>
<div className="bg-white rounded-2xl p-5 border border-slate-200 shadow-xs space-y-3">
<div className="flex items-center justify-between">
<span className="text-xs font-bold text-slate-500">غنی‌سازی کاتالوگ و دانشنامه</span>
<div className="w-8 h-8 rounded-xl bg-amber-50 text-amber-600 flex items-center justify-center">
<Package className="w-4 h-4" />
</div>
</div>
<div className="text-3xl font-black text-slate-900">{typeof activePlan.plannedCatalogEnrichments === 'number' ? activePlan.plannedCatalogEnrichments : 'ناموجود'} <span className="text-sm font-normal text-slate-500">محصول / ماده</span></div>
<p className="text-xs text-slate-500 leading-relaxed">
تکمیل ۵ تب مشخصات کالاها و لینک دوطرفه با دانشنامه ترکیبات کنینا.
</p>
</div>
</div>
)}
{/* اهداف استراتژیک ماه */}
{activePlan && (
<div className="bg-white rounded-2xl p-6 border border-slate-200 shadow-sm space-y-4">
<div className="flex items-center gap-2">
<Target className="w-5 h-5 text-purple-600" />
<h3 className="font-black text-base text-slate-900">اهداف و معیارهای موفقیت ماه</h3>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
{(activePlan.strategicGoals ?? []).map((goal, idx) => (
<div
key={idx}
className="flex items-center gap-3 p-3.5 rounded-xl bg-slate-50 border border-slate-100"
>
<div className="w-6 h-6 rounded-lg bg-emerald-100 text-emerald-700 flex items-center justify-center shrink-0">
<CheckCircle2 className="w-4 h-4" />
</div>
<span className="text-xs sm:text-sm font-medium text-slate-800">{goal}</span>
</div>
))}
</div>
</div>
)}
</section>)}
<HermesPagination meta={meta} loading={loading} onPage={setPage} />
</div>
);
}
@@ -1,86 +0,0 @@
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import SeoTrackingPage from './SeoTrackingPage';
import { seoTrackingApi, type ResearchFinding } from '../services/seoTrackingApi';
vi.mock('../services/seoTrackingApi', () => ({ seoTrackingApi: { getFindings: vi.fn(), getFindingById: vi.fn(), updateCeoFeedback: vi.fn() } }));
const finding = { id: 'f1', title: 'موضوع آزمایشی', hypothesis: 'فرضیه', primaryKeyword: 'کلید', targetKeywords: ['کلید', 'دوم'], expectedOutcome: 'هدف', status: 'ACTIONED', version: 0, createdAt: '2026-10-01T00:00:00Z', updatedAt: '2026-10-02T00:00:00Z', snapshots: [{ id: 's1', snapshotDate: '2026-10-03T00:00:00Z', sourceMetadata: { gsc: { status: 'available', source: 'Search Console', fetchedAt: '2026-10-03T00:00:00Z' }, ga4: { status: 'unavailable', source: 'GA4', fetchedAt: '2026-10-03T00:00:00Z' }, commerce: { status: 'unavailable', source: 'Orders', fetchedAt: '2026-10-03T00:00:00Z' } }, gscImpressions: 0, gscClicks: null, ga4ActiveUsers: null, attributedOrdersCount: null, attributedSalesValue: null }] } as ResearchFinding;
const response = (data = [finding], page = 1, totalPages = 2) => ({ data, meta: { total: 11, page, limit: 10, totalPages, lastPage: totalPages, hasNextPage: page < totalPages, hasPrevPage: page > 1 } });
const list = vi.mocked(seoTrackingApi.getFindings);
const detail = vi.mocked(seoTrackingApi.getFindingById);
const save = vi.mocked(seoTrackingApi.updateCeoFeedback);
async function open() { render(<SeoTrackingPage />); const trigger = await screen.findByRole('button', { name: /مشاهده و پایش/ }); fireEvent.click(trigger); await screen.findByRole('textbox', { name: 'بازخورد مدیرعامل' }); return trigger; }
beforeEach(() => { vi.resetAllMocks(); list.mockResolvedValue(response()); detail.mockResolvedValue(finding); save.mockResolvedValue({ ...finding, ceoFeedback: 'دستور', updatedAt: '2026-10-04T00:00:00Z', snapshots: undefined }); });
afterEach(cleanup);
describe('SEO tracking interactions', () => {
it('renders all history newest first, source periods and legacy provenance without claiming measured zeros', async () => {
detail.mockResolvedValue({ ...finding, snapshots: [
{ ...finding.snapshots![0], id: 'old', snapshotDate: '2026-01-01T00:00:00Z', sourceMetadata: null, actionRecommendation: 'OLD' },
{ ...finding.snapshots![0], id: 'new', snapshotDate: '2026-10-03T00:00:00Z', periodStart: '2026-10-01T00:00:00Z', periodEnd: '2026-10-02T00:00:00Z', actionRecommendation: 'NEW' },
] });
await open(); const articles = within(screen.getByRole('dialog')).getAllByRole('article');
expect(articles).toHaveLength(2); expect(articles[0].textContent).toContain('NEW'); expect(articles[1].textContent).toContain('OLD');
expect(articles[0].textContent).toContain('Search Console'); expect(articles[0].textContent).toContain('available'); expect(articles[0].textContent).toContain('۱۴۰۵/۷/۹');
expect(articles[1].textContent).toContain('منبع تأییدنشده (تاریخی)'); expect(within(articles[1]).queryByText('۰')).toBeNull();
});
it('preserves draft on save failure and sends the new version on subsequent saves, including clear', async () => {
await open(); save.mockRejectedValueOnce(new Error('offline'));
const field = screen.getByLabelText('بازخورد مدیرعامل'); fireEvent.change(field, { target: { value: 'draft' } }); fireEvent.click(screen.getByRole('button', { name: 'ثبت بازخورد' }));
await screen.findByText(/خطا در ثبت بازخورد/); expect((field as HTMLTextAreaElement).value).toBe('draft');
save.mockResolvedValueOnce({ ...finding, ceoFeedback: 'draft', version: 1, snapshots: undefined }); fireEvent.click(screen.getByRole('button', { name: 'ثبت بازخورد' })); await screen.findByText('بازخورد ثبت شد.');
fireEvent.change(field, { target: { value: ' ' } }); fireEvent.click(screen.getByRole('button', { name: 'ثبت بازخورد' }));
await waitFor(() => expect(save).toHaveBeenLastCalledWith('f1', '', 1));
});
it('shows no-snapshot state and initial upstream/access errors distinctly from empty data', async () => {
list.mockRejectedValueOnce({ response: { status: 403 } }); render(<SeoTrackingPage />); await screen.findByText('دسترسی به این بخش مجاز نیست.'); expect(screen.queryByText('موردی یافت نشد.')).toBeNull();
fireEvent.click(screen.getByRole('button', { name: 'تلاش مجدد' })); detail.mockResolvedValue({ ...finding, snapshots: [] }); fireEvent.click(await screen.findByRole('button', { name: /مشاهده و پایش/ })); await screen.findByText('هنوز اولین آمار و داده‌ها برای این موضوع ثبت نشده است.');
});
it('sends server paging, search, filters and sort and resets page', async () => {
render(<SeoTrackingPage />); await screen.findByText(finding.title);
fireEvent.click(screen.getByRole('button', { name: 'صفحه بعد' }));
await waitFor(() => expect(list).toHaveBeenLastCalledWith(expect.objectContaining({ page: 2 }), expect.any(AbortSignal)));
fireEvent.change(screen.getByLabelText('جستجو'), { target: { value: 'سگ' } });
fireEvent.change(screen.getByLabelText('وضعیت'), { target: { value: 'ACTIONED' } });
fireEvent.change(screen.getByLabelText('مرتب‌سازی'), { target: { value: 'title' } });
fireEvent.change(screen.getByLabelText('جهت مرتب‌سازی'), { target: { value: 'asc' } });
await waitFor(() => expect(list).toHaveBeenLastCalledWith(expect.objectContaining({ page: 1, search: 'سگ', status: 'ACTIONED', sortBy: 'title', sortOrder: 'asc' }), expect.any(AbortSignal)));
});
it('distinguishes empty from errors, retaining old rows on failed refresh', async () => {
render(<SeoTrackingPage />); await screen.findByText(finding.title); list.mockRejectedValueOnce(new Error('offline'));
fireEvent.click(screen.getByRole('button', { name: 'به‌روزرسانی' }));
await screen.findByRole('alert'); expect(screen.getByText(finding.title)).toBeDefined(); expect(screen.queryByText('موردی یافت نشد.')).toBeNull();
list.mockResolvedValueOnce(response([], 1, 0)); fireEvent.click(screen.getByRole('button', { name: 'تلاش مجدد' })); await screen.findByText('موردی یافت نشد.');
});
it('renders snapshot history, real zero vs unavailable, saves version and retains history', async () => {
await open(); const dialog = screen.getByRole('dialog');
expect(within(dialog).getByText('تاریخچه آمار و ارقام ثبت‌شده')).toBeDefined(); expect(within(dialog).getAllByText('ناموجود').length).toBeGreaterThan(0); expect(within(dialog).getByText('۰')).toBeDefined();
expect(within(dialog).queryByText(/پایش زنده/)).toBeNull();
fireEvent.change(screen.getByLabelText('بازخورد مدیرعامل'), { target: { value: 'دستور' } }); fireEvent.click(screen.getByRole('button', { name: 'ثبت بازخورد' }));
await waitFor(() => expect(save).toHaveBeenCalledWith('f1', 'دستور', finding.version)); await screen.findByText('بازخورد ثبت شد.'); expect(screen.getByText('۰')).toBeDefined();
});
it('handles conflict without discarding draft, and explicitly reloads latest', async () => {
save.mockRejectedValue({ response: { status: 409 } }); await open();
fireEvent.change(screen.getByLabelText('بازخورد مدیرعامل'), { target: { value: 'پیش‌نویس' } }); fireEvent.click(screen.getByRole('button', { name: 'ثبت بازخورد' }));
await screen.findByText(/رکورد تغییر کرده/); expect((screen.getByLabelText('بازخورد مدیرعامل') as HTMLTextAreaElement).value).toBe('پیش‌نویس');
expect(screen.getByRole('button', { name: 'ثبت بازخورد' }).hasAttribute('disabled')).toBe(true);
detail.mockResolvedValue({ ...finding, ceoFeedback: 'جدید' }); fireEvent.click(screen.getByRole('button', { name: 'دریافت نسخه جدید' })); await waitFor(() => expect((screen.getByLabelText('بازخورد مدیرعامل') as HTMLTextAreaElement).value).toBe('جدید'));
});
it('focuses modal, traps tabs, Escape closes and restores trigger focus', async () => {
const trigger = await open(); const dialog = screen.getByRole('dialog'); const close = within(dialog).getByRole('button', { name: 'بستن' });
expect(dialog.getAttribute('aria-modal')).toBe('true'); expect(document.activeElement).toBe(close);
close.focus(); fireEvent.keyDown(dialog, { key: 'Tab', shiftKey: true }); expect(document.activeElement).toBe(screen.getByRole('button', { name: 'ثبت بازخورد' }));
fireEvent.keyDown(dialog, { key: 'Escape' }); expect(screen.queryByRole('dialog')).toBeNull(); expect(document.activeElement).toBe(trigger);
});
it('shows loading detail immediately and distinct not-found/access errors with retry', async () => {
detail.mockRejectedValueOnce({ response: { status: 404 } }); render(<SeoTrackingPage />); fireEvent.click(await screen.findByRole('button', { name: /مشاهده و پایش/ })); await screen.findByText('یافته پیدا نشد.');
fireEvent.click(screen.getByRole('button', { name: 'تلاش مجدد جزئیات' })); await screen.findByLabelText('بازخورد مدیرعامل');
});
it('cancels requests and ignores stale list/detail completions', async () => {
let resolveOld!: (value: ReturnType<typeof response>) => void;
list.mockImplementationOnce(() => new Promise(resolve => { resolveOld = resolve; })); render(<SeoTrackingPage />);
fireEvent.change(screen.getByLabelText('جستجو'), { target: { value: 'new' } }); await screen.findByText(finding.title);
expect(list.mock.calls[0][1]?.aborted).toBe(true); resolveOld(response([{ ...finding, title: 'stale' }])); await new Promise(resolve => setTimeout(resolve, 0)); expect(screen.queryByText('stale')).toBeNull();
let finish!: (value: ResearchFinding) => void; detail.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
fireEvent.click(screen.getByRole('button', { name: /مشاهده و پایش/ })); expect(screen.getByRole('dialog')).toBeDefined(); fireEvent.click(screen.getByRole('button', { name: 'بستن' })); finish(finding);
await new Promise(resolve => setTimeout(resolve, 0)); expect(screen.queryByRole('dialog')).toBeNull(); expect(detail.mock.calls[0][1]?.aborted).toBe(true);
});
});
@@ -1,823 +0,0 @@
import { useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import {
TrendingUp,
Search,
RefreshCw,
Eye,
Calendar,
AlertCircle,
FileText,
X,
Tag,
CheckCircle2,
Clock,
Sparkles,
ExternalLink,
MessageSquare,
ShieldAlert,
ChevronLeft,
ChevronRight,
BarChart2,
Target
} from 'lucide-react';
import { seoTrackingApi, type ResearchFinding, type PerformanceSnapshot } from '../services/seoTrackingApi';
const statuses: Record<string, { label: string; bg: string; text: string; border: string }> = {
RESEARCHED: { label: 'تحقیق‌شده', bg: 'bg-sky-50', text: 'text-sky-700', border: 'border-sky-200' },
ACTIONED: { label: 'اقدام‌شده', bg: 'bg-emerald-50', text: 'text-emerald-700', border: 'border-emerald-200' },
EVALUATING: { label: 'در حال پایش', bg: 'bg-amber-50', text: 'text-amber-700', border: 'border-amber-200' },
SCALED: { label: 'توسعه‌یافته', bg: 'bg-purple-50', text: 'text-purple-700', border: 'border-purple-200' },
PRUNED: { label: 'بازنگری / حذف', bg: 'bg-rose-50', text: 'text-rose-700', border: 'border-rose-200' },
};
const date = (value?: string | null) =>
value && Number.isFinite(Date.parse(value))
? new Date(value).toLocaleString('fa-IR', { timeZone: 'Asia/Tehran' })
: 'نامشخص';
const metric = (value: unknown) =>
value !== null && value !== undefined && value !== '' && Number.isFinite(Number(value))
? Number(value).toLocaleString('fa-IR')
: 'ناموجود';
function failure(error: unknown, fallback: string) {
const status = (error as { response?: { status?: number } })?.response?.status;
return status === 404
? 'یافته پیدا نشد.'
: status === 403
? 'دسترسی به این بخش مجاز نیست.'
: status === 401
? 'نشست منقضی شده؛ دوباره وارد شوید.'
: fallback;
}
const fields: [keyof PerformanceSnapshot, string][] = [
['gscImpressions', 'ایمپرشن GSC'],
['gscClicks', 'کلیک GSC'],
['gscPosition', 'رتبه GSC'],
['ga4ActiveUsers', 'کاربران فعال GA4'],
['ga4AvgEngagementSec', 'تعامل GA4 (ثانیه)'],
['ga4BounceRate', 'نرخ پرش GA4'],
['ga4ScrollDepthRate', 'نرخ اسکرول GA4'],
['attributedOrdersCount', 'سفارش‌های منتسب'],
['attributedSalesValue', 'ارزش فروش منتسب'],
];
export default function SeoTrackingPage() {
const [findings, setFindings] = useState<ResearchFinding[]>([]);
const [page, setPage] = useState(1);
const [meta, setMeta] = useState({ total: 0, totalPages: 0, hasNextPage: false, hasPrevPage: false });
const [search, setSearch] = useState('');
const [status, setStatus] = useState('');
const [sortBy, setSortBy] = useState('createdAt');
const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc');
const [reload, setReload] = useState(0);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
const [detailId, setDetailId] = useState<string | null>(null);
const [selected, setSelected] = useState<ResearchFinding | null>(null);
const [detailLoading, setDetailLoading] = useState(false);
const [detailError, setDetailError] = useState('');
const [detailReload, setDetailReload] = useState(0);
const [feedback, setFeedback] = useState('');
const [saving, setSaving] = useState(false);
const [conflict, setConflict] = useState(false);
const [feedbackMessage, setFeedbackMessage] = useState('');
const pageContent = useRef<HTMLDivElement>(null);
const modal = useRef<HTMLDivElement>(null);
const closeButton = useRef<HTMLButtonElement>(null);
const opener = useRef<HTMLElement | null>(null);
const detailGeneration = useRef(0);
useEffect(() => {
const controller = new AbortController();
setLoading(true);
setError('');
seoTrackingApi
.getFindings(
{ page, limit: 10, search: search.trim() || undefined, status: status || undefined, sortBy, sortOrder },
controller.signal
)
.then((result) => {
if (!controller.signal.aborted) {
setFindings(result.data);
setMeta(result.meta);
}
})
.catch((err) => {
if (!controller.signal.aborted) {
setError(failure(err, 'خطا در بارگذاری داده‌ها؛ داده‌های قبلی ممکن است قدیمی باشند.'));
}
})
.finally(() => {
if (!controller.signal.aborted) setLoading(false);
});
return () => controller.abort();
}, [page, search, status, sortBy, sortOrder, reload]);
useEffect(() => {
if (!detailId) return;
const controller = new AbortController();
const generation = ++detailGeneration.current;
setDetailLoading(true);
setDetailError('');
setFeedbackMessage('');
seoTrackingApi
.getFindingById(detailId, controller.signal)
.then((data) => {
if (!controller.signal.aborted && generation === detailGeneration.current) {
setSelected(data);
setFeedback(data.ceoFeedback ?? '');
setConflict(false);
}
})
.catch((err) => {
if (!controller.signal.aborted) setDetailError(failure(err, 'خطا در دریافت جزئیات.'));
})
.finally(() => {
if (!controller.signal.aborted) setDetailLoading(false);
});
return () => controller.abort();
}, [detailId, detailReload]);
useEffect(() => {
if (!detailId) return;
const previousOverflow = document.body.style.overflow;
const content = pageContent.current;
if (content) content.inert = true;
document.body.style.overflow = 'hidden';
closeButton.current?.focus();
return () => {
if (content) content.inert = false;
document.body.style.overflow = previousOverflow;
opener.current?.focus();
};
}, [detailId]);
const close = () => {
detailGeneration.current++;
setDetailId(null);
setSelected(null);
setSaving(false);
};
const save = async () => {
if (!selected || saving || conflict) return;
const generation = detailGeneration.current;
setSaving(true);
setFeedbackMessage('');
try {
const updated = await seoTrackingApi.updateCeoFeedback(selected.id, feedback.trim(), selected.version);
if (generation !== detailGeneration.current) return;
setSelected((current) =>
current ? { ...current, ...updated, snapshots: updated.snapshots ?? current.snapshots } : current
);
setFeedback(updated.ceoFeedback ?? '');
setFeedbackMessage('بازخورد ثبت شد.');
setReload((value) => value + 1);
} catch (err) {
if (generation !== detailGeneration.current) return;
if ((err as { response?: { status?: number } })?.response?.status === 409) {
setConflict(true);
setFeedbackMessage(
'رکورد تغییر کرده؛ پیش از ذخیره، نسخه جدید را دریافت کنید. پیش‌نویس شما حفظ شده است.'
);
} else {
setFeedbackMessage(failure(err, 'خطا در ثبت بازخورد؛ پیش‌نویس حفظ شد.'));
}
} finally {
if (generation === detailGeneration.current) setSaving(false);
}
};
const snapshots = [...(selected?.snapshots ?? [])].sort(
(a, b) => Date.parse(b.snapshotDate) - Date.parse(a.snapshotDate)
);
const inputClass =
'w-full text-sm border border-slate-300 rounded-xl px-3 py-2 bg-white text-slate-800 placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-amber-500/20 focus:border-amber-500 transition-all';
return (
<div ref={pageContent} className="p-4 sm:p-6 lg:p-8 space-y-6 max-w-7xl mx-auto" dir="rtl">
{/* هدر صفحه */}
<header className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 pb-2 border-b border-slate-200">
<div>
<div className="flex items-center gap-2.5">
<div className="w-10 h-10 rounded-xl bg-amber-50 border border-amber-200/60 flex items-center justify-center text-amber-600 shadow-sm">
<TrendingUp className="w-5 h-5" />
</div>
<div>
<h1 className="text-xl sm:text-2xl font-black text-slate-900 tracking-tight">
پایش عملکرد سئو و بازخورد مدیرعامل
</h1>
<p className="text-xs sm:text-sm text-slate-500 mt-0.5">
نمایش آمار و ارقام ثبت‌شده؛ این صفحه اتصال زنده یا اجرای خودکار دستور را تأیید نمی‌کند.
</p>
</div>
</div>
</div>
<button
className="inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-semibold text-slate-700 bg-white hover:bg-slate-50 border border-slate-200 shadow-sm active:scale-[0.98] transition-all cursor-pointer"
onClick={() => setReload((n) => n + 1)}
>
<RefreshCw className={`w-4 h-4 text-slate-500 ${loading ? 'animate-spin' : ''}`} />
<span>به‌روزرسانی</span>
</button>
</header>
{/* فیلترها و جستجو */}
<div className="bg-white rounded-2xl p-4 sm:p-5 border border-slate-200/80 shadow-sm">
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3.5">
<div>
<label className="block text-xs font-semibold text-slate-600 mb-1.5">
جستجو
<div className="relative mt-1">
<input
className={`${inputClass} pl-9`}
placeholder="عنوان، فرضیه یا کلمه کلیدی..."
value={search}
onChange={(e) => {
setSearch(e.target.value);
setPage(1);
}}
/>
<Search className="w-4 h-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2 pointer-events-none" />
</div>
</label>
</div>
<div>
<label className="block text-xs font-semibold text-slate-600 mb-1.5">
وضعیت
<select
className={`${inputClass} mt-1`}
value={status}
onChange={(e) => {
setStatus(e.target.value);
setPage(1);
}}
>
<option value="">همه وضعیت‌ها</option>
{Object.entries(statuses).map(([key, item]) => (
<option key={key} value={key}>
{item.label}
</option>
))}
</select>
</label>
</div>
<div>
<label className="block text-xs font-semibold text-slate-600 mb-1.5">
مرتب‌سازی
<select
className={`${inputClass} mt-1`}
value={sortBy}
onChange={(e) => {
setSortBy(e.target.value);
setPage(1);
}}
>
<option value="createdAt">تاریخ ایجاد</option>
<option value="updatedAt">آخرین تغییر</option>
<option value="title">عنوان</option>
<option value="status">وضعیت</option>
</select>
</label>
</div>
<div>
<label className="block text-xs font-semibold text-slate-600 mb-1.5">
جهت مرتب‌سازی
<select
className={`${inputClass} mt-1`}
value={sortOrder}
onChange={(e) => {
setSortOrder(e.target.value as 'asc' | 'desc');
setPage(1);
}}
>
<option value="desc">نزولی (جدیدترین)</option>
<option value="asc">صعودی (قدیمی‌ترین)</option>
</select>
</label>
</div>
</div>
</div>
{/* وضعیت‌های خطا و لودینگ */}
{error && (
<div
role="alert"
className="flex items-center justify-between gap-3 p-4 rounded-xl bg-rose-50 border border-rose-200 text-rose-800 text-sm font-medium"
>
<div className="flex items-center gap-2.5">
<AlertCircle className="w-5 h-5 text-rose-600 shrink-0" />
<span>{error}</span>
</div>
<button
className="px-3 py-1.5 rounded-lg bg-white border border-rose-200 text-rose-700 text-xs font-semibold hover:bg-rose-100 transition-colors shrink-0"
onClick={() => setReload((n) => n + 1)}
>
تلاش مجدد
</button>
</div>
)}
{loading && (
<div role="status" className="flex items-center justify-center p-8 text-slate-500 text-sm gap-2">
<RefreshCw className="w-5 h-5 animate-spin text-amber-500" />
<span>در حال دریافت داده‌ها...</span>
</div>
)}
{/* لیست یافته‌ها (سازگار با موبایل و دسکتاپ) */}
<div className="bg-white rounded-2xl border border-slate-200/90 shadow-sm overflow-hidden">
<table className="w-full text-right" aria-busy={loading}>
<caption className="sr-only">یافته‌های پژوهش سئو</caption>
<thead className="hidden md:table-header-group bg-slate-50/80 border-b border-slate-200 text-slate-700 text-xs font-bold uppercase tracking-wider">
<tr>
{['موضوع و فرضیه', 'کلیدواژه‌ها', 'وضعیت', 'مقاله مرتبط', 'دستور مدیرعامل', 'تاریخ ایجاد', 'عملیات'].map(
(text) => (
<th scope="col" key={text} className="p-3.5 first:pr-5 last:pl-5">
{text}
</th>
)
)}
</tr>
</thead>
<tbody className="divide-y divide-slate-100 block md:table-row-group">
{!loading && !error && findings.length === 0 && (
<tr className="block md:table-row">
<td colSpan={7} className="p-12 text-center text-slate-500 text-sm block md:table-cell">
<div className="max-w-xs mx-auto space-y-2">
<FileText className="w-8 h-8 text-slate-300 mx-auto" />
<p className="font-semibold text-slate-700">موردی یافت نشد.</p>
<p className="text-xs text-slate-400">عبارت جستجو یا فیلترهای بالا را تغییر دهید.</p>
</div>
</td>
</tr>
)}
{findings.map((f) => {
const statusCfg = statuses[f.status] ?? {
label: f.status,
bg: 'bg-slate-100',
text: 'text-slate-700',
border: 'border-slate-200',
};
const otherKeywords = f.targetKeywords?.filter((k) => k !== f.primaryKeyword) ?? [];
return (
<tr
key={f.id}
className="block md:table-row p-4 sm:p-5 md:p-0 border-b md:border-b-0 border-slate-100 hover:bg-slate-50/60 transition-colors"
>
{/* موضوع و فرضیه */}
<td className="block md:table-cell p-0 md:p-3.5 md:pr-5 pb-2 md:pb-3.5 align-top">
<div className="space-y-1">
<div className="flex items-center gap-2 md:hidden mb-2">
<span
className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-semibold border ${statusCfg.bg} ${statusCfg.text} ${statusCfg.border}`}
>
{statusCfg.label}
</span>
{f.ceoFeedback ? (
<span className="inline-flex items-center gap-1 text-[11px] font-semibold text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded-full border border-emerald-200">
<CheckCircle2 className="w-3 h-3" />
دستور ثبت‌شده
</span>
) : (
<span className="inline-flex items-center text-[11px] text-slate-500 bg-slate-50 px-2 py-0.5 rounded-full border border-slate-200">
ثبت‌نشده
</span>
)}
</div>
<strong className="block text-sm sm:text-base font-bold text-slate-900 leading-snug">
{f.title}
</strong>
<p className="text-xs sm:text-sm text-slate-600 line-clamp-2 md:line-clamp-none bg-slate-50/80 md:bg-transparent p-2 md:p-0 rounded-lg md:rounded-none border md:border-0 border-slate-100">
{f.hypothesis}
</p>
</div>
</td>
{/* کلیدواژه‌ها */}
<td className="block md:table-cell p-0 md:p-3.5 py-2 md:py-3.5 align-top">
<div className="flex flex-wrap items-center gap-1.5">
<span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-lg text-xs font-bold bg-amber-50 text-amber-800 border border-amber-200">
<Tag className="w-3 h-3 text-amber-600" />
{f.primaryKeyword}
</span>
{otherKeywords.length > 0 && (
<p className="text-xs text-slate-500">
{otherKeywords.join('، ')}
</p>
)}
</div>
</td>
{/* وضعیت (در دسکتاپ) */}
<td className="hidden md:table-cell p-3.5 align-top">
<span
className={`inline-flex items-center px-2.5 py-1 rounded-full text-xs font-semibold border ${statusCfg.bg} ${statusCfg.text} ${statusCfg.border}`}
>
{statusCfg.label}
</span>
</td>
{/* مقاله مرتبط */}
<td className="block md:table-cell p-0 md:p-3.5 py-2 md:py-3.5 align-top text-xs sm:text-sm">
<span className="md:hidden font-semibold text-slate-500 ml-1">مقاله: </span>
{f.blog ? (
<a
className="inline-flex items-center gap-1 text-blue-700 hover:text-blue-800 font-semibold underline underline-offset-2 transition-colors"
href={`https://canina.ir/blog/${encodeURIComponent(f.blog.slug)}`}
target="_blank"
rel="noopener noreferrer"
>
<span>{f.blog.title}</span>
<ExternalLink className="w-3 h-3 shrink-0" />
</a>
) : (
<span className="text-slate-400 font-normal">بدون مقاله</span>
)}
</td>
{/* دستور مدیرعامل (در دسکتاپ) */}
<td className="hidden md:table-cell p-3.5 align-top text-xs sm:text-sm">
{f.ceoFeedback ? (
<span className="inline-flex items-center gap-1 text-xs font-semibold text-emerald-700 bg-emerald-50 px-2.5 py-1 rounded-full border border-emerald-200">
<CheckCircle2 className="w-3.5 h-3.5" />
دستور ثبت‌شده
</span>
) : (
<span className="text-xs text-slate-400 bg-slate-50 px-2.5 py-1 rounded-full border border-slate-200">
ثبت‌نشده
</span>
)}
</td>
{/* تاریخ ایجاد */}
<td className="block md:table-cell p-0 md:p-3.5 py-1 md:py-3.5 align-top text-xs text-slate-500">
<div className="flex items-center gap-1">
<Calendar className="w-3.5 h-3.5 text-slate-400 md:hidden" />
<span>{date(f.createdAt)}</span>
</div>
</td>
{/* دکمه عملیات */}
<td className="block md:table-cell p-0 md:p-3.5 md:pl-5 pt-3 md:pt-3.5 align-top">
<button
className="w-full md:w-auto inline-flex items-center justify-center gap-2 px-3.5 py-2 rounded-xl text-xs sm:text-sm font-semibold text-slate-700 bg-slate-100 hover:bg-slate-200 border border-slate-200 shadow-sm active:scale-[0.98] transition-all cursor-pointer"
onClick={(e) => {
opener.current = e.currentTarget;
setSelected(null);
setDetailError('');
setFeedbackMessage('');
setDetailId(f.id);
}}
>
<Eye className="w-4 h-4 text-slate-600" />
<span>مشاهده و پایش</span>
</button>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
{/* صفحه‌بندی مدرن */}
<nav
aria-label="صفحه‌بندی"
className="flex flex-col sm:flex-row items-center justify-between gap-4 p-4 bg-white rounded-2xl border border-slate-200/90 shadow-sm text-sm text-slate-600"
>
<span className="font-medium text-xs sm:text-sm">تعداد کل: {meta.total} مورد</span>
<div className="flex items-center gap-2">
<button
className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl border border-slate-200 font-semibold text-xs sm:text-sm bg-white hover:bg-slate-50 disabled:opacity-40 disabled:pointer-events-none transition-all cursor-pointer shadow-sm"
aria-label="صفحه قبل"
disabled={loading || !meta.hasPrevPage}
onClick={() => setPage((p) => Math.max(1, p - 1))}
>
<ChevronRight className="w-4 h-4" />
<span>قبلی</span>
</button>
<span className="px-3 py-1 rounded-lg bg-slate-100 font-bold text-xs sm:text-sm text-slate-800">
صفحه {page} از {meta.totalPages || 1}
</span>
<button
className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl border border-slate-200 font-semibold text-xs sm:text-sm bg-white hover:bg-slate-50 disabled:opacity-40 disabled:pointer-events-none transition-all cursor-pointer shadow-sm"
aria-label="صفحه بعد"
disabled={loading || !meta.hasNextPage}
onClick={() => setPage((p) => p + 1)}
>
<span>بعدی</span>
<ChevronLeft className="w-4 h-4" />
</button>
</div>
</nav>
{/* مودال جزئیات و پایش آمار عملکرد‌ها */}
{detailId &&
createPortal(
<div className="fixed inset-0 z-50 bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-3 sm:p-6" dir="rtl">
<div
ref={modal}
role="dialog"
aria-modal="true"
aria-labelledby="seo-detail-title"
aria-describedby="seo-detail-description"
className="bg-white rounded-3xl shadow-2xl w-full max-w-4xl max-h-[92vh] flex flex-col overflow-hidden border border-slate-200"
onKeyDown={(e) => {
if (e.key === 'Escape') {
e.stopPropagation();
close();
}
if (e.key === 'Tab') {
const elements = Array.from(
modal.current?.querySelectorAll<HTMLElement>(
'button, textarea, a[href], select, input'
) ?? []
).filter((element) => !(element as HTMLButtonElement).disabled);
const first = elements[0];
const last = elements[elements.length - 1];
if (e.shiftKey && document.activeElement === first) {
e.preventDefault();
last?.focus();
} else if (!e.shiftKey && document.activeElement === last) {
e.preventDefault();
first?.focus();
}
}
}}
>
{/* هدر مودال */}
<div className="flex items-center justify-between gap-4 px-6 py-4 border-b border-slate-200 bg-slate-50/70">
<div className="flex items-center gap-3">
<div className="w-9 h-9 rounded-xl bg-amber-100 text-amber-700 flex items-center justify-center shadow-xs">
<BarChart2 className="w-5 h-5" />
</div>
<div>
<h2 id="seo-detail-title" className="font-black text-base sm:text-lg text-slate-900">
{selected?.title ?? 'جزئیات یافته'}
</h2>
<p id="seo-detail-description" className="text-xs text-slate-500">
آمار و ارقام از تاریخچه ذخیره‌شده هستند، نه درخواست زنده به منابع.
</p>
</div>
</div>
<button
ref={closeButton}
className="p-2 rounded-xl text-slate-500 hover:text-slate-800 hover:bg-slate-200/80 transition-colors cursor-pointer"
onClick={close}
aria-label="بستن"
>
<X className="w-5 h-5" />
<span className="sr-only">بستن</span>
</button>
</div>
{/* بدنه مودال با اسکرول */}
<div className="p-6 overflow-y-auto space-y-6">
{detailLoading && (
<div role="status" className="flex items-center justify-center p-12 text-slate-500 text-sm gap-2">
<RefreshCw className="w-5 h-5 animate-spin text-amber-500" />
<span>در حال بارگذاری جزئیات...</span>
</div>
)}
{detailError && (
<div
role="alert"
className="p-4 rounded-xl bg-rose-50 border border-rose-200 text-rose-800 text-sm flex items-center justify-between"
>
<span>{detailError}</span>
<button
className="px-3 py-1.5 rounded-lg bg-white border border-rose-200 text-rose-700 text-xs font-semibold hover:bg-rose-100"
onClick={() => setDetailReload((n) => n + 1)}
>
تلاش مجدد جزئیات
</button>
</div>
)}
{selected && !detailLoading && !detailError && (
<>
{/* کارت فرضیه و هدف کلیدی */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="bg-sky-50/60 rounded-2xl p-4 border border-sky-100">
<div className="flex items-center gap-2 text-sky-800 font-bold text-xs mb-1.5">
<Sparkles className="w-4 h-4 text-sky-600" />
<span>فرضیه تحقیق</span>
</div>
<p className="text-xs sm:text-sm text-slate-700 leading-relaxed">
فرضیه: {selected.hypothesis}
</p>
</div>
<div className="bg-emerald-50/60 rounded-2xl p-4 border border-emerald-100">
<div className="flex items-center gap-2 text-emerald-800 font-bold text-xs mb-1.5">
<Target className="w-4 h-4 text-emerald-600" />
<span>هدف و دستاورد مورد انتظار</span>
</div>
<p className="text-xs sm:text-sm text-slate-700 leading-relaxed">
نتیجه مورد انتظار: {selected.expectedOutcome}
</p>
</div>
</div>
{/* تاریخچه آمار و ارقام */}
<section aria-label="تاریخچه آمار و ارقام" className="space-y-4">
<div className="flex items-center justify-between pb-2 border-b border-slate-100">
<div>
<h3 className="font-bold text-sm sm:text-base text-slate-900 flex items-center gap-2">
<Clock className="w-4 h-4 text-slate-500" />
<span>تاریخچه آمار و ارقام ثبت‌شده</span>
</h3>
<p className="text-xs text-slate-500 mt-0.5">
حداکثر ۳۰ پایش اخیر، به ترتیب جدیدترین تاریخ ثبت آمار.
</p>
</div>
</div>
<p className="text-xs text-slate-500 bg-slate-50 p-3 rounded-xl border border-slate-100">
منابع: GSC / GA4 / Commerce. نبود داده با صفر تفاوت دارد. بازه، زمان گردآوری و واحد فروش فقط در صورت گزارش منبع معتبر است.
</p>
{!snapshots.length && (
<div className="p-8 text-center bg-slate-50 rounded-2xl border border-slate-100">
<p className="text-sm font-semibold text-slate-600">
هنوز اولین آمار و داده‌ها برای این موضوع ثبت نشده است.
</p>
<p className="text-xs text-slate-400 mt-1">
ورکر پایش دوره‌ای پس از انتشار مقاله و گذر زمان مورد نیاز داده‌های عملکرد را ثبت خواهد کرد.
</p>
</div>
)}
{snapshots.map((snapshot) => (
<article
key={snapshot.id}
className="bg-white rounded-2xl p-5 border border-slate-200/90 shadow-xs space-y-4"
>
{/* هدر کارت پایش */}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 pb-3 border-b border-slate-100">
<h4 className="font-bold text-sm text-slate-800 flex items-center gap-1.5">
<Calendar className="w-4 h-4 text-amber-500" />
<span>تاریخ ثبت آمار: {date(snapshot.snapshotDate)}</span>
</h4>
<div className="text-xs text-slate-500">
<span>بازه: {date(snapshot.periodStart)} تا {date(snapshot.periodEnd)}</span>
</div>
</div>
<div className="text-[11px] text-slate-400 flex flex-wrap gap-x-4 gap-y-1">
<span>زمان گردآوری: {date(snapshot.collectedAt)} — زمان ثبت: {date(snapshot.createdAt)}</span>
</div>
{/* وضعیت منابع */}
<ul className="flex flex-wrap gap-2 text-xs">
{(['gsc', 'ga4', 'commerce'] as const).map((source) => {
const provenance = snapshot.sourceMetadata?.[source];
const isAvailable = provenance?.status === 'available';
return (
<li
key={source}
className={`px-3 py-1 rounded-lg border text-xs font-medium ${
isAvailable
? 'bg-emerald-50 text-emerald-800 border-emerald-200'
: 'bg-slate-50 text-slate-600 border-slate-200'
}`}
>
{source.toUpperCase()}:{' '}
{provenance
? `${provenance.source} — ${provenance.status} — دریافت: ${date(provenance.fetchedAt)}`
: 'منبع تأییدنشده (تاریخی)'}
{provenance?.error && ` — ${provenance.error}`}
</li>
);
})}
</ul>
{/* جدول ماتریسی مقادیر آمار عملکرد‌ها */}
<dl className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-3 gap-3">
{fields.map(([key, label]) => {
const sourceKey = key.startsWith('gsc')
? 'gsc'
: key.startsWith('ga4')
? 'ga4'
: 'commerce';
const isAvail = snapshot.sourceMetadata?.[sourceKey]?.status === 'available';
return (
<div
key={key}
className="bg-slate-50/70 p-3 rounded-xl border border-slate-100 flex flex-col justify-between"
>
<dt className="text-xs text-slate-500 font-medium mb-1">{label}</dt>
<dd className="font-black text-base sm:text-lg text-slate-900 tracking-tight">
{isAvail ? metric(snapshot[key]) : 'ناموجود'}
</dd>
</div>
);
})}
</dl>
{/* توصیه پیشنهادی هوشمند */}
<div className="bg-amber-50/70 border border-amber-200/80 p-3.5 rounded-xl space-y-1">
<div className="flex items-center gap-1.5 text-xs font-bold text-amber-900">
<Sparkles className="w-3.5 h-3.5 text-amber-600" />
<span>پیشنهاد سیستم:</span>
</div>
<p className="text-xs sm:text-sm text-amber-950 font-medium">
پیشنهاد ثبت‌شده: {snapshot.actionRecommendation || 'ناموجود'}
</p>
</div>
{snapshot.analysisNotes && (
<p className="text-xs text-slate-600 bg-slate-50 p-3 rounded-xl border border-slate-100">
{snapshot.analysisNotes}
</p>
)}
</article>
))}
</section>
{/* ثبت بازخورد و دستور مدیرعامل */}
<section className="bg-slate-50 rounded-2xl p-5 border border-slate-200 space-y-4">
<div className="flex items-center gap-2">
<MessageSquare className="w-5 h-5 text-amber-600" />
<div>
<h3 className="font-bold text-sm sm:text-base text-slate-900">
دستور و بازخورد مدیرعامل
</h3>
<p className="text-xs text-slate-500 mt-0.5">
ثبت نظر اختیاری است؛ نظر ثبت‌شده باید در اقدامات بعدی رعایت شود. ذخیره در این صفحه به‌تنهایی اثبات اجرای آن در فرایندهای پایین‌دستی نیست.
</p>
</div>
</div>
<div>
<label className="block text-xs font-bold text-slate-700 mb-1.5">
بازخورد مدیرعامل
<textarea
rows={4}
maxLength={10000}
className="mt-1 w-full text-sm border border-slate-300 rounded-xl p-3 bg-white text-slate-800 placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-amber-500/20 focus:border-amber-500 transition-all"
placeholder="دستورات استراتژیک، تعیین اولویت یا اصلاحیه برای این موضوع..."
value={feedback}
disabled={saving}
onChange={(e) => setFeedback(e.target.value)}
/>
</label>
<p className="text-xs text-slate-400 mt-1">آخرین ثبت: {date(selected.feedbackSubmittedAt)}</p>
</div>
<div className="flex flex-wrap items-center gap-3 pt-2">
<button
className="px-5 py-2.5 rounded-xl font-bold text-sm bg-amber-500 hover:bg-amber-600 text-slate-950 shadow-sm active:scale-[0.98] transition-all cursor-pointer disabled:opacity-50 disabled:pointer-events-none"
disabled={saving || conflict}
onClick={save}
>
{saving ? 'در حال ثبت...' : 'ثبت بازخورد'}
</button>
{conflict && (
<button
className="px-4 py-2.5 rounded-xl font-semibold text-sm bg-rose-100 hover:bg-rose-200 text-rose-800 border border-rose-200 transition-all cursor-pointer"
onClick={() => setDetailReload((n) => n + 1)}
>
دریافت نسخه جدید
</button>
)}
{feedbackMessage && (
<p
role="status"
className={`text-xs font-semibold px-3 py-1.5 rounded-lg ${
conflict
? 'bg-rose-50 text-rose-700 border border-rose-200'
: 'bg-emerald-50 text-emerald-700 border border-emerald-200'
}`}
>
{feedbackMessage}
</p>
)}
</div>
</section>
</>
)}
</div>
</div>
</div>,
document.body
)}
</div>
);
}
@@ -20,10 +20,6 @@ const Categories = lazyWithRetry(() => import('../pages/Categories'));
const SymptomsPage = lazyWithRetry(() => import('../pages/SymptomsPage'));
const Blogs = lazyWithRetry(() => import('../pages/Blogs'));
const SeoTrackingPage = lazyWithRetry(() => import('../pages/SeoTrackingPage'));
const CorporateTasksPage = lazyWithRetry(() => import('../pages/CorporateTasksPage'));
const MarketIntelligencePage = lazyWithRetry(() => import('../pages/MarketIntelligencePage'));
const MonthlyRoadmapPage = lazyWithRetry(() => import('../pages/MonthlyRoadmapPage'));
const Wiki = lazyWithRetry(() => import('../pages/Wiki'));
const Pets = lazyWithRetry(() => import('../pages/Pets'));
const UITexts = lazyWithRetry(() => import('../pages/UITexts'));
@@ -99,11 +95,6 @@ export const router = createBrowserRouter([
{ path: 'symptoms/*', element: <SymptomsPage /> },
{ path: 'blogs/*', element: <Blogs /> },
{ path: 'hermes/tasks', element: <CorporateTasksPage /> },
{ path: 'hermes/seo-tracking', element: <SeoTrackingPage /> },
{ path: 'hermes/market-intelligence', element: <MarketIntelligencePage /> },
{ path: 'hermes/monthly-roadmap', element: <MonthlyRoadmapPage /> },
{ path: 'seo-tracking', element: <Navigate to="/hermes/seo-tracking" replace /> },
{ path: 'wiki/*', element: <Wiki /> },
{ path: 'videos/*', element: <Videos /> },
{ path: 'doctors/*', element: <DoctorsManager /> },
@@ -1,38 +0,0 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import api from './api';
import { hermesApi } from './hermesApi';
vi.mock('./api', () => ({ default: { get: vi.fn(), post: vi.fn() } }));
beforeEach(() => vi.resetAllMocks());
describe('Hermes API honesty', () => {
it('preserves pagination in market envelopes', async () => {
const result = { data: [], meta: { total: 20, page: 2, limit: 10, totalPages: 2, hasNextPage: false, hasPrevPage: true } };
vi.mocked(api.get).mockResolvedValue({ data: result });
expect(await hermesApi.getMarketInsights({ page: 2, limit: 10 })).toEqual(result);
});
it('rejects malformed successful create responses', async () => {
vi.mocked(api.post).mockResolvedValue({ data: { success: false } });
await expect(hermesApi.createCeoTask({title:'test',description:'test',department:'CONTENT_SEO'})).rejects.toThrow();
});
it.each(['getTasks', 'getTaskById', 'getMarketInsights', 'getMonthlyRoadmap'] as const)('%s rejects unavailable service', async (method) => {
vi.mocked(api.get).mockRejectedValue(new Error('unavailable'));
const result = method === 'getTaskById' ? hermesApi.getTaskById('real-id') : hermesApi[method]();
await expect(result).rejects.toThrow('unavailable');
});
it('supports service-unwrapped nested list envelopes', async () => {
const result = {data:[],meta:{total:0,page:1,limit:10,totalPages:0,hasNextPage:false,hasPrevPage:false}};
vi.mocked(api.get).mockResolvedValue({data:{data:result}});
expect(await hermesApi.getMonthlyRoadmap()).toEqual(result);
});
it('rejects malformed lists rather than rendering measured zero', async () => {
vi.mocked(api.get).mockResolvedValue({data:{data:[]}});
await expect(hermesApi.getTasks()).rejects.toThrow('پاسخ صفحه');
});
it('never fabricates successful creation', async () => {
vi.mocked(api.post).mockRejectedValue(new Error('not saved'));
await expect(hermesApi.createCeoTask({ title: 'directive', description: 'acceptance', department: 'CONTENT_SEO' })).rejects.toThrow('not saved');
});
it('unwraps task details without requiring a success property', async () => {
vi.mocked(api.get).mockResolvedValue({ data: { data: { id: 'real-id' } } });
expect(await hermesApi.getTaskById('real-id')).toEqual({ id: 'real-id' });
});
});
@@ -1,131 +0,0 @@
import api from './api';
export type TaskDepartment =
| 'CONTENT_SEO'
| 'CATALOG_COMMERCE'
| 'WIKI_SCIENTIFIC'
| 'TECH_DEVOPS'
| 'MARKET_INTELLIGENCE';
export type TaskPriority = 'CEO_EXPEDITE' | 'CRITICAL' | 'HIGH' | 'MEDIUM' | 'LOW';
export type TaskStatus = 'TODO' | 'IN_PROGRESS' | 'DONE' | 'BLOCKED' | 'CANCELLED';
export interface TaskLogItem {
id: string;
speaker: 'PMO' | 'AGENT' | 'QA' | 'CEO' | 'SYSTEM';
speakerName?: string;
step?: string;
content: string;
payload?: Record<string, unknown> | null;
timestamp: string;
}
export interface CorporateTaskItem {
id: string;
taskCode: string;
title: string;
department: TaskDepartment;
priority: TaskPriority;
status: TaskStatus;
actionType: string;
description: string;
targetPillar?: string;
dueCycle?: string;
assignedAgent?: string;
deliverableUrl?: string;
deliverableData?: Record<string, unknown> | null;
ceoNotes?: string;
createdAt: string;
updatedAt: string;
logs?: TaskLogItem[];
}
export interface TaskFilterParams {
page?: number;
limit?: number;
search?: string;
department?: string;
status?: string;
priority?: string;
sortBy?: string;
sortOrder?: 'asc' | 'desc';
}
export interface TasksResponse {
data: CorporateTaskItem[];
meta: {
total: number;
page: number;
limit: number;
totalPages: number;
hasNextPage: boolean;
hasPrevPage: boolean;
};
}
export interface MarketInsightItem {
id: string;
title: string;
category: 'TREND' | 'COMPETITOR' | 'NEW_CHANNEL' | 'CATALOG_GAP';
source: string;
opportunity: string;
impact: 'HIGH' | 'MEDIUM' | 'LOW';
recommendedAction: string;
status: 'DISCOVERED' | 'IN_BACKLOG' | 'ACTIONED' | 'DISMISSED';
createdAt: string;
}
export interface MonthlyRoadmapItem {
id: string;
cycleName: string;
month: string;
seasonalTheme: string;
strategicGoals: string[];
plannedArticlesCount: number;
plannedRefreshesCount: number;
plannedCatalogEnrichments: number;
isActive: boolean;
createdAt: string;
}
export type PageMeta = TasksResponse['meta'];
export interface PaginatedResponse<T> { data: T[]; meta: PageMeta }
export interface ListParams { page?: number; limit?: number; category?: string }
function pageResult<T>(body: unknown): PaginatedResponse<T> {
const outer = body as { data?: unknown; meta?: unknown } | null;
const result = (outer?.meta ? outer : outer?.data) as PaginatedResponse<T> | undefined;
if (!Array.isArray(result?.data) || !result?.meta ||
!Number.isFinite(result.meta.total) || !Number.isFinite(result.meta.page) ||
!Number.isFinite(result.meta.totalPages) || !Number.isFinite(result.meta.limit) ||
typeof result.meta.hasNextPage !== 'boolean' || typeof result.meta.hasPrevPage !== 'boolean') {
throw new Error('پاسخ صفحه‌بندی سرور معتبر نیست.');
}
return result;
}
export const hermesApi = {
getTasks: async (params: TaskFilterParams = {}, signal?: AbortSignal): Promise<TasksResponse> => {
const response = await api.get('/admin/hermes/tasks', { params, signal });
return pageResult<CorporateTaskItem>(response.data);
},
getTaskById: async (id: string, signal?: AbortSignal): Promise<CorporateTaskItem> => {
const response = await api.get(`/admin/hermes/tasks/${encodeURIComponent(id)}`, { signal });
return response.data?.data ?? response.data;
},
createCeoTask: async (data: { title: string; department: TaskDepartment; description: string; priority?: TaskPriority }): Promise<CorporateTaskItem> => {
const response = await api.post('/admin/hermes/tasks', { ...data, priority: data.priority ?? 'CEO_EXPEDITE' });
const item = response.data?.data ?? response.data;
if (!item?.id || !item?.taskCode) throw new Error('پاسخ ثبت تسک معتبر نیست؛ ثبت تأیید نشد.');
return item;
},
getMarketInsights: async (params: ListParams = {}, signal?: AbortSignal): Promise<PaginatedResponse<MarketInsightItem>> => {
const response = await api.get('/admin/hermes/market-insights', { params, signal });
return pageResult<MarketInsightItem>(response.data);
},
getMonthlyRoadmap: async (params: ListParams = {}, signal?: AbortSignal): Promise<PaginatedResponse<MonthlyRoadmapItem>> => {
const response = await api.get('/admin/hermes/monthly-roadmap', { params, signal });
return pageResult<MonthlyRoadmapItem>(response.data);
},
};
@@ -1,106 +0,0 @@
import axios, { AxiosError, CanceledError } from 'axios';
import type { AxiosAdapter, InternalAxiosRequestConfig } from 'axios';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import api from './api';
import { useAdminAuthStore } from '../store/adminAuthStore';
import { seoTrackingApi } from './seoTrackingApi';
vi.mock('react-hot-toast', () => ({ default: { error: vi.fn() } }));
// Exercise the real Axios instance and its request/response interceptors.
// main.ts registers DecimalInterceptor (recursive decimals, no success envelope).
const finding = {
id: 'finding-1', title: 'Research', hypothesis: 'Hypothesis',
targetKeywords: ['keyword'], primaryKeyword: 'keyword', expectedOutcome: 'Outcome',
status: 'RESEARCHED', createdAt: '2026-10-01T00:00:00.000Z',
updatedAt: '2026-10-02T00:00:00.000Z', version: 0, snapshots: [],
};
const meta = { total: 1, page: 1, limit: 10, totalPages: 1, lastPage: 1, hasNextPage: false, hasPrevPage: false };
const originalAdapter = api.defaults.adapter;
function respond(data: unknown, inspect?: (config: InternalAxiosRequestConfig) => void) {
api.defaults.adapter = (async (config) => {
inspect?.(config);
return { data, status: 200, statusText: 'OK', headers: {}, config };
}) satisfies AxiosAdapter;
}
beforeEach(() => { useAdminAuthStore.setState({ accessToken: 'test-access-token' }); });
afterEach(() => { api.defaults.adapter = originalAdapter; useAdminAuthStore.getState().clearAuth(); vi.clearAllMocks(); });
describe('seoTrackingApi wire contract', () => {
it('preserves the raw paginated controller payload and uses bearer authentication', async () => {
const payload = { data: [finding], meta };
const signal = new AbortController().signal;
respond(payload, config => {
expect(config.url).toBe('/admin/seo-tracking');
expect(config.params).toEqual({ page: 2, search: 'cat', status: 'RESEARCHED' });
expect(config.signal).toBe(signal);
expect(config.headers.Authorization).toBe('Bearer test-access-token');
expect(config.withCredentials).toBe(true);
});
expect(await seoTrackingApi.getFindings({ page: 2, search: 'cat', status: 'RESEARCHED' }, signal)).toEqual(payload);
});
it('returns raw details and passes their AbortSignal', async () => {
const signal = new AbortController().signal;
respond(finding, config => { expect(config.signal).toBe(signal); expect(config.url).toBe('/admin/seo-tracking/finding-1'); });
expect(await seoTrackingApi.getFindingById('finding-1', signal)).toEqual(finding);
});
it('sends the exact expectedVersion concurrency token with feedback', async () => {
respond(finding, config => {
expect(config.method).toBe('patch');
expect(config.url).toBe('/admin/seo-tracking/finding-1/feedback');
expect(JSON.parse(config.data)).toEqual({ feedback: 'Reviewed', expectedVersion: finding.version });
});
expect(await seoTrackingApi.updateCeoFeedback('finding-1', 'Reviewed', finding.version)).toEqual(finding);
});
it('preserves snapshot nulls, numeric zeros and source metadata without fabricated metrics', async () => {
const snapshot = { id: 'snapshot-1', findingId: finding.id, snapshotDate: finding.createdAt,
gscClicks: 0, ga4ActiveUsers: null, attributedSalesValue: null,
periodStart: finding.createdAt, periodEnd: finding.updatedAt, collectedAt: finding.updatedAt,
createdAt: finding.updatedAt };
respond(snapshot, config => { expect(config.method).toBe('post'); expect(JSON.parse(config.data)).toEqual({ ga4ActiveUsers: null, gscClicks: 0 }); });
expect(await seoTrackingApi.addSnapshot(finding.id, { ga4ActiveUsers: null, gscClicks: 0 })).toEqual(snapshot);
});
it('preserves a genuinely empty page with server pagination', async () => {
const payload = { data: [], meta: { ...meta, total: 0 } };
respond(payload);
expect(await seoTrackingApi.getFindings()).toEqual(payload);
});
it.each([null, {}, { data: [] }, { data: [finding], meta: { ...meta, total: '1' } }, { data: [{}], meta }, { success: true, data: { data: [finding], meta } }])('rejects malformed or unsupported list shapes: %j', async payload => {
respond(payload);
await expect(seoTrackingApi.getFindings()).rejects.toThrow('Invalid SEO tracking response');
});
it.each([null, {}, { success: true, data: finding }])('rejects malformed or unsupported detail shapes: %j', async payload => {
respond(payload);
await expect(seoTrackingApi.getFindingById(finding.id)).rejects.toThrow('Invalid SEO tracking response');
});
it.each([403, 404, 409, 422, 500])('preserves HTTP %i instead of disguising failures as empty results', async status => {
api.defaults.adapter = async config => {
const response = { data: { message: 'Failure' }, status, statusText: 'Failure', headers: {}, config };
throw new AxiosError('Failure', AxiosError.ERR_BAD_RESPONSE, config, undefined, response);
};
await expect(seoTrackingApi.getFindings()).rejects.toMatchObject({ response: { status } });
});
it.each(['list', 'detail'])('cancels an in-flight %s request using Axios cancellation', async endpoint => {
const controller = new AbortController();
let started!: () => void;
const ready = new Promise<void>(resolve => { started = resolve; });
api.defaults.adapter = config => new Promise((_resolve, reject) => {
config.signal?.addEventListener?.('abort', () => reject(new CanceledError('Canceled')));
started();
});
const request = endpoint === 'list' ? seoTrackingApi.getFindings({}, controller.signal) : seoTrackingApi.getFindingById(finding.id, controller.signal);
const assertion = expect(request).rejects.toSatisfy(axios.isCancel);
await ready;
controller.abort();
await assertion;
});
});
@@ -1,118 +0,0 @@
import api from './api';
export interface ResearchFinding {
id: string;
title: string;
hypothesis: string;
targetKeywords: string[];
primaryKeyword: string;
expectedOutcome: string;
status: 'RESEARCHED' | 'ACTIONED' | 'EVALUATING' | 'SCALED' | 'PRUNED';
blogId?: string | null;
blog?: {
id: string;
title: string;
slug: string;
} | null;
ceoFeedback?: string | null;
feedbackSubmittedAt?: string | null;
snapshots?: PerformanceSnapshot[];
createdAt: string;
updatedAt: string;
version: number;
feedbackVersion?: number;
}
export interface PerformanceSnapshot {
id: string;
findingId: string;
snapshotDate: string;
gscImpressions: number | null;
gscClicks: number | null;
gscPosition: number | null;
ga4ActiveUsers: number | null;
ga4AvgEngagementSec: number | null;
ga4BounceRate: number | null;
ga4ScrollDepthRate: number | null;
attributedOrdersCount: number | null;
attributedSalesValue: number | null;
periodStart?: string | null;
periodEnd?: string | null;
collectedAt?: string | null;
sourceMetadata?: Record<'gsc' | 'ga4' | 'commerce', { status: 'available' | 'unavailable' | 'error'; source: string; fetchedAt: string; error?: string }> | null;
actionRecommendation?: string | null;
analysisNotes?: string | null;
createdAt: string;
}
export interface FindingsResponse {
data: ResearchFinding[];
meta: {
total: number;
page: number;
limit: number;
totalPages: number;
lastPage: number;
hasNextPage: boolean;
hasPrevPage: boolean;
};
}
export interface FindingsParams {
page?: number;
limit?: number;
search?: string;
status?: string;
sortBy?: string;
sortOrder?: 'asc' | 'desc';
}
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === 'object' && value !== null && !Array.isArray(value);
const invalidResponse = () => new Error('Invalid SEO tracking response');
const isFinding = (value: unknown): value is ResearchFinding =>
isRecord(value) && ['id', 'title', 'hypothesis', 'primaryKeyword', 'expectedOutcome', 'createdAt', 'updatedAt']
.every(key => typeof value[key] === 'string') &&
Array.isArray(value.targetKeywords) && value.targetKeywords.every(keyword => typeof keyword === 'string') &&
['RESEARCHED', 'ACTIONED', 'EVALUATING', 'SCALED', 'PRUNED'].includes(String(value.status)) &&
Number.isInteger(value.version) && Number(value.version) >= 0 &&
(value.snapshots === undefined || Array.isArray(value.snapshots));
function findingResponse(value: unknown): ResearchFinding {
if (!isFinding(value)) throw invalidResponse();
return value;
}
// api.ts preserves AxiosResponse; main.ts only installs DecimalInterceptor,
// which recursively serializes decimals but DOES NOT add a success/data wrapper.
// Lists already contain their own { data, meta }; never unwrap that data twice.
export const seoTrackingApi = {
getFindings: async (params?: FindingsParams, signal?: AbortSignal): Promise<FindingsResponse> => {
const { data } = await api.get<unknown>('/admin/seo-tracking', { params, signal });
if (!isRecord(data) || !Array.isArray(data.data) || !data.data.every(isFinding) || !isRecord(data.meta)) {
throw invalidResponse();
}
const meta = data.meta;
if (!['total', 'page', 'limit', 'totalPages', 'lastPage'].every(key =>
typeof meta[key] === 'number' && Number.isFinite(meta[key]) && Number.isInteger(meta[key]) && meta[key] >= 0) ||
typeof meta.hasNextPage !== 'boolean' || typeof meta.hasPrevPage !== 'boolean') throw invalidResponse();
return data as unknown as FindingsResponse;
},
getFindingById: async (id: string, signal?: AbortSignal): Promise<ResearchFinding> => {
const { data } = await api.get<unknown>(`/admin/seo-tracking/${encodeURIComponent(id)}`, { signal });
return findingResponse(data);
},
updateCeoFeedback: async (id: string, feedback: string, expectedVersion: number): Promise<ResearchFinding> => {
const { data } = await api.patch<unknown>(`/admin/seo-tracking/${encodeURIComponent(id)}/feedback`, { feedback, expectedVersion });
return findingResponse(data);
},
addSnapshot: async (id: string, snapshot: Partial<PerformanceSnapshot>): Promise<PerformanceSnapshot> => {
const { data } = await api.post<unknown>(`/admin/seo-tracking/${encodeURIComponent(id)}/snapshots`, snapshot);
if (!isRecord(data) || typeof data.id !== 'string' || typeof data.findingId !== 'string' ||
typeof data.snapshotDate !== 'string' || typeof data.createdAt !== 'string') throw invalidResponse();
return data as unknown as PerformanceSnapshot;
},
};
@@ -82,9 +82,9 @@ describe('BlogPostPage FAQPage Schema injection (SEO-P1-07)', () => {
const jsx=await BlogPostPage({params:Promise.resolve({slug:'fresh'})}); const script:any=React.Children.toArray(jsx.props.children)[0]; const json=JSON.parse(script.props.dangerouslySetInnerHTML.__html); expect(json.dateModified).toBe('2026-01-01T12:00:00.000Z'); expect(json.author['@type']).toBe('Organization'); expect(json.author.name).toBe('کنینا');
});
it('omits dateModified when only technical updatedAt exists', async () => {
it('uses publication as dateModified when only technical updatedAt exists', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ok:true,json:async()=>({slug:'technical',title:'Technical',content:'<p>x</p>',publishedAt:'2026-01-01T01:00:00Z',updatedAt:'2026-01-01T12:00:00Z',contentUpdatedAt:null})}));
const jsx=await BlogPostPage({params:Promise.resolve({slug:'technical'})}); const script:any=React.Children.toArray(jsx.props.children)[0]; const json=JSON.parse(script.props.dangerouslySetInnerHTML.__html); expect(json.dateModified).toBeUndefined();
const jsx=await BlogPostPage({params:Promise.resolve({slug:'technical'})}); const script:any=React.Children.toArray(jsx.props.children)[0]; const json=JSON.parse(script.props.dangerouslySetInnerHTML.__html); expect(json.dateModified).toBe('2026-01-01T01:00:00.000Z');
});
it('uses the stable Organization fallback visibly and in metadata', async () => {
@@ -1,4 +1,4 @@
import { validContentUpdatedAt } from "../../../lib/blogDates";
import { persianDate, validContentUpdatedAt } from "../../../lib/blogDates";
import { resolveBlogAuthorIdentity } from "../../../lib/blogAuthor";
import React from "react";
import { notFound } from 'next/navigation';
@@ -23,7 +23,7 @@ function safeLocalDate(val: any): string {
if (!val) return '';
try {
const d = new Date(val);
return isNaN(d.getTime()) ? '' : d.toLocaleDateString('fa-IR');
return isNaN(d.getTime()) ? '' : persianDate(d.toISOString());
} catch {
return '';
}
@@ -95,7 +95,8 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str
const resolvedAuthor = resolveBlogAuthorIdentity(blog);
const publishedTime = safeIso(blog.publishedAt) || safeIso(blog.createdAt);
const modifiedTime = safeIso(validContentUpdatedAt(blog));
// Technical writes are not substantive edits; unedited articles retain the real publication date.
const modifiedTime = safeIso(validContentUpdatedAt(blog)) || publishedTime;
const keywordsList = blog.focusKeywords
? blog.focusKeywords.split(',').map((k: string) => k.trim())
@@ -181,8 +182,8 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug:
? blog.canonicalUrl.replace(/\/+$/, '')
: `${siteUrl}/blog/${slug}`;
const publishedIso = safeIso(blog.publishedAt) || safeIso(blog.createdAt) || new Date().toISOString();
const modifiedIso = safeIso(validContentUpdatedAt(blog));
const publishedIso = safeIso(blog.publishedAt) || safeIso(blog.createdAt);
const modifiedIso = safeIso(validContentUpdatedAt(blog)) || publishedIso;
const sanitizedContent = sanitizeBlogHtml(blog.content);
const schemaType = blog.schemaType || 'BlogPosting';
@@ -210,7 +211,7 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug:
image: blog.imageUrl
? [blog.imageUrl.startsWith('http') ? blog.imageUrl : `${siteUrl}${blog.imageUrl.startsWith('/') ? '' : '/'}${blog.imageUrl}`]
: [config.ogImageUrl.startsWith('http') ? config.ogImageUrl : `${siteUrl}${config.ogImageUrl.startsWith('/') ? '' : '/'}${config.ogImageUrl}`],
datePublished: publishedIso,
...(publishedIso ? { datePublished: publishedIso } : {}),
...(modifiedIso ? { dateModified: modifiedIso } : {}),
author: authorSchema,
publisher: {
@@ -0,0 +1,73 @@
import React from 'react';
import { afterEach, expect, it, vi } from 'vitest';
import { renderToStaticMarkup } from 'react-dom/server';
import BlogPostPage, { generateMetadata } from './page';
import { validContentUpdatedAt } from '../../../lib/blogDates';
vi.mock('../../../lib/seo', () => ({
getSeoConfig: async () => ({ brandNameFa: 'کنینا', canonicalBaseUrl: 'https://canina.ir', ogImageUrl: 'https://canina.ir/default.webp' }),
formatPageTitle: (title: string) => title,
}));
vi.mock('../../../components/BlogPostClient', () => ({
default: ({ blog, publishedDate }: { blog: any; publishedDate: string }) => <div>
<span>تاریخ انتشار: {publishedDate}</span>
{validContentUpdatedAt(blog) && <span>آخرین به‌روزرسانی</span>}
</div>,
}));
afterEach(() => { vi.unstubAllGlobals(); vi.unstubAllEnvs(); });
const published = '2026-10-29T07:11:40.925Z';
async function readDates(fields: Record<string, unknown>) {
vi.stubEnv('NEXT_PUBLIC_APP_ENV', 'staging');
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: async () => ({
title: 'Timestamp contract', content: '<p>Article</p>', ...fields,
}) }));
const params = Promise.resolve({ slug: 'timestamp-contract' });
const metadata = await generateMetadata({ params });
const jsx = await BlogPostPage({ params });
const script: any = React.Children.toArray(jsx.props.children)[0];
return { og: metadata.openGraph as any, robots: metadata.robots,
article: JSON.parse(script.props.dangerouslySetInnerHTML.__html), html: renderToStaticMarkup(jsx) };
}
it.each([null, undefined, 'invalid', published, '2026-10-28T00:00:00Z'])(
'uses real publication for unedited/invalid/chronologically inapplicable content date %s', async (contentUpdatedAt) => {
const { og, article, html, robots } = await readDates({ publishedAt: published,
contentUpdatedAt, updatedAt: '2026-10-30T09:00:00Z', imageUrl: '/attached.webp' });
expect(og.publishedTime).toBe(published);
expect(og.modifiedTime).toBe(published);
expect(article.datePublished).toBe(published);
expect(article.dateModified).toBe(published);
expect(html).not.toContain('آخرین به‌روزرسانی');
// Stage noindex remains an independent HTTP acceptance check; no robots change in this slice.
});
it('uses actual substantive update consistently without changing publication', async () => {
const modified = '2026-10-29T12:00:00.000Z';
const { og, article, html } = await readDates({ publishedAt: published, contentUpdatedAt: modified });
expect(og.modifiedTime).toBe(modified);
expect(article.dateModified).toBe(modified);
expect(article.datePublished).toBe(published);
expect(html).toContain('آخرین به‌روزرسانی');
});
it.each([null, 'invalid'])('uses the valid existing createdAt fallback when publishedAt is %s', async (publishedAt) => {
const { og, article } = await readDates({ publishedAt, createdAt: published });
expect(og.publishedTime).toBe(published);
expect(og.modifiedTime).toBe(published);
expect(article.datePublished).toBe(published);
expect(article.dateModified).toBe(published);
});
it.each([{}, { publishedAt: 'invalid', createdAt: 'invalid', contentUpdatedAt: '2026-10-30T00:00:00Z' }])(
'does not invent rendering-time publication or modification when unknown: %j', async (fields) => {
const { og, article } = await readDates(fields);
expect(og.publishedTime).toBeUndefined();
expect(og.modifiedTime).toBeUndefined();
expect(article).not.toHaveProperty('datePublished');
expect(article).not.toHaveProperty('dateModified');
});
it('formats visible publication using Persian calendar and Tehran rather than server timezone', async () => {
const { html } = await readDates({ publishedAt: '2026-10-29T21:00:00Z' });
const expected = new Intl.DateTimeFormat('fa-IR-u-ca-persian', {
year: 'numeric', month: 'numeric', day: 'numeric', timeZone: 'Asia/Tehran',
}).format(new Date('2026-10-29T21:00:00Z'));
expect(html).toContain(`تاریخ انتشار: ${expected}`);
});
@@ -0,0 +1,17 @@
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, it } from 'vitest';
import BlogPostClient from '../../../components/BlogPostClient';
it.each([null, undefined, 'invalid', '2026-10-29T07:11:40.925Z', '2026-10-28T00:00:00Z'])(
'actual client keeps publication but no visible update for %s despite later technical writes', (contentUpdatedAt) => {
const html = renderToStaticMarkup(<BlogPostClient
blog={{ id: 'timestamp-fixture', slug: 'timestamp-fixture', title: 'Timestamp',
publishedAt: '2026-10-29T07:11:40.925Z', contentUpdatedAt,
updatedAt: '2026-10-30T10:00:00Z', imageUrl: '/attached.webp' }}
publishedDate="۱۴۰۵/۸/۷" sanitizedContent="<p>Article</p>" authorName="کنینا"
/>);
expect(html).toContain('تاریخ انتشار');
expect(html).toContain('۱۴۰۵/۸/۷');
expect(html).not.toContain('آخرین به‌روزرسانی');
});
@@ -1,12 +1,10 @@
'use client';
import { useCallback, useEffect, useRef } from 'react';
import { useEffect, useRef } from 'react';
import { usePathname } from 'next/navigation';
import { analyticsAllowed, catalogRoute, trackCatalogClick } from '../lib/catalogAnalytics';
declare global {
interface Window {
globalPrivacyControl?: boolean;
dataLayer?: any[];
clarity?: any;
gtag?: (...args: any[]) => void;
@@ -22,36 +20,42 @@ interface AnalyticsDeferredProps {
export default function AnalyticsDeferred({ gtmId, gaId, clarityId }: AnalyticsDeferredProps) {
const pathname = usePathname();
const loadedRef = useRef(false);
const lastPathRef = useRef<string | null>(null);
const pathnameRef = useRef(pathname);
useEffect(() => { pathnameRef.current = pathname; }, [pathname]);
const initialPathRef = useRef<string | null>(null);
const emit = useCallback((event: string, params: Record<string, string>) => {
if (!analyticsAllowed(navigator, window)) return;
if (gaId && window.gtag) window.gtag('event', event, params);
else if (gtmId && window.dataLayer) window.dataLayer.push({ event, ...params });
}, [gaId, gtmId]);
const recordView = useCallback((path: string) => {
if (lastPathRef.current === path) return;
lastPathRef.current = path;
const route = catalogRoute(path);
emit('page_view', { page_path: route, page_location: window.location.origin + route, page_referrer: '' });
if (route === '/shop/[slug]') emit('catalog_product_view', { content_type: 'product' });
if (route === '/blog/[slug]' || route === '/wiki/[slug]') emit('catalog_content_view', { content_type: route.startsWith('/blog') ? 'article' : 'wiki' });
}, [emit]);
useEffect(() => {
if (!initialPathRef.current && pathname) {
initialPathRef.current = pathname;
}
}, [pathname]);
// Track client-side page views on Next.js route transitions
useEffect(() => {
if (!pathname || !loadedRef.current) return;
recordView(pathname);
}, [pathname, recordView]);
if (pathname === initialPathRef.current) return;
// 1. Google Analytics 4 page_view event on client navigation
if (gaId && typeof window !== 'undefined' && typeof window.gtag === 'function') {
window.gtag('event', 'page_view', {
page_path: pathname,
page_location: window.location.href,
page_title: typeof document !== 'undefined' ? document.title : '',
});
}
// 2. Google Tag Manager page_view event on client navigation
if (gtmId && typeof window !== 'undefined' && Array.isArray(window.dataLayer)) {
window.dataLayer.push({
event: 'page_view',
page_path: pathname,
});
}
}, [pathname, gaId, gtmId]);
useEffect(() => {
let loaded = false;
const loadAnalytics = () => {
if (loaded || !analyticsAllowed(navigator, window)) return;
if (loaded) return;
loaded = true;
loadedRef.current = true;
@@ -81,7 +85,7 @@ export default function AnalyticsDeferred({ gtmId, gaId, clarityId }: AnalyticsD
}
window.gtag = gtag;
gtag('js', new Date());
gtag('config', gaId, { send_page_view: false, page_title: '', page_location: window.location.origin + catalogRoute(pathnameRef.current || '/'), page_referrer: '' });
gtag('config', gaId, { page_path: window.location.pathname });
// Only append gtag.js script if not already added
if (!document.querySelector(`script[src*="${gaId}"]`)) {
@@ -108,16 +112,8 @@ export default function AnalyticsDeferred({ gtmId, gaId, clarityId }: AnalyticsD
else l.head.appendChild(t);
})(window, document, 'clarity', 'script', clarityId);
}
if (pathnameRef.current) recordView(pathnameRef.current);
};
const onClick = (event: MouseEvent) => {
if (!loadedRef.current || !analyticsAllowed(navigator, window)) return;
const anchor = event.target instanceof Element ? event.target.closest('a') : null;
if (anchor instanceof HTMLAnchorElement) trackCatalogClick(event, anchor, pathnameRef.current || '/', emit);
};
document.addEventListener('click', onClick);
// Listen to first user interaction
window.addEventListener('scroll', loadAnalytics, { passive: true, once: true });
window.addEventListener('touchstart', loadAnalytics, { passive: true, once: true });
@@ -137,8 +133,6 @@ export default function AnalyticsDeferred({ gtmId, gaId, clarityId }: AnalyticsD
return () => {
loaded = true;
loadedRef.current = false;
lastPathRef.current = null;
document.removeEventListener('click', onClick);
clearTimeout(timer);
if (idleId !== undefined) window.cancelIdleCallback(idleId);
window.removeEventListener('scroll', loadAnalytics);
@@ -146,7 +140,7 @@ export default function AnalyticsDeferred({ gtmId, gaId, clarityId }: AnalyticsD
window.removeEventListener('mousemove', loadAnalytics);
window.removeEventListener('keydown', loadAnalytics);
};
}, [gtmId, gaId, clarityId, emit, recordView]);
}, [gtmId, gaId, clarityId]);
return null;
}
@@ -54,19 +54,14 @@ it('tracks client-side route changes when pathname changes',()=>{
mockPathname = '/blog/test-article';
rerender(<AnalyticsDeferred gaId="G-test" gtmId="GTM-test"/>);
const gtmPageView = window.dataLayer?.find(entry => entry.event === 'page_view');
expect(gtmPageView).toBeUndefined(); // direct GA is the single first-party owner
mockPathname = '/';
rerender(<AnalyticsDeferred gaId="G-test" gtmId="GTM-test"/>);
const views = window.dataLayer?.filter(entry => entry[0] === 'event' && entry[1] === 'page_view');
expect(views?.map(entry => entry[2].page_path)).toEqual(['/','/blog/[slug]','/']);
expect(views?.every(entry => !('page_title' in entry[2]) && !entry[2].page_location.includes('?'))).toBe(true);
const gtmPageView = window.dataLayer?.find(entry => entry.event === 'page_view' && entry.page_path === '/blog/test-article');
expect(gtmPageView).toBeDefined();
const gaPageView = window.dataLayer?.find(entry => {
return Object.prototype.toString.call(entry) === '[object Arguments]' && entry[0] === 'event' && entry[1] === 'page_view';
});
expect(gaPageView).toBeDefined();
expect(gaPageView[2].page_path).toBe('/');
expect(gaPageView[2].page_path).toBe('/blog/test-article');
});
it.each(['scroll','touchstart','mousemove','keydown'])('loads on %s',event=>{
@@ -120,32 +115,6 @@ it('cancels idle work on unmount',()=>{
expect(cancelIdleCallback).toHaveBeenCalledWith(9);
});
it('honors opt-out before loading and after initialization',()=>{
window.globalPrivacyControl=true;
const v=render(<AnalyticsDeferred gaId="G-test"/>);
fireEvent.scroll(window);
expect(document.scripts).toHaveLength(0);
delete window.globalPrivacyControl;
fireEvent.keyDown(window);
const count=window.dataLayer?.length;
window.globalPrivacyControl=true;
mockPathname='/shop/joint';v.rerender(<AnalyticsDeferred gaId="G-test"/>);
expect(window.dataLayer).toHaveLength(count!);
delete window.globalPrivacyControl;
});
it('tracks catalog views and actual enabled contact anchors without commerce events',()=>{
mockPathname='/shop/joint';
const v=render(<AnalyticsDeferred gaId="G-test"/>);
fireEvent.scroll(window);
const a=document.createElement('a');a.href='tel:private';document.body.append(a);
fireEvent.click(a);a.remove();
expect(window.dataLayer?.filter(e=>e[0]==='event').map(e=>e[1])).toEqual(['page_view','catalog_product_view','contact_intent']);
expect(window.dataLayer?.some(e=>e[0]==='config' && e[2].send_page_view===false)).toBe(true);
mockPathname='/shop/joint';v.rerender(<AnalyticsDeferred gaId="G-test"/>);
expect(window.dataLayer?.filter(e=>e[1]==='catalog_product_view')).toHaveLength(1);
});
it('unmount removes event and timeout callbacks',()=>{
const v=render(<AnalyticsDeferred gtmId="GTM-test"/>);
v.unmount();
@@ -1,21 +0,0 @@
import {describe,it,expect,vi} from 'vitest';
import {catalogRoute, analyticsAllowed, trackCatalogClick} from '../catalogAnalytics';
describe('catalog analytics privacy and intent',()=>{
it('uses bounded public route templates without identifiers or private URLs',()=>{
expect(catalogRoute('/shop/joint')).toBe('/shop/[slug]');
expect(catalogRoute('/blog/article')).toBe('/blog/[slug]');
expect(catalogRoute('/dashboard/orders/secret')).toBe('/other');
});
it('respects browser privacy signals',()=>{expect(analyticsAllowed({doNotTrack:'1'},{})).toBe(false);expect(analyticsAllowed({}, {globalPrivacyControl:true})).toBe(false);});
it('records article to product intent without href, title, query or contact data',()=>{
const emit=vi.fn(); const a=document.createElement('a');a.href='/shop/joint?email=private#phone';a.textContent='private';
trackCatalogClick(new MouseEvent('click'),a,'/blog/article',emit);
expect(emit).toHaveBeenCalledExactlyOnceWith('internal_navigation',{source_route:'/blog/[slug]',target_route:'/shop/[slug]'});
});
it('records actual contact anchors but never contact value or external navigation',()=>{
const emit=vi.fn();const a=document.createElement('a');a.href='tel:private';trackCatalogClick(new MouseEvent('click'),a,'/shop/joint',emit);
expect(emit).toHaveBeenCalledExactlyOnceWith('contact_intent',{source_route:'/shop/[slug]',contact_type:'phone'});
emit.mockClear();a.href='https://external.test';trackCatalogClick(new MouseEvent('click'),a,'/blog/a',emit);expect(emit).not.toHaveBeenCalled();
});
it('ignores cancelled, modified, and non-primary clicks',()=>{const emit=vi.fn();const a=document.createElement('a');a.href='/shop/a';for(const event of [new MouseEvent('click',{ctrlKey:true}),new MouseEvent('click',{button:1})]) trackCatalogClick(event,a,'/blog/a',emit);const event=new MouseEvent('click',{cancelable:true});event.preventDefault();trackCatalogClick(event,a,'/blog/a',emit);expect(emit).not.toHaveBeenCalled();});
});
@@ -1,27 +0,0 @@
// Only bounded route classes leave the browser; never arbitrary paths or contact values.
export function catalogRoute(path: string): string {
if (/^\/(shop|blog|wiki)\/[^/]+\/?$/.test(path)) return `/${path.split('/')[1]}/[slug]`;
return ['/', '/shop', '/blog', '/wiki', '/catalog', '/about', '/contact', '/videos'].includes(path) ? path : '/other';
}
export function analyticsAllowed(nav: { doNotTrack?: string | null; globalPrivacyControl?: boolean }, browser: { globalPrivacyControl?: boolean }): boolean {
return nav.doNotTrack !== '1' && !nav.globalPrivacyControl && !browser.globalPrivacyControl;
}
export type CatalogEmitter = (event: string, params: Record<string, string>) => void;
export function trackCatalogClick(event: MouseEvent, anchor: HTMLAnchorElement, source: string, emit: CatalogEmitter): void {
if (event.defaultPrevented || event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey || anchor.hasAttribute('download')) return;
const url = new URL(anchor.href, window.location.origin);
const source_route = catalogRoute(source);
if (url.protocol === 'tel:' || url.protocol === 'mailto:') {
emit('contact_intent', { source_route, contact_type: url.protocol === 'tel:' ? 'phone' : 'email' });
return;
}
if (url.origin !== window.location.origin || !['http:', 'https:'].includes(url.protocol)) return;
const target_route = catalogRoute(url.pathname);
if (target_route === '/other' || url.pathname === source) return;
if (!['/blog/[slug]', '/wiki/[slug]', '/shop/[slug]'].includes(source_route) && target_route !== '/contact') return;
emit(target_route === '/contact' ? 'contact_intent' : 'internal_navigation', target_route === '/contact'
? { source_route, contact_type: 'contact_page' } : { source_route, target_route });
}
+54
View File
@@ -0,0 +1,54 @@
#!/usr/bin/env python3
"""Narrow Canina gateway Git routing repair; run as UID10000 only."""
import hashlib,json,os,pathlib,subprocess,sys,tempfile
HOME=pathlib.Path('/opt/data')
BLOCK='''\n# Managed Canina repository SSH route (no credential provisioning).
Match originalhost git.parsaaghayi.ir user git
Port 222
IdentityFile /opt/data/.ssh/canina_gitea
IdentitiesOnly yes
StrictHostKeyChecking yes
UserKnownHostsFile /opt/data/.ssh/gitea_known_hosts
ConnectTimeout 10
'''
GUIDANCE='''# Canina execution preflight
This gateway runs as UID10000 with HOME=HERMES_HOME=/opt/data; Docker root is not the worker identity.
Before reporting Git credentials missing, run read-only `git ls-remote canina-gitea:parsa/canina.git refs/heads/develop` from the actual worker. The dedicated existing key is /opt/data/.ssh/canina_gitea; pinned trust is /opt/data/.ssh/gitea_known_hosts. Never print/copy private keys, disable host verification, request a new key/token without testing the existing route, or embed HTTPS tokens in URLs. Browser vault login tools are for website forms, not SSH key provisioning.
Raw repository URL: ssh://git@git.parsaaghayi.ir:222/parsa/canina.git. Diagnose URL/SSH host matching independently from repository permissions. A successful read does not establish push permission or CI publication.
Use isolated worktrees and exact tool exit/results. Delegation dispatched is not completed; wait for delivered results, and distinguish failed access, implementation, tests, CI and live acceptance. Do not report feature completion from plans, tool presence or another agent's unsupported claim. Do not replay unrelated feature requests while repairing Hermes.
Preserve owner approval gates, existing sessions and all unrelated profiles. All code/config repair changes must be tracked in Git and released through CI/CD; never restart gateways or deploy site features merely to test access.
'''
def config_probe(path,host,user='git'):
r=subprocess.run(['ssh','-F',str(path),'-G','-l',user,host],capture_output=True,text=True,timeout=10,check=True)
return dict(line.split(' ',1) for line in r.stdout.splitlines() if ' ' in line and line.split(' ',1)[0] in {'port','identitiesonly','stricthostkeychecking','identityfile','userknownhostsfile','hostname'})
def test():
with tempfile.TemporaryDirectory() as t:
p=pathlib.Path(t)/'config'; p.write_text('Host canina-gitea\n HostName git.parsaaghayi.ir\n User git\n Port 222\n IdentityFile /opt/data/.ssh/canina_gitea\n IdentitiesOnly yes\n StrictHostKeyChecking yes\n UserKnownHostsFile /opt/data/.ssh/gitea_known_hosts\n'+BLOCK)
d=config_probe(p,'git.parsaaghayi.ir'); assert d['port']=='222' and d['identitiesonly']=='yes' and d['stricthostkeychecking']=='true' and d['identityfile']=='/opt/data/.ssh/canina_gitea',d
assert config_probe(p,'unrelated.example')['port']=='22'
assert config_probe(p,'git.parsaaghayi.ir','other')['port']=='22'
assert config_probe(p,'canina-gitea')['port']=='222'
print('PASS: raw git route, alias route, unrelated host and unrelated user isolation')
def apply():
assert os.getuid()==10000 and os.getenv('HERMES_HOME')=='/opt/data'
cfg=HOME/'.ssh/config'; before=cfg.read_text(); guide=HOME/'.hermes.md'
assert 'Host canina-gitea\n' in before
assert not guide.exists() or guide.read_text()==GUIDANCE,'unmanaged guidance exists'
assert 'Match originalhost git.parsaaghayi.ir' not in before or BLOCK in before,'unmanaged raw host route'
if BLOCK not in before:
assert 'Host git.parsaaghayi.ir' not in before
backup=HOME/'.ssh/config.before-canina-routing-20261106'
if backup.exists(): assert backup.read_text()==before,'backup conflict'
else:
fd=os.open(backup,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600)
with os.fdopen(fd,'w') as f: f.write(before)
tmp=cfg.with_suffix('.repair-new'); tmp.write_text(before+BLOCK); tmp.chmod(cfg.stat().st_mode & 0o777); os.replace(tmp,cfg)
if not guide.exists():
fd=os.open(guide,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600)
with os.fdopen(fd,'w') as f:f.write(GUIDANCE)
d=config_probe(cfg,'git.parsaaghayi.ir'); assert d['port']=='222' and d['identityfile']=='/opt/data/.ssh/canina_gitea',d
print(json.dumps({'status':'applied','uid':os.getuid(),'config_sha256':hashlib.sha256(cfg.read_bytes()).hexdigest(),'guidance_sha256':hashlib.sha256(guide.read_bytes()).hexdigest(),'restart':False}))
if __name__=='__main__':
test()
if '--apply' in sys.argv: apply()
+53
View File
@@ -0,0 +1,53 @@
"""Default-profile delivery gate: external release claims require structured evidence.
No secrets, commands or tool text persisted. Fail closed for positive release claims.
"""
import json, os, re, threading
_STATE = {}
_LOCK = threading.Lock()
_RELEASE = re.compile(r'(?:deploy(?:ed|ment)?|استقرار|دپلوی|دیپلوی|CI[\s‑#:-]*\d+|/pipelines/\d+|/actions/runs/\d+)', re.I)
_POSITIVE = re.compile(r'(?:completed|succeeded|deployed|refreshed|applied|موفق|انجام شد|تکمیل شد|منتشر شد|مستقر شد)', re.I)
_NEGATIVE = re.compile(r'(?:not verified|unverified|not deployed|no deployment|not performed|not confirmed|missing|unsupported|تأیید نشده|تایید نشده|تأیید نمی|تایید نمی|انجام نشد|نشده|ندارد|نیست|فاقد|مفقود|نامعتبر|اثبات نمی|اثبات نشده)', re.I)
_HASH = re.compile(r'^[a-f0-9]{40}$')
def suspicious(text):
# Evaluate per line so a disclaimer cannot launder a separate affirmative claim.
return any(_RELEASE.search(line) and _POSITIVE.search(line) and not _NEGATIVE.search(line)
for line in str(text).splitlines())
def valid_attestation(value):
if not isinstance(value, dict): return False
a = value.get('canina_release_evidence')
return (isinstance(a, dict) and a.get('ci_system') == 'gitea'
and isinstance(a.get('commit'), str) and bool(_HASH.fullmatch(a['commit']))
and isinstance(a.get('run_id'), int) and a['run_id'] > 0
and a.get('ci_status') == 'success' and a.get('live_commit') == a['commit']
and a.get('environment') in ('stage', 'production')
and a.get('verified_by') == 'managed-release-verifier')
def observe(tool_name='', args=None, result=None, session_id='', turn_id='', **kw):
if os.getenv('HERMES_HOME', '/opt/data') != '/opt/data': return
# Only an existing reviewed verifier invoked via terminal can supply the contract;
# arbitrary tool prose or a delegated summary never counts as publication evidence.
command = (args or {}).get('command', '') if isinstance(args, dict) else ''
if tool_name != 'terminal' or not re.fullmatch(r'/opt/data/bin/canina-release-verify --run [0-9]+ --environment (stage|production)', command): return
try:
payload = json.loads(result) if isinstance(result, str) else result
if not isinstance(payload, dict) or payload.get('exit_code') != 0: return
record = json.loads(payload.get('output', ''))
if not valid_attestation(record): return
with _LOCK: _STATE[(session_id, turn_id)] = True
except (ValueError, TypeError): return
def transform(response_text='', session_id='', turn_id='', **kw):
if os.getenv('HERMES_HOME', '/opt/data') != '/opt/data': return None
with _LOCK: proven = _STATE.pop((session_id, turn_id), False)
if suspicious(response_text) and not proven:
return ('گزارش پیشنهادی شامل ادعای موفقیت استقرار یا CI بود، اما شاهد معتبر انتشار در همین اجرا ثبت نشده است؛ این ادعا مسدود شد. '
'موفقیت انتشار تأیید نشده است. خروجی محلی یا خلاصهٔ عامل، شاهد انتشار نیست. '
'برای پذیرش انتشار باید رکورد واقعی Gitea، commit و نسخهٔ زنده با یکدیگر تطبیق داده شوند. '
'این پیام به معنی تکمیل کار نیست.')
return None
def register(ctx):
ctx.register_hook('post_tool_call', observe)
ctx.register_hook('transform_llm_output', transform)
+14
View File
@@ -0,0 +1,14 @@
import os,pathlib,subprocess,sys
assert os.getuid()==10000 and os.getenv('HERMES_HOME')=='/opt/data'
root=pathlib.Path('/opt/data/plugins/canina-reliability')
root.mkdir(mode=0o700,parents=True,exist_ok=True)
source=pathlib.Path(sys.argv[1])
for name in ['__init__.py','plugin.yaml']:
target=root/name
if target.exists() and target.read_bytes()!= (source/name).read_bytes(): raise RuntimeError('unmanaged plugin conflict')
target.write_bytes((source/name).read_bytes());target.chmod(0o600)
cli='/opt/hermes/bin/hermes'
for key,value in [('agent.verify_on_stop','true'),('agent.tool_use_enforcement','true'),('agent.execution_guidance','true'),('model.default','Canina-content')]:
subprocess.run([cli,'config','set',key,value],check=True)
subprocess.run([cli,'plugins','enable','canina-reliability'],check=True)
print('Scoped default reliability policy installed; gateway restart intentionally separate')
+7
View File
@@ -0,0 +1,7 @@
name: canina-reliability
version: "0.1.0"
description: "Scoped default release-report evidence gate"
author: Canina
provides_hooks:
- post_tool_call
- transform_llm_output
+26
View File
@@ -0,0 +1,26 @@
import importlib.util, pathlib, unittest, os
spec=importlib.util.spec_from_file_location('guard',pathlib.Path(__file__).with_name('__init__.py'))
g=importlib.util.module_from_spec(spec);spec.loader.exec_module(g)
class GuardTests(unittest.TestCase):
def test_fictional_ci(self):
self.assertIsNotNone(g.transform('CI-#8745 completed; deployment succeeded',session_id='a',turn_id='1'))
def test_persian(self):
self.assertIsNotNone(g.transform('دپلوی Stage با موفقیت انجام شد',session_id='a',turn_id='2'))
def test_local_only(self):
self.assertIsNone(g.transform('Local tests: 13 passed. No deployment was performed.',session_id='a',turn_id='3'))
def test_missing_commit(self):
self.assertFalse(g.valid_attestation({'canina_release_evidence':{'ci_status':'success','run_id':8745}}))
def test_delegated_claim_not_evidence(self):
g.observe(tool_name='delegate_task',result={'summary':'Deployment succeeded'},session_id='a',turn_id='4')
self.assertIsNotNone(g.transform('Deployment succeeded',session_id='a',turn_id='4'))
def test_negative(self):
self.assertIsNone(g.transform('استقرار موفق تأیید نشده است؛ مدرک ندارد.',session_id='a',turn_id='5'))
def test_disclaimer_not_launder(self):
self.assertIsNotNone(g.transform('Deployment succeeded\nAnother deployment is not verified',session_id='a',turn_id='6'))
def test_turn_isolation(self):
g._STATE[('a','x')]=True
self.assertIsNotNone(g.transform('Deployment succeeded',session_id='a',turn_id='y'))
def test_failed_terminal_not_evidence(self):
g.observe(tool_name='terminal',args={'command':'/opt/data/bin/canina-release-verify --run 8745 --environment stage'},result={'exit_code':1,'output':'{}'},session_id='a',turn_id='7')
self.assertIsNotNone(g.transform('Deployment succeeded',session_id='a',turn_id='7'))
if __name__=='__main__': unittest.main()
-42
View File
@@ -1,42 +0,0 @@
# Dormant research/directive publication boundary
No runtime publisher, cron, Gate1/2, deployment, or live API is changed. `daily_publisher.run_new` remains a dormant integration boundary, not current cron enforcement.
## Caller contract (breaking change to dormant callback)
`run_new(consumer, stable_run_id, research, draft_content, independent_review, publication_preflight)` saves research before drafting. Content and the independent reviewer receive the complete fetched finding and exact CEO free text/version. The draft must now be the actual Admin Blog payload, not a wrapper containing HTML. A nonempty directive requires reviewer identity, immutable evidence location and exact directive/draft SHA256 bindings. Hash checks establish binding, not reviewer authenticity or arbitrary prose compliance.
`publication_preflight(draft)` MUST run the existing publisher ownership, fresh inventory/relations/quota, backup, independent QA and write-ahead intent guards, and return the **unchanged reviewed payload without creating a Blog**. The consumer alone sends the atomic publication POST. Do not pass the previous Blog-creating callback: a returned string is rejected, but a malicious/incorrect callback could already have written before returning; trusted orchestration and reviewed wiring remain essential. No active wiring is included here.
The SQLite journal persists intent before network writes. Failed/ambiguous POSTs are never automatically retried. `reconcile_link(run)` is now read-only: it confirms a matching committed actionId/blogId, including after later feedback, or blocks for independent repair. It never creates or relinks an article. Other run IDs still require the existing shared publisher quota/ownership guard.
## Backend endpoint and serialization boundary
`POST /api/admin/seo-tracking/:id/publication`
Authenticated JWT admin/superadmin only (same controller guards as existing SEO tracking). Request:
```json
{"expectedVersion":0,"feedbackVersion":0,"actionId":"stable-run-id","blog":{"title":"...","slug":"...","content":"..."}}
```
`blog` uses existing Admin BlogsService create rules, including current-user author fallback, relations/tags, dates, schedule/status defaults and reading-time conversion. The endpoint deliberately does not invent another Blog field schema. It does not accept an arbitrary Prisma create input or bypass Admin create policy. Missing/invalid author or relation fails the entire transaction.
One transaction performs row-locking compare-and-swap on finding id/version/feedbackVersion with `blogId = null`, creates Blog via the existing Admin service using the same transaction client, then stores blogId/actionId. Response contains `blog`, `finding`, `consumedFeedbackVersion`, `cacheRevalidation`. Missing finding is 404; stale version/directive or already-linked finding is 409. Repeat requests are not create-idempotent responses: they conflict; the consumer reconciles saved action identity read-only. Cache revalidation happens only after commit; failure returns `failed` plus the committed identity, not an error encouraging recreation. External generation, review and publisher preflight happen before the transaction, not while holding the row lock.
Feedback PATCH uses the same row and finding version. If feedback commits first, publication's old predicate fails and no Blog exists. If publication locks first, feedback waits; after commit its old expectedVersion fails with 409. A fresh feedback request after committed publication applies to the **next action**, not retroactively to the already committed article. This is a linearization boundary, not a guarantee that all directives arriving after the boundary rewrite published content.
The legacy generic Blog endpoint and PATCH action remain for existing callers: this endpoint does not magically protect callers bypassing it. PATCH action is an acknowledgement/link operation, not publication authorization. No Gate1/2 or semantic-compliance claim is added.
## Many-actions and goals: explicitly not implemented
Prisma currently has one nullable unique blogId, one scalar nonunique external actionId, and one independently nullable goalMetric/goalTarget pair per finding. PATCH replaces those slots; it does not append immutable action history. A finding has many measurement snapshots, but snapshots target the finding only and cannot attribute evidence to a particular action or goal. UI shows one article/expectedOutcome and omits typed action/metric/target fields; the measurement worker resolves one article URL and does not evaluate structured goals.
A future additive migration should introduce Finding 1:N ResearchAction (immutable identity/idempotency key, lifecycle, consumed feedback version, external reference), Finding 1:N ResearchGoal (metric, comparator, unit, target/baseline, window, source), ActionGoal joins, and explicit action article targets. Goal evaluations should reference measured evidence, not imply causal attribution from aggregate page totals. Backfill at most one marked legacy action; never invent historical acknowledgements or complete goals from partial scalar data. Specify legacy projection/conflict rules before dual writes and update backend/UI/worker/tests together. This patch intentionally preserves the initial model and rejects a second publication on a linked finding.
## Local evidence
- Disposable PostgreSQL 16.14, schema pushed only to loopback port 55447; `publication.postgres.spec.ts` exercises actual row-lock wait with distinct backend PIDs via pg_stat_activity, stale-feedback-first rejection, publication-first feedback conflict, full rollback on invalid author, duplicate rejection and cache-failure identity.
- Same suite runs Python `run_new` over actual loopback TCP through Nest JWT/role guards and Prisma, proving successful atomic publication, changed feedback during preflight -> HTTP 409/no Blog, and unauthenticated publication -> HTTP 401. HTTPS production transport is not weakened: the test uses an explicit disposable-only loopback adapter.
- Harness and machine-readable results are local evidence under `/opt/data/cache/scratch/run-publication-pg.mjs`, `publication-pg.log`, `publication-jest.json`. Server shuts down in finally. The existing PG16 npm tooling lives in the untracked evidence directory; it is not a release dependency.
- No live writes, deploy, push, cron activation or runtime publisher edits.
-147
View File
@@ -1,147 +0,0 @@
"""Dormant NEW-only publisher boundary. Never invokes a publisher on its own."""
import hashlib
import json
import sqlite3
import urllib.request
import urllib.error
BASE = '/api/admin/seo-tracking'
class Blocked(RuntimeError):
pass
def digest(value):
return hashlib.sha256(json.dumps(value, sort_keys=True, ensure_ascii=False,
separators=(',', ':')).encode()).hexdigest()
class AdminTransport:
"""Use approved short-lived bearer supplied by caller; no retry or secret logging."""
def __init__(self, origin, bearer):
if not origin.startswith('https://'):
raise ValueError('HTTPS Admin origin required')
self.origin, self.bearer = origin.rstrip('/'), bearer
def __call__(self, method, path, body=None):
if path != BASE and not path.startswith(BASE + '/'):
raise ValueError('Research endpoints only')
request = urllib.request.Request(
self.origin + path, method=method,
data=None if body is None else json.dumps(body).encode(),
headers={'Authorization': 'Bearer ' + self.bearer,
'Content-Type': 'application/json'})
# Never forward Authorization to redirects, even same-origin redirects.
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, *args, **kwargs):
return None
try:
with urllib.request.build_opener(NoRedirect).open(request, timeout=30) as response:
return json.load(response)
except urllib.error.HTTPError as error:
raise Blocked('Admin HTTP ' + str(error.code)) from None
class Consumer:
def __init__(self, path, api):
self.path, self.api = path, api
with self.db() as db:
db.execute('CREATE TABLE IF NOT EXISTS runs (run TEXT PRIMARY KEY, state TEXT NOT NULL, finding TEXT, packet TEXT, draft_hash TEXT, review TEXT, blog TEXT)')
def db(self):
db = sqlite3.connect(self.path, timeout=10)
db.row_factory = sqlite3.Row
return db
def row(self, run):
with self.db() as db:
row = db.execute('SELECT * FROM runs WHERE run=?', (run,)).fetchone()
if row is None:
raise Blocked('Research must be saved before drafting')
return dict(row)
def prepare(self, run, research):
with self.db() as db:
try:
db.execute('INSERT INTO runs(run,state) VALUES (?,?)', (run, 'research_intent'))
except sqlite3.IntegrityError:
row = self.row(run)
if row['state'] == 'prepared':
return json.loads(row['packet'])
raise Blocked('Existing research intent/outcome requires reconciliation') from None
# Persist intent before POST: timeout must never cause duplicate research.
finding = self.api('POST', BASE, research)
packet = self.api('GET', BASE + '/' + finding['id'])
self.check_packet(packet)
with self.db() as db:
db.execute('UPDATE runs SET state=?,finding=?,packet=? WHERE run=?',
('prepared', packet['id'], json.dumps(packet), run))
return packet
@staticmethod
def check_packet(packet):
for key in ('version', 'feedbackVersion'):
if type(packet.get(key)) is not int or packet[key] < 0:
raise Blocked('Missing directive version')
if not isinstance(packet.get('id'), str) or not packet['id']:
raise Blocked('Missing finding identity')
if packet.get('ceoFeedback') is not None and not isinstance(packet['ceoFeedback'], str):
raise Blocked('Invalid directive')
def publish(self, run, packet, draft, review, publication_preflight):
"""Caller must preserve existing ownership/QA/backup/quota/intent guards.
packet is the complete research/directive supplied to Content before drafting.
review is an independent exact-hash receipt, NOT semantic-compliance proof.
"""
row = self.row(run)
if row['packet'] is None or digest(json.loads(row['packet'])) != digest(packet):
raise Blocked('Packet differs from saved directive')
if row['state'] == 'linked':
return row['blog']
if row['state'] != 'prepared':
raise Blocked('In-flight/ambiguous action: reconcile, never recreate')
self.check_packet(packet)
if packet.get('ceoFeedback', None):
if not isinstance(review, dict) or not review.get('reviewer') or not review.get('evidence') or review.get('directiveHash') != digest(packet) or review.get('draftHash') != digest(draft):
raise Blocked('Exact directive/draft independent review evidence required')
with self.db() as db:
changed = db.execute('UPDATE runs SET state=?,draft_hash=?,review=? WHERE run=? AND state=?',
('claiming', digest(draft), json.dumps(review), run, 'prepared')).rowcount
if changed != 1:
raise Blocked('Another consumer owns action')
# Preflight MUST preserve existing ownership/QA/backup/quota/intent
# guards, but must NOT create a Blog. Only this atomic endpoint writes.
reviewed_hash = digest(draft)
payload = publication_preflight(draft)
if not isinstance(payload, dict) or digest(payload) != reviewed_hash:
raise Blocked('Preflight must return the exact reviewed Blog payload')
with self.db() as db:
db.execute('UPDATE runs SET state=? WHERE run=?', ('publication_intent', run))
result = self.api('POST', BASE + '/' + packet['id'] + '/publication',
dict(expectedVersion=packet['version'],
feedbackVersion=packet['feedbackVersion'], actionId=run, blog=payload))
blog = result.get('blog', {}).get('id')
if (not isinstance(blog, str) or not blog or
result.get('consumedFeedbackVersion') != packet['feedbackVersion']):
raise Blocked('Missing committed publication identity; reconcile, never retry')
with self.db() as db:
db.execute('UPDATE runs SET state=?,blog=? WHERE run=?', ('linked', blog, run))
return blog
def reconcile_link(self, run):
"""Read-only repair of an ambiguous response; never creates or relinks."""
row = self.row(run)
if row['state'] == 'linked':
return row['blog']
if row['state'] != 'publication_intent':
raise Blocked('No publication intent; independent reconciliation required')
current = self.api('GET', BASE + '/' + row['finding'])
self.check_packet(current)
if current.get('actionId') != run or not current.get('blogId'):
raise Blocked('No matching committed action; never retry automatically')
with self.db() as db:
db.execute('UPDATE runs SET state=?,blog=? WHERE run=?',
('linked', current['blogId'], run))
return current['blogId']
Loaded 100 of 197 files, more files were not shown because too many files have changed in this diff. Show more