Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dc34c57a0c | ||
|
|
c97ea01ba9 | ||
|
|
00ba4360cf | ||
|
|
8669d183d5 | ||
|
|
66b9d75524 | ||
|
|
d3a0a61d79 | ||
|
|
0ad39bb92c | ||
|
|
0e952ef701 | ||
|
|
f1382e943c | ||
|
|
53fccc2d3c | ||
|
|
9ae839138c | ||
|
|
0fa6abc53d | ||
|
|
2a32f31097 | ||
|
|
52a7aebb51 | ||
|
|
af32ec14e1 | ||
|
|
e34156b2d3 | ||
|
|
721118787a | ||
|
|
292ed7f920 | ||
|
|
432f6a21c7 | ||
|
|
2087001ecd | ||
|
|
ec93af0064 | ||
|
|
effe30ee58 | ||
|
|
99f0c0d626 | ||
|
|
1e27387016 | ||
|
|
c733a806bd | ||
|
|
23cbd693a8 | ||
|
|
366bc9fc88 | ||
|
|
b4420e54b7 | ||
|
|
44d74d35e6 | ||
|
|
5897abcbad | ||
|
|
b3b9e617b5 | ||
|
|
6f9529d31f | ||
|
|
c25b10f7f3 | ||
|
|
c69a779ecc | ||
|
|
688a0e4de5 | ||
|
|
cf9b80bbb3 | ||
|
|
2a341d3969 | ||
|
|
9275233d09 | ||
|
|
13dceaa460 | ||
|
|
0ab2980ff4 | ||
|
|
fd14c05f3a | ||
|
|
cc0358bb12 | ||
|
|
f94ef580fb | ||
|
|
1bb6274b35 | ||
|
|
448c250944 | ||
|
|
5f5c3eb3b9 | ||
|
|
3805057923 | ||
|
|
f4678c48ca | ||
|
|
c40e931168 | ||
|
|
e96a13b255 | ||
|
|
4413c2ef6c | ||
|
|
65063e224a | ||
|
|
c8063b5f2a | ||
|
|
bfeb464bfb | ||
|
|
860324e3a9 | ||
|
|
f705511164 | ||
|
|
70a5449d35 | ||
|
|
80a2e188cf | ||
|
|
e036c5d436 | ||
|
|
ed77f87ab5 | ||
|
|
4712433903 | ||
|
|
f4add07780 | ||
|
|
01b6f1d3d7 | ||
|
|
60a4e14b4b | ||
|
|
6e465663bd | ||
|
|
b1142bd0c0 | ||
|
|
50d0df822c | ||
|
|
ab2f330eb8 | ||
|
|
ca3d4f6a16 | ||
|
|
3321bac22d | ||
|
|
3e78b89cc1 | ||
|
|
bfb1841370 | ||
|
|
6ba2c51403 | ||
|
|
ba0aa5ee4e | ||
|
|
7485c89e9b | ||
|
|
8869ce2583 | ||
|
|
64419f6755 | ||
|
|
8cedc2cd67 | ||
|
|
65a6fe1f0c | ||
|
|
afbee9cf70 | ||
|
|
5984242ce4 | ||
|
|
c523acc9e8 | ||
|
|
c78bdbcdb5 | ||
|
|
7a081e28df | ||
|
|
93d43fb261 | ||
|
|
8c435ab09e | ||
|
|
4388a5c2e6 | ||
|
|
62a7a87378 | ||
|
|
19583c5ad8 | ||
|
|
1858eba3e6 | ||
|
|
cb20c2acb5 | ||
|
|
105ab07fbd | ||
|
|
bf84e5da43 | ||
|
|
02badd0e25 | ||
|
|
aa23c7ef91 | ||
|
|
4b147b0091 | ||
|
|
6950ff0d79 | ||
|
|
cc9ec25388 | ||
|
|
be2ff0719a | ||
|
|
9d93707848 | ||
|
|
aa99216c49 | ||
|
|
58d3794050 | ||
|
|
16f9610027 | ||
|
|
2023dd4e36 | ||
|
|
0bed6e0313 | ||
|
|
f29ba4ab8b | ||
|
|
56b6696ca3 | ||
|
|
0d0c67704c | ||
|
|
09e8a890e0 | ||
|
|
4b17a6fcc3 | ||
|
|
5507fbcb29 | ||
|
|
176cc08a6b | ||
|
|
5953c3cf75 | ||
|
|
0952a482fb | ||
|
|
c7f1d25e98 | ||
|
|
841eab0556 | ||
|
|
ac065fa911 | ||
|
|
70d8128bfb | ||
|
|
8c8ae66c7d | ||
|
|
c8a3f35b0a | ||
|
|
e5c83e87fe | ||
|
|
eb17c8e284 | ||
|
|
459f8b59fe | ||
|
|
740e738fca | ||
|
|
de42b3126b | ||
|
|
4c6127786f | ||
|
|
ee35c10454 | ||
|
|
d9e4447903 | ||
|
|
10413547c1 |
No files matched your search
@@ -12,3 +12,7 @@ uploads
|
||||
**/uploads
|
||||
*.pdf
|
||||
graphify-out
|
||||
**/.revalidation.env*
|
||||
**/.support*.env*
|
||||
**/*runtime.env
|
||||
**/release.override.json
|
||||
@@ -5,6 +5,7 @@ on:
|
||||
branches:
|
||||
- main
|
||||
- develop
|
||||
- release/blog-timestamp-limited-20261030
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
@@ -12,9 +13,23 @@ jobs:
|
||||
steps:
|
||||
- name: Run deploy.sh from within the scripts folder
|
||||
env:
|
||||
BRANCH: ${{ github.ref_name }}
|
||||
SUPPORT_CHAT_KEY: ${{ secrets.SUPPORT_CHAT_KEY }}
|
||||
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=""
|
||||
@@ -25,8 +40,10 @@ jobs:
|
||||
|
||||
# 2. دانلود و اجرای اسکریپت deploy.sh بر اساس برنچ جاری
|
||||
mkdir -p scripts
|
||||
wget --no-proxy -qO scripts/deploy.sh https://git.parsaaghayi.ir/parsa/canina/raw/branch/${BRANCH}/scripts/deploy.sh
|
||||
wget --no-proxy -qO scripts/deploy.sh https://git.parsaaghayi.ir/parsa/canina/raw/commit/${DEPLOY_SHA}/scripts/deploy.sh
|
||||
wget --no-proxy -qO scripts/release-cache-stage.sh https://git.parsaaghayi.ir/parsa/canina/raw/commit/${DEPLOY_SHA}/scripts/release-cache-stage.sh
|
||||
|
||||
wget --no-proxy -qO scripts/release-cache-prod.sh https://git.parsaaghayi.ir/parsa/canina/raw/commit/${DEPLOY_SHA}/scripts/release-cache-prod.sh
|
||||
chmod +x scripts/deploy.sh
|
||||
cd scripts
|
||||
./deploy.sh ${BRANCH}
|
||||
./deploy.sh "${BRANCH}"
|
||||
@@ -16,3 +16,7 @@ playwright-report/
|
||||
playwright/.auth/
|
||||
blob-report/
|
||||
|
||||
|
||||
# Python CI helpers must not dirty immutable release checkouts.
|
||||
__pycache__/
|
||||
*.pyc
|
||||
+9
-9
@@ -1,4 +1,4 @@
|
||||
FROM node:20-alpine AS app-builder
|
||||
FROM node:22-alpine AS app-builder
|
||||
USER root
|
||||
WORKDIR /app
|
||||
ENV NEXT_TELEMETRY_DISABLED=1
|
||||
@@ -7,18 +7,17 @@ ENV NEXT_PUBLIC_API_URL=https://api.canina.ir/api
|
||||
# Optional: Use Nexus as npm registry
|
||||
ARG NPM_REGISTRY=
|
||||
RUN if [ -n "$NPM_REGISTRY" ]; then \
|
||||
npm config set registry "$NPM_REGISTRY" && \
|
||||
npm config set strict-ssl false; \
|
||||
npm config set registry "$NPM_REGISTRY"; \
|
||||
fi
|
||||
|
||||
COPY frontend/application/package*.json ./
|
||||
RUN npm ci --include=dev --prefer-offline --no-audit
|
||||
RUN npm ci --include=dev --prefer-offline --no-audit && test -x node_modules/.bin/next
|
||||
COPY frontend/application ./
|
||||
ARG NEXT_PUBLIC_API_URL
|
||||
ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL
|
||||
RUN npm run build
|
||||
|
||||
FROM node:20-alpine AS admin-builder
|
||||
FROM node:22-alpine AS admin-builder
|
||||
USER root
|
||||
WORKDIR /app
|
||||
ENV VITE_API_URL=https://api.canina.ir/api
|
||||
@@ -26,18 +25,17 @@ ENV VITE_API_URL=https://api.canina.ir/api
|
||||
# Optional: Use Nexus as npm registry (inherits build-arg)
|
||||
ARG NPM_REGISTRY=
|
||||
RUN if [ -n "$NPM_REGISTRY" ]; then \
|
||||
npm config set registry "$NPM_REGISTRY" && \
|
||||
npm config set strict-ssl false; \
|
||||
npm config set registry "$NPM_REGISTRY"; \
|
||||
fi
|
||||
|
||||
COPY frontend/admin-panel/package*.json ./
|
||||
RUN npm ci --include=dev --prefer-offline --no-audit
|
||||
RUN npm ci --include=dev --prefer-offline --no-audit && test -x node_modules/.bin/vite
|
||||
COPY frontend/admin-panel ./
|
||||
ARG VITE_API_URL
|
||||
ENV VITE_API_URL=$VITE_API_URL
|
||||
RUN npm run build
|
||||
|
||||
FROM node:20-alpine
|
||||
FROM node:22-alpine
|
||||
USER root
|
||||
RUN addgroup -S nginx 2>/dev/null || true && adduser -S nginx -G nginx 2>/dev/null || true
|
||||
RUN mkdir -p /var/log/nginx /var/cache/nginx /run/nginx /etc/nginx/conf.d /etc/nginx/http.d
|
||||
@@ -49,6 +47,8 @@ RUN chown -R nginx:nginx /var/log/nginx /var/cache/nginx /run/nginx 2>/dev/null
|
||||
WORKDIR /app
|
||||
COPY --from=app-builder /app .
|
||||
COPY --from=admin-builder /app/dist ./admin_static
|
||||
# Build-context umask must not make public assets unreadable by nginx workers.
|
||||
RUN chmod -R a+rX /app/admin_static
|
||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||
COPY nginx.conf /etc/nginx/http.d/default.conf
|
||||
|
||||
|
||||
+3
-2
@@ -12,7 +12,6 @@ ENV npm_config_cache=/tmp/npm-cache
|
||||
ARG NPM_REGISTRY=
|
||||
RUN if [ -n "$NPM_REGISTRY" ]; then \
|
||||
npm config set registry "$NPM_REGISTRY" && \
|
||||
npm config set strict-ssl false && \
|
||||
echo "Using npm registry: $NPM_REGISTRY"; \
|
||||
fi
|
||||
|
||||
@@ -32,8 +31,10 @@ RUN http_proxy=http://172.17.0.1:8888 https_proxy=http://172.17.0.1:8888 \
|
||||
FROM node:20-alpine
|
||||
USER root
|
||||
RUN http_proxy=http://172.17.0.1:8888 https_proxy=http://172.17.0.1:8888 apk add --no-cache openssl || apk add --no-cache openssl || true
|
||||
RUN mkdir -p /app/uploads && chown node:node /app/uploads
|
||||
RUN mkdir -p /app/uploads /app/private-stage-test && chmod 700 /app/private-stage-test && chown node:node /app/uploads /app/private-stage-test
|
||||
WORKDIR /app
|
||||
ARG STAGE_TEST_ARTIFACT_SHA=disabled
|
||||
RUN printf "%s" "$STAGE_TEST_ARTIFACT_SHA" > /app/STAGE_TEST_ARTIFACT_SHA
|
||||
ENV PRISMA_HIDE_UPDATE_MESSAGE=true
|
||||
COPY --chown=node:node --from=builder /app/package*.json ./
|
||||
COPY --chown=node:node --from=builder /app/tsconfig.json ./tsconfig.json
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
# Prisma migration history and Orchestration v4 rollout boundary
|
||||
|
||||
The checked-in history is **not a complete baseline of the current Prisma schema**. Do not assume that replaying it into an empty database can recreate the application, or that existing production tables imply corresponding migration records. Never use `prisma db push`, reset, or edit applied SQL to reconcile this.
|
||||
|
||||
## Actual tracked history
|
||||
|
||||
| Migration | What its SQL actually does |
|
||||
| --- | --- |
|
||||
| `20260526145407_init` | Creates users, addresses, wallets, products, product ingredients/symptoms, pets and medical conditions, reminders/completions, health logs, coupons, orders and order items, with their indexes/foreign keys. |
|
||||
| `20260526160916_add_ui_texts_and_scientific_terms` | Creates `ui_texts` and `scientific_terms`. |
|
||||
| `20261013210253_add_admin_modules` | Creates only `competitor_price_logs`, `b2b_leads`, `price_suggestions`, and `sms_campaigns`, with indexes and product foreign keys. It does **not** create legacy approvals, department tasks or audit logs. |
|
||||
| `20261015000000_add_support_conversations` | Creates support conversations/messages and their foreign keys. |
|
||||
| `20261020000000_add_blog_freshness_authorship` | Adds three columns to an assumed-existing `blogs` table. No earlier tracked migration creates `blogs`; fresh replay is therefore incomplete before v4. |
|
||||
| `20261022000000_add_orchestration_v4_core` | Additively creates nine `orchestration_*` tables, indexes and internal foreign keys; it neither creates nor copies legacy governance tables. |
|
||||
|
||||
There is no checked-in CREATE TABLE migration for `approval_requests`, `department_tasks`, or `audit_logs`. Their models/controllers are not evidence that either live environment has these tables, nor proof of how any historical database acquired them. The broader missing legacy schema must be reconciled separately. This document does not certify live table existence or migration status.
|
||||
|
||||
## Required rollout safeguards (not authorization to deploy)
|
||||
|
||||
1. Back up each environment and verify restore capability. Capture its actual schema and `_prisma_migrations` history read-only; compare those independently against all tracked SQL, including prerequisites such as `blogs`.
|
||||
2. Rehearse the exact planned chain on a disposable database restored from a reviewed baseline. A failed empty replay is a legacy-history gap, not evidence that the additive v4 SQL alone is faulty. Resolve the missing baseline through a separately reviewed migration/baseline plan, never by skipping errors.
|
||||
3. `prisma migrate resolve --applied <name>` only records history; it creates no objects. Use it only for a specifically verified, fully matching existing migration and reviewed environment-specific plan. Never mark the whole chain applied or mark missing tables as applied.
|
||||
4. After baseline reconciliation and rehearsal pass, apply reviewed pending migrations through CI/CD only using `prisma migrate deploy`. Verify all nine v4 tables, constraints, migration records and application health before considering the read surface ready.
|
||||
5. Keep v4 mutations, chat and runtime capabilities denied. Retiring legacy mutation routes does not authorize a replacement execution path.
|
||||
|
||||
No deployment, live DDL, baseline resolution or migration SQL change is part of this hardening milestone. Schema rollout remains a separate gate, not full-system completion.
|
||||
|
||||
Rollback is application-first: stop use of the new module while retaining append-only records. Do not drop tables in automated rollback; removal requires separately reviewed archival migration.
|
||||
@@ -1,15 +0,0 @@
|
||||
-- A server-issued attestation is persisted atomically with a DONE transition.
|
||||
CREATE TABLE "task_completion_attestations" (
|
||||
"id" UUID NOT NULL,
|
||||
"task_id" UUID NOT NULL,
|
||||
"artifact_type" VARCHAR(20) NOT NULL,
|
||||
"artifact_id" UUID NOT NULL,
|
||||
"artifact_url" VARCHAR(255) NOT NULL,
|
||||
"verifier" VARCHAR(50) NOT NULL,
|
||||
"verified_at" TIMESTAMPTZ NOT NULL,
|
||||
CONSTRAINT "task_completion_attestations_pkey" PRIMARY KEY ("id"),
|
||||
CONSTRAINT "task_completion_attestations_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "department_tasks"("id") ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT "task_completion_attestations_artifact_type_check" CHECK ("artifact_type" = 'BLOG'),
|
||||
CONSTRAINT "task_completion_attestations_verifier_check" CHECK ("verifier" = 'SERVER_ARTIFACT_VERIFIER')
|
||||
);
|
||||
CREATE INDEX "task_completion_attestations_task_id_idx" ON "task_completion_attestations"("task_id");
|
||||
@@ -0,0 +1,211 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_tasks" (
|
||||
"id" UUID NOT NULL,
|
||||
"key" VARCHAR(120) NOT NULL,
|
||||
"title" VARCHAR(255) NOT NULL,
|
||||
"department" VARCHAR(50) NOT NULL,
|
||||
"state" VARCHAR(40) NOT NULL DEFAULT 'DRAFT',
|
||||
"operation_mode" VARCHAR(30) NOT NULL,
|
||||
"model_tier" VARCHAR(2),
|
||||
"budget_limit_cents" INTEGER NOT NULL,
|
||||
"version" INTEGER NOT NULL DEFAULT 1,
|
||||
"metadata" JSONB NOT NULL DEFAULT '{}',
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMPTZ NOT NULL,
|
||||
|
||||
CONSTRAINT "orchestration_tasks_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_runs" (
|
||||
"id" UUID NOT NULL,
|
||||
"task_id" UUID NOT NULL,
|
||||
"attempt" INTEGER NOT NULL DEFAULT 1,
|
||||
"status" VARCHAR(30) NOT NULL DEFAULT 'PENDING',
|
||||
"commit_sha" VARCHAR(64) NOT NULL,
|
||||
"environment" VARCHAR(50) NOT NULL,
|
||||
"retry_class" VARCHAR(30),
|
||||
"idempotency_key" VARCHAR(150) NOT NULL,
|
||||
"started_at" TIMESTAMPTZ,
|
||||
"finished_at" TIMESTAMPTZ,
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "orchestration_runs_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_artifacts" (
|
||||
"id" UUID NOT NULL,
|
||||
"run_id" UUID NOT NULL,
|
||||
"kind" VARCHAR(50) NOT NULL,
|
||||
"uri" TEXT NOT NULL,
|
||||
"sha256" CHAR(64) NOT NULL,
|
||||
"size_bytes" BIGINT,
|
||||
"metadata" JSONB NOT NULL DEFAULT '{}',
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "orchestration_artifacts_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_attestations" (
|
||||
"id" UUID NOT NULL,
|
||||
"run_id" UUID NOT NULL,
|
||||
"kind" VARCHAR(50) NOT NULL,
|
||||
"subject_hash" CHAR(64) NOT NULL,
|
||||
"predicate" JSONB NOT NULL,
|
||||
"signer" VARCHAR(150) NOT NULL,
|
||||
"signature" TEXT,
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "orchestration_attestations_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_dependencies" (
|
||||
"id" UUID NOT NULL,
|
||||
"task_id" UUID NOT NULL,
|
||||
"depends_on_task_id" UUID NOT NULL,
|
||||
"kind" VARCHAR(30) NOT NULL DEFAULT 'BLOCKS',
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "orchestration_dependencies_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_approval_decisions" (
|
||||
"id" UUID NOT NULL,
|
||||
"task_id" UUID NOT NULL,
|
||||
"gate" INTEGER NOT NULL,
|
||||
"decision" VARCHAR(20) NOT NULL,
|
||||
"actor_id" VARCHAR(100) NOT NULL,
|
||||
"notes" TEXT,
|
||||
"expires_at" TIMESTAMPTZ NOT NULL,
|
||||
"idempotency_key" VARCHAR(150) NOT NULL,
|
||||
"run_id" UUID,
|
||||
"artifact_hash" CHAR(64),
|
||||
"commit_sha" VARCHAR(64),
|
||||
"environment" VARCHAR(50),
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "orchestration_approval_decisions_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_events" (
|
||||
"id" UUID NOT NULL,
|
||||
"task_id" UUID,
|
||||
"event_type" VARCHAR(60) NOT NULL,
|
||||
"from_state" VARCHAR(40),
|
||||
"to_state" VARCHAR(40),
|
||||
"sequence" INTEGER NOT NULL,
|
||||
"actor_id" VARCHAR(100) NOT NULL,
|
||||
"idempotency_key" VARCHAR(150),
|
||||
"payload" JSONB NOT NULL DEFAULT '{}',
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "orchestration_events_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_budget_ledger" (
|
||||
"id" UUID NOT NULL,
|
||||
"task_id" UUID NOT NULL,
|
||||
"amount_cents" INTEGER NOT NULL,
|
||||
"kind" VARCHAR(40) NOT NULL,
|
||||
"idempotency_key" VARCHAR(150) NOT NULL,
|
||||
"actor_id" VARCHAR(100) NOT NULL,
|
||||
"metadata" JSONB NOT NULL DEFAULT '{}',
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "orchestration_budget_ledger_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_kill_switches" (
|
||||
"scope" VARCHAR(80) NOT NULL,
|
||||
"level" VARCHAR(30) NOT NULL,
|
||||
"active" BOOLEAN NOT NULL DEFAULT true,
|
||||
"reason" TEXT NOT NULL,
|
||||
"actor_id" VARCHAR(100) NOT NULL,
|
||||
"version" INTEGER NOT NULL DEFAULT 1,
|
||||
"updated_at" TIMESTAMPTZ NOT NULL,
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "orchestration_kill_switches_pkey" PRIMARY KEY ("scope")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_tasks_key_key" ON "orchestration_tasks"("key");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "orchestration_tasks_state_created_at_idx" ON "orchestration_tasks"("state", "created_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "orchestration_tasks_department_state_idx" ON "orchestration_tasks"("department", "state");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_runs_idempotency_key_key" ON "orchestration_runs"("idempotency_key");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "orchestration_runs_task_id_status_idx" ON "orchestration_runs"("task_id", "status");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_runs_task_id_attempt_key" ON "orchestration_runs"("task_id", "attempt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_artifacts_run_id_sha256_key" ON "orchestration_artifacts"("run_id", "sha256");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_attestations_run_id_kind_subject_hash_signer_key" ON "orchestration_attestations"("run_id", "kind", "subject_hash", "signer");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_dependencies_task_id_depends_on_task_id_key" ON "orchestration_dependencies"("task_id", "depends_on_task_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_approval_decisions_idempotency_key_key" ON "orchestration_approval_decisions"("idempotency_key");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "orchestration_approval_decisions_task_id_gate_created_at_idx" ON "orchestration_approval_decisions"("task_id", "gate", "created_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_events_idempotency_key_key" ON "orchestration_events"("idempotency_key");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "orchestration_events_event_type_created_at_idx" ON "orchestration_events"("event_type", "created_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_events_task_id_sequence_key" ON "orchestration_events"("task_id", "sequence");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_budget_ledger_idempotency_key_key" ON "orchestration_budget_ledger"("idempotency_key");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "orchestration_budget_ledger_task_id_created_at_idx" ON "orchestration_budget_ledger"("task_id", "created_at");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_runs" ADD CONSTRAINT "orchestration_runs_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_artifacts" ADD CONSTRAINT "orchestration_artifacts_run_id_fkey" FOREIGN KEY ("run_id") REFERENCES "orchestration_runs"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_attestations" ADD CONSTRAINT "orchestration_attestations_run_id_fkey" FOREIGN KEY ("run_id") REFERENCES "orchestration_runs"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_dependencies" ADD CONSTRAINT "orchestration_dependencies_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_dependencies" ADD CONSTRAINT "orchestration_dependencies_depends_on_task_id_fkey" FOREIGN KEY ("depends_on_task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_approval_decisions" ADD CONSTRAINT "orchestration_approval_decisions_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_approval_decisions" ADD CONSTRAINT "orchestration_approval_decisions_run_id_fkey" FOREIGN KEY ("run_id") REFERENCES "orchestration_runs"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_events" ADD CONSTRAINT "orchestration_events_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_budget_ledger" ADD CONSTRAINT "orchestration_budget_ledger_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,10 @@
|
||||
-- Immutable evidence and accounting; corrections are new entries.
|
||||
CREATE FUNCTION orchestration_append_only() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN RAISE EXCEPTION 'Orchestration append-only record cannot be changed'; END;
|
||||
$$;
|
||||
CREATE TRIGGER orchestration_budget_immutable BEFORE UPDATE OR DELETE ON orchestration_budget_ledger FOR EACH ROW EXECUTE FUNCTION orchestration_append_only();
|
||||
CREATE TRIGGER orchestration_events_immutable BEFORE UPDATE OR DELETE ON orchestration_events FOR EACH ROW EXECUTE FUNCTION orchestration_append_only();
|
||||
CREATE TRIGGER orchestration_approvals_immutable BEFORE UPDATE OR DELETE ON orchestration_approval_decisions FOR EACH ROW EXECUTE FUNCTION orchestration_append_only();
|
||||
CREATE TRIGGER orchestration_artifacts_immutable BEFORE UPDATE OR DELETE ON orchestration_artifacts FOR EACH ROW EXECUTE FUNCTION orchestration_append_only();
|
||||
CREATE TRIGGER orchestration_attestations_immutable BEFORE UPDATE OR DELETE ON orchestration_attestations FOR EACH ROW EXECUTE FUNCTION orchestration_append_only();
|
||||
ALTER TABLE orchestration_tasks ADD CONSTRAINT orchestration_budget_nonnegative CHECK (budget_limit_cents >= 0);
|
||||
@@ -0,0 +1,10 @@
|
||||
CREATE TABLE prepare_workflow_outbox (
|
||||
id uuid PRIMARY KEY, task_id uuid NOT NULL UNIQUE REFERENCES orchestration_tasks(id) ON DELETE RESTRICT,
|
||||
status varchar(20) NOT NULL DEFAULT 'PENDING' CHECK (status IN ('PENDING','DONE')),
|
||||
attempts integer NOT NULL DEFAULT 0 CHECK (attempts BETWEEN 0 AND 3),
|
||||
lease_owner varchar(100), lease_token uuid, lease_until timestamptz, heartbeat_at timestamptz,
|
||||
run_id uuid REFERENCES orchestration_runs(id) ON DELETE RESTRICT,
|
||||
reservation_id uuid REFERENCES orchestration_budget_ledger(id) ON DELETE RESTRICT,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX prepare_workflow_outbox_status_lease_until_idx ON prepare_workflow_outbox(status,lease_until);
|
||||
@@ -0,0 +1,3 @@
|
||||
-- Scheduling is distinct from immutable approval validity. Existing queues run immediately.
|
||||
ALTER TABLE "prepare_workflow_outbox" ADD COLUMN "not_before" TIMESTAMPTZ;
|
||||
CREATE INDEX "prepare_workflow_outbox_due_idx" ON "prepare_workflow_outbox" ("status", "not_before", "created_at");
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "auth_expires_at" TIMESTAMPTZ, ADD COLUMN IF NOT EXISTS "stage_test_session" VARCHAR(64), ADD COLUMN IF NOT EXISTS "stage_test_generation" UUID;
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
-- Drop legacy governance and orchestration tables
|
||||
DROP TABLE IF EXISTS "prepare_workflow_outbox" CASCADE;
|
||||
DROP TABLE IF EXISTS "orchestration_kill_switches" CASCADE;
|
||||
DROP TABLE IF EXISTS "orchestration_budget_ledger" CASCADE;
|
||||
DROP TABLE IF EXISTS "orchestration_events" CASCADE;
|
||||
DROP TABLE IF EXISTS "orchestration_approval_decisions" CASCADE;
|
||||
DROP TABLE IF EXISTS "orchestration_dependencies" CASCADE;
|
||||
DROP TABLE IF EXISTS "orchestration_attestations" CASCADE;
|
||||
DROP TABLE IF EXISTS "orchestration_artifacts" CASCADE;
|
||||
DROP TABLE IF EXISTS "orchestration_runs" CASCADE;
|
||||
DROP TABLE IF EXISTS "orchestration_tasks" CASCADE;
|
||||
DROP TABLE IF EXISTS "department_tasks" CASCADE;
|
||||
DROP TABLE IF EXISTS "audit_logs" CASCADE;
|
||||
DROP TABLE IF EXISTS "approval_requests" CASCADE;
|
||||
@@ -16,6 +16,9 @@ model User {
|
||||
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()
|
||||
stageTestGeneration String? @map("stage_test_generation") @db.Uuid
|
||||
stageTestSession String? @map("stage_test_session") @db.VarChar(64)
|
||||
walletBalance Decimal @default(0.00) @map("wallet_balance") @db.Decimal(15, 2)
|
||||
charityDonationTotal Decimal @default(0.00) @map("charity_donation_total") @db.Decimal(15, 2)
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
@@ -1017,92 +1020,3 @@ model SmsCampaign {
|
||||
@@map("sms_campaigns")
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// 5. ApprovalRequest (CEO Governance & Decision Gate)
|
||||
// ------------------------------------------------------------------------------
|
||||
model ApprovalRequest {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
department String @db.VarChar(50)
|
||||
category String @db.VarChar(50)
|
||||
title String @db.VarChar(255)
|
||||
payload Json @db.JsonB
|
||||
testContext Json? @map("test_context") @db.JsonB
|
||||
status String @default("PENDING") @db.VarChar(30)
|
||||
ceoNotes String? @map("ceo_notes") @db.Text
|
||||
executedAt DateTime? @map("executed_at") @db.Timestamptz()
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
|
||||
|
||||
@@index([department])
|
||||
@@index([category])
|
||||
@@index([status])
|
||||
@@index([createdAt])
|
||||
@@map("approval_requests")
|
||||
}
|
||||
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// 6. AuditLog (System & Database Changes History)
|
||||
// ------------------------------------------------------------------------------
|
||||
model AuditLog {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
entity String @db.VarChar(50) // e.g. product, blog, order, approval, settings
|
||||
entityId String? @map("entity_id") @db.VarChar(100)
|
||||
action String @db.VarChar(50) // CREATE, UPDATE, DELETE, EXECUTE, APPROVE, REJECT
|
||||
department String? @db.VarChar(50) // devops, seo, content, vet, commerce, pmo
|
||||
actor String @default("SYSTEM") @db.VarChar(100)
|
||||
summary String @db.VarChar(255)
|
||||
oldValues Json? @map("old_values") @db.JsonB
|
||||
newValues Json? @map("new_values") @db.JsonB
|
||||
metadata Json? @db.JsonB
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
|
||||
@@index([entity])
|
||||
@@index([action])
|
||||
@@index([department])
|
||||
@@index([createdAt])
|
||||
@@map("audit_logs")
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// 7. DepartmentTask (Autonomous Corporate Task & Kanban Manager)
|
||||
// ------------------------------------------------------------------------------
|
||||
model TaskCompletionAttestation {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
taskId String @map("task_id") @db.Uuid
|
||||
artifactType String @map("artifact_type") @db.VarChar(20)
|
||||
artifactId String @map("artifact_id") @db.Uuid
|
||||
artifactUrl String @map("artifact_url") @db.VarChar(255)
|
||||
verifier String @db.VarChar(50)
|
||||
verifiedAt DateTime @map("verified_at") @db.Timestamptz()
|
||||
task DepartmentTask @relation(fields: [taskId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([taskId])
|
||||
@@map("task_completion_attestations")
|
||||
}
|
||||
|
||||
model DepartmentTask {
|
||||
completionAttestations TaskCompletionAttestation[]
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
code String @unique @db.VarChar(50)
|
||||
department String @db.VarChar(50) // devops, seo, content, vet, commerce, pmo
|
||||
title String @db.VarChar(255)
|
||||
description String? @db.Text
|
||||
status String @default("BACKLOG") @db.VarChar(30) // BACKLOG, IN_PROGRESS, IN_REVIEW, APPROVED, DEPLOYING, DONE
|
||||
priority String @default("MEDIUM") @db.VarChar(20) // LOW, MEDIUM, HIGH, CRITICAL
|
||||
assignee String? @db.VarChar(100)
|
||||
acceptanceCriteria Json? @map("acceptance_criteria") @db.JsonB
|
||||
executionLogs Json? @map("execution_logs") @db.JsonB
|
||||
deliverableUrl String? @map("deliverable_url") @db.VarChar(255)
|
||||
approvalId String? @map("approval_id") @db.Uuid
|
||||
startedAt DateTime? @map("started_at") @db.Timestamptz()
|
||||
completedAt DateTime? @map("completed_at") @db.Timestamptz()
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
|
||||
|
||||
@@index([department])
|
||||
@@index([status])
|
||||
@@index([priority])
|
||||
@@index([createdAt])
|
||||
@@map("department_tasks")
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { ForbiddenException } from "@nestjs/common";
|
||||
import { AdminService } from "./admin.service";
|
||||
import { AdminController } from "./admin.controller";
|
||||
|
||||
// All identities and credentials here are disposable test fixtures.
|
||||
describe("admin user privilege boundary", () => {
|
||||
let service: any;
|
||||
let prisma: any;
|
||||
const owner = { id: "owner-fixture", role: "SUPER_ADMIN" };
|
||||
const admin = { id: "admin-fixture", role: "ADMIN" };
|
||||
beforeEach(() => {
|
||||
prisma = {
|
||||
user: {
|
||||
findUnique: jest.fn().mockResolvedValue({ id: "target-fixture", role: "SUPER_ADMIN" }),
|
||||
update: jest.fn().mockImplementation(async ({ data }) => ({ role: "SUPER_ADMIN", ...data })),
|
||||
create: jest.fn(),
|
||||
},
|
||||
walletTransaction: { create: jest.fn() },
|
||||
$transaction: jest.fn(),
|
||||
};
|
||||
service = new AdminService(prisma, {} as never, {} as never);
|
||||
});
|
||||
it("allows an authenticated superadmin password-only edit without changing the exact role", async () => {
|
||||
const result = await service.updateUser("target-fixture", { password: "Fixture-only-123" }, owner);
|
||||
expect(result.role).toBe("SUPER_ADMIN");
|
||||
expect(prisma.user.update.mock.calls[0][0].data).not.toHaveProperty("role");
|
||||
});
|
||||
it.each(["ADMIN", "Admin", "User_PetOwner"])("denies %s assigning superadmin on create", async role => {
|
||||
prisma.user.findUnique.mockResolvedValue(null);
|
||||
await expect(service.createUser({ firstName: "Test", lastName: "Fixture", mobile: "09120000001", role: "SUPER_ADMIN" }, { id: "actor", role })).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(prisma.user.create).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each(["SUPER_ADMIN", "super-admin", "AdminSuper"])("denies ordinary admin escalation to %s", async role => {
|
||||
prisma.user.findUnique.mockResolvedValue({ id: admin.id, role: "Admin" });
|
||||
await expect(service.updateUser(admin.id, { role }, admin)).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(prisma.user.update).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each([{ password: "Fixture-only-123" }, { email: "fixture@example.test" }, { mobile: "09120000001" }, { role: "Admin" }, { walletBalance: 1 }, { firstName: "Changed" }])("denies ordinary admin editing superadmin", async dto => {
|
||||
await expect(service.updateUser("target-fixture", dto, admin)).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(prisma.user.update).not.toHaveBeenCalled();
|
||||
});
|
||||
it("denies alternate role endpoint revocation", async () => {
|
||||
await expect(service.updateUserRole("target-fixture", "Admin", admin)).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(prisma.user.update).not.toHaveBeenCalled();
|
||||
});
|
||||
it("denies deleting superadmin", async () => {
|
||||
await expect(service.deleteUser("target-fixture", admin)).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(prisma.$transaction).not.toHaveBeenCalled();
|
||||
});
|
||||
it("denies changing superadmin wallet", async () => {
|
||||
await expect(service.adjustUserWallet("target-fixture", 1, "deposit", "fixture", admin)).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(prisma.walletTransaction.create).not.toHaveBeenCalled();
|
||||
});
|
||||
it("accepts ADMIN alias for ordinary CRUD and authorized promotion/revocation", async () => {
|
||||
prisma.user.findUnique.mockResolvedValue({ id: "target-fixture", role: "User_PetOwner" });
|
||||
await service.updateUser("target-fixture", { role: "ADMIN" }, admin);
|
||||
await service.updateUser("target-fixture", { role: "SUPER_ADMIN" }, owner);
|
||||
prisma.user.findUnique.mockResolvedValue({ id: "target-fixture", role: "SUPER_ADMIN" });
|
||||
await service.updateUserRole("target-fixture", "Admin", owner);
|
||||
expect(prisma.user.update).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
it("fails closed without authenticated actor or with API key superadmin", async () => {
|
||||
await expect(service.updateUser("target-fixture", { role: "Admin" })).rejects.toBeInstanceOf(ForbiddenException);
|
||||
await expect(service.updateUser("target-fixture", { role: "Admin" }, { ...owner, isApiKey: true })).rejects.toBeInstanceOf(ForbiddenException);
|
||||
});
|
||||
it("controller forwards authenticated request identity, not DTO identity", async () => {
|
||||
const svc = { updateUser: jest.fn().mockResolvedValue({}) };
|
||||
const controller: any = new AdminController(svc as never, {} as never);
|
||||
const dto = { firstName: "Test" };
|
||||
await controller.updateUser("target-fixture", dto, { user: admin });
|
||||
expect(svc.updateUser).toHaveBeenCalledWith("target-fixture", dto, admin);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
import { Test } from "@nestjs/testing";
|
||||
import { ExecutionContext } from "@nestjs/common";
|
||||
import { firstValueFrom, of } from "rxjs";
|
||||
import { AdminService } from "./admin.service";
|
||||
import { AdminController } from "./admin.controller";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
import { RedisService } from "../redis/redis.service";
|
||||
import { RevalidationService } from "../common/revalidation/revalidation.service";
|
||||
import { DecimalInterceptor } from "../common/interceptors/decimal.interceptor";
|
||||
import { Prisma } from "@prisma/client";
|
||||
|
||||
describe("admin users list contract", () => {
|
||||
const prisma = { user: { findMany: jest.fn(), count: jest.fn() } };
|
||||
let service: AdminService;
|
||||
|
||||
beforeEach(async () => {
|
||||
jest.clearAllMocks();
|
||||
const module = await Test.createTestingModule({
|
||||
providers: [
|
||||
AdminService,
|
||||
{ provide: PrismaService, useValue: prisma },
|
||||
{ provide: RedisService, useValue: {} },
|
||||
{ provide: RevalidationService, useValue: {} },
|
||||
],
|
||||
}).compile();
|
||||
service = module.get(AdminService);
|
||||
});
|
||||
|
||||
it("returns only allowlisted list fields with aggregates through the controller and decimal interceptor", async () => {
|
||||
// Deliberately return extra fields even if the query selects safely.
|
||||
prisma.user.findMany.mockResolvedValue([{
|
||||
id: "fixture-user", firstName: "Fixture", lastName: "User",
|
||||
mobile: "fixture-mobile", email: null, role: "ADMIN",
|
||||
walletBalance: new Prisma.Decimal(0), charityDonationTotal: new Prisma.Decimal(12),
|
||||
createdAt: new Date("2026-01-01T00:00:00Z"),
|
||||
password: "test-only-password-hash", passwordHash: "test-only-hash",
|
||||
refreshToken: "test-only-token", futureSecret: "must-not-leak",
|
||||
walletTransactions: [{ transactionReference: "private-reference" }],
|
||||
addresses: [], orders: [{ totalAmount: new Prisma.Decimal(100) }, { totalAmount: 25 }],
|
||||
_count: { orders: 3, reviews: 2, blogComments: 1, pets: 4 },
|
||||
}]);
|
||||
prisma.user.count.mockResolvedValue(11);
|
||||
const controller = new AdminController(service, {} as never);
|
||||
const result = await controller.getUsers({ page: 2, limit: 10 });
|
||||
const body = await firstValueFrom(new DecimalInterceptor().intercept({} as ExecutionContext, { handle: () => of(result) }));
|
||||
expect(body).toEqual({
|
||||
data: [{
|
||||
id: "fixture-user", firstName: "Fixture", lastName: "User", mobile: "fixture-mobile",
|
||||
email: null, role: "ADMIN", walletBalance: "0", charityDonationTotal: "12",
|
||||
createdAt: new Date("2026-01-01T00:00:00Z"), addresses: [],
|
||||
totalSpent: 125, ordersCount: 3, reviewsCount: 3, petsCount: 4,
|
||||
}],
|
||||
meta: { total: 11, page: 2, limit: 10, lastPage: 2 },
|
||||
});
|
||||
const query = prisma.user.findMany.mock.calls[0][0];
|
||||
expect(query.select).toBeDefined();
|
||||
expect(query.select.password).toBeUndefined();
|
||||
expect(query.include).toBeUndefined();
|
||||
expect(query.skip).toBe(10);
|
||||
});
|
||||
|
||||
it("preserves the empty paginated list contract and filters", async () => {
|
||||
prisma.user.findMany.mockResolvedValue([]);
|
||||
prisma.user.count.mockResolvedValue(0);
|
||||
expect(await service.getUsers({ search: "fixture", role: "ADMIN" })).toEqual({
|
||||
data: [], meta: { total: 0, page: 1, limit: 10, lastPage: 1 },
|
||||
});
|
||||
expect(prisma.user.findMany).toHaveBeenCalledWith(expect.objectContaining({
|
||||
where: expect.objectContaining({ role: "ADMIN", OR: expect.any(Array) }),
|
||||
}));
|
||||
});
|
||||
});
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
Body,
|
||||
Param,
|
||||
Query,
|
||||
Req,
|
||||
UseGuards,
|
||||
BadRequestException,
|
||||
} from "@nestjs/common";
|
||||
@@ -27,6 +28,7 @@ import {
|
||||
} from "@nestjs/swagger";
|
||||
|
||||
import { CreateUserDto, UpdateUserDto } from "./dto/user.dto";
|
||||
import type { UserAdminActor } from "./user-role-policy";
|
||||
import { SettingsService } from "../settings/settings.service";
|
||||
|
||||
import { RolesGuard } from "../common/guards/roles.guard";
|
||||
@@ -62,8 +64,8 @@ export class AdminController {
|
||||
|
||||
@Post("users")
|
||||
@ApiOperation({ summary: "ایجاد کاربر جدید توسط ادمین" })
|
||||
async createUser(@Body() dto: CreateUserDto) {
|
||||
const user = await this.adminService.createUser(dto);
|
||||
async createUser(@Body() dto: CreateUserDto, @Req() req?: { user?: UserAdminActor }) {
|
||||
const user = await this.adminService.createUser(dto, req?.user);
|
||||
return {
|
||||
success: true,
|
||||
message: "کاربر جدید با موفقیت ایجاد شد",
|
||||
@@ -80,8 +82,8 @@ export class AdminController {
|
||||
|
||||
@Put("users/:id")
|
||||
@ApiOperation({ summary: "ویرایش مشخصات کامل کاربر" })
|
||||
async updateUser(@Param("id") id: string, @Body() dto: UpdateUserDto) {
|
||||
const user = await this.adminService.updateUser(id, dto);
|
||||
async updateUser(@Param("id") id: string, @Body() dto: UpdateUserDto, @Req() req?: { user?: UserAdminActor }) {
|
||||
const user = await this.adminService.updateUser(id, dto, req?.user);
|
||||
return {
|
||||
success: true,
|
||||
message: "اطلاعات کاربر با موفقیت ویرایش شد",
|
||||
@@ -91,8 +93,8 @@ export class AdminController {
|
||||
|
||||
@Delete("users/:id")
|
||||
@ApiOperation({ summary: "حذف کاربر و دادههای مرتبط" })
|
||||
async deleteUser(@Param("id") id: string) {
|
||||
await this.adminService.deleteUser(id);
|
||||
async deleteUser(@Param("id") id: string, @Req() req?: { user?: UserAdminActor }) {
|
||||
await this.adminService.deleteUser(id, req?.user);
|
||||
return {
|
||||
success: true,
|
||||
message: "کاربر با موفقیت از سیستم حذف شد",
|
||||
@@ -101,8 +103,8 @@ export class AdminController {
|
||||
|
||||
@Put("users/:id/role")
|
||||
@ApiOperation({ summary: "تغییر نقش کاربر" })
|
||||
async updateUserRole(@Param("id") id: string, @Body("role") role: string) {
|
||||
const user = await this.adminService.updateUserRole(id, role);
|
||||
async updateUserRole(@Param("id") id: string, @Body("role") role: string, @Req() req?: { user?: UserAdminActor }) {
|
||||
const user = await this.adminService.updateUserRole(id, role, req?.user);
|
||||
return { success: true, data: user };
|
||||
}
|
||||
|
||||
@@ -113,6 +115,7 @@ export class AdminController {
|
||||
@Body("amount") amount: number,
|
||||
@Body("type") type: "deposit" | "withdrawal" | "refund",
|
||||
@Body("description") description?: string,
|
||||
@Req() req?: { user?: UserAdminActor },
|
||||
) {
|
||||
const numAmount = Number(amount);
|
||||
if (!numAmount || isNaN(numAmount) || numAmount <= 0) {
|
||||
@@ -130,6 +133,7 @@ export class AdminController {
|
||||
numAmount,
|
||||
type,
|
||||
description,
|
||||
req?.user,
|
||||
);
|
||||
return {
|
||||
success: true,
|
||||
|
||||
@@ -21,9 +21,6 @@ import { CompetitorPricingController } from "./competitor-pricing.controller";
|
||||
import { B2BLeadsController } from "./b2b-leads.controller";
|
||||
import { PricingSuggestionsController } from "./pricing-suggestions.controller";
|
||||
import { SmsCampaignsController } from "./sms-campaigns.controller";
|
||||
import { ApprovalsController } from "./approvals.controller";
|
||||
import { AuditLogsController } from "./audit-logs.controller";
|
||||
import { DepartmentTasksController } from "./department-tasks.controller";
|
||||
import { PrismaModule } from "../prisma/prisma.module";
|
||||
import { RedisModule } from "../redis/redis.module";
|
||||
import { SettingsModule } from "../settings/settings.module";
|
||||
@@ -46,9 +43,6 @@ import { SupportChatAnalyticsService } from "./support-chat-analytics.service";
|
||||
B2BLeadsController,
|
||||
PricingSuggestionsController,
|
||||
SmsCampaignsController,
|
||||
ApprovalsController,
|
||||
AuditLogsController,
|
||||
DepartmentTasksController,
|
||||
SupportChatAnalyticsController,
|
||||
],
|
||||
providers: [
|
||||
|
||||
@@ -61,15 +61,10 @@ export class CouponInput {
|
||||
targets?: CouponTargetInput[];
|
||||
}
|
||||
|
||||
const ALLOWED_USER_ROLES = [
|
||||
"User_PetOwner",
|
||||
"User_Vet",
|
||||
"User_Clinic",
|
||||
"User_PetShop",
|
||||
"Customer",
|
||||
"Admin",
|
||||
"SUPER_ADMIN",
|
||||
];
|
||||
import { ALLOWED_USER_ROLES, assertUserMutationAllowed } from "./user-role-policy";
|
||||
import type { UserAdminActor } from "./user-role-policy";
|
||||
import { randomUUID } from "crypto";
|
||||
import { authorizeStageSession, STAGE_TEST_ID, STAGE_TEST_EMAIL, STAGE_TEST_MOBILE } from "../auth/stage-test-principal";
|
||||
|
||||
@Injectable()
|
||||
export class AdminService {
|
||||
@@ -168,12 +163,17 @@ export class AdminService {
|
||||
skip,
|
||||
take: limit,
|
||||
orderBy: { [sortField]: sortDirection },
|
||||
include: {
|
||||
select: {
|
||||
id: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
mobile: true,
|
||||
email: true,
|
||||
role: true,
|
||||
walletBalance: true,
|
||||
charityDonationTotal: true,
|
||||
createdAt: true,
|
||||
addresses: true,
|
||||
walletTransactions: {
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 20,
|
||||
},
|
||||
orders: {
|
||||
where: { status: { not: "CANCELLED" } },
|
||||
select: { totalAmount: true },
|
||||
@@ -197,9 +197,19 @@ export class AdminService {
|
||||
(acc, curr) => acc + (Number(curr.totalAmount) || 0),
|
||||
0,
|
||||
) || 0;
|
||||
const { orders: _orders, ...rest } = u;
|
||||
// Explicit response allowlist: never expose authentication fields or
|
||||
// new model columns implicitly through this administrative list.
|
||||
return {
|
||||
...rest,
|
||||
id: u.id,
|
||||
firstName: u.firstName,
|
||||
lastName: u.lastName,
|
||||
mobile: u.mobile,
|
||||
email: u.email,
|
||||
role: u.role,
|
||||
walletBalance: u.walletBalance,
|
||||
charityDonationTotal: u.charityDonationTotal,
|
||||
createdAt: u.createdAt,
|
||||
addresses: u.addresses,
|
||||
totalSpent,
|
||||
ordersCount: u._count?.orders || 0,
|
||||
reviewsCount: (u._count?.reviews || 0) + (u._count?.blogComments || 0),
|
||||
@@ -227,7 +237,12 @@ export class AdminService {
|
||||
return user;
|
||||
}
|
||||
|
||||
async createUser(dto: CreateUserDto) {
|
||||
async createUser(dto: CreateUserDto, actor?: UserAdminActor) {
|
||||
assertUserMutationAllowed(actor, undefined, dto.role);
|
||||
return this.persistUser(dto);
|
||||
}
|
||||
|
||||
private async persistUser(dto: CreateUserDto, stage?: { session: string; expiresAt: Date; generation?: string }) {
|
||||
const mobile = normalizeMobile(dto.mobile);
|
||||
const existingMobile = await this.prisma.user.findUnique({
|
||||
where: { mobile },
|
||||
@@ -260,6 +275,7 @@ export class AdminService {
|
||||
|
||||
return this.prisma.user.create({
|
||||
data: {
|
||||
...(stage ? { id: STAGE_TEST_ID, stageTestGeneration:stage.generation || randomUUID(), stageTestSession: stage.session, authExpiresAt: stage.expiresAt } : {}),
|
||||
firstName: dto.firstName.trim(),
|
||||
lastName: dto.lastName.trim(),
|
||||
mobile,
|
||||
@@ -274,7 +290,30 @@ export class AdminService {
|
||||
});
|
||||
}
|
||||
|
||||
async updateUser(id: string, dto: UpdateUserDto) {
|
||||
// Explicit CI seed authority, NOT a fabricated SUPER_ADMIN actor. Not controller-exposed.
|
||||
async provisionStageTestPrincipal(env: NodeJS.ProcessEnv, sha: string, password: string) {
|
||||
const grant = authorizeStageSession(env, sha);
|
||||
const existing = await this.prisma.user.findFirst({where:{OR:[{id:STAGE_TEST_ID},{email:STAGE_TEST_EMAIL},{mobile:STAGE_TEST_MOBILE}]}});
|
||||
if (existing) {
|
||||
if (existing.id !== STAGE_TEST_ID || existing.email !== STAGE_TEST_EMAIL || existing.mobile !== STAGE_TEST_MOBILE || existing.stageTestSession !== grant.session || (env.STAGE_TEST_GENERATION && existing.stageTestGeneration !== env.STAGE_TEST_GENERATION) || existing.role !== 'SUPER_ADMIN' || !existing.authExpiresAt || existing.authExpiresAt.getTime() <= Date.now() || !await bcrypt.compare(password, existing.password || '')) throw new Error('Refusing existing or unowned principal');
|
||||
return existing; // Never renew TTL on retry.
|
||||
}
|
||||
if (password.length < 32) throw new Error('Server generated secret required');
|
||||
return this.persistUser({firstName:'Stage',lastName:'CI independent reviewer',email:STAGE_TEST_EMAIL,mobile:STAGE_TEST_MOBILE,role:'SUPER_ADMIN',password}, {session:grant.session,expiresAt:new Date(Date.now()+grant.ttl*1000),generation:env.STAGE_TEST_GENERATION});
|
||||
}
|
||||
|
||||
async cleanupStageTestPrincipal(env: NodeJS.ProcessEnv, sha: string, onRevoked: () => void = () => undefined) {
|
||||
const grant = authorizeStageSession(env, sha);
|
||||
const existing = await this.prisma.user.findUnique({where:{id:STAGE_TEST_ID}});
|
||||
if (!existing) { onRevoked(); return; }
|
||||
if (existing.email !== STAGE_TEST_EMAIL || existing.mobile !== STAGE_TEST_MOBILE || existing.stageTestSession !== grant.session || !existing.authExpiresAt || (env.STAGE_TEST_GENERATION && existing.stageTestGeneration !== env.STAGE_TEST_GENERATION)) throw new Error('Refusing unowned principal cleanup');
|
||||
// Revoke before relational cleanup; failed cleanup cannot leave valid tokens.
|
||||
await this.prisma.user.update({where:{id:STAGE_TEST_ID,stageTestSession:grant.session,stageTestGeneration:existing.stageTestGeneration},data:{authExpiresAt:new Date(0),password:''}});
|
||||
onRevoked();
|
||||
return this.deleteUserRecords(STAGE_TEST_ID, {session:grant.session,generation:existing.stageTestGeneration});
|
||||
}
|
||||
|
||||
async updateUser(id: string, dto: UpdateUserDto, actor?: UserAdminActor) {
|
||||
if (id === "12345678-1234-1234-1234-123456789012") {
|
||||
throw new BadRequestException(
|
||||
"امکان ویرایش حساب ادمین پیشفرض وجود ندارد",
|
||||
@@ -286,6 +325,8 @@ export class AdminService {
|
||||
throw new NotFoundException(`کاربری با شناسه ${id} یافت نشد`);
|
||||
}
|
||||
|
||||
assertUserMutationAllowed(actor, user.role, dto.role);
|
||||
|
||||
const normalizedMobile = dto.mobile
|
||||
? normalizeMobile(dto.mobile)
|
||||
: undefined;
|
||||
@@ -340,17 +381,11 @@ export class AdminService {
|
||||
});
|
||||
}
|
||||
|
||||
async updateUserRole(id: string, role: string) {
|
||||
if (!ALLOWED_USER_ROLES.includes(role)) {
|
||||
throw new BadRequestException("نقش کاربری مشخص شده نامعتبر است");
|
||||
}
|
||||
return this.prisma.user.update({
|
||||
where: { id },
|
||||
data: { role },
|
||||
});
|
||||
async updateUserRole(id: string, role: string, actor?: UserAdminActor) {
|
||||
return this.updateUser(id, { role }, actor);
|
||||
}
|
||||
|
||||
async deleteUser(id: string) {
|
||||
async deleteUser(id: string, actor?: UserAdminActor) {
|
||||
if (id === "12345678-1234-1234-1234-123456789012") {
|
||||
throw new BadRequestException("امکان حذف حساب ادمین پیشفرض وجود ندارد");
|
||||
}
|
||||
@@ -360,7 +395,17 @@ export class AdminService {
|
||||
throw new NotFoundException(`کاربری با شناسه ${id} یافت نشد`);
|
||||
}
|
||||
|
||||
assertUserMutationAllowed(actor, user.role);
|
||||
|
||||
return this.deleteUserRecords(id);
|
||||
}
|
||||
|
||||
private async deleteUserRecords(id: string, stage?: {session:string; generation:string|null}) {
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
if (stage) {
|
||||
// Acquire the row lock with an exact fence before deleting any related rows.
|
||||
await tx.user.update({where:{id,stageTestSession:stage.session,stageTestGeneration:stage.generation},data:{authExpiresAt:new Date(0),password:''}});
|
||||
}
|
||||
await tx.userAddress.deleteMany({ where: { userId: id } });
|
||||
await tx.walletTransaction.deleteMany({ where: { userId: id } });
|
||||
await tx.pet.deleteMany({ where: { userId: id } });
|
||||
@@ -1397,12 +1442,15 @@ export class AdminService {
|
||||
amount: number,
|
||||
type: "deposit" | "withdrawal" | "refund",
|
||||
description?: string,
|
||||
actor?: UserAdminActor,
|
||||
) {
|
||||
const user = await this.prisma.user.findUnique({ where: { id: userId } });
|
||||
if (!user) {
|
||||
throw new NotFoundException(`کاربری با شناسه ${userId} یافت نشد.`);
|
||||
}
|
||||
|
||||
assertUserMutationAllowed(actor, user.role);
|
||||
|
||||
const transaction = await this.prisma.walletTransaction.create({
|
||||
data: {
|
||||
userId,
|
||||
|
||||
@@ -1,271 +0,0 @@
|
||||
import { Test, TestingModule } from "@nestjs/testing";
|
||||
import { BadRequestException, NotFoundException } from "@nestjs/common";
|
||||
import { ApprovalsController } from "./approvals.controller";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
|
||||
describe("ApprovalsController", () => {
|
||||
let controller: ApprovalsController;
|
||||
let prisma: {
|
||||
approvalRequest: {
|
||||
findUnique: jest.Mock;
|
||||
findMany: jest.Mock;
|
||||
count: jest.Mock;
|
||||
create: jest.Mock;
|
||||
update: jest.Mock;
|
||||
delete: jest.Mock;
|
||||
};
|
||||
departmentTask: {
|
||||
findFirst: jest.Mock;
|
||||
findMany: jest.Mock;
|
||||
create: jest.Mock;
|
||||
update: jest.Mock;
|
||||
deleteMany: jest.Mock;
|
||||
updateMany: jest.Mock;
|
||||
};
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
prisma = {
|
||||
approvalRequest: {
|
||||
findUnique: jest.fn(),
|
||||
findMany: jest.fn(),
|
||||
count: jest.fn(),
|
||||
create: jest.fn(),
|
||||
update: jest.fn(),
|
||||
delete: jest.fn(),
|
||||
},
|
||||
departmentTask: {
|
||||
findFirst: jest.fn(),
|
||||
findMany: jest.fn(),
|
||||
create: jest.fn(),
|
||||
update: jest.fn(),
|
||||
deleteMany: jest.fn(),
|
||||
updateMany: jest.fn(),
|
||||
},
|
||||
};
|
||||
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [ApprovalsController],
|
||||
providers: [
|
||||
{
|
||||
provide: PrismaService,
|
||||
useValue: prisma,
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<ApprovalsController>(ApprovalsController);
|
||||
});
|
||||
|
||||
describe("decide - B2B_SUPPLIER_STRATEGY approval separation", () => {
|
||||
it("B2B_SUPPLIER_STRATEGY approval must not create digital task nor set executedAt as physical action", async () => {
|
||||
const approvalId = "b2b-strategy-uuid-1";
|
||||
const approvalItem = {
|
||||
id: approvalId,
|
||||
department: "B2B",
|
||||
category: "B2B_SUPPLIER_STRATEGY",
|
||||
title: "[طرح استراتژیک تامینکننده] توسعه شبکه کلینیکی آلمان",
|
||||
payload: { target: "German Suppliers", tier: "Direct" },
|
||||
status: "PENDING",
|
||||
};
|
||||
|
||||
prisma.approvalRequest.findUnique.mockResolvedValue(approvalItem);
|
||||
prisma.approvalRequest.update.mockResolvedValue({
|
||||
...approvalItem,
|
||||
status: "APPROVED",
|
||||
ceoNotes: "موافقت با مذاکره اولیه",
|
||||
});
|
||||
prisma.departmentTask.findFirst.mockResolvedValue(null);
|
||||
|
||||
const result = await controller.decide(approvalId, {
|
||||
decision: "APPROVED",
|
||||
ceoNotes: "موافقت با مذاکره اولیه",
|
||||
});
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(prisma.approvalRequest.update).toHaveBeenCalledWith({
|
||||
where: { id: approvalId },
|
||||
data: expect.objectContaining({
|
||||
status: "APPROVED",
|
||||
ceoNotes: "موافقت با مذاکره اولیه",
|
||||
}),
|
||||
});
|
||||
|
||||
// Verify executedAt is NOT set as physical action
|
||||
const updateCall = prisma.approvalRequest.update.mock.calls[0][0];
|
||||
expect(updateCall.data.executedAt).toBeUndefined();
|
||||
|
||||
// Verify NO digital task is created in departmentTask queue
|
||||
expect(prisma.departmentTask.create).not.toHaveBeenCalled();
|
||||
expect(prisma.departmentTask.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("B2B_SUPPLIER_STRATEGY approval must not requeue existing digital task", async () => {
|
||||
const approvalId = "b2b-strategy-uuid-2";
|
||||
const approvalItem = {
|
||||
id: approvalId,
|
||||
department: "B2B",
|
||||
category: "B2B_SUPPLIER_STRATEGY",
|
||||
title: "[طرح استراتژیک تامینکننده] پکیج نمونه دارویی",
|
||||
payload: {},
|
||||
status: "PENDING",
|
||||
};
|
||||
|
||||
prisma.approvalRequest.findUnique.mockResolvedValue(approvalItem);
|
||||
prisma.approvalRequest.update.mockResolvedValue({
|
||||
...approvalItem,
|
||||
status: "APPROVED",
|
||||
});
|
||||
prisma.departmentTask.findFirst.mockResolvedValue({
|
||||
id: "task-existing-1",
|
||||
status: "BACKLOG",
|
||||
title: "Legacy task",
|
||||
});
|
||||
|
||||
const result = await controller.decide(approvalId, {
|
||||
decision: "APPROVED",
|
||||
});
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
// Ensure existing task was NOT updated or requeued to TODO
|
||||
expect(prisma.departmentTask.update).not.toHaveBeenCalled();
|
||||
expect(prisma.departmentTask.create).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("decide - SEO approval actionable digital task", () => {
|
||||
it("SEO approval creates actionable digital task in TODO", async () => {
|
||||
const approvalId = "seo-approval-uuid-1";
|
||||
const approvalItem = {
|
||||
id: approvalId,
|
||||
department: "SEO",
|
||||
category: "SEO",
|
||||
title: "بهینهسازی متاتگهای صفحات دستهبندی گربه",
|
||||
payload: { targetUrl: "/category/cat-food" },
|
||||
status: "PENDING",
|
||||
};
|
||||
|
||||
prisma.approvalRequest.findUnique.mockResolvedValue(approvalItem);
|
||||
prisma.approvalRequest.update.mockResolvedValue({
|
||||
...approvalItem,
|
||||
status: "APPROVED",
|
||||
ceoNotes: "در اولویت سئو قرار گیرد",
|
||||
});
|
||||
prisma.departmentTask.findFirst.mockResolvedValue(null);
|
||||
prisma.departmentTask.create.mockResolvedValue({
|
||||
id: "new-task-uuid",
|
||||
code: "TSK-892110",
|
||||
department: "SEO",
|
||||
title: approvalItem.title,
|
||||
status: "TODO",
|
||||
priority: "HIGH",
|
||||
assignee: "AI_AGENT",
|
||||
approvalId: approvalId,
|
||||
});
|
||||
|
||||
const result = await controller.decide(approvalId, {
|
||||
decision: "APPROVED",
|
||||
ceoNotes: "در اولویت سئو قرار گیرد",
|
||||
});
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(prisma.approvalRequest.update).toHaveBeenCalledWith({
|
||||
where: { id: approvalId },
|
||||
data: expect.objectContaining({
|
||||
status: "APPROVED",
|
||||
ceoNotes: "در اولویت سئو قرار گیرد",
|
||||
}),
|
||||
});
|
||||
|
||||
// Digital task MUST be created with status TODO
|
||||
expect(prisma.departmentTask.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({
|
||||
department: "SEO",
|
||||
title: approvalItem.title,
|
||||
status: "TODO",
|
||||
priority: "HIGH",
|
||||
assignee: "AI_AGENT",
|
||||
approvalId: approvalId,
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
it("SEO approval requeues existing task to TODO when existing task found", async () => {
|
||||
const approvalId = "seo-approval-uuid-2";
|
||||
const approvalItem = {
|
||||
id: approvalId,
|
||||
department: "SEO",
|
||||
category: "SEO",
|
||||
title: "بررسی کنیبان سئو مقاله تغذیه سگ",
|
||||
payload: {},
|
||||
status: "PENDING",
|
||||
};
|
||||
const existingTask = {
|
||||
id: "existing-task-99",
|
||||
code: "TSK-112233",
|
||||
status: "IN_REVIEW",
|
||||
description: "Initial draft",
|
||||
approvalId: approvalId,
|
||||
};
|
||||
|
||||
prisma.approvalRequest.findUnique.mockResolvedValue(approvalItem);
|
||||
prisma.approvalRequest.update.mockResolvedValue({
|
||||
...approvalItem,
|
||||
status: "APPROVED",
|
||||
ceoNotes: "تایید نهایی جهت اقدام",
|
||||
});
|
||||
prisma.departmentTask.findFirst.mockResolvedValue(existingTask);
|
||||
prisma.departmentTask.update.mockResolvedValue({
|
||||
...existingTask,
|
||||
status: "TODO",
|
||||
});
|
||||
|
||||
const result = await controller.decide(approvalId, {
|
||||
decision: "APPROVED",
|
||||
ceoNotes: "تایید نهایی جهت اقدام",
|
||||
});
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(prisma.departmentTask.update).toHaveBeenCalledWith({
|
||||
where: { id: existingTask.id },
|
||||
data: expect.objectContaining({
|
||||
status: "TODO",
|
||||
}),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("decide - rejection handling", () => {
|
||||
it("handles REJECTED decision cleanly without deleting approval audit history", async () => {
|
||||
const approvalId = "approval-reject-uuid";
|
||||
const approvalItem = {
|
||||
id: approvalId,
|
||||
department: "SEO",
|
||||
category: "SEO",
|
||||
title: "تغییر ساختار URL",
|
||||
status: "PENDING",
|
||||
};
|
||||
|
||||
prisma.approvalRequest.findUnique.mockResolvedValue(approvalItem);
|
||||
prisma.approvalRequest.update.mockResolvedValue({
|
||||
...approvalItem,
|
||||
status: "REJECTED",
|
||||
ceoNotes: "ریسک بالای افت رتبه سئو",
|
||||
});
|
||||
|
||||
const result = await controller.decide(approvalId, {
|
||||
decision: "REJECTED",
|
||||
ceoNotes: "ریسک بالای افت رتبه سئو",
|
||||
});
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(prisma.approvalRequest.update).toHaveBeenCalledWith({
|
||||
where: { id: approvalId },
|
||||
data: expect.objectContaining({
|
||||
status: "REJECTED",
|
||||
ceoNotes: "ریسک بالای افت رتبه سئو",
|
||||
}),
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,264 +0,0 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Put,
|
||||
Delete,
|
||||
Body,
|
||||
Param,
|
||||
Query,
|
||||
UseGuards,
|
||||
NotFoundException,
|
||||
BadRequestException,
|
||||
} from "@nestjs/common";
|
||||
import { ApiTags, ApiBearerAuth, ApiOperation } from "@nestjs/swagger";
|
||||
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
|
||||
import { RolesGuard } from "../common/guards/roles.guard";
|
||||
import { Roles } from "../common/decorators/roles.decorator";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
import {
|
||||
CreateApprovalRequestDto,
|
||||
DecideApprovalDto,
|
||||
QueryApprovalDto,
|
||||
} from "./dto/approval-request.dto";
|
||||
|
||||
@ApiTags("Admin - CEO Approvals & Governance")
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles("Admin", "SUPER_ADMIN")
|
||||
@Controller("admin/approvals")
|
||||
export class ApprovalsController {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: "لیست موارد کارتابل تاییدات مدیریت" })
|
||||
async findAll(@Query() query: QueryApprovalDto) {
|
||||
const page = Number(query.page) || 1;
|
||||
const limit = Number(query.limit) || 100;
|
||||
const skip = (page - 1) * limit;
|
||||
|
||||
const where: any = {};
|
||||
if (query.department) where.department = query.department;
|
||||
if (query.category) where.category = query.category;
|
||||
if (query.status) where.status = query.status;
|
||||
|
||||
const [total, items, pendingCount] = await Promise.all([
|
||||
(this.prisma as any).approvalRequest.count({ where }),
|
||||
(this.prisma as any).approvalRequest.findMany({
|
||||
where,
|
||||
skip,
|
||||
take: limit,
|
||||
orderBy: { createdAt: "desc" },
|
||||
}),
|
||||
(this.prisma as any).approvalRequest.count({
|
||||
where: { status: "PENDING" },
|
||||
}),
|
||||
]);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: items,
|
||||
meta: {
|
||||
total,
|
||||
page,
|
||||
limit,
|
||||
totalPages: Math.ceil(total / limit),
|
||||
pendingCount,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@Get(":id")
|
||||
@ApiOperation({ summary: "دریافت جزییات یک آیتم کارتابل" })
|
||||
async findOne(@Param("id") id: string) {
|
||||
const item = await (this.prisma as any).approvalRequest.findUnique({
|
||||
where: { id },
|
||||
});
|
||||
if (!item) {
|
||||
throw new NotFoundException(`Approval request ${id} not found`);
|
||||
}
|
||||
return { success: true, data: item };
|
||||
}
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: "ثبت آیتم جدید جهت تایید مدیریت (از طرف سیستم یا دپارتمانها)" })
|
||||
async create(@Body() dto: CreateApprovalRequestDto) {
|
||||
const item = await (this.prisma as any).approvalRequest.create({
|
||||
data: {
|
||||
department: dto.department,
|
||||
category: dto.category,
|
||||
title: dto.title,
|
||||
payload: dto.payload,
|
||||
testContext: dto.testContext || {},
|
||||
status: "PENDING",
|
||||
},
|
||||
});
|
||||
return { success: true, data: item };
|
||||
}
|
||||
|
||||
@Post(":id/test")
|
||||
@ApiOperation({ summary: "اجرای شبیهسازی تست زنده برای آیتم کارتابل" })
|
||||
async runTestSimulation(@Param("id") id: string) {
|
||||
const item = await (this.prisma as any).approvalRequest.findUnique({
|
||||
where: { id },
|
||||
});
|
||||
if (!item) {
|
||||
throw new NotFoundException(`Approval request ${id} not found`);
|
||||
}
|
||||
|
||||
let testResult: any = { status: "SIMULATION_SUCCESS" };
|
||||
if (item.category === "PRICING") {
|
||||
const payload = item.payload as any;
|
||||
testResult = {
|
||||
impact: "Price change simulation",
|
||||
currentPrice: payload.currentPrice,
|
||||
newPrice: payload.newPrice,
|
||||
marginDiff: payload.newPrice && payload.buyPrice
|
||||
? (((payload.newPrice - payload.buyPrice) / payload.newPrice) * 100).toFixed(1) + "%"
|
||||
: "N/A",
|
||||
torobFeedReflectEstimate: "< 5 seconds",
|
||||
};
|
||||
} else if (item.category === "PURCHASE_ORDER") {
|
||||
const payload = item.payload as any;
|
||||
testResult = {
|
||||
document: "PO Pre-check",
|
||||
itemsCount: payload.items ? payload.items.length : 1,
|
||||
totalEstimatedCost: payload.totalCost || "محاسبه بر اساس نرخ خرید",
|
||||
fulfillmentCapacity: "انبار آماده پذیرش",
|
||||
};
|
||||
} else {
|
||||
testResult = {
|
||||
executionSafe: true,
|
||||
summary: "تست سلامت اولیه و اعتبارسنجی مقادیر با موفقیت انجام شد.",
|
||||
};
|
||||
}
|
||||
|
||||
return { success: true, testResult };
|
||||
}
|
||||
|
||||
@Put(":id/decide")
|
||||
@ApiOperation({ summary: "تصمیمگیری مدیرعامل (تایید یا رد همراه با یادداشت)" })
|
||||
async decide(@Param("id") id: string, @Body() dto: DecideApprovalDto) {
|
||||
if (!["APPROVED", "REJECTED"].includes(dto.decision)) {
|
||||
throw new BadRequestException("Decision must be either APPROVED or REJECTED");
|
||||
}
|
||||
|
||||
const item = await (this.prisma as any).approvalRequest.findUnique({
|
||||
where: { id },
|
||||
});
|
||||
if (!item) {
|
||||
throw new NotFoundException(`Approval request ${id} not found`);
|
||||
}
|
||||
|
||||
if (dto.decision === "REJECTED") {
|
||||
const updated = await (this.prisma as any).approvalRequest.update({
|
||||
where: { id },
|
||||
data: {
|
||||
status: "REJECTED",
|
||||
ceoNotes: dto.ceoNotes || null,
|
||||
},
|
||||
});
|
||||
|
||||
if ((this.prisma as any).departmentTask?.updateMany) {
|
||||
await (this.prisma as any).departmentTask.updateMany({
|
||||
where: { approvalId: id },
|
||||
data: { status: "REJECTED" },
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "درخواست رد شد و در سوابق ممیزی ثبت گردید.",
|
||||
data: updated,
|
||||
};
|
||||
}
|
||||
|
||||
// تفکیک اقدامات استراتژیک تامینکننده/مدیریتی از کارهای دیجیتال سایت
|
||||
const isStrategicSupplierAction =
|
||||
item.category === "B2B_SUPPLIER_STRATEGY" ||
|
||||
item.category === "PARTNERSHIP" ||
|
||||
(item.department === "B2B" && String(item.category || "").includes("STRATEGY"));
|
||||
|
||||
if (isStrategicSupplierAction) {
|
||||
// طرحهای B2B_SUPPLIER_STRATEGY منحصراً در سوابق مدیریتی تایید میشوند.
|
||||
// هیچ تسک دیجیتالی ایجاد یا بازگشایی نمیشود و executedAt فیزیکی ثبت نمیگردد.
|
||||
const updateData: any = {
|
||||
status: "APPROVED",
|
||||
ceoNotes: dto.ceoNotes || null,
|
||||
};
|
||||
|
||||
if (dto.outcome || dto.evidence) {
|
||||
const payload = typeof item.payload === "object" && item.payload !== null
|
||||
? { ...(item.payload as Record<string, any>) }
|
||||
: {};
|
||||
if (dto.outcome) payload.outcome = dto.outcome;
|
||||
if (dto.evidence) payload.evidence = dto.evidence;
|
||||
updateData.payload = payload;
|
||||
}
|
||||
|
||||
const updated = await (this.prisma as any).approvalRequest.update({
|
||||
where: { id },
|
||||
data: updateData,
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "طرح استراتژیک تامینکننده تایید گردید و در سوابق مدیریتی ثبت شد.",
|
||||
data: updated,
|
||||
};
|
||||
}
|
||||
|
||||
// کارهای دیجیتال (مانند SEO، محتوا، قیمتگذاری و فنی)
|
||||
// تایید مجوز اجرای کار دیجیتال است و تسک متناظر را در صف TODO قرار میدهد
|
||||
const updated = await (this.prisma as any).approvalRequest.update({
|
||||
where: { id },
|
||||
data: {
|
||||
status: "APPROVED",
|
||||
ceoNotes: dto.ceoNotes || null,
|
||||
},
|
||||
});
|
||||
|
||||
// جستجو یا ایجاد تسک متناظر با استاتوس TODO
|
||||
const existingTask = await (this.prisma as any).departmentTask.findFirst({
|
||||
where: { approvalId: id },
|
||||
});
|
||||
|
||||
if (existingTask) {
|
||||
await (this.prisma as any).departmentTask.update({
|
||||
where: { id: existingTask.id },
|
||||
data: {
|
||||
status: "TODO",
|
||||
description: dto.ceoNotes
|
||||
? (existingTask.description || "") + "\n\n[یادداشت مدیرعامل]: " + dto.ceoNotes
|
||||
: existingTask.description,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
await (this.prisma as any).departmentTask.create({
|
||||
data: {
|
||||
code: "TSK-" + Date.now().toString().slice(-6),
|
||||
department: item.department || "SEO",
|
||||
title: item.title,
|
||||
description: dto.ceoNotes ? (item.title + "\n\n[یادداشت مدیرعامل]: " + dto.ceoNotes) : item.title,
|
||||
status: "TODO",
|
||||
priority: "HIGH",
|
||||
assignee: "AI_AGENT",
|
||||
approvalId: item.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "درخواست تایید شد و مأموریت به صف اقدام (TODO) دپارتمان منتقل گردید.",
|
||||
data: updated,
|
||||
};
|
||||
}
|
||||
|
||||
@Delete(":id")
|
||||
@ApiOperation({ summary: "حذف آیتم از کارتابل" })
|
||||
async remove(@Param("id") id: string) {
|
||||
await (this.prisma as any).approvalRequest.delete({ where: { id } });
|
||||
return { success: true, message: "Deleted successfully" };
|
||||
}
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Body,
|
||||
Query,
|
||||
UseGuards,
|
||||
Param,
|
||||
} from "@nestjs/common";
|
||||
import { ApiTags, ApiBearerAuth, ApiOperation } from "@nestjs/swagger";
|
||||
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
|
||||
import { RolesGuard } from "../common/guards/roles.guard";
|
||||
import { Roles } from "../common/decorators/roles.decorator";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
|
||||
@ApiTags("Admin - System Audit & History")
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles("Admin", "SUPER_ADMIN")
|
||||
@Controller("admin/audit-logs")
|
||||
export class AuditLogsController {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: "لیست لاگهای تغییرات دیتابیس و سیستم" })
|
||||
async findAll(@Query() query: any) {
|
||||
const page = Number(query.page) || 1;
|
||||
const limit = Number(query.limit) || 30;
|
||||
const skip = (page - 1) * limit;
|
||||
|
||||
const where: any = {};
|
||||
if (query.entity) where.entity = query.entity;
|
||||
if (query.action) where.action = query.action;
|
||||
if (query.department) where.department = query.department;
|
||||
if (query.search) {
|
||||
where.OR = [
|
||||
{ summary: { contains: query.search, mode: "insensitive" } },
|
||||
{ actor: { contains: query.search, mode: "insensitive" } },
|
||||
{ entityId: { contains: query.search, mode: "insensitive" } },
|
||||
];
|
||||
}
|
||||
|
||||
const [total, items] = await Promise.all([
|
||||
(this.prisma as any).auditLog.count({ where }),
|
||||
(this.prisma as any).auditLog.findMany({
|
||||
where,
|
||||
skip,
|
||||
take: limit,
|
||||
orderBy: { createdAt: "desc" },
|
||||
}),
|
||||
]);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: items,
|
||||
meta: {
|
||||
total,
|
||||
page,
|
||||
limit,
|
||||
totalPages: Math.ceil(total / limit),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@Get("recent")
|
||||
@ApiOperation({ summary: "آخرین رخدادهای سیستم برای ویجت داشبورد" })
|
||||
async getRecent(@Query("limit") limitParam?: string) {
|
||||
const limit = Number(limitParam) || 10;
|
||||
const items = await (this.prisma as any).auditLog.findMany({
|
||||
take: limit,
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
return { success: true, data: items };
|
||||
}
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: "ثبت لاگ جدید در تاریخچه سیستم" })
|
||||
async create(@Body() body: any) {
|
||||
const item = await (this.prisma as any).auditLog.create({
|
||||
data: {
|
||||
entity: body.entity,
|
||||
entityId: body.entityId ? String(body.entityId) : null,
|
||||
action: body.action || "UPDATE",
|
||||
department: body.department || "system",
|
||||
actor: body.actor || "ADMIN",
|
||||
summary: body.summary,
|
||||
oldValues: body.oldValues || null,
|
||||
newValues: body.newValues || null,
|
||||
metadata: body.metadata || null,
|
||||
},
|
||||
});
|
||||
return { success: true, data: item };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import { BadRequestException, ConflictException, NotFoundException } from "@nestjs/common";
|
||||
import { BlogsService } from "./blogs.service";
|
||||
|
||||
// Stateful transactional double: deliberately interleave after snapshot read.
|
||||
// Complements the DB integration test; it does not assert PostgreSQL locking.
|
||||
describe("BlogsService atomic optimistic update", () => {
|
||||
const token = "2026-10-24T23:36:08.501Z";
|
||||
let row: any;
|
||||
let service: BlogsService;
|
||||
let prisma: any;
|
||||
let revalidate: jest.Mock;
|
||||
let afterRead: (() => void) | undefined;
|
||||
let failRelations: boolean;
|
||||
beforeEach(() => {
|
||||
row = { id: "b1", slug: "post", title: "Original", updatedAt: new Date(token), tags: ["old"] };
|
||||
afterRead = undefined;
|
||||
failRelations = false;
|
||||
const blog = {
|
||||
findUnique: jest.fn(async () => {
|
||||
const snapshot = { ...row };
|
||||
afterRead?.();
|
||||
return snapshot;
|
||||
}),
|
||||
updateMany: jest.fn(async ({ where, data }) => {
|
||||
if (row.updatedAt >= where.updatedAt.gte && row.updatedAt < where.updatedAt.lt) {
|
||||
row = { ...row, ...data };
|
||||
return { count: 1 };
|
||||
}
|
||||
return { count: 0 };
|
||||
}),
|
||||
update: jest.fn(async ({ data }) => {
|
||||
if (failRelations) throw new Error("relation failure");
|
||||
row = { ...row, ...data };
|
||||
return { ...row };
|
||||
}),
|
||||
};
|
||||
// Serialize transactions like row locks. Rollback restores only transaction writes.
|
||||
let tail = Promise.resolve();
|
||||
prisma = { blog, $transaction: jest.fn((cb) => {
|
||||
const next = tail.then(async () => {
|
||||
const before = { ...row };
|
||||
try { return await cb({ blog }); } catch (error) { row = before; throw error; }
|
||||
});
|
||||
tail = next.catch(() => undefined);
|
||||
return next;
|
||||
}) };
|
||||
revalidate = jest.fn().mockResolvedValue(true);
|
||||
service = new BlogsService(prisma, { revalidateBlog: revalidate } as any);
|
||||
});
|
||||
|
||||
it.each([null, 0, 123, true, {}, [], "", "garbage", "2026-02-30T00:00:00.000Z", "2026-10-24", "2026-10-24T23:36:08.501001Z"])("rejects invalid token %p without mutations", async (value) => {
|
||||
await expect(service.updateBlog("b1", { title: "bad", expectedUpdatedAt: value })).rejects.toBeInstanceOf(ConflictException);
|
||||
expect(prisma.blog.update).not.toHaveBeenCalled();
|
||||
expect(prisma.blog.updateMany).not.toHaveBeenCalled();
|
||||
expect(revalidate).not.toHaveBeenCalled();
|
||||
});
|
||||
it("rejects stale token and leaves all relations untouched", async () => {
|
||||
await expect(service.updateBlog("b1", { expectedUpdatedAt: "2026-10-20T00:00:00.000Z", tagNames: ["new"], categoryId: "c" })).rejects.toBeInstanceOf(ConflictException);
|
||||
expect(row.tags).toEqual(["old"]);
|
||||
expect(prisma.blog.update).not.toHaveBeenCalled();
|
||||
expect(revalidate).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each([token, "2026-10-25T01:36:08.501+02:00"])("accepts current token %s and atomically includes relations", async (expectedUpdatedAt) => {
|
||||
const result = await service.updateBlog("b1", { title: "new", expectedUpdatedAt, authorId: "a", categoryId: "c", tagNames: ["new"] });
|
||||
expect(result.title).toBe("new");
|
||||
expect(prisma.$transaction).toHaveBeenCalledTimes(1);
|
||||
expect(prisma.blog.updateMany).toHaveBeenCalledWith({ where: { id: "b1", updatedAt: { gte: new Date(token), lt: new Date(new Date(token).getTime() + 1) } }, data: { updatedAt: expect.any(Date) } });
|
||||
expect(prisma.blog.update.mock.calls[0][0].data).toMatchObject({ author: { connect: { id: "a" } }, category: { connect: { id: "c" } }, tags: { set: [], connectOrCreate: expect.any(Array) } });
|
||||
expect(prisma.blog.update.mock.calls[0][0].data).not.toHaveProperty("expectedUpdatedAt");
|
||||
expect(result.updatedAt.getTime()).toBeGreaterThan(new Date(token).getTime());
|
||||
expect(revalidate).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it("detects writer interleaving after read before write", async () => {
|
||||
afterRead = () => { row = { ...row, title: "winner", updatedAt: new Date("2026-10-24T23:36:08.502Z"), tags: ["winner"] }; };
|
||||
await expect(service.updateBlog("b1", { expectedUpdatedAt: token, title: "loser", tagNames: ["loser"] })).rejects.toBeInstanceOf(ConflictException);
|
||||
expect(row.title).toBe("winner");
|
||||
expect(row.tags).toEqual(["winner"]);
|
||||
expect(prisma.blog.update).not.toHaveBeenCalled();
|
||||
expect(revalidate).not.toHaveBeenCalled();
|
||||
});
|
||||
it("permits exactly one of two requests sharing a token", async () => {
|
||||
const results = await Promise.allSettled([service.updateBlog("b1", { expectedUpdatedAt: token, title: "a" }), service.updateBlog("b1", { expectedUpdatedAt: token, title: "b" })]);
|
||||
expect(results.filter(r => r.status === "fulfilled")).toHaveLength(1);
|
||||
const rejected = results.find(r => r.status === "rejected") as PromiseRejectedResult;
|
||||
expect(rejected.reason).toBeInstanceOf(ConflictException);
|
||||
expect(revalidate).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it("advances token even when clock is within same millisecond", async () => {
|
||||
jest.useFakeTimers().setSystemTime(new Date(token));
|
||||
try {
|
||||
await service.updateBlog("b1", { expectedUpdatedAt: token, title: "first" });
|
||||
await expect(service.updateBlog("b1", { expectedUpdatedAt: token, title: "second" })).rejects.toBeInstanceOf(ConflictException);
|
||||
} finally { jest.useRealTimers(); }
|
||||
});
|
||||
it("rolls back claim on nested relation failure without invalidating cache", async () => {
|
||||
failRelations = true;
|
||||
await expect(service.updateBlog("b1", { expectedUpdatedAt: token, tagNames: ["new"] })).rejects.toThrow("relation failure");
|
||||
expect(row.updatedAt.toISOString()).toBe(token);
|
||||
expect(row.tags).toEqual(["old"]);
|
||||
expect(revalidate).not.toHaveBeenCalled();
|
||||
});
|
||||
it("preserves legacy omission without demanding a token", async () => {
|
||||
await service.updateBlog("b1", { title: "legacy" });
|
||||
expect(row.title).toBe("legacy");
|
||||
expect(prisma.$transaction).not.toHaveBeenCalled();
|
||||
});
|
||||
it("returns 404 for a missing blog", async () => {
|
||||
prisma.blog.findUnique.mockResolvedValue(null);
|
||||
await expect(service.updateBlog("missing", { expectedUpdatedAt: token })).rejects.toBeInstanceOf(NotFoundException);
|
||||
});
|
||||
it("does not fail committed writes if revalidation throws", async () => {
|
||||
revalidate.mockRejectedValue(new Error("cache down"));
|
||||
const result = await service.updateBlog("b1", { expectedUpdatedAt: token, title: "saved" });
|
||||
expect(result.cacheRevalidation).toBe("failed");
|
||||
expect(row.title).toBe("saved");
|
||||
});
|
||||
});
|
||||
@@ -54,6 +54,8 @@ describe("Admin BlogsService", () => {
|
||||
}).compile();
|
||||
|
||||
service = module.get<BlogsService>(BlogsService);
|
||||
mockRevalidationService.revalidateBlog.mockReset();
|
||||
mockRevalidationService.revalidateBlog.mockResolvedValue(true);
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
@@ -200,7 +202,10 @@ describe("Admin BlogsService", () => {
|
||||
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith(
|
||||
"new-health-post",
|
||||
);
|
||||
expect(result).toEqual(createdBlog);
|
||||
expect(result).toEqual({
|
||||
...createdBlog,
|
||||
cacheRevalidation: "success",
|
||||
});
|
||||
});
|
||||
|
||||
it("allowlists create fields and blocks server-owned and unknown fields", async () => {
|
||||
@@ -272,6 +277,66 @@ describe("Admin BlogsService", () => {
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("should expose cacheRevalidation status on create result without failing persistence", async () => {
|
||||
const blogData = {
|
||||
title: "Health Post",
|
||||
slug: "health-post",
|
||||
content: "Content",
|
||||
};
|
||||
const createdBlog = { id: "blog-1", ...blogData };
|
||||
mockPrisma.blog.create.mockResolvedValue(createdBlog);
|
||||
mockRevalidationService.revalidateBlog.mockResolvedValue(true);
|
||||
|
||||
const result = await service.createBlog(blogData, "user-admin-1");
|
||||
|
||||
expect(mockPrisma.blog.create).toHaveBeenCalled();
|
||||
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith("health-post");
|
||||
expect(result).toEqual({
|
||||
...createdBlog,
|
||||
cacheRevalidation: "success",
|
||||
});
|
||||
});
|
||||
|
||||
it("should return cacheRevalidation 'failed' when revalidation fails without failing persistence", async () => {
|
||||
const blogData = {
|
||||
title: "Health Post",
|
||||
slug: "health-post",
|
||||
content: "Content",
|
||||
};
|
||||
const createdBlog = { id: "blog-1", ...blogData };
|
||||
mockPrisma.blog.create.mockResolvedValue(createdBlog);
|
||||
mockRevalidationService.revalidateBlog.mockResolvedValue(false);
|
||||
|
||||
const result = await service.createBlog(blogData, "user-admin-1");
|
||||
|
||||
expect(mockPrisma.blog.create).toHaveBeenCalled();
|
||||
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith("health-post");
|
||||
expect(result).toEqual({
|
||||
...createdBlog,
|
||||
cacheRevalidation: "failed",
|
||||
});
|
||||
});
|
||||
|
||||
it("should catch unexpected revalidation exceptions on create and return cacheRevalidation 'failed'", async () => {
|
||||
const blogData = {
|
||||
title: "Health Post",
|
||||
slug: "health-post",
|
||||
content: "Content",
|
||||
};
|
||||
const createdBlog = { id: "blog-1", ...blogData };
|
||||
mockPrisma.blog.create.mockResolvedValue(createdBlog);
|
||||
mockRevalidationService.revalidateBlog.mockRejectedValue(new Error("Frontend offline"));
|
||||
|
||||
const result = await service.createBlog(blogData, "user-admin-1");
|
||||
|
||||
expect(mockPrisma.blog.create).toHaveBeenCalled();
|
||||
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith("health-post");
|
||||
expect(result).toEqual({
|
||||
...createdBlog,
|
||||
cacheRevalidation: "failed",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("updateBlog", () => {
|
||||
@@ -314,7 +379,61 @@ describe("Admin BlogsService", () => {
|
||||
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith(
|
||||
"my-post",
|
||||
);
|
||||
expect(result).toEqual(updated);
|
||||
expect(result).toEqual({
|
||||
...updated,
|
||||
cacheRevalidation: "success",
|
||||
});
|
||||
});
|
||||
|
||||
it("should expose cacheRevalidation status on update result without failing persistence", async () => {
|
||||
const existing = { id: "b1", slug: "my-post", title: "Old Title" };
|
||||
mockPrisma.blog.findUnique.mockResolvedValue(existing);
|
||||
const updated = { ...existing, title: "New Title" };
|
||||
mockPrisma.blog.update.mockResolvedValue(updated);
|
||||
mockRevalidationService.revalidateBlog.mockResolvedValue(true);
|
||||
|
||||
const result = await service.updateBlog("b1", { title: "New Title" });
|
||||
|
||||
expect(mockPrisma.blog.update).toHaveBeenCalled();
|
||||
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith("my-post");
|
||||
expect(result).toEqual({
|
||||
...updated,
|
||||
cacheRevalidation: "success",
|
||||
});
|
||||
});
|
||||
|
||||
it("should return cacheRevalidation 'failed' when revalidation fails on update without failing persistence", async () => {
|
||||
const existing = { id: "b1", slug: "my-post", title: "Old Title" };
|
||||
mockPrisma.blog.findUnique.mockResolvedValue(existing);
|
||||
const updated = { ...existing, title: "New Title" };
|
||||
mockPrisma.blog.update.mockResolvedValue(updated);
|
||||
mockRevalidationService.revalidateBlog.mockResolvedValue(false);
|
||||
|
||||
const result = await service.updateBlog("b1", { title: "New Title" });
|
||||
|
||||
expect(mockPrisma.blog.update).toHaveBeenCalled();
|
||||
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith("my-post");
|
||||
expect(result).toEqual({
|
||||
...updated,
|
||||
cacheRevalidation: "failed",
|
||||
});
|
||||
});
|
||||
|
||||
it("should catch unexpected revalidation exceptions on update and return cacheRevalidation 'failed'", async () => {
|
||||
const existing = { id: "b1", slug: "my-post", title: "Old Title" };
|
||||
mockPrisma.blog.findUnique.mockResolvedValue(existing);
|
||||
const updated = { ...existing, title: "New Title" };
|
||||
mockPrisma.blog.update.mockResolvedValue(updated);
|
||||
mockRevalidationService.revalidateBlog.mockRejectedValue(new Error("Revalidation timeout"));
|
||||
|
||||
const result = await service.updateBlog("b1", { title: "New Title" });
|
||||
|
||||
expect(mockPrisma.blog.update).toHaveBeenCalled();
|
||||
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith("my-post");
|
||||
expect(result).toEqual({
|
||||
...updated,
|
||||
cacheRevalidation: "failed",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
OnModuleInit,
|
||||
@@ -255,8 +256,21 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
},
|
||||
});
|
||||
|
||||
await this.revalidationService.revalidateBlog(created.slug);
|
||||
return created;
|
||||
let cacheRevalidation: "success" | "failed" = "failed";
|
||||
try {
|
||||
const revalidated = await this.revalidationService.revalidateBlog(created.slug);
|
||||
cacheRevalidation = revalidated ? "success" : "failed";
|
||||
} catch (err: any) {
|
||||
this.logger.warn(
|
||||
`Cache revalidation failed for created blog [${created.slug}]: ${err?.message}`,
|
||||
);
|
||||
cacheRevalidation = "failed";
|
||||
}
|
||||
|
||||
return {
|
||||
...created,
|
||||
cacheRevalidation,
|
||||
};
|
||||
}
|
||||
|
||||
async updateBlog(id: string, data: any) {
|
||||
@@ -272,8 +286,30 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
readingTime,
|
||||
markContentUpdated,
|
||||
contentUpdatedAt,
|
||||
expectedUpdatedAt,
|
||||
} = data;
|
||||
|
||||
const conflict = () => new ConflictException(
|
||||
"CONCURRENT_MODIFICATION: Blog has been modified by another process",
|
||||
);
|
||||
let expectedTime: number | undefined;
|
||||
if (expectedUpdatedAt !== undefined) {
|
||||
// Only accept the millisecond, timezone-qualified ISO token returned by GET
|
||||
// (or an equivalent offset). Avoid Date's coercion of null, numbers, arrays,
|
||||
// and its normalization of impossible calendar dates.
|
||||
const match = typeof expectedUpdatedAt === "string" && expectedUpdatedAt.match(
|
||||
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?(Z|[+-]\d{2}:\d{2})$/,
|
||||
);
|
||||
if (!match) throw conflict();
|
||||
expectedTime = Date.parse(expectedUpdatedAt);
|
||||
const calendar = new Date(`${match[1]}-${match[2]}-${match[3]}T00:00:00.000Z`);
|
||||
if (!Number.isFinite(expectedTime) ||
|
||||
calendar.toISOString().slice(0, 10) !== `${match[1]}-${match[2]}-${match[3]}` ||
|
||||
Number(match[4]) > 23 || Number(match[5]) > 59 || Number(match[6]) > 59) {
|
||||
throw conflict();
|
||||
}
|
||||
}
|
||||
|
||||
const mutableScalarFields = [
|
||||
"title",
|
||||
"slug",
|
||||
@@ -390,25 +426,68 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
};
|
||||
}
|
||||
|
||||
const updated = await this.prisma.blog.update({
|
||||
where: { id },
|
||||
data: updatePayload,
|
||||
include: {
|
||||
author: { select: { firstName: true, lastName: true } },
|
||||
category: true,
|
||||
tags: true,
|
||||
},
|
||||
});
|
||||
const include = {
|
||||
author: { select: { firstName: true, lastName: true } },
|
||||
category: true,
|
||||
tags: true,
|
||||
};
|
||||
// Legacy UI requests without a token intentionally retain last-write-wins.
|
||||
// Guarded requests claim the row using a DB predicate, not the earlier read.
|
||||
const updated = expectedTime === undefined
|
||||
? await this.prisma.blog.update({ where: { id }, data: updatePayload, include })
|
||||
: await this.prisma.$transaction(async (tx) => {
|
||||
// PostgreSQL timestamptz defaults to microseconds; JSON/JS Dates expose
|
||||
// milliseconds. Match the entire represented millisecond, then move
|
||||
// strictly beyond it (including same-ms writes and clock rollback).
|
||||
const claimedAt = new Date(Math.max(Date.now(), expectedTime + 1));
|
||||
const claim = await tx.blog.updateMany({
|
||||
where: {
|
||||
id,
|
||||
updatedAt: {
|
||||
gte: new Date(expectedTime),
|
||||
lt: new Date(expectedTime + 1),
|
||||
},
|
||||
},
|
||||
data: { updatedAt: claimedAt },
|
||||
});
|
||||
if (claim.count !== 1) throw conflict();
|
||||
// The claim holds the row lock until this nested mutation commits.
|
||||
// Any relation failure rolls back both the claim and all data writes.
|
||||
return tx.blog.update({
|
||||
where: { id },
|
||||
data: { ...updatePayload, updatedAt: claimedAt },
|
||||
include,
|
||||
});
|
||||
});
|
||||
|
||||
await this.revalidationService.revalidateBlog(updated.slug);
|
||||
return updated;
|
||||
let cacheRevalidation: "success" | "failed" = "failed";
|
||||
try {
|
||||
const revalidated = await this.revalidationService.revalidateBlog(updated.slug);
|
||||
cacheRevalidation = revalidated ? "success" : "failed";
|
||||
} catch (err: any) {
|
||||
this.logger.warn(
|
||||
`Cache revalidation failed for updated blog [${updated.slug}]: ${err?.message}`,
|
||||
);
|
||||
cacheRevalidation = "failed";
|
||||
}
|
||||
|
||||
return {
|
||||
...updated,
|
||||
cacheRevalidation,
|
||||
};
|
||||
}
|
||||
|
||||
async deleteBlog(id: string) {
|
||||
const blog = await this.prisma.blog.findUnique({ where: { id } });
|
||||
if (!blog) throw new NotFoundException("Blog not found");
|
||||
const res = await this.prisma.blog.delete({ where: { id } });
|
||||
await this.revalidationService.revalidateBlog(blog.slug);
|
||||
try {
|
||||
await this.revalidationService.revalidateBlog(blog.slug);
|
||||
} catch (err: any) {
|
||||
this.logger.warn(
|
||||
`Cache revalidation failed for deleted blog [${blog.slug}]: ${err?.message}`,
|
||||
);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,95 +0,0 @@
|
||||
import { BadRequestException } from "@nestjs/common";
|
||||
import { assertTaskCanComplete } from "./department-task-completion.policy";
|
||||
|
||||
describe("department task completion policy", () => {
|
||||
it("rejects model-only output without a live deliverable", () => {
|
||||
expect(() =>
|
||||
assertTaskCanComplete({
|
||||
deliverableUrl: null,
|
||||
acceptanceCriteria: { criteria: ["live URL responds 200"] },
|
||||
executionLogs: [{ status: "COMPLETED_BY_AGENT" }],
|
||||
}),
|
||||
).toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it("rejects completion without acceptance criteria", () => {
|
||||
expect(() =>
|
||||
assertTaskCanComplete({
|
||||
deliverableUrl: "https://canina.ir/blog/verified",
|
||||
acceptanceCriteria: null,
|
||||
executionLogs: [{ status: "QA_PASSED" }],
|
||||
}),
|
||||
).toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it("rejects completion without QA evidence", () => {
|
||||
expect(() =>
|
||||
assertTaskCanComplete({
|
||||
deliverableUrl: "https://canina.ir/blog/verified",
|
||||
acceptanceCriteria: { criteria: ["HTTP 200"] },
|
||||
executionLogs: [{ status: "COMPLETED_BY_AGENT" }],
|
||||
}),
|
||||
).toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it("does not trust caller-spoofable QA evidence even with URL and criteria", () => {
|
||||
expect(() => assertTaskCanComplete({
|
||||
deliverableUrl: "https://canina.ir/blog/verified",
|
||||
acceptanceCriteria: { criteria: ["HTTP 200"] },
|
||||
executionLogs: [{ status: "QA_PASSED" }],
|
||||
})).toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it("requires matching server-issued artifact identity", () => {
|
||||
expect(() => assertTaskCanComplete({
|
||||
id: "task-1", deliverableUrl: "https://canina.ir/blog/verified",
|
||||
acceptanceCriteria: { criteria: ["HTTP 200"] },
|
||||
attestation: { taskId: "task-1", artifactType: "BLOG", artifactId: "blog-1", artifactUrl: "https://canina.ir/blog/verified", verifier: "SERVER_ARTIFACT_VERIFIER" },
|
||||
})).not.toThrow();
|
||||
expect(() => assertTaskCanComplete({
|
||||
id: "task-2", deliverableUrl: "https://canina.ir/blog/verified",
|
||||
acceptanceCriteria: { criteria: ["HTTP 200"] },
|
||||
attestation: { taskId: "task-1", artifactType: "BLOG", artifactId: "blog-1", artifactUrl: "https://canina.ir/blog/verified", verifier: "SERVER_ARTIFACT_VERIFIER" },
|
||||
})).toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it("rejects pseudo-protocol canina:// deliverable URLs", () => {
|
||||
expect(() =>
|
||||
assertTaskCanComplete({
|
||||
deliverableUrl: "canina://blog/sample-article",
|
||||
acceptanceCriteria: { criteria: ["HTTP 200"] },
|
||||
executionLogs: [{ status: "QA_PASSED" }],
|
||||
}),
|
||||
).toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it("rejects git://stage staging or repo URLs as verifiable deliverable", () => {
|
||||
expect(() =>
|
||||
assertTaskCanComplete({
|
||||
deliverableUrl: "git://stage/canina-repo#commit123",
|
||||
acceptanceCriteria: { criteria: ["HTTP 200"] },
|
||||
executionLogs: [{ status: "QA_PASSED" }],
|
||||
}),
|
||||
).toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it("rejects missing or placeholder post-tsk article deliverables", () => {
|
||||
expect(() =>
|
||||
assertTaskCanComplete({
|
||||
deliverableUrl: "https://canina.ir/blog/post-tsk-49102",
|
||||
acceptanceCriteria: { criteria: ["HTTP 200"] },
|
||||
executionLogs: [{ status: "QA_PASSED" }],
|
||||
}),
|
||||
).toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it("rejects completion when QA evidence reports missing article or 404 error", () => {
|
||||
expect(() =>
|
||||
assertTaskCanComplete({
|
||||
deliverableUrl: "https://canina.ir/blog/verified-article",
|
||||
acceptanceCriteria: { criteria: ["HTTP 200"] },
|
||||
executionLogs: [{ status: "QA_PASSED", note: "HTTP 404 - مقاله یافت نشد" }],
|
||||
}),
|
||||
).toThrow(BadRequestException);
|
||||
});
|
||||
});
|
||||
@@ -1,70 +0,0 @@
|
||||
import { BadRequestException } from "@nestjs/common";
|
||||
|
||||
export interface CompletableTask {
|
||||
code?: string | null;
|
||||
title?: string | null;
|
||||
deliverableUrl?: string | null;
|
||||
acceptanceCriteria?: unknown;
|
||||
executionLogs?: unknown;
|
||||
id?: string;
|
||||
attestation?: { taskId: string; artifactType: string; artifactId: string; artifactUrl: string; verifier: string };
|
||||
}
|
||||
|
||||
function hasAcceptanceCriteria(criteria: unknown): boolean {
|
||||
if (!criteria) return false;
|
||||
if (typeof criteria === "string") return criteria.trim().length > 0;
|
||||
if (Array.isArray(criteria)) return criteria.length > 0;
|
||||
if (typeof criteria === "object") {
|
||||
const value = criteria as Record<string, unknown>;
|
||||
const items = value.criteria;
|
||||
return Array.isArray(items) ? items.length > 0 : Object.keys(value).length > 0;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function assertTaskCanComplete(task: CompletableTask): void {
|
||||
const rawUrl = task.deliverableUrl?.trim();
|
||||
if (!rawUrl) {
|
||||
throw new BadRequestException("DONE requires a verifiable deliverable URL");
|
||||
}
|
||||
|
||||
const lowerUrl = rawUrl.toLowerCase();
|
||||
|
||||
// Reject internal pseudo-protocols
|
||||
if (lowerUrl.startsWith("canina://") || lowerUrl.includes("canina://")) {
|
||||
throw new BadRequestException("Deliverable URL cannot use pseudo-protocol canina://; an independently verifiable HTTP(S) URL is required");
|
||||
}
|
||||
|
||||
// Reject git repository pointers or staging branches as production deliverables
|
||||
if (lowerUrl.startsWith("git://") || lowerUrl.includes("git://stage")) {
|
||||
throw new BadRequestException("Deliverable URL cannot be a git staging reference; an independently verifiable HTTP(S) URL is required");
|
||||
}
|
||||
|
||||
// Must be an HTTP or HTTPS URL
|
||||
if (!lowerUrl.startsWith("http://") && !lowerUrl.startsWith("https://")) {
|
||||
throw new BadRequestException("DONE requires an independently verifiable HTTP or HTTPS deliverable URL");
|
||||
}
|
||||
|
||||
// Reject deleted or placeholder post-tsk articles
|
||||
if (/post[-_]?tsk/i.test(rawUrl)) {
|
||||
throw new BadRequestException("Deliverable URL references an unverified or deleted post-tsk placeholder article");
|
||||
}
|
||||
if (task.title && /post[-_]?tsk/i.test(task.title)) {
|
||||
throw new BadRequestException("Task references an unverified or deleted post-tsk article");
|
||||
}
|
||||
if (task.code && /post[-_]?tsk/i.test(task.code)) {
|
||||
throw new BadRequestException("Task references an unverified or deleted post-tsk code");
|
||||
}
|
||||
|
||||
if (!hasAcceptanceCriteria(task.acceptanceCriteria)) {
|
||||
throw new BadRequestException("DONE requires explicit acceptance criteria");
|
||||
}
|
||||
|
||||
const evidence = task.attestation;
|
||||
if (!task.id || !evidence || evidence.taskId !== task.id ||
|
||||
evidence.verifier !== "SERVER_ARTIFACT_VERIFIER" ||
|
||||
evidence.artifactType !== "BLOG" || !evidence.artifactId ||
|
||||
evidence.artifactUrl !== rawUrl) {
|
||||
throw new BadRequestException("DONE requires a matching server-verified artifact attestation");
|
||||
}
|
||||
}
|
||||
@@ -1,236 +0,0 @@
|
||||
import { Test, TestingModule } from "@nestjs/testing";
|
||||
import { BadRequestException, NotFoundException } from "@nestjs/common";
|
||||
import { DepartmentTasksController } from "./department-tasks.controller";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
|
||||
describe("DepartmentTasksController", () => {
|
||||
let controller: DepartmentTasksController;
|
||||
let prisma: {
|
||||
taskCompletionAttestation: { create: jest.Mock };
|
||||
blog: { findUnique: jest.Mock };
|
||||
product: { findUnique: jest.Mock };
|
||||
$transaction: jest.Mock;
|
||||
departmentTask: {
|
||||
findUnique: jest.Mock;
|
||||
findMany: jest.Mock;
|
||||
count: jest.Mock;
|
||||
create: jest.Mock;
|
||||
update: jest.Mock;
|
||||
delete: jest.Mock;
|
||||
};
|
||||
auditLog: {
|
||||
create: jest.Mock;
|
||||
};
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
prisma = {
|
||||
taskCompletionAttestation: { create: jest.fn() },
|
||||
blog: { findUnique: jest.fn() },
|
||||
product: { findUnique: jest.fn() },
|
||||
$transaction: jest.fn(async (callback) => callback(prisma)),
|
||||
departmentTask: {
|
||||
findUnique: jest.fn(),
|
||||
findMany: jest.fn(),
|
||||
count: jest.fn(),
|
||||
create: jest.fn(),
|
||||
update: jest.fn(),
|
||||
delete: jest.fn(),
|
||||
},
|
||||
auditLog: {
|
||||
create: jest.fn().mockResolvedValue({ id: "audit-1" }),
|
||||
},
|
||||
};
|
||||
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [DepartmentTasksController],
|
||||
providers: [
|
||||
{
|
||||
provide: PrismaService,
|
||||
useValue: prisma,
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<DepartmentTasksController>(DepartmentTasksController);
|
||||
});
|
||||
|
||||
describe("trusted completion authorization", () => {
|
||||
const validTask = {
|
||||
id: "task-105", code: "TSK-100105", title: "Published blog", status: "TEST",
|
||||
acceptanceCriteria: { criteria: ["Published blog"] }, executionLogs: [{ status: "QA_PASSED" }],
|
||||
deliverableUrl: "https://canina.ir/blog/cat-food-nutrition",
|
||||
};
|
||||
|
||||
it("cannot create a DONE task even with caller-supplied QA logs", async () => {
|
||||
await expect(controller.create({ department: "content", title: "fake", status: "DONE", executionLogs: [{ status: "QA_PASSED" }] }))
|
||||
.rejects.toThrow(BadRequestException);
|
||||
expect(prisma.departmentTask.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects unknown statuses at creation and transition", async () => {
|
||||
await expect(controller.create({ department: "content", title: "fake", status: "DONE " })).rejects.toThrow(BadRequestException);
|
||||
prisma.departmentTask.findUnique.mockResolvedValue(validTask);
|
||||
await expect(controller.updateStatus(validTask.id, { status: "COMPLETE" })).rejects.toThrow(BadRequestException);
|
||||
expect(prisma.departmentTask.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects spoofed historical QA and requires independent verification", async () => {
|
||||
prisma.departmentTask.findUnique.mockResolvedValue(validTask);
|
||||
prisma.blog.findUnique.mockResolvedValue(null);
|
||||
await expect(controller.updateStatus(validTask.id, { status: "DONE" })).rejects.toThrow(BadRequestException);
|
||||
expect(prisma.departmentTask.update).not.toHaveBeenCalled();
|
||||
expect(prisma.taskCompletionAttestation.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects arbitrary hosts and changed deliverables before lookup", async () => {
|
||||
prisma.departmentTask.findUnique.mockResolvedValue(validTask);
|
||||
await expect(controller.updateStatus(validTask.id, { status: "DONE", deliverableUrl: "https://evil.example/blog/cat-food-nutrition" }))
|
||||
.rejects.toThrow(BadRequestException);
|
||||
expect(prisma.blog.findUnique).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects an unpublished artifact", async () => {
|
||||
prisma.departmentTask.findUnique.mockResolvedValue(validTask);
|
||||
prisma.blog.findUnique.mockResolvedValue({ id: "blog-1", slug: "cat-food-nutrition", status: "DRAFT", isPublished: false });
|
||||
await expect(controller.updateStatus(validTask.id, { status: "DONE" })).rejects.toThrow(BadRequestException);
|
||||
expect(prisma.departmentTask.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not write DONE if attestation persistence fails", async () => {
|
||||
prisma.departmentTask.findUnique.mockResolvedValue(validTask);
|
||||
prisma.blog.findUnique.mockResolvedValue({ id: "blog-1", slug: "cat-food-nutrition", status: "PUBLISHED", isPublished: true });
|
||||
prisma.taskCompletionAttestation.create.mockRejectedValue(new Error("attestation store unavailable"));
|
||||
await expect(controller.updateStatus(validTask.id, { status: "DONE" })).rejects.toThrow("attestation store unavailable");
|
||||
expect(prisma.departmentTask.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("persists a server-verifier attestation bound to the task and artifact before DONE", async () => {
|
||||
prisma.departmentTask.findUnique.mockResolvedValue(validTask);
|
||||
prisma.blog.findUnique.mockResolvedValue({ id: "blog-1", slug: "cat-food-nutrition", status: "PUBLISHED", isPublished: true });
|
||||
prisma.departmentTask.update.mockResolvedValue({ ...validTask, status: "DONE" });
|
||||
await controller.updateStatus(validTask.id, { status: "DONE", logNote: "QA_PASSED" });
|
||||
expect(prisma.taskCompletionAttestation.create).toHaveBeenCalledWith({ data: expect.objectContaining({
|
||||
taskId: validTask.id, artifactType: "BLOG", artifactId: "blog-1", artifactUrl: validTask.deliverableUrl,
|
||||
verifier: "SERVER_ARTIFACT_VERIFIER", verifiedAt: expect.any(Date),
|
||||
}) });
|
||||
expect(prisma.$transaction).toHaveBeenCalled();
|
||||
expect(prisma.departmentTask.update).toHaveBeenCalledWith({ where: { id: validTask.id }, data: expect.objectContaining({ status: "DONE" }) });
|
||||
});
|
||||
});
|
||||
|
||||
describe("updateStatus - verifiable completion guards", () => {
|
||||
it("rejects completion with pseudo-protocol canina://", async () => {
|
||||
const taskId = "task-101";
|
||||
prisma.departmentTask.findUnique.mockResolvedValue({
|
||||
id: taskId,
|
||||
code: "TSK-100101",
|
||||
title: "Test Task",
|
||||
status: "TEST",
|
||||
acceptanceCriteria: { criteria: ["200 OK"] },
|
||||
executionLogs: [{ status: "QA_PASSED" }],
|
||||
deliverableUrl: null,
|
||||
});
|
||||
|
||||
await expect(
|
||||
controller.updateStatus(taskId, {
|
||||
status: "DONE",
|
||||
deliverableUrl: "canina://blog/fake-article",
|
||||
}),
|
||||
).rejects.toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it("rejects completion with git://stage repository reference", async () => {
|
||||
const taskId = "task-102";
|
||||
prisma.departmentTask.findUnique.mockResolvedValue({
|
||||
id: taskId,
|
||||
code: "TSK-100102",
|
||||
title: "Test Task",
|
||||
status: "TEST",
|
||||
acceptanceCriteria: { criteria: ["200 OK"] },
|
||||
executionLogs: [{ status: "QA_PASSED" }],
|
||||
deliverableUrl: null,
|
||||
});
|
||||
|
||||
await expect(
|
||||
controller.updateStatus(taskId, {
|
||||
status: "DONE",
|
||||
deliverableUrl: "git://stage/canina-repo#commit-xyz",
|
||||
}),
|
||||
).rejects.toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it("rejects completion with post-tsk placeholder article", async () => {
|
||||
const taskId = "task-103";
|
||||
prisma.departmentTask.findUnique.mockResolvedValue({
|
||||
id: taskId,
|
||||
code: "TSK-100103",
|
||||
title: "Test Task",
|
||||
status: "TEST",
|
||||
acceptanceCriteria: { criteria: ["200 OK"] },
|
||||
executionLogs: [{ status: "QA_PASSED" }],
|
||||
deliverableUrl: null,
|
||||
});
|
||||
|
||||
await expect(
|
||||
controller.updateStatus(taskId, {
|
||||
status: "DONE",
|
||||
deliverableUrl: "https://canina.ir/blog/post-tsk-998877",
|
||||
}),
|
||||
).rejects.toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it("rejects completion when QA log reports missing article / 404", async () => {
|
||||
const taskId = "task-104";
|
||||
prisma.departmentTask.findUnique.mockResolvedValue({
|
||||
id: taskId,
|
||||
code: "TSK-100104",
|
||||
title: "Test Task",
|
||||
status: "TEST",
|
||||
acceptanceCriteria: { criteria: ["200 OK"] },
|
||||
executionLogs: [],
|
||||
deliverableUrl: "https://canina.ir/blog/real-article",
|
||||
});
|
||||
|
||||
await expect(
|
||||
controller.updateStatus(taskId, {
|
||||
status: "DONE",
|
||||
logNote: "QA_PASSED but received 404 - مقاله یافت نشد",
|
||||
}),
|
||||
).rejects.toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it("allows completion with valid HTTPS deliverable URL and verified QA evidence", async () => {
|
||||
const taskId = "task-105";
|
||||
const existingTask = {
|
||||
id: taskId,
|
||||
code: "TSK-100105",
|
||||
title: "Optimized Cat Food Landing",
|
||||
status: "TEST",
|
||||
acceptanceCriteria: { criteria: ["HTTP 200", "Lighthouse > 90"] },
|
||||
executionLogs: [{ status: "PRODUCTION_VERIFIED", note: "Live 200 verified on production" }],
|
||||
deliverableUrl: "https://canina.ir/blog/cat-food-nutrition",
|
||||
};
|
||||
prisma.departmentTask.findUnique.mockResolvedValue(existingTask);
|
||||
prisma.blog.findUnique.mockResolvedValue({ id: "blog-2", slug: "cat-food-nutrition", status: "PUBLISHED", isPublished: true });
|
||||
prisma.departmentTask.update.mockResolvedValue({
|
||||
...existingTask,
|
||||
status: "DONE",
|
||||
completedAt: new Date(),
|
||||
});
|
||||
|
||||
const res = await controller.updateStatus(taskId, {
|
||||
status: "DONE",
|
||||
});
|
||||
|
||||
expect(res.success).toBe(true);
|
||||
expect(prisma.departmentTask.update).toHaveBeenCalledWith({
|
||||
where: { id: taskId },
|
||||
data: expect.objectContaining({
|
||||
status: "DONE",
|
||||
completedAt: expect.any(Date),
|
||||
}),
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,255 +0,0 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Put,
|
||||
Delete,
|
||||
Body,
|
||||
Param,
|
||||
Query,
|
||||
UseGuards,
|
||||
NotFoundException,
|
||||
BadRequestException,
|
||||
} from "@nestjs/common";
|
||||
import { assertTaskCanComplete } from "./department-task-completion.policy";
|
||||
import { ApiTags, ApiBearerAuth, ApiOperation } from "@nestjs/swagger";
|
||||
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
|
||||
import { RolesGuard } from "../common/guards/roles.guard";
|
||||
import { Roles } from "../common/decorators/roles.decorator";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
|
||||
@ApiTags("Admin - Department & Agent Tasks")
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles("Admin", "SUPER_ADMIN")
|
||||
@Controller("admin/department-tasks")
|
||||
export class DepartmentTasksController {
|
||||
private readonly allowedStatuses = new Set([
|
||||
"BACKLOG", "TODO", "IN_PROGRESS", "TEST", "IN_REVIEW", "APPROVED", "DEPLOYING", "DONE",
|
||||
]);
|
||||
|
||||
private assertStatus(status: unknown): void {
|
||||
if (typeof status !== "string" || !this.allowedStatuses.has(status)) {
|
||||
throw new BadRequestException("Unknown task status");
|
||||
}
|
||||
}
|
||||
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: "لیست تسکهای دپارتمانها و ایجنتها" })
|
||||
async findAll(@Query() query: any) {
|
||||
const page = Number(query.page) || 1;
|
||||
const limit = Number(query.limit) || 100;
|
||||
const skip = (page - 1) * limit;
|
||||
|
||||
const where: any = {};
|
||||
if (query.department) where.department = query.department;
|
||||
if (query.status) where.status = query.status;
|
||||
if (query.priority) where.priority = query.priority;
|
||||
if (query.search) {
|
||||
where.OR = [
|
||||
{ code: { contains: query.search, mode: "insensitive" } },
|
||||
{ title: { contains: query.search, mode: "insensitive" } },
|
||||
{ description: { contains: query.search, mode: "insensitive" } },
|
||||
];
|
||||
}
|
||||
|
||||
const [total, items] = await Promise.all([
|
||||
(this.prisma as any).departmentTask.count({ where }),
|
||||
(this.prisma as any).departmentTask.findMany({
|
||||
where,
|
||||
skip,
|
||||
take: limit,
|
||||
orderBy: [{ priority: "desc" }, { createdAt: "desc" }],
|
||||
}),
|
||||
]);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: items,
|
||||
meta: {
|
||||
total,
|
||||
page,
|
||||
limit,
|
||||
totalPages: Math.ceil(total / limit),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@Get("stats")
|
||||
@ApiOperation({ summary: "آمار تسکها به تفکیک استیت و دپارتمان" })
|
||||
async getStats() {
|
||||
const tasks = await (this.prisma as any).departmentTask.findMany({
|
||||
select: { department: true, status: true, priority: true },
|
||||
});
|
||||
|
||||
const statusCounts: Record<string, number> = {
|
||||
TODO: 0,
|
||||
IN_PROGRESS: 0,
|
||||
TEST: 0,
|
||||
DONE: 0,
|
||||
BACKLOG: 0,
|
||||
IN_REVIEW: 0,
|
||||
APPROVED: 0,
|
||||
DEPLOYING: 0,
|
||||
};
|
||||
const departmentCounts: Record<string, number> = {};
|
||||
|
||||
for (const t of tasks) {
|
||||
statusCounts[t.status] = (statusCounts[t.status] || 0) + 1;
|
||||
departmentCounts[t.department] = (departmentCounts[t.department] || 0) + 1;
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
total: tasks.length,
|
||||
byStatus: statusCounts,
|
||||
byDepartment: departmentCounts,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@Get(":id")
|
||||
@ApiOperation({ summary: "دریافت جزییات یک تسک" })
|
||||
async findOne(@Param("id") id: string) {
|
||||
const task = await (this.prisma as any).departmentTask.findUnique({
|
||||
where: { id },
|
||||
});
|
||||
if (!task) throw new NotFoundException(`Task ${id} not found`);
|
||||
return { success: true, data: task };
|
||||
}
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: "ایجاد تسک جدید سازمانی" })
|
||||
async create(@Body() body: any) {
|
||||
this.assertStatus(body.status || "TODO");
|
||||
// Creation cannot attest its own work; require an existing task for verification.
|
||||
if (body.status === "DONE") throw new BadRequestException("Create task before completing it");
|
||||
const code = body.code || "TSK-" + Date.now().toString().slice(-6);
|
||||
const task = await (this.prisma as any).departmentTask.create({
|
||||
data: {
|
||||
code,
|
||||
department: body.department,
|
||||
title: body.title,
|
||||
description: body.description || null,
|
||||
status: body.status || "TODO",
|
||||
priority: body.priority || "MEDIUM",
|
||||
assignee: body.assignee || "AI_AGENT",
|
||||
acceptanceCriteria: body.acceptanceCriteria || null,
|
||||
executionLogs: body.executionLogs || [],
|
||||
deliverableUrl: body.deliverableUrl || null,
|
||||
startedAt: body.status === "IN_PROGRESS" ? new Date() : null,
|
||||
},
|
||||
});
|
||||
|
||||
await (this.prisma as any).auditLog.create({
|
||||
data: {
|
||||
entity: "task",
|
||||
entityId: task.id,
|
||||
action: "CREATE",
|
||||
department: task.department,
|
||||
actor: task.assignee || "SYSTEM",
|
||||
summary: "تسک جدید " + task.code + " (" + task.title + ") ایجاد شد.",
|
||||
newValues: task,
|
||||
},
|
||||
});
|
||||
|
||||
return { success: true, data: task };
|
||||
}
|
||||
|
||||
@Put(":id/status")
|
||||
@ApiOperation({ summary: "تغییر وضعیت تسک همراه با لاگ اجرا" })
|
||||
async updateStatus(
|
||||
@Param("id") id: string,
|
||||
@Body() body: { status: string; logNote?: string; deliverableUrl?: string }
|
||||
) {
|
||||
const existing = await (this.prisma as any).departmentTask.findUnique({
|
||||
where: { id },
|
||||
});
|
||||
if (!existing) throw new NotFoundException(`Task ${id} not found`);
|
||||
this.assertStatus(body.status);
|
||||
|
||||
const logs = Array.isArray(existing.executionLogs) ? [...existing.executionLogs] : [];
|
||||
if (body.logNote) {
|
||||
logs.push({
|
||||
timestamp: new Date().toISOString(),
|
||||
status: body.status,
|
||||
note: body.logNote,
|
||||
});
|
||||
}
|
||||
|
||||
const candidateDeliverableUrl = body.deliverableUrl || existing.deliverableUrl;
|
||||
let attestation: { taskId: string; artifactType: string; artifactId: string; artifactUrl: string; verifier: string; verifiedAt: Date } | undefined;
|
||||
if (body.status === "DONE") {
|
||||
// Only a canonical first-party blog URL is an eligible identity. Never fetch
|
||||
// arbitrary caller URLs (SSRF), or accept claims in executionLogs as proof.
|
||||
let url: URL;
|
||||
try { url = new URL(candidateDeliverableUrl); }
|
||||
catch { throw new BadRequestException("DONE requires a canonical published blog URL"); }
|
||||
const match = /^\/blog\/([a-z0-9]+(?:-[a-z0-9]+)*)$/.exec(url.pathname);
|
||||
if (url.protocol !== "https:" || url.hostname !== "canina.ir" ||
|
||||
url.port || url.username || url.password || url.search || url.hash || !match ||
|
||||
/^post-tsk(?:-|$)/.test(match[1])) {
|
||||
throw new BadRequestException("DONE requires a canonical published blog URL");
|
||||
}
|
||||
const blog = await (this.prisma as any).blog.findUnique({ where: { slug: match[1] } });
|
||||
if (!blog || blog.status !== "PUBLISHED" || blog.isPublished !== true) {
|
||||
throw new BadRequestException("DONE requires an independently verified published artifact");
|
||||
}
|
||||
attestation = {
|
||||
taskId: id, artifactType: "BLOG", artifactId: blog.id,
|
||||
artifactUrl: candidateDeliverableUrl, verifier: "SERVER_ARTIFACT_VERIFIER",
|
||||
verifiedAt: new Date(),
|
||||
};
|
||||
assertTaskCanComplete({
|
||||
id, code: existing.code, title: existing.title,
|
||||
deliverableUrl: candidateDeliverableUrl,
|
||||
acceptanceCriteria: existing.acceptanceCriteria,
|
||||
attestation,
|
||||
});
|
||||
}
|
||||
|
||||
const updateData: any = {
|
||||
status: body.status,
|
||||
executionLogs: logs,
|
||||
};
|
||||
if (body.deliverableUrl) updateData.deliverableUrl = body.deliverableUrl;
|
||||
if (body.status === "IN_PROGRESS" && !existing.startedAt) updateData.startedAt = new Date();
|
||||
if (body.status === "DONE") updateData.completedAt = new Date();
|
||||
if (body.status === "TODO" && body.logNote) {
|
||||
updateData.description = (existing.description || "") + "\n\n[اصلاحات و تضمین کیفیت QA]: " + body.logNote;
|
||||
}
|
||||
|
||||
const updated = attestation
|
||||
? await (this.prisma as any).$transaction(async (tx: any) => {
|
||||
// Persist attestation and transition together: no DONE without its record.
|
||||
await tx.taskCompletionAttestation.create({ data: attestation });
|
||||
return tx.departmentTask.update({ where: { id }, data: updateData });
|
||||
})
|
||||
: await (this.prisma as any).departmentTask.update({ where: { id }, data: updateData });
|
||||
|
||||
await (this.prisma as any).auditLog.create({
|
||||
data: {
|
||||
entity: "task",
|
||||
entityId: updated.id,
|
||||
action: "UPDATE",
|
||||
department: updated.department,
|
||||
actor: "SYSTEM",
|
||||
summary: "وضعیت تسک " + updated.code + " به " + body.status + " تغییر یافت.",
|
||||
oldValues: { status: existing.status },
|
||||
newValues: { status: updated.status, note: body.logNote },
|
||||
},
|
||||
});
|
||||
|
||||
return { success: true, data: updated };
|
||||
}
|
||||
|
||||
@Delete(":id")
|
||||
@ApiOperation({ summary: "حذف تسک" })
|
||||
async remove(@Param("id") id: string) {
|
||||
await (this.prisma as any).departmentTask.delete({ where: { id } });
|
||||
return { success: true, message: "Deleted successfully" };
|
||||
}
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsString, IsOptional, IsObject } from "class-validator";
|
||||
|
||||
export class CreateApprovalRequestDto {
|
||||
@ApiProperty({ description: "دپارتمان مبدا (DEV, SUPPLY, FINANCE, SEO, CRM, CONTENT)" })
|
||||
@IsString()
|
||||
department: string;
|
||||
|
||||
@ApiProperty({ description: "دستهبندی (PRICING, PURCHASE_ORDER, CAMPAIGN, DEPLOY, etc)" })
|
||||
@IsString()
|
||||
category: string;
|
||||
|
||||
@ApiProperty({ description: "عنوان مورد تایید" })
|
||||
@IsString()
|
||||
title: string;
|
||||
|
||||
@ApiProperty({ description: "دادههای تغییرات پیشنهادی" })
|
||||
@IsObject()
|
||||
payload: Record<string, any>;
|
||||
|
||||
@ApiPropertyOptional({ description: "دادههای سناریوی تست و ارزیابی" })
|
||||
@IsOptional()
|
||||
@IsObject()
|
||||
testContext?: Record<string, any>;
|
||||
}
|
||||
|
||||
export class DecideApprovalDto {
|
||||
@ApiProperty({ description: "تصمیم: APPROVED یا REJECTED" })
|
||||
@IsString()
|
||||
decision: "APPROVED" | "REJECTED";
|
||||
|
||||
@ApiPropertyOptional({ description: "توضیحات و یادداشت مدیرعامل" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
ceoNotes?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "نتیجه اقدام مدیریتی یا استراتژیک" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
outcome?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "مستندات و مدرک اقدام مدیریتی" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
evidence?: string;
|
||||
}
|
||||
|
||||
export class QueryApprovalDto {
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
department?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
category?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
status?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
page?: number;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
limit?: number;
|
||||
}
|
||||
@@ -5,9 +5,12 @@ import {
|
||||
IsEmail,
|
||||
MinLength,
|
||||
IsNumber,
|
||||
IsIn,
|
||||
} from "class-validator";
|
||||
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||
|
||||
import { ALLOWED_USER_ROLES } from "../user-role-policy";
|
||||
|
||||
export class CreateUserDto {
|
||||
@ApiProperty({ description: "نام کاربر", example: "علی" })
|
||||
@IsNotEmpty({ message: "نام الزامی است" })
|
||||
@@ -41,6 +44,7 @@ export class CreateUserDto {
|
||||
@ApiPropertyOptional({ description: "نقش کاربر", example: "User_PetOwner" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@IsIn(ALLOWED_USER_ROLES)
|
||||
role?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "موجودی اولیه کیف پول", example: 0 })
|
||||
@@ -85,6 +89,7 @@ export class UpdateUserDto {
|
||||
@ApiPropertyOptional({ description: "نقش کاربر", example: "User_PetOwner" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@IsIn(ALLOWED_USER_ROLES)
|
||||
role?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "موجودی کیف پول", example: 500000 })
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { ForbiddenException } from "@nestjs/common";
|
||||
|
||||
export const ALLOWED_USER_ROLES = [
|
||||
"User_PetOwner", "User_Vet", "User_Clinic", "User_PetShop",
|
||||
"User_Wholesale", "User_B2B", "Customer", "Admin", "ADMIN", "SUPER_ADMIN",
|
||||
];
|
||||
|
||||
export interface UserAdminActor {
|
||||
id?: string;
|
||||
role?: string;
|
||||
isApiKey?: boolean;
|
||||
}
|
||||
|
||||
// Match RolesGuard semantics; keep stored values unchanged.
|
||||
export function isSuperAdminRole(role?: string): boolean {
|
||||
const normalized = typeof role === "string" ? role.toLowerCase().replace(/[_-]/g, "") : "";
|
||||
return normalized === "superadmin" || normalized === "adminsuper";
|
||||
}
|
||||
|
||||
export function assertUserMutationAllowed(actor?: UserAdminActor, currentRole?: string, nextRole?: string): void {
|
||||
const role = actor?.role?.toLowerCase().replace(/[_-]/g, "");
|
||||
const isSuperAdmin = !!actor?.id && !actor.isApiKey && isSuperAdminRole(actor.role);
|
||||
if ((!actor?.id && !actor?.isApiKey) || (role !== "admin" && !isSuperAdmin) ||
|
||||
((isSuperAdminRole(currentRole) || isSuperAdminRole(nextRole)) && !isSuperAdmin)) {
|
||||
throw new ForbiddenException("فقط مدیر ارشد مجاز به مدیریت حساب و نقش مدیر ارشد است");
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import { SmsService } from "../common/services/sms.service";
|
||||
import * as bcrypt from "bcryptjs";
|
||||
import * as crypto from "crypto";
|
||||
import { normalizeMobile } from "../common/utils/phone.utils";
|
||||
import { assertPrincipalActive } from "./stage-test-principal";
|
||||
import { getJwtRefreshSecret } from "./auth.constants";
|
||||
|
||||
export class RegisterInput {
|
||||
@@ -200,7 +201,8 @@ export class AuthService {
|
||||
});
|
||||
}
|
||||
|
||||
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role };
|
||||
assertPrincipalActive(user);
|
||||
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role, ...(user.stageTestSession ? {stageTestSession:user.stageTestSession, stageTestGeneration:user.stageTestGeneration} : {}) };
|
||||
const tokens = await this.generateTokens(payload);
|
||||
|
||||
const { password: _p, ...safeUser } = user;
|
||||
@@ -257,7 +259,8 @@ export class AuthService {
|
||||
},
|
||||
});
|
||||
|
||||
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role };
|
||||
assertPrincipalActive(user);
|
||||
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role, ...(user.stageTestSession ? {stageTestSession:user.stageTestSession, stageTestGeneration:user.stageTestGeneration} : {}) };
|
||||
const tokens = await this.generateTokens(payload);
|
||||
|
||||
const { password: _p, ...safeUser } = user;
|
||||
@@ -300,7 +303,8 @@ export class AuthService {
|
||||
});
|
||||
}
|
||||
|
||||
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role };
|
||||
assertPrincipalActive(user);
|
||||
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role, ...(user.stageTestSession ? {stageTestSession:user.stageTestSession, stageTestGeneration:user.stageTestGeneration} : {}) };
|
||||
const tokens = await this.generateTokens(payload);
|
||||
|
||||
const { password: _pw, ...safeUser } = user;
|
||||
@@ -326,10 +330,12 @@ export class AuthService {
|
||||
if (dbAdmin && dbAdmin.password && body.password) {
|
||||
const isMatch = await bcrypt.compare(body.password, dbAdmin.password);
|
||||
if (isMatch) {
|
||||
assertPrincipalActive(dbAdmin);
|
||||
const payload = {
|
||||
sub: dbAdmin.id,
|
||||
email: dbAdmin.email,
|
||||
role: dbAdmin.role,
|
||||
...(dbAdmin.stageTestSession ? {stageTestSession:dbAdmin.stageTestSession, stageTestGeneration:dbAdmin.stageTestGeneration} : {}),
|
||||
};
|
||||
const tokens = await this.generateTokens(payload);
|
||||
const { password: _p, ...safeUser } = dbAdmin;
|
||||
@@ -443,11 +449,14 @@ export class AuthService {
|
||||
|
||||
const user = await this.prisma.user.findUnique({ where: { id: userId } });
|
||||
if (user) {
|
||||
assertPrincipalActive(user);
|
||||
if (user.stageTestSession && (!user.stageTestGeneration || decoded.stageTestGeneration !== user.stageTestGeneration || decoded.stageTestSession !== user.stageTestSession)) throw new UnauthorizedException("Stage session revoked");
|
||||
userPayload = {
|
||||
sub: user.id,
|
||||
email: user.email,
|
||||
phoneNumber: user.mobile,
|
||||
role: user.role,
|
||||
...(user.stageTestSession ? {stageTestSession:user.stageTestSession, stageTestGeneration:user.stageTestGeneration} : {}),
|
||||
};
|
||||
const { password: _p, ...restUser } = user;
|
||||
safeUser = restUser;
|
||||
@@ -487,12 +496,15 @@ export class AuthService {
|
||||
email?: string;
|
||||
role?: string;
|
||||
mobile?: string;
|
||||
stageTestSession?: string | null;
|
||||
stageTestGeneration?: string | null;
|
||||
}) {
|
||||
const payload = {
|
||||
sub: user.id,
|
||||
email: user.email,
|
||||
role: user.role,
|
||||
phoneNumber: user.mobile,
|
||||
...(user.stageTestSession ? {stageTestSession:user.stageTestSession, stageTestGeneration:user.stageTestGeneration} : {}),
|
||||
};
|
||||
const tokens = await this.generateTokens(payload);
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { AdminService } from '../admin/admin.service';
|
||||
import { STAGE_TEST_ID, STAGE_TEST_EMAIL, STAGE_TEST_MOBILE } from './stage-test-principal';
|
||||
const sha='a'.repeat(40), generation='8311eb41-23b4-4aab-ade2-e97b90debc11';
|
||||
const env={APP_ENV:'stage',CI:'true',STAGE_TEST_PRINCIPAL_ENABLED:'true',STAGE_TEST_APPROVAL:'owner-authorized-stage-editorial',STAGE_TEST_SHA:sha,STAGE_TEST_SESSION:'cleanup-session',STAGE_TEST_TTL_SECONDS:'600',STAGE_TEST_GENERATION:generation};
|
||||
describe('durable cleanup ownership fence',()=>{
|
||||
it('does not revoke a replacement generation',async()=>{
|
||||
const update=jest.fn();
|
||||
const db={user:{findUnique:async()=>({id:STAGE_TEST_ID,email:STAGE_TEST_EMAIL,mobile:STAGE_TEST_MOBILE,stageTestSession:env.STAGE_TEST_SESSION,stageTestGeneration:'replacement',authExpiresAt:new Date()}),update}};
|
||||
await expect(new AdminService(db as any,undefined as any,undefined as any).cleanupStageTestPrincipal(env,sha)).rejects.toThrow('Refusing');
|
||||
expect(update).not.toHaveBeenCalled();
|
||||
});
|
||||
it('confirms revocation before relational deletion failure',async()=>{
|
||||
const events:string[]=[];
|
||||
const db={user:{findUnique:async()=>({id:STAGE_TEST_ID,email:STAGE_TEST_EMAIL,mobile:STAGE_TEST_MOBILE,stageTestSession:env.STAGE_TEST_SESSION,stageTestGeneration:generation,authExpiresAt:new Date()}),update:async()=>events.push('revoke')},$transaction:async()=>{events.push('delete');throw Error('FK failure');}};
|
||||
await expect((new AdminService(db as any,undefined as any,undefined as any).cleanupStageTestPrincipal as any)(env,sha,()=>events.push('handle-removed'))).rejects.toThrow('FK failure');
|
||||
expect(events).toEqual(['revoke','handle-removed','delete']);
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import { ExtractJwt, Strategy } from "passport-jwt";
|
||||
import { PassportStrategy } from "@nestjs/passport";
|
||||
import { Injectable, UnauthorizedException } from "@nestjs/common";
|
||||
import { UsersService } from "../users/users.service";
|
||||
import { assertPrincipalActive } from "./stage-test-principal";
|
||||
import { getJwtSecret } from "./auth.constants";
|
||||
|
||||
import { RedisService } from "../redis/redis.service";
|
||||
@@ -12,6 +13,8 @@ export interface JwtPayload {
|
||||
email?: string;
|
||||
role?: string;
|
||||
phoneNumber?: string;
|
||||
stageTestSession?: string;
|
||||
stageTestGeneration?: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
@@ -59,6 +62,13 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
|
||||
if (!user) {
|
||||
throw new UnauthorizedException("کاربر یافت نشد");
|
||||
}
|
||||
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] || '';
|
||||
const allowed = req.method === 'GET' && /^\/api\/admin\/orchestration\/tasks(?:\/[a-f0-9-]+)?$/.test(path) || req.method === 'POST' && (/^\/api\/admin\/orchestration\/tasks$/.test(path) || /^\/api\/admin\/orchestration\/tasks\/[a-f0-9-]+\/(?:gates\/1\/decide|editorial-failure|editorial-completed-recovery)$/.test(path));
|
||||
if (!allowed) throw new UnauthorizedException('Stage test scope denied');
|
||||
}
|
||||
return user;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { AuthService } from './auth.service';
|
||||
import { RedisService } from '../redis/redis.service';
|
||||
import { STAGE_TEST_ID } from './stage-test-principal';
|
||||
import { createServer, Server } from 'http';
|
||||
import { execFile } from 'child_process';
|
||||
import { promisify } from 'util';
|
||||
import { readFileSync, writeFileSync, existsSync } from 'fs';
|
||||
const enabled=process.env.STAGE_PRINCIPAL_DISPOSABLE_TEST==='true';
|
||||
(enabled?describe:describe.skip)('actual internal CLI disposable lifecycle',()=>{
|
||||
const sha='a'.repeat(40), generation='b411eb41-23b4-4aab-ade2-e97b90debc11', session='cli-integration-session';
|
||||
const handle=`/app/private-stage-test/${session}.json`;
|
||||
const db=new PrismaClient({log:[]}), redis=new RedisService(); let server:Server;
|
||||
const env={...process.env,APP_ENV:'stage',CI:'true',STAGE_TEST_PRINCIPAL_ENABLED:'true',STAGE_TEST_APPROVAL:'owner-authorized-stage-editorial',STAGE_TEST_SHA:sha,STAGE_TEST_SESSION:session,STAGE_TEST_TTL_SECONDS:'600',STAGE_TEST_GENERATION:generation};
|
||||
const cli=(action:string)=>promisify(execFile)(process.execPath,['-r','ts-node/register','src/auth/stage-test-principal.cli.ts',action],{env,timeout:90000});
|
||||
beforeAll(async()=>{
|
||||
if(!process.env.DATABASE_URL?.endsWith('/principal_disposable')) throw Error('Disposable database only');
|
||||
writeFileSync('/app/STAGE_TEST_ARTIFACT_SHA',sha); redis.onModuleInit();
|
||||
const auth=new AuthService(db as any,new JwtService({secret:process.env.JWT_SECRET,signOptions:{expiresIn:'2h'}}),redis,undefined as any);
|
||||
server=createServer(async(req,res)=>{
|
||||
try {let body='';for await(const chunk of req) body+=chunk;
|
||||
if(req.url!=='/api/auth/admin-login') {res.writeHead(404).end();return;}
|
||||
const login=await auth.adminLogin(JSON.parse(body));res.setHeader('content-type','application/json');res.end(JSON.stringify(login));
|
||||
} catch {res.writeHead(401).end();}
|
||||
});
|
||||
await new Promise<void>(r=>server.listen(3000,'127.0.0.1',r));
|
||||
},120000);
|
||||
afterAll(async()=>{await new Promise<void>(r=>server.close(()=>r()));redis.onModuleDestroy();await db.$disconnect();});
|
||||
it('logs in using persisted credentials and removes handle on confirmed revocation despite failed delete',async()=>{
|
||||
await cli('open'); expect(existsSync(handle)).toBe(true);
|
||||
const credential=JSON.parse(readFileSync(handle,'utf8'));expect(credential.accessToken).toBeTruthy();
|
||||
expect((await db.user.findUnique({where:{id:STAGE_TEST_ID}}))?.stageTestGeneration).toBe(generation);
|
||||
await db.$executeRawUnsafe(`CREATE FUNCTION deny_principal_delete() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'test FK deletion failure'; END $$`);
|
||||
await db.$executeRawUnsafe(`CREATE TRIGGER deny_principal_delete BEFORE DELETE ON users FOR EACH ROW EXECUTE FUNCTION deny_principal_delete()`);
|
||||
try {
|
||||
await expect(cli('close')).rejects.toThrow();
|
||||
expect(existsSync(handle)).toBe(false);
|
||||
const revoked=await db.user.findUnique({where:{id:STAGE_TEST_ID}});
|
||||
expect(revoked?.authExpiresAt?.getTime()).toBe(0);expect(revoked?.password).toBe('');
|
||||
} finally {await db.$executeRawUnsafe(`DROP TRIGGER deny_principal_delete ON users`);await db.$executeRawUnsafe(`DROP FUNCTION deny_principal_delete()`);}
|
||||
await cli('close');expect(await db.user.findUnique({where:{id:STAGE_TEST_ID}})).toBeNull();
|
||||
},240000);
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
import 'reflect-metadata';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { randomBytes } from 'crypto';
|
||||
import { mkdirSync, openSync, writeFileSync, closeSync, readFileSync, statSync, unlinkSync, constants } from 'fs';
|
||||
import { AdminService } from '../admin/admin.service';
|
||||
import { authorizeStageSession, STAGE_TEST_EMAIL } from './stage-test-principal';
|
||||
|
||||
// CI-only internal seed command; deliberately not registered in AppModule.
|
||||
async function main() {
|
||||
const sha = readFileSync('/app/STAGE_TEST_ARTIFACT_SHA', 'utf8').trim();
|
||||
const grant = authorizeStageSession(process.env, sha);
|
||||
const action = process.argv[2];
|
||||
if (action === 'cleanup-capability') { process.stdout.write('stage-generation-cleanup-v1'); return; }
|
||||
if (!['open','close'].includes(action)) throw new Error('Unknown command');
|
||||
const root = '/app/private-stage-test';
|
||||
mkdirSync(root,{recursive:true,mode:0o700});
|
||||
const st = statSync(root);
|
||||
if (st.uid !== process.getuid!() || (st.mode & 0o777) !== 0o700) throw new Error('Unsafe private directory');
|
||||
if (!/^[a-f0-9-]{36}$/.test(process.env.STAGE_TEST_GENERATION || '')) throw new Error('Generation required');
|
||||
const handle = `${root}/${grant.session}.json`;
|
||||
const removeHandle = () => { try {unlinkSync(handle);} catch(e:any) {if(e.code !== 'ENOENT') throw e;} };
|
||||
const audit = (event:string) => {
|
||||
const fd = openSync(`${root}/audit.jsonl`, constants.O_WRONLY|constants.O_CREAT|constants.O_APPEND|constants.O_NOFOLLOW,0o600);
|
||||
try { writeFileSync(fd,JSON.stringify({event,sha,session:grant.session,at:new Date().toISOString()})+'\n'); } finally {closeSync(fd);}
|
||||
};
|
||||
const db = new PrismaClient({log:[]});
|
||||
const service = new AdminService(db as any,undefined as any,undefined as any);
|
||||
try {
|
||||
audit(`${action}-requested`);
|
||||
if(action === 'close') {
|
||||
await service.cleanupStageTestPrincipal(process.env,sha,removeHandle);
|
||||
audit('revoked-and-deleted');
|
||||
return;
|
||||
}
|
||||
let fd:number;
|
||||
let password:string;
|
||||
try {
|
||||
fd = openSync(handle,constants.O_WRONLY|constants.O_CREAT|constants.O_EXCL|constants.O_NOFOLLOW,0o600);
|
||||
password = randomBytes(48).toString('base64url');
|
||||
try {writeFileSync(fd,JSON.stringify({password}));} finally {closeSync(fd);}
|
||||
} catch(e:any) {
|
||||
if(e.code !== 'EEXIST') throw e;
|
||||
fd = openSync(handle,constants.O_RDONLY|constants.O_NOFOLLOW);
|
||||
try {
|
||||
const {fstatSync} = await import('fs'); const s=fstatSync(fd);
|
||||
if(!s.isFile() || s.uid !== process.getuid!() || (s.mode & 0o777) !== 0o600) throw new Error('Unsafe handle');
|
||||
password=JSON.parse(readFileSync(fd,'utf8')).password;
|
||||
} finally {closeSync(fd);}
|
||||
}
|
||||
const user=await service.provisionStageTestPrincipal(process.env,sha,password);
|
||||
// Use deployed persisted-account HTTP login, never sign tokens here.
|
||||
const response=await fetch('http://127.0.0.1:3000/api/auth/admin-login',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({email:STAGE_TEST_EMAIL,password}),signal:AbortSignal.timeout(15000)});
|
||||
if(!response.ok) throw new Error('Persisted login failed');
|
||||
const result:any=await response.json();
|
||||
if(result.data?.user?.id !== user.id || result.data?.user?.role !== 'SUPER_ADMIN' || !result.data?.accessToken) throw new Error('Persisted login mismatch');
|
||||
fd=openSync(handle,constants.O_WRONLY|constants.O_TRUNC|constants.O_NOFOLLOW);
|
||||
try {writeFileSync(fd,JSON.stringify({password,...result.data,expiresAt:user.authExpiresAt}));} finally {closeSync(fd);}
|
||||
audit('created-and-login-verified');
|
||||
// Only an opaque local path is public. Never upload this file as a CI artifact.
|
||||
process.stdout.write(`Stage credential handle: ${handle}\n`);
|
||||
} catch {
|
||||
audit('failed');
|
||||
// Leave only a revoked account if relational cleanup fails.
|
||||
await service.cleanupStageTestPrincipal(process.env,sha,removeHandle).catch(()=>undefined);
|
||||
throw new Error('Stage test principal operation failed; inspect private audit');
|
||||
} finally {await db.$disconnect();}
|
||||
}
|
||||
main().catch(()=>{process.stderr.write('Stage test principal denied or failed\n');process.exitCode=1;});
|
||||
@@ -0,0 +1,58 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { randomBytes } from 'crypto';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { AdminService } from '../admin/admin.service';
|
||||
import { AuthService } from './auth.service';
|
||||
import { UsersService } from '../users/users.service';
|
||||
import { JwtStrategy } from './jwt.strategy';
|
||||
import { RedisService } from '../redis/redis.service';
|
||||
import { STAGE_TEST_ID, STAGE_TEST_EMAIL, STAGE_TEST_MOBILE } from './stage-test-principal';
|
||||
const enabled=process.env.STAGE_PRINCIPAL_DISPOSABLE_TEST === 'true';
|
||||
(enabled ? describe : describe.skip)('disposable persisted Stage principal lifecycle',()=>{
|
||||
const sha='a'.repeat(40), grant={APP_ENV:'stage',CI:'true',STAGE_TEST_PRINCIPAL_ENABLED:'true',STAGE_TEST_APPROVAL:'owner-authorized-stage-editorial',STAGE_TEST_SHA:sha,STAGE_TEST_SESSION:'integration-session',STAGE_TEST_TTL_SECONDS:'600'};
|
||||
const db=new PrismaClient({log:[]}); const redis=new RedisService();
|
||||
let admin:AdminService,auth:AuthService,strategy:JwtStrategy,password:string;
|
||||
beforeAll(async()=>{
|
||||
// Deliberately require a disposable database name; never point this suite at Stage.
|
||||
if(!process.env.DATABASE_URL?.endsWith('/principal_disposable')) throw new Error('Disposable database required');
|
||||
redis.onModuleInit(); password=randomBytes(48).toString('base64url');
|
||||
admin=new AdminService(db as any,redis,undefined as any);
|
||||
auth=new AuthService(db as any,new JwtService({secret:process.env.JWT_SECRET,signOptions:{expiresIn:'2h'}}),redis,undefined as any);
|
||||
strategy=new JwtStrategy(new UsersService(db as any),redis);
|
||||
});
|
||||
afterAll(async()=>{await admin.cleanupStageTestPrincipal(grant,sha); await db.$disconnect();redis.onModuleDestroy();});
|
||||
it('rejects unowned collision and never changes it',async()=>{
|
||||
const collision=await db.user.create({data:{firstName:'Unowned',lastName:'Account',email:STAGE_TEST_EMAIL,mobile:STAGE_TEST_MOBILE}});
|
||||
try {
|
||||
await expect(admin.provisionStageTestPrincipal(grant,sha,password)).rejects.toThrow('Refusing');
|
||||
expect((await db.user.findUnique({where:{id:collision.id}}))?.role).toBe('User_PetOwner');
|
||||
} finally {await db.user.delete({where:{id:collision.id}});}
|
||||
});
|
||||
it('creates through account service, logs in, verifies signed tokens, never renews retry TTL',async()=>{
|
||||
const u=await admin.provisionStageTestPrincipal(grant,sha,password);
|
||||
expect(u.id).toBe(STAGE_TEST_ID); expect(u.role).toBe('SUPER_ADMIN'); expect(u.password).not.toBe(password);
|
||||
const retry=await admin.provisionStageTestPrincipal(grant,sha,password); expect(retry.authExpiresAt).toEqual(u.authExpiresAt);
|
||||
await expect(admin.provisionStageTestPrincipal({...grant,STAGE_TEST_SESSION:'different-session'},sha,password)).rejects.toThrow('Refusing');
|
||||
const login=await auth.adminLogin({email:STAGE_TEST_EMAIL,password});
|
||||
const jwt=new JwtService({secret:process.env.JWT_SECRET});
|
||||
const payload=jwt.verify(login.data.accessToken); expect(payload.sub).toBe(u.id);expect(payload.role).toBe('SUPER_ADMIN');
|
||||
const req:any={method:'GET',originalUrl:'/api/admin/orchestration/tasks',headers:{authorization:`Bearer ${login.data.accessToken}`}};
|
||||
expect((await strategy.validate(req,payload)).id).toBe(u.id);
|
||||
await expect(strategy.validate({...req,originalUrl:'/api/admin/users'},payload)).rejects.toThrow('scope denied');
|
||||
await expect(strategy.validate({...req,method:'POST',originalUrl:'/api/admin/orchestration/tasks/abcd/gates/2/decide'},payload)).rejects.toThrow('scope denied');
|
||||
// Fixture time travel: persisted expiry is enforced independently of the long-lived signed token.
|
||||
await db.user.update({where:{id:u.id},data:{authExpiresAt:new Date(0)}});
|
||||
await expect(strategy.validate(req,payload)).rejects.toThrow();
|
||||
await expect(auth.adminLogin({email:STAGE_TEST_EMAIL,password})).rejects.toThrow();
|
||||
await expect(auth.refreshToken(login.data.refreshToken)).rejects.toThrow();
|
||||
await admin.cleanupStageTestPrincipal(grant,sha);
|
||||
await expect(strategy.validate(req,payload)).rejects.toThrow();
|
||||
expect(await db.user.findUnique({where:{id:u.id}})).toBeNull();
|
||||
const replacement=await admin.provisionStageTestPrincipal(grant,sha,password);
|
||||
expect(replacement.stageTestGeneration).not.toBe(u.stageTestGeneration);
|
||||
await expect(strategy.validate(req,payload)).rejects.toThrow();
|
||||
await expect(auth.refreshToken(login.data.refreshToken)).rejects.toThrow();
|
||||
const fresh=await auth.adminLogin({email:STAGE_TEST_EMAIL,password});
|
||||
expect((await strategy.validate(req,jwt.verify(fresh.data.accessToken))).id).toBe(u.id);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
import { assertPrincipalActive, authorizeStageSession } from './stage-test-principal';
|
||||
const sha = 'a'.repeat(40);
|
||||
const valid = { APP_ENV: 'stage', STAGE_TEST_PRINCIPAL_ENABLED: 'true', CI: 'true', STAGE_TEST_APPROVAL: 'owner-authorized-stage-editorial', STAGE_TEST_SHA: sha, STAGE_TEST_SESSION: 'editorial-20261024', STAGE_TEST_TTL_SECONDS: '600' };
|
||||
describe('Stage CI authority', () => {
|
||||
it('denies by default and in Production despite opt in', () => {
|
||||
expect(() => authorizeStageSession({}, sha)).toThrow();
|
||||
expect(() => authorizeStageSession({...valid, APP_ENV:'production'}, sha)).toThrow();
|
||||
});
|
||||
it('requires immutable matching SHA and bounded explicit authorization', () => {
|
||||
expect(authorizeStageSession(valid, sha).ttl).toBe(600);
|
||||
for(const patch of [{STAGE_TEST_SHA:'main'}, {STAGE_TEST_SHA:'b'.repeat(40)}, {STAGE_TEST_TTL_SECONDS:'3601'}, {STAGE_TEST_TTL_SECONDS:'0'}, {STAGE_TEST_APPROVAL:''}, {CI:''}]) expect(() => authorizeStageSession({...valid,...patch},sha)).toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
// 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';
|
||||
export const STAGE_TEST_MOBILE = '09999999071';
|
||||
export function authorizeStageSession(env: NodeJS.ProcessEnv, artifactSha: string) {
|
||||
if (env.APP_ENV !== 'stage' || env.STAGE_TEST_PRINCIPAL_ENABLED !== 'true' || env.CI !== 'true' || env.STAGE_TEST_APPROVAL !== 'owner-authorized-stage-editorial' || !/^[a-f0-9]{40}$/.test(artifactSha) || env.STAGE_TEST_SHA !== artifactSha || !/^[a-z0-9-]{8,64}$/.test(env.STAGE_TEST_SESSION || '')) throw new Error('Stage CI authority denied');
|
||||
const ttl = Number(env.STAGE_TEST_TTL_SECONDS);
|
||||
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 }, now = Date.now()) {
|
||||
if (user.authExpiresAt && user.authExpiresAt.getTime() <= now) throw new Error('Principal expired');
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { JwtStrategy } from './jwt.strategy';
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
describe('Stage credentials remain fenced to their creation session', () => {
|
||||
const id='e876e7a0-738f-4e59-b6db-e270512ababc';
|
||||
const current={id, role:'SUPER_ADMIN', stageTestSession:'new-session', stageTestGeneration:'fresh-generation', authExpiresAt:new Date(Date.now()+600000)};
|
||||
const redis:any={get:jest.fn(async()=> '1'),del:jest.fn(),set:jest.fn()};
|
||||
beforeAll(()=> {process.env.JWT_SECRET='disposable-only-test-secret-at-least-32-characters';process.env.JWT_REFRESH_SECRET='disposable-only-refresh-secret-at-least-32-characters';});
|
||||
it('rejects an old-session access token after fixed account ID is recreated',async()=>{
|
||||
const strategy=new JwtStrategy({findById:async()=>current} as any,{get:async()=>null} as any);
|
||||
const req:any={method:'GET',originalUrl:'/api/admin/orchestration/tasks',headers:{}};
|
||||
await expect(strategy.validate(req,{sub:id,stageTestSession:'old-session'} as any)).rejects.toThrow();
|
||||
await expect(strategy.validate(req,{sub:id})).rejects.toThrow();
|
||||
await expect(strategy.validate(req,{sub:id,stageTestSession:'new-session',stageTestGeneration:'old-generation'} as any)).rejects.toThrow();
|
||||
await expect(strategy.validate(req,{sub:id,stageTestSession:'new-session',stageTestGeneration:'fresh-generation'} as any)).resolves.toMatchObject({id});
|
||||
});
|
||||
it('rejects an old-session refresh token even while its Redis entry remains active',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 token=jwt.sign({sub:id,jti:'old-refresh',role:'SUPER_ADMIN',stageTestSession:'old-session'},{secret:process.env.JWT_REFRESH_SECRET});
|
||||
await expect(auth.refreshToken(token)).rejects.toThrow();
|
||||
});
|
||||
it('includes session fencing in newly issued credentials',async()=>{
|
||||
const jwt=new JwtService({secret:process.env.JWT_SECRET});
|
||||
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');
|
||||
expect(jwt.verify(result.data.refreshToken,{secret:process.env.JWT_REFRESH_SECRET}).stageTestSession).toBe('new-session');
|
||||
});
|
||||
});
|
||||
@@ -2,8 +2,15 @@ import { Injectable, NotFoundException } from "@nestjs/common";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
import { PaginationDto } from "../common/dto/pagination.dto";
|
||||
import {
|
||||
createPaginationMeta,
|
||||
extractSearchTokens,
|
||||
normalizeSearchText,
|
||||
calculateRelevanceScore,
|
||||
} from "../common/utils/search.utils";
|
||||
|
||||
export interface BlogFilterDto extends PaginationDto {
|
||||
categoryId?: string;
|
||||
categorySlug?: string;
|
||||
tagSlug?: string;
|
||||
featured?: boolean | string;
|
||||
@@ -20,6 +27,7 @@ export class BlogsService {
|
||||
limit = 10,
|
||||
sortBy = "publishedAt",
|
||||
sortOrder = "desc",
|
||||
categoryId,
|
||||
categorySlug,
|
||||
tagSlug,
|
||||
featured,
|
||||
@@ -32,20 +40,23 @@ export class BlogsService {
|
||||
OR: [{ publishedAt: null }, { publishedAt: { lte: now } }],
|
||||
};
|
||||
|
||||
if (search) {
|
||||
const tokens = extractSearchTokens(search);
|
||||
if (tokens.length > 0) {
|
||||
whereClause.AND = [
|
||||
{
|
||||
OR: [
|
||||
{ title: { contains: search, mode: "insensitive" } },
|
||||
{ excerpt: { contains: search, mode: "insensitive" } },
|
||||
{ content: { contains: search, mode: "insensitive" } },
|
||||
{ keywords: { contains: search, mode: "insensitive" } },
|
||||
],
|
||||
OR: tokens.flatMap((token) => [
|
||||
{ title: { contains: token, mode: "insensitive" } },
|
||||
{ excerpt: { contains: token, mode: "insensitive" } },
|
||||
{ keywords: { contains: token, mode: "insensitive" } },
|
||||
{ tags: { some: { name: { contains: token, mode: "insensitive" } } } },
|
||||
]),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (categorySlug) {
|
||||
if (categoryId && categoryId !== "ALL") {
|
||||
whereClause.categoryId = categoryId;
|
||||
} else if (categorySlug && categorySlug !== "all") {
|
||||
whereClause.category = { slug: categorySlug };
|
||||
}
|
||||
|
||||
@@ -57,13 +68,15 @@ export class BlogsService {
|
||||
whereClause.featured = String(featured) === "true";
|
||||
}
|
||||
|
||||
const skip = (Number(page) - 1) * Number(limit);
|
||||
const safePage = Math.max(1, Number(page) || 1);
|
||||
const safeLimit = Math.max(1, Number(limit) || 10);
|
||||
const skip = (safePage - 1) * safeLimit;
|
||||
|
||||
const [data, total] = await Promise.all([
|
||||
const [rawBlogs, total] = await Promise.all([
|
||||
this.prisma.blog.findMany({
|
||||
where: whereClause,
|
||||
skip,
|
||||
take: Number(limit),
|
||||
skip: tokens.length > 0 ? undefined : skip,
|
||||
take: tokens.length > 0 ? 100 : safeLimit,
|
||||
orderBy: [
|
||||
{
|
||||
[sortBy === "createdAt" ? "createdAt" : "publishedAt"]: sortOrder,
|
||||
@@ -88,14 +101,30 @@ export class BlogsService {
|
||||
this.prisma.blog.count({ where: whereClause }),
|
||||
]);
|
||||
|
||||
let data = rawBlogs;
|
||||
if (tokens.length > 0 && search) {
|
||||
data = [...rawBlogs]
|
||||
.map((b) => ({
|
||||
blog: b,
|
||||
score: calculateRelevanceScore(
|
||||
{
|
||||
title: b.title,
|
||||
slug: b.slug,
|
||||
shortDescription: b.excerpt,
|
||||
tags: b.tags,
|
||||
},
|
||||
search,
|
||||
tokens,
|
||||
),
|
||||
}))
|
||||
.sort((a, b) => b.score - a.score)
|
||||
.map((item) => item.blog)
|
||||
.slice(skip, skip + safeLimit);
|
||||
}
|
||||
|
||||
return {
|
||||
data,
|
||||
meta: {
|
||||
total,
|
||||
page: Number(page),
|
||||
lastPage: Math.ceil(total / Number(limit)) || 1,
|
||||
limit: Number(limit),
|
||||
},
|
||||
meta: createPaginationMeta(total, safePage, safeLimit),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -26,6 +26,16 @@ describe("RevalidationService", () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
|
||||
it("uses the Next server rather than the nginx API proxy as production fallback", async () => {
|
||||
delete process.env.FRONTEND_INTERNAL_URL;
|
||||
delete process.env.FRONTEND_URL;
|
||||
delete process.env.NEXT_PUBLIC_SITE_URL;
|
||||
process.env.NODE_ENV = "production";
|
||||
const fetchSpy = jest.spyOn(global, "fetch").mockResolvedValue({ ok: true } as Response);
|
||||
await service.revalidate(["blogs"], ["/blog"]);
|
||||
expect(fetchSpy).toHaveBeenCalledWith("http://frontend_prod:3000/api/revalidate", expect.anything());
|
||||
});
|
||||
|
||||
describe("revalidateTag", () => {
|
||||
it("should send POST request with tag and secret header and return true on 200", async () => {
|
||||
const mockFetch = jest.spyOn(global, "fetch" as any).mockResolvedValue({
|
||||
@@ -111,6 +121,48 @@ describe("RevalidationService", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("revalidateBlog", () => {
|
||||
it("should trigger all tags and paths for blog slug and return true when all succeed", async () => {
|
||||
const tagSpy = jest
|
||||
.spyOn(service, "revalidateTag")
|
||||
.mockResolvedValue(true);
|
||||
const pathSpy = jest
|
||||
.spyOn(service, "revalidatePath")
|
||||
.mockResolvedValue(true);
|
||||
|
||||
const result = await service.revalidateBlog("test-slug");
|
||||
|
||||
expect(tagSpy).toHaveBeenCalledWith("blogs");
|
||||
expect(tagSpy).toHaveBeenCalledWith("home-data");
|
||||
expect(tagSpy).toHaveBeenCalledWith("blog-test-slug");
|
||||
expect(pathSpy).toHaveBeenCalledWith("/blog");
|
||||
expect(pathSpy).toHaveBeenCalledWith("/sitemap.xml");
|
||||
expect(pathSpy).toHaveBeenCalledWith("/");
|
||||
expect(pathSpy).toHaveBeenCalledWith("/blog/test-slug");
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
it("should return false when a tag or path revalidation fails rather than swallowing false", async () => {
|
||||
jest.spyOn(service, "revalidateTag").mockImplementation(async (tag: string) => {
|
||||
return tag !== "blogs";
|
||||
});
|
||||
jest.spyOn(service, "revalidatePath").mockResolvedValue(true);
|
||||
|
||||
const result = await service.revalidateBlog("test-slug");
|
||||
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it("should catch unexpected revalidation errors and return false", async () => {
|
||||
jest.spyOn(service, "revalidateTag").mockRejectedValue(new Error("Network disconnected"));
|
||||
jest.spyOn(service, "revalidatePath").mockResolvedValue(true);
|
||||
|
||||
const result = await service.revalidateBlog("test-slug");
|
||||
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("revalidate batch", () => {
|
||||
it("should send deduplicated tags and paths in one request", async () => {
|
||||
const mockFetch = jest.spyOn(global, "fetch" as any).mockResolvedValue({ ok: true, status: 200 } as any);
|
||||
|
||||
@@ -10,7 +10,7 @@ export class RevalidationService {
|
||||
process.env.FRONTEND_URL ||
|
||||
process.env.NEXT_PUBLIC_SITE_URL ||
|
||||
(process.env.NODE_ENV === "production"
|
||||
? "http://frontend_prod:8080"
|
||||
? "http://frontend_prod:3000"
|
||||
: "http://localhost:3000");
|
||||
return raw.replace(/\/+$/, "");
|
||||
}
|
||||
@@ -135,7 +135,7 @@ export class RevalidationService {
|
||||
await Promise.allSettled(tasks);
|
||||
}
|
||||
|
||||
async revalidateBlog(slug?: string): Promise<void> {
|
||||
async revalidateBlog(slug?: string): Promise<boolean> {
|
||||
const tasks: Promise<boolean>[] = [
|
||||
this.revalidateTag("blogs"),
|
||||
this.revalidateTag("home-data"),
|
||||
@@ -149,7 +149,18 @@ export class RevalidationService {
|
||||
tasks.push(this.revalidatePath(`/blog/${slug}`));
|
||||
}
|
||||
|
||||
await Promise.allSettled(tasks);
|
||||
try {
|
||||
const results = await Promise.allSettled(tasks);
|
||||
return (
|
||||
results.length > 0 &&
|
||||
results.every(
|
||||
(result) => result.status === "fulfilled" && result.value === true,
|
||||
)
|
||||
);
|
||||
} catch (err: any) {
|
||||
this.logger.debug(`Revalidation blog skipped or failed: ${err?.message}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async revalidateSettings(): Promise<void> {
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
import { Injectable, Logger } from "@nestjs/common";
|
||||
|
||||
@Injectable()
|
||||
export class HermesClientService {
|
||||
private readonly logger = new Logger(HermesClientService.name);
|
||||
private readonly baseUrl: string;
|
||||
private readonly apiKey: string;
|
||||
|
||||
constructor() {
|
||||
this.baseUrl = process.env.HERMES_GATEWAY_URL || "http://canina-bot:8642";
|
||||
this.apiKey = process.env.HERMES_API_KEY || process.env.API_SERVER_KEY || "";
|
||||
}
|
||||
|
||||
async checkHealth(): Promise<boolean> {
|
||||
try {
|
||||
const res = await fetch(`${this.baseUrl}/v1/health`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
},
|
||||
});
|
||||
return res.status === 200;
|
||||
} catch (error: any) {
|
||||
this.logger.error(`Hermes health check failed: ${error.message}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async triggerEvent(eventName: string, payload: Record<string, any>) {
|
||||
try {
|
||||
this.logger.log(`Dispatching event ${eventName} to Hermes Gateway`);
|
||||
const res = await fetch(`${this.baseUrl}/v1/chat/completions`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: "hermes-agent",
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: `[EVENT:${eventName}] ${JSON.stringify(payload)}`,
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
const data = await res.json();
|
||||
return { success: true, data };
|
||||
} catch (error: any) {
|
||||
this.logger.warn(`Could not dispatch event to Hermes: ${error.message}`);
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import {
|
||||
normalizeSearchText,
|
||||
extractSearchTokens,
|
||||
calculateRelevanceScore,
|
||||
createPaginationMeta,
|
||||
} from "./search.utils";
|
||||
|
||||
describe("search.utils", () => {
|
||||
describe("createPaginationMeta", () => {
|
||||
it("builds consistent pagination metadata", () => {
|
||||
const meta = createPaginationMeta(52, 2, 10);
|
||||
expect(meta).toEqual({
|
||||
total: 52,
|
||||
page: 2,
|
||||
limit: 10,
|
||||
totalPages: 6,
|
||||
lastPage: 6,
|
||||
hasNextPage: true,
|
||||
hasPrevPage: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("handles boundary zero and single page counts safely", () => {
|
||||
const metaZero = createPaginationMeta(0, 1, 10);
|
||||
expect(metaZero.totalPages).toBe(1);
|
||||
expect(metaZero.hasNextPage).toBe(false);
|
||||
expect(metaZero.hasPrevPage).toBe(false);
|
||||
|
||||
const metaOne = createPaginationMeta(5, 1, 10);
|
||||
expect(metaOne.totalPages).toBe(1);
|
||||
expect(metaOne.hasNextPage).toBe(false);
|
||||
expect(metaOne.hasPrevPage).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("normalizeSearchText", () => {
|
||||
it("normalizes Arabic kaf and yeh to Persian equivalents", () => {
|
||||
expect(normalizeSearchText("قطره قلب كنينای ايران")).toBe("قطره قلب کنینای ایران");
|
||||
});
|
||||
|
||||
it("strips parentheses, diacritics, and half-spaces", () => {
|
||||
expect(normalizeSearchText("ال-کارنیتین (L-Carnitine) \u200c دارویی")).toBe("ال کارنیتین l carnitine دارویی");
|
||||
expect(normalizeSearchText("مُکَمِّل")).toBe("مکمل");
|
||||
});
|
||||
|
||||
it("converts Persian digits to English digits", () => {
|
||||
expect(normalizeSearchText("محصول شماره ۱۲۳")).toBe("محصول شماره 123");
|
||||
});
|
||||
});
|
||||
|
||||
describe("extractSearchTokens", () => {
|
||||
it("extracts meaningful tokens and removes stop words", () => {
|
||||
const tokens = extractSearchTokens("بهترین قطره برای تقویت قلب سگ و گربه");
|
||||
expect(tokens).toContain("قطره");
|
||||
expect(tokens).toContain("تقویت");
|
||||
expect(tokens).toContain("قلب");
|
||||
expect(tokens).toContain("سگ");
|
||||
expect(tokens).toContain("گربه");
|
||||
expect(tokens).not.toContain("برای");
|
||||
expect(tokens).not.toContain("و");
|
||||
});
|
||||
});
|
||||
|
||||
describe("calculateRelevanceScore", () => {
|
||||
it("ranks exact title / ingredient matches far higher than general description mentions", () => {
|
||||
const herzVital = {
|
||||
title: "هیرتز ویتال (مکمل تقویت قلب) کنینا",
|
||||
slug: "canina-herz-vital-100ml",
|
||||
ingredients: [{ nameFa: "ال-کارنیتین (L-Carnitine)", nameEn: "L-Carnitine" }],
|
||||
symptoms: [{ symptom: "بیماری قلبی" }],
|
||||
shortDescription: "حمایت تخصصی از عضله قلب سگ و گربه",
|
||||
description: "توضیحات مفصل درباره کارکرد قلب و عروق...",
|
||||
};
|
||||
|
||||
const genericProduct = {
|
||||
title: "پودر ویتامین پلاس سگ",
|
||||
slug: "canina-vitamin-plus",
|
||||
ingredients: [{ nameFa: "ویتامین A", nameEn: "Vitamin A" }],
|
||||
symptoms: [],
|
||||
shortDescription: "تقویت عمومی بدن",
|
||||
description: "این مولتی ویتامین برای تمام اندامهای بدن از جمله قلب، کبد و مفاصل مفید است.",
|
||||
};
|
||||
|
||||
const tokens = extractSearchTokens("ال-کارنیتین قلب");
|
||||
const scoreHerz = calculateRelevanceScore(herzVital, "ال-کارنیتین قلب", tokens);
|
||||
const scoreGeneric = calculateRelevanceScore(genericProduct, "ال-کارنیتین قلب", tokens);
|
||||
|
||||
expect(scoreHerz).toBeGreaterThan(scoreGeneric * 4);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,251 @@
|
||||
export interface PaginationMeta {
|
||||
total: number;
|
||||
page: number;
|
||||
limit: number;
|
||||
totalPages: number;
|
||||
lastPage: number;
|
||||
hasNextPage: boolean;
|
||||
hasPrevPage: boolean;
|
||||
}
|
||||
|
||||
export function createPaginationMeta(
|
||||
total: number,
|
||||
page: number,
|
||||
limit: number,
|
||||
): PaginationMeta {
|
||||
const safeTotal = Math.max(0, Number(total) || 0);
|
||||
const safeLimit = Math.max(1, Number(limit) || 10);
|
||||
const safePage = Math.max(1, Number(page) || 1);
|
||||
const totalPages = Math.ceil(safeTotal / safeLimit) || 1;
|
||||
|
||||
return {
|
||||
total: safeTotal,
|
||||
page: safePage,
|
||||
limit: safeLimit,
|
||||
totalPages,
|
||||
lastPage: totalPages,
|
||||
hasNextPage: safePage < totalPages,
|
||||
hasPrevPage: safePage > 1,
|
||||
};
|
||||
}
|
||||
|
||||
const PERSIAN_ARABIC_DIGITS: Record<string, string> = {
|
||||
"۰": "0", "۱": "1", "۲": "2", "۳": "3", "۴": "4",
|
||||
"۵": "5", "۶": "6", "۷": "7", "۸": "8", "۹": "9",
|
||||
"٠": "0", "١": "1", "٢": "2", "٣": "3", "٤": "4",
|
||||
"٥": "5", "٦": "6", "٧": "7", "٨": "8", "٩": "9",
|
||||
};
|
||||
|
||||
export const COMMON_STOP_WORDS = new Set([
|
||||
"از", "به", "در", "با", "برای", "و", "یا", "که", "این", "آن", "ها", "های",
|
||||
"تر", "ترین", "روی", "توی", "را", "تا", "بر", "اما", "اگر", "ولی", "یک",
|
||||
"the", "a", "an", "and", "or", "for", "with", "in", "on", "at", "to", "of",
|
||||
]);
|
||||
|
||||
export const SEARCH_EXPANSION_MAP: Record<string, string[]> = {
|
||||
"تایورین": ["تورین", "taurine", "taurin"],
|
||||
"تائورین": ["تورین", "taurine", "taurin"],
|
||||
"تورین": ["تایورین", "تائورین", "taurine", "taurin"],
|
||||
"taurine": ["تورین", "تایورین", "تائورین", "taurin"],
|
||||
"taurin": ["تورین", "تایورین", "تائورین", "taurine"],
|
||||
"کارنیتین": ["carnitine", "l-carnitine"],
|
||||
"carnitine": ["کارنیتین", "l-carnitine"],
|
||||
"گلوکزامین": ["گلوکوزامین", "glucosamine"],
|
||||
"گلوکوزامین": ["گلوکزامین", "glucosamine"],
|
||||
"glucosamine": ["گلوکوزامین", "گلوکزامین"],
|
||||
"امگا": ["omega", "امگا ۳", "سالمون", "salmon"],
|
||||
"omega": ["امگا", "امگا ۳", "salmon"],
|
||||
"کندرویتین": ["chondroitin"],
|
||||
"chondroitin": ["کندرویتین"],
|
||||
"بیوتین": ["biotin"],
|
||||
"biotin": ["بیوتین"],
|
||||
"کلسیم": ["calcium"],
|
||||
"calcium": ["کلسیم"],
|
||||
};
|
||||
|
||||
/**
|
||||
* Normalizes Persian and English text by standardizing characters,
|
||||
* removing diacritics, half-spaces, punctuation, and folding case.
|
||||
*/
|
||||
export function normalizeSearchText(text?: string | null): string {
|
||||
if (!text) return "";
|
||||
|
||||
let s = String(text);
|
||||
|
||||
// Convert Persian/Arabic digits
|
||||
s = s.replace(/[۰-۹٠-٩]/g, (ch) => PERSIAN_ARABIC_DIGITS[ch] || ch);
|
||||
|
||||
// Normalize Arabic letters to standard Persian/English
|
||||
s = s
|
||||
.replace(/[يى]/g, "ی")
|
||||
.replace(/[ك]/g, "ک")
|
||||
.replace(/[ة]/g, "ه")
|
||||
.replace(/[آأإٱ]/g, "ا")
|
||||
.replace(/[ؤ]/g, "و")
|
||||
.replace(/[ئ]/g, "ی");
|
||||
|
||||
// Remove Arabic/Persian diacritics (fatha, damma, kasra, tanwin, sukun, tashdid)
|
||||
s = s.replace(/[\u064B-\u065F\u0670]/g, "");
|
||||
|
||||
// Replace half-space, non-breaking space, parentheses, brackets, quotes, punctuation with single space
|
||||
s = s.replace(/[\u200B-\u200D\uFEFF\u00A0\u200E\u200F_~`!@#$%^&*()+=[\]{}|\\;:'",.<>/?،؛؟]/g, " ");
|
||||
|
||||
// Collapse hyphens surrounded by spaces or replace hyphen with space
|
||||
s = s.replace(/-/g, " ");
|
||||
|
||||
// Lowercase & collapse whitespace
|
||||
return s.toLowerCase().replace(/\s+/g, " ").trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts meaningful tokens from a query, eliminating stop words
|
||||
* unless the entire query only consists of stop words.
|
||||
*/
|
||||
export function extractSearchTokens(rawQuery?: string | null): string[] {
|
||||
const normalized = normalizeSearchText(rawQuery);
|
||||
if (!normalized) return [];
|
||||
|
||||
const rawTokens = normalized.split(" ").filter((t) => t.length > 0);
|
||||
if (rawTokens.length === 0) return [];
|
||||
|
||||
// Filter out stop words
|
||||
const meaningful = rawTokens.filter(
|
||||
(t) => !COMMON_STOP_WORDS.has(t) && t.length >= 2,
|
||||
);
|
||||
|
||||
// If filtering left nothing, return original non-empty tokens
|
||||
const baseTokens = meaningful.length > 0 ? meaningful : rawTokens;
|
||||
|
||||
// Expand with domain aliases (e.g. تائورین <-> تورین <-> taurine)
|
||||
const expanded = new Set<string>(baseTokens);
|
||||
for (const token of baseTokens) {
|
||||
const directAliases =
|
||||
SEARCH_EXPANSION_MAP[token] ||
|
||||
SEARCH_EXPANSION_MAP[token.toLowerCase()] ||
|
||||
SEARCH_EXPANSION_MAP[normalizeSearchText(token)];
|
||||
if (directAliases) {
|
||||
for (const alias of directAliases) {
|
||||
expanded.add(normalizeSearchText(alias));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Array.from(expanded).filter((t) => t.length >= 2);
|
||||
}
|
||||
|
||||
export interface SearchScoreItem {
|
||||
artNo?: string | null;
|
||||
barcode?: string | null;
|
||||
slug?: string | null;
|
||||
title?: string | null;
|
||||
shortDescription?: string | null;
|
||||
description?: string | null;
|
||||
tags?: Array<{ name?: string | null } | string> | null;
|
||||
ingredients?: Array<
|
||||
| { ingredient?: string | null; nameFa?: string | null; nameEn?: string | null }
|
||||
| string
|
||||
> | null;
|
||||
symptoms?: Array<{ symptom?: string | null } | string> | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates a relevance score for a product or blog item against search tokens.
|
||||
*/
|
||||
export function calculateRelevanceScore(
|
||||
item: SearchScoreItem,
|
||||
rawQuery: string,
|
||||
tokens: string[],
|
||||
): number {
|
||||
if (!rawQuery || tokens.length === 0) return 0;
|
||||
|
||||
const normalizedQuery = normalizeSearchText(rawQuery);
|
||||
const normalizedTitle = normalizeSearchText(item.title);
|
||||
const normalizedArtNo = normalizeSearchText(item.artNo);
|
||||
const normalizedBarcode = normalizeSearchText(item.barcode);
|
||||
const normalizedSlug = normalizeSearchText(item.slug);
|
||||
|
||||
let score = 0;
|
||||
|
||||
// Exact matches get massive priority
|
||||
if (normalizedArtNo && normalizedArtNo === normalizedQuery) score += 200;
|
||||
if (normalizedBarcode && normalizedBarcode === normalizedQuery) score += 180;
|
||||
if (normalizedTitle && normalizedTitle === normalizedQuery) score += 150;
|
||||
if (normalizedSlug && normalizedSlug === normalizedQuery) score += 140;
|
||||
|
||||
// Title starts with full query
|
||||
if (normalizedTitle && normalizedTitle.startsWith(normalizedQuery)) score += 80;
|
||||
|
||||
// Title contains exact full query phrase
|
||||
if (normalizedTitle && normalizedTitle.includes(normalizedQuery)) score += 60;
|
||||
|
||||
// Token level matching in title (highest relevance)
|
||||
const titleTokens = normalizedTitle.split(" ");
|
||||
for (const token of tokens) {
|
||||
if (titleTokens.includes(token)) {
|
||||
score += 35;
|
||||
} else if (normalizedTitle.includes(token)) {
|
||||
score += 20;
|
||||
}
|
||||
}
|
||||
|
||||
// Ingredient / scientific terms matching
|
||||
if (item.ingredients && Array.isArray(item.ingredients)) {
|
||||
for (const ing of item.ingredients) {
|
||||
let ingName = "";
|
||||
if (typeof ing === "string") {
|
||||
ingName = ing;
|
||||
} else if (ing) {
|
||||
ingName = `${ing.ingredient || ""} ${ing.nameFa || ""} ${ing.nameEn || ""}`.trim();
|
||||
}
|
||||
const normIng = normalizeSearchText(ingName);
|
||||
if (normIng.includes(normalizedQuery)) score += 40;
|
||||
for (const token of tokens) {
|
||||
if (normIng.includes(token)) score += 15;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Symptoms matching
|
||||
if (item.symptoms && Array.isArray(item.symptoms)) {
|
||||
for (const sym of item.symptoms) {
|
||||
const symName = typeof sym === "string" ? sym : sym.symptom || "";
|
||||
const normSym = normalizeSearchText(symName);
|
||||
if (normSym.includes(normalizedQuery)) score += 30;
|
||||
for (const token of tokens) {
|
||||
if (normSym.includes(token)) score += 10;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Tags matching
|
||||
if (item.tags && Array.isArray(item.tags)) {
|
||||
for (const tag of item.tags) {
|
||||
const tagName = typeof tag === "string" ? tag : tag.name || "";
|
||||
const normTag = normalizeSearchText(tagName);
|
||||
if (normTag.includes(normalizedQuery)) score += 25;
|
||||
for (const token of tokens) {
|
||||
if (normTag.includes(token)) score += 8;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Short description matching
|
||||
const normShort = normalizeSearchText(item.shortDescription);
|
||||
if (normShort) {
|
||||
for (const token of tokens) {
|
||||
if (normShort.includes(token)) score += 5;
|
||||
}
|
||||
}
|
||||
|
||||
// Long description (low weight, capped so it never overwhelms title/ingredients)
|
||||
const normDesc = normalizeSearchText(item.description);
|
||||
if (normDesc) {
|
||||
let descHits = 0;
|
||||
for (const token of tokens) {
|
||||
if (normDesc.includes(token)) descHits += 1;
|
||||
}
|
||||
score += Math.min(descHits * 2, 6);
|
||||
}
|
||||
|
||||
return score;
|
||||
}
|
||||
@@ -3,6 +3,11 @@ import { PrismaService } from "../prisma/prisma.service";
|
||||
import { GetProductsDto } from "./dto/get-products.dto";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { RevalidationService } from "../common/revalidation/revalidation.service";
|
||||
import {
|
||||
createPaginationMeta,
|
||||
extractSearchTokens,
|
||||
calculateRelevanceScore,
|
||||
} from "../common/utils/search.utils";
|
||||
|
||||
@Injectable()
|
||||
export class ProductsService {
|
||||
@@ -62,37 +67,60 @@ export class ProductsService {
|
||||
andConditions.push({ priceValue: { lte: Number(maxPrice) } });
|
||||
}
|
||||
|
||||
if (search) {
|
||||
andConditions.push({
|
||||
OR: [
|
||||
{ artNo: { contains: search, mode: "insensitive" } },
|
||||
{ barcode: { contains: search, mode: "insensitive" } },
|
||||
{ nameFa: { contains: search, mode: "insensitive" } },
|
||||
{ nameEn: { contains: search, mode: "insensitive" } },
|
||||
{ description: { contains: search, mode: "insensitive" } },
|
||||
{ shortDescription: { contains: search, mode: "insensitive" } },
|
||||
const tokens = extractSearchTokens(search);
|
||||
if (tokens.length > 0) {
|
||||
const mode = "insensitive" as const;
|
||||
const searchConditions: Prisma.ProductWhereInput[] = [
|
||||
{ artNo: { contains: search, mode } },
|
||||
{ barcode: { contains: search, mode } },
|
||||
{ slug: { contains: search, mode } },
|
||||
{ nameFa: { contains: search, mode } },
|
||||
{ nameEn: { contains: search, mode } },
|
||||
{ shortDescription: { contains: search, mode } },
|
||||
];
|
||||
|
||||
for (const token of tokens) {
|
||||
searchConditions.push(
|
||||
{ nameFa: { contains: token, mode } },
|
||||
{ nameEn: { contains: token, mode } },
|
||||
{
|
||||
symptoms: {
|
||||
ingredientList: {
|
||||
some: {
|
||||
symptom: { contains: search, mode: "insensitive" },
|
||||
OR: [
|
||||
{ ingredient: { contains: token, mode } },
|
||||
{ ingredientCardSlug: { contains: token, mode } },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
{
|
||||
symptoms: {
|
||||
some: {
|
||||
symptom: { contains: token, mode },
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
andConditions.push({
|
||||
OR: searchConditions,
|
||||
});
|
||||
}
|
||||
|
||||
const whereClause: Prisma.ProductWhereInput =
|
||||
andConditions.length > 0 ? { AND: andConditions } : {};
|
||||
|
||||
const skip = (page - 1) * limit;
|
||||
const safePage = Math.max(1, Number(page) || 1);
|
||||
const safeLimit = Math.max(1, Number(limit) || 50);
|
||||
const skip = (safePage - 1) * safeLimit;
|
||||
|
||||
// 1. Fetch products with lean relations (no heavy N+1 orderItems join)
|
||||
// 1. Fetch products with lean relations
|
||||
const [rawProducts, total] = await Promise.all([
|
||||
this.prisma.product.findMany({
|
||||
where: whereClause,
|
||||
skip,
|
||||
take: limit,
|
||||
skip: tokens.length > 0 ? undefined : skip,
|
||||
take: tokens.length > 0 ? 100 : safeLimit,
|
||||
orderBy: { [sortBy]: sortOrder },
|
||||
include: {
|
||||
ingredientList: true,
|
||||
@@ -102,8 +130,34 @@ export class ProductsService {
|
||||
this.prisma.product.count({ where: whereClause }),
|
||||
]);
|
||||
|
||||
// Rank by relevance if searching
|
||||
let candidateProducts = rawProducts;
|
||||
if (tokens.length > 0 && search) {
|
||||
candidateProducts = [...rawProducts]
|
||||
.map((p) => ({
|
||||
product: p,
|
||||
score: calculateRelevanceScore(
|
||||
{
|
||||
artNo: p.artNo,
|
||||
barcode: p.barcode,
|
||||
slug: p.slug,
|
||||
title: p.nameFa || p.nameEn,
|
||||
shortDescription: p.shortDescription,
|
||||
description: p.description,
|
||||
ingredients: p.ingredientList,
|
||||
symptoms: p.symptoms,
|
||||
},
|
||||
search,
|
||||
tokens,
|
||||
),
|
||||
}))
|
||||
.sort((a, b) => b.score - a.score)
|
||||
.map((item) => item.product)
|
||||
.slice(skip, skip + safeLimit);
|
||||
}
|
||||
|
||||
// 2. Efficient single aggregate query for total sold counts for the current page slice
|
||||
const productIds = rawProducts.map((p) => p.id);
|
||||
const productIds = candidateProducts.map((p) => p.id);
|
||||
let salesMap: Record<string, number> = {};
|
||||
|
||||
if (productIds.length > 0) {
|
||||
@@ -131,7 +185,7 @@ export class ProductsService {
|
||||
userRole === "SuperAdmin";
|
||||
const isAdmin = userRole === "ADMIN" || userRole === "SuperAdmin";
|
||||
|
||||
const data = rawProducts.map((p) => {
|
||||
const data = candidateProducts.map((p) => {
|
||||
const totalSold = salesMap[p.id] || 0;
|
||||
const { buyPrice, wholesalePrice, ...publicProduct } = p;
|
||||
void buyPrice;
|
||||
@@ -146,12 +200,7 @@ export class ProductsService {
|
||||
|
||||
return {
|
||||
data,
|
||||
meta: {
|
||||
total,
|
||||
page,
|
||||
lastPage: Math.ceil(total / limit) || 1,
|
||||
limit,
|
||||
},
|
||||
meta: createPaginationMeta(total, safePage, safeLimit),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -20,7 +20,10 @@ describe('support HTTP boundary', () => {
|
||||
beforeAll(async () => {
|
||||
process.env.JWT_ACCESS_SECRET = 'test-secret-with-at-least-32-characters';
|
||||
const mod = await Test.createTestingModule({ imports: [PassportModule], controllers: [SupportChatController], providers: [{ provide: SupportChatSettingsService, useValue: { read: async () => ({ enabled: true, provider: 'p', model: 'm' }) } }, SupportChatService, OptionalCustomerJwtGuard, TestJwt, { provide: PrismaService, useValue: prisma }] }).compile();
|
||||
app = mod.createNestApplication(); app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true })); await app.init();
|
||||
app = mod.createNestApplication(); app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true }));
|
||||
// Own the listener for the entire suite. Otherwise Supertest lets the first
|
||||
// request start the server and close it while its concurrent peer is using it.
|
||||
await app.listen(0, '127.0.0.1');
|
||||
});
|
||||
afterAll(() => app.close());
|
||||
beforeEach(() => {
|
||||
@@ -45,7 +48,14 @@ describe('support HTTP boundary', () => {
|
||||
});
|
||||
it('scopes wallet to validated identity across concurrent callers', async () => {
|
||||
const replies=await Promise.all(['alice','bob'].map(sub => request(app.getHttpServer()).post('/support-chat/ask').set('Authorization','Bearer '+jwt.sign({sub})).send({message:'کیف پول'}).expect(201)));
|
||||
expect(replies[0].body.answer).toContain('11'); expect(replies[0].body.answer).not.toContain('22'); expect(replies[1].body.answer).toContain('22'); expect(prisma.product.findMany).not.toHaveBeenCalled();
|
||||
expect(replies[0].body.answer).toBe('موجودی کیف پول شما: 11 تومان.');
|
||||
expect(replies[1].body.answer).toBe('موجودی کیف پول شما: 22 تومان.');
|
||||
expect(prisma.user.findUnique).toHaveBeenCalledTimes(2);
|
||||
for (const id of ['alice', 'bob']) {
|
||||
expect(prisma.user.findUnique).toHaveBeenCalledWith({ where: { id }, select: { walletBalance: true } });
|
||||
}
|
||||
expect(prisma.product.findMany).not.toHaveBeenCalled();
|
||||
expect(prisma.order.findMany).not.toHaveBeenCalled();
|
||||
});
|
||||
it('scopes bounded orders to identity', async () => { const r=await request(app.getHttpServer()).post('/support-chat/ask').set('Authorization','Bearer '+jwt.sign({sub:'bob'})).send({message:'سفارش'}).expect(201); expect(r.body.answer).toContain('bob-order'); expect(prisma.order.findMany).toHaveBeenCalledWith(expect.objectContaining({ where:{userId:'bob'}, take:5 })); });
|
||||
it.each(['', 'x'.repeat(1501)])('bounds message length', async message => { await request(app.getHttpServer()).post('/support-chat/ask').send({message}).expect(400); });
|
||||
|
||||
@@ -2,6 +2,11 @@ import { Injectable, NotFoundException } from "@nestjs/common";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
import { PaginationDto } from "../common/dto/pagination.dto";
|
||||
import {
|
||||
createPaginationMeta,
|
||||
extractSearchTokens,
|
||||
calculateRelevanceScore,
|
||||
} from "../common/utils/search.utils";
|
||||
|
||||
@Injectable()
|
||||
export class WikiService {
|
||||
@@ -19,33 +24,57 @@ export class WikiService {
|
||||
const sortBy = allowedSortFields.includes(rawSortBy) ? rawSortBy : "term";
|
||||
|
||||
const whereClause: Prisma.ScientificTermWhereInput = {};
|
||||
if (search) {
|
||||
const tokens = extractSearchTokens(search);
|
||||
if (tokens.length > 0) {
|
||||
const mode = "insensitive" as const;
|
||||
whereClause.OR = [
|
||||
{ term: { contains: search, mode: "insensitive" } },
|
||||
{ definition: { contains: search, mode: "insensitive" } },
|
||||
{ term: { contains: search, mode } },
|
||||
{ key: { contains: search, mode } },
|
||||
{ definition: { contains: search, mode } },
|
||||
...tokens.flatMap((token) => [
|
||||
{ term: { contains: token, mode } },
|
||||
{ key: { contains: token, mode } },
|
||||
]),
|
||||
];
|
||||
}
|
||||
|
||||
const skip = (page - 1) * limit;
|
||||
const safePage = Math.max(1, Number(page) || 1);
|
||||
const safeLimit = Math.max(1, Number(limit) || 10);
|
||||
const skip = (safePage - 1) * safeLimit;
|
||||
|
||||
const [data, total] = await Promise.all([
|
||||
const [rawTerms, total] = await Promise.all([
|
||||
this.prisma.scientificTerm.findMany({
|
||||
where: whereClause,
|
||||
skip,
|
||||
take: limit,
|
||||
skip: tokens.length > 0 ? undefined : skip,
|
||||
take: tokens.length > 0 ? 100 : safeLimit,
|
||||
orderBy: { [sortBy]: sortOrder },
|
||||
}),
|
||||
this.prisma.scientificTerm.count({ where: whereClause }),
|
||||
]);
|
||||
|
||||
let data = rawTerms;
|
||||
if (tokens.length > 0 && search) {
|
||||
data = [...rawTerms]
|
||||
.map((t) => ({
|
||||
term: t,
|
||||
score: calculateRelevanceScore(
|
||||
{
|
||||
slug: t.key,
|
||||
title: t.term,
|
||||
description: t.definition,
|
||||
},
|
||||
search,
|
||||
tokens,
|
||||
),
|
||||
}))
|
||||
.sort((a, b) => b.score - a.score)
|
||||
.map((item) => item.term)
|
||||
.slice(skip, skip + safeLimit);
|
||||
}
|
||||
|
||||
return {
|
||||
data,
|
||||
meta: {
|
||||
total,
|
||||
page,
|
||||
lastPage: Math.ceil(total / limit),
|
||||
limit,
|
||||
},
|
||||
meta: createPaginationMeta(total, safePage, safeLimit),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
# Narrow auth schema operation — approval required
|
||||
|
||||
## Exact scope
|
||||
`auth-schema-reconcile.sql` adds only users.auth_expires_at TIMESTAMPTZ NULL, stage_test_session VARCHAR(64) NULL, stage_test_generation UUID NULL (no defaults/backfill), and prepare_workflow_outbox with its original CHECKs, three RESTRICT FKs, task uniqueness, lease and due indexes, including nullable not_before. No existing rows changed, no auth behavior disabled, no Prisma metadata altered.
|
||||
|
||||
Read-only production PostgreSQL 16.14 catalogs verified all three users columns and outbox absent; users.id and orchestration_tasks/runs/budget_ledger.id are UUID PKs. Existing users wallet CHECK and orchestration constraints stay intact. Production has six ledger rows (one historical rolled-back admin_modules attempt), no Oct22–24 entries despite orchestration objects existing. Never run generic migrate deploy or mark whole pending history applied.
|
||||
|
||||
Historical principal migration at e036c5d has two columns, SHA256 8b4fe1fdedd2ae459b720f78479cfcb13da465eec821b422ece5e9bb41dc47ae; 80a2e18 edited it to three, SHA256 a458a94329b1ad078298b042ae0bd2e25439c1f0bb5a086beb55c517d9e0aa28. Read-only Stage ledger records the latter, not the former. Preserve both historical files unchanged here. This operation is separately journaled by CI/backup receipt, not invented Prisma history. Broader baseline/history repair remains separate work.
|
||||
|
||||
## Execution contract
|
||||
Dedicated push workflow `auth-schema-reconcile.yml` uses DEPLOY_KEY and pinned DEPLOY_KNOWN_HOSTS, fixed SSH endpoint, isolated immutable Git checkout; it does not deploy applications. It accepts only exact branches `ops/auth-schema-stage` and `ops/auth-schema-production`, mapping their full refs to Stage and production respectively. It requires REVIEWED_AUTH_SCHEMA_COMMIT matching the event SHA and checks detached checkout HEAD equals that SHA. SQL digest is fixed to `8a22f3e89efb3dacc24f3ed9337ae87d0b4345da003a607bc1994478f69c6feb`, approval ID to `CEO-AUTH-SCHEMA-20261025`; neither is push-supplied input. Production additionally requires PRODUCTION_AUTH_SCHEMA_APPROVAL = SHA:SQL_SHA256:APPROVAL_ID and STAGE_AUTH_SCHEMA_ACCEPTANCE = SHA:SQL_SHA256, provisioned only after real review and Stage auth acceptance. These are explicit approval records, not automatically issued receipts. The repository's workflow/secret permissions must restrict dedicated-ref mutation to trusted maintainers; unrestricted malicious workflow edits can bypass any workflow-local gate. Review/protect this boundary before provisioning production approval.
|
||||
|
||||
Stage already has the DDL: Stage mode backs up production read-only, restores into isolated network-none temporary PostgreSQL, applies exact SQL there, compares resulting catalog with Stage read-only, and writes a SHA-bound structural receipt only. Production requires that receipt, repeats fresh full backup and restore/patch rehearsal, then executes only exact approved SQL. Full dumps remain mode600 host-only under /opt/backups/canina-auth-reconcile; never upload/log PII. Backup nonempty and pg_restore TOC checked. Restore errors/capacity failure stop before DDL. tmpfs is capped at 1GiB: if full restore exceeds capacity, separately review capacity rather than skipping restore. Existing read-only schema backup was 94,694 bytes / 67 tables, no PII copied; its restored PostgreSQL rehearsal is genuine, not a full data-backup recovery claim.
|
||||
|
||||
SQL lock_timeout 3s, statement_timeout 30s, idle transaction 60s; advisory lock plus host flock. DDL transactional; lock/contention failure aborts all. No automatic retries. Re-execution with existing outbox fails closed pending comparison, rather than silently accepting drift. Stage/production outputs compare columns/types/nullability/defaults, all outbox constraints/indexes to fresh rehearsed expected schema.
|
||||
|
||||
## Gitea 1.22.6 trigger semantics and operator sequence
|
||||
Gitea [1.22 comparison](https://docs.gitea.com/1.22/usage/actions/comparison) explicitly marks `workflow_dispatch` ignored. The [v1.22.6 notifier implementation](https://github.com/go-gitea/gitea/blob/v1.22.6/services/actions/notifier_helper.go) resolves the pushed ref's commit, detects workflows at that commit and records `Ref` and `CommitSHA` on the run. Push is not default-branch-only. The dedicated branch must therefore contain this workflow and point to the **final integrated reviewed commit**, not a new trigger-only commit. Existing app deployment listens only to `main`/`develop`, not either operations branch.
|
||||
|
||||
After independent review/authorization, a trusted operator can push `<REVIEWED_FULL_SHA>:refs/heads/ops/auth-schema-stage` to origin. Inspect that CI run's SHA and structural receipt, then complete real Stage auth tests. Only after separate production and Stage acceptance approval records exist for the **same** SHA/digest may the operator push `<REVIEWED_FULL_SHA>:refs/heads/ops/auth-schema-production`. No empty commits, merges, arbitrary ref inputs, secret updates by this workflow, automatic acceptance, or app promotion. A no-op push does not retrigger; do not change the reviewed SHA to manufacture a run. Any SHA change requires fresh review, approval bindings and Stage evidence. Workflow preparation has not pushed either branch, changed secrets/protections or executed the operation.
|
||||
|
||||
## Acceptance and rollback
|
||||
1. Parent DBA review exact commit/diff plus SQL hash and workflow trusted-ref/secret permissions. Approve read-only production full backup + isolated full restore scope separately from production DDL.
|
||||
2. Run Stage workflow from exact commit; inspect successful backup/restore/catalog comparison. Existing Stage backend must pass ordinary admin password login + protected dashboard, OTP flow with authorized principal, refresh, and expiry/session/generation rejection tests. Do not manufacture acceptance if no approved credential/test principal is available. Record actual test run identifiers before setting Stage acceptance approval.
|
||||
3. Obtain explicit approval: execute only this commit's SQL in caninodb_prod, three nullable users columns + empty outbox and declared constraints/indexes, 3s lock/30s statement budgets, no unrelated migrations/history writes/seeds. Provision approval binding SHA, SQL digest, approval record. Trigger production workflow, inspect terminal CI log. No production execution has been performed during preparation.
|
||||
4. Release separately via existing code-only develop→Stage→main CI, using actual regenerated backend client, runtime-image/schema guard, immutable image receipts and authenticated login/OTP/refresh/protected data acceptance. Keep current compatible backend until this passes. Schema approval alone does not authorize application promotion.
|
||||
5. Before commit failure: transaction rollback. After successful DDL: leave additive nullable fields/table intact, roll back application to known compatible immutable image via approved CI; do not DROP columns or outbox after writes. Restore full backup only under separately approved incident/data-loss recovery process. Existing backup tables remain untouched.
|
||||
|
||||
## Verified preparation / limitations
|
||||
Disposable network-none PG16 schema-only restore and exact SQL executed successfully (see JSON). Missing-column SELECT failed before patch and passed after; invalid status rejected; second application rejected without changes; container removed. Independent reviewer found SQL definition matched history; requested stronger gating, Stage preexisting-schema handling, capacity awareness and postcondition validation, addressed or explicit prerequisites above. Full-data restore and dedicated workflow SSH path are implemented but not yet executed in actual CI. No production writes or deployments occurred. Approval/environment gates must not be represented as production repair completion.
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"schema_backup_bytes": 94694,
|
||||
"schema_backup_sha256": "9c6367a06acaf97c1afe9355e4306d2a10f878b7fe156c7dbc5d58d675262c72",
|
||||
"schema_tables": 67,
|
||||
"pii_copied": false,
|
||||
"postgres": "16.14",
|
||||
"restore_and_patch_seconds": 3.669,
|
||||
"pre_patch_missing_columns_failed": true,
|
||||
"post_patch_queries": " auth_expires_at | stage_test_session | stage_test_generation \n-----------------+--------------------+-----------------------\n(0 rows)\n\n count \n-------\n 0\n(1 row)\n\n count \n-------\n 0\n(1 row)\n\n",
|
||||
"constraints": " conname | pg_get_constraintdef \n---------------------------------------------+-----------------------------------------------------------------------------------------------------------\n prepare_workflow_outbox_attempts_check | CHECK (((attempts >= 0) AND (attempts <= 3)))\n prepare_workflow_outbox_pkey | PRIMARY KEY (id)\n prepare_workflow_outbox_reservation_id_fkey | FOREIGN KEY (reservation_id) REFERENCES orchestration_budget_ledger(id) ON DELETE RESTRICT\n prepare_workflow_outbox_run_id_fkey | FOREIGN KEY (run_id) REFERENCES orchestration_runs(id) ON DELETE RESTRICT\n prepare_workflow_outbox_status_check | CHECK (((status)::text = ANY ((ARRAY['PENDING'::character varying, 'DONE'::character varying])::text[])))\n prepare_workflow_outbox_task_id_fkey | FOREIGN KEY (task_id) REFERENCES orchestration_tasks(id) ON DELETE RESTRICT\n prepare_workflow_outbox_task_id_key | UNIQUE (task_id)\n(7 rows)\n\n",
|
||||
"invalid_status_rejected": true,
|
||||
"repeat_execution_rejected_without_writes": true,
|
||||
"production_writes": false
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
# Host disk retention
|
||||
|
||||
Successful authenticated CI rollout runs release-retention.py. Default keep policy is only the current active release per environment; Docker mounts and Compose working directories always protect older still-used artifacts. Dry/unpublished source and unknown ignored files are preserved, so this is not a hard quota. CI restores only its own tracked nginx/dockerignore render changes after successful acceptance. New clones use sparse checkout to omit the 85 MiB tracked graphify-out history. No node_modules were bundled in the audited releases: their ~218 MiB is tracked source/assets plus an independent ~44 MiB Git store. Historical dirty releases require individual source review; never reset them for cleanup.
|
||||
|
||||
Retained small private runtime configuration is copied mode0600 under .retained-runtime before deleting a clean obsolete release. This avoids secret deletion; this archive is not a release rollback and requires explicit secret retention review separately. No volumes, databases, sessions, evidence, images or build cache are deleted.
|
||||
|
||||
The CI-installed canina-disk-watch.timer checks every five minutes with stdlib Python, no model calls. It logs daemon.err and returns nonzero at >=85% usage or <10GiB free. This is local detection, NOT off-host paging. systemctl status canina-disk-watch.service and journalctl -t canina-disk-watch expose alarms. Monitoring does not guarantee the disk cannot fill.
|
||||
|
||||
Audit 2026-10-26: Docker daemon already bounds new json-file containers to 3x10MiB and BuildKit GC to 6GB. Fifteen pre-existing containers (including Nexus, Gitea, databases and proxy) have empty LogConfig and remain unbounded until their owners roll them through their own Git/CI. Journald has no explicit SystemMaxUse and currently occupies 1.3GB. Nexus data is real persistent storage; retention tasks were not authenticated/audited and no blobs were deleted. Neither unrelated service config nor daemon/journal configuration is changed by Canina CI. Worktree branches with unpushed commits remain intentionally retained. These residual growth mechanisms prevent any honest claim of a globally bounded host or <50GB total.
|
||||
@@ -0,0 +1,69 @@
|
||||
# Orchestration v4: Hermes runtime seam (review-only)
|
||||
|
||||
## Installed evidence / compatibility
|
||||
|
||||
Read-only inspection of `canina-hermes` source at `/opt/hermes` and Docker metadata:
|
||||
|
||||
- Running image ID: `sha256:373ddd5e6649f525b17993e1c885cdf1352127f8e98fd329140a73237125e52f`.
|
||||
- Registry digest (pinned template): `nousresearch/hermes-agent@sha256:9774f4f39a9bb8c2f68ce728ed5e99ddbad282163be56764afacf88ed952b784`.
|
||||
- Current command is `gateway run`, **not** `serve`. Loopback 9119 connection refused. This implementation does not claim a live dashboard integration or start one.
|
||||
- Existing `/opt/data` mount is external volume `canina-hermes_canina_hermes_data`; preserve it. Read-only cron JSON count: **17 jobs, 0 enabled**. Paused state is `enabled:false`, not a `paused` boolean. No cron/runtime/config mutation was made.
|
||||
- Existing untracked `/opt/services/ai/canina-hermes/compose.yml` remains untouched.
|
||||
|
||||
Sources inspected: `hermes_cli/web_routers/{status,profiles,models,sessions,analytics,cron,chat_ws}.py`, cron scoping helpers, `cron/jobs.py`, `hermes_cli/inventory.py`, `hermes_cli/dashboard_auth/{routes,middleware}.py`, `hermes_cli/web_server{,_chat}.py`, `tui_gateway/ws.py`.
|
||||
|
||||
## Supported allowlist
|
||||
|
||||
| Service method | Installed upstream contract | Public projection |
|
||||
|---|---|---|
|
||||
| health | GET /api/health | ok/version/commit/auth_required |
|
||||
| status | GET /api/status?profile= | version/gateway_running/gateway_state/overall/active_agents |
|
||||
| profiles | GET /api/profiles -> {profiles:[]} | name/is_default/gateway_running, filtered by backend scope |
|
||||
| modelInfo | GET /api/model/info?profile= | model/provider/effective_context_length |
|
||||
| modelOptions | GET /api/model/options?profile= | provider slug/name + model ID strings |
|
||||
| usage | GET /api/analytics/usage?profile=&days= | period_days and four numeric totals |
|
||||
| sessions | GET /api/sessions?profile=&limit=&offset=&full=false&order=recent | ID/profile/source/is_active, total |
|
||||
| crons | GET /api/cron/jobs?profile= -> array | ID/profile/enabled |
|
||||
| pauseCron | POST /api/cron/jobs/{id}/pause?profile= | ID/profile/enabled |
|
||||
| resumeCron | POST /api/cron/jobs/{id}/resume?profile= | implemented adapter; **disabled in registered service** |
|
||||
|
||||
No generic route/HTTP/RPC proxy. No model setter, config, secrets, PTY, trigger, deletion, raw transcript or raw logs. Status is not fabricated if unavailable. Numeric nulls/malformed/missing required fields produce CONTRACT (some empty analytics stores may therefore be unavailable). Unknown upstream fields are dropped, never forwarded; this is intentional forward-compatible redaction, not raw JSON passthrough. Scope mismatch is forbidden. Arrays cap at 1000, upstream bytes at 256 KiB, in-flight requests at 4, whole request/token budget at 5 seconds, no retries, redirects forbidden. The production fetch honors AbortSignal. Error messages never include upstream response/URL/token/exception. Do not log request headers or config objects.
|
||||
|
||||
Upstream GET /api/sessions can auto-archive internally; we inspected source only and did not call it against production. Some model inventory endpoints warm caches/probe providers. Classify these as managed reads, not guaranteed filesystem-pure operations.
|
||||
|
||||
## Authentication and WS discovery
|
||||
|
||||
- Non-loopback dashboard binds engage the provider-verified auth gate. REST supports provider-verified Bearer session tokens. Legacy loopback accepts session header/Bearer; **a Canina JWT or API_SERVER_KEY is not interchangeable**.
|
||||
- POST `/api/auth/ws-ticket` needs verified `request.state.session`; response `{ticket,ttl_seconds}` is single-use / 30 seconds. Do not mint tickets for a browser or copy credentials into browser URLs.
|
||||
- Installed WS: `/api/ws`, `/api/console`, `/api/events`, `/api/pub`, `/api/pty`; **no assumed `/api/chat/ws`**.
|
||||
- `/api/ws` uses newline-delimited JSON-RPC and `gateway.ready`; same dispatcher as TUI, broad privilege. Gated admission supports a ticket, including subprotocols `hermes-gateway-v1` and `hermes-gateway-ticket.<ticket>`; legacy process token is rejected in gated mode. Internal process credentials must never be extracted.
|
||||
- We deliberately do not bridge a powerful socket without a verified session/run ownership and event allowlist contract. `chat`/`control` return UNSUPPORTED after policy; event dispatch returns FORBIDDEN even with policy approval. No WS dependency, background connection, reconnect, or ticket endpoint is exposed.
|
||||
|
||||
## Wiring (owner integration step, no app.module.ts changes here)
|
||||
|
||||
Import `HermesManagementModule.register(config, authorizer)` in the owning backend module, then inject **HermesIntegrationService**, never the adapter into browser controllers. Registration exports the service only and defaults to deny-all policy. Example configuration:
|
||||
|
||||
```ts
|
||||
HermesManagementModule.register({
|
||||
origin: 'http://canina-hermes:9119',
|
||||
token: () => secretStore.read('hermes_dashboard_access_token'),
|
||||
}, backendRuntimeAuthorizer)
|
||||
```
|
||||
|
||||
Supply a provider-verified, short-lived Hermes token through backend secret storage (template references `/run/secrets/hermes_dashboard_access_token` only). Provision/refresh is an operator responsibility; this change neither extracts existing runtime secrets nor invents a login flow. No token in database/UI/env templates.
|
||||
|
||||
Controllers must verify Canina admin JWT, resolve subject/profile scopes from trusted backend data (not request DTO), enforce permission and rate limit/audit, translate HermesError codes to safe API errors (AUTH_REQUIRED/UNAVAILABLE -> 503, FORBIDDEN ->403, LIMIT ->429, CONTRACT/UNSUPPORTED ->502/501). Never forward upstream errors. `RuntimePrincipal` is an internal context, not a user input DTO. Authorizer must independently verify subject/action/profile. Missing/throwing authorizer denies. Registered module hard-disables resume; enabling requires an explicit reviewed code change. Resume can immediately make overdue recurring jobs due: never test it on production.
|
||||
|
||||
## Disabled event dispatch design
|
||||
|
||||
No listener, cron, poller, outbox consumer or webhook is registered. A future dispatcher must use backend-verified event identity, durable outbox and idempotency, server-resolved department/profile/run ownership, permission per action, payload minimization/redaction, budget and approval policy. Then use a tested narrow execution transport; never map arbitrary event text to TUI RPC or `/api/pub`. Unknown event/schema/principal/approval/ownership -> reject with no IO. Do not enable before isolated acceptance proves interruption, stream bounds and safe tool-output projection.
|
||||
|
||||
## Manifests and verification
|
||||
|
||||
`infra/hermes-runtime/compose.template.yml` is **not a deployable replacement yet**: manual-only profile, no automatic restart/public ports/socket/credentials, preserves external data volume, dedicated external backend network. It intentionally retains `gateway run`; dashboard/auth/network topology and gateway egress need an approved migration design. Do not run alongside current service sharing the same writable state. Never `down -v`.
|
||||
|
||||
`.gitea/workflows/hermes-runtime-contract.yml` is manual contract review only, no deploy job, SSH, runtime secret or event dispatch. Existing deploy workflow untouched. Compose parsed with `docker compose ... config --quiet`; no containers deployed.
|
||||
|
||||
Tests: `cd backend && npm test -- --runInBand hermes-management` (14 assertions across 4 suites); strict isolated typecheck/build `npx tsc -p src/hermes-management/tsconfig.contract.json [--noEmit]`; full backend `npm run build` after isolated `npx prisma generate`. All passed. Local HTTP transport is exercised on ephemeral loopback, not production. TDD failures were observed for missing adapter, inventory methods, integration service, module and concurrency limit before implementations. No live authenticated dashboard or WS execution was exercised. Host has no Node; disposable node:22-bookworm runners used. Initial shared dependency resolution and offline Prisma binary download failed; fresh worktree dependencies and isolated network-enabled Prisma generation resolved them, without DB connection/migration.
|
||||
|
||||
Final verification: full backend Jest regression **93 suites / 771 tests passed**; scoped ESLint and strict typecheck passed, full `tsc -b` build passed. Existing SSL/payment negative tests print expected error logs despite passing. No deploy or production action performed.
|
||||
@@ -0,0 +1,95 @@
|
||||
**Superseded wiring/provenance: see [snapshot repair](hermes-snapshot-provenance.md). Do not use literal grants or the old DNS alias below.**
|
||||
|
||||
# Runtime read vertical slice (not deployed)
|
||||
|
||||
Branch feature/v4-runtime-completion, base 5507fbc. No AppModule, live gateway,
|
||||
production database, cron, dispatch, or existing compose was changed.
|
||||
|
||||
## Parent registration
|
||||
|
||||
Import `RuntimeReadModule.register({ '<verified-user-id>': ['default', '<department>'] })`
|
||||
from `backend/src/hermes-management/runtime-read.module` into AppModule.
|
||||
This module uses the existing Passport `jwt` strategy (DB-resolved user identity),
|
||||
not the API-key fallback. Parent must retain AuthModule/JwtStrategy initialization.
|
||||
Missing grants deny. Never construct grants from browser body, JWT profile claims,
|
||||
or unreviewed environment input. Allowlist is copied/frozen. Admin/SUPER_ADMIN
|
||||
role AND exact subject grant required; API-key identities forbidden.
|
||||
|
||||
GET `/admin/orchestration/runtime/{health,profiles,status,usage,sessions,schedules,model-info}`.
|
||||
All except health/profiles require exactly one allowed `profile` query string.
|
||||
Usage accepts days 1..365 (30); sessions limit 1..100 (20), offset 0..10000 (0).
|
||||
Unknown parameters on profile routes rejected. Profiles is filtered to server grants.
|
||||
Responses use existing adapter projections, no prompts/transcripts/config/tokens.
|
||||
Missing/forged JWT ->401; missing grant/role/profile ->403; runtime auth/network/
|
||||
contract failure ->503 `Runtime unavailable`; limits ->429. No browser Hermes
|
||||
cookie, credential, socket ticket or mutation handler is provided.
|
||||
|
||||
Mount backend `/run/secrets/hermes_username` and `hermes_password` as files.
|
||||
Only these fixed secret paths are read, after authorization. Broker login/cache
|
||||
stays server-side. Backend and isolated inventory runtime must receive matching
|
||||
credentials. Runtime additionally mounts `hermes_signing_key` (>=32 random chars).
|
||||
Do not put credentials in YAML/env, commands, logs or Git. Rotate key to invalidate
|
||||
sessions; rotate password and restart inventory plus backend to clear cached access.
|
||||
Stateless old sessions remain valid until TTL/key rotation.
|
||||
|
||||
## Deliberately separate snapshot topology
|
||||
|
||||
Installed Hermes `serve` lifespan starts reconciliation and hosted-room recovery;
|
||||
GET sessions auto-archives. Sharing its writable home with existing gateway is
|
||||
therefore NOT a safe read-only sidecar. `serve.py` runs the pinned installed app
|
||||
with lifespan OFF and an outer exact GET allowlist, password-login only and all
|
||||
WebSockets denied1008. It does NOT start scheduler/gateway/MCP/rooms/provider chat.
|
||||
The existing gateway and external volume `canina-hermes_canina_hermes_data` remain
|
||||
unchanged, solely owned by existing gateway. Inventory mounts an independently
|
||||
provisioned snapshot volume `canina_hermes_inventory_snapshot`; it NEVER mounts
|
||||
original home. Its incidental session auto-archive writes affect only snapshot.
|
||||
This is snapshot inventory, NOT live runtime freshness/status acceptance. A copy
|
||||
of gateway PID state is not evidence of live gateway health. UI must not claim live
|
||||
readiness from this deployment. Parent should expose snapshot provenance/freshness
|
||||
before enabling it for business use.
|
||||
|
||||
Provisioning must use an approved consistent SQLite backup/checkpoint/export and
|
||||
redacted profile config inventory, not raw `cp` of changing SQLite/WAL or credentials.
|
||||
No automatic snapshot job is installed here. No secrets need be copied from live
|
||||
home. Review which configs the model/status APIs need and omit auth.json/.env.
|
||||
Missing store/schema -> unavailable, not fabricated empty healthy telemetry.
|
||||
Dedicated internal network must contain only backend and inventory; do NOT connect
|
||||
existing gateway with same `canina-hermes` DNS alias. Backend name resolves inventory.
|
||||
Inventory network must have no external egress. Compose refers to external network;
|
||||
operator must create it `--internal`. No host ports/socket are published.
|
||||
|
||||
## CI ownership / apply
|
||||
|
||||
`compose.readonly.yml` is deployable ONLY after external snapshot, internal network,
|
||||
secret files and backend mounts/registration are provisioned. `ci-apply.sh` requires
|
||||
CI=true, exact reviewed HEAD SHA, clean checkout, snapshot-reviewed assertion,
|
||||
existing volume/network/files, then compose config/up. Never run alongside any
|
||||
other inventory instance writing same snapshot. CI job fragment is tracked under
|
||||
infra ownership; parent owns real workflow wiring and approval environment. No
|
||||
active deployment trigger added. Existing review-only compose template is unchanged.
|
||||
|
||||
## Executed evidence
|
||||
|
||||
Remote `/opt/services/canina/validation/v4-runtime-completion/`:
|
||||
- read-red.log missing controller regression; read-green.log 6 suites/27 tests.
|
||||
- read-http-green.log 7 suites/30 tests: real Nest HTTP with signed JWT strategy,
|
||||
bad signature/no auth401, ungranted admin403, allowed admin200, no cookie,
|
||||
mutation404. This uses a mocked runtime service, not live Canina credentials.
|
||||
- pinned-http.log exact installed image FastAPI login/protected inventory:
|
||||
wrong password401, real login200/HttpOnly provider-verifiable token, profiles200,
|
||||
tampered token401. No lifespan/live home.
|
||||
- serve-http.log actual loopback TCP9119 in network-none disposable pinned image:
|
||||
unauth inventory401, wrong password401, login200, profiles200, health auth true,
|
||||
mutation/config/ws HTTP404. Generated test-only credentials. No live volume.
|
||||
- ws-red.log existing socket rejection code differed; ws-green.log explicit
|
||||
outer boundary denies authenticated sockets1008 independently of upstream tickets.
|
||||
- build.log private Prisma generation and full backend tsc build exit0.
|
||||
|
||||
Pinned local exact image ID sha256:373ddd5e6649f525b17993e1c885cdf1352127f8e98fd329140a73237125e52f;
|
||||
tracked registry digest sha256:9774f4f39a9bb8c2f68ce728ed5e99ddbad282163be56764afacf88ed952b784.
|
||||
Node22 disposable runner copied read-only source/dependency donor privately;
|
||||
no DB migration. broker-pinned-e2e.log proves actual compiled Node broker -> TCP pinned Hermes login -> adapter -> policy-filtered inventory (and deny zero secret reads). Nest HTTP authentication tested separately; these tests do not establish full Canina application E2E, snapshot
|
||||
refresh, CI deployment, live gateway truth or business workflow acceptance.
|
||||
Those remain explicit integration/provisioning gates, not claimed completion.
|
||||
|
||||
Final full non-DB regression: 106 suites / 850 tests pass; expected legacy negative SSL/payment logs. Scoped ESLint has zero errors, six type-safety warnings; full build passes. No RELEASE_AUTHORIZE integration suite run.
|
||||
@@ -0,0 +1,86 @@
|
||||
# Snapshot provenance repair — integration contract
|
||||
|
||||
This is independent snapshot inventory, **not a live Hermes executor**. No Production,
|
||||
deployment, live gateway edits, or RELEASE_AUTHORIZE execution is included.
|
||||
|
||||
## Parent-owned application wiring
|
||||
|
||||
Keep AuthModule/JwtStrategy. Replace literal user grants in parent-owned app.module.ts with:
|
||||
|
||||
```ts
|
||||
RuntimeReadModule.registerFromFile('/run/secrets/hermes_runtime_grants')
|
||||
```
|
||||
|
||||
Nest supports the resulting Promise<DynamicModule> in imports. Alternatively pass the
|
||||
reviewed nonsecret file `/etc/canina/runtime-grants.json`. No env/JWT/browser grant
|
||||
input is accepted by this registration. File is JSON object mapping exact verified DB
|
||||
user IDs to nonempty unique profile arrays; `{}` explicitly denies everyone. Missing,
|
||||
malformed, symlinked, group/world-writable, oversized files fail startup closed. Mount
|
||||
read-only and provision via reviewed configuration/secrets management; do not commit
|
||||
real user grants. Existing explicit register(grants) remains for tests/legacy consumers.
|
||||
Backend also mounts `/run/secrets/hermes_username` and `hermes_password` read-only.
|
||||
No app.module.ts modification belongs to this commit.
|
||||
|
||||
## Required coordinated origin change
|
||||
|
||||
Authenticated management module and broker now exclusively use
|
||||
`http://canina-hermes-inventory:9119`. compose.readonly.yml uses the distinct alias
|
||||
`canina-hermes-inventory`, NEVER `canina-hermes`. Generic adapter allowlist retains
|
||||
both reviewed exact origins for compatibility with separate existing consumers.
|
||||
No arbitrary origin/env URL accepted. Parent must cherry-pick broker/module/adapter
|
||||
and inventory compose together; do not add an alias to the existing gateway.
|
||||
No deployment performed. External network should still be internal and only contain
|
||||
backend/inventory; the distinct alias cannot shadow the live canina-hermes hostname.
|
||||
|
||||
## Snapshot exporter/operator gate
|
||||
|
||||
Every independent inventory root must include `snapshot-manifest.json`:
|
||||
|
||||
```json
|
||||
{"schemaVersion":1,"source":"snapshot","capturedAt":"2026-10-23T12:00:00Z"}
|
||||
```
|
||||
|
||||
The example is a schema example, NOT an actual capture attestation. Exporter must
|
||||
write the real capture instant from the approved consistent export. Never copy the
|
||||
example, use startup time, filesystem mtime, or claim this change captures/refreshes
|
||||
snapshots. Missing/invalid/future manifest prevents startup. It is revalidated per
|
||||
successful GET; invalid after startup returns503. Manifest is exporter metadata,
|
||||
not a cryptographic proof of consistency. Immutable reviewed export provisioning
|
||||
remains required. Fresh means age <=3600 seconds, otherwise stale; even fresh is
|
||||
NOT live readiness. No snapshot scheduler installed.
|
||||
|
||||
## Additive public response fields / panel handoff
|
||||
|
||||
All object read DTOs (health/status/usage/sessions/model-info) add:
|
||||
`provenance:{source:'snapshot',capturedAt:string,ageSeconds:number,freshness:'fresh'|'stale',liveProcess:'unknown'}`.
|
||||
Profile and schedule array shapes are preserved: provenance is on each row. Empty
|
||||
arrays have no rows to annotate; use the health response to display snapshot metadata.
|
||||
Profile rows add `liveGatewayState:'unknown'`; status adds the same plus
|
||||
`liveActiveAgents:null`. Existing required scalars remain typed but are conservative
|
||||
placeholders: `gateway_running:false`, `active_agents:0`, `gateway_state:null`,
|
||||
`overall:'unknown'`. False/zero MUST NOT render as measured offline/idle: when
|
||||
provenance.source is snapshot use the explicit unknown fields, label snapshot and
|
||||
show capturedAt/freshness. Health.ok only means inventory HTTP app responsiveness,
|
||||
never live gateway readiness. Profile existence is inventory availability, NOT
|
||||
process readiness. Adapter enforces provenance on dedicated snapshot origin and
|
||||
conservatively overwrites copied PID-derived status/profile scalars again.
|
||||
|
||||
Installed status handler was unsafe here: it probes gateway HTTP/PIDs/platforms and
|
||||
can stall despite this being an independent snapshot. Snapshot server replaces that
|
||||
route with measured package version and explicit unknown process fields; no status
|
||||
probe is run. Password auth/mutation denial/WebSocket denial remain intact.
|
||||
|
||||
## Executed acceptance
|
||||
|
||||
Remote disposable network-none exact pinned Hermes image, no original volumes:
|
||||
manifest-missing regression failed first; TCP login/profile/health/status provenance
|
||||
and stale capture assertions now pass; authenticated sockets denied1008. Disposable
|
||||
Node22 copy of source/dependencies: 9 hermes-management suites /34 tests pass and
|
||||
full backend tsc build passes. Adapter copied-live-state regression failed first;
|
||||
grants-loader missing-function regression failed first. Compiled actual Node broker
|
||||
-> TCP pinned server -> adapter -> policy-filtered profiles/status passes, deny reads
|
||||
zero credentials. Test timestamps/credentials are fixtures, not live telemetry.
|
||||
The first HTTP retry raced fixture startup and returned UNAVAILABLE; retry after
|
||||
server startup passed. No claim of full app/user-flow or live runtime integration.
|
||||
|
||||
Full non-DB Jest regression: 108 suites/854 tests passed; 1 suite/18 tests skipped. No RELEASE_AUTHORIZE suite was enabled.
|
||||
@@ -0,0 +1,21 @@
|
||||
# Queued Gate1 validity correction
|
||||
|
||||
## Read-only Stage evidence (2026-10-24)
|
||||
|
||||
Task `565ace1f-8cfc-4447-b978-66c36e7b767b`: READY, version 4, PREPARE/STAGE_PREPARE, proposer `pmo`. Approval `30f8ce5c-ce00-4885-8eea-3c1bb5a7e8b0`: gate 1 APPROVED by independent actor `4a0afc72-0fd4-4d76-825b-aea13f00e880`, created 05:37:54.808Z, **expires 06:37:00Z**. runId/artifactHash/commitSha/environment on that Gate1 decision are null (normal Gate1 task binding, not Gate2 binding). Recovery event sequence 4 queued the valid approval at 06:22:06.891Z; outbox PENDING, attempts 0, runId null, notBefore null. At 09:15Z it was truly expired. Editorial claim queries newest decision for this task/gate, not a version-specific approval; it correctly rejects it. No evidence of a binding/version mismatch.
|
||||
|
||||
## Behavior
|
||||
|
||||
Persisted state remains READY; separate displayState reports blocked/renewal-required on reads. No approval is extended automatically. Existing independent reviewer authorization and task row lock protect a new ordinary Gate1 APPROVED decision. Renewal is limited to READY with a latest expired independent APPROVED decision and an unstarted PENDING outbox. It appends a decision and PREPARE_GATE1_RENEWED event, increments task version, preserves task scope/commit/budget and the existing outbox/notBefore. It rejects scheduling changes, active/attempted execution, valid approvals and self-review. Claim logic and its kill/budget/lease checks remain unchanged.
|
||||
|
||||
## Owner steps after parent CI integration
|
||||
|
||||
1. Sign in normally as an independent SUPER_ADMIN (or existing provisioned canonical owner reviewer); do not use worker identity or impersonation.
|
||||
2. Open orchestration, refresh server state, find this same task in owner decisions marked `مسدود — تأیید Gate1 منقضی شده؛ نیازمند تأیید مجدد مالک`.
|
||||
3. Review immutable scope, acceptance criteria, commit, environment and 20-cent budget; open ordinary Gate1 approval. Confirm bounded work explicitly. Renewal keeps the previous schedule; no new scheduled-start input is shown.
|
||||
4. Confirm once. The existing POST `/api/admin/orchestration/tasks/565ace1f-8cfc-4447-b978-66c36e7b767b/gates/1/decide` uses `{decision:"APPROVED",expectedVersion:4,idempotencyKey:<fresh unique key>}` (use refreshed version if changed). Notes optional; omit expiresAt for backend 24-hour validity. Retry only the identical payload/key after an ambiguous response; 409 requires refresh.
|
||||
5. Verify new independent decision, PREPARE_GATE1_RENEWED event and version increment. Do not recreate task or enqueue another outbox. Parent performs separately authorized runner/live acceptance.
|
||||
|
||||
## Verification
|
||||
|
||||
Frozen 09:15Z regression observed RED before implementation for READY representation and ordinary renewal; editorial exact 403/read mismatch observed RED; UI owner queue observed RED. GREEN: 41 backend scoped tests, 25 admin scoped tests. Disposable PostgreSQL test passes real simultaneous renewal/replay and claim serialization, expired denial, immutable old approval retention, one outbox/one claim. Backend build, Prisma client generation, admin build and application TypeScript check passed in Node22 with private donor dependencies. Initial build permission/stale-generated-client setup failures corrected only in private worktree copies. No Stage/Production DB mutation, approval, runner invocation, push or deploy.
|
||||
@@ -0,0 +1,22 @@
|
||||
# Orchestration v4 read-only integration verification
|
||||
|
||||
Base e5c83e87fe2d52d06eb36532fa9e354570678c43 plus cherry-picks admin a34c2a9, runtime bd58cc4, router b0f4636. Separate remote worktree; no dirty core edits, pushes, deploys, DB access or runtime changes.
|
||||
|
||||
## RED → GREEN proof
|
||||
- New backend HTTP boundary suite initially failed 4/4: mutation returned 201, BigInt serialization returned 500, overview missing (404). After integration: 4/4 pass, covering all mutation routes, anonymous/customer rejection, secret projection, actual overview and unavailable resources.
|
||||
- New UI fail-closed capability test initially failed because Create bounded work was visible without authorization. After capability gating: 7/7 command-center tests pass. Existing explicit action/binding/retry tests retained.
|
||||
|
||||
## Disposable remote validation
|
||||
Node 22 bookworm, network none, userns host (host Docker remapping prevents normal bind mounts), worktree source mounts, read-only sibling dependency cache. Vite cache directories are ephemeral tmpfs; no existing dependency trees changed.
|
||||
- Backend focused aggregate: **13 suites, 65 tests pass** (orchestration, Hermes, router usage).
|
||||
- Backend `tsc --noEmit`: exit 0. `npm run build`: exit 0.
|
||||
- Backend changed controller/HTTP spec ESLint: exit 0, 8 unsafe-argument warnings (7 test harness, 1 existing any-typed Prisma result). Baseline subsystem lint had 256 errors/8 warnings largely inherited formatting; no full lint pass claimed.
|
||||
- Admin focused aggregate: **5 files, 19 tests pass** (command center, orchestration/router adapters, creation, navigation).
|
||||
- Admin `npm run build`: exit 0, existing unresolved font warning remains.
|
||||
- Admin `tsc --noEmit -p tsconfig.app.json`: exit 2 with **33 inherited diagnostics** outside this change: legacy Approvals/Audit/HQ/Dashboard/ManagerActions/Tasks unused imports, Orders requiresRx missing, Symptoms ConfirmModal props/unused setter. No changed-file diagnostics. Full admin typecheck is NOT green.
|
||||
|
||||
## Security/release blockers
|
||||
The committed legacy core permits gate-state bypass through generic transitions and lacks hardened replay/authorization/budget/kill-switch boundaries. It is retained unchanged for parent integration; every exposed v4 mutation is unconditionally denied by controller. Do not restore controller calls or enable execution until hardened core is merged and reverified.
|
||||
Runtime dashboard not listening per parent investigation; no fabricated health or live availability claim. No trusted runtime identity/profile policy or runtime auth configured. Chat, cron mutations, execution/event dispatch, release execution stay disabled. Read-only inventory still requires orchestration schema migration through approved CI/CD, never manual DB changes. Backend read queries are currently full inventory and release evidence uses per-task reads; pagination/scaling remains future work.
|
||||
|
||||
Parent must inspect this commit and reconcile hardened core before any mutation milestone. No Stage promotion performed by this worker; admin typecheck failures remain explicit verification blockers for parent decision.
|
||||
@@ -0,0 +1,50 @@
|
||||
# Stage v4 rollout safety
|
||||
|
||||
## Scope and deployment boundary
|
||||
|
||||
Only a push to `develop` followed by the existing Gitea workflow may roll out this change. Do not run `deploy.sh` manually. Its CI marker is an accident guard, not an authentication boundary: runner permissions remain the security boundary. `main`, unknown branches and the former `stage-backend-only` bypass fail before Docker operations. Production is intentionally blocked pending separate review; no silent baseline/resolve is permitted.
|
||||
|
||||
## Tracked sequence
|
||||
|
||||
1. Acquire the Stage rollout lock (same lock as the retired backend-only path).
|
||||
2. Fetch the branch and build images using the existing workflow. Build failure leaves old applications running.
|
||||
3. Stop Stage frontend and backend (maintenance/outage; no promise of a custom 503 page).
|
||||
4. Run the newly built backend image as an isolated one-off Prisma CLI job (`compose run --rm --no-deps --entrypoint ... migrate deploy`). No app command, published service ports or automatic baseline. Existing DB must already be running.
|
||||
5. Only on migration success start backend. Require all nine v4 tables, the successful tracked migration receipt and an actual HTTP catalog response with the catalog envelope. HTTP acceptance has bounded retries and timeouts; no response body is logged.
|
||||
6. On backend acceptance failure stop both applications and fail. Only after acceptance start frontend. CI success marker follows these gates. The shared support bot is not rebuilt/replaced by this Stage rollout.
|
||||
|
||||
Migration failure leaves maintenance in place; do not auto-restart old apps against a partly migrated schema. Diagnose from CI logs, restore from an authorized backup or ship a reviewed forward fix through CI/CD. Never `db push`, seed, silently `migrate resolve`, or manually apply live DDL.
|
||||
|
||||
## Verification (2026-10-22)
|
||||
|
||||
Strict RED/GREEN cycles captured missing rollout function, migration failure ordering, missing backend acceptance and missing CI/Production guard before implementation. `python3 scripts/tests/test_stage_rollout.py`: 3 passed. Shell tests simulate Docker failures to prove sequencing only; they do NOT certify a healthy release. `node --test scripts/tests/test_rollout_health.cjs`: 4 passed using a local HTTP server (503, HTML, incorrect envelope rejected; valid empty catalog shape accepted). These fixtures are not live health evidence.
|
||||
|
||||
`python3 scripts/tests/rehearse_rollout.py` performs only schema-only `pg_dump` and migration-history-only data dump from Stage. It restores into a fresh PostgreSQL 16 container with no network, no host ports, no persistent volume, and no customer rows. Prisma runs in that disposable container's network namespace using an existing generated v4 client/dependencies read-only from the core test worktree. Dumps have a private temporary directory and are removed on exit.
|
||||
|
||||
Observed output:
|
||||
|
||||
```
|
||||
Applying migration `20261022000000_add_orchestration_v4_core`
|
||||
All migrations have been successfully applied.
|
||||
No pending migrations to apply.
|
||||
PASS: actual Prisma legacy catalog/support and v4 relation queries
|
||||
Restored 61 legacy tables; all business tables empty
|
||||
PASS: unchanged legacy column definitions; 61 legacy queries; 9 v4 tables; migrate deploy repeatable
|
||||
Disposable database/container removed; no live DDL performed
|
||||
```
|
||||
|
||||
The first rehearsal hit a read-only nested mount creation error, cleaned up, and was corrected to mount only `prisma/` plus dependencies; subsequent rehearsals passed.
|
||||
|
||||
## Remaining acceptance constraints
|
||||
|
||||
- No push, actual deployment, live DDL, customer export, or Production change was performed. No live v4 health success is claimed.
|
||||
- Schema-only rehearsal proves schema/query compatibility, not row-volume performance, locks under traffic, or business-data backfill behavior. All 61 legacy business tables were verified empty.
|
||||
- Full image build/start and public frontend/admin/API acceptance still require the authorized CI rollout. The gate currently covers backend schema/catalog; frontend start success is not browser acceptance.
|
||||
- Workflow now downloads the deployment entrypoint by triggering `github.sha` and passes `DEPLOY_SHA`. The entrypoint rejects missing/malformed SHA values, verifies that the commit belongs to the fetched deployment branch, and checks out that exact commit. Six disposable rollout tests cover sequencing, CI/Production guards, pin wiring and SHA validation. Actual runner execution and strong artifact/release attestation still require live CI acceptance; SHA pinning alone does not authenticate artifact evidence.
|
||||
- Existing compose credentials are out of scope; no new credentials are added. Continue restricting runner access and runtime env files. Orchestration mutation/chat/runtime remain disabled in the integration base; this rollout does not enable them.
|
||||
|
||||
## Completion-branch rehearsal
|
||||
|
||||
The repository-relative rehearsal applied both `20261022000000_add_orchestration_v4_core` and `20261022190000_harden_orchestration_ledger` to a disposable database restored from Stage schema/history only. All 61 legacy business tables were empty, their column definitions were unchanged, nine v4 tables and actual Prisma queries passed, and a second deploy found no pending migrations. No live DDL or release execution occurred.
|
||||
|
||||
The workflow shell now stops on download failure. SHA-pinning and six rollout tests plus four HTTP fixtures are verified locally in disposable containers; they are not proof of an actual CI rollout or frontend acceptance.
|
||||
@@ -0,0 +1,41 @@
|
||||
# 9router admin consumption adapter
|
||||
|
||||
## Wiring (integration owner)
|
||||
Import `RouterUsageModule` from `backend/src/router-usage/router-usage.module` into the root application's imports. This branch deliberately does not edit app.module.ts. Existing AuthModule/JWT strategy must be registered by the application. Route requires a JWT bearer user with admin/superadmin role; API-key authentication is deliberately not enabled for this sensitive endpoint.
|
||||
|
||||
Set backend-only `ROUTER_USAGE_CLI_TOKEN` using the existing router CLI auth token from the operator secret store. Optional `ROUTER_USAGE_BASE_URL` must be exactly `https://nr.parsaaghayi.ir` (an origin slash is accepted). Do not ship this token to the frontend. No environment/configuration was changed during implementation. No push/deploy performed; integration follows CI/CD and production needs separate Gate2.
|
||||
|
||||
## Exact API
|
||||
`GET /admin/router-usage?period=7d` (plus the existing application global prefix, if any).
|
||||
Allowed periods: `today`, `24h`, `7d`, `30d`, `60d`, `all`; default `7d`. Unknown query properties/custom from/to ranges and invalid periods return 400. Missing/invalid JWT is rejected by Passport; authenticated non-admin gets 403. Response is private/no-store.
|
||||
|
||||
Response fields:
|
||||
- `source: "9router"`, `period`
|
||||
- `status: "available" | "unavailable"`
|
||||
- `reason: null | "not_configured" | "invalid_configuration" | "busy" | "upstream_unavailable"`
|
||||
- `attribution: {scope:"9router_total", hermes:null, additive:false}`
|
||||
- `freshness: {retrievedAt: ISO8601|null, sourceUpdatedAt:null, stale:null}`. Retrieval time is NOT a guarantee of provider freshness. The source exposes no authoritative updated-at for aggregates. No last-good cache is served.
|
||||
- `capabilities: {errors:false, reasoningTokens:false, cacheWriteTokens:false, quota:false, customTimeRange:false}`
|
||||
- `data: null | {totals, providers:[], models:[], accounts:[]}`
|
||||
|
||||
Every metrics object contains `requests`, `inputTokens`, `outputTokens`, `cacheReadTokens`, `cacheWriteTokens`, `reasoningTokens`, `errors` (number|null). Zero is retained only if upstream reported zero; absent/invalid counters remain null. Input/output/cache map to promptTokens/completionTokens/cachedTokens; cache-read is a subset of input, never add it again. Cache-write/reasoning/errors are always null because the stats contract does not expose these aggregates.
|
||||
|
||||
Provider rows: `{provider,...metrics}`. Model rows: `{model,provider,...metrics}`. Account rows: `{accountId,model,provider,...metrics,quota:{status:"unknown",remaining:null,resetAt:null,reason:"upstream_quota_get_mutates_credentials"}}`. Account rows are upstream account/model summaries, NOT unique account inventory; accounts without usage are absent. IDs are validated, nullable if unsafe; account names/emails are never returned. No raw upstream maps, logs, prompts, provider data or credentials are returned. Dimensions are different views of the same consumption: do NOT sum totals+models+accounts. Hermes attribution remains unknown; do NOT add Hermes telemetry to router totals.
|
||||
|
||||
## Deployed-source inspection and real probe
|
||||
Read-only inspected running `9router` image `decolua/9router:vpn`: compiled `/app/.next/server/app/api/usage/stats/route.js`, `/app/.next/server/chunks/9100.js`, `/app/.next/server/middleware.js`, `/app/.next/server/chunks/7211.js`, providers routes and `/app/open-sse/services/usage.js`. No credential tables or router DB contents were dumped/modified.
|
||||
|
||||
Verified stats route accepts the periods above. `today` uses router-local midnight, `24h` rolling history; 7/30/60d use router-local daily buckets, `all` all retained daily aggregates. This is not arbitrary UTC timestamp filtering; retention/completeness is upstream-owned.
|
||||
|
||||
Authenticated internal GET probe returned HTTP 200, 5 provider summaries, 21 model summaries, 21 account/model summaries. Verified model fields: requests, promptTokens, completionTokens, cachedTokens, cost, rawModel, provider, lastUsed. Account fields additionally include connectionId/accountName. Only schema/counts printed; no keys or account values printed. Public HTTPS reverse proxy path was not live-authenticated, so its separate proxy authentication/network reachability remains an operator verification step.
|
||||
|
||||
Dashboard routes authenticate using `x-9r-cli-token` or valid `auth_token` session cookie. Normal inference API Bearer keys do NOT authenticate these dashboard routes. CLI token is NOT the contents of cli-secret: deployed middleware computes first 16 hex characters of SHA256(machine-id + "9r-cli-auth" + cli-secret). Probe derived it only inside the router process command and never emitted it; no new token or configuration was created.
|
||||
|
||||
**Security finding:** stats `byApiKey` map keys contain raw inference keys, even when row fields are masked. Adapter discards this map entirely and never logs response bodies/errors.
|
||||
|
||||
**Quota blocker:** `GET /api/usage/[connectionId]` calls refreshAndUpdateCredentials, including updateProviderConnection; OAuth refresh/retry can persist credentials. It is NOT read-only despite being GET. Therefore adapter does NOT call it. Provider quota handlers can return quotas (used/total/remaining/resetAt), messages or synthesized unlimited defaults; these cannot safely be treated as verified provider truth here. Quota reset grants exist in provider helpers but must never be consumed by this adapter. No safe deployed cache-only provider quota route was established. A separately reviewed router-side non-mutating, provenance/timestamp-bearing quota snapshot API is required before exposing live remaining/reset. Quota is unknown, never zero/unlimited fabricated. Connection inventory/status refresh is also not represented as quota truth.
|
||||
|
||||
## Bounds and verification
|
||||
Only fixed-origin authenticated GET `/api/usage/stats` is invoked; redirect:error, abort after 5 seconds, streaming cap 1 MiB, <=2000 rows per dimension, <=4 concurrent requests per backend process. No retries or stale cache. Schema/transport/auth/rate-limit/oversize failures produce unavailable + null data without raw errors. No SQL, POST or token refresh.
|
||||
|
||||
Strict test-first slices observed missing contract, adapter, module failures before implementation. Disposable containers used existing backend image dependencies, read-only source mounts, network disabled and copied source into ephemeral /work; no host dependencies/build output or running containers changed. `npm run build` passed. Focused: 3 suites/24 tests passed. Full backend regression: 92 suites/781 tests passed (existing negative-path tests log expected payment/SSL errors). HTTP guard tests replace JWT authentication only and exercise real RolesGuard; deployed JWT strategy remains application-owned.
|
||||
@@ -0,0 +1,53 @@
|
||||
# Durable Stage cleanup verification
|
||||
|
||||
This change replaces the SHA-pinned transient timer with a root-owned intent journal
|
||||
and a fixed host systemd retry worker. No host service is installed or enabled by
|
||||
the CI credential command. The tracked `deploy.yml` → `ci-host-deploy.sh` →
|
||||
`deploy.sh` path invokes `install-stage-principal-cleanup.py` from the verified
|
||||
immutable release before `stage_rollout`. It atomically installs the root-owned
|
||||
worker (0755) and supplied systemd units (0644), reloads systemd, enables/starts
|
||||
the timer and verifies enabled/active state. Failure aborts rollout. No manual
|
||||
sudo provisioning is required or permitted during review. The open wrapper refuses to operate
|
||||
without an enabled and active timer. Never overwrite or delete the 0700 root-owned
|
||||
`/opt/services/canina/stage-principal-cleanup` journal during deployments.
|
||||
|
||||
A journal entry is fsynced before provisioning and contains the exact session,
|
||||
random generation, creation SHA, bounded TTL and immutable cleanup deadline.
|
||||
Repeated opens fail rather than replace an intent or renew TTL. Close and the
|
||||
30-second boot/periodic retry worker retain intents on lock contention, unavailable
|
||||
containers/DB, and relational deletion failures. Cleanup resolves the current Stage
|
||||
container ID once, verifies its cleanup capability, and authenticates against its
|
||||
current artifact SHA while retaining original session/generation ownership. Older
|
||||
artifacts without generation cleanup support fail closed; never roll back to one
|
||||
with a pending principal. Persisted expiry remains independently enforced at login,
|
||||
refresh and every scoped JWT request.
|
||||
|
||||
Revocation commits before private-handle removal; relational deletion is subsequent.
|
||||
A transaction acquires a generation/session-fenced row lock before touching related
|
||||
records. Failed deletion retains a revoked row and a pending retry intent, but no
|
||||
credential handle. Wrong ownership/generation never invokes the handle callback.
|
||||
The CLI requires the generation supplied by the private journal; no broader admin
|
||||
or production authority was introduced.
|
||||
|
||||
Verification performed in a new isolated worktree and disposable Docker network:
|
||||
- Cleanup fence tests: RED (replacement generation was revoked; callback missing),
|
||||
then GREEN (2 tests).
|
||||
- Python simulated worker tests: restart/redeploy, failed-delete retry, lock
|
||||
contention, immutable container ID/current artifact and old-CLI refusal (4 tests).
|
||||
- Persisted account lifecycle plus delete/recreate access AND refresh regression.
|
||||
- Actual CLI via ts-node with real disposable Postgres/Redis and HTTP adminLogin
|
||||
handler, injected PostgreSQL delete trigger failure: confirmed revocation,
|
||||
private handle removal, then successful repeated cleanup after trigger removal.
|
||||
- TypeScript `tsc --noEmit`: passed.
|
||||
- Full migration chain attempt on fresh disposable database: baseline failure in
|
||||
20261020000000_add_blog_freshness_authorship (`blogs` missing). Not concealed.
|
||||
Independent migration test constructed the pre-Stage schema excluding all three
|
||||
new fields, then applied the EXACT committed 20261024090000 migration with psql
|
||||
ON_ERROR_STOP before exercising persisted lifecycle. Not db-push-only testing.
|
||||
|
||||
No live account, Stage/Production DB mutation, deployment, push, host service change,
|
||||
or retry of the previous pending-approval operation was performed.
|
||||
|
||||
Invocation after normal reviewed deployment and host prerequisite provisioning:
|
||||
`sudo -n env CI=true STAGE_TEST_APPROVAL=owner-authorized-stage-editorial bash /opt/services/canina/releases/<promoted-sha>/scripts/stage-test-principal-host.sh <promoted-sha> <unique-session> 600 open`
|
||||
Use the same command with `close` immediately after the authorized test.
|
||||
@@ -0,0 +1,145 @@
|
||||
# Opt-in Stage runtime provisioning (parent wiring contract)
|
||||
|
||||
This provisions **snapshot inventory** and credentials for the existing PREPARE
|
||||
transport. It does NOT create a real LLM executor. The current deterministic worker
|
||||
is still `llmPilot:false`. No provider credentials are collected, no cron installed,
|
||||
no task claimed and no worker polling/service started by the provisioner.
|
||||
|
||||
## CI-only host invocation
|
||||
|
||||
Parent owns workflow/deploy.sh/AppModule; none are changed here. Run only through
|
||||
the existing pinned authenticated SSH CI boundary, under its Stage environment
|
||||
approval and serialized rollout lock. `CI=true` is an accident guard, not an auth
|
||||
boundary. Provisioner checks clean HEAD equals the full approved commit; no branch
|
||||
promotion, push, Production, RELEASE_AUTHORIZE, Docker or DB writes are performed.
|
||||
Only the CI account should be able to invoke this on a root-owned trusted parent.
|
||||
|
||||
From the clean pinned release checkout on the host (not the dirty Stage checkout):
|
||||
|
||||
```sh
|
||||
CI=true STAGE_PROVISION_ENABLED=true STAGE_PROVISION_APPROVED_SHA="$DEPLOY_SHA" \
|
||||
python3 scripts/provision-stage-runtime.py --uid 1000 --gid 1000
|
||||
```
|
||||
|
||||
Default output root is `/opt/services/canina/stage-runtime` and its parent must
|
||||
already exist. First creation is staged and atomically renamed. Repeating validates
|
||||
existing state without rotating credentials. Corrupt/missing/unsafe files fail
|
||||
closed, not repaired. CI MUST serialize execution and prevent untrusted edits to
|
||||
source/output parents; this is not a hostile-filesystem sandbox. `--root` is for
|
||||
CI-reviewed test/Stage locations only, not arbitrary browser input. Secure backup
|
||||
and separately approved rotation are parent/operator responsibilities.
|
||||
|
||||
- `secrets/` 0700, files 0400 owned by the runtime UID (1000 in the current backend
|
||||
image); `hermes_username/password/signing_key` are new independent random values.
|
||||
- `prepare_worker_grants` contains SHA256 only, exact separate service identities
|
||||
`stage-prepare-worker`/WORKFLOW_WORKER and `stage-evidence-ci`/STAGE_CI. These are
|
||||
transport service identities, **not invented DB admin users**.
|
||||
- Raw `credentials/prepare_worker_token` and `credentials/stage_ci_token` stay in a
|
||||
CI-owner-only 0700 directory, 0400 files. Do NOT mount either into inventory or
|
||||
backend, log them, upload them as artifacts or send them to browsers. A later
|
||||
reviewed one-shot executor receives only its own token through a private file.
|
||||
- `artifacts/` is 0700 owned by backend UID; backend alone writes it. Persistent
|
||||
local disk is not object storage or external publication evidence.
|
||||
- `hermes_runtime_grants` is `{}`: deny all. No live admin query was needed/performed.
|
||||
Parent must separately query actual Stage admin IDs read-only, review exact ID to
|
||||
profile mapping and provision a private replacement via configuration management
|
||||
before claiming panel access. Never infer identities from usernames or JWT input.
|
||||
Deliberately changed grants require separate review; default provisioner refuses
|
||||
nonempty runtime grants on repeat.
|
||||
- Compose file-backed secrets preserve host permissions/ownership; `uid/gid/mode`
|
||||
declarations do not fix bind mount ownership. Verify effective host IDs if Docker
|
||||
uses userns remapping; do not chmod 0444 as a workaround.
|
||||
|
||||
## Consistent restricted export
|
||||
|
||||
After approval, the SAME CI invocation may explicitly request one profile's source
|
||||
SQLite DB. Resolve its real `HERMES_HOME/state.db` through reviewed host mounts;
|
||||
never guess a gateway volume path or mount the original home into inventory.
|
||||
|
||||
```sh
|
||||
CI=true STAGE_PROVISION_ENABLED=true STAGE_PROVISION_APPROVED_SHA="$DEPLOY_SHA" \
|
||||
python3 scripts/provision-stage-runtime.py --uid 1000 --gid 1000 \
|
||||
--snapshot-db "$REVIEWED_STATE_DB" --profile default \
|
||||
--snapshot-name "$UNIQUE_CI_CAPTURE_ID"
|
||||
```
|
||||
|
||||
SQLite online `Connection.backup()` reads committed WAL frames into memory (never
|
||||
`cp state.db`, never `immutable=1`). A 30-second callback deadline bounds busy
|
||||
backup. Only explicit source/time/token/cost columns from `sessions` are projected.
|
||||
Private session IDs become capture-local ordinal IDs; sources use an enum; no
|
||||
messages, titles, prompts, user/chat IDs, paths, URLs, model config, credentials,
|
||||
config.yaml, auth.json, .env, cron commands, memory or skills are exported. Unknown
|
||||
schema/nonnumeric metadata fails. One profile per immutable capture; there is no
|
||||
multi-DB atomicity claim. A source DB may be large: backup is memory-bound, so size
|
||||
and host resources need operator review before a real capture.
|
||||
|
||||
Output directory is new/immutable (0500, 0400 files), never overwritten:
|
||||
`inventory.json`, exact three-field `snapshot-manifest.json` and `export-report.json`.
|
||||
Manifest `capturedAt` is measured immediately after successful backup, not startup,
|
||||
mtime or an example. Report records actual projected row count, inventory digest,
|
||||
method/exclusions; it is not a signature or proof of source authenticity. No live
|
||||
capture was performed in this change. Never reuse fixture manifests as evidence.
|
||||
|
||||
Projected HTTP readers never consult gateway config, state DB or cron files:
|
||||
model/provider are explicit `unknown`, context length is a placeholder zero,
|
||||
cron arrays empty mean **not captured**, session activity false is a placeholder,
|
||||
profile inventory doesn't establish live process availability. Status retains
|
||||
`liveProcess:unknown`. Usage days are relative to actual capture time. Snapshot
|
||||
fresh/stale provenance from the existing adapter remains mandatory. No real LLM
|
||||
pilot readiness follows from this inventory responding 200.
|
||||
|
||||
## Exact parent compose/application wiring
|
||||
|
||||
`infra/hermes-runtime/compose.stage-provision.yml` is an opt-in merge fragment,
|
||||
NOT called by the existing deploy script or ci-apply.sh. Parent must include it
|
||||
in **every** Stage compose command after provisioning, using the existing stable
|
||||
Compose project identity and existing release isolation/volume rules:
|
||||
|
||||
```sh
|
||||
export STAGE_RUNTIME_SERVE_FILE="$PINNED_RELEASE/infra/hermes-runtime/serve.py"
|
||||
export STAGE_RUNTIME_SNAPSHOT="/opt/services/canina/stage-runtime/snapshots/$UNIQUE_CI_CAPTURE_ID"
|
||||
# Only inside approved CI rollout, never manually:
|
||||
# docker compose -p <existing-stage-project> -f <parent-stage-compose> \
|
||||
# -f "$PINNED_RELEASE/infra/hermes-runtime/compose.stage-provision.yml" \
|
||||
# --profile stage-runtime-inventory <parent-approved command>
|
||||
```
|
||||
|
||||
The fragment adds backend `PREPARE_WORKER_ENABLED=true`, fixed-path secrets
|
||||
`/run/secrets/prepare_worker_grants`, `/run/secrets/hermes_runtime_grants`,
|
||||
`hermes_username/password`, and artifact bind at
|
||||
`/var/lib/canina/prepare-artifacts`. It adds a project-scoped **internal** network
|
||||
between backend and inventory only, alias `canina-hermes-inventory` (not the live
|
||||
`canina-hermes`). No host port, Docker socket or live gateway volume. Inventory is
|
||||
read-only, nonroot, no capabilities, restricted tmpfs and pinned image, mounts only
|
||||
its immutable projected export and script. `create_host_path:false` fails on missing
|
||||
exports/storage. Original compose.readonly.yml/ci-apply.sh remain legacy review-only;
|
||||
do not combine those with this provisioning fragment.
|
||||
|
||||
AppModule must keep AuthModule/JwtStrategy, import
|
||||
`RuntimeReadModule.registerFromFile('/run/secrets/hermes_runtime_grants')` for reads,
|
||||
and spread `...registerPrepareWorker()` for the opt-in worker transport (verify
|
||||
existing AppModule before adding duplicates). The latter defaults to no module
|
||||
unless exact env `true`; enabling compose alone cannot add missing imports. Routes
|
||||
remain service-authenticated. Artifact base is fixed to
|
||||
`https://stageapi.canina.ir/api/internal/prepare-worker/artifacts`; parent must verify
|
||||
its actual global `/api` prefix/proxy/authenticated retrieval after CI deployment.
|
||||
No URL here is asserted externally reachable by disposable tests.
|
||||
|
||||
Parent still must implement/review a bounded one-shot real LLM executor separately;
|
||||
this commit intentionally adds neither model/provider secrets nor automatic polling.
|
||||
After CI rollout verify backend UID/secret readability by names only, deny-all reads,
|
||||
worker unauth denial, snapshot provenance and authenticated artifact digest readback
|
||||
before a separately authorized task. Do not call RELEASE_AUTHORIZE.
|
||||
|
||||
## Executed disposable validation
|
||||
|
||||
Pinned Hermes image, `--network none`, repository mounted read-only; private
|
||||
TemporaryDirectory fixtures only. RED observed missing provisioner, missing exporter,
|
||||
wrong projected profile and acceptance of malformed credential; GREEN: four
|
||||
provision/export/security/CI-guard unittest cases; projected HTTP auth/profile/session/
|
||||
wrong-profile/model/cron assertions; existing exact-image HTTP acceptance, TCP serve
|
||||
mutation denial and authenticated WebSocket 1008 denial. Compose merged config
|
||||
`--quiet` passed without applying it. An initial test mount mismatch was corrected
|
||||
(`/source` for repo-relative tests, `/contract` for legacy tests). No application
|
||||
backend code changed; full backend suites not rerun. No host credentials, artifact
|
||||
storage, snapshots, DB users, services or networks were provisioned live.
|
||||
@@ -0,0 +1,44 @@
|
||||
# Temporary Stage editorial reviewer (disabled by default)
|
||||
|
||||
Authority: repository write/CI-dispatch permission plus the existing authenticated,
|
||||
pinned Stage deployment SSH boundary. This is a narrowly scoped seed operation,
|
||||
not an API-key actor, owner JWT, or a public bootstrap endpoint. The destructive
|
||||
legacy seed is not used. `AdminService` shares its normal hashing/persistence and
|
||||
relational cleanup implementation with the internal command; normal user mutation
|
||||
role checks remain unchanged. The canonical default administrator is untouched.
|
||||
|
||||
## Activation after independent review
|
||||
|
||||
1. Promote this commit through the normal Git/CI Stage deployment. Do not run the
|
||||
seed command against an old image: the embedded immutable SHA must match.
|
||||
Apply the additive migration through the existing migration deployment step.
|
||||
2. Dispatch **Owner authorized Stage test principal** on develop with `approval`
|
||||
exactly `owner-authorized-stage-editorial`, unique `session` such as
|
||||
`editorial-20261024-a`, `ttl` explicitly 600 (maximum 3600), and `action=open`.
|
||||
The workflow uses existing DEPLOY_KEY / pinned DEPLOY_KNOWN_HOSTS only.
|
||||
3. CI reports only `/app/private-stage-test/<session>.json` inside
|
||||
`canino_backend_stage`. This mode-0600 file in a mode-0700 directory contains
|
||||
the process-generated password and real persisted-account login tokens.
|
||||
Consume it only from an approved in-container CI HTTP process; never print,
|
||||
download, publish as an artifact, or type it into a browser. No owner secret is
|
||||
needed. Audit records contain events, session and SHA, never credentials.
|
||||
4. Use this independent reviewer for Gate1 only; the proposer/PMO must be a
|
||||
distinct actor. Existing self-review checks are not changed. This session does
|
||||
NOT authorize Gate2, publication, release, general admin APIs, worker identity
|
||||
replacement, or budget increases. Approve a separate explicit bounded test
|
||||
budget before running inference; unknown prior reservations remain retained.
|
||||
5. Dispatch the same workflow/session/ttl with `action=close` immediately after
|
||||
tests. This revokes persisted authentication BEFORE relational deletion and
|
||||
removes the private credential file. Close is idempotent when absent.
|
||||
|
||||
A durable root-owned host cleanup journal and boot/periodic systemd retry worker must be provisioned before opening a session. Cleanup follows the current Stage artifact but retains the original exact session and generation fence; persisted expiry cannot be extended. See [cleanup verification and promotion prerequisites](stage-principal-cleanup-verification.md). No live host services are changed by review tests.
|
||||
|
||||
## Verification
|
||||
|
||||
Unit guards and existing independent self-review/role tests run with Jest.
|
||||
`stage-test-principal.integration.spec.ts` is opt-in via
|
||||
`STAGE_PRINCIPAL_DISPOSABLE_TEST=true` and requires a database URL ending in
|
||||
`/principal_disposable`; use a new isolated Postgres and Redis, then remove both.
|
||||
It verifies real account persistence/hash, signed access/refresh login tokens,
|
||||
collision refusal, nonrenewing retries, request scope, expiry, deletion/revocation.
|
||||
Never run it against Stage or Production.
|
||||
@@ -112,18 +112,6 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side
|
||||
{ icon: MessageSquare, label: 'تحلیل مشاوره سایت', path: '/settings/smart-chat' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'governance',
|
||||
title: 'حاکمیت، تاییدات و وظایف',
|
||||
icon: CheckSquare,
|
||||
items: [
|
||||
{ icon: Building2, label: 'نمای وضعیت دپارتمانها', path: '/governance/hq' },
|
||||
{ icon: Briefcase, label: 'اقدامات مدیریتی و همکاریها', path: '/manager-actions' },
|
||||
{ icon: CheckSquare, label: 'مجوزهای عملیاتی', path: '/approvals' },
|
||||
{ icon: Briefcase, label: 'وظایف دپارتمانها و ایجنتها', path: '/tasks' },
|
||||
{ icon: History, label: 'تاریخچه تغییرات دیتابیس (Audit)', path: '/history' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'monitoring',
|
||||
title: 'مرکز مانیتورینگ و سلامت',
|
||||
|
||||
@@ -12,9 +12,6 @@ interface TopbarProps {
|
||||
}
|
||||
|
||||
const SEARCHABLE_PAGES = [
|
||||
{ label: "اقدامات مدیریتی و همکاریها (Manager Actions)", path: "/manager-actions", keywords: ["اقدامات", "مدیریتی", "همکاری", "b2b", "تامین", "استراتژی", "actions"] },
|
||||
{ label: "مجوزهای عملیاتی مدیریت (Operational Approvals)", path: "/approvals", keywords: ["مجوز", "مجوزها", "تاییدات", "approvals", "عملیاتی", "تایید"] },
|
||||
{ label: "وضعیت دپارتمانها و ارکستراسیون (HQ)", path: "/governance/hq", keywords: ["ارکستراسیون", "دپارتمان", "hq", "governance", "وضعیت"] },
|
||||
{ label: 'داشبورد (خلاصه وضعیت فروشگاه)', path: '/', keywords: ['dashboard', 'آمار', 'فروش', 'خانه'] },
|
||||
{ label: 'مرکز مانیتورینگ و سلامت سرویسها', path: '/monitoring', keywords: ['monitoring', 'مانیتورینگ', 'سلامت', 'پینگ', 'وضعیت', 'سرعت'] },
|
||||
{ label: 'مدیریت نسخههای پزشکی (Prescriptions)', path: '/prescriptions', keywords: ['نسخه', 'نسخهها', 'پزشک', 'دارو', 'تجویز', 'rx', 'prescription', 'بررسی نسخه'] },
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
|
||||
@font-face {
|
||||
font-family: 'Shabnam';
|
||||
src: url('/fonts/shabnam-font-v33.003/fonts/webfonts/Shabnam.woff2') format('woff2');
|
||||
src: url('/fonts/shabnam-font-v5.0.1/Shabnam.woff2') format('woff2');
|
||||
font-weight: normal;
|
||||
font-style: normal;
|
||||
font-display: swap;
|
||||
|
||||
@@ -1,163 +0,0 @@
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import toast from "react-hot-toast";
|
||||
import api from "../services/api";
|
||||
import ApprovalsPage from "./ApprovalsPage";
|
||||
|
||||
vi.mock("../services/api", () => {
|
||||
return {
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("react-hot-toast", () => ({
|
||||
default: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
describe("ApprovalsPage Component", () => {
|
||||
const mockApprovals = [
|
||||
{
|
||||
id: "app-1",
|
||||
department: "CONTENT",
|
||||
category: "CAMPAIGN",
|
||||
title: "کمپین تخصصی مفاصل: برتری بالینی صدف لبسبز کنینا نسبت به وتاکسپرت",
|
||||
status: "PENDING",
|
||||
createdAt: "2026-10-19T10:00:00Z",
|
||||
payload: {
|
||||
"1_مسئله_و_شکاف_بازار": "قیمت گزاف قرص مفاصل وتاکسپرت لهستان باعث شکست دورههای درمانی شده است.",
|
||||
"2_راهحل_و_مزیت_کنینا": "معرفی مکمل بیرقیب Velox Gelenkenergie ۱۰۰٪ عصاره صدف لبسبز با نصف قیمت رقیب.",
|
||||
"3_طرح_اقدام_عملیاتی": "تولید لندینگپیج جامع و سئومحور و اتصال مستقیم به ترب.",
|
||||
"4_دپارتمانهای_مسئول": "CONTENT, SEO, CLINICAL_RD",
|
||||
"5_معیار_پذیرش_و_تکمیل": "رندر شدن لندینگ بدون خطای SSR و افزایش ایمپرشن ارگانیک."
|
||||
}
|
||||
},
|
||||
{
|
||||
id: "app-2",
|
||||
department: "PRICING",
|
||||
category: "PRICE_CHANGE",
|
||||
title: "پیشنهاد اصلاح قیمت و همگامسازی با ترب: Canina Flexan 150g",
|
||||
status: "PENDING",
|
||||
createdAt: "2026-10-19T11:00:00Z",
|
||||
payload: {
|
||||
product_name: "Canina Flexan 150g",
|
||||
current_price: 34800000,
|
||||
suggested_price: 36500000,
|
||||
margin_percent: 20.5,
|
||||
competitor_min_torob: 37200000,
|
||||
reason: "افزایش قیمت تامینکننده و میانگین قیمت ترب روی ۳۷.۲ میلیون ریال است."
|
||||
}
|
||||
},
|
||||
{
|
||||
id: "app-3",
|
||||
department: "MARKETING",
|
||||
category: "SMS_CAMPAIGN",
|
||||
title: "کمپین یادآوری تمدید دوره مکملهای مفاصل و GAG",
|
||||
status: "APPROVED",
|
||||
createdAt: "2026-10-18T09:00:00Z",
|
||||
executedAt: "2026-10-18T10:00:00Z",
|
||||
ceoNotes: "تایید شد و پیامکها ارسال شدند.",
|
||||
payload: {
|
||||
campaign_name: "Refill GAG 60-Day Reminder",
|
||||
sms_pattern: "سلام {name} عزیز، دوره مکمل مفاصل کنینا رو به اتمام است.",
|
||||
target_count: 86,
|
||||
estimated_cost_irr: 860000,
|
||||
expected_revenue_irr: 54000000,
|
||||
expected_conversion_rate: "18%"
|
||||
}
|
||||
}
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
(api.get as any).mockResolvedValue({
|
||||
data: {
|
||||
success: true,
|
||||
data: mockApprovals,
|
||||
meta: {
|
||||
total: 3,
|
||||
pendingCount: 2,
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("renders header, KPI cards, and maps strategic 5-part proposal nicely", async () => {
|
||||
render(<ApprovalsPage />);
|
||||
|
||||
expect(await screen.findByText(/کارتابل حاکمیت سازمانی و تاییدات مدیرعامل/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/2 پیشنهاد منتظر تصمیم شما/i)).toBeInTheDocument();
|
||||
|
||||
// Verify 5-part structured fields are cleanly mapped
|
||||
expect(screen.getByText(/مسئله و شکاف شناساییشده در بازار:/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/قیمت گزاف قرص مفاصل وتاکسپرت لهستان/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/راهحل، محصول و مزیت رقابتی کنینا:/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/Velox Gelenkenergie/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders pricing payload with current price, suggested price, and margin", async () => {
|
||||
render(<ApprovalsPage />);
|
||||
|
||||
expect(await screen.findByText(/پیشنهاد اصلاح قیمت و همگامسازی با ترب/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/محاسبه قیمتگذاری و سود ناخالص:/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/20.5٪/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("approves a pending request with CEO directive note", async () => {
|
||||
(api.put as any).mockResolvedValue({
|
||||
data: { success: true },
|
||||
});
|
||||
|
||||
render(<ApprovalsPage />);
|
||||
|
||||
expect(await screen.findByText(/کمپین تخصصی مفاصل/i)).toBeInTheDocument();
|
||||
|
||||
const approveButtons = screen.getAllByRole("button", { name: /تایید و صدور مجوز اجرا/i });
|
||||
expect(approveButtons.length).toBeGreaterThan(0);
|
||||
|
||||
fireEvent.click(approveButtons[0]);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.put).toHaveBeenCalledWith(
|
||||
"/admin/approvals/app-2/decide",
|
||||
expect.objectContaining({ decision: "APPROVED" })
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("runs simulation test when clicking play button", async () => {
|
||||
(api.post as any).mockResolvedValue({
|
||||
data: {
|
||||
success: true,
|
||||
testResult: {
|
||||
status: "SIMULATION_SUCCESS",
|
||||
executionSafe: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
render(<ApprovalsPage />);
|
||||
|
||||
const runTestButtons = await screen.findAllByRole("button", { name: /اجرای تست و شبیهسازی/i });
|
||||
expect(runTestButtons.length).toBeGreaterThan(0);
|
||||
|
||||
fireEvent.click(runTestButtons[0]);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.post).toHaveBeenCalledWith("/admin/approvals/app-2/test");
|
||||
});
|
||||
|
||||
expect(await screen.findByText(/نتیجه تست سلامت و شبیهسازی:/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,323 +0,0 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import {
|
||||
History,
|
||||
Search,
|
||||
Filter,
|
||||
RefreshCw,
|
||||
Clock,
|
||||
User,
|
||||
Database,
|
||||
ArrowRight,
|
||||
Shield,
|
||||
Layers,
|
||||
ChevronDown,
|
||||
Calendar,
|
||||
AlertCircle,
|
||||
Eye,
|
||||
CheckCircle2
|
||||
} from 'lucide-react';
|
||||
import api from '../services/api';
|
||||
|
||||
interface AuditLogItem {
|
||||
id: string;
|
||||
entity: string;
|
||||
entityId: string;
|
||||
action: 'CREATE' | 'UPDATE' | 'DELETE' | 'EXECUTE' | 'BULK_UPDATE';
|
||||
department: string;
|
||||
actor: string;
|
||||
summary: string;
|
||||
oldValues?: any;
|
||||
newValues?: any;
|
||||
metadata?: any;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export default function AuditHistoryPage() {
|
||||
const [logs, setLogs] = useState<AuditLogItem[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
const [selectedEntity, setSelectedEntity] = useState('ALL');
|
||||
const [selectedDept, setSelectedDept] = useState('ALL');
|
||||
const [selectedAction, setSelectedAction] = useState('ALL');
|
||||
const [activeLogModal, setActiveLogModal] = useState<AuditLogItem | null>(null);
|
||||
|
||||
const fetchLogs = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await api.get('/admin/audit-logs?limit=100');
|
||||
if (res.data?.success) {
|
||||
setLogs(res.data.data);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error fetching audit logs:', err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchLogs();
|
||||
}, []);
|
||||
|
||||
const filteredLogs = logs.filter((log) => {
|
||||
const matchesSearch =
|
||||
!searchTerm ||
|
||||
log.summary.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
log.actor.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
log.entity.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
log.entityId.toLowerCase().includes(searchTerm.toLowerCase());
|
||||
|
||||
const matchesEntity = selectedEntity === 'ALL' || log.entity === selectedEntity;
|
||||
const matchesDept = selectedDept === 'ALL' || log.department === selectedDept;
|
||||
const matchesAction = selectedAction === 'ALL' || log.action === selectedAction;
|
||||
|
||||
return matchesSearch && matchesEntity && matchesDept && matchesAction;
|
||||
});
|
||||
|
||||
const getActionBadge = (action: string) => {
|
||||
switch (action) {
|
||||
case 'CREATE':
|
||||
return <span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-emerald-100 text-emerald-800 border border-emerald-200">افزودن (Create)</span>;
|
||||
case 'UPDATE':
|
||||
return <span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-blue-100 text-blue-800 border border-blue-200">ویرایش (Update)</span>;
|
||||
case 'DELETE':
|
||||
return <span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-rose-100 text-rose-800 border border-rose-200">حذف (Delete)</span>;
|
||||
case 'EXECUTE':
|
||||
return <span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-purple-100 text-purple-800 border border-purple-200">اجرا (Execute)</span>;
|
||||
case 'BULK_UPDATE':
|
||||
return <span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-amber-100 text-amber-800 border border-amber-200">دستهجمعی (Bulk)</span>;
|
||||
default:
|
||||
return <span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-gray-100 text-gray-800">{action}</span>;
|
||||
}
|
||||
};
|
||||
|
||||
const getDeptBadge = (dept: string) => {
|
||||
const map: Record<string, string> = {
|
||||
COMMERCE: 'بازرگانی و مالی',
|
||||
PRODUCT: 'محصولات',
|
||||
CONTENT: 'محتوا و وبلاگ',
|
||||
SEO: 'سئو و مارکتینگ',
|
||||
DEV: 'فنی و زیرساخت',
|
||||
ORDER: 'سفارشات',
|
||||
APPROVAL: 'تاییدات مدیریت',
|
||||
};
|
||||
return (
|
||||
<span className="text-[11px] font-bold text-gray-600 bg-gray-100 px-2 py-0.5 rounded-md border border-gray-200">
|
||||
{map[dept] || dept}
|
||||
</span>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6 font-vazir pb-12" dir="rtl">
|
||||
{/* Top Header */}
|
||||
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4 bg-white p-6 rounded-2xl border border-gray-100 shadow-sm">
|
||||
<div>
|
||||
<div className="flex items-center gap-3 mb-1">
|
||||
<div className="w-10 h-10 rounded-xl bg-purple-100 flex items-center justify-center text-purple-700">
|
||||
<History className="w-5 h-5" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-xl font-black text-gray-900">تاریخچه تغییرات زنده دیتابیس (Audit Logs)</h1>
|
||||
<p className="text-xs text-gray-500 font-medium">ردیابی تمامی عملیاتهای اصلاح قیمت، استوک، پستها و کاتالوگ</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={fetchLogs}
|
||||
disabled={loading}
|
||||
className="inline-flex items-center gap-2 px-4 py-2.5 rounded-xl bg-purple-50 text-purple-700 text-xs font-bold hover:bg-purple-100 transition-colors border border-purple-200 cursor-pointer disabled:opacity-50"
|
||||
>
|
||||
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
|
||||
<span>بهروزرسانی لحظهای</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Filter and Search Bar */}
|
||||
<div className="bg-white p-4 rounded-2xl border border-gray-100 shadow-sm space-y-4">
|
||||
<div className="grid grid-cols-1 md:grid-cols-4 gap-3">
|
||||
<div className="relative">
|
||||
<Search className="w-4 h-4 absolute right-3 top-3 text-gray-400" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="جستجو در خلاصه تغییرات، شناسه، اپراتور..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
className="w-full pr-9 pl-3 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500 font-medium"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<select
|
||||
value={selectedEntity}
|
||||
onChange={(e) => setSelectedEntity(e.target.value)}
|
||||
className="w-full px-3 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500 font-bold text-gray-700"
|
||||
>
|
||||
<option value="ALL">همه موجودیتها (Entities)</option>
|
||||
<option value="product">محصولات (Product)</option>
|
||||
<option value="blog">وبلاگ و مقالات (Blog)</option>
|
||||
<option value="category">دستهبندیها (Category)</option>
|
||||
<option value="order">سفارشات (Order)</option>
|
||||
<option value="approval">تاییدیه مدیریت (Approval)</option>
|
||||
<option value="task">تسکها (Task)</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<select
|
||||
value={selectedDept}
|
||||
onChange={(e) => setSelectedDept(e.target.value)}
|
||||
className="w-full px-3 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500 font-bold text-gray-700"
|
||||
>
|
||||
<option value="ALL">همه دپارتمانها</option>
|
||||
<option value="COMMERCE">بازرگانی و مالی</option>
|
||||
<option value="PRODUCT">کاتالوگ و انبار</option>
|
||||
<option value="CONTENT">محتوا و وبلاگ</option>
|
||||
<option value="SEO">سئو و مارکتینگ</option>
|
||||
<option value="DEV">فنی و زیرساخت</option>
|
||||
<option value="APPROVAL">تاییدات هیئت مدیره</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<select
|
||||
value={selectedAction}
|
||||
onChange={(e) => setSelectedAction(e.target.value)}
|
||||
className="w-full px-3 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500 font-bold text-gray-700"
|
||||
>
|
||||
<option value="ALL">همه نوع عملیات</option>
|
||||
<option value="CREATE">افزودن (Create)</option>
|
||||
<option value="UPDATE">ویرایش (Update)</option>
|
||||
<option value="DELETE">حذف (Delete)</option>
|
||||
<option value="EXECUTE">اجرای تغییر (Execute)</option>
|
||||
<option value="BULK_UPDATE">بهروزرسانی انبوه (Bulk)</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Audit Logs Table */}
|
||||
<div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
|
||||
{loading ? (
|
||||
<div className="p-12 text-center text-gray-500 font-bold text-sm">
|
||||
<RefreshCw className="w-6 h-6 animate-spin mx-auto mb-2 text-purple-600" />
|
||||
در حال بارگذاری لاگهای تغییرات دیتابیس...
|
||||
</div>
|
||||
) : filteredLogs.length === 0 ? (
|
||||
<div className="p-12 text-center text-gray-400 font-bold text-sm">
|
||||
هیچ رکورد تغییری با فیلترهای انتخابی یافت نشد.
|
||||
</div>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-right text-xs">
|
||||
<thead className="bg-gray-50/75 border-b border-gray-100 text-gray-500 font-black">
|
||||
<tr>
|
||||
<th className="py-3 px-4">زمان ثبت</th>
|
||||
<th className="py-3 px-4">موجودیت / شناسه</th>
|
||||
<th className="py-3 px-4">نوع اقدام</th>
|
||||
<th className="py-3 px-4">دپارتمان</th>
|
||||
<th className="py-3 px-4">اقدامکننده</th>
|
||||
<th className="py-3 px-4">شرح تغییرات</th>
|
||||
<th className="py-3 px-4 text-center">جزییات فنی</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-100 font-medium text-gray-700">
|
||||
{filteredLogs.map((log) => (
|
||||
<tr key={log.id} className="hover:bg-purple-50/20 transition-colors">
|
||||
<td className="py-3.5 px-4 whitespace-nowrap text-gray-500">
|
||||
<div className="flex items-center gap-1.5 font-sans font-bold text-[11px]">
|
||||
<Clock className="w-3.5 h-3.5 text-gray-400" />
|
||||
<span>{new Date(log.createdAt).toLocaleString('fa-IR')}</span>
|
||||
</div>
|
||||
</td>
|
||||
<td className="py-3.5 px-4 whitespace-nowrap">
|
||||
<div className="font-bold text-gray-900">{log.entity}</div>
|
||||
<div className="text-[10px] font-mono text-gray-400 truncate max-w-[120px]">{log.entityId}</div>
|
||||
</td>
|
||||
<td className="py-3.5 px-4 whitespace-nowrap">
|
||||
{getActionBadge(log.action)}
|
||||
</td>
|
||||
<td className="py-3.5 px-4 whitespace-nowrap">
|
||||
{getDeptBadge(log.department)}
|
||||
</td>
|
||||
<td className="py-3.5 px-4 whitespace-nowrap font-bold text-purple-900">
|
||||
<div className="flex items-center gap-1">
|
||||
<User className="w-3.5 h-3.5 text-purple-600" />
|
||||
<span>{log.actor}</span>
|
||||
</div>
|
||||
</td>
|
||||
<td className="py-3.5 px-4">
|
||||
<div className="font-bold text-gray-800 line-clamp-2 max-w-md">{log.summary}</div>
|
||||
</td>
|
||||
<td className="py-3.5 px-4 text-center whitespace-nowrap">
|
||||
<button
|
||||
onClick={() => setActiveLogModal(log)}
|
||||
className="inline-flex items-center gap-1 px-2.5 py-1 rounded-lg bg-gray-100 hover:bg-purple-100 hover:text-purple-700 text-gray-600 font-bold text-[11px] transition-colors cursor-pointer"
|
||||
>
|
||||
<Eye className="w-3.5 h-3.5" />
|
||||
<span>مشاهده Diff</span>
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Modal View Diff */}
|
||||
{activeLogModal && (
|
||||
<div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4 backdrop-blur-sm animate-in fade-in duration-150">
|
||||
<div className="bg-white rounded-2xl max-w-2xl w-full p-6 space-y-4 shadow-2xl border border-gray-100 max-h-[85vh] overflow-y-auto">
|
||||
<div className="flex items-center justify-between border-b border-gray-100 pb-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Database className="w-5 h-5 text-purple-600" />
|
||||
<h3 className="font-black text-sm text-gray-900">جزییات تغییر دادهها ({activeLogModal.entity})</h3>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setActiveLogModal(null)}
|
||||
className="text-gray-400 hover:text-gray-600 font-bold text-sm cursor-pointer"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="text-xs space-y-2">
|
||||
<div className="p-3 bg-gray-50 rounded-xl">
|
||||
<span className="font-bold text-gray-500">خلاصه عملیات: </span>
|
||||
<span className="font-black text-gray-800">{activeLogModal.summary}</span>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<h4 className="font-bold text-rose-700 mb-1">مقادیر قبلی (Old Values):</h4>
|
||||
<pre className="bg-rose-50 text-rose-900 p-3 rounded-xl text-[10px] font-mono overflow-x-auto max-h-56">
|
||||
{JSON.stringify(activeLogModal.oldValues || { info: 'مقداری ثبت نشده بود' }, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h4 className="font-bold text-emerald-700 mb-1">مقادیر جدید (New Values):</h4>
|
||||
<pre className="bg-emerald-50 text-emerald-900 p-3 rounded-xl text-[10px] font-mono overflow-x-auto max-h-56">
|
||||
{JSON.stringify(activeLogModal.newValues || { info: 'تغییری ثبت نشده' }, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="pt-2 text-left">
|
||||
<button
|
||||
onClick={() => setActiveLogModal(null)}
|
||||
className="px-4 py-2 bg-purple-600 text-white rounded-xl text-xs font-bold hover:bg-purple-700 transition-colors"
|
||||
>
|
||||
بستن
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,352 +0,0 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import {
|
||||
Building2,
|
||||
CheckCircle2,
|
||||
Clock,
|
||||
AlertTriangle,
|
||||
ArrowUpRight,
|
||||
RefreshCw,
|
||||
ShieldCheck,
|
||||
Briefcase,
|
||||
FileText,
|
||||
Stethoscope,
|
||||
Search,
|
||||
Headphones,
|
||||
Cpu,
|
||||
Layers,
|
||||
Terminal,
|
||||
Activity,
|
||||
XCircle,
|
||||
} from 'lucide-react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import api from '../services/api';
|
||||
|
||||
interface DepartmentCard {
|
||||
id: string;
|
||||
name: string;
|
||||
role: string;
|
||||
agentName: string;
|
||||
avatarColor: string;
|
||||
icon: any;
|
||||
status: 'ACTIVE' | 'PROCESSING' | 'STANDBY';
|
||||
currentFocus: string;
|
||||
pendingApprovals: number;
|
||||
completedTasks: number;
|
||||
recentReasoningSnippet: string;
|
||||
}
|
||||
|
||||
const BASE_DEPARTMENTS: Omit<DepartmentCard, 'status' | 'pendingApprovals' | 'completedTasks' | 'recentReasoningSnippet' | 'currentFocus'>[] = [
|
||||
{
|
||||
id: 'CONTENT',
|
||||
name: 'واحد محتوا و وبلاگ تخصصی',
|
||||
role: 'تحقیق عمیق، مقالات بالینی، تولید تصویر و سئوی محتوایی',
|
||||
agentName: 'Canina-Content-Agent',
|
||||
avatarColor: 'from-blue-600 to-indigo-700',
|
||||
icon: FileText,
|
||||
},
|
||||
{
|
||||
id: 'CLINICAL_RD',
|
||||
name: 'واحد تحقیق و توسعه بالینی (R&D)',
|
||||
role: 'فکتچکینگ پزشکی، اعتبارسنجی دوزها و مراجع داروسازی آلمان',
|
||||
agentName: 'Canina-Medical-Agent',
|
||||
avatarColor: 'from-emerald-600 to-teal-700',
|
||||
icon: Stethoscope,
|
||||
},
|
||||
{
|
||||
id: 'SEO',
|
||||
name: 'واحد سئو و هوش بازار',
|
||||
role: 'پایش سرچ کنسول، شناسایی کلمات کلیدی، بهینهسازی اسکیما و فید ترب',
|
||||
agentName: 'Canina-SEO-Agent',
|
||||
avatarColor: 'from-amber-500 to-orange-600',
|
||||
icon: Search,
|
||||
},
|
||||
{
|
||||
id: 'B2B',
|
||||
name: 'واحد توسعه سازمانی و B2B',
|
||||
role: 'پایپلاین کلینیکها، بیمارستانهای دامپزشکی و بستههای نمایندگی',
|
||||
agentName: 'Canina-B2B-Agent',
|
||||
avatarColor: 'from-purple-600 to-violet-800',
|
||||
icon: Building2,
|
||||
},
|
||||
{
|
||||
id: 'DEVOPS',
|
||||
name: 'واحد مهندسی، زیرساخت و امنیت',
|
||||
role: 'پایش سلامت کانتینرها، مصرف دیسک، SSL و پایپلاین آزمونمحور TDD',
|
||||
agentName: 'Canina-DevOps-Agent',
|
||||
avatarColor: 'from-rose-600 to-red-700',
|
||||
icon: Cpu,
|
||||
},
|
||||
{
|
||||
id: 'SUPPORT',
|
||||
name: 'واحد پشتیبانی و مشاوره هوشمند',
|
||||
role: 'پاسخگویی به مشتریان، تریاژ پرسشهای پت و ثبت تیکتهای پیگیری',
|
||||
agentName: 'Canina-Support-Agent',
|
||||
avatarColor: 'from-cyan-600 to-blue-700',
|
||||
icon: Headphones,
|
||||
}
|
||||
];
|
||||
|
||||
export default function CompanyOrchestrationHQ() {
|
||||
const [departments, setDepartments] = useState<DepartmentCard[]>([]);
|
||||
const [totalPendingApprovals, setTotalPendingApprovals] = useState<number>(0);
|
||||
const [totalTasksCount, setTotalTasksCount] = useState<number>(0);
|
||||
const [isLoading, setIsLoading] = useState<boolean>(true);
|
||||
const [hasError, setHasError] = useState<boolean>(false);
|
||||
|
||||
const fetchLiveStatus = async () => {
|
||||
setIsLoading(true);
|
||||
setHasError(false);
|
||||
try {
|
||||
const [_statsRes, tasksRes, approvalsRes] = await Promise.all([
|
||||
api.get('/admin/department-tasks/stats'),
|
||||
api.get('/admin/department-tasks?limit=100'),
|
||||
api.get('/admin/approvals?limit=100')
|
||||
]);
|
||||
|
||||
const tasks = tasksRes.data?.data || [];
|
||||
const approvals = approvalsRes.data?.data || [];
|
||||
|
||||
// Calculate operational pending approvals (excluding non-authorization items)
|
||||
const pendingApprovalsList = approvals.filter((a: any) =>
|
||||
a.status === 'PENDING' && a.category !== 'B2B_SUPPLIER_STRATEGY'
|
||||
);
|
||||
setTotalPendingApprovals(pendingApprovalsList.length);
|
||||
setTotalTasksCount(tasks.length);
|
||||
|
||||
const mapped: DepartmentCard[] = BASE_DEPARTMENTS.map(base => {
|
||||
const deptTasks = tasks.filter((t: any) =>
|
||||
t.department === base.id || (base.id === 'DEVOPS' && t.department === 'DEV')
|
||||
);
|
||||
const inProgress = deptTasks.find((t: any) => t.status === 'IN_PROGRESS');
|
||||
const latestTask = deptTasks[0];
|
||||
const completedCount = deptTasks.filter((t: any) => t.status === 'DONE').length;
|
||||
|
||||
let status: 'ACTIVE' | 'PROCESSING' | 'STANDBY' = 'STANDBY';
|
||||
if (inProgress) status = 'ACTIVE';
|
||||
else if (deptTasks.some((t: any) => t.status === 'TEST' || t.status === 'WAITING_DEPENDENCIES')) {
|
||||
status = 'PROCESSING';
|
||||
}
|
||||
|
||||
let currentFocus = 'آمادهباش / بدون وظیفه فعال در حال حاضر';
|
||||
if (inProgress) currentFocus = inProgress.title;
|
||||
else if (latestTask) currentFocus = latestTask.title;
|
||||
|
||||
let snippet = 'بدون ثبت لاگ اجرایی در وظایف اخیر.';
|
||||
if (latestTask?.executionLogs?.length) {
|
||||
const lastLog = latestTask.executionLogs[latestTask.executionLogs.length - 1];
|
||||
snippet = lastLog?.summary || lastLog?.note || (lastLog?.deliverable?.type ? `تحویل خروجی: ${lastLog.deliverable.type}` : snippet);
|
||||
}
|
||||
|
||||
// Real department-specific pending approvals (strictly from live data, no synthetic telemetry)
|
||||
const deptPendingCount = pendingApprovalsList.filter((a: any) =>
|
||||
a.department === base.id || (base.id === 'DEVOPS' && a.department === 'DEV')
|
||||
).length;
|
||||
|
||||
return {
|
||||
...base,
|
||||
status,
|
||||
currentFocus,
|
||||
pendingApprovals: deptPendingCount,
|
||||
completedTasks: completedCount,
|
||||
recentReasoningSnippet: snippet
|
||||
};
|
||||
});
|
||||
|
||||
setDepartments(mapped);
|
||||
} catch (err) {
|
||||
console.error('Error fetching live orchestration telemetry:', err);
|
||||
setHasError(true);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchLiveStatus();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="space-y-6 font-vazir" dir="rtl">
|
||||
{/* Honest Executive Header */}
|
||||
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4 bg-white p-6 rounded-3xl border border-gray-200 shadow-sm">
|
||||
<div>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="p-3 bg-purple-100 text-purple-700 rounded-2xl border border-purple-200">
|
||||
<Building2 className="w-8 h-8" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-xl md:text-2xl font-black text-gray-900 flex items-center gap-3">
|
||||
وضعیت و ارکستراسیون دپارتمانها (Department Governance Status)
|
||||
{hasError ? (
|
||||
<span className="text-[10px] px-2.5 py-1 rounded-full font-black bg-rose-100 text-rose-800 border border-rose-300">
|
||||
خطا در همگامسازی وضعیت
|
||||
</span>
|
||||
) : isLoading ? (
|
||||
<span className="text-[10px] px-2.5 py-1 rounded-full font-black bg-blue-100 text-blue-800 border border-blue-300">
|
||||
در حال دریافت دادهها...
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-[10px] px-2.5 py-1 rounded-full font-black bg-emerald-100 text-emerald-800 border border-emerald-300">
|
||||
دادههای زنده سیستم
|
||||
</span>
|
||||
)}
|
||||
</h1>
|
||||
<p className="text-xs text-gray-500 mt-1 font-medium">
|
||||
پایش وظایف، وضعیت و خروجی عملیاتی دپارتمانها و ایجنتها بر اساس دادههای واقعی سرویس
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2.5">
|
||||
<Link
|
||||
to="/manager-actions"
|
||||
className="flex items-center gap-1.5 px-3.5 py-2 bg-indigo-50 hover:bg-indigo-100 text-indigo-700 border border-indigo-200 rounded-xl text-xs font-bold transition-all"
|
||||
>
|
||||
<Briefcase className="w-4 h-4 text-indigo-600" />
|
||||
<span>اقدامات مدیریتی و همکاریها</span>
|
||||
</Link>
|
||||
|
||||
<Link
|
||||
to="/approvals"
|
||||
className="flex items-center gap-1.5 px-3.5 py-2 bg-amber-50 hover:bg-amber-100 text-amber-800 border border-amber-300 rounded-xl text-xs font-bold transition-all"
|
||||
>
|
||||
<ShieldCheck className="w-4 h-4 text-amber-600" />
|
||||
<span>مجوزهای عملیاتی ({totalPendingApprovals} مورد)</span>
|
||||
</Link>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={fetchLiveStatus}
|
||||
disabled={isLoading}
|
||||
className="inline-flex items-center gap-1.5 px-3 py-2 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-700 text-xs font-bold transition-all border border-gray-200 cursor-pointer disabled:opacity-50"
|
||||
>
|
||||
<RefreshCw className={`w-3.5 h-3.5 ${isLoading ? 'animate-spin' : ''}`} />
|
||||
<span>تازهسازی</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Honest Error State */}
|
||||
{hasError ? (
|
||||
<div className="bg-white p-8 rounded-3xl border border-rose-200 shadow-sm text-center space-y-3">
|
||||
<XCircle className="w-12 h-12 text-rose-500 mx-auto" />
|
||||
<h3 className="text-base font-black text-gray-900">دادههای وضعیت در دسترس نیست</h3>
|
||||
<p className="text-xs text-gray-500 max-w-md mx-auto">
|
||||
امکان ارتباط با سرویس ارکستراسیون یا دریافت آمار وظایف دپارتمانها وجود ندارد. به منظور حفظ صداقت عملیاتی، هیچ وضعیت شبیهسازیشدهای رندر نمیشود.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={fetchLiveStatus}
|
||||
className="px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-xl text-xs font-bold transition-all"
|
||||
>
|
||||
تلاش مجدد جهت اتصال
|
||||
</button>
|
||||
</div>
|
||||
) : isLoading ? (
|
||||
<div className="py-24 flex flex-col justify-center items-center gap-3">
|
||||
<RefreshCw className="w-8 h-8 text-purple-600 animate-spin" />
|
||||
<span className="text-xs font-bold text-gray-500">در حال واکشی وضعیت واقعی دپارتمانها...</span>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{/* Honest Metrics Summary */}
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
|
||||
<div className="bg-white p-4 rounded-2xl border border-gray-200 shadow-xs">
|
||||
<span className="text-[11px] font-bold text-gray-500">کل دپارتمانهای سازمانی</span>
|
||||
<p className="text-2xl font-black text-gray-900 mt-1 font-mono">{departments.length}</p>
|
||||
</div>
|
||||
<div className="bg-white p-4 rounded-2xl border border-gray-200 shadow-xs">
|
||||
<span className="text-[11px] font-bold text-gray-500">کل وظایف ثبتشده</span>
|
||||
<p className="text-2xl font-black text-gray-900 mt-1 font-mono">{totalTasksCount}</p>
|
||||
</div>
|
||||
<div className="bg-white p-4 rounded-2xl border border-amber-200 shadow-xs">
|
||||
<span className="text-[11px] font-bold text-amber-700">مجوزهای عملیاتی معلق</span>
|
||||
<p className="text-2xl font-black text-amber-700 mt-1 font-mono">{totalPendingApprovals}</p>
|
||||
</div>
|
||||
<div className="bg-white p-4 rounded-2xl border border-emerald-200 shadow-xs">
|
||||
<span className="text-[11px] font-bold text-emerald-700">دپارتمانهای در حال کار</span>
|
||||
<p className="text-2xl font-black text-emerald-700 mt-1 font-mono">
|
||||
{departments.filter(d => d.status === 'ACTIVE').length}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Department Cards Grid */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
|
||||
{departments.map((dept) => (
|
||||
<div
|
||||
key={dept.id}
|
||||
className="bg-white border border-gray-200 rounded-3xl p-5 hover:border-purple-300 hover:shadow-md transition-all flex flex-col justify-between shadow-xs"
|
||||
>
|
||||
<div>
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className={`p-3 rounded-2xl bg-gradient-to-br ${dept.avatarColor} text-white shadow-xs`}>
|
||||
<dept.icon className="w-5 h-5" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-sm font-black text-gray-900">{dept.name}</h3>
|
||||
<p className="text-[11px] text-purple-700 font-bold">{dept.agentName}</p>
|
||||
</div>
|
||||
</div>
|
||||
<span className={`text-[10px] font-black px-2 py-0.5 rounded-full border ${
|
||||
dept.status === 'ACTIVE'
|
||||
? 'bg-emerald-50 text-emerald-800 border-emerald-200'
|
||||
: dept.status === 'PROCESSING'
|
||||
? 'bg-amber-50 text-amber-800 border-amber-200'
|
||||
: 'bg-gray-100 text-gray-600 border-gray-200'
|
||||
}`}>
|
||||
{dept.status === 'ACTIVE' ? 'در حال کار' : dept.status === 'PROCESSING' ? 'در حال تست' : 'آمادهباش'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-gray-600 mt-3 font-medium leading-relaxed">
|
||||
{dept.role}
|
||||
</p>
|
||||
|
||||
<div className="mt-4 p-3 rounded-2xl bg-gray-50 border border-gray-100 space-y-1">
|
||||
<div className="text-[10px] font-bold text-gray-500 flex items-center gap-1.5">
|
||||
<Activity className="w-3.5 h-3.5 text-purple-600" />
|
||||
<span>تمرکز فعلی دپارتمان:</span>
|
||||
</div>
|
||||
<p className="text-xs text-gray-800 font-medium line-clamp-1">
|
||||
{dept.currentFocus}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="mt-2 p-3 rounded-2xl bg-gray-50 border border-gray-100 space-y-1">
|
||||
<div className="text-[10px] font-bold text-gray-500 flex items-center gap-1.5">
|
||||
<Terminal className="w-3.5 h-3.5 text-purple-600" />
|
||||
<span>آخرین لاگ و استدلال واقعی:</span>
|
||||
</div>
|
||||
<p className="text-[11px] text-gray-700 font-mono leading-relaxed line-clamp-2">
|
||||
{dept.recentReasoningSnippet}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-5 pt-4 border-t border-gray-100 flex items-center justify-between text-xs">
|
||||
<div className="space-x-2 space-x-reverse text-gray-600">
|
||||
<span>وظایف انجامشده: <strong className="text-gray-900 font-bold">{dept.completedTasks}</strong></span>
|
||||
{dept.pendingApprovals > 0 && (
|
||||
<span className="text-amber-700 font-bold">({dept.pendingApprovals} مجوز معلق)</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Link
|
||||
to="/tasks"
|
||||
className="flex items-center gap-1 text-purple-700 hover:text-purple-800 font-bold text-xs"
|
||||
>
|
||||
<span>مشاهده وظایف</span>
|
||||
<ArrowUpRight className="w-3.5 h-3.5" />
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -43,13 +43,7 @@ describe('Dashboard Page Component', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(api.get).mockImplementation((url: string) => {
|
||||
if (url.includes('/admin/audit-logs')) {
|
||||
return Promise.resolve({ data: { success: true, data: [] } } as any);
|
||||
}
|
||||
if (url.includes('/admin/approvals')) {
|
||||
return Promise.resolve({ data: { success: true, meta: { pendingCount: 0 } } } as any);
|
||||
}
|
||||
vi.mocked(api.get).mockImplementation((_url: string) => {
|
||||
return Promise.resolve({ data: { success: true, data: mockStats } } as any);
|
||||
});
|
||||
});
|
||||
@@ -65,8 +59,8 @@ describe('Dashboard Page Component', () => {
|
||||
it('renders dashboard headers and initial zero or placeholder stats', async () => {
|
||||
renderDashboard();
|
||||
|
||||
expect(screen.getByText('داشبورد فرماندهی کنینا')).toBeInTheDocument();
|
||||
expect(screen.getByText('خلاصه عملیات، وضعیت دیتابیس و نظارت بر وظایف خودکار سازمان')).toBeInTheDocument();
|
||||
expect(screen.getByText('داشبورد')).toBeInTheDocument();
|
||||
expect(screen.getByText('خلاصهای از وضعیت فروشگاه کنینا')).toBeInTheDocument();
|
||||
expect(screen.getByText('درآمد کل')).toBeInTheDocument();
|
||||
expect(screen.getByText('سفارشات جدید')).toBeInTheDocument();
|
||||
expect(screen.getByText('کاربران فعال')).toBeInTheDocument();
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Activity, DollarSign, ShoppingCart, Users, ShieldAlert, ArrowLeft, History, Briefcase, Clock, Database } from "lucide-react";
|
||||
import { Activity, DollarSign, ShoppingCart, Users } from "lucide-react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { CartesianGrid, Cell, Line, LineChart, Pie, PieChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
|
||||
@@ -17,25 +17,7 @@ interface DashboardData {
|
||||
categoriesDistribution?: CategoryDist[];
|
||||
}
|
||||
|
||||
interface AuditLogSummary {
|
||||
id: string;
|
||||
entity: string;
|
||||
action: string;
|
||||
department: string;
|
||||
actor: string;
|
||||
summary: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export default function Dashboard() {
|
||||
const [pendingApprovalsCount, setPendingApprovalsCount] = useState<number>(0);
|
||||
const [recentLogs, setRecentLogs] = useState<AuditLogSummary[]>([]);
|
||||
const [taskStats, setTaskStats] = useState<{ total: number; done: number; inProgress: number }>({
|
||||
total: 0,
|
||||
done: 0,
|
||||
inProgress: 0,
|
||||
});
|
||||
|
||||
const [data, setData] = useState<DashboardData>({
|
||||
revenue: 0,
|
||||
newOrders: 0,
|
||||
@@ -44,18 +26,6 @@ export default function Dashboard() {
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const fetchPendingApprovals = async () => {
|
||||
try {
|
||||
const res = await api.get('/admin/approvals?limit=1');
|
||||
if (res.data?.success && res.data?.meta) {
|
||||
setPendingApprovalsCount(res.data.meta.pendingCount || 0);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to fetch approvals count', e);
|
||||
}
|
||||
};
|
||||
fetchPendingApprovals();
|
||||
|
||||
const fetchStats = async () => {
|
||||
try {
|
||||
const response = await api.get('/admin/dashboard/stats');
|
||||
@@ -67,36 +37,6 @@ export default function Dashboard() {
|
||||
}
|
||||
};
|
||||
fetchStats();
|
||||
|
||||
// Fetch recent audit logs for live widget
|
||||
const fetchRecentLogs = async () => {
|
||||
try {
|
||||
const res = await api.get('/admin/audit-logs?limit=5');
|
||||
if (res.data?.success) {
|
||||
setRecentLogs(Array.isArray(res.data.data) ? res.data.data : (Array.isArray(res.data.data?.logs) ? res.data.data.logs : []));
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to fetch audit logs widget', e);
|
||||
}
|
||||
};
|
||||
fetchRecentLogs();
|
||||
|
||||
// Fetch tasks summary
|
||||
const fetchTaskStats = async () => {
|
||||
try {
|
||||
const res = await api.get('/admin/department-tasks/stats');
|
||||
if (res.data?.success) {
|
||||
setTaskStats({
|
||||
total: res.data.data.total || 0,
|
||||
done: res.data.data.byStatus?.DONE || 0,
|
||||
inProgress: res.data.data.byStatus?.IN_PROGRESS || 0,
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to fetch task stats widget', e);
|
||||
}
|
||||
};
|
||||
fetchTaskStats();
|
||||
}, []);
|
||||
|
||||
const chartData = [
|
||||
@@ -125,60 +65,11 @@ export default function Dashboard() {
|
||||
|
||||
return (
|
||||
<div className="space-y-6 font-vazir" dir="rtl">
|
||||
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
|
||||
<div>
|
||||
<h2 className="text-2xl font-black text-gray-900">داشبورد فرماندهی کنینا</h2>
|
||||
<p className="text-gray-500 font-medium mt-1">خلاصه عملیات، وضعیت دیتابیس و نظارت بر وظایف خودکار سازمان</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Link
|
||||
to="/history"
|
||||
className="flex items-center gap-1.5 px-3 py-2 bg-white border border-gray-200 hover:border-purple-300 text-gray-700 rounded-xl text-xs font-bold transition-all shadow-sm"
|
||||
>
|
||||
<History className="w-4 h-4 text-purple-600" />
|
||||
<span>تاریخچه تغییرات دیتابیس</span>
|
||||
</Link>
|
||||
|
||||
<Link
|
||||
to="/tasks"
|
||||
className="flex items-center gap-1.5 px-3 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-xl text-xs font-bold transition-all shadow-sm"
|
||||
>
|
||||
<Briefcase className="w-4 h-4" />
|
||||
<span>کارتابل تسکها ({taskStats.total})</span>
|
||||
</Link>
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-2xl font-black text-gray-900">داشبورد</h2>
|
||||
<p className="text-gray-500 font-medium mt-1">خلاصهای از وضعیت فروشگاه کنینا</p>
|
||||
</div>
|
||||
|
||||
{/* Approval Gate Alert Banner */}
|
||||
{pendingApprovalsCount > 0 && (
|
||||
<div className="bg-gradient-to-r from-amber-500/10 via-amber-500/5 to-transparent border border-amber-500/30 rounded-2xl p-5 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
|
||||
<div className="flex items-center gap-3.5">
|
||||
<div className="w-12 h-12 rounded-xl bg-amber-500 text-white flex items-center justify-center shadow-lg shadow-amber-500/20 shrink-0">
|
||||
<ShieldAlert className="w-6 h-6" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="font-bold text-gray-900 text-base flex items-center gap-2">
|
||||
میز کار تاییدات و حاکمیت سازمانی
|
||||
<span className="bg-amber-100 text-amber-800 text-xs px-2.5 py-0.5 rounded-full font-black">
|
||||
{pendingApprovalsCount} مورد در انتظار تصمیم شما
|
||||
</span>
|
||||
</h3>
|
||||
<p className="text-xs text-gray-500 mt-1 font-medium">
|
||||
پیشنهادات کارشناسی دپارتمانها (مالی، تامین، محتوا، بازاریابی و DevOps) معلق به تایید نهایی شما هستند.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<Link
|
||||
to="/approvals"
|
||||
className="flex items-center gap-2 bg-amber-500 hover:bg-amber-600 text-white font-bold text-xs px-4 py-2.5 rounded-xl transition-all shadow-sm shrink-0"
|
||||
>
|
||||
ورود به کارتابل و بررسی
|
||||
<ArrowLeft className="w-4 h-4" />
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Quick Stats Grid */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
|
||||
{stats.map((stat, i) => {
|
||||
@@ -197,77 +88,6 @@ export default function Dashboard() {
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Live History Widget & Department Tasks Widget */}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
{/* Recent Audit Logs Widget */}
|
||||
<div className="bg-white p-6 rounded-2xl shadow-sm border border-gray-100">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<Database className="w-5 h-5 text-purple-600" />
|
||||
<h3 className="text-sm font-black text-gray-900">آخرین تغییرات زنده دیتابیس (Audit History)</h3>
|
||||
</div>
|
||||
<Link to="/history" className="text-xs font-bold text-purple-600 hover:underline">
|
||||
مشاهده تمام لاگها
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
{recentLogs.length === 0 ? (
|
||||
<div className="text-center py-6 text-gray-400 text-xs font-medium">
|
||||
رکوردی در تاریخچه ثبت نشده است.
|
||||
</div>
|
||||
) : (
|
||||
(Array.isArray(recentLogs) ? recentLogs : []).map((log) => (
|
||||
<div key={log.id} className="p-3 bg-gray-50 rounded-xl flex items-center justify-between text-xs hover:bg-purple-50/40 transition-colors">
|
||||
<div className="flex items-center gap-2.5 overflow-hidden">
|
||||
<span className="w-2 h-2 rounded-full bg-purple-500 shrink-0" />
|
||||
<div className="truncate">
|
||||
<p className="font-bold text-gray-800 truncate">{log.summary}</p>
|
||||
<span className="text-[10px] text-gray-400">{log.entity} • توسط {log.actor}</span>
|
||||
</div>
|
||||
</div>
|
||||
<span className="text-[10px] text-gray-400 shrink-0 font-mono">
|
||||
{new Date(log.createdAt).toLocaleTimeString('fa-IR')}
|
||||
</span>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Department Tasks Live Pipeline Widget */}
|
||||
<div className="bg-white p-6 rounded-2xl shadow-sm border border-gray-100">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<Briefcase className="w-5 h-5 text-indigo-600" />
|
||||
<h3 className="text-sm font-black text-gray-900">پایپلاین وظایف دپارتمانها و ایجنتها</h3>
|
||||
</div>
|
||||
<Link to="/tasks" className="text-xs font-bold text-indigo-600 hover:underline">
|
||||
ورود به تسک منیجر
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-3 gap-3 mb-4">
|
||||
<div className="p-3 bg-gray-50 rounded-xl text-center">
|
||||
<div className="text-lg font-black text-gray-800">{taskStats.total}</div>
|
||||
<div className="text-[11px] font-bold text-gray-500">کل تسکها</div>
|
||||
</div>
|
||||
<div className="p-3 bg-blue-50 rounded-xl text-center">
|
||||
<div className="text-lg font-black text-blue-700">{taskStats.inProgress}</div>
|
||||
<div className="text-[11px] font-bold text-blue-600">در حال انجام</div>
|
||||
</div>
|
||||
<div className="p-3 bg-emerald-50 rounded-xl text-center">
|
||||
<div className="text-lg font-black text-emerald-700">{taskStats.done}</div>
|
||||
<div className="text-[11px] font-bold text-emerald-600">تکمیلشده</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-gray-500 leading-relaxed font-medium">
|
||||
تمام تسکهای تاییدشده به صورت خودکار به پایپلاین اجرایی منتقل شده و لاگ تغییرات آنها در جدول دیتابیس و تاریخچه به ثبت میرسد.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||
<div className="bg-white p-6 rounded-2xl shadow-sm border border-gray-100 col-span-1 lg:col-span-2">
|
||||
<h3 className="text-lg font-bold text-gray-900 mb-6">روند بازدید و فروش (۷ روز گذشته)</h3>
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import CompanyOrchestrationHQ from './CompanyOrchestrationHQ';
|
||||
|
||||
vi.mock('../services/api', () => ({ default: { get: vi.fn() } }));
|
||||
|
||||
describe('governance source integrity', () => {
|
||||
beforeEach(() => { vi.clearAllMocks(); });
|
||||
it('shows unavailable instead of a synthetic active department when APIs fail', async () => {
|
||||
vi.mocked(api.get).mockRejectedValue(new Error('offline'));
|
||||
render(<MemoryRouter><CompanyOrchestrationHQ /></MemoryRouter>);
|
||||
expect(await screen.findByText(/دادههای وضعیت در دسترس نیست/)).toBeInTheDocument();
|
||||
expect(screen.queryByText(/سیستم زنده و فعال/)).not.toBeInTheDocument();
|
||||
expect(screen.queryByText(/نمای سهبعدی و بصری/)).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -1,150 +0,0 @@
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import ManagerActionsPage from './ManagerActionsPage';
|
||||
|
||||
vi.mock('../services/api', () => ({
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
put: vi.fn(),
|
||||
post: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('react-hot-toast', () => ({
|
||||
default: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
const mockItems = [
|
||||
{
|
||||
id: 'act-supplier-1',
|
||||
category: 'B2B_SUPPLIER_STRATEGY',
|
||||
department: 'B2B',
|
||||
title: 'توسعه استراتژی تامینکننده صدف لبسبز آلمان',
|
||||
status: 'IN_PROGRESS',
|
||||
createdAt: '2026-10-19T08:00:00Z',
|
||||
payload: {
|
||||
'1_مسئله_و_شکاف_بازار': 'کمبود ماده موثره پودر صدف در خطوط تولید داخلی',
|
||||
'2_راهحل_و_مزیت_کنینا': 'عقد تفاهمنامه مستقیم با تامینکننده لوکزامبورگ/آلمان',
|
||||
'3_طرح_اقدام_عملیاتی': 'مذاکره بازرگانی جهت دریافت نمونه آزمایشگاهی و بچ آزمایشی',
|
||||
'4_دپارتمانهای_مسئول': 'B2B, CLINICAL_RD',
|
||||
},
|
||||
// No outcome or evidence yet
|
||||
outcome: null,
|
||||
evidence: null,
|
||||
},
|
||||
{
|
||||
id: 'act-supplier-2',
|
||||
category: 'B2B_SUPPLIER_STRATEGY',
|
||||
department: 'B2B',
|
||||
title: 'قرارداد عاملیت توزیع کلینیکی بیمارستان دامپزشکی مرکزی',
|
||||
status: 'COMPLETED',
|
||||
createdAt: '2026-10-18T10:00:00Z',
|
||||
payload: {
|
||||
partner_name: 'بیمارستان دامپزشکی مرکزی',
|
||||
scope: 'توزیع انحصاری مکملهای مفاصل و آرامبخش',
|
||||
},
|
||||
outcome: 'انعقاد قرارداد رسمی عاملیت توزیع سالانه با سهمیه ماهانه ۵۰ بسته',
|
||||
evidence: 'قرارداد امضاشده شماره B2B-1405-091 در بایگانی حقوقی',
|
||||
},
|
||||
{
|
||||
id: 'auth-seo-1',
|
||||
category: 'SEO',
|
||||
department: 'SEO',
|
||||
title: 'تغییر عنوان متاتگ و ریدایرکتهای مقالات مفاصل',
|
||||
status: 'PENDING',
|
||||
createdAt: '2026-10-19T09:00:00Z',
|
||||
payload: {
|
||||
target_url: '/blog/joint-supplements-guide',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
describe('ManagerActionsPage Component', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(api.get).mockResolvedValue({
|
||||
data: {
|
||||
success: true,
|
||||
data: mockItems,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('renders B2B_SUPPLIER_STRATEGY items and excludes operational SEO authorizations', async () => {
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<ManagerActionsPage />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
expect(await screen.findByText('توسعه استراتژی تامینکننده صدف لبسبز آلمان')).toBeInTheDocument();
|
||||
expect(screen.getByText('قرارداد عاملیت توزیع کلینیکی بیمارستان دامپزشکی مرکزی')).toBeInTheDocument();
|
||||
|
||||
// SEO item belongs strictly in operational authorization queue, not here!
|
||||
expect(screen.queryByText('تغییر عنوان متاتگ و ریدایرکتهای مقالات مفاصل')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('never displays an approval button; requires explicit outcome and evidence for completion', async () => {
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<ManagerActionsPage />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
await screen.findByText('توسعه استراتژی تامینکننده صدف لبسبز آلمان');
|
||||
|
||||
// Rule: Manager actions are NOT operational authorizations. No "approval" button allowed!
|
||||
expect(screen.queryByRole('button', { name: /تایید و صدور مجوز اجرا/i })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: /تایید درخواست/i })).not.toBeInTheDocument();
|
||||
|
||||
// Incomplete manager action shows explicit requirement indicator
|
||||
expect(screen.getByText(/نیازمند ثبت نتیجه و مدرک جهت احراز تکمیل/i)).toBeInTheDocument();
|
||||
|
||||
// Completed action displays its explicit outcome and evidence
|
||||
expect(screen.getByText(/انعقاد قرارداد رسمی عاملیت توزیع سالانه با سهمیه ماهانه ۵۰ بسته/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/قرارداد امضاشده شماره B2B-1405-091 در بایگانی حقوقی/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/تکمیلشده و احراز شده با مستندات/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('allows recording explicit outcome and evidence for an action', async () => {
|
||||
vi.mocked(api.put).mockResolvedValue({
|
||||
data: { success: true },
|
||||
});
|
||||
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<ManagerActionsPage />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
expect(await screen.findByText('توسعه استراتژی تامینکننده صدف لبسبز آلمان')).toBeInTheDocument();
|
||||
|
||||
const outcomeInput = screen.getByPlaceholderText(/نتیجه حاصله از این اقدام مدیریتی.../i);
|
||||
const evidenceInput = screen.getByPlaceholderText(/مستندات، شماره سند، لینک گزارش یا فایل.../i);
|
||||
|
||||
fireEvent.change(outcomeInput, { target: { value: 'نمونه اولیه آزمایشگاهی با خلوص ۹۸٪ تایید شد' } });
|
||||
fireEvent.change(evidenceInput, { target: { value: 'گواهی آنالیز آزمایشگاه رازی کد QA-9921' } });
|
||||
|
||||
const submitBtn = screen.getByRole('button', { name: /ثبت نتیجه و مستندات اقدام/i });
|
||||
fireEvent.click(submitBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.put).toHaveBeenCalledWith(
|
||||
'/admin/approvals/act-supplier-1/decide',
|
||||
expect.objectContaining({
|
||||
outcome: 'نمونه اولیه آزمایشگاهی با خلوص ۹۸٪ تایید شد',
|
||||
evidence: 'گواهی آنالیز آزمایشگاه رازی کد QA-9921',
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,477 +0,0 @@
|
||||
import React, { useState, useEffect, useMemo } from 'react';
|
||||
import {
|
||||
Building2,
|
||||
Briefcase,
|
||||
CheckCircle2,
|
||||
AlertTriangle,
|
||||
Clock,
|
||||
RefreshCw,
|
||||
Search,
|
||||
FileText,
|
||||
ShieldCheck,
|
||||
Send,
|
||||
AlertCircle,
|
||||
Layers,
|
||||
} from 'lucide-react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import toast from 'react-hot-toast';
|
||||
import api from '../services/api';
|
||||
|
||||
interface ManagerActionItem {
|
||||
id: string;
|
||||
department: string;
|
||||
category: string;
|
||||
title: string;
|
||||
payload: any;
|
||||
status: string;
|
||||
ceoNotes?: string;
|
||||
outcome?: string | null;
|
||||
evidence?: string | null;
|
||||
createdAt: string;
|
||||
executedAt?: string;
|
||||
}
|
||||
|
||||
export default function ManagerActionsPage() {
|
||||
const [items, setItems] = useState<ManagerActionItem[]>([]);
|
||||
const [loading, setLoading] = useState<boolean>(true);
|
||||
const [error, setError] = useState<boolean>(false);
|
||||
const [searchQuery, setSearchQuery] = useState<string>('');
|
||||
const [statusFilter, setStatusFilter] = useState<'ALL' | 'VERIFIED' | 'PENDING_EVIDENCE'>('ALL');
|
||||
|
||||
// Input states for outcome and evidence editing
|
||||
const [actionForm, setActionForm] = useState<Record<string, { outcome: string; evidence: string }>>({});
|
||||
const [submittingId, setSubmittingId] = useState<string | null>(null);
|
||||
|
||||
const fetchActions = async () => {
|
||||
setLoading(true);
|
||||
setError(false);
|
||||
try {
|
||||
const res = await api.get('/admin/approvals?limit=100');
|
||||
if (res.data?.success && Array.isArray(res.data.data)) {
|
||||
// Manager actions are strategic categories like B2B_SUPPLIER_STRATEGY or PARTNERSHIP
|
||||
// Operational authorizations (SEO, PRICING, SMS, etc.) are strictly excluded!
|
||||
const managerActions = res.data.data.filter((item: any) =>
|
||||
item.category === 'B2B_SUPPLIER_STRATEGY' ||
|
||||
item.category === 'PARTNERSHIP' ||
|
||||
(item.department === 'B2B' && item.category?.includes('STRATEGY'))
|
||||
);
|
||||
|
||||
const initialForms: Record<string, { outcome: string; evidence: string }> = {};
|
||||
managerActions.forEach((item: ManagerActionItem) => {
|
||||
initialForms[item.id] = {
|
||||
outcome: item.outcome || item.payload?.outcome || item.payload?.['نتیجه_اقدام'] || '',
|
||||
evidence: item.evidence || item.payload?.evidence || item.payload?.['مستندات_و_مدرک'] || '',
|
||||
};
|
||||
});
|
||||
|
||||
setItems(managerActions);
|
||||
setActionForm(initialForms);
|
||||
} else {
|
||||
setError(true);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch manager actions:', err);
|
||||
setError(true);
|
||||
toast.error('خطا در دریافت لیست اقدامات مدیریتی');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchActions();
|
||||
}, []);
|
||||
|
||||
const handleSaveEvidence = async (id: string) => {
|
||||
const form = actionForm[id] || { outcome: '', evidence: '' };
|
||||
if (!form.outcome.trim() || !form.evidence.trim()) {
|
||||
toast.error('برای ثبت اقدام، درج هر دو مورد نتیجه و مدرک/مستندات الزامی است.');
|
||||
return;
|
||||
}
|
||||
|
||||
setSubmittingId(id);
|
||||
try {
|
||||
const res = await api.put(`/admin/approvals/${id}/decide`, {
|
||||
decision: 'APPROVED',
|
||||
outcome: form.outcome.trim(),
|
||||
evidence: form.evidence.trim(),
|
||||
ceoNotes: `اقدام تکمیل شد با نتیجه: ${form.outcome.trim()}`,
|
||||
});
|
||||
|
||||
if (res.data?.success) {
|
||||
toast.success('نتیجه و مستندات اقدام مدیریتی با موفقیت ثبت شد');
|
||||
// Update local item with verified outcome and evidence
|
||||
setItems((prev) =>
|
||||
prev.map((item) =>
|
||||
item.id === id
|
||||
? {
|
||||
...item,
|
||||
status: 'COMPLETED',
|
||||
outcome: form.outcome.trim(),
|
||||
evidence: form.evidence.trim(),
|
||||
}
|
||||
: item
|
||||
)
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to update manager action evidence:', err);
|
||||
toast.error('خطا در ثبت نتیجه و مستندات اقدام');
|
||||
} finally {
|
||||
setSubmittingId(null);
|
||||
}
|
||||
};
|
||||
|
||||
const filteredItems = useMemo(() => {
|
||||
return items.filter((item) => {
|
||||
const isVerified = Boolean(item.outcome?.trim()) && Boolean(item.evidence?.trim());
|
||||
|
||||
if (statusFilter === 'VERIFIED' && !isVerified) return false;
|
||||
if (statusFilter === 'PENDING_EVIDENCE' && isVerified) return false;
|
||||
|
||||
if (searchQuery.trim()) {
|
||||
const q = searchQuery.toLowerCase().trim();
|
||||
const form = actionForm[item.id] || { outcome: '', evidence: '' };
|
||||
const matchTitle = item.title?.toLowerCase().includes(q);
|
||||
const matchDept = item.department?.toLowerCase().includes(q);
|
||||
const matchPayload = JSON.stringify(item.payload || {}).toLowerCase().includes(q);
|
||||
const matchOutcome = (item.outcome || form.outcome)?.toLowerCase().includes(q);
|
||||
if (!matchTitle && !matchDept && !matchPayload && !matchOutcome) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
}, [items, actionForm, statusFilter, searchQuery]);
|
||||
|
||||
const verifiedCount = items.filter(
|
||||
(item) => Boolean(item.outcome?.trim()) && Boolean(item.evidence?.trim())
|
||||
).length;
|
||||
const pendingEvidenceCount = items.length - verifiedCount;
|
||||
|
||||
return (
|
||||
<div className="space-y-6 max-w-7xl mx-auto p-4 md:p-6 font-vazir text-gray-900 bg-gray-50 min-h-screen" dir="rtl">
|
||||
{/* Header */}
|
||||
<div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 bg-white p-6 rounded-3xl border border-gray-200/80 shadow-xs">
|
||||
<div>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-10 h-10 rounded-2xl bg-indigo-100 flex items-center justify-center text-indigo-700 shadow-xs">
|
||||
<Briefcase className="w-6 h-6" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-xl md:text-2xl font-black text-gray-900 tracking-tight">
|
||||
اقدامات مدیریتی و همکاریها (Manager Strategic Actions & Partnerships)
|
||||
</h1>
|
||||
<p className="text-xs text-gray-500 font-medium mt-1 leading-relaxed">
|
||||
طرحهای راهبردی، پروژههای B2B و تامینکنندگان. این موارد مجوز سیستمی نیستند؛ تکمیل اقدام صرفاً با احراز نتیجه و مستندات معتبر صورت میگیرد.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2.5">
|
||||
<Link
|
||||
to="/approvals"
|
||||
className="inline-flex items-center gap-1.5 px-3.5 py-2 rounded-2xl bg-amber-50 hover:bg-amber-100 text-amber-800 text-xs font-bold transition-all border border-amber-300"
|
||||
>
|
||||
<ShieldCheck className="w-4 h-4 text-amber-600" />
|
||||
<span>رفتن به مجوزهای عملیاتی</span>
|
||||
</Link>
|
||||
|
||||
<Link
|
||||
to="/tasks"
|
||||
className="inline-flex items-center gap-1.5 px-3.5 py-2 rounded-2xl bg-purple-50 hover:bg-purple-100 text-purple-700 text-xs font-bold transition-all border border-purple-200"
|
||||
>
|
||||
<Layers className="w-4 h-4 text-purple-600" />
|
||||
<span>مشاهده وظایف دپارتمانها</span>
|
||||
</Link>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={fetchActions}
|
||||
disabled={loading}
|
||||
className="inline-flex items-center gap-1.5 px-3.5 py-2 rounded-2xl bg-gray-100 hover:bg-gray-200 text-gray-700 text-xs font-bold transition-all border border-gray-200 cursor-pointer disabled:opacity-50"
|
||||
>
|
||||
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
|
||||
<span className="hidden sm:inline">تازهسازی</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Governance Directive Banner */}
|
||||
<div className="bg-indigo-50/80 border border-indigo-200 p-4 rounded-2xl flex items-start gap-3">
|
||||
<AlertCircle className="w-5 h-5 text-indigo-700 shrink-0 mt-0.5" />
|
||||
<div className="text-xs text-indigo-950 space-y-1">
|
||||
<p className="font-bold">قانون تفکیک حاکمیتی اقدامات مدیریتی از مجوزهای عملیاتی:</p>
|
||||
<p className="leading-relaxed text-indigo-900">
|
||||
طرحهای استراتژیک تامینکنندگان (B2B_SUPPLIER_STRATEGY) و همکاریهای تجاری، وظایف انسانی و راهبردی هستند که دکمه تایید فوری ندارند. تکمیل این موارد صرفاً با درج صریح نتیجه واقعی (Outcome) و مستندات قابل اعتبارسنجی (Evidence) محقق میشود.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* KPI Cards */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3.5">
|
||||
<div className="bg-white p-4 rounded-2xl border border-gray-200/80 shadow-xs flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-[11px] font-bold text-gray-500">کل اقدامات مدیریتی</p>
|
||||
<p className="text-2xl font-black text-gray-900 mt-1 font-mono">{items.length}</p>
|
||||
</div>
|
||||
<div className="w-10 h-10 rounded-xl bg-indigo-50 text-indigo-700 flex items-center justify-center font-bold">
|
||||
<Building2 className="w-5 h-5" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white p-4 rounded-2xl border border-amber-300 shadow-xs flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-[11px] font-bold text-amber-700">نیازمند ثبت نتیجه و مدرک</p>
|
||||
<p className="text-2xl font-black text-amber-700 mt-1 font-mono">{pendingEvidenceCount}</p>
|
||||
</div>
|
||||
<div className="w-10 h-10 rounded-xl bg-amber-50 text-amber-700 flex items-center justify-center font-bold">
|
||||
<Clock className="w-5 h-5" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white p-4 rounded-2xl border border-emerald-200 shadow-xs flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-[11px] font-bold text-emerald-700">تکمیل و احراز شده با مستندات</p>
|
||||
<p className="text-2xl font-black text-emerald-700 mt-1 font-mono">{verifiedCount}</p>
|
||||
</div>
|
||||
<div className="w-10 h-10 rounded-xl bg-emerald-50 text-emerald-700 flex items-center justify-center font-bold">
|
||||
<CheckCircle2 className="w-5 h-5" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Filters Bar */}
|
||||
<div className="bg-white p-4 rounded-3xl border border-gray-200/80 shadow-xs flex flex-col md:flex-row gap-3 items-center justify-between">
|
||||
<div className="relative w-full md:w-96">
|
||||
<Search className="w-4 h-4 text-gray-400 absolute right-3.5 top-1/2 -translate-y-1/2" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="جستجو در عنوان اقدام، تامینکننده، دپارتمان..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="w-full pr-10 pl-4 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-indigo-500 font-medium text-gray-900"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2 w-full md:w-auto">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setStatusFilter('ALL')}
|
||||
className={`px-3 py-1.5 rounded-xl text-xs font-bold transition-all ${
|
||||
statusFilter === 'ALL'
|
||||
? 'bg-indigo-600 text-white shadow-xs'
|
||||
: 'bg-gray-100 text-gray-600 hover:bg-gray-200'
|
||||
}`}
|
||||
>
|
||||
همه موارد ({items.length})
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setStatusFilter('PENDING_EVIDENCE')}
|
||||
className={`px-3 py-1.5 rounded-xl text-xs font-bold transition-all ${
|
||||
statusFilter === 'PENDING_EVIDENCE'
|
||||
? 'bg-amber-600 text-white shadow-xs'
|
||||
: 'bg-gray-100 text-gray-600 hover:bg-gray-200'
|
||||
}`}
|
||||
>
|
||||
نیازمند نتیجه ({pendingEvidenceCount})
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setStatusFilter('VERIFIED')}
|
||||
className={`px-3 py-1.5 rounded-xl text-xs font-bold transition-all ${
|
||||
statusFilter === 'VERIFIED'
|
||||
? 'bg-emerald-600 text-white shadow-xs'
|
||||
: 'bg-gray-100 text-gray-600 hover:bg-gray-200'
|
||||
}`}
|
||||
>
|
||||
احراز شده ({verifiedCount})
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Main List */}
|
||||
{error ? (
|
||||
<div className="bg-white p-8 rounded-3xl border border-rose-200 text-center space-y-3">
|
||||
<AlertTriangle className="w-12 h-12 text-rose-500 mx-auto" />
|
||||
<h3 className="text-base font-black text-gray-900">دریافت اقدامات ناموفق بود</h3>
|
||||
<p className="text-xs text-gray-500">امکان برقراری ارتباط با سرور و واکشی اقدامات مدیریتی وجود ندارد.</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={fetchActions}
|
||||
className="px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl text-xs font-bold transition-all"
|
||||
>
|
||||
تلاش مجدد
|
||||
</button>
|
||||
</div>
|
||||
) : loading ? (
|
||||
<div className="py-24 flex flex-col justify-center items-center gap-3">
|
||||
<RefreshCw className="w-8 h-8 text-indigo-600 animate-spin" />
|
||||
<span className="text-xs font-bold text-gray-500">در حال دریافت اقدامات مدیریتی...</span>
|
||||
</div>
|
||||
) : filteredItems.length === 0 ? (
|
||||
<div className="bg-white p-12 text-center rounded-3xl border border-gray-200/80 shadow-xs space-y-2">
|
||||
<CheckCircle2 className="w-12 h-12 text-indigo-500 mx-auto mb-2" />
|
||||
<h3 className="text-base font-black text-gray-900">اقدامی در این فهرست یافت نشد</h3>
|
||||
<p className="text-xs text-gray-500">موردی با شرایط فیلتر انتخابشده مطابقت ندارد.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-5">
|
||||
{filteredItems.map((item) => {
|
||||
const form = actionForm[item.id] || { outcome: item.outcome || '', evidence: item.evidence || '' };
|
||||
const isCompleted = Boolean(item.outcome?.trim()) && Boolean(item.evidence?.trim());
|
||||
|
||||
return (
|
||||
<div
|
||||
key={item.id}
|
||||
className={`bg-white rounded-3xl border transition-all overflow-hidden ${
|
||||
isCompleted ? 'border-emerald-200 shadow-xs' : 'border-amber-300 shadow-md ring-1 ring-amber-300/40'
|
||||
}`}
|
||||
>
|
||||
{/* Header */}
|
||||
<div className="p-5 border-b border-gray-100 flex flex-col md:flex-row justify-between items-start md:items-center gap-3 bg-gray-50/60">
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-xl text-[11px] font-black border bg-indigo-50 text-indigo-800 border-indigo-200">
|
||||
<Building2 className="w-3.5 h-3.5 shrink-0" />
|
||||
<span>{item.category === 'B2B_SUPPLIER_STRATEGY' ? 'طرح استراتژیک تامینکننده' : item.category}</span>
|
||||
</span>
|
||||
<div>
|
||||
<h3 className="font-black text-gray-900 text-sm md:text-base leading-snug">
|
||||
{item.title}
|
||||
</h3>
|
||||
<div className="flex items-center gap-2 mt-1 text-[11px] text-gray-500 font-medium">
|
||||
<span>دپارتمان: <strong className="text-gray-800">{item.department}</strong></span>
|
||||
<span>•</span>
|
||||
<span>
|
||||
ثبت: {new Intl.DateTimeFormat('fa-IR', { year: 'numeric', month: '2-digit', day: '2-digit' }).format(new Date(item.createdAt))}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
{isCompleted ? (
|
||||
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-black bg-emerald-50 text-emerald-800 border border-emerald-200">
|
||||
<CheckCircle2 className="w-3.5 h-3.5 text-emerald-600" />
|
||||
<span>تکمیلشده و احراز شده با مستندات</span>
|
||||
</span>
|
||||
) : (
|
||||
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-black bg-amber-50 text-amber-800 border border-amber-300">
|
||||
<Clock className="w-3.5 h-3.5 text-amber-600" />
|
||||
<span>نیازمند ثبت نتیجه و مدرک جهت احراز تکمیل</span>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Body */}
|
||||
<div className="p-5 space-y-4">
|
||||
{/* Strategic 5-Part Proposal Mapping */}
|
||||
{item.payload && (
|
||||
<div className="space-y-2.5">
|
||||
{item.payload['1_مسئله_و_شکاف_بازار'] && (
|
||||
<div className="p-3 bg-rose-50/60 border border-rose-200/80 rounded-xl text-xs">
|
||||
<span className="font-black text-rose-800 block mb-1">مسئله و شکاف بازار:</span>
|
||||
<span className="text-gray-800">{item.payload['1_مسئله_و_شکاف_بازار']}</span>
|
||||
</div>
|
||||
)}
|
||||
{item.payload['2_راهحل_و_مزیت_کنینا'] && (
|
||||
<div className="p-3 bg-emerald-50/60 border border-emerald-200/80 rounded-xl text-xs">
|
||||
<span className="font-black text-emerald-800 block mb-1">راهحل و مزیت کنینا:</span>
|
||||
<span className="text-gray-800">{item.payload['2_راهحل_و_مزیت_کنینا']}</span>
|
||||
</div>
|
||||
)}
|
||||
{item.payload['3_طرح_اقدام_عملیاتی'] && (
|
||||
<div className="p-3 bg-blue-50/60 border border-blue-200/80 rounded-xl text-xs">
|
||||
<span className="font-black text-blue-800 block mb-1">طرح اقدام عملیاتی:</span>
|
||||
<span className="text-gray-800">{item.payload['3_طرح_اقدام_عملیاتی']}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Explicit Outcome & Evidence Section */}
|
||||
<div className="bg-gray-50/90 rounded-2xl p-4 border border-gray-200 space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-xs font-black text-gray-800 flex items-center gap-1.5">
|
||||
<FileText className="w-4 h-4 text-indigo-600" />
|
||||
<span>نتیجه و مدرک تحقق اقدام (Outcome & Evidence)</span>
|
||||
</span>
|
||||
<span className="text-[11px] text-gray-500 font-medium">
|
||||
تکمیل صرفاً با مستندات معتبر احراز میشود
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{isCompleted ? (
|
||||
<div className="space-y-2 text-xs">
|
||||
<div className="p-3 bg-white rounded-xl border border-emerald-200 space-y-1">
|
||||
<span className="text-emerald-800 font-bold block">نتیجه حاصله (Outcome):</span>
|
||||
<p className="text-gray-800 font-medium">{item.outcome}</p>
|
||||
</div>
|
||||
<div className="p-3 bg-white rounded-xl border border-emerald-200 space-y-1">
|
||||
<span className="text-emerald-800 font-bold block">مستندات و مدرک تحقق (Evidence):</span>
|
||||
<p className="text-gray-800 font-medium">{item.evidence}</p>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
<div className="space-y-1">
|
||||
<label className="text-[11px] font-bold text-gray-700 block">
|
||||
نتیجه حاصله از این اقدام مدیریتی (Outcome):
|
||||
</label>
|
||||
<textarea
|
||||
rows={2}
|
||||
placeholder="نتیجه حاصله از این اقدام مدیریتی..."
|
||||
value={form.outcome}
|
||||
onChange={(e) =>
|
||||
setActionForm((prev) => ({
|
||||
...prev,
|
||||
[item.id]: { ...form, outcome: e.target.value },
|
||||
}))
|
||||
}
|
||||
className="w-full p-2.5 text-xs bg-white border border-gray-200 rounded-xl focus:outline-none focus:border-indigo-500 font-medium"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<label className="text-[11px] font-bold text-gray-700 block">
|
||||
مستندات و مدرک تحقق (Evidence):
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="مستندات، شماره سند، لینک گزارش یا فایل..."
|
||||
value={form.evidence}
|
||||
onChange={(e) =>
|
||||
setActionForm((prev) => ({
|
||||
...prev,
|
||||
[item.id]: { ...form, evidence: e.target.value },
|
||||
}))
|
||||
}
|
||||
className="w-full p-2.5 text-xs bg-white border border-gray-200 rounded-xl focus:outline-none focus:border-indigo-500 font-medium"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end pt-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleSaveEvidence(item.id)}
|
||||
disabled={submittingId === item.id || !form.outcome.trim() || !form.evidence.trim()}
|
||||
className="inline-flex items-center gap-1.5 px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl text-xs font-black shadow-xs transition-all disabled:opacity-50 cursor-pointer"
|
||||
>
|
||||
<Send className="w-3.5 h-3.5" />
|
||||
<span>{submittingId === item.id ? 'در حال ثبت...' : 'ثبت نتیجه و مستندات اقدام'}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,15 +1,15 @@
|
||||
import {
|
||||
Activity,
|
||||
CheckCircle2,
|
||||
Clock,
|
||||
CreditCard,
|
||||
Database,
|
||||
FileText,
|
||||
MessageSquare,
|
||||
RefreshCw,
|
||||
Truck
|
||||
Activity,
|
||||
CheckCircle2,
|
||||
Clock,
|
||||
CreditCard,
|
||||
Database,
|
||||
FileText,
|
||||
MessageSquare,
|
||||
RefreshCw,
|
||||
Truck
|
||||
} from 'lucide-react';
|
||||
import { useCallback,useEffect,useState } from 'react';
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import Badge from '../components/ui/Badge';
|
||||
import Button from '../components/ui/Button';
|
||||
|
||||
@@ -1,31 +1,15 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import ApprovalsPage from './ApprovalsPage';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import routes from '../routes/adminRoutes.tsx?raw';
|
||||
|
||||
vi.mock('../services/api', () => ({ default: { get: vi.fn(), post: vi.fn(), put: vi.fn() } }));
|
||||
vi.mock('react-hot-toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));
|
||||
|
||||
const item = (id: string, category: string, status = 'PENDING') => ({
|
||||
id, category, status, department: category === 'SEO' ? 'SEO' : 'B2B',
|
||||
title: id, payload: {}, createdAt: '2026-10-19T10:00:00Z',
|
||||
});
|
||||
const pages = import.meta.glob('./*.tsx');
|
||||
|
||||
// Approvals and manager actions were removed in effe30e. Keep this boundary
|
||||
// covered without importing the deleted page or restoring its obsolete UI.
|
||||
describe('operational authorization boundary', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(api.get).mockResolvedValue({ data: {
|
||||
success: true,
|
||||
data: [item('supplier-action', 'B2B_SUPPLIER_STRATEGY'), item('seo-approval', 'SEO')],
|
||||
meta: { pendingCount: 2 },
|
||||
} });
|
||||
});
|
||||
|
||||
it('does not expose a supplier manager action as authorization while SEO remains', async () => {
|
||||
render(<ApprovalsPage />);
|
||||
expect(await screen.findByText('seo-approval')).toBeInTheDocument();
|
||||
expect(screen.queryByText('supplier-action')).not.toBeInTheDocument();
|
||||
expect(screen.getAllByRole('button', { name: /تایید و صدور مجوز اجرا/ })).toHaveLength(1);
|
||||
expect(screen.getByText(/1 پیشنهاد منتظر تصمیم شما/)).toBeInTheDocument();
|
||||
it('does not register removed approvals or manager-action pages', () => {
|
||||
expect(routes).not.toMatch(/ApprovalsPage|ManagerActionsPage/);
|
||||
expect(routes).not.toMatch(/path:\s*['"](?:approvals|manager-actions)(?:\/\*)?['"]/);
|
||||
expect(pages).not.toHaveProperty('./ApprovalsPage.tsx');
|
||||
expect(pages).not.toHaveProperty('./ManagerActionsPage.tsx');
|
||||
});
|
||||
});
|
||||
@@ -37,6 +37,7 @@ export interface OrderItem {
|
||||
priceValue?: number;
|
||||
quantity?: number;
|
||||
product?: {
|
||||
requiresRx?: boolean;
|
||||
id?: string;
|
||||
nameFa?: string;
|
||||
name?: string;
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import { beforeEach, expect, it, vi } from "vitest";
|
||||
import api from "../services/api";
|
||||
import SymptomsPage from "./SymptomsPage";
|
||||
vi.mock("../services/api", () => ({default: {get: vi.fn(), delete: vi.fn()}}));
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.mocked(api.get).mockResolvedValue({data: {data: [{id:"symptom-1", name:"Anemia", slug:"anemia"}], meta:{lastPage:1}}});
|
||||
vi.mocked(api.delete).mockResolvedValue({data:{}});
|
||||
});
|
||||
it("shows deletion consequences and cancels without deleting, then confirms the selected symptom", async () => {
|
||||
render(<MemoryRouter><SymptomsPage/></MemoryRouter>);
|
||||
await screen.findByText("Anemia");
|
||||
fireEvent.click(screen.getByTitle("حذف"));
|
||||
expect(screen.getByText(/با حذف این علامت، ارتباط آن/)).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("button",{name:"لغو"}));
|
||||
expect(screen.queryByText(/با حذف این علامت، ارتباط آن/)).not.toBeInTheDocument();
|
||||
expect(api.delete).not.toHaveBeenCalled();
|
||||
fireEvent.click(screen.getByTitle("حذف"));
|
||||
fireEvent.click(screen.getByRole("button",{name:"تایید"}));
|
||||
await waitFor(() => expect(api.delete).toHaveBeenCalledWith("/admin/symptoms/symptom-1"));
|
||||
await waitFor(() => expect(screen.queryByText(/با حذف این علامت، ارتباط آن/)).not.toBeInTheDocument());
|
||||
});
|
||||
@@ -22,7 +22,7 @@ export interface Symptom {
|
||||
}
|
||||
|
||||
export default function SymptomsPage() {
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const [searchParams] = useSearchParams();
|
||||
const [symptoms, setSymptoms] = useState<Symptom[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [search, setSearch] = useState(() => searchParams.get('search') || '');
|
||||
@@ -311,10 +311,10 @@ export default function SymptomsPage() {
|
||||
{/* Delete Confirmation */}
|
||||
<ConfirmModal
|
||||
isOpen={!!deleteTargetId}
|
||||
onClose={() => setDeleteTargetId(null)}
|
||||
onCancel={() => setDeleteTargetId(null)}
|
||||
onConfirm={handleDelete}
|
||||
title="حذف علامت بالینی"
|
||||
description="با حذف این علامت، ارتباط آن از تمام محصولات کاتالوگ نیز به طور خودکار حذف خواهد شد. آیا مطمئن هستید؟"
|
||||
message="با حذف این علامت، ارتباط آن از تمام محصولات کاتالوگ نیز به طور خودکار حذف خواهد شد. آیا مطمئن هستید؟"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,606 +0,0 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import {
|
||||
Search,
|
||||
RefreshCw,
|
||||
Bot,
|
||||
Briefcase,
|
||||
ChevronDown,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
Play,
|
||||
CheckCircle,
|
||||
Clock,
|
||||
Filter
|
||||
} from 'lucide-react';
|
||||
import api from '../services/api';
|
||||
import toast from 'react-hot-toast';
|
||||
|
||||
interface DepartmentTask {
|
||||
id: string;
|
||||
code: string;
|
||||
department: string;
|
||||
title: string;
|
||||
description?: string;
|
||||
status: string;
|
||||
priority: string;
|
||||
assignee: string;
|
||||
acceptanceCriteria?: any;
|
||||
executionLogs?: any;
|
||||
deliverableUrl?: string;
|
||||
startedAt?: string;
|
||||
completedAt?: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export default function TasksManagementPage() {
|
||||
const [tasks, setTasks] = useState<DepartmentTask[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
const [sortOrder, setSortOrder] = useState<'desc' | 'asc'>('desc');
|
||||
const [selectedDept, setSelectedDept] = useState('ALL');
|
||||
const [selectedStatus, setSelectedStatus] = useState('ALL');
|
||||
const [selectedPriority, setSelectedPriority] = useState('ALL');
|
||||
const [activeTaskModal, setActiveTaskModal] = useState<DepartmentTask | null>(null);
|
||||
const [logNote, setLogNote] = useState('');
|
||||
const [updating, setUpdating] = useState(false);
|
||||
|
||||
// Pagination states
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const itemsPerPage = 10;
|
||||
|
||||
const fetchTasks = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await api.get('/admin/department-tasks?limit=200');
|
||||
if (res.data?.success) {
|
||||
setTasks(res.data.data);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error fetching tasks:', err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchTasks();
|
||||
}, []);
|
||||
|
||||
const handleStatusChange = async (taskId: string, newStatus: string) => {
|
||||
setUpdating(true);
|
||||
try {
|
||||
const res = await api.put(`/admin/department-tasks/${taskId}/status`, {
|
||||
status: newStatus,
|
||||
logNote: logNote || `تغییر وضعیت به ${newStatus}`,
|
||||
});
|
||||
if (res.data?.success) {
|
||||
toast.success(`وضعیت تسک به ${newStatus} بهروزرسانی شد`);
|
||||
setLogNote('');
|
||||
setActiveTaskModal(null);
|
||||
fetchTasks();
|
||||
}
|
||||
} catch (err) {
|
||||
toast.error('خطا در بهروزرسانی وضعیت تسک');
|
||||
} finally {
|
||||
setUpdating(false);
|
||||
}
|
||||
};
|
||||
|
||||
const sortedTasks = [...tasks].sort((a, b) => {
|
||||
const tA = new Date(a.createdAt || 0).getTime();
|
||||
const tB = new Date(b.createdAt || 0).getTime();
|
||||
return sortOrder === 'desc' ? tB - tA : tA - tB;
|
||||
});
|
||||
const filteredTasks = sortedTasks.filter((t) => {
|
||||
const matchesSearch =
|
||||
!searchTerm ||
|
||||
t.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
t.code.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
(t.description && t.description.toLowerCase().includes(searchTerm.toLowerCase()));
|
||||
|
||||
const matchesDept = selectedDept === 'ALL' || t.department === selectedDept;
|
||||
const matchesStatus = selectedStatus === 'ALL' || t.status === selectedStatus;
|
||||
const matchesPriority = selectedPriority === 'ALL' || t.priority === selectedPriority;
|
||||
|
||||
return matchesSearch && matchesDept && matchesStatus && matchesPriority;
|
||||
});
|
||||
|
||||
// Calculate pagination
|
||||
const totalPages = Math.ceil(filteredTasks.length / itemsPerPage) || 1;
|
||||
const paginatedTasks = filteredTasks.slice(
|
||||
(currentPage - 1) * itemsPerPage,
|
||||
currentPage * itemsPerPage
|
||||
);
|
||||
|
||||
const getStatusBadge = (status: string) => {
|
||||
switch (status) {
|
||||
case 'TODO':
|
||||
case 'BACKLOG':
|
||||
return (
|
||||
<span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-gray-100 text-gray-700 border border-gray-200">
|
||||
۱. صف اقدام (TODO)
|
||||
</span>
|
||||
);
|
||||
case 'IN_PROGRESS':
|
||||
return (
|
||||
<span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-blue-100 text-blue-800 border border-blue-200 animate-pulse">
|
||||
۲. در حال توسعه (IN_PROGRESS)
|
||||
</span>
|
||||
);
|
||||
case 'TEST':
|
||||
case 'IN_REVIEW':
|
||||
return (
|
||||
<span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-amber-100 text-amber-800 border border-amber-200">
|
||||
۳. تست استیج و QA (TEST)
|
||||
</span>
|
||||
);
|
||||
case 'WAITING_DEPENDENCIES':
|
||||
return (
|
||||
<span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-violet-100 text-violet-800 border border-violet-200">
|
||||
۳. منتظر تکمیل اقدامات وابسته
|
||||
</span>
|
||||
);
|
||||
case 'DONE':
|
||||
return (
|
||||
<span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-emerald-100 text-emerald-800 border border-emerald-200">
|
||||
۴. خروجی راستیآزماییشده (DONE)
|
||||
</span>
|
||||
);
|
||||
case 'REJECTED':
|
||||
return (
|
||||
<span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-rose-100 text-rose-800 border border-rose-200">
|
||||
رد شده (REJECTED)
|
||||
</span>
|
||||
);
|
||||
default:
|
||||
return <span>{status}</span>;
|
||||
}
|
||||
};
|
||||
|
||||
const getStatusTransitionsSummary = (logsRaw: any) => {
|
||||
const list = Array.isArray(logsRaw) ? logsRaw : (typeof logsRaw === 'object' && logsRaw ? [logsRaw] : []);
|
||||
let inProgressCount = 0;
|
||||
let testCount = 0;
|
||||
let qaRejectedCount = 0;
|
||||
let qaPassedCount = 0;
|
||||
|
||||
list.forEach((entry: any) => {
|
||||
const st = String(entry?.status || '');
|
||||
if (st.includes('STARTED') || st === 'IN_PROGRESS') inProgressCount += 1;
|
||||
if (st.includes('COMPLETED') || st === 'TEST') testCount += 1;
|
||||
if (st === 'QA_FAILED') qaRejectedCount += 1;
|
||||
if (st === 'QA_PASSED') qaPassedCount += 1;
|
||||
});
|
||||
|
||||
return { inProgressCount, testCount, qaRejectedCount, qaPassedCount, totalEvents: list.length };
|
||||
};
|
||||
|
||||
const getPriorityBadge = (priority: string) => {
|
||||
switch (priority) {
|
||||
case 'CEO_EXPEDITE':
|
||||
return <span className="px-1.5 py-0.5 text-[9px] font-black bg-purple-700 text-white rounded animate-pulse shadow-sm shadow-purple-300">⚡ فوری مدیرعامل</span>;
|
||||
case 'CRITICAL':
|
||||
return <span className="px-1.5 py-0.5 text-[9px] font-black bg-rose-600 text-white rounded">فوری / بحرانی</span>;
|
||||
case 'HIGH':
|
||||
return <span className="px-1.5 py-0.5 text-[9px] font-black bg-rose-100 text-rose-700 rounded border border-rose-200">بالا</span>;
|
||||
case 'MEDIUM':
|
||||
return <span className="px-1.5 py-0.5 text-[9px] font-black bg-amber-100 text-amber-700 rounded border border-amber-200">متوسط</span>;
|
||||
default:
|
||||
return <span className="px-1.5 py-0.5 text-[9px] font-black bg-gray-100 text-gray-600 rounded">عادی</span>;
|
||||
}
|
||||
};
|
||||
|
||||
const getDeptName = (dept: string) => {
|
||||
const map: Record<string, string> = {
|
||||
DEV: 'مهندسی و توسعه',
|
||||
COMMERCE: 'بازرگانی و مالی',
|
||||
PRODUCT: 'کاتالوگ و انبار',
|
||||
CONTENT: 'تولید محتوا و سئو',
|
||||
SEO: 'رشد و مارکتینگ',
|
||||
CRM: 'ارتباط با مشتریان',
|
||||
PMO: 'مدیریت و استراتژی',
|
||||
};
|
||||
return map[dept] || dept;
|
||||
};
|
||||
|
||||
const renderAcceptanceCriteria = (criteria: any) => {
|
||||
if (!criteria) return null;
|
||||
if (typeof criteria === 'string') return criteria;
|
||||
if (typeof criteria === 'object') {
|
||||
if (criteria.rule) return criteria.rule;
|
||||
try {
|
||||
return JSON.stringify(criteria, null, 2);
|
||||
} catch (e) {
|
||||
return String(criteria);
|
||||
}
|
||||
}
|
||||
return String(criteria);
|
||||
};
|
||||
|
||||
const renderExecutionLogs = (logs: any) => {
|
||||
if (!logs) return [];
|
||||
if (Array.isArray(logs)) return logs;
|
||||
if (typeof logs === 'object') {
|
||||
return [
|
||||
{
|
||||
note: logs.notes || logs.message || JSON.stringify(logs),
|
||||
timestamp: new Date().toISOString(),
|
||||
status: logs.status || 'LOG',
|
||||
},
|
||||
];
|
||||
}
|
||||
return [{ note: String(logs), timestamp: new Date().toISOString(), status: 'LOG' }];
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6 font-vazir pb-12" dir="rtl">
|
||||
{/* Top Header */}
|
||||
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4 bg-white p-6 rounded-2xl border border-gray-100 shadow-sm">
|
||||
<div>
|
||||
<div className="flex items-center gap-3 mb-1">
|
||||
<div className="w-10 h-10 rounded-xl bg-purple-100 flex items-center justify-center text-purple-700">
|
||||
<Briefcase className="w-5 h-5" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-xl font-black text-gray-900">مدیریت تسکهای دپارتمانها و ایجنتها (Task Manager)</h1>
|
||||
<p className="text-xs text-gray-500 font-medium">پایش لحظهای فعالیتهای خودکار، استیت تسکها و تضمین کیفیت تحویل</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={fetchTasks}
|
||||
disabled={loading}
|
||||
className="inline-flex items-center gap-2 px-4 py-2.5 rounded-xl bg-purple-50 text-purple-700 text-xs font-bold hover:bg-purple-100 transition-colors border border-purple-200 cursor-pointer disabled:opacity-50"
|
||||
>
|
||||
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
|
||||
<span>بهروزرسانی وظایف</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Filter and Search Bar */}
|
||||
<div className="bg-white p-4 rounded-2xl border border-gray-100 shadow-sm space-y-4">
|
||||
<div className="grid grid-cols-1 md:grid-cols-4 gap-3">
|
||||
<div className="relative">
|
||||
<Search className="w-4 h-4 absolute right-3 top-3 text-gray-400" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="جستجو بر اساس عنوان تسک، کد..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => {
|
||||
setSearchTerm(e.target.value);
|
||||
setCurrentPage(1);
|
||||
}}
|
||||
className="w-full pr-9 pl-3 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500 font-medium"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<select
|
||||
value={selectedDept}
|
||||
onChange={(e) => {
|
||||
setSelectedDept(e.target.value);
|
||||
setCurrentPage(1);
|
||||
}}
|
||||
className="w-full px-3 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500 font-bold text-gray-700"
|
||||
>
|
||||
<option value="ALL">همه دپارتمانها</option>
|
||||
<option value="DEV">مهندسی و توسعه (DEV)</option>
|
||||
<option value="DEVOPS">زیرساخت و سرور (DEVOPS)</option>
|
||||
<option value="SEO">سئو و مارکتپلیس (SEO)</option>
|
||||
<option value="CONTENT">محتوا و وبلاگ (CONTENT)</option>
|
||||
<option value="CLINICAL_RD">تحقیق و توسعه بالینی (CLINICAL_RD)</option>
|
||||
<option value="B2B">بازرگانی و توسعه کلینیکها (B2B)</option>
|
||||
<option value="SUPPORT">پشتیبانی مشتریان و CRM (SUPPORT)</option>
|
||||
<option value="QA">تضمین کیفیت و تست (QA)</option>
|
||||
<option value="COMMERCE">بازرگانی و مالی (COMMERCE)</option>
|
||||
<option value="PRODUCT">کاتالوگ و استوک (PRODUCT)</option>
|
||||
<option value="PMO">مدیریت محصول و ارکستراسیون (PMO)</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<select
|
||||
value={selectedStatus}
|
||||
onChange={(e) => {
|
||||
setSelectedStatus(e.target.value);
|
||||
setCurrentPage(1);
|
||||
}}
|
||||
className="w-full px-3 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500 font-bold text-gray-700"
|
||||
>
|
||||
<option value="ALL">همه وضعیتها</option>
|
||||
<option value="TODO">۱. صف اقدام (TODO)</option>
|
||||
<option value="IN_PROGRESS">۲. در حال اجرا (IN_PROGRESS)</option>
|
||||
<option value="TEST">۳. تست استیج و QA (TEST)</option>
|
||||
<option value="WAITING_DEPENDENCIES">۴. منتظر اقدامات وابسته (WAITING_DEPENDENCIES)</option>
|
||||
<option value="DONE">۵. تکمیل و راستیآزماییشده (DONE)</option>
|
||||
<option value="REJECTED">۶. رد شده (REJECTED)</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<select
|
||||
value={selectedPriority}
|
||||
onChange={(e) => {
|
||||
setSelectedPriority(e.target.value);
|
||||
setCurrentPage(1);
|
||||
}}
|
||||
className="w-full px-3 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500 font-bold text-gray-700"
|
||||
>
|
||||
<option value="ALL">همه اولویتها</option>
|
||||
<option value="CEO_EXPEDITE">⚡ فوری مدیرعامل (CEO_EXPEDITE)</option>
|
||||
<option value="CRITICAL">بحرانی / فوری</option>
|
||||
<option value="HIGH">بالا</option>
|
||||
<option value="MEDIUM">متوسط</option>
|
||||
<option value="LOW">عادی</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Task List Table */}
|
||||
<div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
|
||||
{loading ? (
|
||||
<div className="p-12 text-center text-gray-500 font-bold text-sm">
|
||||
<RefreshCw className="w-6 h-6 animate-spin mx-auto mb-2 text-purple-600" />
|
||||
در حال بارگذاری لیست تسکها...
|
||||
</div>
|
||||
) : filteredTasks.length === 0 ? (
|
||||
<div className="p-12 text-center text-gray-400 font-bold text-sm">
|
||||
هیچ تسکی با این مشخصات یافت نشد.
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-right text-xs">
|
||||
<thead className="bg-gray-50/75 border-b border-gray-100 text-gray-500 font-black">
|
||||
<tr>
|
||||
<th className="py-3 px-4">کد تسک</th>
|
||||
<th className="py-3 px-4 cursor-pointer select-none hover:text-purple-700" onClick={() => setSortOrder(prev => prev === 'desc' ? 'asc' : 'desc')}>
|
||||
<div className="flex items-center gap-1">
|
||||
<span>تاریخ و ساعت (تهران)</span>
|
||||
<span className="text-[10px] text-purple-600">({sortOrder === 'desc' ? '▼ جدیدترین' : '▲ قدیمیترین'})</span>
|
||||
</div>
|
||||
</th>
|
||||
<th className="py-3 px-4">عنوان و شرح وظیفه</th>
|
||||
<th className="py-3 px-4">دپارتمان</th>
|
||||
<th className="py-3 px-4">اولویت</th>
|
||||
<th className="py-3 px-4">مسئول اجرا (Agent)</th>
|
||||
<th className="py-3 px-4">وضعیت</th>
|
||||
<th className="py-3 px-4 text-center">اقدام و تغییر استیت</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-100 font-medium text-gray-700">
|
||||
{paginatedTasks.map((task) => (
|
||||
<tr key={task.id} className="hover:bg-purple-50/20 transition-colors">
|
||||
<td className="py-3.5 px-4 whitespace-nowrap">
|
||||
<span className="font-mono font-bold text-gray-500 bg-gray-100 px-2 py-1 rounded">
|
||||
{task.code}
|
||||
</span>
|
||||
</td>
|
||||
<td className="py-3.5 px-4 whitespace-nowrap text-xs text-gray-600 font-medium" dir="ltr">
|
||||
{task.createdAt ? new Intl.DateTimeFormat('fa-IR', {
|
||||
timeZone: 'Asia/Tehran',
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
}).format(new Date(task.createdAt)) : '-'}
|
||||
</td>
|
||||
<td className="py-3.5 px-4">
|
||||
<div className="font-black text-gray-900 text-xs mb-0.5">{task.title}</div>
|
||||
{task.description && (
|
||||
<div className="text-[11px] text-gray-500 line-clamp-1 max-w-sm">{task.description}</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="py-3.5 px-4 whitespace-nowrap">
|
||||
<span className="text-[11px] font-bold text-purple-700 bg-purple-50 px-2.5 py-0.5 rounded-md border border-purple-100">
|
||||
{getDeptName(task.department)}
|
||||
</span>
|
||||
</td>
|
||||
<td className="py-3.5 px-4 whitespace-nowrap">
|
||||
{getPriorityBadge(task.priority)}
|
||||
</td>
|
||||
<td className="py-3.5 px-4 whitespace-nowrap">
|
||||
<div className="flex items-center gap-1.5 font-bold text-gray-800">
|
||||
<Bot className="w-4 h-4 text-indigo-600" />
|
||||
<span>{task.assignee}</span>
|
||||
</div>
|
||||
</td>
|
||||
<td className="py-3.5 px-4 whitespace-nowrap">
|
||||
{getStatusBadge(task.status)}
|
||||
</td>
|
||||
<td className="py-3.5 px-4 text-center whitespace-nowrap">
|
||||
<button
|
||||
onClick={() => setActiveTaskModal(task)}
|
||||
className="inline-flex items-center gap-1 px-3 py-1.5 rounded-xl bg-purple-600 text-white font-bold text-[11px] hover:bg-purple-700 transition-colors shadow-sm cursor-pointer"
|
||||
>
|
||||
<span>مدیریت و استیت</span>
|
||||
<ChevronDown className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{/* Pagination Controls */}
|
||||
<div className="p-4 border-t border-gray-100 flex items-center justify-between text-xs">
|
||||
<span className="text-gray-500 font-medium">
|
||||
نمایش {(currentPage - 1) * itemsPerPage + 1} تا {Math.min(currentPage * itemsPerPage, filteredTasks.length)} از کل {filteredTasks.length} تسک
|
||||
</span>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
|
||||
disabled={currentPage === 1}
|
||||
className="p-1.5 rounded-lg border border-gray-200 text-gray-600 hover:bg-gray-50 disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer"
|
||||
>
|
||||
<ChevronRight className="w-4 h-4" />
|
||||
</button>
|
||||
|
||||
<div className="flex items-center gap-1">
|
||||
{Array.from({ length: totalPages }).map((_, i) => (
|
||||
<button
|
||||
key={i}
|
||||
onClick={() => setCurrentPage(i + 1)}
|
||||
className={`w-7 h-7 rounded-lg text-xs font-bold transition-colors cursor-pointer ${
|
||||
currentPage === i + 1
|
||||
? 'bg-purple-600 text-white shadow-sm'
|
||||
: 'text-gray-600 hover:bg-gray-100'
|
||||
}`}
|
||||
>
|
||||
{i + 1}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
|
||||
disabled={currentPage === totalPages}
|
||||
className="p-1.5 rounded-lg border border-gray-200 text-gray-600 hover:bg-gray-50 disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer"
|
||||
>
|
||||
<ChevronLeft className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Task Modal for Status Updates */}
|
||||
{activeTaskModal && (
|
||||
<div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4 backdrop-blur-sm animate-in fade-in duration-150">
|
||||
<div className="bg-white rounded-2xl max-w-xl w-full p-6 space-y-4 shadow-2xl border border-gray-100 max-h-[90vh] overflow-y-auto">
|
||||
<div className="flex items-center justify-between border-b border-gray-100 pb-3">
|
||||
<div>
|
||||
<span className="text-[11px] font-mono text-purple-600 font-bold">{activeTaskModal.code}</span>
|
||||
<h3 className="font-black text-sm text-gray-900">{activeTaskModal.title}</h3>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setActiveTaskModal(null)}
|
||||
className="text-gray-400 hover:text-gray-600 font-bold text-sm cursor-pointer"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="text-xs space-y-3">
|
||||
<div className="p-3 bg-gray-50 rounded-xl space-y-1">
|
||||
<div className="font-bold text-gray-500">شرح کامل وظیفه:</div>
|
||||
<div className="text-gray-800 font-medium leading-relaxed">{activeTaskModal.description || 'توضیحی ثبت نشده است.'}</div>
|
||||
</div>
|
||||
|
||||
{activeTaskModal.acceptanceCriteria && (
|
||||
<div className="p-3 bg-indigo-50/50 rounded-xl space-y-1 border border-indigo-100">
|
||||
<div className="font-bold text-indigo-900">معیارهای پذیرش (Acceptance Criteria):</div>
|
||||
<div className="text-indigo-800 font-medium whitespace-pre-wrap">
|
||||
{renderAcceptanceCriteria(activeTaskModal.acceptanceCriteria)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Status Update Options */}
|
||||
<div className="pt-2">
|
||||
<label className="block text-xs font-black text-gray-700 mb-2">تغییر وضعیت تسک به:</label>
|
||||
<div className="grid grid-cols-3 sm:grid-cols-6 gap-2">
|
||||
{['TODO', 'IN_PROGRESS', 'TEST', 'WAITING_DEPENDENCIES', 'DONE', 'REJECTED'].map((st) => (
|
||||
<button
|
||||
key={st}
|
||||
type="button"
|
||||
onClick={() => handleStatusChange(activeTaskModal.id, st)}
|
||||
disabled={updating || activeTaskModal.status === st}
|
||||
className={`py-2 px-2 text-[11px] font-bold rounded-xl border text-center transition-all cursor-pointer ${
|
||||
activeTaskModal.status === st
|
||||
? 'bg-purple-600 text-white border-purple-600 shadow-sm'
|
||||
: 'bg-white hover:bg-gray-50 text-gray-700 border-gray-200'
|
||||
}`}
|
||||
>
|
||||
{st}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="pt-2">
|
||||
<label className="block text-xs font-bold text-gray-700 mb-1">یادداشت برای تاریخچه لاگ (اختیاری):</label>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="مثال: تستها پاس شد و کاتالوگ بهروز گردید..."
|
||||
value={logNote}
|
||||
onChange={(e) => setLogNote(e.target.value)}
|
||||
className="w-full px-3 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500 font-medium"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Status History & Transitions Summary */}
|
||||
{activeTaskModal.executionLogs && (() => {
|
||||
const summary = getStatusTransitionsSummary(activeTaskModal.executionLogs);
|
||||
return (
|
||||
<div className="p-3 bg-purple-50/50 rounded-2xl border border-purple-100 space-y-2">
|
||||
<div className="font-bold text-purple-900 text-[11px] flex items-center justify-between">
|
||||
<span>آمار چرخهها و وضعیتهای طیشده تسک:</span>
|
||||
<span className="font-mono text-[10px] text-purple-700 bg-white px-2 py-0.5 rounded-full border border-purple-200">
|
||||
{summary.totalEvents} رکورد ثبتی
|
||||
</span>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
|
||||
<div className="bg-white p-2 rounded-xl border border-blue-100 text-center shadow-xs">
|
||||
<span className="block text-[10px] text-gray-500 font-bold">دفعات ارجاع به اجرا</span>
|
||||
<span className="text-xs font-black text-blue-700 font-mono">{summary.inProgressCount} بار</span>
|
||||
</div>
|
||||
<div className="bg-white p-2 rounded-xl border border-amber-100 text-center shadow-xs">
|
||||
<span className="block text-[10px] text-gray-500 font-bold">بررسی تست و QA</span>
|
||||
<span className="text-xs font-black text-amber-700 font-mono">{summary.testCount} بار</span>
|
||||
</div>
|
||||
<div className="bg-white p-2 rounded-xl border border-rose-100 text-center shadow-xs">
|
||||
<span className="block text-[10px] text-gray-500 font-bold">عدم تایید QA</span>
|
||||
<span className="text-xs font-black text-rose-700 font-mono">{summary.qaRejectedCount} بار</span>
|
||||
</div>
|
||||
<div className="bg-white p-2 rounded-xl border border-emerald-100 text-center shadow-xs">
|
||||
<span className="block text-[10px] text-gray-500 font-bold">تاییدیه کیفی</span>
|
||||
<span className="text-xs font-black text-emerald-700">{summary.qaPassedCount > 0 ? 'دارد (تایید)' : 'در جریان'}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
|
||||
{/* Execution Logs Timeline */}
|
||||
{activeTaskModal.executionLogs && (
|
||||
<div className="pt-2 space-y-1.5">
|
||||
<div className="font-bold text-gray-600 text-[11px] flex items-center justify-between">
|
||||
<span>تایملاین رویدادها و تغییر وضعیتها:</span>
|
||||
<span className="text-[10px] text-gray-400">(به وقت تهران)</span>
|
||||
</div>
|
||||
<div className="space-y-1.5 max-h-48 overflow-y-auto p-1">
|
||||
{renderExecutionLogs(activeTaskModal.executionLogs).map((lg: any, i: number) => (
|
||||
<div key={i} className="text-[10px] p-2.5 bg-gray-50 hover:bg-gray-100/70 rounded-xl flex items-start justify-between gap-3 border border-gray-100 transition-colors">
|
||||
<span className="font-bold text-gray-800 leading-relaxed text-right flex-1">{lg.note || JSON.stringify(lg)}</span>
|
||||
<span className="text-gray-400 font-mono text-[9px] whitespace-nowrap dir-ltr pt-0.5">
|
||||
{lg.timestamp ? new Date(lg.timestamp).toLocaleString('fa-IR', { hour: '2-digit', minute: '2-digit', second: '2-digit', day: '2-digit', month: '2-digit' }) : '-'}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="pt-3 border-t border-gray-100 flex justify-end">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setActiveTaskModal(null)}
|
||||
className="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-xl text-xs font-bold transition-colors cursor-pointer"
|
||||
>
|
||||
انصراف
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -4,6 +4,46 @@ import { MemoryRouter } from 'react-router-dom';
|
||||
import { beforeEach,describe,expect,it,vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import Users from './Users';
|
||||
import { useAdminAuthStore } from '../store/adminAuthStore';
|
||||
|
||||
vi.mock('../store/adminAuthStore', () => ({ useAdminAuthStore: vi.fn() }));
|
||||
|
||||
describe('Users superadmin editor', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(useAdminAuthStore).mockReturnValue('SUPER_ADMIN');
|
||||
vi.mocked(api.get).mockResolvedValue({ data: { data: [{ id: 'owner-fixture', firstName: 'Owner', role: 'SUPER_ADMIN' }], meta: { total: 1 } } });
|
||||
vi.mocked(api.put).mockResolvedValue({ data: { success: true } });
|
||||
});
|
||||
it.each(['SUPER_ADMIN', 'ADMIN', 'Admin', 'User_Vet'])('preserves exact %s role on password-only save', async (role) => {
|
||||
vi.mocked(api.get).mockResolvedValue({ data: { data: [{ id: 'owner-fixture', firstName: 'Owner', role }], meta: { total: 1 } } });
|
||||
render(<MemoryRouter><Users /></MemoryRouter>);
|
||||
fireEvent.click((await screen.findAllByTitle('ویرایش مشخصات'))[0]);
|
||||
const select = screen.getAllByRole('combobox')[1];
|
||||
expect(select).toHaveValue(role);
|
||||
expect(screen.getAllByRole('option', { name: /مدیر ارشد/ }).length).toBeGreaterThan(0);
|
||||
fireEvent.change(document.querySelector('input[type="password"]')!, { target: { value: 'Fixture-only-123' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: 'ذخیره تغییرات' }));
|
||||
await waitFor(() => expect(api.put).toHaveBeenCalled());
|
||||
const payload = vi.mocked(api.put).mock.calls[0][1] as Record<string, unknown>;
|
||||
expect(payload).not.toHaveProperty('role');
|
||||
});
|
||||
it('submits explicit superadmin promotion for authorized actor', async () => {
|
||||
vi.mocked(api.get).mockResolvedValue({ data: { data: [{ id: 'ordinary-fixture', role: 'Admin' }], meta: { total: 1 } } });
|
||||
render(<MemoryRouter><Users /></MemoryRouter>);
|
||||
fireEvent.click((await screen.findAllByTitle('ویرایش مشخصات'))[0]);
|
||||
fireEvent.change(screen.getAllByRole('combobox')[1], { target: { value: 'SUPER_ADMIN' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: 'ذخیره تغییرات' }));
|
||||
await waitFor(() => expect(api.put).toHaveBeenCalledWith('/admin/users/ordinary-fixture', expect.objectContaining({ role: 'SUPER_ADMIN' })));
|
||||
});
|
||||
it('does not offer superadmin promotion to ordinary admin', async () => {
|
||||
vi.mocked(useAdminAuthStore).mockReturnValue('Admin');
|
||||
render(<MemoryRouter><Users /></MemoryRouter>);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'افزودن کاربر جدید' }));
|
||||
const select = screen.getAllByRole('combobox')[1];
|
||||
expect(select.querySelector('option[value="SUPER_ADMIN"]')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
vi.mock('../services/api', () => ({
|
||||
default: {
|
||||
@@ -57,9 +97,9 @@ describe('Users Page', () => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(api.get).mockResolvedValue({
|
||||
data: {
|
||||
success: true,
|
||||
// Actual GET /admin/users contract: no success envelope.
|
||||
data: mockUsers,
|
||||
meta: { lastPage: 2, total: 2 },
|
||||
meta: { lastPage: 2, total: 2, page: 1, limit: 10 },
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -260,9 +300,8 @@ describe('Users Page', () => {
|
||||
it('renders empty table state when no users are returned', async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({
|
||||
data: {
|
||||
success: true,
|
||||
data: [],
|
||||
meta: { lastPage: 1, total: 0 },
|
||||
meta: { lastPage: 1, total: 0, page: 1, limit: 10 },
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ import Button from '../components/ui/Button';
|
||||
import Modal from '../components/ui/Modal';
|
||||
import Pagination from '../components/ui/Pagination';
|
||||
import api from '../services/api';
|
||||
import { useAdminAuthStore } from '../store/adminAuthStore';
|
||||
|
||||
|
||||
|
||||
@@ -44,6 +45,8 @@ export interface UserRecord {
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
|
||||
export default function Users() {
|
||||
const actorRole = useAdminAuthStore(state => state.adminUser?.role);
|
||||
const canManageSuperAdmin = ['superadmin', 'adminsuper'].includes((actorRole || '').toLowerCase().replace(/[_-]/g, ''));
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const [users, setUsers] = useState<UserRecord[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
@@ -179,7 +182,8 @@ export default function Users() {
|
||||
if (role) params.append('role', role);
|
||||
|
||||
const response = await api.get(`/admin/users?${params.toString()}`);
|
||||
if (response.data?.success) {
|
||||
// The list endpoint returns { data, meta }, not a success envelope.
|
||||
if (Array.isArray(response.data?.data)) {
|
||||
const userList = response.data.data || [];
|
||||
setUsers(userList);
|
||||
setTotalPages(response.data.meta?.lastPage || 1);
|
||||
@@ -265,7 +269,7 @@ export default function Users() {
|
||||
firstName: editFormData.firstName.trim(),
|
||||
lastName: editFormData.lastName.trim(),
|
||||
mobile: editFormData.mobile.trim(),
|
||||
role: editFormData.role,
|
||||
...(editFormData.role !== editUser.role && { role: editFormData.role }),
|
||||
walletBalance: Number(editFormData.walletBalance) || 0,
|
||||
};
|
||||
if (editFormData.email.trim()) payload.email = editFormData.email.trim();
|
||||
@@ -357,6 +361,7 @@ export default function Users() {
|
||||
<option value="User_Wholesale">خریدار عمده</option>
|
||||
<option value="User_B2B">همکار (B2B)</option>
|
||||
<option value="ADMIN">مدیر سیستم (Admin)</option>
|
||||
<option value="SUPER_ADMIN">مدیر ارشد (Super Admin)</option>
|
||||
</select>
|
||||
|
||||
<div className="relative w-full sm:w-64">
|
||||
@@ -632,6 +637,7 @@ export default function Users() {
|
||||
<option value="User_Wholesale">خریدار عمده (داروخانه/پتشاپ)</option>
|
||||
<option value="User_B2B">همکار (B2B)</option>
|
||||
<option value="ADMIN">مدیر سیستم (Admin)</option>
|
||||
{canManageSuperAdmin && <option value="SUPER_ADMIN">مدیر ارشد (Super Admin)</option>}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
@@ -741,6 +747,7 @@ export default function Users() {
|
||||
<label className="block text-gray-700 font-bold mb-1">نقش دسترسی</label>
|
||||
<select
|
||||
value={editFormData.role}
|
||||
disabled={!canManageSuperAdmin && ['superadmin', 'adminsuper'].includes((editUser?.role || '').toLowerCase().replace(/[_-]/g, ''))}
|
||||
onChange={(e) => setEditFormData({ ...editFormData, role: e.target.value })}
|
||||
className="w-full px-3 py-2.5 rounded-xl border border-gray-200 focus:border-purple-500 outline-none font-bold bg-white"
|
||||
>
|
||||
@@ -748,6 +755,10 @@ export default function Users() {
|
||||
<option value="User_Wholesale">خریدار عمده (داروخانه/پتشاپ)</option>
|
||||
<option value="User_B2B">همکار (B2B)</option>
|
||||
<option value="ADMIN">مدیر سیستم (Admin)</option>
|
||||
{canManageSuperAdmin && <option value="SUPER_ADMIN">مدیر ارشد (Super Admin)</option>}
|
||||
{editUser?.role && !['User_PetOwner', 'User_Wholesale', 'User_B2B', 'ADMIN', ...(canManageSuperAdmin ? ['SUPER_ADMIN'] : [])].includes(editUser.role) && (
|
||||
<option value={editUser.role}>{['superadmin', 'adminsuper'].includes(editUser.role.toLowerCase().replace(/[_-]/g, '')) ? 'مدیر ارشد (Super Admin)' : editUser.role}</option>
|
||||
)}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -50,11 +50,6 @@ const DoctorsManager = lazyWithRetry(() => import('../pages/DoctorsManager'));
|
||||
const FAQManager = lazyWithRetry(() => import('../pages/FAQManager'));
|
||||
const MenuManager = lazyWithRetry(() => import('../pages/MenuManager'));
|
||||
const MonitoringPage = lazyWithRetry(() => import('../pages/MonitoringPage'));
|
||||
const ManagerActionsPage = lazyWithRetry(() => import('../pages/ManagerActionsPage'));
|
||||
const ApprovalsPage = lazyWithRetry(() => import('../pages/ApprovalsPage'));
|
||||
const AuditHistoryPage = lazyWithRetry(() => import('../pages/AuditHistoryPage'));
|
||||
const TasksManagementPage = lazyWithRetry(() => import('../pages/TasksManagementPage'));
|
||||
const CompanyOrchestrationHQ = lazyWithRetry(() => import('../pages/CompanyOrchestrationHQ'));
|
||||
|
||||
export interface AdminRouteConfig {
|
||||
path: string;
|
||||
@@ -120,11 +115,6 @@ export const router = createBrowserRouter([
|
||||
{ path: 'faq/*', element: <FAQManager /> },
|
||||
{ path: 'menu/*', element: <MenuManager /> },
|
||||
{ path: 'monitoring/*', element: <MonitoringPage /> },
|
||||
{ path: 'approvals/*', element: <ApprovalsPage /> },
|
||||
{ path: 'manager-actions/*', element: <ManagerActionsPage /> },
|
||||
{ path: 'history/*', element: <AuditHistoryPage /> },
|
||||
{ path: 'tasks/*', element: <TasksManagementPage /> },
|
||||
{ path: 'governance/hq/*', element: <CompanyOrchestrationHQ /> },
|
||||
],
|
||||
},
|
||||
],
|
||||
|
||||
@@ -1 +1,13 @@
|
||||
import '@testing-library/jest-dom/vitest';
|
||||
|
||||
// Vitest preserves Node 26's host storage globals when populating jsdom.
|
||||
// Bind the actual jsdom Storage objects, not the unavailable host storage.
|
||||
const browserWindow = (globalThis as typeof globalThis & {
|
||||
jsdom: { window: Window };
|
||||
}).jsdom.window;
|
||||
for (const name of ['localStorage', 'sessionStorage'] as const) {
|
||||
Object.defineProperty(globalThis, name, {
|
||||
configurable: true,
|
||||
value: browserWindow[name],
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { expect, it } from 'vitest';
|
||||
|
||||
it('uses browser storage for persistent auth instead of Node host storage', () => {
|
||||
expect(localStorage).toBe(window.localStorage);
|
||||
expect(localStorage).toBeInstanceOf(window.Storage);
|
||||
expect(sessionStorage).toBeInstanceOf(window.Storage);
|
||||
localStorage.setItem('storage-probe', 'browser');
|
||||
expect(localStorage.getItem('storage-probe')).toBe('browser');
|
||||
localStorage.removeItem('storage-probe');
|
||||
});
|
||||
@@ -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())
|
||||
@@ -109,6 +110,10 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str
|
||||
keywords: keywordsList,
|
||||
alternates: {
|
||||
canonical: canonicalUrl,
|
||||
languages: {
|
||||
'fa-IR': canonicalUrl,
|
||||
'x-default': canonicalUrl,
|
||||
},
|
||||
},
|
||||
robots: isStaging
|
||||
? {
|
||||
@@ -138,8 +143,6 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str
|
||||
images: [
|
||||
{
|
||||
url: ogImageUrl,
|
||||
width: 1200,
|
||||
height: 630,
|
||||
alt: blog.imageAlt || blog.title || title,
|
||||
},
|
||||
],
|
||||
@@ -179,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';
|
||||
@@ -208,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,21 @@
|
||||
import { afterEach, expect, it, vi } from 'vitest';
|
||||
import { generateMetadata } from './page';
|
||||
|
||||
vi.mock('../../../lib/seo', () => ({
|
||||
getSeoConfig: async () => ({ brandNameFa: 'کنینا', canonicalBaseUrl: 'https://canina.ir', ogImageUrl: '/fallback.png' }),
|
||||
formatPageTitle: (title: string) => title,
|
||||
}));
|
||||
|
||||
afterEach(() => { vi.unstubAllGlobals(); vi.unstubAllEnvs(); });
|
||||
|
||||
it('uses the exact canonical for monolingual self-referencing language hints', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: async () => ({ title: 'Ear care', canonicalUrl: 'https://canina.ir/blog/ear-care/' }) }));
|
||||
const metadata = await generateMetadata({ params: Promise.resolve({ slug: 'ear-care' }) });
|
||||
expect(metadata.alternates).toEqual({ canonical: 'https://canina.ir/blog/ear-care', languages: { 'fa-IR': 'https://canina.ir/blog/ear-care', 'x-default': 'https://canina.ir/blog/ear-care' } });
|
||||
});
|
||||
|
||||
it('does not invent dimensions for a publisher supplied OG asset', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: async () => ({ title: 'Ear care', imageUrl: '/ear-800x450.jpg' }) }));
|
||||
const metadata = await generateMetadata({ params: Promise.resolve({ slug: 'ear-care' }) });
|
||||
expect((metadata.openGraph as any).images[0]).toEqual({ url: '/ear-800x450.jpg', alt: 'Ear care' });
|
||||
});
|
||||
@@ -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('آخرین بهروزرسانی');
|
||||
});
|
||||
@@ -34,7 +34,7 @@ async function getBlogs() {
|
||||
const apiUrl = process.env.INTERNAL_API_URL || process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4001/api';
|
||||
const apiBase = apiUrl.endsWith('/api') ? apiUrl : `${apiUrl.replace(/\/$/, '')}/api`;
|
||||
try {
|
||||
const res = await fetch(`${apiBase}/blogs?limit=50`, {
|
||||
const res = await fetch(`${apiBase}/blogs?limit=200`, {
|
||||
next: { tags: ['blogs'], revalidate: 3600 },
|
||||
});
|
||||
if (!res.ok) {
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import CartDrawer from "../../components/CartDrawer";
|
||||
|
||||
export default function CartClient() {
|
||||
const router = useRouter();
|
||||
return (
|
||||
<main className="min-h-screen bg-medical-gray-50" dir="rtl">
|
||||
<h1 className="sr-only">سبد خرید</h1>
|
||||
<CartDrawer
|
||||
isOpen
|
||||
onClose={() => router.push("/")}
|
||||
onCheckout={() => router.push("/checkout")}
|
||||
onShopNavigate={() => router.push("/shop")}
|
||||
/>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { generateMetadata } from './page';
|
||||
|
||||
vi.mock('../../lib/seo', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../../lib/seo')>();
|
||||
return {
|
||||
...actual,
|
||||
getSeoConfig: vi.fn().mockResolvedValue({
|
||||
texts: {},
|
||||
brandNameFa: 'کنینا ایران',
|
||||
titleSeparator: '|',
|
||||
titlePosition: 'suffix',
|
||||
canonicalBaseUrl: 'https://canina.ir',
|
||||
ogImageUrl: 'https://canina.ir/assets/og.jpg',
|
||||
defaultMetaTitle: 'کنینا ایران',
|
||||
defaultMetaDescription: 'فروشگاه رسمی کنینا',
|
||||
keywords: ['canina'],
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
describe('/cart metadata', () => {
|
||||
beforeEach(() => {
|
||||
vi.stubEnv('NEXT_PUBLIC_APP_ENV', 'production');
|
||||
vi.stubEnv('NODE_ENV', 'production');
|
||||
vi.stubEnv('NEXT_PUBLIC_SITE_URL', 'https://canina.ir');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
it('provides explicit noindex and self-canonical without pointing canonical to home', async () => {
|
||||
const meta = await generateMetadata();
|
||||
|
||||
// Must be noindex
|
||||
expect(meta.robots).toMatchObject({
|
||||
index: false,
|
||||
follow: false,
|
||||
});
|
||||
|
||||
// Canonical must be self-referential /cart, NOT home '/'
|
||||
expect(meta.alternates?.canonical).toBe('https://canina.ir/cart');
|
||||
expect(meta.alternates?.canonical).not.toBe('https://canina.ir/');
|
||||
expect(meta.alternates?.canonical).not.toBe('https://canina.ir');
|
||||
});
|
||||
});
|
||||
@@ -1,19 +1,16 @@
|
||||
"use client";
|
||||
import type { Metadata } from 'next';
|
||||
import { getPageMetadata } from '../../lib/seo';
|
||||
import CartClient from './CartClient';
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import CartDrawer from "../../components/CartDrawer";
|
||||
export async function generateMetadata(): Promise<Metadata> {
|
||||
return getPageMetadata('cart', {
|
||||
canonicalPath: '/cart',
|
||||
fallbackTitle: 'سبد خرید',
|
||||
fallbackDesc: 'مشاهده و مدیریت اقلام انتخابی سبد خرید، محاسبه تخفیف و ادامه فرآیند سفارش.',
|
||||
noIndex: true,
|
||||
});
|
||||
}
|
||||
|
||||
export default function CartPage() {
|
||||
const router = useRouter();
|
||||
return (
|
||||
<main className="min-h-screen bg-medical-gray-50" dir="rtl">
|
||||
<h1 className="sr-only">سبد خرید</h1>
|
||||
<CartDrawer
|
||||
isOpen
|
||||
onClose={() => router.push("/")}
|
||||
onCheckout={() => router.push("/checkout")}
|
||||
onShopNavigate={() => router.push("/shop")}
|
||||
/>
|
||||
</main>
|
||||
);
|
||||
return <CartClient />;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import AuthModal from "../../components/AuthModal";
|
||||
|
||||
export default function LoginClient() {
|
||||
const router = useRouter();
|
||||
return (
|
||||
<main className="min-h-screen bg-medical-gray-50 px-4 py-12" dir="rtl">
|
||||
<h1 className="sr-only">ورود یا ثبتنام</h1>
|
||||
<AuthModal isOpen onClose={() => router.push("/")} />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { generateMetadata } from './page';
|
||||
|
||||
vi.mock('../../lib/seo', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../../lib/seo')>();
|
||||
return {
|
||||
...actual,
|
||||
getSeoConfig: vi.fn().mockResolvedValue({
|
||||
texts: {},
|
||||
brandNameFa: 'کنینا ایران',
|
||||
titleSeparator: '|',
|
||||
titlePosition: 'suffix',
|
||||
canonicalBaseUrl: 'https://canina.ir',
|
||||
ogImageUrl: 'https://canina.ir/assets/og.jpg',
|
||||
defaultMetaTitle: 'کنینا ایران',
|
||||
defaultMetaDescription: 'فروشگاه رسمی کنینا',
|
||||
keywords: ['canina'],
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
describe('/login metadata', () => {
|
||||
beforeEach(() => {
|
||||
vi.stubEnv('NEXT_PUBLIC_APP_ENV', 'production');
|
||||
vi.stubEnv('NODE_ENV', 'production');
|
||||
vi.stubEnv('NEXT_PUBLIC_SITE_URL', 'https://canina.ir');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
it('provides explicit noindex and self-canonical without pointing canonical to home', async () => {
|
||||
const meta = await generateMetadata();
|
||||
|
||||
// Must be noindex
|
||||
expect(meta.robots).toMatchObject({
|
||||
index: false,
|
||||
follow: false,
|
||||
});
|
||||
|
||||
// Canonical must be self-referential /login, NOT home '/'
|
||||
expect(meta.alternates?.canonical).toBe('https://canina.ir/login');
|
||||
expect(meta.alternates?.canonical).not.toBe('https://canina.ir/');
|
||||
expect(meta.alternates?.canonical).not.toBe('https://canina.ir');
|
||||
});
|
||||
});
|
||||
@@ -1,14 +1,16 @@
|
||||
"use client";
|
||||
import type { Metadata } from 'next';
|
||||
import { getPageMetadata } from '../../lib/seo';
|
||||
import LoginClient from './LoginClient';
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import AuthModal from "../../components/AuthModal";
|
||||
export async function generateMetadata(): Promise<Metadata> {
|
||||
return getPageMetadata('login', {
|
||||
canonicalPath: '/login',
|
||||
fallbackTitle: 'ورود یا ثبتنام',
|
||||
fallbackDesc: 'ورود به حساب کاربری، ثبتنام و مدیریت سفارشات مکملهای دارویی کنینا آلمان.',
|
||||
noIndex: true,
|
||||
});
|
||||
}
|
||||
|
||||
export default function LoginPage() {
|
||||
const router = useRouter();
|
||||
return (
|
||||
<main className="min-h-screen bg-medical-gray-50 px-4 py-12" dir="rtl">
|
||||
<h1 className="sr-only">ورود یا ثبتنام</h1>
|
||||
<AuthModal isOpen onClose={() => router.push("/")} />
|
||||
</main>
|
||||
);
|
||||
return <LoginClient />;
|
||||
}
|
||||
@@ -6,15 +6,30 @@ import sanitizeHtml from 'sanitize-html';
|
||||
import { getSeoConfig, formatPageTitle } from "../../../lib/seo";
|
||||
import { generateMedicalWebPageSchema, generateBreadcrumbSchema, safeJsonLd } from "../../../lib/schema";
|
||||
import SafeImage from "../../../components/SafeImage";
|
||||
import { normalizeRouteSlug, safeEncodeSlug } from "../../../lib/slug";
|
||||
|
||||
const API_URL = process.env.INTERNAL_API_URL || process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4001/api';
|
||||
const apiBase = API_URL.endsWith('/api') ? API_URL : `${API_URL.replace(/\/$/, '')}/api`;
|
||||
function getApiBase(): string {
|
||||
const apiUrl = process.env.INTERNAL_API_URL || process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4001/api';
|
||||
return apiUrl.endsWith('/api') ? apiUrl : `${apiUrl.replace(/\/$/, '')}/api`;
|
||||
}
|
||||
|
||||
const WIKI_SLUG_ALIASES: Record<string, string> = {
|
||||
'taurine': 'taurin',
|
||||
'تائورین': 'تورین',
|
||||
};
|
||||
|
||||
async function getWikiTerm(rawKey: string) {
|
||||
const normalizedKey = normalizeRouteSlug(rawKey);
|
||||
if (!normalizedKey) return null;
|
||||
|
||||
const lookupKey = WIKI_SLUG_ALIASES[normalizedKey.toLowerCase()] || WIKI_SLUG_ALIASES[normalizedKey] || normalizedKey;
|
||||
const encodedKey = safeEncodeSlug(lookupKey);
|
||||
const apiBase = getApiBase();
|
||||
|
||||
async function getWikiTerm(key: string) {
|
||||
try {
|
||||
// 1. Try scientific terms endpoint
|
||||
const res = await fetch(`${apiBase}/wiki/${encodeURIComponent(key)}`, {
|
||||
next: { revalidate: 3600, tags: ['wiki', `wiki-${key}`] }
|
||||
const res = await fetch(`${apiBase}/wiki/${encodedKey}`, {
|
||||
next: { revalidate: 3600, tags: ['wiki', `wiki-${encodedKey}`] }
|
||||
});
|
||||
if (res.ok) {
|
||||
return await res.json();
|
||||
@@ -25,14 +40,15 @@ async function getWikiTerm(key: string) {
|
||||
|
||||
try {
|
||||
// 2. Fallback to ingredients endpoint if slug is an ingredient slug
|
||||
const ingRes = await fetch(`${apiBase}/ingredients/${encodeURIComponent(key)}`, {
|
||||
next: { revalidate: 3600, tags: ['ingredients', `ing-${key}`] }
|
||||
const ingRes = await fetch(`${apiBase}/ingredients/${encodedKey}`, {
|
||||
next: { revalidate: 3600, tags: ['ingredients', `ing-${encodedKey}`] }
|
||||
});
|
||||
if (ingRes.ok) {
|
||||
const ing = await ingRes.json();
|
||||
return {
|
||||
key: ing.slug,
|
||||
term: ing.nameFa || ing.nameEn || ing.slug,
|
||||
rawIngredient: ing,
|
||||
definition: ing.description || `بررسی تخصصی ترکیب دارویی و خواص ${ing.nameFa || ing.nameEn} در کاتالوگ مکملهای کنینا آلمان.`,
|
||||
metaTitle: `خواص دارویی ${ing.nameFa || ing.nameEn} | دانشنامه کنینا ایران`,
|
||||
metaDescription: (ing.description || '').slice(0, 155),
|
||||
@@ -46,14 +62,53 @@ async function getWikiTerm(key: string) {
|
||||
return null;
|
||||
}
|
||||
|
||||
async function getRelatedProducts(termName: string) {
|
||||
async function getRelatedProducts(term: any) {
|
||||
try {
|
||||
const res = await fetch(`${apiBase}/products?search=${encodeURIComponent(termName)}&limit=4`, {
|
||||
next: { revalidate: 3600, tags: ['products'] },
|
||||
});
|
||||
if (!res.ok) return [];
|
||||
const json = await res.json();
|
||||
return json.data || json || [];
|
||||
const apiBase = getApiBase();
|
||||
const searchCandidates: string[] = [];
|
||||
if (typeof term === 'string') {
|
||||
searchCandidates.push(term);
|
||||
} else if (term) {
|
||||
if (term.key) searchCandidates.push(term.key);
|
||||
if (term.wikiId) searchCandidates.push(term.wikiId);
|
||||
if (term.rawIngredient) {
|
||||
if (term.rawIngredient.scientificName) searchCandidates.push(term.rawIngredient.scientificName);
|
||||
if (term.rawIngredient.nameEn) searchCandidates.push(term.rawIngredient.nameEn);
|
||||
if (term.rawIngredient.slug) searchCandidates.push(term.rawIngredient.slug);
|
||||
if (term.rawIngredient.nameFa) {
|
||||
const cleanFa = term.rawIngredient.nameFa.replace(/\s*\([^)]*\)\s*/g, ' ').trim();
|
||||
searchCandidates.push(cleanFa);
|
||||
if (cleanFa.startsWith('ال-') || cleanFa.startsWith('ال ')) {
|
||||
searchCandidates.push(cleanFa.replace(/^ال[- ]/, ''));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (term.term) {
|
||||
const cleanTerm = String(term.term).replace(/\s*\([^)]*\)\s*/g, ' ').trim();
|
||||
searchCandidates.push(cleanTerm);
|
||||
}
|
||||
}
|
||||
|
||||
const uniqueCandidates = Array.from(new Set(searchCandidates.filter(Boolean)));
|
||||
const productMap = new Map<string, any>();
|
||||
|
||||
for (const candidate of uniqueCandidates) {
|
||||
const res = await fetch(`${apiBase}/products?search=${encodeURIComponent(candidate)}&limit=4`, {
|
||||
next: { revalidate: 3600, tags: ['products'] },
|
||||
});
|
||||
if (res.ok) {
|
||||
const json = await res.json();
|
||||
const list = Array.isArray(json.data) ? json.data : Array.isArray(json) ? json : [];
|
||||
for (const p of list) {
|
||||
if (p?.id && !productMap.has(p.id)) {
|
||||
productMap.set(p.id, p);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (productMap.size >= 4) break;
|
||||
}
|
||||
|
||||
return Array.from(productMap.values()).slice(0, 4);
|
||||
} catch (error) {
|
||||
console.error('[Wiki] Error fetching related products for ingredient:', error);
|
||||
return [];
|
||||
@@ -62,6 +117,7 @@ async function getRelatedProducts(termName: string) {
|
||||
|
||||
export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }): Promise<Metadata> {
|
||||
const { slug } = await params;
|
||||
const normalizedKey = normalizeRouteSlug(slug);
|
||||
const term = await getWikiTerm(slug);
|
||||
const config = await getSeoConfig();
|
||||
|
||||
@@ -77,7 +133,7 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str
|
||||
term.metaDescription ||
|
||||
(term.definition ? term.definition.replace(/<[^>]+>/g, '').substring(0, 155).trim() : '') ||
|
||||
`بررسی خواص بالینی، فواید و مکملهای دارویی حاوی ${term.term} در دامپزشکی کنینا آلمان.`;
|
||||
const canonicalUrl = `${config.canonicalBaseUrl.replace(/\/$/, '')}/wiki/${slug}`;
|
||||
const canonicalUrl = `${config.canonicalBaseUrl.replace(/\/$/, '')}/wiki/${safeEncodeSlug(normalizedKey)}`;
|
||||
|
||||
return {
|
||||
title,
|
||||
@@ -102,27 +158,31 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str
|
||||
|
||||
export default async function WikiTermPage({ params }: { params: Promise<{ slug: string }> }) {
|
||||
const { slug } = await params;
|
||||
const normalizedKey = normalizeRouteSlug(slug);
|
||||
const term = await getWikiTerm(slug);
|
||||
|
||||
if (!term) {
|
||||
notFound();
|
||||
}
|
||||
|
||||
const relatedProducts = await getRelatedProducts(term.term);
|
||||
const relatedProducts = await getRelatedProducts(term);
|
||||
const encodedSlug = safeEncodeSlug(normalizedKey);
|
||||
|
||||
const medicalSchema = generateMedicalWebPageSchema({
|
||||
title: `ترکیب درمانی ${term.term} - دانشنامه تخصصی کنینا`,
|
||||
description: term.metaDescription || (term.definition ? term.definition.replace(/<[^>]+>/g, '').substring(0, 160) : ''),
|
||||
url: `https://canina.ir/wiki/${slug}`,
|
||||
url: `https://canina.ir/wiki/${encodedSlug}`,
|
||||
aspects: [term.term, 'Veterinary Supplements', 'Pet Nutrition'],
|
||||
});
|
||||
|
||||
const breadcrumbs = generateBreadcrumbSchema([
|
||||
{ name: 'صفحه اصلی', url: 'https://canina.ir' },
|
||||
{ name: 'دانشنامه ترکیبات', url: 'https://canina.ir/wiki' },
|
||||
{ name: term.term, url: `https://canina.ir/wiki/${slug}` },
|
||||
{ name: term.term, url: `https://canina.ir/wiki/${encodedSlug}` },
|
||||
]);
|
||||
|
||||
const shopSearchTerm = (term.rawIngredient?.nameFa ? term.rawIngredient.nameFa.replace(/\s*\([^)]*\)\s*/g, ' ').trim() : term.term).replace(/\s*\([^)]*\)\s*/g, ' ').trim();
|
||||
|
||||
return (
|
||||
<>
|
||||
<script
|
||||
@@ -188,7 +248,7 @@ export default async function WikiTermPage({ params }: { params: Promise<{ slug:
|
||||
</h2>
|
||||
</div>
|
||||
<Link
|
||||
href={`/shop?search=${encodeURIComponent(term.term)}`}
|
||||
href={`/shop?search=${encodeURIComponent(shopSearchTerm)}`}
|
||||
className="text-xs font-bold text-canina-blue hover:underline flex items-center gap-1"
|
||||
>
|
||||
مشاهده همه در فروشگاه
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import React from 'react';
|
||||
import WikiTermPage, { generateMetadata } from './page';
|
||||
|
||||
vi.mock('../../../lib/seo', () => ({
|
||||
getSeoConfig: vi.fn().mockResolvedValue({
|
||||
brandNameFa: 'کنینا ایران',
|
||||
canonicalBaseUrl: 'https://canina.ir',
|
||||
ogImageUrl: '/assets/og.jpg',
|
||||
defaultMetaDescription: 'توضیحات دانشنامه',
|
||||
titleSeparator: '|',
|
||||
titlePosition: 'suffix',
|
||||
}),
|
||||
formatPageTitle: vi.fn((title) => `${title} | کنینا ایران`),
|
||||
}));
|
||||
|
||||
const mockNotFound = vi.fn();
|
||||
vi.mock('next/navigation', () => ({
|
||||
notFound: () => {
|
||||
mockNotFound();
|
||||
throw new Error('NEXT_NOT_FOUND');
|
||||
},
|
||||
}));
|
||||
|
||||
describe('WikiTermPage slug decoding and single-encoding', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.stubEnv('INTERNAL_API_URL', 'http://backend:3000/api');
|
||||
vi.stubEnv('NEXT_PUBLIC_SITE_URL', 'https://canina.ir');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
it('correctly fetches Persian term when slug is passed URL-encoded (آغوز)', async () => {
|
||||
const fetchMock = vi.fn()
|
||||
// First call: /wiki/%D8%A2%D8%BA%D9%88%D8%B2
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
key: 'آغوز',
|
||||
term: 'آغوز (Colostrum)',
|
||||
definition: 'اولین شیر پستانداران پس از زایمان.',
|
||||
wikiId: 'colostrum',
|
||||
}),
|
||||
})
|
||||
// Second call: /products?search=...
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({ data: [] }),
|
||||
});
|
||||
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
// Incoming params from Next router for /wiki/%D8%A2%D8%BA%D9%88%D8%B2
|
||||
const jsx = await WikiTermPage({
|
||||
params: Promise.resolve({ slug: '%D8%A2%D8%BA%D9%88%D8%B2' }),
|
||||
});
|
||||
|
||||
expect(jsx).toBeDefined();
|
||||
expect(fetchMock).toHaveBeenCalled();
|
||||
const firstCallUrl = fetchMock.mock.calls[0][0];
|
||||
// Must NOT be double-encoded %25D8%25A2...
|
||||
expect(firstCallUrl).toBe('http://backend:3000/api/wiki/%D8%A2%D8%BA%D9%88%D8%B2');
|
||||
expect(firstCallUrl).not.toContain('%25');
|
||||
});
|
||||
|
||||
it('correctly generates metadata with single-encoded canonical for Persian slug', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
key: 'آغوز',
|
||||
term: 'آغوز (Colostrum)',
|
||||
definition: 'اولین شیر پستانداران پس از زایمان.',
|
||||
wikiId: 'colostrum',
|
||||
}),
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
const meta = await generateMetadata({
|
||||
params: Promise.resolve({ slug: '%D8%A2%D8%BA%D9%88%D8%B2' }),
|
||||
});
|
||||
|
||||
expect(meta.alternates?.canonical).toBe('https://canina.ir/wiki/%D8%A2%D8%BA%D9%88%D8%B2');
|
||||
expect(meta.title).toBe('ترکیب دارویی و خواص آغوز (Colostrum) | کنینا ایران');
|
||||
});
|
||||
|
||||
it('handles EPA/DHA without turning into malformed path or double encoding', async () => {
|
||||
const fetchMock = vi.fn()
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
key: 'EPA/DHA',
|
||||
term: 'EPA/DHA',
|
||||
definition: 'اسیدهای چرب امگا ۳.',
|
||||
wikiId: 'epa-dha',
|
||||
}),
|
||||
})
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({ data: [] }),
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
const jsx = await WikiTermPage({
|
||||
params: Promise.resolve({ slug: 'EPA%2FDHA' }),
|
||||
});
|
||||
expect(jsx).toBeDefined();
|
||||
expect(fetchMock.mock.calls[0][0]).toBe('http://backend:3000/api/wiki/EPA%2FDHA');
|
||||
});
|
||||
|
||||
it('resolves alias taurine to taurin and searches related products', async () => {
|
||||
const fetchMock = vi.fn()
|
||||
// First call: /wiki/taurin (fails)
|
||||
.mockResolvedValueOnce({ ok: false, status: 404 })
|
||||
// Second call: /ingredients/taurin (succeeds)
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
slug: 'taurin',
|
||||
nameFa: 'تورین (Taurine)',
|
||||
scientificName: 'Taurine',
|
||||
description: 'اسید آمینه ضروری',
|
||||
}),
|
||||
})
|
||||
// Third call: /products?search=taurin
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({ data: [{ id: 'p1', name: 'مکمل تورین گربه', slug: 'canina-taurin' }] }),
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
const jsx = await WikiTermPage({
|
||||
params: Promise.resolve({ slug: 'taurine' }),
|
||||
});
|
||||
expect(jsx).toBeDefined();
|
||||
// First attempted /wiki/taurin because of alias
|
||||
expect(fetchMock.mock.calls[0][0]).toBe('http://backend:3000/api/wiki/taurin');
|
||||
// Second attempted /ingredients/taurin
|
||||
expect(fetchMock.mock.calls[1][0]).toBe('http://backend:3000/api/ingredients/taurin');
|
||||
});
|
||||
|
||||
it('returns notFound() when neither scientific term nor ingredient exists', async () => {
|
||||
const fetchMock = vi.fn()
|
||||
// 1. wiki term 404
|
||||
.mockResolvedValueOnce({ ok: false, status: 404 })
|
||||
// 2. ingredient fallback 404
|
||||
.mockResolvedValueOnce({ ok: false, status: 404 });
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await expect(
|
||||
WikiTermPage({ params: Promise.resolve({ slug: 'non-existent' }) })
|
||||
).rejects.toThrow('NEXT_NOT_FOUND');
|
||||
expect(mockNotFound).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
Loaded 100 of 249 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user