Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
55d11fa597 | ||
|
|
85ef01d337 | ||
|
|
4d41a5bbf7 | ||
|
|
625c3f5ce2 | ||
|
|
6fbbd7140d | ||
|
|
468856538c | ||
|
|
27b61ce6d5 | ||
|
|
054b9470ab | ||
|
|
55d1bb5967 | ||
|
|
6c1a11a8e2 | ||
|
|
1c4f7e9d10 | ||
|
|
d9cf64d0be | ||
|
|
3a0e0f2acc | ||
|
|
fae4b570f9 | ||
|
|
d881dc491e |
No files matched your search
@@ -12,7 +12,3 @@ uploads
|
|||||||
**/uploads
|
**/uploads
|
||||||
*.pdf
|
*.pdf
|
||||||
graphify-out
|
graphify-out
|
||||||
**/.revalidation.env*
|
|
||||||
**/.support*.env*
|
|
||||||
**/*runtime.env
|
|
||||||
**/release.override.json
|
|
||||||
@@ -5,7 +5,6 @@ on:
|
|||||||
branches:
|
branches:
|
||||||
- main
|
- main
|
||||||
- develop
|
- develop
|
||||||
- release/blog-timestamp-limited-20261030
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
deploy:
|
deploy:
|
||||||
@@ -13,23 +12,11 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Run deploy.sh from within the scripts folder
|
- name: Run deploy.sh from within the scripts folder
|
||||||
env:
|
env:
|
||||||
DEPLOY_REF: ${{ github.ref }}
|
BRANCH: ${{ github.ref_name }}
|
||||||
|
SUPPORT_CHAT_KEY: ${{ secrets.SUPPORT_CHAT_KEY }}
|
||||||
DEPLOY_SHA: ${{ github.sha }}
|
DEPLOY_SHA: ${{ github.sha }}
|
||||||
GITHUB_ACTIONS: 'true'
|
GITHUB_ACTIONS: 'true'
|
||||||
run: |
|
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 و غیرفعال کردن پروکسی برای دامنه محلی
|
# 1. رفع مشکل DNS و غیرفعال کردن پروکسی برای دامنه محلی
|
||||||
echo "87.248.133.138 git.parsaaghayi.ir" >> /etc/hosts
|
echo "87.248.133.138 git.parsaaghayi.ir" >> /etc/hosts
|
||||||
export http_proxy=""
|
export http_proxy=""
|
||||||
@@ -41,9 +28,10 @@ jobs:
|
|||||||
# 2. دانلود و اجرای اسکریپت deploy.sh بر اساس برنچ جاری
|
# 2. دانلود و اجرای اسکریپت deploy.sh بر اساس برنچ جاری
|
||||||
mkdir -p scripts
|
mkdir -p scripts
|
||||||
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/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
|
if [ "$BRANCH" = develop ]; then
|
||||||
|
wget --no-proxy -qO scripts/release-corporate-stage.sh https://git.parsaaghayi.ir/parsa/canina/raw/commit/${DEPLOY_SHA}/scripts/release-corporate-stage.sh
|
||||||
|
fi
|
||||||
|
|
||||||
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
|
chmod +x scripts/deploy.sh
|
||||||
cd scripts
|
cd scripts
|
||||||
./deploy.sh "${BRANCH}"
|
./deploy.sh ${BRANCH}
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
name: Repair Canina Hermes Git route
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- ops/hermes-git-routing-20261106
|
|
||||||
jobs:
|
|
||||||
routing:
|
|
||||||
runs-on: canina
|
|
||||||
steps:
|
|
||||||
- name: Apply scoped runtime routing without restart
|
|
||||||
env:
|
|
||||||
REPAIR_SHA: ${{ github.sha }}
|
|
||||||
REPAIR_REF: ${{ github.ref }}
|
|
||||||
run: |
|
|
||||||
set -eu
|
|
||||||
[ "$REPAIR_REF" = refs/heads/ops/hermes-git-routing-20261106 ]
|
|
||||||
case "$REPAIR_SHA" in *[!0-9a-f]*|'') exit 2 ;; esac
|
|
||||||
[ "${#REPAIR_SHA}" -eq 40 ]
|
|
||||||
export http_proxy= https_proxy= HTTP_PROXY= HTTPS_PROXY=
|
|
||||||
wget --no-proxy -qO repair.py "https://git.parsaaghayi.ir/parsa/canina/raw/commit/${REPAIR_SHA}/infra/hermes-git-routing/repair.py"
|
|
||||||
python3 repair.py
|
|
||||||
docker exec -i -u 10000 -e HOME=/opt/data -e HERMES_HOME=/opt/data canina-hermes python3 - --apply < repair.py
|
|
||||||
docker exec -u 10000 -e HOME=/opt/data -e HERMES_HOME=/opt/data canina-hermes git ls-remote ssh://git@git.parsaaghayi.ir:222/parsa/canina.git refs/heads/develop
|
|
||||||
docker exec -u 10000 -e HOME=/opt/data -e HERMES_HOME=/opt/data canina-hermes git ls-remote canina-gitea:parsa/canina.git refs/heads/develop
|
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
name: Canina Hermes reliability
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- ops/hermes-reliability-20261106
|
|
||||||
jobs:
|
|
||||||
reliability:
|
|
||||||
runs-on: canina
|
|
||||||
steps:
|
|
||||||
- name: Test and install default-only reliability policy
|
|
||||||
env:
|
|
||||||
REPAIR_SHA: ${{ github.sha }}
|
|
||||||
REPAIR_REF: ${{ github.ref }}
|
|
||||||
run: |
|
|
||||||
set -eu
|
|
||||||
[ "$REPAIR_REF" = refs/heads/ops/hermes-reliability-20261106 ]
|
|
||||||
case "$REPAIR_SHA" in *[!0-9a-f]*|'') exit 2 ;; esac
|
|
||||||
[ "${#REPAIR_SHA}" -eq 40 ]
|
|
||||||
export http_proxy= https_proxy= HTTP_PROXY= HTTPS_PROXY=
|
|
||||||
mkdir -p reliability
|
|
||||||
for f in __init__.py plugin.yaml test_guard.py install.py; do
|
|
||||||
wget --no-proxy -qO "reliability/$f" "https://git.parsaaghayi.ir/parsa/canina/raw/commit/${REPAIR_SHA}/infra/hermes-reliability/$f"
|
|
||||||
done
|
|
||||||
python3 reliability/test_guard.py
|
|
||||||
docker exec -u 10000 canina-hermes mkdir -p /opt/data/cache/scratch/reliability-managed
|
|
||||||
for f in __init__.py plugin.yaml install.py; do
|
|
||||||
docker exec -i -u 10000 canina-hermes sh -c "umask 077; tee /opt/data/cache/scratch/reliability-managed/$f >/dev/null" < "reliability/$f"
|
|
||||||
done
|
|
||||||
docker exec -u 10000 -e HOME=/opt/data -e HERMES_HOME=/opt/data canina-hermes python3 /opt/data/cache/scratch/reliability-managed/install.py /opt/data/cache/scratch/reliability-managed
|
|
||||||
@@ -16,7 +16,3 @@ playwright-report/
|
|||||||
playwright/.auth/
|
playwright/.auth/
|
||||||
blob-report/
|
blob-report/
|
||||||
|
|
||||||
|
|
||||||
# Python CI helpers must not dirty immutable release checkouts.
|
|
||||||
__pycache__/
|
|
||||||
*.pyc
|
|
||||||
+9
-9
@@ -1,4 +1,4 @@
|
|||||||
FROM node:22-alpine AS app-builder
|
FROM node:20-alpine AS app-builder
|
||||||
USER root
|
USER root
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
ENV NEXT_TELEMETRY_DISABLED=1
|
ENV NEXT_TELEMETRY_DISABLED=1
|
||||||
@@ -7,17 +7,18 @@ ENV NEXT_PUBLIC_API_URL=https://api.canina.ir/api
|
|||||||
# Optional: Use Nexus as npm registry
|
# Optional: Use Nexus as npm registry
|
||||||
ARG NPM_REGISTRY=
|
ARG NPM_REGISTRY=
|
||||||
RUN if [ -n "$NPM_REGISTRY" ]; then \
|
RUN if [ -n "$NPM_REGISTRY" ]; then \
|
||||||
npm config set registry "$NPM_REGISTRY"; \
|
npm config set registry "$NPM_REGISTRY" && \
|
||||||
|
npm config set strict-ssl false; \
|
||||||
fi
|
fi
|
||||||
|
|
||||||
COPY frontend/application/package*.json ./
|
COPY frontend/application/package*.json ./
|
||||||
RUN npm ci --include=dev --prefer-offline --no-audit && test -x node_modules/.bin/next
|
RUN npm ci --include=dev --prefer-offline --no-audit
|
||||||
COPY frontend/application ./
|
COPY frontend/application ./
|
||||||
ARG NEXT_PUBLIC_API_URL
|
ARG NEXT_PUBLIC_API_URL
|
||||||
ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL
|
ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL
|
||||||
RUN npm run build
|
RUN npm run build
|
||||||
|
|
||||||
FROM node:22-alpine AS admin-builder
|
FROM node:20-alpine AS admin-builder
|
||||||
USER root
|
USER root
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
ENV VITE_API_URL=https://api.canina.ir/api
|
ENV VITE_API_URL=https://api.canina.ir/api
|
||||||
@@ -25,17 +26,18 @@ ENV VITE_API_URL=https://api.canina.ir/api
|
|||||||
# Optional: Use Nexus as npm registry (inherits build-arg)
|
# Optional: Use Nexus as npm registry (inherits build-arg)
|
||||||
ARG NPM_REGISTRY=
|
ARG NPM_REGISTRY=
|
||||||
RUN if [ -n "$NPM_REGISTRY" ]; then \
|
RUN if [ -n "$NPM_REGISTRY" ]; then \
|
||||||
npm config set registry "$NPM_REGISTRY"; \
|
npm config set registry "$NPM_REGISTRY" && \
|
||||||
|
npm config set strict-ssl false; \
|
||||||
fi
|
fi
|
||||||
|
|
||||||
COPY frontend/admin-panel/package*.json ./
|
COPY frontend/admin-panel/package*.json ./
|
||||||
RUN npm ci --include=dev --prefer-offline --no-audit && test -x node_modules/.bin/vite
|
RUN npm ci --include=dev --prefer-offline --no-audit
|
||||||
COPY frontend/admin-panel ./
|
COPY frontend/admin-panel ./
|
||||||
ARG VITE_API_URL
|
ARG VITE_API_URL
|
||||||
ENV VITE_API_URL=$VITE_API_URL
|
ENV VITE_API_URL=$VITE_API_URL
|
||||||
RUN npm run build
|
RUN npm run build
|
||||||
|
|
||||||
FROM node:22-alpine
|
FROM node:20-alpine
|
||||||
USER root
|
USER root
|
||||||
RUN addgroup -S nginx 2>/dev/null || true && adduser -S nginx -G nginx 2>/dev/null || true
|
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
|
RUN mkdir -p /var/log/nginx /var/cache/nginx /run/nginx /etc/nginx/conf.d /etc/nginx/http.d
|
||||||
@@ -47,8 +49,6 @@ RUN chown -R nginx:nginx /var/log/nginx /var/cache/nginx /run/nginx 2>/dev/null
|
|||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY --from=app-builder /app .
|
COPY --from=app-builder /app .
|
||||||
COPY --from=admin-builder /app/dist ./admin_static
|
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/conf.d/default.conf
|
||||||
COPY nginx.conf /etc/nginx/http.d/default.conf
|
COPY nginx.conf /etc/nginx/http.d/default.conf
|
||||||
|
|
||||||
|
|||||||
+2
-5
@@ -2,7 +2,6 @@ FROM node:20-alpine AS builder
|
|||||||
USER root
|
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 http_proxy=http://172.17.0.1:8888 https_proxy=http://172.17.0.1:8888 apk add --no-cache openssl || apk add --no-cache openssl || true
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
ENV PRISMA_HIDE_UPDATE_MESSAGE=true
|
|
||||||
ENV PRISMA_SKIP_POSTINSTALL_GENERATE=true
|
ENV PRISMA_SKIP_POSTINSTALL_GENERATE=true
|
||||||
ENV PRISMA_ENGINES_MIRROR=https://registry.npmmirror.com/-/binary/prisma
|
ENV PRISMA_ENGINES_MIRROR=https://registry.npmmirror.com/-/binary/prisma
|
||||||
ENV DISABLE_OPENCOLLECTIVE=1
|
ENV DISABLE_OPENCOLLECTIVE=1
|
||||||
@@ -12,6 +11,7 @@ ENV npm_config_cache=/tmp/npm-cache
|
|||||||
ARG NPM_REGISTRY=
|
ARG NPM_REGISTRY=
|
||||||
RUN if [ -n "$NPM_REGISTRY" ]; then \
|
RUN if [ -n "$NPM_REGISTRY" ]; then \
|
||||||
npm config set registry "$NPM_REGISTRY" && \
|
npm config set registry "$NPM_REGISTRY" && \
|
||||||
|
npm config set strict-ssl false && \
|
||||||
echo "Using npm registry: $NPM_REGISTRY"; \
|
echo "Using npm registry: $NPM_REGISTRY"; \
|
||||||
fi
|
fi
|
||||||
|
|
||||||
@@ -31,11 +31,8 @@ RUN http_proxy=http://172.17.0.1:8888 https_proxy=http://172.17.0.1:8888 \
|
|||||||
FROM node:20-alpine
|
FROM node:20-alpine
|
||||||
USER root
|
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 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 /app/private-stage-test && chmod 700 /app/private-stage-test && chown node:node /app/uploads /app/private-stage-test
|
RUN mkdir -p /app/uploads && chown node:node /app/uploads
|
||||||
WORKDIR /app
|
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/package*.json ./
|
||||||
COPY --chown=node:node --from=builder /app/tsconfig.json ./tsconfig.json
|
COPY --chown=node:node --from=builder /app/tsconfig.json ./tsconfig.json
|
||||||
COPY --chown=node:node --from=builder /app/eslint.config.mjs ./eslint.config.mjs
|
COPY --chown=node:node --from=builder /app/eslint.config.mjs ./eslint.config.mjs
|
||||||
|
|||||||
@@ -1,28 +0,0 @@
|
|||||||
# 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.
|
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import { PrismaClient } from '@prisma/client';
|
||||||
|
|
||||||
|
const prisma = new PrismaClient();
|
||||||
|
|
||||||
|
async function cleanFaqs() {
|
||||||
|
console.log('--- Cleaning Misplaced Content Tasks from FAQs ---');
|
||||||
|
const countBefore = await prisma.fAQ.count();
|
||||||
|
console.log(`Total FAQs before cleanup: ${countBefore}`);
|
||||||
|
|
||||||
|
const deleteResult = await prisma.fAQ.deleteMany({
|
||||||
|
where: {
|
||||||
|
OR: [
|
||||||
|
{ question: { contains: 'راهنمای' } },
|
||||||
|
{ question: { contains: 'اینفوگرافیک' } },
|
||||||
|
{ question: { contains: 'نگارش' } },
|
||||||
|
{ question: { contains: 'تدوین' } },
|
||||||
|
{ question: { contains: 'تولید' } },
|
||||||
|
{ question: { contains: 'مقاله' } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log(`Successfully deleted ${deleteResult.count} misplaced content tasks.`);
|
||||||
|
const countAfter = await prisma.fAQ.count();
|
||||||
|
console.log(`Total real customer FAQs remaining: ${countAfter}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
cleanFaqs()
|
||||||
|
.catch((err) => {
|
||||||
|
console.error('Clean FAQs error:', err);
|
||||||
|
process.exit(1);
|
||||||
|
})
|
||||||
|
.finally(async () => {
|
||||||
|
await prisma.$disconnect();
|
||||||
|
});
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
ALTER TABLE blogs ADD COLUMN IF NOT EXISTS author_team VARCHAR(200);
|
|
||||||
ALTER TABLE blogs ADD COLUMN IF NOT EXISTS author_role VARCHAR(200);
|
|
||||||
ALTER TABLE blogs ADD COLUMN IF NOT EXISTS content_updated_at TIMESTAMPTZ;
|
|
||||||
@@ -1,211 +0,0 @@
|
|||||||
-- 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;
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
-- 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);
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
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);
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
-- 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");
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
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
@@ -1,14 +0,0 @@
|
|||||||
-- 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;
|
|
||||||
+117
@@ -0,0 +1,117 @@
|
|||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "advisor_contacts" (
|
||||||
|
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
|
||||||
|
"name" VARCHAR(150) NOT NULL,
|
||||||
|
"phone" VARCHAR(20) NOT NULL,
|
||||||
|
"title" VARCHAR(100),
|
||||||
|
"is_default" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
"is_active" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "advisor_contacts_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "product_advisors" (
|
||||||
|
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
|
||||||
|
"product_id" UUID NOT NULL,
|
||||||
|
"advisor_id" UUID NOT NULL,
|
||||||
|
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "product_advisors_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "leads" (
|
||||||
|
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
|
||||||
|
"first_name" VARCHAR(100) NOT NULL,
|
||||||
|
"last_name" VARCHAR(100) NOT NULL,
|
||||||
|
"phone" VARCHAR(20) NOT NULL,
|
||||||
|
"product_id" UUID,
|
||||||
|
"advisor_id" UUID,
|
||||||
|
"status" VARCHAR(30) NOT NULL DEFAULT 'PENDING',
|
||||||
|
"notes" TEXT,
|
||||||
|
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "leads_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "notification_queues" (
|
||||||
|
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
|
||||||
|
"channel" VARCHAR(20) NOT NULL,
|
||||||
|
"recipient" VARCHAR(150) NOT NULL,
|
||||||
|
"event" VARCHAR(50) NOT NULL,
|
||||||
|
"subject" VARCHAR(255),
|
||||||
|
"content" TEXT NOT NULL,
|
||||||
|
"payload" JSONB,
|
||||||
|
"status" VARCHAR(30) NOT NULL DEFAULT 'QUEUED',
|
||||||
|
"attempts" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"max_attempts" INTEGER NOT NULL DEFAULT 3,
|
||||||
|
"last_error" TEXT,
|
||||||
|
"idempotency_key" VARCHAR(100),
|
||||||
|
"sent_at" TIMESTAMPTZ,
|
||||||
|
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "notification_queues_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "notification_templates" (
|
||||||
|
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
|
||||||
|
"channel" VARCHAR(20) NOT NULL,
|
||||||
|
"event" VARCHAR(50) NOT NULL,
|
||||||
|
"name" VARCHAR(150) NOT NULL,
|
||||||
|
"subject" VARCHAR(255),
|
||||||
|
"body" TEXT NOT NULL,
|
||||||
|
"pattern_code" VARCHAR(50),
|
||||||
|
"variables" TEXT[] DEFAULT ARRAY[]::TEXT[],
|
||||||
|
"recipient_type" VARCHAR(30) NOT NULL DEFAULT 'customer',
|
||||||
|
"custom_recipient" VARCHAR(150),
|
||||||
|
"is_active" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "notification_templates_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "advisor_contacts_phone_key" ON "advisor_contacts"("phone");
|
||||||
|
CREATE INDEX "advisor_contacts_phone_idx" ON "advisor_contacts"("phone");
|
||||||
|
CREATE INDEX "advisor_contacts_is_default_idx" ON "advisor_contacts"("is_default");
|
||||||
|
CREATE INDEX "advisor_contacts_is_active_idx" ON "advisor_contacts"("is_active");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "product_advisors_product_id_advisor_id_key" ON "product_advisors"("product_id", "advisor_id");
|
||||||
|
CREATE INDEX "product_advisors_product_id_idx" ON "product_advisors"("product_id");
|
||||||
|
CREATE INDEX "product_advisors_advisor_id_idx" ON "product_advisors"("advisor_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "leads_phone_idx" ON "leads"("phone");
|
||||||
|
CREATE INDEX "leads_status_idx" ON "leads"("status");
|
||||||
|
CREATE INDEX "leads_created_at_idx" ON "leads"("created_at");
|
||||||
|
CREATE INDEX "leads_advisor_id_idx" ON "leads"("advisor_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "notification_queues_idempotency_key_key" ON "notification_queues"("idempotency_key");
|
||||||
|
CREATE INDEX "notification_queues_status_idx" ON "notification_queues"("status");
|
||||||
|
CREATE INDEX "notification_queues_channel_idx" ON "notification_queues"("channel");
|
||||||
|
CREATE INDEX "notification_queues_event_idx" ON "notification_queues"("event");
|
||||||
|
CREATE INDEX "notification_queues_created_at_idx" ON "notification_queues"("created_at");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "notification_templates_channel_event_key" ON "notification_templates"("channel", "event");
|
||||||
|
CREATE INDEX "notification_templates_channel_idx" ON "notification_templates"("channel");
|
||||||
|
CREATE INDEX "notification_templates_event_idx" ON "notification_templates"("event");
|
||||||
|
CREATE INDEX "notification_templates_is_active_idx" ON "notification_templates"("is_active");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "product_advisors" ADD CONSTRAINT "product_advisors_product_id_fkey" FOREIGN KEY ("product_id") REFERENCES "products"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "product_advisors" ADD CONSTRAINT "product_advisors_advisor_id_fkey" FOREIGN KEY ("advisor_id") REFERENCES "advisor_contacts"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "leads" ADD CONSTRAINT "leads_product_id_fkey" FOREIGN KEY ("product_id") REFERENCES "products"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "leads" ADD CONSTRAINT "leads_advisor_id_fkey" FOREIGN KEY ("advisor_id") REFERENCES "advisor_contacts"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
+72
@@ -0,0 +1,72 @@
|
|||||||
|
-- CreateTable approval_requests
|
||||||
|
CREATE TABLE IF NOT EXISTS public.approval_requests (
|
||||||
|
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
|
||||||
|
"department" VARCHAR(50) NOT NULL,
|
||||||
|
"category" VARCHAR(50) NOT NULL,
|
||||||
|
"title" VARCHAR(255) NOT NULL,
|
||||||
|
"payload" JSONB NOT NULL,
|
||||||
|
"test_context" JSONB,
|
||||||
|
"status" VARCHAR(30) NOT NULL DEFAULT 'PENDING',
|
||||||
|
"ceo_notes" TEXT,
|
||||||
|
"executed_at" TIMESTAMPTZ(6),
|
||||||
|
"created_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "approval_requests_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable audit_logs
|
||||||
|
CREATE TABLE IF NOT EXISTS public.audit_logs (
|
||||||
|
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
|
||||||
|
"entity" VARCHAR(50) NOT NULL,
|
||||||
|
"entity_id" VARCHAR(100),
|
||||||
|
"action" VARCHAR(50) NOT NULL,
|
||||||
|
"department" VARCHAR(50),
|
||||||
|
"actor" VARCHAR(100) NOT NULL DEFAULT 'SYSTEM',
|
||||||
|
"summary" VARCHAR(255) NOT NULL,
|
||||||
|
"old_values" JSONB,
|
||||||
|
"new_values" JSONB,
|
||||||
|
"metadata" JSONB,
|
||||||
|
"created_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "audit_logs_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable department_tasks
|
||||||
|
CREATE TABLE IF NOT EXISTS public.department_tasks (
|
||||||
|
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
|
||||||
|
"code" VARCHAR(50) NOT NULL,
|
||||||
|
"department" VARCHAR(50) NOT NULL,
|
||||||
|
"title" VARCHAR(255) NOT NULL,
|
||||||
|
"description" TEXT,
|
||||||
|
"status" VARCHAR(30) NOT NULL DEFAULT 'BACKLOG',
|
||||||
|
"priority" VARCHAR(20) NOT NULL DEFAULT 'MEDIUM',
|
||||||
|
"assignee" VARCHAR(100),
|
||||||
|
"acceptance_criteria" JSONB,
|
||||||
|
"execution_logs" JSONB,
|
||||||
|
"deliverable_url" VARCHAR(255),
|
||||||
|
"approval_id" UUID,
|
||||||
|
"started_at" TIMESTAMPTZ(6),
|
||||||
|
"completed_at" TIMESTAMPTZ(6),
|
||||||
|
"created_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "department_tasks_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS "department_tasks_code_key" ON public.department_tasks("code");
|
||||||
|
CREATE INDEX IF NOT EXISTS "approval_requests_department_idx" ON public.approval_requests("department");
|
||||||
|
CREATE INDEX IF NOT EXISTS "approval_requests_category_idx" ON public.approval_requests("category");
|
||||||
|
CREATE INDEX IF NOT EXISTS "approval_requests_status_idx" ON public.approval_requests("status");
|
||||||
|
CREATE INDEX IF NOT EXISTS "approval_requests_created_at_idx" ON public.approval_requests("created_at");
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS "audit_logs_entity_idx" ON public.audit_logs("entity");
|
||||||
|
CREATE INDEX IF NOT EXISTS "audit_logs_action_idx" ON public.audit_logs("action");
|
||||||
|
CREATE INDEX IF NOT EXISTS "audit_logs_department_idx" ON public.audit_logs("department");
|
||||||
|
CREATE INDEX IF NOT EXISTS "audit_logs_created_at_idx" ON public.audit_logs("created_at");
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS "department_tasks_department_idx" ON public.department_tasks("department");
|
||||||
|
CREATE INDEX IF NOT EXISTS "department_tasks_status_idx" ON public.department_tasks("status");
|
||||||
|
CREATE INDEX IF NOT EXISTS "department_tasks_priority_idx" ON public.department_tasks("priority");
|
||||||
|
CREATE INDEX IF NOT EXISTS "department_tasks_created_at_idx" ON public.department_tasks("created_at");
|
||||||
@@ -16,9 +16,6 @@ model User {
|
|||||||
mobile String @unique @db.VarChar(15)
|
mobile String @unique @db.VarChar(15)
|
||||||
password String? @db.VarChar(255)
|
password String? @db.VarChar(255)
|
||||||
role String @default("User_PetOwner") @db.VarChar(30)
|
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)
|
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)
|
charityDonationTotal Decimal @default(0.00) @map("charity_donation_total") @db.Decimal(15, 2)
|
||||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||||
@@ -181,9 +178,7 @@ model Blog {
|
|||||||
slug String @unique @db.VarChar(200)
|
slug String @unique @db.VarChar(200)
|
||||||
content String @db.Text
|
content String @db.Text
|
||||||
excerpt String? @db.Text
|
excerpt String? @db.Text
|
||||||
authorId String? @map("author_id") @db.Uuid
|
authorId String @map("author_id") @db.Uuid
|
||||||
authorTeam String? @map("author_team") @db.VarChar(200)
|
|
||||||
authorRole String? @map("author_role") @db.VarChar(200)
|
|
||||||
categoryId String? @map("category_id") @db.Uuid
|
categoryId String? @map("category_id") @db.Uuid
|
||||||
imageUrl String? @map("image_url") @db.Text
|
imageUrl String? @map("image_url") @db.Text
|
||||||
imageAlt String? @map("image_alt") @db.VarChar(255)
|
imageAlt String? @map("image_alt") @db.VarChar(255)
|
||||||
@@ -203,7 +198,6 @@ model Blog {
|
|||||||
isPublished Boolean @default(true) @map("is_published")
|
isPublished Boolean @default(true) @map("is_published")
|
||||||
publishedAt DateTime? @map("published_at") @db.Timestamptz()
|
publishedAt DateTime? @map("published_at") @db.Timestamptz()
|
||||||
scheduledAt DateTime? @map("scheduled_at") @db.Timestamptz()
|
scheduledAt DateTime? @map("scheduled_at") @db.Timestamptz()
|
||||||
contentUpdatedAt DateTime? @map("content_updated_at") @db.Timestamptz()
|
|
||||||
readingTime Int @default(3) @map("reading_time")
|
readingTime Int @default(3) @map("reading_time")
|
||||||
featured Boolean @default(false)
|
featured Boolean @default(false)
|
||||||
allowComments Boolean @default(true) @map("allow_comments")
|
allowComments Boolean @default(true) @map("allow_comments")
|
||||||
@@ -215,7 +209,7 @@ model Blog {
|
|||||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||||
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
|
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
|
||||||
|
|
||||||
author User? @relation(fields: [authorId], references: [id])
|
author User @relation(fields: [authorId], references: [id])
|
||||||
category BlogCategory? @relation(fields: [categoryId], references: [id], onDelete: SetNull)
|
category BlogCategory? @relation(fields: [categoryId], references: [id], onDelete: SetNull)
|
||||||
tags BlogTag[]
|
tags BlogTag[]
|
||||||
comments BlogComment[]
|
comments BlogComment[]
|
||||||
@@ -292,6 +286,8 @@ model Product {
|
|||||||
reviews ProductReview[]
|
reviews ProductReview[]
|
||||||
competitorPriceLogs CompetitorPriceLog[]
|
competitorPriceLogs CompetitorPriceLog[]
|
||||||
priceSuggestions PriceSuggestion[]
|
priceSuggestions PriceSuggestion[]
|
||||||
|
productAdvisors ProductAdvisor[]
|
||||||
|
leads Lead[]
|
||||||
|
|
||||||
@@index([categorySlug])
|
@@index([categorySlug])
|
||||||
@@index([suitableFor])
|
@@index([suitableFor])
|
||||||
@@ -1020,3 +1016,394 @@ model SmsCampaign {
|
|||||||
@@map("sms_campaigns")
|
@@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 DepartmentTask {
|
||||||
|
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")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------------------
|
||||||
|
// 8. AdvisorContact (مشاوران تخصصی و پاسخگویی)
|
||||||
|
// ------------------------------------------------------------------------------
|
||||||
|
model AdvisorContact {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
name String @db.VarChar(150)
|
||||||
|
phone String @unique @db.VarChar(20)
|
||||||
|
title String? @db.VarChar(100)
|
||||||
|
isDefault Boolean @default(false) @map("is_default")
|
||||||
|
isActive Boolean @default(true) @map("is_active")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||||
|
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
|
||||||
|
|
||||||
|
productAdvisors ProductAdvisor[]
|
||||||
|
leads Lead[]
|
||||||
|
|
||||||
|
@@index([phone])
|
||||||
|
@@index([isDefault])
|
||||||
|
@@index([isActive])
|
||||||
|
@@map("advisor_contacts")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------------------
|
||||||
|
// 9. ProductAdvisor (اتصال مشاور به محصول)
|
||||||
|
// ------------------------------------------------------------------------------
|
||||||
|
model ProductAdvisor {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
productId String @map("product_id") @db.Uuid
|
||||||
|
advisorId String @map("advisor_id") @db.Uuid
|
||||||
|
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||||
|
|
||||||
|
product Product @relation(fields: [productId], references: [id], onDelete: Cascade)
|
||||||
|
advisor AdvisorContact @relation(fields: [advisorId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
|
@@unique([productId, advisorId])
|
||||||
|
@@index([productId])
|
||||||
|
@@index([advisorId])
|
||||||
|
@@map("product_advisors")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------------------
|
||||||
|
// 10. Lead (درخواستهای تماس و مشاوره کاربران)
|
||||||
|
// ------------------------------------------------------------------------------
|
||||||
|
model Lead {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
firstName String @map("first_name") @db.VarChar(100)
|
||||||
|
lastName String @map("last_name") @db.VarChar(100)
|
||||||
|
phone String @db.VarChar(20)
|
||||||
|
productId String? @map("product_id") @db.Uuid
|
||||||
|
advisorId String? @map("advisor_id") @db.Uuid
|
||||||
|
status String @default("PENDING") @db.VarChar(30) // PENDING, CONTACTED, CANCELLED
|
||||||
|
notes String? @db.Text
|
||||||
|
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||||
|
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
|
||||||
|
|
||||||
|
product Product? @relation(fields: [productId], references: [id], onDelete: SetNull)
|
||||||
|
advisor AdvisorContact? @relation(fields: [advisorId], references: [id], onDelete: SetNull)
|
||||||
|
|
||||||
|
@@index([phone])
|
||||||
|
@@index([status])
|
||||||
|
@@index([createdAt])
|
||||||
|
@@index([advisorId])
|
||||||
|
@@map("leads")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------------------
|
||||||
|
// 11. NotificationQueue (صف ناهمگام نوتیفیکیشنها با قابلیت Retry و Idempotency)
|
||||||
|
// ------------------------------------------------------------------------------
|
||||||
|
model NotificationQueue {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
channel String @db.VarChar(20) // SMS, EMAIL
|
||||||
|
recipient String @db.VarChar(150)
|
||||||
|
event String @db.VarChar(50)
|
||||||
|
subject String? @db.VarChar(255)
|
||||||
|
content String @db.Text
|
||||||
|
payload Json? @db.JsonB
|
||||||
|
status String @default("QUEUED") @db.VarChar(30) // QUEUED, PROCESSING, SENT, FAILED
|
||||||
|
attempts Int @default(0)
|
||||||
|
maxAttempts Int @default(3) @map("max_attempts")
|
||||||
|
lastError String? @map("last_error") @db.Text
|
||||||
|
idempotencyKey String? @unique @map("idempotency_key") @db.VarChar(100)
|
||||||
|
sentAt DateTime? @map("sent_at") @db.Timestamptz()
|
||||||
|
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||||
|
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
|
||||||
|
|
||||||
|
@@index([status])
|
||||||
|
@@index([channel])
|
||||||
|
@@index([event])
|
||||||
|
@@index([createdAt])
|
||||||
|
@@map("notification_queues")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------------------
|
||||||
|
// 12. NotificationTemplate (قالبهای رویدادها برای ایمیل و پیامک)
|
||||||
|
// ------------------------------------------------------------------------------
|
||||||
|
model NotificationTemplate {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
channel String @db.VarChar(20) // SMS, EMAIL
|
||||||
|
event String @db.VarChar(50) // ORDER_CREATED, PAYMENT_SUCCESS, NEW_LEAD, etc.
|
||||||
|
name String @db.VarChar(150)
|
||||||
|
subject String? @db.VarChar(255)
|
||||||
|
body String @db.Text
|
||||||
|
patternCode String? @map("pattern_code") @db.VarChar(50)
|
||||||
|
variables String[] @default([])
|
||||||
|
recipientType String @default("customer") @map("recipient_type") @db.VarChar(30)
|
||||||
|
customRecipient String? @map("custom_recipient") @db.VarChar(150)
|
||||||
|
isActive Boolean @default(true) @map("is_active")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||||
|
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
|
||||||
|
|
||||||
|
@@unique([channel, event])
|
||||||
|
@@index([channel])
|
||||||
|
@@index([event])
|
||||||
|
@@index([isActive])
|
||||||
|
@@map("notification_templates")
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
enum CorporateTaskStatus {
|
||||||
|
TODO
|
||||||
|
IN_PROGRESS
|
||||||
|
TEST
|
||||||
|
DONE
|
||||||
|
BLOCKED
|
||||||
|
REJECTED
|
||||||
|
CANCELLED
|
||||||
|
}
|
||||||
|
|
||||||
|
enum CorporatePriority {
|
||||||
|
CEO_EXPEDITE
|
||||||
|
CRITICAL
|
||||||
|
HIGH
|
||||||
|
MEDIUM
|
||||||
|
LOW
|
||||||
|
}
|
||||||
|
|
||||||
|
model CorporateTask {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
taskCode String @unique
|
||||||
|
title String
|
||||||
|
normalizedTitle String
|
||||||
|
normalizedCode String
|
||||||
|
description String
|
||||||
|
department String
|
||||||
|
priority CorporatePriority @default(CEO_EXPEDITE)
|
||||||
|
status CorporateTaskStatus @default(TODO)
|
||||||
|
actionType String @default("CEO_DIRECTIVE")
|
||||||
|
dueCycle String?
|
||||||
|
parentId String? @db.Uuid
|
||||||
|
parent CorporateTask? @relation("TaskChildren", fields: [parentId], references: [id])
|
||||||
|
children CorporateTask[] @relation("TaskChildren")
|
||||||
|
goalId String? @db.Uuid
|
||||||
|
goal CorporateGoal? @relation(fields: [goalId], references: [id])
|
||||||
|
assignedAgent String?
|
||||||
|
claimToken String? @db.Uuid
|
||||||
|
leasedUntil DateTime? @db.Timestamptz()
|
||||||
|
executionCount Int @default(0)
|
||||||
|
qaCount Int @default(0)
|
||||||
|
rejectionCount Int @default(0)
|
||||||
|
createdBy String
|
||||||
|
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||||
|
updatedAt DateTime @updatedAt @db.Timestamptz()
|
||||||
|
logs CorporateEvent[]
|
||||||
|
evidence CorporateEvidence[]
|
||||||
|
reviews CorporateReview[]
|
||||||
|
effects CorporateEffect[]
|
||||||
|
@@index([status, priority, updatedAt])
|
||||||
|
@@index([parentId])
|
||||||
|
@@index([goalId])
|
||||||
|
@@map("corporate_tasks")
|
||||||
|
}
|
||||||
|
|
||||||
|
model CorporateEvent {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
taskId String @db.Uuid
|
||||||
|
task CorporateTask @relation(fields: [taskId], references: [id])
|
||||||
|
speaker String
|
||||||
|
speakerName String
|
||||||
|
step String
|
||||||
|
content String
|
||||||
|
payload Json?
|
||||||
|
timestamp DateTime @default(now()) @db.Timestamptz()
|
||||||
|
@@index([taskId, timestamp])
|
||||||
|
@@map("corporate_events")
|
||||||
|
}
|
||||||
|
|
||||||
|
model CorporateEvidence {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
taskId String @db.Uuid
|
||||||
|
task CorporateTask @relation(fields: [taskId], references: [id])
|
||||||
|
claimToken String @db.Uuid
|
||||||
|
executor String
|
||||||
|
artifactUri String
|
||||||
|
sha256 String
|
||||||
|
summary String
|
||||||
|
tool String
|
||||||
|
result String
|
||||||
|
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||||
|
reviews CorporateReview[]
|
||||||
|
@@index([taskId])
|
||||||
|
@@map("corporate_evidence")
|
||||||
|
}
|
||||||
|
|
||||||
|
model CorporateReview {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
taskId String @db.Uuid
|
||||||
|
task CorporateTask @relation(fields: [taskId], references: [id])
|
||||||
|
evidenceId String @db.Uuid
|
||||||
|
evidence CorporateEvidence @relation(fields: [evidenceId], references: [id])
|
||||||
|
reviewer String
|
||||||
|
passed Boolean
|
||||||
|
findings String
|
||||||
|
verification Json
|
||||||
|
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||||
|
@@index([taskId])
|
||||||
|
@@map("corporate_reviews")
|
||||||
|
}
|
||||||
|
|
||||||
|
model CorporateResearch {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
title String
|
||||||
|
category String
|
||||||
|
source String
|
||||||
|
opportunity String
|
||||||
|
impact String
|
||||||
|
recommendedAction String
|
||||||
|
status String @default("DISCOVERED")
|
||||||
|
cadence String
|
||||||
|
provenance Json
|
||||||
|
createdBy String
|
||||||
|
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||||
|
sources CorporateSource[]
|
||||||
|
roadmaps CorporateRoadmap[]
|
||||||
|
@@map("corporate_research")
|
||||||
|
}
|
||||||
|
|
||||||
|
model CorporateSource {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
researchId String @db.Uuid
|
||||||
|
research CorporateResearch @relation(fields: [researchId], references: [id])
|
||||||
|
url String
|
||||||
|
title String
|
||||||
|
excerpt String
|
||||||
|
retrievedAt DateTime @db.Timestamptz()
|
||||||
|
sha256 String
|
||||||
|
@@index([researchId])
|
||||||
|
@@map("corporate_sources")
|
||||||
|
}
|
||||||
|
|
||||||
|
model CorporateRoadmap {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
researchId String @db.Uuid
|
||||||
|
research CorporateResearch @relation(fields: [researchId], references: [id])
|
||||||
|
cycleName String
|
||||||
|
month String
|
||||||
|
seasonalTheme String
|
||||||
|
strategicGoals String[]
|
||||||
|
plannedArticlesCount Int
|
||||||
|
plannedRefreshesCount Int
|
||||||
|
plannedCatalogEnrichments Int
|
||||||
|
isActive Boolean @default(false)
|
||||||
|
createdBy String
|
||||||
|
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||||
|
goals CorporateGoal[]
|
||||||
|
@@index([month])
|
||||||
|
@@map("corporate_roadmaps")
|
||||||
|
}
|
||||||
|
|
||||||
|
model CorporateGoal {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
roadmapId String @db.Uuid
|
||||||
|
roadmap CorporateRoadmap @relation(fields: [roadmapId], references: [id])
|
||||||
|
title String
|
||||||
|
department String
|
||||||
|
acceptanceCriteria String
|
||||||
|
metric String
|
||||||
|
target Float?
|
||||||
|
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||||
|
tasks CorporateTask[]
|
||||||
|
@@index([roadmapId])
|
||||||
|
@@map("corporate_goals")
|
||||||
|
}
|
||||||
|
|
||||||
|
model CorporateEffect {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
taskId String @db.Uuid
|
||||||
|
task CorporateTask @relation(fields: [taskId], references: [id])
|
||||||
|
metric String
|
||||||
|
availability String
|
||||||
|
baseline Float?
|
||||||
|
observed Float?
|
||||||
|
source String
|
||||||
|
observedAt DateTime @db.Timestamptz()
|
||||||
|
recordedBy String
|
||||||
|
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||||
|
@@index([taskId])
|
||||||
|
@@map("corporate_effects")
|
||||||
|
}
|
||||||
|
|
||||||
|
model CorporateReport {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
day String @unique
|
||||||
|
summary String
|
||||||
|
snapshot Json
|
||||||
|
createdBy String
|
||||||
|
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||||
|
@@map("corporate_reports")
|
||||||
|
}
|
||||||
|
|
||||||
|
model CorporateOperation {
|
||||||
|
key String @id
|
||||||
|
payloadHash String
|
||||||
|
response Json
|
||||||
|
createdAt DateTime @default(now()) @db.Timestamptz()
|
||||||
|
@@map("corporate_operations")
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
import { PrismaClient } from '@prisma/client';
|
||||||
|
|
||||||
|
const prisma = new PrismaClient();
|
||||||
|
|
||||||
|
const defaultFaqs = [
|
||||||
|
{
|
||||||
|
order: 1,
|
||||||
|
question: 'آیا برای خرید مکملهای تخصصی کنینا به نسخه دامپزشک نیاز است؟',
|
||||||
|
answer: 'خیر، مکملهای غذایی و درمانی کنینا بدون نسخه قابل سفارش هستند. با این وجود جهت تعیین دقیقترین دوز مصرفی متناسب با سن، وزن و شرایط بالینی پت دلبندتان، میتوانید از خدمات مشاوره تخصصی و رایگان دامپزشکان کنینا استفاده نمایید.',
|
||||||
|
isActive: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
order: 2,
|
||||||
|
question: 'چگونه میتوانم از اصالت مکملهای آلمانی کنینا اطمینان حاصل کنم؟',
|
||||||
|
answer: 'تمامی محصولات کنینا در ایران به صورت ۱۰۰٪ اورجینال و با هولوگرام اصالت، بارکد رسمی کارخانه Canina pharma GmbH آلمان و بچنامبر معتبر عرضه میگردند و اصالت آنها تضمین بالینی و قانونی دارد.',
|
||||||
|
isActive: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
order: 3,
|
||||||
|
question: 'ارسال سفارشها به چه صورت است و چقدر زمان میبرد؟',
|
||||||
|
answer: 'سفارشهای تهران از طریق پیک اختصاصی و اکسپرس در همان روز یا روز بعد و سفارشهای سراسر کشور از طریق پست پیشتاز و تیپاکس ظرف ۲ الی ۴ روز کاری با بستهبندی ایمن و استاندارد تحویل داده میشوند.',
|
||||||
|
isActive: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
order: 4,
|
||||||
|
question: 'شرایط ارسال رایگان سفارشها چیست؟',
|
||||||
|
answer: 'سفارشهای بالای ۲,۰۰۰,۰۰۰ تومان در سراسر کشور مشمول ارسال کاملاً رایگان کنینا خواهند شد.',
|
||||||
|
isActive: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
order: 5,
|
||||||
|
question: 'آیا امکان دریافت مشاوره قبل از خرید مکمل مفاصل یا کلسیم وجود دارد؟',
|
||||||
|
answer: 'بله، شما میتوانید از طریق کلید شناور «درخواست مشاوره تلفنی» در سایت یا شماره تماس پشتیبانی با کارشناسان و کادر دامپزشکی ما گفتگوی مستقیم و رایگان داشته باشید.',
|
||||||
|
isActive: true,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
async function seedRealFaqs() {
|
||||||
|
console.log('--- Seeding Real Customer FAQs ---');
|
||||||
|
for (const item of defaultFaqs) {
|
||||||
|
await prisma.fAQ.create({
|
||||||
|
data: item,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const count = await prisma.fAQ.count();
|
||||||
|
console.log(`Successfully seeded real customer FAQs. Total count: ${count}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
seedRealFaqs()
|
||||||
|
.catch((err) => {
|
||||||
|
console.error('Seed error:', err);
|
||||||
|
process.exit(1);
|
||||||
|
})
|
||||||
|
.finally(async () => {
|
||||||
|
await prisma.$disconnect();
|
||||||
|
});
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
import { PrismaClient } from '@prisma/client';
|
||||||
|
|
||||||
|
const prisma = new PrismaClient();
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
console.log('--- Inspecting and Cleaning FAQs ---');
|
||||||
|
|
||||||
|
const totalBefore = await prisma.fAQ.count();
|
||||||
|
console.log(`Total FAQs before: ${totalBefore}`);
|
||||||
|
|
||||||
|
const activeCount = await prisma.fAQ.count({ where: { isActive: true } });
|
||||||
|
const inactiveCount = await prisma.fAQ.count({ where: { isActive: false } });
|
||||||
|
console.log(`Active FAQs: ${activeCount}, Inactive FAQs: ${inactiveCount}`);
|
||||||
|
|
||||||
|
// Fetch sample of active and inactive
|
||||||
|
const sampleActive = await prisma.fAQ.findMany({
|
||||||
|
where: { isActive: true },
|
||||||
|
select: { id: true, question: true, order: true },
|
||||||
|
take: 5,
|
||||||
|
});
|
||||||
|
console.log('Sample Active FAQs:', JSON.stringify(sampleActive, null, 2));
|
||||||
|
|
||||||
|
// Find tasks that contain content development phrases
|
||||||
|
const tasksToDelete = await prisma.fAQ.findMany({
|
||||||
|
where: {
|
||||||
|
OR: [
|
||||||
|
{ question: { contains: 'راهنمای' } },
|
||||||
|
{ question: { contains: 'اینفوگرافیک' } },
|
||||||
|
{ question: { contains: 'نگارش' } },
|
||||||
|
{ question: { contains: 'تدوین' } },
|
||||||
|
{ question: { contains: 'تولید' } },
|
||||||
|
{ question: { contains: 'مقاله' } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
select: { id: true, question: true, isActive: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log(`Found ${tasksToDelete.length} content tasks inside FAQs table.`);
|
||||||
|
|
||||||
|
if (tasksToDelete.length > 0) {
|
||||||
|
const ids = tasksToDelete.map(t => t.id);
|
||||||
|
const deleteResult = await prisma.fAQ.deleteMany({
|
||||||
|
where: { id: { in: ids } },
|
||||||
|
});
|
||||||
|
console.log(`Successfully deleted ${deleteResult.count} misplaced content tasks from faqs.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const totalAfter = await prisma.fAQ.count();
|
||||||
|
console.log(`Total FAQs remaining: ${totalAfter}`);
|
||||||
|
|
||||||
|
const remaining = await prisma.fAQ.findMany({
|
||||||
|
select: { id: true, question: true, isActive: true, order: true },
|
||||||
|
take: 10,
|
||||||
|
});
|
||||||
|
console.log('Remaining FAQs:', JSON.stringify(remaining, null, 2));
|
||||||
|
}
|
||||||
|
|
||||||
|
main()
|
||||||
|
.catch(e => {
|
||||||
|
console.error(e);
|
||||||
|
process.exit(1);
|
||||||
|
})
|
||||||
|
.finally(async () => {
|
||||||
|
await prisma.$disconnect();
|
||||||
|
});
|
||||||
@@ -1,73 +0,0 @@
|
|||||||
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);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,72 +0,0 @@
|
|||||||
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,7 +7,6 @@ import {
|
|||||||
Body,
|
Body,
|
||||||
Param,
|
Param,
|
||||||
Query,
|
Query,
|
||||||
Req,
|
|
||||||
UseGuards,
|
UseGuards,
|
||||||
BadRequestException,
|
BadRequestException,
|
||||||
} from "@nestjs/common";
|
} from "@nestjs/common";
|
||||||
@@ -28,7 +27,6 @@ import {
|
|||||||
} from "@nestjs/swagger";
|
} from "@nestjs/swagger";
|
||||||
|
|
||||||
import { CreateUserDto, UpdateUserDto } from "./dto/user.dto";
|
import { CreateUserDto, UpdateUserDto } from "./dto/user.dto";
|
||||||
import type { UserAdminActor } from "./user-role-policy";
|
|
||||||
import { SettingsService } from "../settings/settings.service";
|
import { SettingsService } from "../settings/settings.service";
|
||||||
|
|
||||||
import { RolesGuard } from "../common/guards/roles.guard";
|
import { RolesGuard } from "../common/guards/roles.guard";
|
||||||
@@ -59,13 +57,13 @@ export class AdminController {
|
|||||||
@ApiQuery({ name: "search", required: false, description: "جستجو" })
|
@ApiQuery({ name: "search", required: false, description: "جستجو" })
|
||||||
async getUsers(@Query() query: AdminQueryDto) {
|
async getUsers(@Query() query: AdminQueryDto) {
|
||||||
const result = await this.adminService.getUsers(query);
|
const result = await this.adminService.getUsers(query);
|
||||||
return result;
|
return { success: true, ...result };
|
||||||
}
|
}
|
||||||
|
|
||||||
@Post("users")
|
@Post("users")
|
||||||
@ApiOperation({ summary: "ایجاد کاربر جدید توسط ادمین" })
|
@ApiOperation({ summary: "ایجاد کاربر جدید توسط ادمین" })
|
||||||
async createUser(@Body() dto: CreateUserDto, @Req() req?: { user?: UserAdminActor }) {
|
async createUser(@Body() dto: CreateUserDto) {
|
||||||
const user = await this.adminService.createUser(dto, req?.user);
|
const user = await this.adminService.createUser(dto);
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
message: "کاربر جدید با موفقیت ایجاد شد",
|
message: "کاربر جدید با موفقیت ایجاد شد",
|
||||||
@@ -82,8 +80,8 @@ export class AdminController {
|
|||||||
|
|
||||||
@Put("users/:id")
|
@Put("users/:id")
|
||||||
@ApiOperation({ summary: "ویرایش مشخصات کامل کاربر" })
|
@ApiOperation({ summary: "ویرایش مشخصات کامل کاربر" })
|
||||||
async updateUser(@Param("id") id: string, @Body() dto: UpdateUserDto, @Req() req?: { user?: UserAdminActor }) {
|
async updateUser(@Param("id") id: string, @Body() dto: UpdateUserDto) {
|
||||||
const user = await this.adminService.updateUser(id, dto, req?.user);
|
const user = await this.adminService.updateUser(id, dto);
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
message: "اطلاعات کاربر با موفقیت ویرایش شد",
|
message: "اطلاعات کاربر با موفقیت ویرایش شد",
|
||||||
@@ -93,8 +91,8 @@ export class AdminController {
|
|||||||
|
|
||||||
@Delete("users/:id")
|
@Delete("users/:id")
|
||||||
@ApiOperation({ summary: "حذف کاربر و دادههای مرتبط" })
|
@ApiOperation({ summary: "حذف کاربر و دادههای مرتبط" })
|
||||||
async deleteUser(@Param("id") id: string, @Req() req?: { user?: UserAdminActor }) {
|
async deleteUser(@Param("id") id: string) {
|
||||||
await this.adminService.deleteUser(id, req?.user);
|
await this.adminService.deleteUser(id);
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
message: "کاربر با موفقیت از سیستم حذف شد",
|
message: "کاربر با موفقیت از سیستم حذف شد",
|
||||||
@@ -103,8 +101,8 @@ export class AdminController {
|
|||||||
|
|
||||||
@Put("users/:id/role")
|
@Put("users/:id/role")
|
||||||
@ApiOperation({ summary: "تغییر نقش کاربر" })
|
@ApiOperation({ summary: "تغییر نقش کاربر" })
|
||||||
async updateUserRole(@Param("id") id: string, @Body("role") role: string, @Req() req?: { user?: UserAdminActor }) {
|
async updateUserRole(@Param("id") id: string, @Body("role") role: string) {
|
||||||
const user = await this.adminService.updateUserRole(id, role, req?.user);
|
const user = await this.adminService.updateUserRole(id, role);
|
||||||
return { success: true, data: user };
|
return { success: true, data: user };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -115,7 +113,6 @@ export class AdminController {
|
|||||||
@Body("amount") amount: number,
|
@Body("amount") amount: number,
|
||||||
@Body("type") type: "deposit" | "withdrawal" | "refund",
|
@Body("type") type: "deposit" | "withdrawal" | "refund",
|
||||||
@Body("description") description?: string,
|
@Body("description") description?: string,
|
||||||
@Req() req?: { user?: UserAdminActor },
|
|
||||||
) {
|
) {
|
||||||
const numAmount = Number(amount);
|
const numAmount = Number(amount);
|
||||||
if (!numAmount || isNaN(numAmount) || numAmount <= 0) {
|
if (!numAmount || isNaN(numAmount) || numAmount <= 0) {
|
||||||
@@ -133,7 +130,6 @@ export class AdminController {
|
|||||||
numAmount,
|
numAmount,
|
||||||
type,
|
type,
|
||||||
description,
|
description,
|
||||||
req?.user,
|
|
||||||
);
|
);
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
@@ -149,7 +145,7 @@ export class AdminController {
|
|||||||
@ApiQuery({ name: "search", required: false, description: "جستجو" })
|
@ApiQuery({ name: "search", required: false, description: "جستجو" })
|
||||||
async getProducts(@Query() query: AdminQueryDto) {
|
async getProducts(@Query() query: AdminQueryDto) {
|
||||||
const result = await this.adminService.getProducts(query);
|
const result = await this.adminService.getProducts(query);
|
||||||
return result;
|
return { success: true, ...result };
|
||||||
}
|
}
|
||||||
|
|
||||||
@Post("products")
|
@Post("products")
|
||||||
@@ -210,7 +206,7 @@ export class AdminController {
|
|||||||
@ApiQuery({ name: "status", required: false, description: "فیلتر وضعیت" })
|
@ApiQuery({ name: "status", required: false, description: "فیلتر وضعیت" })
|
||||||
async getOrders(@Query() query: AdminQueryDto) {
|
async getOrders(@Query() query: AdminQueryDto) {
|
||||||
const result = await this.adminService.getOrders(query);
|
const result = await this.adminService.getOrders(query);
|
||||||
return result;
|
return { success: true, ...result };
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get("orders/:id")
|
@Get("orders/:id")
|
||||||
@@ -358,34 +354,4 @@ export class AdminController {
|
|||||||
await this.settingsService.updateBulkUiTexts(body);
|
await this.settingsService.updateBulkUiTexts(body);
|
||||||
return { success: true, data: body };
|
return { success: true, data: body };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Get("symptoms")
|
|
||||||
@ApiOperation({ summary: "لیست کامل علائم درمانی با صفحهبندی، جستجو و متادیتا" })
|
|
||||||
async getSymptoms(@Query() query: { page?: number; limit?: number; search?: string }) {
|
|
||||||
const res = await this.adminService.getSymptoms(query);
|
|
||||||
return res;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Post("symptoms")
|
|
||||||
@ApiOperation({ summary: "افزودن علامت درمانی جدید" })
|
|
||||||
async createSymptom(@Body() body: { name: string; slug?: string; description?: string; metaTitle?: string; metaDescription?: string; keywords?: string }) {
|
|
||||||
const res = await this.adminService.createSymptom(body);
|
|
||||||
return { success: true, data: res };
|
|
||||||
}
|
|
||||||
|
|
||||||
@Put("symptoms/:id")
|
|
||||||
@ApiOperation({ summary: "ویرایش کامل علامت درمانی و متادیتاهای سئو" })
|
|
||||||
async updateSymptom(@Param("id") id: string, @Body() body: any) {
|
|
||||||
const res = await this.adminService.updateSymptom(id, body);
|
|
||||||
return { success: true, data: res };
|
|
||||||
}
|
|
||||||
|
|
||||||
@Delete("symptoms/:id")
|
|
||||||
@ApiOperation({ summary: "حذف علامت درمانی" })
|
|
||||||
async deleteSymptom(@Param("id") id: string) {
|
|
||||||
const res = await this.adminService.deleteSymptom(id);
|
|
||||||
return res;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,6 @@
|
|||||||
import { Module } from "@nestjs/common";
|
import { Module } from "@nestjs/common";
|
||||||
|
import { CorporateController } from "./hermes/corporate.controller";
|
||||||
|
import { CorporateService } from "./hermes/corporate.service";
|
||||||
import { AdminController } from "./admin.controller";
|
import { AdminController } from "./admin.controller";
|
||||||
import { AdminService } from "./admin.service";
|
import { AdminService } from "./admin.service";
|
||||||
import { ReportsController } from "./reports.controller";
|
import { ReportsController } from "./reports.controller";
|
||||||
@@ -21,6 +23,9 @@ import { CompetitorPricingController } from "./competitor-pricing.controller";
|
|||||||
import { B2BLeadsController } from "./b2b-leads.controller";
|
import { B2BLeadsController } from "./b2b-leads.controller";
|
||||||
import { PricingSuggestionsController } from "./pricing-suggestions.controller";
|
import { PricingSuggestionsController } from "./pricing-suggestions.controller";
|
||||||
import { SmsCampaignsController } from "./sms-campaigns.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 { PrismaModule } from "../prisma/prisma.module";
|
||||||
import { RedisModule } from "../redis/redis.module";
|
import { RedisModule } from "../redis/redis.module";
|
||||||
import { SettingsModule } from "../settings/settings.module";
|
import { SettingsModule } from "../settings/settings.module";
|
||||||
@@ -30,6 +35,7 @@ import { SupportChatAnalyticsService } from "./support-chat-analytics.service";
|
|||||||
@Module({
|
@Module({
|
||||||
imports: [PrismaModule, RedisModule, SettingsModule],
|
imports: [PrismaModule, RedisModule, SettingsModule],
|
||||||
controllers: [
|
controllers: [
|
||||||
|
CorporateController,
|
||||||
AdminController,
|
AdminController,
|
||||||
ReportsController,
|
ReportsController,
|
||||||
MediaController,
|
MediaController,
|
||||||
@@ -43,9 +49,13 @@ import { SupportChatAnalyticsService } from "./support-chat-analytics.service";
|
|||||||
B2BLeadsController,
|
B2BLeadsController,
|
||||||
PricingSuggestionsController,
|
PricingSuggestionsController,
|
||||||
SmsCampaignsController,
|
SmsCampaignsController,
|
||||||
|
ApprovalsController,
|
||||||
|
AuditLogsController,
|
||||||
|
DepartmentTasksController,
|
||||||
SupportChatAnalyticsController,
|
SupportChatAnalyticsController,
|
||||||
],
|
],
|
||||||
providers: [
|
providers: [
|
||||||
|
CorporateService,
|
||||||
AdminService,
|
AdminService,
|
||||||
ReportsService,
|
ReportsService,
|
||||||
MediaService,
|
MediaService,
|
||||||
|
|||||||
@@ -61,10 +61,15 @@ export class CouponInput {
|
|||||||
targets?: CouponTargetInput[];
|
targets?: CouponTargetInput[];
|
||||||
}
|
}
|
||||||
|
|
||||||
import { ALLOWED_USER_ROLES, assertUserMutationAllowed } from "./user-role-policy";
|
const ALLOWED_USER_ROLES = [
|
||||||
import type { UserAdminActor } from "./user-role-policy";
|
"User_PetOwner",
|
||||||
import { randomUUID } from "crypto";
|
"User_Vet",
|
||||||
import { authorizeStageSession, STAGE_TEST_ID, STAGE_TEST_EMAIL, STAGE_TEST_MOBILE } from "../auth/stage-test-principal";
|
"User_Clinic",
|
||||||
|
"User_PetShop",
|
||||||
|
"Customer",
|
||||||
|
"Admin",
|
||||||
|
"SUPER_ADMIN",
|
||||||
|
];
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class AdminService {
|
export class AdminService {
|
||||||
@@ -163,17 +168,12 @@ export class AdminService {
|
|||||||
skip,
|
skip,
|
||||||
take: limit,
|
take: limit,
|
||||||
orderBy: { [sortField]: sortDirection },
|
orderBy: { [sortField]: sortDirection },
|
||||||
select: {
|
include: {
|
||||||
id: true,
|
|
||||||
firstName: true,
|
|
||||||
lastName: true,
|
|
||||||
mobile: true,
|
|
||||||
email: true,
|
|
||||||
role: true,
|
|
||||||
walletBalance: true,
|
|
||||||
charityDonationTotal: true,
|
|
||||||
createdAt: true,
|
|
||||||
addresses: true,
|
addresses: true,
|
||||||
|
walletTransactions: {
|
||||||
|
orderBy: { createdAt: "desc" },
|
||||||
|
take: 20,
|
||||||
|
},
|
||||||
orders: {
|
orders: {
|
||||||
where: { status: { not: "CANCELLED" } },
|
where: { status: { not: "CANCELLED" } },
|
||||||
select: { totalAmount: true },
|
select: { totalAmount: true },
|
||||||
@@ -197,19 +197,9 @@ export class AdminService {
|
|||||||
(acc, curr) => acc + (Number(curr.totalAmount) || 0),
|
(acc, curr) => acc + (Number(curr.totalAmount) || 0),
|
||||||
0,
|
0,
|
||||||
) || 0;
|
) || 0;
|
||||||
// Explicit response allowlist: never expose authentication fields or
|
const { orders: _orders, ...rest } = u;
|
||||||
// new model columns implicitly through this administrative list.
|
|
||||||
return {
|
return {
|
||||||
id: u.id,
|
...rest,
|
||||||
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,
|
totalSpent,
|
||||||
ordersCount: u._count?.orders || 0,
|
ordersCount: u._count?.orders || 0,
|
||||||
reviewsCount: (u._count?.reviews || 0) + (u._count?.blogComments || 0),
|
reviewsCount: (u._count?.reviews || 0) + (u._count?.blogComments || 0),
|
||||||
@@ -237,12 +227,7 @@ export class AdminService {
|
|||||||
return user;
|
return user;
|
||||||
}
|
}
|
||||||
|
|
||||||
async createUser(dto: CreateUserDto, actor?: UserAdminActor) {
|
async createUser(dto: CreateUserDto) {
|
||||||
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 mobile = normalizeMobile(dto.mobile);
|
||||||
const existingMobile = await this.prisma.user.findUnique({
|
const existingMobile = await this.prisma.user.findUnique({
|
||||||
where: { mobile },
|
where: { mobile },
|
||||||
@@ -275,7 +260,6 @@ export class AdminService {
|
|||||||
|
|
||||||
return this.prisma.user.create({
|
return this.prisma.user.create({
|
||||||
data: {
|
data: {
|
||||||
...(stage ? { id: STAGE_TEST_ID, stageTestGeneration:stage.generation || randomUUID(), stageTestSession: stage.session, authExpiresAt: stage.expiresAt } : {}),
|
|
||||||
firstName: dto.firstName.trim(),
|
firstName: dto.firstName.trim(),
|
||||||
lastName: dto.lastName.trim(),
|
lastName: dto.lastName.trim(),
|
||||||
mobile,
|
mobile,
|
||||||
@@ -290,30 +274,7 @@ export class AdminService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Explicit CI seed authority, NOT a fabricated SUPER_ADMIN actor. Not controller-exposed.
|
async updateUser(id: string, dto: UpdateUserDto) {
|
||||||
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") {
|
if (id === "12345678-1234-1234-1234-123456789012") {
|
||||||
throw new BadRequestException(
|
throw new BadRequestException(
|
||||||
"امکان ویرایش حساب ادمین پیشفرض وجود ندارد",
|
"امکان ویرایش حساب ادمین پیشفرض وجود ندارد",
|
||||||
@@ -325,8 +286,6 @@ export class AdminService {
|
|||||||
throw new NotFoundException(`کاربری با شناسه ${id} یافت نشد`);
|
throw new NotFoundException(`کاربری با شناسه ${id} یافت نشد`);
|
||||||
}
|
}
|
||||||
|
|
||||||
assertUserMutationAllowed(actor, user.role, dto.role);
|
|
||||||
|
|
||||||
const normalizedMobile = dto.mobile
|
const normalizedMobile = dto.mobile
|
||||||
? normalizeMobile(dto.mobile)
|
? normalizeMobile(dto.mobile)
|
||||||
: undefined;
|
: undefined;
|
||||||
@@ -381,11 +340,17 @@ export class AdminService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async updateUserRole(id: string, role: string, actor?: UserAdminActor) {
|
async updateUserRole(id: string, role: string) {
|
||||||
return this.updateUser(id, { role }, actor);
|
if (!ALLOWED_USER_ROLES.includes(role)) {
|
||||||
|
throw new BadRequestException("نقش کاربری مشخص شده نامعتبر است");
|
||||||
|
}
|
||||||
|
return this.prisma.user.update({
|
||||||
|
where: { id },
|
||||||
|
data: { role },
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async deleteUser(id: string, actor?: UserAdminActor) {
|
async deleteUser(id: string) {
|
||||||
if (id === "12345678-1234-1234-1234-123456789012") {
|
if (id === "12345678-1234-1234-1234-123456789012") {
|
||||||
throw new BadRequestException("امکان حذف حساب ادمین پیشفرض وجود ندارد");
|
throw new BadRequestException("امکان حذف حساب ادمین پیشفرض وجود ندارد");
|
||||||
}
|
}
|
||||||
@@ -395,17 +360,7 @@ export class AdminService {
|
|||||||
throw new NotFoundException(`کاربری با شناسه ${id} یافت نشد`);
|
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) => {
|
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.userAddress.deleteMany({ where: { userId: id } });
|
||||||
await tx.walletTransaction.deleteMany({ where: { userId: id } });
|
await tx.walletTransaction.deleteMany({ where: { userId: id } });
|
||||||
await tx.pet.deleteMany({ where: { userId: id } });
|
await tx.pet.deleteMany({ where: { userId: id } });
|
||||||
@@ -1442,15 +1397,12 @@ export class AdminService {
|
|||||||
amount: number,
|
amount: number,
|
||||||
type: "deposit" | "withdrawal" | "refund",
|
type: "deposit" | "withdrawal" | "refund",
|
||||||
description?: string,
|
description?: string,
|
||||||
actor?: UserAdminActor,
|
|
||||||
) {
|
) {
|
||||||
const user = await this.prisma.user.findUnique({ where: { id: userId } });
|
const user = await this.prisma.user.findUnique({ where: { id: userId } });
|
||||||
if (!user) {
|
if (!user) {
|
||||||
throw new NotFoundException(`کاربری با شناسه ${userId} یافت نشد.`);
|
throw new NotFoundException(`کاربری با شناسه ${userId} یافت نشد.`);
|
||||||
}
|
}
|
||||||
|
|
||||||
assertUserMutationAllowed(actor, user.role);
|
|
||||||
|
|
||||||
const transaction = await this.prisma.walletTransaction.create({
|
const transaction = await this.prisma.walletTransaction.create({
|
||||||
data: {
|
data: {
|
||||||
userId,
|
userId,
|
||||||
@@ -1917,164 +1869,4 @@ export class AdminService {
|
|||||||
};
|
};
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async getSymptoms(params?: { page?: number; limit?: number; search?: string }) {
|
|
||||||
const page = Math.max(1, Number(params?.page) || 1);
|
|
||||||
const limit = Math.max(1, Number(params?.limit) || 20);
|
|
||||||
const offset = (page - 1) * limit;
|
|
||||||
const search = params?.search?.trim() || '';
|
|
||||||
|
|
||||||
let items: any[] = [];
|
|
||||||
let total = 0;
|
|
||||||
|
|
||||||
if (search) {
|
|
||||||
const searchPattern = `%${search}%`;
|
|
||||||
const [listResult, countResult] = await Promise.all([
|
|
||||||
this.prisma.$queryRaw<any[]>`
|
|
||||||
SELECT
|
|
||||||
s.id,
|
|
||||||
s.name,
|
|
||||||
s.slug,
|
|
||||||
s.description,
|
|
||||||
s.meta_title as "metaTitle",
|
|
||||||
s.meta_description as "metaDescription",
|
|
||||||
s.keywords,
|
|
||||||
s.icon,
|
|
||||||
s.created_at as "createdAt",
|
|
||||||
COALESCE(COUNT(ps.product_id), 0)::int as "productsCount"
|
|
||||||
FROM symptoms s
|
|
||||||
LEFT JOIN product_symptoms ps ON ps.symptom = s.name
|
|
||||||
WHERE s.name ILIKE ${searchPattern} OR s.slug ILIKE ${searchPattern}
|
|
||||||
GROUP BY s.id, s.name, s.slug, s.description, s.meta_title, s.meta_description, s.keywords, s.icon, s.created_at
|
|
||||||
ORDER BY s.name ASC
|
|
||||||
LIMIT ${limit} OFFSET ${offset};
|
|
||||||
`,
|
|
||||||
this.prisma.$queryRaw<any[]>`
|
|
||||||
SELECT COUNT(*)::int as total
|
|
||||||
FROM symptoms s
|
|
||||||
WHERE s.name ILIKE ${searchPattern} OR s.slug ILIKE ${searchPattern};
|
|
||||||
`,
|
|
||||||
]);
|
|
||||||
items = listResult;
|
|
||||||
total = countResult[0]?.total || 0;
|
|
||||||
} else {
|
|
||||||
const [listResult, countResult] = await Promise.all([
|
|
||||||
this.prisma.$queryRaw<any[]>`
|
|
||||||
SELECT
|
|
||||||
s.id,
|
|
||||||
s.name,
|
|
||||||
s.slug,
|
|
||||||
s.description,
|
|
||||||
s.meta_title as "metaTitle",
|
|
||||||
s.meta_description as "metaDescription",
|
|
||||||
s.keywords,
|
|
||||||
s.icon,
|
|
||||||
s.created_at as "createdAt",
|
|
||||||
COALESCE(COUNT(ps.product_id), 0)::int as "productsCount"
|
|
||||||
FROM symptoms s
|
|
||||||
LEFT JOIN product_symptoms ps ON ps.symptom = s.name
|
|
||||||
GROUP BY s.id, s.name, s.slug, s.description, s.meta_title, s.meta_description, s.keywords, s.icon, s.created_at
|
|
||||||
ORDER BY s.name ASC
|
|
||||||
LIMIT ${limit} OFFSET ${offset};
|
|
||||||
`,
|
|
||||||
this.prisma.$queryRaw<any[]>`
|
|
||||||
SELECT COUNT(*)::int as total
|
|
||||||
FROM symptoms s;
|
|
||||||
`,
|
|
||||||
]);
|
|
||||||
items = listResult;
|
|
||||||
total = countResult[0]?.total || 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
const lastPage = Math.ceil(total / limit) || 1;
|
|
||||||
|
|
||||||
return {
|
|
||||||
data: items,
|
|
||||||
meta: {
|
|
||||||
page,
|
|
||||||
limit,
|
|
||||||
total,
|
|
||||||
lastPage,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
async createSymptom(dto: { name: string; slug?: string; description?: string; metaTitle?: string; metaDescription?: string; keywords?: string }) {
|
|
||||||
if (!dto.name?.trim()) throw new BadRequestException('نام علامت الزامی است');
|
|
||||||
const name = dto.name.trim();
|
|
||||||
const slug = dto.slug?.trim() || name.replace(/\s+/g, '-').toLowerCase();
|
|
||||||
|
|
||||||
return await this.prisma.$queryRawUnsafe(`
|
|
||||||
INSERT INTO symptoms (name, slug, description, meta_title, meta_description, keywords)
|
|
||||||
VALUES ($1, $2, $3, $4, $5, $6)
|
|
||||||
RETURNING id, name, slug, description, meta_title as "metaTitle", meta_description as "metaDescription", keywords;
|
|
||||||
`, name, slug, dto.description || '', dto.metaTitle || '', dto.metaDescription || '', dto.keywords || '');
|
|
||||||
}
|
|
||||||
|
|
||||||
async updateSymptom(id: string, dto: { name?: string; slug?: string; description?: string; metaTitle?: string; metaDescription?: string; keywords?: string }) {
|
|
||||||
// 1. Get existing symptom
|
|
||||||
const existing = await this.prisma.$queryRawUnsafe<any[]>(`SELECT * FROM symptoms WHERE id = $1::uuid LIMIT 1`, id);
|
|
||||||
if (!existing || existing.length === 0) throw new NotFoundException('علامت یافت نشد');
|
|
||||||
const oldName = existing[0].name;
|
|
||||||
const newName = dto.name?.trim() || oldName;
|
|
||||||
const newSlug = dto.slug?.trim() || existing[0].slug;
|
|
||||||
|
|
||||||
return await this.prisma.$transaction(async (tx) => {
|
|
||||||
// Update symptoms table
|
|
||||||
const updated = await tx.$queryRawUnsafe(`
|
|
||||||
UPDATE symptoms
|
|
||||||
SET
|
|
||||||
name = $2,
|
|
||||||
slug = $3,
|
|
||||||
description = $4,
|
|
||||||
meta_title = $5,
|
|
||||||
meta_description = $6,
|
|
||||||
keywords = $7,
|
|
||||||
updated_at = CURRENT_TIMESTAMP
|
|
||||||
WHERE id = $1::uuid
|
|
||||||
RETURNING id, name, slug, description, meta_title as "metaTitle", meta_description as "metaDescription", keywords;
|
|
||||||
`, id, newName, newSlug, dto.description ?? existing[0].description, dto.metaTitle ?? existing[0].meta_title, dto.metaDescription ?? existing[0].meta_description, dto.keywords ?? existing[0].keywords);
|
|
||||||
|
|
||||||
// If name changed, cascade update across product_symptoms & products JSON
|
|
||||||
if (oldName !== newName) {
|
|
||||||
await tx.$executeRaw`UPDATE product_symptoms SET symptom = ${newName} WHERE symptom = ${oldName};`;
|
|
||||||
await tx.$executeRaw`
|
|
||||||
UPDATE products
|
|
||||||
SET dosage_config = jsonb_set(
|
|
||||||
dosage_config,
|
|
||||||
'{symptoms}',
|
|
||||||
(
|
|
||||||
SELECT jsonb_agg(
|
|
||||||
CASE
|
|
||||||
WHEN elem::text = to_jsonb(${oldName}::text)::text THEN to_jsonb(${newName}::text)
|
|
||||||
ELSE elem
|
|
||||||
END
|
|
||||||
)
|
|
||||||
FROM jsonb_array_elements(dosage_config->'symptoms') AS elem
|
|
||||||
)
|
|
||||||
)
|
|
||||||
WHERE dosage_config ? 'symptoms'
|
|
||||||
AND dosage_config->'symptoms' @> to_jsonb(${oldName}::text);
|
|
||||||
`;
|
|
||||||
}
|
|
||||||
|
|
||||||
return updated;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async deleteSymptom(id: string) {
|
|
||||||
const existing = await this.prisma.$queryRawUnsafe<any[]>(`SELECT * FROM symptoms WHERE id = $1::uuid LIMIT 1`, id);
|
|
||||||
if (!existing || existing.length === 0) throw new NotFoundException('علامت یافت نشد');
|
|
||||||
const name = existing[0].name;
|
|
||||||
|
|
||||||
return await this.prisma.$transaction(async (tx) => {
|
|
||||||
// Delete join links
|
|
||||||
await tx.$executeRaw`DELETE FROM product_symptoms WHERE symptom = ${name};`;
|
|
||||||
// Delete symptom row
|
|
||||||
await tx.$queryRawUnsafe(`DELETE FROM symptoms WHERE id = $1::uuid;`, id);
|
|
||||||
return { success: true, message: `علامت «${name}» با موفقیت حذف شد` };
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,219 @@
|
|||||||
|
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") {
|
||||||
|
// 5. رد توسط مدیرعامل: تسک و درخواست کلاً از سیستم پاکسازی کامل میشوند
|
||||||
|
await (this.prisma as any).departmentTask.deleteMany({
|
||||||
|
where: { approvalId: id },
|
||||||
|
});
|
||||||
|
await (this.prisma as any).approvalRequest.delete({
|
||||||
|
where: { id },
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: "درخواست با موفقیت رد و از سیستم پاکسازی شد.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1. تایید مدیرعامل: وضعیت درخواست APPROVED و وضعیت تسک در صف اقدام به TODO تغییر مییابد
|
||||||
|
const updated = await (this.prisma as any).approvalRequest.update({
|
||||||
|
where: { id },
|
||||||
|
data: {
|
||||||
|
status: "APPROVED",
|
||||||
|
ceoNotes: dto.ceoNotes || null,
|
||||||
|
executedAt: new Date(),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// جستجو یا ایجاد تسک متناظر با استاتوس 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,
|
||||||
|
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" };
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
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 };
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,117 +0,0 @@
|
|||||||
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");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -229,15 +229,6 @@ describe("BlogsController (Admin)", () => {
|
|||||||
expect(result).toEqual({ success: true, data: createdBlog });
|
expect(result).toEqual({ success: true, data: createdBlog });
|
||||||
});
|
});
|
||||||
|
|
||||||
it("propagates create validation failures", async () => {
|
|
||||||
const req = { user: { id: "admin-user-id" } };
|
|
||||||
const body = { title: "Bad date", contentUpdatedAt: "invalid", createdAt: "2000-01-01" };
|
|
||||||
mockBlogsService.createBlog.mockRejectedValueOnce(new Error("Invalid contentUpdatedAt"));
|
|
||||||
|
|
||||||
await expect(controller.createBlog(body, req)).rejects.toThrow("Invalid contentUpdatedAt");
|
|
||||||
expect(service.createBlog).toHaveBeenCalledWith(body, req.user.id);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("updateBlog should update blog details and return success: true", async () => {
|
it("updateBlog should update blog details and return success: true", async () => {
|
||||||
const blogId = "blog-10";
|
const blogId = "blog-10";
|
||||||
const body = {
|
const body = {
|
||||||
@@ -253,14 +244,6 @@ describe("BlogsController (Admin)", () => {
|
|||||||
expect(result).toEqual({ success: true, data: updatedBlog });
|
expect(result).toEqual({ success: true, data: updatedBlog });
|
||||||
});
|
});
|
||||||
|
|
||||||
it("propagates invalid content timestamp rejection without accepting createdAt", async () => {
|
|
||||||
const body = { contentUpdatedAt: "invalid", createdAt: "2000-01-01" };
|
|
||||||
mockBlogsService.updateBlog.mockRejectedValueOnce(new Error("Invalid contentUpdatedAt"));
|
|
||||||
|
|
||||||
await expect(controller.updateBlog("blog-10", body)).rejects.toThrow("Invalid contentUpdatedAt");
|
|
||||||
expect(service.updateBlog).toHaveBeenCalledWith("blog-10", body);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("deleteBlog should delete blog and return success: true", async () => {
|
it("deleteBlog should delete blog and return success: true", async () => {
|
||||||
const blogId = "blog-10";
|
const blogId = "blog-10";
|
||||||
mockBlogsService.deleteBlog.mockResolvedValue(undefined);
|
mockBlogsService.deleteBlog.mockResolvedValue(undefined);
|
||||||
|
|||||||
@@ -54,8 +54,6 @@ describe("Admin BlogsService", () => {
|
|||||||
}).compile();
|
}).compile();
|
||||||
|
|
||||||
service = module.get<BlogsService>(BlogsService);
|
service = module.get<BlogsService>(BlogsService);
|
||||||
mockRevalidationService.revalidateBlog.mockReset();
|
|
||||||
mockRevalidationService.revalidateBlog.mockResolvedValue(true);
|
|
||||||
jest.clearAllMocks();
|
jest.clearAllMocks();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -202,54 +200,7 @@ describe("Admin BlogsService", () => {
|
|||||||
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith(
|
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith(
|
||||||
"new-health-post",
|
"new-health-post",
|
||||||
);
|
);
|
||||||
expect(result).toEqual({
|
expect(result).toEqual(createdBlog);
|
||||||
...createdBlog,
|
|
||||||
cacheRevalidation: "success",
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("allowlists create fields and blocks server-owned and unknown fields", async () => {
|
|
||||||
mockPrisma.blog.create.mockResolvedValue({ id: "created", slug: "safe-post" });
|
|
||||||
|
|
||||||
await service.createBlog(
|
|
||||||
{
|
|
||||||
title: "Safe post",
|
|
||||||
slug: "safe-post",
|
|
||||||
content: "Safe content",
|
|
||||||
id: "client-id",
|
|
||||||
createdAt: "2000-01-01T00:00:00.000Z",
|
|
||||||
updatedAt: "2000-01-01T00:00:00.000Z",
|
|
||||||
viewCount: 999999,
|
|
||||||
serverOwned: "must-not-pass",
|
|
||||||
},
|
|
||||||
"user-admin-1",
|
|
||||||
);
|
|
||||||
|
|
||||||
const payload = mockPrisma.blog.create.mock.calls[0][0].data;
|
|
||||||
expect(payload).toEqual(expect.objectContaining({
|
|
||||||
title: "Safe post",
|
|
||||||
slug: "safe-post",
|
|
||||||
content: "Safe content",
|
|
||||||
}));
|
|
||||||
expect(payload).not.toHaveProperty("id");
|
|
||||||
expect(payload).not.toHaveProperty("createdAt");
|
|
||||||
expect(payload).not.toHaveProperty("updatedAt");
|
|
||||||
expect(payload).not.toHaveProperty("viewCount");
|
|
||||||
expect(payload).not.toHaveProperty("serverOwned");
|
|
||||||
});
|
|
||||||
|
|
||||||
it.each([
|
|
||||||
["contentUpdatedAt", { contentUpdatedAt: "not-a-date" }, "Invalid contentUpdatedAt"],
|
|
||||||
["publishedAt", { publishedAt: "not-a-date" }, "Invalid publishedAt"],
|
|
||||||
["scheduledAt", { scheduledAt: "not-a-date" }, "Invalid scheduledAt"],
|
|
||||||
])("rejects invalid explicit %s", async (_field, timestamps, message) => {
|
|
||||||
await expect(
|
|
||||||
service.createBlog(
|
|
||||||
{ title: "Bad date", slug: "bad-date", content: "Content", ...timestamps },
|
|
||||||
"user-admin-1",
|
|
||||||
),
|
|
||||||
).rejects.toThrow(message);
|
|
||||||
expect(mockPrisma.blog.create).not.toHaveBeenCalled();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should create a SCHEDULED blog if scheduledAt is in the future", async () => {
|
it("should create a SCHEDULED blog if scheduledAt is in the future", async () => {
|
||||||
@@ -277,66 +228,6 @@ 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", () => {
|
describe("updateBlog", () => {
|
||||||
@@ -379,136 +270,7 @@ describe("Admin BlogsService", () => {
|
|||||||
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith(
|
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith(
|
||||||
"my-post",
|
"my-post",
|
||||||
);
|
);
|
||||||
expect(result).toEqual({
|
expect(result).toEqual(updated);
|
||||||
...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",
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("material freshness and scheduled publishing", () => {
|
|
||||||
it("sets contentUpdatedAt intentionally and never rewrites createdAt", async () => {
|
|
||||||
mockPrisma.blog.findUnique.mockResolvedValue({ id: "b1", slug: "post", createdAt: new Date("2025-01-01") });
|
|
||||||
mockPrisma.blog.update.mockResolvedValue({ id: "b1", slug: "post" });
|
|
||||||
await service.updateBlog("b1", { title: "Material edit", markContentUpdated: true });
|
|
||||||
const payload = mockPrisma.blog.update.mock.calls[0][0].data;
|
|
||||||
expect(payload.contentUpdatedAt).toEqual(expect.any(Date));
|
|
||||||
expect(payload).not.toHaveProperty("markContentUpdated");
|
|
||||||
expect(payload).not.toHaveProperty("createdAt");
|
|
||||||
});
|
|
||||||
it("automatically marks freshness when material article content changes", async () => {
|
|
||||||
mockPrisma.blog.findUnique.mockResolvedValue({ id: "b1", slug: "post", content: "Old content" });
|
|
||||||
mockPrisma.blog.update.mockResolvedValue({ id: "b1", slug: "post" });
|
|
||||||
await service.updateBlog("b1", { content: "Meaningfully revised content" });
|
|
||||||
expect(mockPrisma.blog.update.mock.calls[0][0].data.contentUpdatedAt).toEqual(expect.any(Date));
|
|
||||||
});
|
|
||||||
it("does not mark freshness for attribution-only changes", async () => {
|
|
||||||
mockPrisma.blog.findUnique.mockResolvedValue({ id: "b1", slug: "post", content: "Same content" });
|
|
||||||
mockPrisma.blog.update.mockResolvedValue({ id: "b1", slug: "post" });
|
|
||||||
await service.updateBlog("b1", { authorTeam: "Clinical team", authorRole: "Review" });
|
|
||||||
expect(mockPrisma.blog.update.mock.calls[0][0].data).not.toHaveProperty("contentUpdatedAt");
|
|
||||||
});
|
|
||||||
it("allows explicitly clearing contentUpdatedAt", async () => {
|
|
||||||
mockPrisma.blog.findUnique.mockResolvedValue({ id: "b1", slug: "post" });
|
|
||||||
mockPrisma.blog.update.mockResolvedValue({ id: "b1", slug: "post" });
|
|
||||||
await service.updateBlog("b1", { contentUpdatedAt: null });
|
|
||||||
expect(mockPrisma.blog.update.mock.calls[0][0].data.contentUpdatedAt).toBeNull();
|
|
||||||
});
|
|
||||||
it("publishes due posts without rewriting createdAt", async () => {
|
|
||||||
const scheduledAt = new Date("2025-02-01T10:00:00Z");
|
|
||||||
mockPrisma.blog.findMany.mockResolvedValue([{ id: "b1", slug: "post", title: "Post", scheduledAt }]);
|
|
||||||
mockPrisma.blog.update.mockResolvedValue({});
|
|
||||||
await service.publishDueScheduledBlogs();
|
|
||||||
expect(mockPrisma.blog.update).toHaveBeenCalledWith({ where: { id: "b1" }, data: { status: "PUBLISHED", isPublished: true, publishedAt: scheduledAt } });
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("updateBlog security and freshness validation", () => {
|
|
||||||
beforeEach(() => {
|
|
||||||
mockPrisma.blog.findUnique.mockResolvedValue({ id: "blog-1", slug: "safe" });
|
|
||||||
mockPrisma.blog.update.mockResolvedValue({ id: "blog-1", slug: "safe" });
|
|
||||||
});
|
|
||||||
|
|
||||||
it("allowlists mutable fields and ignores createdAt and unrecognized fields", async () => {
|
|
||||||
await service.updateBlog("blog-1", {
|
|
||||||
title: "Allowed title",
|
|
||||||
createdAt: "2000-01-01T00:00:00.000Z",
|
|
||||||
serverOwned: "must-not-pass",
|
|
||||||
});
|
|
||||||
|
|
||||||
const payload = mockPrisma.blog.update.mock.calls[0][0].data;
|
|
||||||
expect(payload.title).toBe("Allowed title");
|
|
||||||
expect(payload).not.toHaveProperty("createdAt");
|
|
||||||
expect(payload).not.toHaveProperty("serverOwned");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("rejects an invalid explicit contentUpdatedAt", async () => {
|
|
||||||
await expect(
|
|
||||||
service.updateBlog("blog-1", { contentUpdatedAt: "not-a-date" }),
|
|
||||||
).rejects.toThrow("Invalid contentUpdatedAt");
|
|
||||||
expect(mockPrisma.blog.update).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("preserves explicit null clearing and markContentUpdated precedence", async () => {
|
|
||||||
await service.updateBlog("blog-1", { contentUpdatedAt: null });
|
|
||||||
expect(mockPrisma.blog.update.mock.calls[0][0].data.contentUpdatedAt).toBeNull();
|
|
||||||
|
|
||||||
await service.updateBlog("blog-1", {
|
|
||||||
contentUpdatedAt: "not-a-date",
|
|
||||||
markContentUpdated: true,
|
|
||||||
});
|
|
||||||
expect(mockPrisma.blog.update.mock.calls[1][0].data.contentUpdatedAt).toEqual(expect.any(Date));
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -706,6 +468,7 @@ describe("Admin BlogsService", () => {
|
|||||||
status: "PUBLISHED",
|
status: "PUBLISHED",
|
||||||
isPublished: true,
|
isPublished: true,
|
||||||
publishedAt: scheduledDate,
|
publishedAt: scheduledDate,
|
||||||
|
createdAt: scheduledDate,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith(
|
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith(
|
||||||
|
|||||||
@@ -1,6 +1,4 @@
|
|||||||
import {
|
import {
|
||||||
BadRequestException,
|
|
||||||
ConflictException,
|
|
||||||
Injectable,
|
Injectable,
|
||||||
NotFoundException,
|
NotFoundException,
|
||||||
OnModuleInit,
|
OnModuleInit,
|
||||||
@@ -143,31 +141,16 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
|||||||
|
|
||||||
async createBlog(data: any, currentUserId: string) {
|
async createBlog(data: any, currentUserId: string) {
|
||||||
const {
|
const {
|
||||||
|
tags,
|
||||||
tagNames,
|
tagNames,
|
||||||
categoryId,
|
categoryId,
|
||||||
authorId,
|
authorId,
|
||||||
publishedAt,
|
publishedAt,
|
||||||
scheduledAt,
|
scheduledAt,
|
||||||
readingTime,
|
readingTime,
|
||||||
markContentUpdated,
|
...rest
|
||||||
contentUpdatedAt,
|
|
||||||
} = data;
|
} = data;
|
||||||
|
|
||||||
const parseOptionalDate = (value: unknown, field: string): Date | null => {
|
|
||||||
if (value === undefined || value === null || value === "") return null;
|
|
||||||
const parsed = new Date(value as string | number | Date);
|
|
||||||
if (!Number.isFinite(parsed.getTime())) {
|
|
||||||
throw new BadRequestException(`Invalid ${field}`);
|
|
||||||
}
|
|
||||||
return parsed;
|
|
||||||
};
|
|
||||||
|
|
||||||
const parsedPublishedAt = parseOptionalDate(publishedAt, "publishedAt");
|
|
||||||
const parsedScheduledAt = parseOptionalDate(scheduledAt, "scheduledAt");
|
|
||||||
const parsedContentUpdatedAt = markContentUpdated
|
|
||||||
? new Date()
|
|
||||||
: parseOptionalDate(contentUpdatedAt, "contentUpdatedAt");
|
|
||||||
|
|
||||||
// Connect or create tags
|
// Connect or create tags
|
||||||
const tagConnectOrCreate = [];
|
const tagConnectOrCreate = [];
|
||||||
if (Array.isArray(tagNames) && tagNames.length > 0) {
|
if (Array.isArray(tagNames) && tagNames.length > 0) {
|
||||||
@@ -188,12 +171,13 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
|||||||
|
|
||||||
const targetAuthorId = authorId || currentUserId;
|
const targetAuthorId = authorId || currentUserId;
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
|
const parsedScheduledAt = scheduledAt ? new Date(scheduledAt) : null;
|
||||||
const isFutureSchedule = parsedScheduledAt && parsedScheduledAt > now;
|
const isFutureSchedule = parsedScheduledAt && parsedScheduledAt > now;
|
||||||
|
|
||||||
let finalStatus = data.status || "PUBLISHED";
|
let finalStatus = rest.status || "PUBLISHED";
|
||||||
let finalIsPublished =
|
let finalIsPublished =
|
||||||
data.isPublished !== undefined ? data.isPublished : true;
|
rest.isPublished !== undefined ? rest.isPublished : true;
|
||||||
let finalPublishedAt = parsedPublishedAt;
|
let finalPublishedAt = publishedAt ? new Date(publishedAt) : null;
|
||||||
|
|
||||||
if (isFutureSchedule) {
|
if (isFutureSchedule) {
|
||||||
finalStatus = "SCHEDULED";
|
finalStatus = "SCHEDULED";
|
||||||
@@ -207,45 +191,19 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
|||||||
finalPublishedAt = now;
|
finalPublishedAt = now;
|
||||||
}
|
}
|
||||||
|
|
||||||
const createPayload = {
|
const createPayload: Prisma.BlogCreateInput = {
|
||||||
title: data.title,
|
...rest,
|
||||||
slug: data.slug,
|
|
||||||
content: data.content,
|
|
||||||
excerpt: data.excerpt,
|
|
||||||
authorTeam: data.authorTeam,
|
|
||||||
authorRole: data.authorRole,
|
|
||||||
imageUrl: data.imageUrl,
|
|
||||||
imageAlt: data.imageAlt,
|
|
||||||
imageCaption: data.imageCaption,
|
|
||||||
metaTitle: data.metaTitle,
|
|
||||||
metaDescription: data.metaDescription,
|
|
||||||
keywords: data.keywords,
|
|
||||||
focusKeywords: data.focusKeywords,
|
|
||||||
canonicalUrl: data.canonicalUrl,
|
|
||||||
noIndex: data.noIndex,
|
|
||||||
noFollow: data.noFollow,
|
|
||||||
schemaType: data.schemaType,
|
|
||||||
ogTitle: data.ogTitle,
|
|
||||||
ogDescription: data.ogDescription,
|
|
||||||
ogImage: data.ogImage,
|
|
||||||
status: finalStatus,
|
status: finalStatus,
|
||||||
isPublished: finalIsPublished,
|
isPublished: finalIsPublished,
|
||||||
featured: data.featured,
|
readingTime: readingTime ? Number(readingTime) : 3,
|
||||||
allowComments: data.allowComments,
|
|
||||||
showOnHome: data.showOnHome,
|
|
||||||
homeDisplayMode: data.homeDisplayMode,
|
|
||||||
relatedProductIds: data.relatedProductIds,
|
|
||||||
relatedBlogIds: data.relatedBlogIds,
|
|
||||||
readingTime: readingTime !== undefined ? Number(readingTime) : 3,
|
|
||||||
publishedAt: finalPublishedAt,
|
publishedAt: finalPublishedAt,
|
||||||
scheduledAt: parsedScheduledAt,
|
scheduledAt: parsedScheduledAt,
|
||||||
contentUpdatedAt: parsedContentUpdatedAt,
|
|
||||||
author: { connect: { id: targetAuthorId } },
|
author: { connect: { id: targetAuthorId } },
|
||||||
...(categoryId ? { category: { connect: { id: categoryId } } } : {}),
|
...(categoryId ? { category: { connect: { id: categoryId } } } : {}),
|
||||||
...(tagConnectOrCreate.length > 0
|
...(tagConnectOrCreate.length > 0
|
||||||
? { tags: { connectOrCreate: tagConnectOrCreate } }
|
? { tags: { connectOrCreate: tagConnectOrCreate } }
|
||||||
: {}),
|
: {}),
|
||||||
} satisfies Prisma.BlogCreateInput;
|
};
|
||||||
|
|
||||||
const created = await this.prisma.blog.create({
|
const created = await this.prisma.blog.create({
|
||||||
data: createPayload,
|
data: createPayload,
|
||||||
@@ -256,21 +214,8 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
let cacheRevalidation: "success" | "failed" = "failed";
|
await this.revalidationService.revalidateBlog(created.slug);
|
||||||
try {
|
return created;
|
||||||
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) {
|
async updateBlog(id: string, data: any) {
|
||||||
@@ -278,105 +223,19 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
|||||||
if (!blog) throw new NotFoundException("Blog not found");
|
if (!blog) throw new NotFoundException("Blog not found");
|
||||||
|
|
||||||
const {
|
const {
|
||||||
|
tags,
|
||||||
tagNames,
|
tagNames,
|
||||||
categoryId,
|
categoryId,
|
||||||
authorId,
|
authorId,
|
||||||
publishedAt,
|
publishedAt,
|
||||||
scheduledAt,
|
scheduledAt,
|
||||||
readingTime,
|
readingTime,
|
||||||
markContentUpdated,
|
...rest
|
||||||
contentUpdatedAt,
|
|
||||||
expectedUpdatedAt,
|
|
||||||
} = data;
|
} = 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",
|
|
||||||
"content",
|
|
||||||
"excerpt",
|
|
||||||
"authorTeam",
|
|
||||||
"authorRole",
|
|
||||||
"imageUrl",
|
|
||||||
"imageAlt",
|
|
||||||
"imageCaption",
|
|
||||||
"metaTitle",
|
|
||||||
"metaDescription",
|
|
||||||
"keywords",
|
|
||||||
"focusKeywords",
|
|
||||||
"canonicalUrl",
|
|
||||||
"noIndex",
|
|
||||||
"noFollow",
|
|
||||||
"schemaType",
|
|
||||||
"ogTitle",
|
|
||||||
"ogDescription",
|
|
||||||
"ogImage",
|
|
||||||
"status",
|
|
||||||
"isPublished",
|
|
||||||
"featured",
|
|
||||||
"allowComments",
|
|
||||||
"showOnHome",
|
|
||||||
"homeDisplayMode",
|
|
||||||
"relatedProductIds",
|
|
||||||
"relatedBlogIds",
|
|
||||||
] as const;
|
|
||||||
const updatePayload: Prisma.BlogUpdateInput = {};
|
|
||||||
for (const field of mutableScalarFields) {
|
|
||||||
if (data[field] !== undefined) {
|
|
||||||
(updatePayload as Record<string, unknown>)[field] = data[field];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
const materialContentFields = [
|
const updatePayload: Prisma.BlogUpdateInput = {
|
||||||
"title",
|
...rest,
|
||||||
"content",
|
|
||||||
"excerpt",
|
|
||||||
"imageUrl",
|
|
||||||
"imageAlt",
|
|
||||||
"imageCaption",
|
|
||||||
] as const;
|
|
||||||
const hasMaterialContentChange = materialContentFields.some(
|
|
||||||
(field) => data[field] !== undefined && data[field] !== blog[field],
|
|
||||||
);
|
|
||||||
if (markContentUpdated || (contentUpdatedAt === undefined && hasMaterialContentChange)) {
|
|
||||||
(updatePayload as Record<string, unknown>).contentUpdatedAt = now;
|
|
||||||
} else if (contentUpdatedAt !== undefined) {
|
|
||||||
if (contentUpdatedAt === null || contentUpdatedAt === "") {
|
|
||||||
(updatePayload as Record<string, unknown>).contentUpdatedAt = null;
|
|
||||||
} else {
|
|
||||||
const parsedContentUpdatedAt = new Date(contentUpdatedAt);
|
|
||||||
if (!Number.isFinite(parsedContentUpdatedAt.getTime())) {
|
|
||||||
throw new BadRequestException("Invalid contentUpdatedAt");
|
|
||||||
}
|
|
||||||
(updatePayload as Record<string, unknown>).contentUpdatedAt = parsedContentUpdatedAt;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Object.assign(updatePayload, {
|
|
||||||
...(readingTime !== undefined
|
|
||||||
? { readingTime: Number(readingTime) }
|
|
||||||
: {}),
|
|
||||||
...(readingTime !== undefined
|
...(readingTime !== undefined
|
||||||
? { readingTime: Number(readingTime) }
|
? { readingTime: Number(readingTime) }
|
||||||
: {}),
|
: {}),
|
||||||
@@ -386,7 +245,7 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
|||||||
? { category: { connect: { id: categoryId } } }
|
? { category: { connect: { id: categoryId } } }
|
||||||
: { category: { disconnect: true } }
|
: { category: { disconnect: true } }
|
||||||
: {}),
|
: {}),
|
||||||
});
|
};
|
||||||
|
|
||||||
if (scheduledAt !== undefined) {
|
if (scheduledAt !== undefined) {
|
||||||
const parsedScheduledAt = scheduledAt ? new Date(scheduledAt) : null;
|
const parsedScheduledAt = scheduledAt ? new Date(scheduledAt) : null;
|
||||||
@@ -400,6 +259,7 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
|||||||
updatePayload.status = "PUBLISHED";
|
updatePayload.status = "PUBLISHED";
|
||||||
updatePayload.isPublished = true;
|
updatePayload.isPublished = true;
|
||||||
updatePayload.publishedAt = parsedScheduledAt;
|
updatePayload.publishedAt = parsedScheduledAt;
|
||||||
|
updatePayload.createdAt = parsedScheduledAt;
|
||||||
}
|
}
|
||||||
} else if (publishedAt !== undefined) {
|
} else if (publishedAt !== undefined) {
|
||||||
updatePayload.publishedAt = publishedAt ? new Date(publishedAt) : null;
|
updatePayload.publishedAt = publishedAt ? new Date(publishedAt) : null;
|
||||||
@@ -426,68 +286,25 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const include = {
|
const updated = await this.prisma.blog.update({
|
||||||
author: { select: { firstName: true, lastName: true } },
|
where: { id },
|
||||||
category: true,
|
data: updatePayload,
|
||||||
tags: true,
|
include: {
|
||||||
};
|
author: { select: { firstName: true, lastName: true } },
|
||||||
// Legacy UI requests without a token intentionally retain last-write-wins.
|
category: true,
|
||||||
// Guarded requests claim the row using a DB predicate, not the earlier read.
|
tags: true,
|
||||||
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,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
let cacheRevalidation: "success" | "failed" = "failed";
|
await this.revalidationService.revalidateBlog(updated.slug);
|
||||||
try {
|
return updated;
|
||||||
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) {
|
async deleteBlog(id: string) {
|
||||||
const blog = await this.prisma.blog.findUnique({ where: { id } });
|
const blog = await this.prisma.blog.findUnique({ where: { id } });
|
||||||
if (!blog) throw new NotFoundException("Blog not found");
|
if (!blog) throw new NotFoundException("Blog not found");
|
||||||
const res = await this.prisma.blog.delete({ where: { id } });
|
const res = await this.prisma.blog.delete({ where: { id } });
|
||||||
try {
|
await this.revalidationService.revalidateBlog(blog.slug);
|
||||||
await this.revalidationService.revalidateBlog(blog.slug);
|
|
||||||
} catch (err: any) {
|
|
||||||
this.logger.warn(
|
|
||||||
`Cache revalidation failed for deleted blog [${blog.slug}]: ${err?.message}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -655,6 +472,7 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
|||||||
status: "PUBLISHED",
|
status: "PUBLISHED",
|
||||||
isPublished: true,
|
isPublished: true,
|
||||||
publishedAt: publishDate,
|
publishedAt: publishDate,
|
||||||
|
createdAt: publishDate,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,208 @@
|
|||||||
|
import {
|
||||||
|
Controller,
|
||||||
|
Get,
|
||||||
|
Post,
|
||||||
|
Put,
|
||||||
|
Delete,
|
||||||
|
Body,
|
||||||
|
Param,
|
||||||
|
Query,
|
||||||
|
UseGuards,
|
||||||
|
NotFoundException,
|
||||||
|
} 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 - Department & Agent Tasks")
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||||
|
@Roles("Admin", "SUPER_ADMIN")
|
||||||
|
@Controller("admin/department-tasks")
|
||||||
|
export class DepartmentTasksController {
|
||||||
|
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) {
|
||||||
|
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`);
|
||||||
|
|
||||||
|
const logs = Array.isArray(existing.executionLogs) ? [...existing.executionLogs] : [];
|
||||||
|
if (body.logNote) {
|
||||||
|
logs.push({
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
status: body.status,
|
||||||
|
note: body.logNote,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
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();
|
||||||
|
// اگر تست QA ناموفق بود و به TODO برگشت، لاگ اصلاح ضمیمه میشود
|
||||||
|
if (body.status === "TODO" && body.logNote) {
|
||||||
|
updateData.description = (existing.description || "") + "\n\n[اصلاحات و تضمین کیفیت QA]: " + body.logNote;
|
||||||
|
}
|
||||||
|
|
||||||
|
const updated = await (this.prisma as any).departmentTask.update({
|
||||||
|
where: { id },
|
||||||
|
data: updateData,
|
||||||
|
});
|
||||||
|
|
||||||
|
// ثبت در تاریخچه
|
||||||
|
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" };
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class QueryApprovalDto {
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
department?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
category?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
status?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
page?: number;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
limit?: number;
|
||||||
|
}
|
||||||
@@ -5,12 +5,9 @@ import {
|
|||||||
IsEmail,
|
IsEmail,
|
||||||
MinLength,
|
MinLength,
|
||||||
IsNumber,
|
IsNumber,
|
||||||
IsIn,
|
|
||||||
} from "class-validator";
|
} from "class-validator";
|
||||||
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||||
|
|
||||||
import { ALLOWED_USER_ROLES } from "../user-role-policy";
|
|
||||||
|
|
||||||
export class CreateUserDto {
|
export class CreateUserDto {
|
||||||
@ApiProperty({ description: "نام کاربر", example: "علی" })
|
@ApiProperty({ description: "نام کاربر", example: "علی" })
|
||||||
@IsNotEmpty({ message: "نام الزامی است" })
|
@IsNotEmpty({ message: "نام الزامی است" })
|
||||||
@@ -44,7 +41,6 @@ export class CreateUserDto {
|
|||||||
@ApiPropertyOptional({ description: "نقش کاربر", example: "User_PetOwner" })
|
@ApiPropertyOptional({ description: "نقش کاربر", example: "User_PetOwner" })
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsString()
|
@IsString()
|
||||||
@IsIn(ALLOWED_USER_ROLES)
|
|
||||||
role?: string;
|
role?: string;
|
||||||
|
|
||||||
@ApiPropertyOptional({ description: "موجودی اولیه کیف پول", example: 0 })
|
@ApiPropertyOptional({ description: "موجودی اولیه کیف پول", example: 0 })
|
||||||
@@ -89,7 +85,6 @@ export class UpdateUserDto {
|
|||||||
@ApiPropertyOptional({ description: "نقش کاربر", example: "User_PetOwner" })
|
@ApiPropertyOptional({ description: "نقش کاربر", example: "User_PetOwner" })
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsString()
|
@IsString()
|
||||||
@IsIn(ALLOWED_USER_ROLES)
|
|
||||||
role?: string;
|
role?: string;
|
||||||
|
|
||||||
@ApiPropertyOptional({ description: "موجودی کیف پول", example: 500000 })
|
@ApiPropertyOptional({ description: "موجودی کیف پول", example: 500000 })
|
||||||
|
|||||||
@@ -0,0 +1,69 @@
|
|||||||
|
import {
|
||||||
|
normalizeSearch,
|
||||||
|
pagination,
|
||||||
|
taskInput,
|
||||||
|
monthlyPlanInput,
|
||||||
|
} from './corporate-policy';
|
||||||
|
describe('corporate contract policy', () => {
|
||||||
|
it.each([
|
||||||
|
['2027-02', 28],
|
||||||
|
['2028-02', 29],
|
||||||
|
['2028-04', 30],
|
||||||
|
['2028-01', 31],
|
||||||
|
])('enforces real calendar coverage for %s', (month, count) => {
|
||||||
|
const id = '11111111-1111-4111-8111-111111111111';
|
||||||
|
const body = {
|
||||||
|
roadmapId: id,
|
||||||
|
month,
|
||||||
|
needs: [],
|
||||||
|
dailyArticles: Array.from({ length: Number(count) }, (_, i) => ({
|
||||||
|
title: 'new article',
|
||||||
|
description: 'instruction',
|
||||||
|
actionType: 'BLOG_NEW',
|
||||||
|
department: 'CONTENT_SEO',
|
||||||
|
goalId: id,
|
||||||
|
sourceIds: [id],
|
||||||
|
dueCycle: `${month}-${String(i + 1).padStart(2, '0')}`,
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
expect(monthlyPlanInput(body).dailyArticles).toHaveLength(Number(count));
|
||||||
|
expect(() =>
|
||||||
|
monthlyPlanInput({ ...body, dailyArticles: body.dailyArticles.slice(1) }),
|
||||||
|
).toThrow();
|
||||||
|
expect(() =>
|
||||||
|
monthlyPlanInput({
|
||||||
|
...body,
|
||||||
|
dailyArticles: [...body.dailyArticles, body.dailyArticles[0]],
|
||||||
|
}),
|
||||||
|
).toThrow();
|
||||||
|
});
|
||||||
|
it('normalizes Persian letters, digits and separators', () => {
|
||||||
|
expect(normalizeSearch('كيك ۱۲۳ (ة)')).toBe('کیک 123 ه');
|
||||||
|
});
|
||||||
|
it('bounds pagination and sort keys', () => {
|
||||||
|
expect(pagination({ limit: '100' }).limit).toBe(100);
|
||||||
|
expect(() => pagination({ limit: '101' })).toThrow();
|
||||||
|
expect(() => pagination({ page: '-1' })).toThrow();
|
||||||
|
expect(() => pagination({ sortBy: 'password' })).toThrow();
|
||||||
|
});
|
||||||
|
it('defaults CEO priority and rejects status/command injection', () => {
|
||||||
|
expect(
|
||||||
|
taskInput({
|
||||||
|
title: 'عنوان',
|
||||||
|
description: 'کار',
|
||||||
|
department: 'CONTENT_SEO',
|
||||||
|
}).priority,
|
||||||
|
).toBe('CEO_EXPEDITE');
|
||||||
|
expect(() =>
|
||||||
|
taskInput({
|
||||||
|
title: 'x',
|
||||||
|
description: 'x',
|
||||||
|
department: 'CONTENT_SEO',
|
||||||
|
status: 'DONE',
|
||||||
|
}),
|
||||||
|
).toThrow();
|
||||||
|
expect(() =>
|
||||||
|
taskInput({ title: '', description: 'x', department: 'CONTENT_SEO' }),
|
||||||
|
).toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,317 @@
|
|||||||
|
import { BadRequestException } from '@nestjs/common';
|
||||||
|
export const departments = [
|
||||||
|
'CONTENT_SEO',
|
||||||
|
'CATALOG_COMMERCE',
|
||||||
|
'WIKI_SCIENTIFIC',
|
||||||
|
'TECH_DEVOPS',
|
||||||
|
'MARKET_INTELLIGENCE',
|
||||||
|
];
|
||||||
|
export const priorities = ['CEO_EXPEDITE', 'CRITICAL', 'HIGH', 'MEDIUM', 'LOW'];
|
||||||
|
export const statuses = [
|
||||||
|
'TODO',
|
||||||
|
'IN_PROGRESS',
|
||||||
|
'TEST',
|
||||||
|
'DONE',
|
||||||
|
'BLOCKED',
|
||||||
|
'REJECTED',
|
||||||
|
'CANCELLED',
|
||||||
|
];
|
||||||
|
export function object(value: unknown, keys: string[]): Record<string, any> {
|
||||||
|
if (
|
||||||
|
!value ||
|
||||||
|
typeof value !== 'object' ||
|
||||||
|
Array.isArray(value) ||
|
||||||
|
Object.keys(value).some((k) => !keys.includes(k))
|
||||||
|
)
|
||||||
|
throw new BadRequestException('Invalid fields');
|
||||||
|
return value as Record<string, any>;
|
||||||
|
}
|
||||||
|
export function text(value: unknown, max = 10000): string {
|
||||||
|
if (typeof value !== 'string' || !value.trim() || value.length > max)
|
||||||
|
throw new BadRequestException('Invalid text');
|
||||||
|
return value.trim();
|
||||||
|
}
|
||||||
|
export function uuid(value: unknown): string {
|
||||||
|
const id = text(value, 36);
|
||||||
|
if (
|
||||||
|
!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(
|
||||||
|
id,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
throw new BadRequestException('Invalid UUID');
|
||||||
|
return id.toLowerCase();
|
||||||
|
}
|
||||||
|
export function choice(value: unknown, values: string[]): string {
|
||||||
|
if (typeof value !== 'string' || !values.includes(value))
|
||||||
|
throw new BadRequestException('Invalid enum');
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
export function normalizeSearch(value: string): string {
|
||||||
|
return value
|
||||||
|
.normalize('NFKC')
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/[يى]/g, 'ی')
|
||||||
|
.replace(/ك/g, 'ک')
|
||||||
|
.replace(/ة/g, 'ه')
|
||||||
|
.replace(/[۰-۹٠-٩]/g, (c) =>
|
||||||
|
String(
|
||||||
|
'۰۱۲۳۴۵۶۷۸۹'.includes(c)
|
||||||
|
? '۰۱۲۳۴۵۶۷۸۹'.indexOf(c)
|
||||||
|
: '٠١٢٣٤٥٦٧٨٩'.indexOf(c),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.replace(/[\u200c\u200d()()]/g, ' ')
|
||||||
|
.replace(/[\u064b-\u065f]/g, '')
|
||||||
|
.replace(/\s+/g, ' ')
|
||||||
|
.trim();
|
||||||
|
}
|
||||||
|
export function pagination(q: Record<string, any>) {
|
||||||
|
const page = Number(q.page ?? 1),
|
||||||
|
limit = Number(q.limit ?? 20);
|
||||||
|
if (
|
||||||
|
!Number.isSafeInteger(page) ||
|
||||||
|
page < 1 ||
|
||||||
|
page > 1000000 ||
|
||||||
|
!Number.isInteger(limit) ||
|
||||||
|
limit < 1 ||
|
||||||
|
limit > 100
|
||||||
|
)
|
||||||
|
throw new BadRequestException('Invalid pagination');
|
||||||
|
const sortBy = choice(q.sortBy ?? 'createdAt', [
|
||||||
|
'createdAt',
|
||||||
|
'updatedAt',
|
||||||
|
'title',
|
||||||
|
'taskCode',
|
||||||
|
'priority',
|
||||||
|
'status',
|
||||||
|
]);
|
||||||
|
const sortOrder = choice(q.sortOrder ?? 'desc', ['asc', 'desc']) as
|
||||||
|
| 'asc'
|
||||||
|
| 'desc';
|
||||||
|
return { page, limit, skip: (page - 1) * limit, sortBy, sortOrder };
|
||||||
|
}
|
||||||
|
export function meta(total: number, page: number, limit: number) {
|
||||||
|
const totalPages = Math.ceil(total / limit);
|
||||||
|
return {
|
||||||
|
total,
|
||||||
|
page,
|
||||||
|
limit,
|
||||||
|
totalPages,
|
||||||
|
hasNextPage: page < totalPages,
|
||||||
|
hasPrevPage: page > 1,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
export function taskInput(input: unknown) {
|
||||||
|
const b = object(input, [
|
||||||
|
'title',
|
||||||
|
'department',
|
||||||
|
'description',
|
||||||
|
'priority',
|
||||||
|
'parentId',
|
||||||
|
'goalId',
|
||||||
|
'actionType',
|
||||||
|
'dueCycle',
|
||||||
|
]);
|
||||||
|
return {
|
||||||
|
title: text(b.title, 300),
|
||||||
|
description: text(b.description),
|
||||||
|
department: choice(b.department, departments),
|
||||||
|
priority: choice(b.priority ?? 'CEO_EXPEDITE', priorities),
|
||||||
|
parentId: b.parentId === undefined ? undefined : uuid(b.parentId),
|
||||||
|
goalId: b.goalId === undefined ? undefined : uuid(b.goalId),
|
||||||
|
actionType: choice(b.actionType ?? 'CEO_DIRECTIVE', [
|
||||||
|
'CEO_DIRECTIVE',
|
||||||
|
'BLOG_NEW',
|
||||||
|
'BLOG_UPDATE',
|
||||||
|
'CATALOG_ENRICH',
|
||||||
|
'WIKI_ENRICH',
|
||||||
|
'RESEARCH',
|
||||||
|
'ENGINEERING',
|
||||||
|
]),
|
||||||
|
dueCycle: b.dueCycle === undefined ? undefined : text(b.dueCycle, 40),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
export function planMonth(value: unknown): string {
|
||||||
|
const month = text(value, 7);
|
||||||
|
if (!/^(?:[2-9]\d{3})-(?:0[1-9]|1[0-2])$/.test(month))
|
||||||
|
throw new BadRequestException('Invalid YYYY-MM month');
|
||||||
|
return month;
|
||||||
|
}
|
||||||
|
export function monthlyPlanInput(input: unknown) {
|
||||||
|
const b = object(input, ['roadmapId', 'month', 'dailyArticles', 'needs']);
|
||||||
|
const month = planMonth(b.month);
|
||||||
|
const days = new Date(
|
||||||
|
Date.UTC(Number(month.slice(0, 4)), Number(month.slice(5)), 0),
|
||||||
|
).getUTCDate();
|
||||||
|
if (
|
||||||
|
!Array.isArray(b.dailyArticles) ||
|
||||||
|
b.dailyArticles.length !== days ||
|
||||||
|
!Array.isArray(b.needs) ||
|
||||||
|
b.needs.length > 200
|
||||||
|
)
|
||||||
|
throw new BadRequestException(
|
||||||
|
'Full daily article coverage and bounded needs required',
|
||||||
|
);
|
||||||
|
const mapping: Record<string, string> = {
|
||||||
|
BLOG_NEW: 'CONTENT_SEO',
|
||||||
|
BLOG_UPDATE: 'CONTENT_SEO',
|
||||||
|
CATALOG_ENRICH: 'CATALOG_COMMERCE',
|
||||||
|
WIKI_ENRICH: 'WIKI_SCIENTIFIC',
|
||||||
|
ENGINEERING: 'TECH_DEVOPS',
|
||||||
|
};
|
||||||
|
const parse = (raw: unknown, daily: boolean) => {
|
||||||
|
const t = object(raw, [
|
||||||
|
'title',
|
||||||
|
'description',
|
||||||
|
'department',
|
||||||
|
'priority',
|
||||||
|
'goalId',
|
||||||
|
'actionType',
|
||||||
|
'dueCycle',
|
||||||
|
'sourceIds',
|
||||||
|
'target',
|
||||||
|
'reason',
|
||||||
|
]);
|
||||||
|
const actionType = choice(
|
||||||
|
t.actionType,
|
||||||
|
daily
|
||||||
|
? ['BLOG_NEW']
|
||||||
|
: ['BLOG_UPDATE', 'CATALOG_ENRICH', 'WIKI_ENRICH', 'ENGINEERING'],
|
||||||
|
);
|
||||||
|
const department = choice(t.department, [mapping[actionType]]);
|
||||||
|
const dueCycle = text(t.dueCycle, 10);
|
||||||
|
const date = new Date(dueCycle + 'T00:00:00Z');
|
||||||
|
if (
|
||||||
|
!/^\d{4}-\d{2}-\d{2}$/.test(dueCycle) ||
|
||||||
|
!dueCycle.startsWith(month + '-') ||
|
||||||
|
!Number.isFinite(date.getTime()) ||
|
||||||
|
date.toISOString().slice(0, 10) !== dueCycle
|
||||||
|
)
|
||||||
|
throw new BadRequestException('Invalid plan day');
|
||||||
|
if (
|
||||||
|
!Array.isArray(t.sourceIds) ||
|
||||||
|
!t.sourceIds.length ||
|
||||||
|
t.sourceIds.length > 30
|
||||||
|
)
|
||||||
|
throw new BadRequestException('Stored sources required');
|
||||||
|
const sourceIds = t.sourceIds.map(uuid);
|
||||||
|
if (new Set(sourceIds).size !== sourceIds.length)
|
||||||
|
throw new BadRequestException('Duplicate source');
|
||||||
|
if (daily && (t.target !== undefined || t.reason !== undefined))
|
||||||
|
throw new BadRequestException('Daily new articles cannot be needs');
|
||||||
|
return {
|
||||||
|
title: text(t.title, 300),
|
||||||
|
description: text(t.description),
|
||||||
|
department,
|
||||||
|
actionType,
|
||||||
|
dueCycle,
|
||||||
|
priority: choice(t.priority ?? 'MEDIUM', priorities),
|
||||||
|
goalId: uuid(t.goalId),
|
||||||
|
sourceIds,
|
||||||
|
...(daily
|
||||||
|
? {}
|
||||||
|
: { target: text(t.target, 2000), reason: text(t.reason) }),
|
||||||
|
};
|
||||||
|
};
|
||||||
|
const dailyArticles = b.dailyArticles.map((t) => parse(t, true));
|
||||||
|
if (new Set(dailyArticles.map((t) => t.dueCycle)).size !== days)
|
||||||
|
throw new BadRequestException(
|
||||||
|
'Exactly one new article per calendar day required',
|
||||||
|
);
|
||||||
|
const needs = b.needs.map((t) => parse(t, false));
|
||||||
|
if (
|
||||||
|
new Set(needs.map((t) => canonical([t.actionType, t.target, t.dueCycle])))
|
||||||
|
.size !== needs.length
|
||||||
|
)
|
||||||
|
throw new BadRequestException('Duplicate need');
|
||||||
|
return { roadmapId: uuid(b.roadmapId), month, dailyArticles, needs };
|
||||||
|
}
|
||||||
|
export function canonical(value: any): string {
|
||||||
|
if (Array.isArray(value)) return '[' + value.map(canonical).join(',') + ']';
|
||||||
|
if (value && typeof value === 'object')
|
||||||
|
return (
|
||||||
|
'{' +
|
||||||
|
Object.keys(value)
|
||||||
|
.sort()
|
||||||
|
.map((k) => JSON.stringify(k) + ':' + canonical(value[k]))
|
||||||
|
.join(',') +
|
||||||
|
'}'
|
||||||
|
);
|
||||||
|
return JSON.stringify(value);
|
||||||
|
}
|
||||||
|
/** Public projection must also cover nested evidence and child records. */
|
||||||
|
export function publicData(value: any): any {
|
||||||
|
if (value instanceof Date) return value;
|
||||||
|
if (Array.isArray(value)) return value.map(publicData);
|
||||||
|
if (value && typeof value === 'object')
|
||||||
|
return Object.fromEntries(
|
||||||
|
Object.entries(value)
|
||||||
|
.filter(([key]) => key !== 'claimToken')
|
||||||
|
.map(([key, item]) => [key, publicData(item)]),
|
||||||
|
);
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
export function httpsUrl(value: unknown): string {
|
||||||
|
const raw = text(value, 2000);
|
||||||
|
try {
|
||||||
|
if (!/^https:\/\/[a-z0-9]/i.test(raw) || /[\s\\]/.test(raw))
|
||||||
|
throw new Error();
|
||||||
|
const u = new URL(raw);
|
||||||
|
const host = u.hostname.toLowerCase();
|
||||||
|
if (
|
||||||
|
u.protocol !== 'https:' ||
|
||||||
|
u.username ||
|
||||||
|
u.password ||
|
||||||
|
!/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/.test(host) ||
|
||||||
|
host === 'localhost' ||
|
||||||
|
host.endsWith('.localhost') ||
|
||||||
|
/(^|\.)example\.(com|org|net)$/.test(host)
|
||||||
|
)
|
||||||
|
throw new Error();
|
||||||
|
return raw;
|
||||||
|
} catch {
|
||||||
|
throw new BadRequestException('Valid HTTPS host URL required');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
export function timestamp(value: unknown, message: string): Date {
|
||||||
|
if (
|
||||||
|
typeof value !== 'string' ||
|
||||||
|
!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/.test(value)
|
||||||
|
)
|
||||||
|
throw new BadRequestException(message);
|
||||||
|
const date = new Date(value);
|
||||||
|
if (
|
||||||
|
!Number.isFinite(date.getTime()) ||
|
||||||
|
date.getTime() > Date.now() ||
|
||||||
|
date.toISOString().slice(0, 19) !== value.slice(0, 19)
|
||||||
|
)
|
||||||
|
throw new BadRequestException(message);
|
||||||
|
return date;
|
||||||
|
}
|
||||||
|
export function evidenceInput(input: unknown) {
|
||||||
|
const b = object(input, [
|
||||||
|
'claimToken',
|
||||||
|
'artifactUri',
|
||||||
|
'sha256',
|
||||||
|
'summary',
|
||||||
|
'tool',
|
||||||
|
'result',
|
||||||
|
]);
|
||||||
|
const uri = text(b.artifactUri, 2000);
|
||||||
|
|
||||||
|
const sha = text(b.sha256, 64);
|
||||||
|
if (!/^[a-f0-9]{64}$/.test(sha))
|
||||||
|
throw new BadRequestException('Invalid digest');
|
||||||
|
if (uri.startsWith('urn:')) {
|
||||||
|
if (uri !== 'urn:sha256:' + sha)
|
||||||
|
throw new BadRequestException('Digest locator mismatch');
|
||||||
|
} else httpsUrl(uri);
|
||||||
|
return {
|
||||||
|
claimToken: uuid(b.claimToken),
|
||||||
|
artifactUri: uri,
|
||||||
|
sha256: sha,
|
||||||
|
summary: text(b.summary),
|
||||||
|
tool: text(b.tool, 100),
|
||||||
|
result: text(b.result),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
import {
|
||||||
|
Body,
|
||||||
|
Controller,
|
||||||
|
Get,
|
||||||
|
Headers,
|
||||||
|
Param,
|
||||||
|
Post,
|
||||||
|
Query,
|
||||||
|
Req,
|
||||||
|
UnauthorizedException,
|
||||||
|
UseGuards,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { JwtAuthGuard } from '../../auth/jwt-auth.guard';
|
||||||
|
import { RolesGuard } from '../../common/guards/roles.guard';
|
||||||
|
import { Roles } from '../../common/decorators/roles.decorator';
|
||||||
|
import { CorporateService } from './corporate.service';
|
||||||
|
import { randomUUID } from 'crypto';
|
||||||
|
import { text } from './corporate-policy';
|
||||||
|
|
||||||
|
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||||
|
@Roles('Admin', 'SUPER_ADMIN')
|
||||||
|
@Controller('admin/hermes')
|
||||||
|
export class CorporateController {
|
||||||
|
constructor(private readonly service: CorporateService) {}
|
||||||
|
private actor(req: any) {
|
||||||
|
// API keys must use their authenticated key identity, not an editable worker label.
|
||||||
|
const user = req.user;
|
||||||
|
const id = user?.id ?? user?.sub;
|
||||||
|
if (!id) throw new UnauthorizedException('Authenticated subject required');
|
||||||
|
return (user.isApiKey ? 'apikey:' : 'user:') + text(String(id), 200);
|
||||||
|
}
|
||||||
|
private key(key?: string) {
|
||||||
|
return text(key, 200);
|
||||||
|
}
|
||||||
|
@Get('runtime') runtime() {
|
||||||
|
return {
|
||||||
|
mode: 'MANUAL_DORMANT',
|
||||||
|
schedulesEnabled: false,
|
||||||
|
externalExecutionEnabled: false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
@Get('tasks') tasks(@Query() query: Record<string, any>) {
|
||||||
|
return this.service.tasks(query);
|
||||||
|
}
|
||||||
|
@Get('tasks/:id') detail(@Param('id') id: string) {
|
||||||
|
return this.service.detail(id);
|
||||||
|
}
|
||||||
|
@Post('tasks') create(
|
||||||
|
@Req() req: any,
|
||||||
|
@Headers('idempotency-key') key: string,
|
||||||
|
@Body() body: unknown,
|
||||||
|
) {
|
||||||
|
return this.service.create(this.actor(req), key ?? randomUUID(), body);
|
||||||
|
}
|
||||||
|
@Post('claims') claim(
|
||||||
|
@Req() req: any,
|
||||||
|
@Headers('idempotency-key') key: string,
|
||||||
|
@Body() body: unknown,
|
||||||
|
) {
|
||||||
|
return this.service.claim(this.actor(req), this.key(key), body);
|
||||||
|
}
|
||||||
|
@Post('tasks/:id/evidence') evidence(
|
||||||
|
@Req() req: any,
|
||||||
|
@Headers('idempotency-key') key: string,
|
||||||
|
@Param('id') id: string,
|
||||||
|
@Body() body: unknown,
|
||||||
|
) {
|
||||||
|
return this.service.submitEvidence(
|
||||||
|
this.actor(req),
|
||||||
|
this.key(key),
|
||||||
|
id,
|
||||||
|
body,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
@Post('tasks/:id/reviews') review(
|
||||||
|
@Req() req: any,
|
||||||
|
@Headers('idempotency-key') key: string,
|
||||||
|
@Param('id') id: string,
|
||||||
|
@Body() body: unknown,
|
||||||
|
) {
|
||||||
|
return this.service.review(this.actor(req), this.key(key), id, body);
|
||||||
|
}
|
||||||
|
@Post('tasks/:id/effects') effect(
|
||||||
|
@Req() req: any,
|
||||||
|
@Headers('idempotency-key') key: string,
|
||||||
|
@Param('id') id: string,
|
||||||
|
@Body() body: unknown,
|
||||||
|
) {
|
||||||
|
return this.service.effect(this.actor(req), this.key(key), id, body);
|
||||||
|
}
|
||||||
|
@Get('market-insights') insights(@Query() q: Record<string, any>) {
|
||||||
|
return this.service.collection('market-insights', q);
|
||||||
|
}
|
||||||
|
@Post('market-insights') research(
|
||||||
|
@Req() req: any,
|
||||||
|
@Headers('idempotency-key') key: string,
|
||||||
|
@Body() body: unknown,
|
||||||
|
) {
|
||||||
|
return this.service.research(this.actor(req), this.key(key), body);
|
||||||
|
}
|
||||||
|
@Get('monthly-roadmap') roadmaps(@Query() q: Record<string, any>) {
|
||||||
|
return this.service.collection('monthly-roadmap', q);
|
||||||
|
}
|
||||||
|
@Post('monthly-roadmap') roadmap(
|
||||||
|
@Req() req: any,
|
||||||
|
@Headers('idempotency-key') key: string,
|
||||||
|
@Body() body: unknown,
|
||||||
|
) {
|
||||||
|
return this.service.roadmap(this.actor(req), this.key(key), body);
|
||||||
|
}
|
||||||
|
@Post('monthly-plans') persistMonthlyPlan(
|
||||||
|
@Req() req: any,
|
||||||
|
@Headers('idempotency-key') key: string,
|
||||||
|
@Body() body: unknown,
|
||||||
|
) {
|
||||||
|
return this.service.persistMonthlyPlan(
|
||||||
|
this.actor(req),
|
||||||
|
this.key(key),
|
||||||
|
body,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
@Get('monthly-plans/:roadmapId') monthlyPlan(
|
||||||
|
@Param('roadmapId') roadmapId: string,
|
||||||
|
@Query('month') month: string,
|
||||||
|
) {
|
||||||
|
return this.service.monthlyPlan(roadmapId, month);
|
||||||
|
}
|
||||||
|
@Get('reports') reports(@Query() q: Record<string, any>) {
|
||||||
|
return this.service.collection('reports', q);
|
||||||
|
}
|
||||||
|
@Post('reports') report(
|
||||||
|
@Req() req: any,
|
||||||
|
@Headers('idempotency-key') key: string,
|
||||||
|
@Body() body: unknown,
|
||||||
|
) {
|
||||||
|
return this.service.report(this.actor(req), this.key(key), body);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,840 @@
|
|||||||
|
import passport from 'passport';
|
||||||
|
import { Strategy, ExtractJwt } from 'passport-jwt';
|
||||||
|
import { PrismaClient } from '@prisma/client';
|
||||||
|
import { Test } from '@nestjs/testing';
|
||||||
|
import { INestApplication, ValidationPipe } from '@nestjs/common';
|
||||||
|
import { randomUUID } from 'crypto';
|
||||||
|
import request from 'supertest';
|
||||||
|
import { PrismaService } from '../../prisma/prisma.service';
|
||||||
|
import { CorporateController } from './corporate.controller';
|
||||||
|
import { CorporateService } from './corporate.service';
|
||||||
|
import { ApiKeysService } from '../api-keys.service';
|
||||||
|
|
||||||
|
const integration = process.env.CORPORATE_TEST_DATABASE_URL
|
||||||
|
? describe
|
||||||
|
: describe.skip;
|
||||||
|
integration('corporate API / disposable PostgreSQL', () => {
|
||||||
|
let app: INestApplication, db: PrismaService;
|
||||||
|
const key = () => randomUUID();
|
||||||
|
const post = (path: string, body: any, actor = 'executor', op = key()) =>
|
||||||
|
request(app.getHttpServer())
|
||||||
|
.post('/admin/hermes/' + path)
|
||||||
|
.set('x-api-key', actor)
|
||||||
|
.set('Idempotency-Key', op)
|
||||||
|
.send(body);
|
||||||
|
const input = {
|
||||||
|
title: 'كيك ۱۲۳',
|
||||||
|
description: 'integration fixture',
|
||||||
|
department: 'CONTENT_SEO',
|
||||||
|
};
|
||||||
|
beforeAll(async () => {
|
||||||
|
// Explicit disposable loopback opt-in only; never consumes runtime DATABASE_URL.
|
||||||
|
const url = new URL(process.env.CORPORATE_TEST_DATABASE_URL!);
|
||||||
|
if (url.hostname !== '127.0.0.1' || url.pathname !== '/corporate_test')
|
||||||
|
throw new Error('Disposable loopback corporate_test DB required');
|
||||||
|
passport.use(
|
||||||
|
'jwt',
|
||||||
|
new Strategy(
|
||||||
|
{
|
||||||
|
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||||
|
secretOrKey: 'test-only-not-runtime',
|
||||||
|
},
|
||||||
|
(_payload, done) => done(null, false),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
db = new PrismaClient({
|
||||||
|
datasources: { db: { url: process.env.CORPORATE_TEST_DATABASE_URL } },
|
||||||
|
}) as PrismaService;
|
||||||
|
const module = await Test.createTestingModule({
|
||||||
|
controllers: [CorporateController],
|
||||||
|
providers: [
|
||||||
|
CorporateService,
|
||||||
|
{ provide: PrismaService, useValue: db },
|
||||||
|
{
|
||||||
|
provide: ApiKeysService,
|
||||||
|
useValue: {
|
||||||
|
validateKey: async (id: string) => ({
|
||||||
|
id,
|
||||||
|
isApiKey: true,
|
||||||
|
role: 'Admin',
|
||||||
|
scopes: id === 'unscoped' ? [] : ['admin'],
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}).compile();
|
||||||
|
app = module.createNestApplication();
|
||||||
|
app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true }));
|
||||||
|
await app.listen(0, '127.0.0.1');
|
||||||
|
});
|
||||||
|
afterAll(async () => {
|
||||||
|
if (db)
|
||||||
|
await db.$executeRawUnsafe(
|
||||||
|
'TRUNCATE corporate_operations, corporate_reports, corporate_effects, corporate_reviews, corporate_evidence, corporate_events, corporate_tasks, corporate_goals, corporate_roadmaps, corporate_sources, corporate_research CASCADE',
|
||||||
|
);
|
||||||
|
await app?.close();
|
||||||
|
await db?.$disconnect();
|
||||||
|
passport.unuse('jwt');
|
||||||
|
});
|
||||||
|
beforeEach(async () => {
|
||||||
|
await db.$executeRawUnsafe(
|
||||||
|
'TRUNCATE corporate_operations, corporate_reports, corporate_effects, corporate_reviews, corporate_evidence, corporate_events, corporate_tasks, corporate_goals, corporate_roadmaps, corporate_sources, corporate_research CASCADE',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
async function planFixture(month = '2996-02') {
|
||||||
|
const research = (
|
||||||
|
await post('market-insights', {
|
||||||
|
title: 'monthly fixture',
|
||||||
|
category: 'TREND',
|
||||||
|
source: 'disposable receipt',
|
||||||
|
opportunity: 'test planning',
|
||||||
|
impact: 'LOW',
|
||||||
|
recommendedAction: 'plan',
|
||||||
|
cadence: 'MONTHLY',
|
||||||
|
provenance: {
|
||||||
|
method: 'fixture',
|
||||||
|
collector: 'jest',
|
||||||
|
context: 'disposable',
|
||||||
|
},
|
||||||
|
sources: [
|
||||||
|
{
|
||||||
|
url: 'https://pubmed.ncbi.nlm.nih.gov/',
|
||||||
|
title: 'fixture',
|
||||||
|
excerpt: 'test only',
|
||||||
|
retrievedAt: '2026-01-01T00:00:00Z',
|
||||||
|
sha256: 'a'.repeat(64),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}).expect(201)
|
||||||
|
).body;
|
||||||
|
const roadmap = (
|
||||||
|
await post('monthly-roadmap', {
|
||||||
|
researchId: research.id,
|
||||||
|
month,
|
||||||
|
cycleName: 'monthly fixture',
|
||||||
|
seasonalTheme: 'test',
|
||||||
|
strategicGoals: ['coverage'],
|
||||||
|
plannedArticlesCount: 29,
|
||||||
|
plannedRefreshesCount: 0,
|
||||||
|
plannedCatalogEnrichments: 0,
|
||||||
|
goals: [
|
||||||
|
'CONTENT_SEO',
|
||||||
|
'CATALOG_COMMERCE',
|
||||||
|
'WIKI_SCIENTIFIC',
|
||||||
|
'TECH_DEVOPS',
|
||||||
|
].map((department) => ({
|
||||||
|
title: department,
|
||||||
|
department,
|
||||||
|
acceptanceCriteria: 'independent QA',
|
||||||
|
metric: 'coverage',
|
||||||
|
})),
|
||||||
|
}).expect(201)
|
||||||
|
).body;
|
||||||
|
const task = (
|
||||||
|
actionType: string,
|
||||||
|
department: string,
|
||||||
|
dueCycle: string,
|
||||||
|
) => ({
|
||||||
|
title: actionType + ' ' + dueCycle,
|
||||||
|
description: 'Evidence-backed instruction requiring QA',
|
||||||
|
actionType,
|
||||||
|
department,
|
||||||
|
dueCycle,
|
||||||
|
goalId: roadmap.goals.find((g: any) => g.department === department).id,
|
||||||
|
sourceIds: [research.sources[0].id],
|
||||||
|
...(actionType === 'BLOG_NEW'
|
||||||
|
? {}
|
||||||
|
: {
|
||||||
|
target: 'https://canina.ir/identified-gap',
|
||||||
|
reason: 'Documented coverage gap',
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
research,
|
||||||
|
roadmap,
|
||||||
|
body: {
|
||||||
|
roadmapId: roadmap.id,
|
||||||
|
month,
|
||||||
|
dailyArticles: Array.from({ length: 29 }, (_, i) =>
|
||||||
|
task(
|
||||||
|
'BLOG_NEW',
|
||||||
|
'CONTENT_SEO',
|
||||||
|
`${month}-${String(i + 1).padStart(2, '0')}`,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
needs: [
|
||||||
|
task('BLOG_UPDATE', 'CONTENT_SEO', month + '-01'),
|
||||||
|
task('CATALOG_ENRICH', 'CATALOG_COMMERCE', month + '-02'),
|
||||||
|
task('WIKI_ENRICH', 'WIKI_SCIENTIFIC', month + '-03'),
|
||||||
|
task('ENGINEERING', 'TECH_DEVOPS', month + '-04'),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
it('persists a complete leap-month daily-new plan, separate needs and evidence lineage with readback', async () => {
|
||||||
|
const { body, research, roadmap } = await planFixture();
|
||||||
|
body.roadmapId = body.roadmapId.toUpperCase();
|
||||||
|
for (const entry of [...body.dailyArticles, ...body.needs]) {
|
||||||
|
entry.goalId = entry.goalId.toUpperCase();
|
||||||
|
entry.sourceIds = entry.sourceIds.map((id: string) => id.toUpperCase());
|
||||||
|
}
|
||||||
|
const op = key();
|
||||||
|
const created = (
|
||||||
|
await post('monthly-plans', body, 'planner', op).expect(201)
|
||||||
|
).body;
|
||||||
|
expect(created.tasks).toHaveLength(33);
|
||||||
|
const need = created.tasks.find((t: any) => t.actionType === 'WIKI_ENRICH');
|
||||||
|
expect(need.logs[0].payload).toMatchObject({
|
||||||
|
target: body.needs[2].target,
|
||||||
|
reason: body.needs[2].reason,
|
||||||
|
});
|
||||||
|
expect(
|
||||||
|
created.tasks.filter((t: any) => t.actionType === 'BLOG_NEW'),
|
||||||
|
).toHaveLength(29);
|
||||||
|
expect(created.tasks.every((t: any) => t.status === 'TODO')).toBe(true);
|
||||||
|
expect(
|
||||||
|
(await post('monthly-plans', body, 'planner', op).expect(201)).body,
|
||||||
|
).toEqual(created);
|
||||||
|
const read = await request(app.getHttpServer())
|
||||||
|
.get(`/admin/hermes/monthly-plans/${roadmap.id.toUpperCase()}?month=${body.month}`)
|
||||||
|
.set('x-api-key', 'executor')
|
||||||
|
.expect(200);
|
||||||
|
expect(read.body).toEqual(created);
|
||||||
|
const detail = await request(app.getHttpServer())
|
||||||
|
.get('/admin/hermes/tasks/' + created.tasks[0].id)
|
||||||
|
.set('x-api-key', 'executor')
|
||||||
|
.expect(200);
|
||||||
|
expect(detail.body.logs[0].step).toBe('PLANNED');
|
||||||
|
expect(detail.body.logs[0].payload).toMatchObject({
|
||||||
|
researchId: research.id,
|
||||||
|
roadmapId: roadmap.id,
|
||||||
|
month: body.month,
|
||||||
|
dueCycle: body.month + '-01',
|
||||||
|
sourceIds: [research.sources[0].id],
|
||||||
|
});
|
||||||
|
expect(await db.corporateOperation.count()).toBe(3);
|
||||||
|
expect((await post('claims', {}).expect(201)).body.task).toBeNull();
|
||||||
|
});
|
||||||
|
it('validates calendar, action separation, needs and stored lineage without partial writes', async () => {
|
||||||
|
const { body } = await planFixture();
|
||||||
|
const mutations: Array<[number, (b: any) => void]> = [
|
||||||
|
[400, (b) => b.dailyArticles.pop()],
|
||||||
|
[400, (b) => (b.dailyArticles[1].dueCycle = b.dailyArticles[0].dueCycle)],
|
||||||
|
[400, (b) => (b.dailyArticles[0].dueCycle = '2028-02-30')],
|
||||||
|
[400, (b) => (b.month = '2028-13')],
|
||||||
|
[400, (b) => (b.dailyArticles[0].actionType = 'BLOG_UPDATE')],
|
||||||
|
[400, (b) => (b.needs[0].actionType = 'BLOG_NEW')],
|
||||||
|
[400, (b) => (b.needs[0].reason = ' ')],
|
||||||
|
[400, (b) => delete b.needs[0].target],
|
||||||
|
[400, (b) => (b.needs[0].department = 'WIKI_SCIENTIFIC')],
|
||||||
|
[400, (b) => (b.dailyArticles[0].sourceIds = [])],
|
||||||
|
[409, (b) => (b.dailyArticles[0].sourceIds = [key()])],
|
||||||
|
[409, (b) => (b.dailyArticles[0].goalId = key())],
|
||||||
|
[409, (b) => (b.needs[0].goalId = b.needs[1].goalId)],
|
||||||
|
[409, (b) => (b.roadmapId = key())],
|
||||||
|
];
|
||||||
|
for (const [status, mutate] of mutations) {
|
||||||
|
const invalid = JSON.parse(JSON.stringify(body));
|
||||||
|
mutate(invalid);
|
||||||
|
await post('monthly-plans', invalid).expect(status);
|
||||||
|
expect(await db.corporateTask.count()).toBe(0);
|
||||||
|
expect(await db.corporateEvent.count()).toBe(0);
|
||||||
|
expect(await db.corporateOperation.count()).toBe(2);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
it('serializes competing actors and keys on roadmap/month, rejects changed replay and keeps auth dormant', async () => {
|
||||||
|
const { body } = await planFixture();
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.post('/admin/hermes/monthly-plans')
|
||||||
|
.send(body)
|
||||||
|
.expect(401);
|
||||||
|
await post('monthly-plans', body, 'unscoped').expect(403);
|
||||||
|
const op = key();
|
||||||
|
const otherOp = key();
|
||||||
|
let release!: () => void;
|
||||||
|
let ready!: () => void;
|
||||||
|
const locked = new Promise<void>((r) => (ready = r));
|
||||||
|
const hold = new Promise<void>((r) => (release = r));
|
||||||
|
const scope = JSON.stringify(['monthly-plan', body.roadmapId, body.month]);
|
||||||
|
const blocker = db.$transaction(async (tx) => {
|
||||||
|
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${scope}, 0))`;
|
||||||
|
ready();
|
||||||
|
await hold;
|
||||||
|
});
|
||||||
|
await locked;
|
||||||
|
const pending = [
|
||||||
|
post('monthly-plans', body, 'planner', op).then((r) => r),
|
||||||
|
post('monthly-plans', body, 'other', otherOp).then((r) => r),
|
||||||
|
];
|
||||||
|
try {
|
||||||
|
let waiters = 0;
|
||||||
|
for (let i = 0; i < 100; i++) {
|
||||||
|
const rows = await db.$queryRaw<any[]>`SELECT pid FROM pg_stat_activity
|
||||||
|
WHERE datname=current_database() AND wait_event_type='Lock' AND query LIKE '%pg_advisory_xact_lock%'`;
|
||||||
|
waiters = rows.length;
|
||||||
|
if (waiters >= 2) break;
|
||||||
|
await new Promise((r) => setTimeout(r, 10));
|
||||||
|
}
|
||||||
|
expect(waiters).toBeGreaterThanOrEqual(2);
|
||||||
|
} finally {
|
||||||
|
release();
|
||||||
|
await blocker;
|
||||||
|
}
|
||||||
|
const results = await Promise.all(pending);
|
||||||
|
expect(results.map((r) => r.status).sort()).toEqual([201, 409]);
|
||||||
|
expect(await db.corporateTask.count()).toBe(33);
|
||||||
|
expect(await db.corporateEvent.count({ where: { step: 'PLANNED' } })).toBe(
|
||||||
|
33,
|
||||||
|
);
|
||||||
|
const winner = results[0].status === 201 ? 'planner' : 'other';
|
||||||
|
const winningOp = winner === 'planner' ? op : otherOp;
|
||||||
|
await post(
|
||||||
|
'monthly-plans',
|
||||||
|
{ ...body, needs: [] },
|
||||||
|
winner,
|
||||||
|
winningOp,
|
||||||
|
).expect(409);
|
||||||
|
expect(
|
||||||
|
(await post('monthly-plans', body, winner, winningOp).expect(201)).body,
|
||||||
|
).toEqual(results[winner === 'planner' ? 0 : 1].body);
|
||||||
|
const runtime = await request(app.getHttpServer())
|
||||||
|
.get('/admin/hermes/runtime')
|
||||||
|
.set('x-api-key', 'executor')
|
||||||
|
.expect(200);
|
||||||
|
expect(runtime.body).toEqual({
|
||||||
|
mode: 'MANUAL_DORMANT',
|
||||||
|
schedulesEnabled: false,
|
||||||
|
externalExecutionEnabled: false,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
it('rolls back a mid-plan database failure including tasks, events and idempotency receipt', async () => {
|
||||||
|
const { body } = await planFixture();
|
||||||
|
// Disposable-only trigger fails after the first task/event have been written.
|
||||||
|
await db.$executeRawUnsafe(
|
||||||
|
`CREATE FUNCTION reject_plan_event() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.step='PLANNED' AND NEW.payload->>'dueCycle'='2996-02-02' THEN RAISE EXCEPTION 'injected plan failure'; END IF; RETURN NEW; END $$`,
|
||||||
|
);
|
||||||
|
await db.$executeRawUnsafe(
|
||||||
|
'CREATE TRIGGER reject_plan_event BEFORE INSERT ON corporate_events FOR EACH ROW EXECUTE FUNCTION reject_plan_event()',
|
||||||
|
);
|
||||||
|
const op = key();
|
||||||
|
try {
|
||||||
|
await post('monthly-plans', body, 'planner', op).expect(500);
|
||||||
|
expect(await db.corporateTask.count()).toBe(0);
|
||||||
|
expect(await db.corporateEvent.count()).toBe(0);
|
||||||
|
expect(await db.corporateOperation.count()).toBe(2);
|
||||||
|
} finally {
|
||||||
|
await db.$executeRawUnsafe(
|
||||||
|
'DROP TRIGGER reject_plan_event ON corporate_events',
|
||||||
|
);
|
||||||
|
await db.$executeRawUnsafe('DROP FUNCTION reject_plan_event()');
|
||||||
|
}
|
||||||
|
await post('monthly-plans', body, 'planner', op).expect(201);
|
||||||
|
});
|
||||||
|
it('gates only PLANNED future tasks while legacy future dueCycle remains claimable and UTC today is eligible', async () => {
|
||||||
|
const { body } = await planFixture();
|
||||||
|
await post('monthly-plans', body).expect(201);
|
||||||
|
const legacy = (
|
||||||
|
await post('tasks', { ...input, dueCycle: '2999-12-31' }).expect(201)
|
||||||
|
).body;
|
||||||
|
expect((await post('claims', {}).expect(201)).body.task.id).toBe(legacy.id);
|
||||||
|
expect((await post('claims', {}).expect(201)).body.task).toBeNull();
|
||||||
|
// Model the persisted event's due-day boundary in the disposable DB without changing system time.
|
||||||
|
const planned = await db.corporateTask.findFirstOrThrow({
|
||||||
|
where: { actionType: 'BLOG_NEW' },
|
||||||
|
});
|
||||||
|
const day = new Date().toISOString().slice(0, 10);
|
||||||
|
await db.corporateTask.update({
|
||||||
|
where: { id: planned.id },
|
||||||
|
data: { dueCycle: day },
|
||||||
|
});
|
||||||
|
expect((await post('claims', {}).expect(201)).body.task).toBeNull(); // mismatch fails closed
|
||||||
|
const event = await db.corporateEvent.findFirstOrThrow({
|
||||||
|
where: { taskId: planned.id, step: 'PLANNED' },
|
||||||
|
});
|
||||||
|
await db.corporateEvent.update({
|
||||||
|
where: { id: event.id },
|
||||||
|
data: { payload: { ...(event.payload as object), dueCycle: day } },
|
||||||
|
});
|
||||||
|
expect((await post('claims', {}).expect(201)).body.task.id).toBe(
|
||||||
|
planned.id,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
it('rejects children after a parent claim commits while child creation waits on its row lock', async () => {
|
||||||
|
const parent = (await post('tasks', input).expect(201)).body;
|
||||||
|
let release!: () => void, locked!: () => void;
|
||||||
|
const ready = new Promise<void>((r) => (locked = r));
|
||||||
|
const hold = new Promise<void>((r) => (release = r));
|
||||||
|
const claiming = db.$transaction(async (tx) => {
|
||||||
|
await tx.$queryRaw`SELECT id FROM corporate_tasks WHERE id=${parent.id}::uuid FOR UPDATE`;
|
||||||
|
await tx.corporateTask.update({
|
||||||
|
where: { id: parent.id },
|
||||||
|
data: {
|
||||||
|
status: 'IN_PROGRESS',
|
||||||
|
claimToken: key(),
|
||||||
|
assignedAgent: 'executor',
|
||||||
|
leasedUntil: new Date(Date.now() + 60000),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
locked();
|
||||||
|
await hold;
|
||||||
|
});
|
||||||
|
await ready;
|
||||||
|
const pending = post('tasks', { ...input, parentId: parent.id }).then(
|
||||||
|
(r) => r,
|
||||||
|
);
|
||||||
|
try {
|
||||||
|
// Observe actual competing PostgreSQL lock wait, not a timing-only race.
|
||||||
|
let waiting = false;
|
||||||
|
for (let i = 0; i < 100; i++) {
|
||||||
|
const rows = await db.$queryRaw<
|
||||||
|
any[]
|
||||||
|
>`SELECT pid FROM pg_stat_activity WHERE datname=current_database() AND wait_event_type='Lock' AND query LIKE '%corporate_tasks%'`;
|
||||||
|
if (rows.length) {
|
||||||
|
waiting = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
await new Promise((r) => setTimeout(r, 10));
|
||||||
|
}
|
||||||
|
expect(waiting).toBe(true);
|
||||||
|
} finally {
|
||||||
|
release();
|
||||||
|
await claiming;
|
||||||
|
}
|
||||||
|
expect((await pending).status).toBe(409);
|
||||||
|
expect(
|
||||||
|
await db.corporateTask.count({ where: { parentId: parent.id } }),
|
||||||
|
).toBe(0);
|
||||||
|
});
|
||||||
|
it('accepts children on TODO and BLOCKED, which prevents parent claiming', async () => {
|
||||||
|
for (const status of ['TODO', 'BLOCKED'] as const) {
|
||||||
|
const parent = (await post('tasks', input).expect(201)).body;
|
||||||
|
await db.corporateTask.update({
|
||||||
|
where: { id: parent.id },
|
||||||
|
data: { status },
|
||||||
|
});
|
||||||
|
const child = (
|
||||||
|
await post('tasks', { ...input, parentId: parent.id }).expect(201)
|
||||||
|
).body;
|
||||||
|
expect((await post('claims', {}).expect(201)).body.task.id).toBe(
|
||||||
|
child.id,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
it('rejects malformed artifact locators and mismatched digest URNs before persistence', async () => {
|
||||||
|
const task = (await post('tasks', input).expect(201)).body;
|
||||||
|
const claim = (await post('claims', {}).expect(201)).body.task;
|
||||||
|
const body = {
|
||||||
|
claimToken: claim.claimToken,
|
||||||
|
artifactUri: '',
|
||||||
|
sha256: 'a'.repeat(64),
|
||||||
|
summary: 'receipt',
|
||||||
|
tool: 'jest',
|
||||||
|
result: 'passed',
|
||||||
|
};
|
||||||
|
for (const artifactUri of [
|
||||||
|
'https://',
|
||||||
|
'https://?x',
|
||||||
|
'https:///pubmed.ncbi.nlm.nih.gov/x',
|
||||||
|
'https://pubmed.ncbi.nlm.nih.gov./x',
|
||||||
|
'https://bad host/x',
|
||||||
|
'https://user:pass@host.org/a',
|
||||||
|
'https://localhost/a',
|
||||||
|
'https://127.1/a',
|
||||||
|
'https://[::1]/a',
|
||||||
|
'urn:sha256:',
|
||||||
|
'urn:sha256:' + 'b'.repeat(64),
|
||||||
|
]) {
|
||||||
|
await post(`tasks/${task.id}/evidence`, { ...body, artifactUri }).expect(
|
||||||
|
400,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
expect(await db.corporateEvidence.count()).toBe(0);
|
||||||
|
await post(`tasks/${task.id}/evidence`, {
|
||||||
|
...body,
|
||||||
|
artifactUri: 'https://pubmed.ncbi.nlm.nih.gov/123/',
|
||||||
|
}).expect(201);
|
||||||
|
});
|
||||||
|
it('rejects implicit timestamp coercions in source and effect inputs', async () => {
|
||||||
|
const service = app.get(CorporateService);
|
||||||
|
const research = {
|
||||||
|
title: 'research',
|
||||||
|
category: 'TREND',
|
||||||
|
source: 'receipt',
|
||||||
|
opportunity: 'investigate',
|
||||||
|
impact: 'LOW',
|
||||||
|
recommendedAction: 'measure',
|
||||||
|
cadence: 'MONTHLY',
|
||||||
|
provenance: { method: 'test', collector: 'fixture', context: 'isolated' },
|
||||||
|
sources: [
|
||||||
|
{
|
||||||
|
url: 'https://pubmed.ncbi.nlm.nih.gov/',
|
||||||
|
title: 'source',
|
||||||
|
excerpt: 'receipt',
|
||||||
|
retrievedAt: '',
|
||||||
|
sha256: 'a'.repeat(64),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
for (const time of [
|
||||||
|
null,
|
||||||
|
0,
|
||||||
|
false,
|
||||||
|
[],
|
||||||
|
'2026-01-01',
|
||||||
|
'2026-02-30T00:00:00Z',
|
||||||
|
]) {
|
||||||
|
await expect(
|
||||||
|
Promise.resolve().then(() =>
|
||||||
|
service.research('fixture', key(), {
|
||||||
|
...research,
|
||||||
|
sources: [{ ...research.sources[0], retrievedAt: time }],
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
).rejects.toThrow();
|
||||||
|
await expect(
|
||||||
|
Promise.resolve().then(() =>
|
||||||
|
service.effect('fixture', key(), key(), {
|
||||||
|
metric: 'views',
|
||||||
|
availability: 'UNAVAILABLE',
|
||||||
|
source: 'none',
|
||||||
|
observedAt: time,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
).rejects.toThrow('Invalid observation time');
|
||||||
|
}
|
||||||
|
for (const url of ['https://', 'https://?bad', 'https://bad host'])
|
||||||
|
await expect(
|
||||||
|
Promise.resolve().then(() =>
|
||||||
|
service.research('fixture', key(), {
|
||||||
|
...research,
|
||||||
|
sources: [
|
||||||
|
{
|
||||||
|
...research.sources[0],
|
||||||
|
retrievedAt: '2026-01-01T00:00:00Z',
|
||||||
|
url,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
).rejects.toThrow();
|
||||||
|
expect(await db.corporateResearch.count()).toBe(0);
|
||||||
|
});
|
||||||
|
it('public reads strip claim tokens recursively while claim and replay retain ownership token', async () => {
|
||||||
|
const parent = (await post('tasks', input).expect(201)).body;
|
||||||
|
const child = (
|
||||||
|
await post('tasks', { ...input, parentId: parent.id }).expect(201)
|
||||||
|
).body;
|
||||||
|
const op = key();
|
||||||
|
const claim = (await post('claims', {}, 'executor', op).expect(201)).body
|
||||||
|
.task;
|
||||||
|
expect(claim.claimToken).toBeTruthy();
|
||||||
|
expect(
|
||||||
|
(await post('claims', {}, 'executor', op).expect(201)).body.task
|
||||||
|
.claimToken,
|
||||||
|
).toBe(claim.claimToken);
|
||||||
|
await post(`tasks/${child.id}/evidence`, {
|
||||||
|
claimToken: claim.claimToken,
|
||||||
|
artifactUri: 'urn:sha256:' + 'a'.repeat(64),
|
||||||
|
sha256: 'a'.repeat(64),
|
||||||
|
summary: 'receipt',
|
||||||
|
tool: 'jest',
|
||||||
|
result: 'passed',
|
||||||
|
}).expect(201);
|
||||||
|
for (const path of ['tasks', 'tasks/' + child.id, 'tasks/' + parent.id]) {
|
||||||
|
const r = await request(app.getHttpServer())
|
||||||
|
.get('/admin/hermes/' + path)
|
||||||
|
.set('x-api-key', 'competitor')
|
||||||
|
.expect(200);
|
||||||
|
expect(JSON.stringify(r.body)).not.toContain('claimToken');
|
||||||
|
expect(JSON.stringify(r.body)).not.toContain(claim.claimToken);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
it('bounds detail relations and report snapshots with explicit truncation and immutable replay', async () => {
|
||||||
|
const task = (await post('tasks', input).expect(201)).body;
|
||||||
|
await db.corporateEvent.createMany({
|
||||||
|
data: Array.from({ length: 105 }, () => ({
|
||||||
|
taskId: task.id,
|
||||||
|
speaker: 'SYSTEM',
|
||||||
|
speakerName: 'fixture',
|
||||||
|
step: 'FIXTURE',
|
||||||
|
content: 'x'.repeat(10000),
|
||||||
|
payload: { nested: ['x'.repeat(10000)] },
|
||||||
|
})),
|
||||||
|
});
|
||||||
|
const detail = await request(app.getHttpServer())
|
||||||
|
.get('/admin/hermes/tasks/' + task.id)
|
||||||
|
.set('x-api-key', 'executor')
|
||||||
|
.expect(200);
|
||||||
|
expect(detail.body.logs).toHaveLength(100);
|
||||||
|
expect(detail.body.relationsMeta.logs).toEqual({
|
||||||
|
total: 106,
|
||||||
|
returned: 100,
|
||||||
|
limit: 100,
|
||||||
|
truncated: true,
|
||||||
|
});
|
||||||
|
const op = key(),
|
||||||
|
body = { day: new Date().toISOString().slice(0, 10), summary: 'bounded' };
|
||||||
|
const report = (await post('reports', body, 'executor', op).expect(201))
|
||||||
|
.body;
|
||||||
|
expect(report.snapshot.events).toHaveLength(100);
|
||||||
|
expect(report.snapshot.meta.events).toEqual({
|
||||||
|
total: 106,
|
||||||
|
returned: 100,
|
||||||
|
limit: 100,
|
||||||
|
truncated: true,
|
||||||
|
});
|
||||||
|
expect(report.snapshot.events.every((e: any) => !('payload' in e))).toBe(
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
expect(report.snapshot.meta.fieldsTruncated).toBe(true);
|
||||||
|
expect(
|
||||||
|
Buffer.byteLength(JSON.stringify(report.body ?? report)),
|
||||||
|
).toBeLessThan(1000000);
|
||||||
|
await db.corporateEvent.deleteMany();
|
||||||
|
expect(
|
||||||
|
(await post('reports', body, 'executor', op).expect(201)).body,
|
||||||
|
).toEqual(report);
|
||||||
|
});
|
||||||
|
it('rolls back oversized mutation responses instead of persisting huge idempotency values', async () => {
|
||||||
|
const service = app.get(CorporateService) as any;
|
||||||
|
const before = await db.corporateTask.count();
|
||||||
|
await expect(
|
||||||
|
service.operation('fixture', 'oversize', key(), {}, async (tx: any) => {
|
||||||
|
await tx.corporateTask.create({
|
||||||
|
data: {
|
||||||
|
title: 'rollback',
|
||||||
|
description: 'fixture',
|
||||||
|
taskCode: key(),
|
||||||
|
normalizedTitle: 'rollback',
|
||||||
|
normalizedCode: key(),
|
||||||
|
department: 'CONTENT_SEO',
|
||||||
|
createdBy: 'fixture',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return { value: 'x'.repeat(1100000) };
|
||||||
|
}),
|
||||||
|
).rejects.toThrow('Operation response exceeds limit');
|
||||||
|
expect(await db.corporateTask.count()).toBe(before);
|
||||||
|
expect(await db.corporateOperation.count()).toBe(0);
|
||||||
|
});
|
||||||
|
it('auth, UI list contract, normalized search, immutable idempotent replay', async () => {
|
||||||
|
await request(app.getHttpServer()).get('/admin/hermes/tasks').expect(401);
|
||||||
|
await post('tasks', input, 'unscoped').expect(403);
|
||||||
|
const op = key(),
|
||||||
|
a = await post('tasks', input, 'executor', op).expect(201);
|
||||||
|
const b = await post('tasks', input, 'executor', op).expect(201);
|
||||||
|
expect(b.body.id).toBe(a.body.id);
|
||||||
|
await post('tasks', { ...input, title: 'changed' }, 'executor', op).expect(
|
||||||
|
409,
|
||||||
|
);
|
||||||
|
const list = await request(app.getHttpServer())
|
||||||
|
.get('/admin/hermes/tasks?search=کیک%20123&limit=1')
|
||||||
|
.set('x-api-key', 'executor')
|
||||||
|
.expect(200);
|
||||||
|
expect(list.body.meta).toEqual({
|
||||||
|
total: 1,
|
||||||
|
page: 1,
|
||||||
|
limit: 1,
|
||||||
|
totalPages: 1,
|
||||||
|
hasNextPage: false,
|
||||||
|
hasPrevPage: false,
|
||||||
|
});
|
||||||
|
expect(list.body.data[0].priority).toBe('CEO_EXPEDITE');
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.get('/admin/hermes/tasks?limit=101')
|
||||||
|
.set('x-api-key', 'executor')
|
||||||
|
.expect(400);
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.get('/admin/hermes/tasks?sortBy=password')
|
||||||
|
.set('x-api-key', 'executor')
|
||||||
|
.expect(400);
|
||||||
|
});
|
||||||
|
it('claims exclusively, expires/reclaims, fences stale executor, requires independent QA', async () => {
|
||||||
|
const task = (await post('tasks', input).expect(201)).body;
|
||||||
|
const claims = await Promise.all([
|
||||||
|
post('claims', {}, 'executor'),
|
||||||
|
post('claims', {}, 'competitor'),
|
||||||
|
]);
|
||||||
|
expect(claims.filter((x) => x.body.task !== null)).toHaveLength(1);
|
||||||
|
const claimed = claims.find((x) => x.body.task !== null)!.body.task;
|
||||||
|
const oldActor = claimed.assignedAgent.replace('apikey:', '');
|
||||||
|
await db.$executeRaw`UPDATE corporate_tasks SET "leasedUntil"=clock_timestamp()-interval '1 second' WHERE id=${task.id}::uuid`;
|
||||||
|
const renewed = (await post('claims', {}, 'new-executor').expect(201)).body
|
||||||
|
.task;
|
||||||
|
expect(renewed.claimToken).not.toBe(claimed.claimToken);
|
||||||
|
const evidence = {
|
||||||
|
claimToken: claimed.claimToken,
|
||||||
|
artifactUri: 'urn:sha256:' + 'a'.repeat(64),
|
||||||
|
sha256: 'a'.repeat(64),
|
||||||
|
summary: 'receipt',
|
||||||
|
tool: 'jest',
|
||||||
|
result: 'passed',
|
||||||
|
};
|
||||||
|
await post(`tasks/${task.id}/evidence`, evidence, oldActor).expect(409);
|
||||||
|
const e = (
|
||||||
|
await post(
|
||||||
|
`tasks/${task.id}/evidence`,
|
||||||
|
{ ...evidence, claimToken: renewed.claimToken },
|
||||||
|
'new-executor',
|
||||||
|
).expect(201)
|
||||||
|
).body;
|
||||||
|
const review = {
|
||||||
|
evidenceId: e.id,
|
||||||
|
passed: true,
|
||||||
|
findings: 'verified',
|
||||||
|
verification: {
|
||||||
|
artifactUri: e.artifactUri,
|
||||||
|
sha256: e.sha256,
|
||||||
|
method: 'digest readback',
|
||||||
|
result: 'match',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
await post(`tasks/${task.id}/reviews`, review, 'new-executor').expect(409);
|
||||||
|
await post(`tasks/${task.id}/reviews`, review, 'reviewer').expect(201);
|
||||||
|
const detail = await request(app.getHttpServer())
|
||||||
|
.get('/admin/hermes/tasks/' + task.id)
|
||||||
|
.set('x-api-key', 'reviewer')
|
||||||
|
.expect(200);
|
||||||
|
expect(detail.body.status).toBe('DONE');
|
||||||
|
expect(detail.body.logs.map((x: any) => x.step)).toContain('QA_PASSED');
|
||||||
|
await post(`tasks/${task.id}/effects`, {
|
||||||
|
metric: 'engagement',
|
||||||
|
availability: 'UNAVAILABLE',
|
||||||
|
observed: 0,
|
||||||
|
source: 'provider unavailable',
|
||||||
|
observedAt: new Date().toISOString(),
|
||||||
|
}).expect(400);
|
||||||
|
});
|
||||||
|
it('skips a held row lock and gives CEO priority before lower priorities', async () => {
|
||||||
|
const urgent = (await post('tasks', input).expect(201)).body;
|
||||||
|
const low = (await post('tasks', { ...input, priority: 'LOW' }).expect(201))
|
||||||
|
.body;
|
||||||
|
let release!: () => void, locked!: () => void;
|
||||||
|
const ready = new Promise<void>((r) => (locked = r)),
|
||||||
|
hold = new Promise<void>((r) => (release = r));
|
||||||
|
const locking = db.$transaction(async (tx) => {
|
||||||
|
await tx.$queryRaw`SELECT id FROM corporate_tasks WHERE id=${urgent.id}::uuid FOR UPDATE`;
|
||||||
|
locked();
|
||||||
|
await hold;
|
||||||
|
});
|
||||||
|
await ready;
|
||||||
|
try {
|
||||||
|
const claim = (await post('claims', {}).expect(201)).body.task;
|
||||||
|
expect(claim.id).toBe(low.id);
|
||||||
|
} finally {
|
||||||
|
release();
|
||||||
|
await locking;
|
||||||
|
}
|
||||||
|
const next = (await post('claims', {}, 'other').expect(201)).body.task;
|
||||||
|
expect(next.id).toBe(urgent.id);
|
||||||
|
});
|
||||||
|
it('serializes simultaneous duplicate mutations into one durable record', async () => {
|
||||||
|
const op = key();
|
||||||
|
const responses = await Promise.all([
|
||||||
|
post('tasks', input, 'executor', op),
|
||||||
|
post('tasks', input, 'executor', op),
|
||||||
|
]);
|
||||||
|
expect(responses.map((r) => r.status)).toEqual([201, 201]);
|
||||||
|
expect(responses[0].body.id).toBe(responses[1].body.id);
|
||||||
|
expect(await db.corporateTask.count()).toBe(1);
|
||||||
|
});
|
||||||
|
it('gates parents on children, persists provenance, roadmap/goals and reports', async () => {
|
||||||
|
const parent = (await post('tasks', input).expect(201)).body;
|
||||||
|
const child = (
|
||||||
|
await post('tasks', { ...input, parentId: parent.id }).expect(201)
|
||||||
|
).body;
|
||||||
|
const claim = (await post('claims', {}).expect(201)).body.task;
|
||||||
|
expect(claim.id).toBe(child.id);
|
||||||
|
const e = (
|
||||||
|
await post(`tasks/${child.id}/evidence`, {
|
||||||
|
claimToken: claim.claimToken,
|
||||||
|
artifactUri: 'urn:sha256:' + 'b'.repeat(64),
|
||||||
|
sha256: 'b'.repeat(64),
|
||||||
|
summary: 'child artifact',
|
||||||
|
tool: 'jest',
|
||||||
|
result: 'receipt',
|
||||||
|
}).expect(201)
|
||||||
|
).body;
|
||||||
|
await post(
|
||||||
|
`tasks/${child.id}/reviews`,
|
||||||
|
{
|
||||||
|
evidenceId: e.id,
|
||||||
|
passed: false,
|
||||||
|
findings: 'needs correction',
|
||||||
|
verification: {
|
||||||
|
artifactUri: e.artifactUri,
|
||||||
|
sha256: e.sha256,
|
||||||
|
method: 'readback',
|
||||||
|
result: 'failed',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
'reviewer',
|
||||||
|
).expect(201);
|
||||||
|
expect(
|
||||||
|
(await db.corporateTask.findUniqueOrThrow({ where: { id: parent.id } }))
|
||||||
|
.status,
|
||||||
|
).toBe('BLOCKED');
|
||||||
|
expect((await post('claims', {}).expect(201)).body.task.id).toBe(child.id);
|
||||||
|
const research = (
|
||||||
|
await post('market-insights', {
|
||||||
|
title: 'fixture research',
|
||||||
|
category: 'TREND',
|
||||||
|
source: 'study receipt',
|
||||||
|
opportunity: 'investigate',
|
||||||
|
impact: 'LOW',
|
||||||
|
recommendedAction: 'measure',
|
||||||
|
cadence: 'MONTHLY',
|
||||||
|
provenance: {
|
||||||
|
method: 'test fixture',
|
||||||
|
collector: 'integration',
|
||||||
|
context: 'disposable',
|
||||||
|
},
|
||||||
|
sources: [
|
||||||
|
{
|
||||||
|
url: 'https://pubmed.ncbi.nlm.nih.gov/',
|
||||||
|
title: 'fixture',
|
||||||
|
excerpt: 'test-only',
|
||||||
|
retrievedAt: '2026-01-01T00:00:00Z',
|
||||||
|
sha256: 'a'.repeat(64),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}).expect(201)
|
||||||
|
).body;
|
||||||
|
const roadmap = (
|
||||||
|
await post('monthly-roadmap', {
|
||||||
|
researchId: research.id,
|
||||||
|
cycleName: 'test',
|
||||||
|
month: '2026-10',
|
||||||
|
seasonalTheme: 'evidence pending seasonal analysis',
|
||||||
|
strategicGoals: ['measure'],
|
||||||
|
plannedArticlesCount: 31,
|
||||||
|
plannedRefreshesCount: 0,
|
||||||
|
plannedCatalogEnrichments: 0,
|
||||||
|
goals: [
|
||||||
|
{
|
||||||
|
title: 'goal',
|
||||||
|
department: 'CONTENT_SEO',
|
||||||
|
acceptanceCriteria: 'QA',
|
||||||
|
metric: 'engagement',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}).expect(201)
|
||||||
|
).body;
|
||||||
|
expect(roadmap.goals).toHaveLength(1);
|
||||||
|
await post('tasks', { ...input, goalId: roadmap.goals[0].id }).expect(201);
|
||||||
|
for (const path of ['market-insights', 'monthly-roadmap']) {
|
||||||
|
const r = await request(app.getHttpServer())
|
||||||
|
.get('/admin/hermes/' + path)
|
||||||
|
.set('x-api-key', 'executor')
|
||||||
|
.expect(200);
|
||||||
|
expect(r.body.meta.total).toBe(1);
|
||||||
|
}
|
||||||
|
const report = (
|
||||||
|
await post('reports', {
|
||||||
|
day: new Date().toISOString().slice(0, 10),
|
||||||
|
summary: 'test fixture daily report',
|
||||||
|
}).expect(201)
|
||||||
|
).body;
|
||||||
|
expect(report.snapshot.tasks).toHaveLength(3);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,828 @@
|
|||||||
|
import {
|
||||||
|
Injectable,
|
||||||
|
BadRequestException,
|
||||||
|
ConflictException,
|
||||||
|
NotFoundException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { Prisma, CorporatePriority } from '@prisma/client';
|
||||||
|
import { createHash, randomUUID } from 'crypto';
|
||||||
|
import { PrismaService } from '../../prisma/prisma.service';
|
||||||
|
import {
|
||||||
|
canonical,
|
||||||
|
monthlyPlanInput,
|
||||||
|
planMonth,
|
||||||
|
publicData,
|
||||||
|
choice,
|
||||||
|
departments,
|
||||||
|
evidenceInput,
|
||||||
|
httpsUrl,
|
||||||
|
timestamp,
|
||||||
|
meta,
|
||||||
|
normalizeSearch,
|
||||||
|
object,
|
||||||
|
pagination,
|
||||||
|
priorities,
|
||||||
|
statuses,
|
||||||
|
taskInput,
|
||||||
|
text,
|
||||||
|
uuid,
|
||||||
|
} from './corporate-policy';
|
||||||
|
type Tx = Prisma.TransactionClient;
|
||||||
|
@Injectable()
|
||||||
|
export class CorporateService {
|
||||||
|
constructor(private readonly db: PrismaService) {}
|
||||||
|
private async operation(
|
||||||
|
actor: string,
|
||||||
|
op: string,
|
||||||
|
key: string,
|
||||||
|
body: unknown,
|
||||||
|
fn: (tx: Tx) => Promise<any>,
|
||||||
|
) {
|
||||||
|
text(key, 200);
|
||||||
|
const scoped = createHash('sha256')
|
||||||
|
.update(canonical([actor, op, key]))
|
||||||
|
.digest('hex');
|
||||||
|
const hash = createHash('sha256').update(canonical(body)).digest('hex');
|
||||||
|
return this.db.$transaction(
|
||||||
|
async (tx) => {
|
||||||
|
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${scoped}, 0))`;
|
||||||
|
const prior = await tx.corporateOperation.findUnique({
|
||||||
|
where: { key: scoped },
|
||||||
|
});
|
||||||
|
if (prior) {
|
||||||
|
if (prior.payloadHash !== hash)
|
||||||
|
throw new ConflictException('Idempotency key payload mismatch');
|
||||||
|
return prior.response;
|
||||||
|
}
|
||||||
|
const result = await fn(tx);
|
||||||
|
const serialized = JSON.stringify(result);
|
||||||
|
if (Buffer.byteLength(serialized, 'utf8') > 1000000)
|
||||||
|
throw new BadRequestException('Operation response exceeds limit');
|
||||||
|
const response = JSON.parse(serialized);
|
||||||
|
await tx.corporateOperation.create({
|
||||||
|
data: { key: scoped, payloadHash: hash, response },
|
||||||
|
});
|
||||||
|
return response;
|
||||||
|
},
|
||||||
|
{ maxWait: 10000, timeout: 20000 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
private event(
|
||||||
|
tx: Tx,
|
||||||
|
taskId: string,
|
||||||
|
actor: string,
|
||||||
|
step: string,
|
||||||
|
content: string,
|
||||||
|
speaker = 'SYSTEM',
|
||||||
|
payload?: any,
|
||||||
|
) {
|
||||||
|
return tx.corporateEvent.create({
|
||||||
|
data: { taskId, speaker, speakerName: actor, step, content, payload },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
private async lock(tx: Tx, id: string) {
|
||||||
|
uuid(id);
|
||||||
|
const rows = await tx.$queryRaw<
|
||||||
|
{ id: string }[]
|
||||||
|
>`SELECT id FROM corporate_tasks WHERE id=${id}::uuid FOR UPDATE`;
|
||||||
|
if (!rows.length) throw new NotFoundException('Task not found');
|
||||||
|
return tx.corporateTask.findUniqueOrThrow({ where: { id } });
|
||||||
|
}
|
||||||
|
private async fenced(tx: Tx, id: string, token: string, actor: string) {
|
||||||
|
const t = await this.lock(tx, id);
|
||||||
|
const rows = await tx.$queryRaw<
|
||||||
|
{ id: string }[]
|
||||||
|
>`SELECT id FROM corporate_tasks WHERE id=${id}::uuid AND "claimToken"=${token}::uuid AND "assignedAgent"=${actor} AND "leasedUntil">clock_timestamp() AND status='IN_PROGRESS'`;
|
||||||
|
if (!rows.length) throw new ConflictException('Stale lease or owner');
|
||||||
|
return t;
|
||||||
|
}
|
||||||
|
async tasks(q: Record<string, any>) {
|
||||||
|
const p = pagination(q),
|
||||||
|
where: Prisma.CorporateTaskWhereInput = {};
|
||||||
|
if (q.department) where.department = choice(q.department, departments);
|
||||||
|
if (q.priority)
|
||||||
|
where.priority = choice(q.priority, priorities) as CorporatePriority;
|
||||||
|
if (q.status) where.status = choice(q.status, statuses) as any;
|
||||||
|
if (q.search) {
|
||||||
|
const search = normalizeSearch(text(q.search, 300));
|
||||||
|
where.OR = [
|
||||||
|
{ normalizedTitle: { contains: search } },
|
||||||
|
{ normalizedCode: { contains: search } },
|
||||||
|
];
|
||||||
|
}
|
||||||
|
if (q.goalId) where.goalId = uuid(q.goalId);
|
||||||
|
return this.db.$transaction(
|
||||||
|
async (tx) => {
|
||||||
|
const total = await tx.corporateTask.count({ where });
|
||||||
|
const data = await tx.corporateTask.findMany({
|
||||||
|
where,
|
||||||
|
skip: p.skip,
|
||||||
|
take: p.limit,
|
||||||
|
orderBy: [{ [p.sortBy]: p.sortOrder }, { id: 'asc' }],
|
||||||
|
});
|
||||||
|
return publicData({ data, meta: meta(total, p.page, p.limit) });
|
||||||
|
},
|
||||||
|
{ isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
async detail(id: string) {
|
||||||
|
uuid(id);
|
||||||
|
return this.db.$transaction(
|
||||||
|
async (tx) => {
|
||||||
|
const order = { id: 'asc' as const };
|
||||||
|
const task = await tx.corporateTask.findUnique({
|
||||||
|
where: { id },
|
||||||
|
include: {
|
||||||
|
logs: { take: 100, orderBy: [{ timestamp: 'asc' }, order] },
|
||||||
|
evidence: { take: 100, orderBy: order },
|
||||||
|
reviews: { take: 100, orderBy: order },
|
||||||
|
effects: { take: 100, orderBy: order },
|
||||||
|
children: { take: 100, orderBy: order },
|
||||||
|
_count: {
|
||||||
|
select: {
|
||||||
|
logs: true,
|
||||||
|
evidence: true,
|
||||||
|
reviews: true,
|
||||||
|
effects: true,
|
||||||
|
children: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (!task) throw new NotFoundException('Task not found');
|
||||||
|
const { _count, ...data } = task;
|
||||||
|
const relationsMeta = Object.fromEntries(
|
||||||
|
Object.entries(_count).map(([name, total]) => [
|
||||||
|
name,
|
||||||
|
{
|
||||||
|
total,
|
||||||
|
returned: Math.min(total, 100),
|
||||||
|
limit: 100,
|
||||||
|
truncated: total > 100,
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
return publicData({ ...data, relationsMeta });
|
||||||
|
},
|
||||||
|
{ isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
create(actor: string, key: string, input: unknown) {
|
||||||
|
const b = taskInput(input);
|
||||||
|
return this.operation(actor, 'create-task', key, b, async (tx) => {
|
||||||
|
if (b.parentId) {
|
||||||
|
const parent = await this.lock(tx, b.parentId);
|
||||||
|
if (!['TODO', 'BLOCKED'].includes(parent.status))
|
||||||
|
throw new ConflictException('Parent no longer accepts children');
|
||||||
|
}
|
||||||
|
const code = 'TSK-' + randomUUID();
|
||||||
|
const task = await tx.corporateTask.create({
|
||||||
|
data: {
|
||||||
|
...b,
|
||||||
|
priority: b.priority as CorporatePriority,
|
||||||
|
taskCode: code,
|
||||||
|
normalizedCode: normalizeSearch(code),
|
||||||
|
normalizedTitle: normalizeSearch(b.title),
|
||||||
|
createdBy: actor,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await this.event(tx, task.id, actor, 'CREATED', b.description, 'CEO');
|
||||||
|
return task;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
private plannedWhere(
|
||||||
|
roadmapId: string,
|
||||||
|
month: string,
|
||||||
|
): Prisma.CorporateEventWhereInput {
|
||||||
|
return {
|
||||||
|
step: 'PLANNED',
|
||||||
|
AND: [
|
||||||
|
{ payload: { path: ['roadmapId'], equals: roadmapId } },
|
||||||
|
{ payload: { path: ['month'], equals: month } },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
private async readPlan(tx: Tx, roadmapId: string, month: string) {
|
||||||
|
const roadmap = await tx.corporateRoadmap.findUnique({
|
||||||
|
where: { id: roadmapId },
|
||||||
|
});
|
||||||
|
const tasks = await tx.corporateTask.findMany({
|
||||||
|
where: { logs: { some: this.plannedWhere(roadmapId, month) } },
|
||||||
|
include: {
|
||||||
|
logs: {
|
||||||
|
where: this.plannedWhere(roadmapId, month),
|
||||||
|
orderBy: { id: 'asc' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
orderBy: [{ dueCycle: 'asc' }, { actionType: 'asc' }, { id: 'asc' }],
|
||||||
|
});
|
||||||
|
if (!roadmap || !tasks.length)
|
||||||
|
throw new NotFoundException('Monthly plan not found');
|
||||||
|
return publicData({
|
||||||
|
roadmapId,
|
||||||
|
month,
|
||||||
|
researchId: roadmap.researchId,
|
||||||
|
tasks,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
monthlyPlan(roadmapId: string, month: unknown) {
|
||||||
|
roadmapId = uuid(roadmapId);
|
||||||
|
const cycle = planMonth(month);
|
||||||
|
return this.db.$transaction((tx) => this.readPlan(tx, roadmapId, cycle), {
|
||||||
|
isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
persistMonthlyPlan(actor: string, key: string, input: unknown) {
|
||||||
|
const b = monthlyPlanInput(input);
|
||||||
|
return this.operation(actor, 'monthly-plan', key, b, async (tx) => {
|
||||||
|
// Separate actor/key-independent fence: one complete plan per roadmap/month.
|
||||||
|
const scope = canonical(['monthly-plan', b.roadmapId, b.month]);
|
||||||
|
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${scope}, 0))`;
|
||||||
|
if (
|
||||||
|
await tx.corporateEvent.count({
|
||||||
|
where: this.plannedWhere(b.roadmapId, b.month),
|
||||||
|
})
|
||||||
|
)
|
||||||
|
throw new ConflictException('Monthly plan already persisted');
|
||||||
|
const roadmap = await tx.corporateRoadmap.findUnique({
|
||||||
|
where: { id: b.roadmapId },
|
||||||
|
include: { goals: true, research: { include: { sources: true } } },
|
||||||
|
});
|
||||||
|
if (
|
||||||
|
!roadmap ||
|
||||||
|
roadmap.month !== b.month ||
|
||||||
|
!roadmap.research.sources.length
|
||||||
|
)
|
||||||
|
throw new ConflictException(
|
||||||
|
'Matching evidence-backed roadmap required',
|
||||||
|
);
|
||||||
|
const entries = [...b.dailyArticles, ...b.needs];
|
||||||
|
for (const entry of entries) {
|
||||||
|
if (
|
||||||
|
!roadmap.goals.some(
|
||||||
|
(g) => g.id === entry.goalId && g.department === entry.department,
|
||||||
|
) ||
|
||||||
|
!entry.sourceIds.every((id) =>
|
||||||
|
roadmap.research.sources.some((s) => s.id === id),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
throw new ConflictException(
|
||||||
|
'Goal/department and source lineage must match roadmap research',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for (const entry of entries) {
|
||||||
|
const { sourceIds, target, reason, ...data } = entry;
|
||||||
|
const taskCode = 'TSK-' + randomUUID();
|
||||||
|
const task = await tx.corporateTask.create({
|
||||||
|
data: {
|
||||||
|
...data,
|
||||||
|
priority: data.priority as CorporatePriority,
|
||||||
|
status: 'TODO',
|
||||||
|
taskCode,
|
||||||
|
normalizedCode: normalizeSearch(taskCode),
|
||||||
|
normalizedTitle: normalizeSearch(data.title),
|
||||||
|
createdBy: actor,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await this.event(
|
||||||
|
tx,
|
||||||
|
task.id,
|
||||||
|
actor,
|
||||||
|
'PLANNED',
|
||||||
|
entry.description,
|
||||||
|
'SYSTEM',
|
||||||
|
{
|
||||||
|
version: 1,
|
||||||
|
roadmapId: roadmap.id,
|
||||||
|
researchId: roadmap.researchId,
|
||||||
|
month: b.month,
|
||||||
|
goalId: entry.goalId,
|
||||||
|
department: entry.department,
|
||||||
|
actionType: entry.actionType,
|
||||||
|
dueCycle: entry.dueCycle,
|
||||||
|
sourceIds,
|
||||||
|
...(target ? { target, reason } : {}),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return this.readPlan(tx, b.roadmapId, b.month);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
claim(actor: string, key: string, input: unknown) {
|
||||||
|
const b = object(input, ['department', 'leaseSeconds']);
|
||||||
|
const department =
|
||||||
|
b.department === undefined ? null : choice(b.department, departments);
|
||||||
|
const seconds = Number(b.leaseSeconds ?? 300);
|
||||||
|
if (!Number.isInteger(seconds) || seconds < 30 || seconds > 900)
|
||||||
|
throw new BadRequestException('Lease must be 30..900 seconds');
|
||||||
|
return this.operation(
|
||||||
|
actor,
|
||||||
|
'claim',
|
||||||
|
key,
|
||||||
|
{ department, seconds },
|
||||||
|
async (tx) => {
|
||||||
|
const candidates = await tx.$queryRaw<
|
||||||
|
{ id: string }[]
|
||||||
|
>`SELECT t.id FROM corporate_tasks t
|
||||||
|
WHERE (t.status='TODO' OR (t.status='BLOCKED' AND EXISTS (SELECT 1 FROM corporate_tasks c WHERE c."parentId"=t.id)) OR (t.status='IN_PROGRESS' AND t."leasedUntil"<=clock_timestamp()))
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM corporate_events e WHERE e."taskId"=t.id AND e.step='PLANNED'
|
||||||
|
AND (t."dueCycle" IS NULL OR t."dueCycle" !~ '^[0-9]{4}-[0-9]{2}-[0-9]{2}$'
|
||||||
|
OR e.payload->>'dueCycle' IS DISTINCT FROM t."dueCycle"
|
||||||
|
OR t."dueCycle">to_char(clock_timestamp() AT TIME ZONE 'UTC','YYYY-MM-DD')))
|
||||||
|
AND (${department}::text IS NULL OR t.department=${department})
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM corporate_tasks c WHERE c."parentId"=t.id AND c.status<>'DONE')
|
||||||
|
ORDER BY t.priority ASC,t."updatedAt" ASC,t.id ASC FOR UPDATE OF t SKIP LOCKED LIMIT 1`;
|
||||||
|
if (!candidates.length) return { task: null };
|
||||||
|
const id = candidates[0].id,
|
||||||
|
token = randomUUID();
|
||||||
|
await tx.$executeRaw`UPDATE corporate_tasks SET status='IN_PROGRESS', "assignedAgent"=${actor}, "claimToken"=${token}::uuid, "leasedUntil"=clock_timestamp()+make_interval(secs=>${seconds}::int), "executionCount"="executionCount"+1,"updatedAt"=clock_timestamp() WHERE id=${id}::uuid`;
|
||||||
|
await this.event(tx, id, actor, 'CLAIMED', 'Manual lease acquired');
|
||||||
|
return {
|
||||||
|
task: await tx.corporateTask.findUniqueOrThrow({ where: { id } }),
|
||||||
|
};
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
submitEvidence(actor: string, key: string, id: string, input: unknown) {
|
||||||
|
const b = evidenceInput(input);
|
||||||
|
return this.operation(actor, 'evidence:' + id, key, b, async (tx) => {
|
||||||
|
await this.fenced(tx, id, b.claimToken, actor);
|
||||||
|
const e = await tx.corporateEvidence.create({
|
||||||
|
data: { ...b, taskId: id, executor: actor },
|
||||||
|
});
|
||||||
|
await tx.corporateTask.update({
|
||||||
|
where: { id },
|
||||||
|
data: { status: 'TEST', leasedUntil: null },
|
||||||
|
});
|
||||||
|
await this.event(
|
||||||
|
tx,
|
||||||
|
id,
|
||||||
|
actor,
|
||||||
|
'EVIDENCE_SUBMITTED',
|
||||||
|
b.summary,
|
||||||
|
'AGENT',
|
||||||
|
{ evidenceId: e.id },
|
||||||
|
);
|
||||||
|
return e;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
review(actor: string, key: string, id: string, input: unknown) {
|
||||||
|
const b = object(input, [
|
||||||
|
'evidenceId',
|
||||||
|
'passed',
|
||||||
|
'findings',
|
||||||
|
'verification',
|
||||||
|
]);
|
||||||
|
const evidenceId = uuid(b.evidenceId),
|
||||||
|
findings = text(b.findings);
|
||||||
|
if (typeof b.passed !== 'boolean')
|
||||||
|
throw new BadRequestException('passed must be boolean');
|
||||||
|
const v = object(b.verification, [
|
||||||
|
'artifactUri',
|
||||||
|
'sha256',
|
||||||
|
'method',
|
||||||
|
'result',
|
||||||
|
]);
|
||||||
|
const verification = {
|
||||||
|
artifactUri: text(v.artifactUri, 2000),
|
||||||
|
sha256: text(v.sha256, 64),
|
||||||
|
method: text(v.method, 1000),
|
||||||
|
result: text(v.result),
|
||||||
|
};
|
||||||
|
return this.operation(actor, 'review:' + id, key, b, async (tx) => {
|
||||||
|
uuid(id);
|
||||||
|
const relation = await tx.corporateTask.findUnique({
|
||||||
|
where: { id },
|
||||||
|
select: { parentId: true },
|
||||||
|
});
|
||||||
|
if (relation?.parentId) await this.lock(tx, relation.parentId);
|
||||||
|
const task = await this.lock(tx, id);
|
||||||
|
const evidence = await tx.corporateEvidence.findUnique({
|
||||||
|
where: { id: evidenceId },
|
||||||
|
});
|
||||||
|
if (
|
||||||
|
task.status !== 'TEST' ||
|
||||||
|
!evidence ||
|
||||||
|
evidence.taskId !== id ||
|
||||||
|
evidence.claimToken !== task.claimToken
|
||||||
|
)
|
||||||
|
throw new ConflictException('Current execution evidence required');
|
||||||
|
if (evidence.executor === actor)
|
||||||
|
throw new ConflictException('Independent reviewer required');
|
||||||
|
if (
|
||||||
|
verification.sha256 !== evidence.sha256 ||
|
||||||
|
verification.artifactUri !== evidence.artifactUri
|
||||||
|
)
|
||||||
|
throw new ConflictException('QA must verify exact artifact');
|
||||||
|
if (
|
||||||
|
b.passed &&
|
||||||
|
(await tx.corporateTask.count({
|
||||||
|
where: { parentId: id, status: { not: 'DONE' } },
|
||||||
|
}))
|
||||||
|
)
|
||||||
|
throw new ConflictException('Unfinished children');
|
||||||
|
const r = await tx.corporateReview.create({
|
||||||
|
data: {
|
||||||
|
taskId: id,
|
||||||
|
evidenceId,
|
||||||
|
reviewer: actor,
|
||||||
|
passed: b.passed,
|
||||||
|
findings,
|
||||||
|
verification,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await tx.corporateTask.update({
|
||||||
|
where: { id },
|
||||||
|
data: {
|
||||||
|
status: b.passed ? 'DONE' : 'TODO',
|
||||||
|
claimToken: null,
|
||||||
|
leasedUntil: null,
|
||||||
|
qaCount: { increment: 1 },
|
||||||
|
rejectionCount: { increment: b.passed ? 0 : 1 },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (!b.passed && task.parentId) {
|
||||||
|
await tx.corporateTask.update({
|
||||||
|
where: { id: task.parentId },
|
||||||
|
data: { status: 'BLOCKED' },
|
||||||
|
});
|
||||||
|
await this.event(
|
||||||
|
tx,
|
||||||
|
task.parentId,
|
||||||
|
actor,
|
||||||
|
'CHILD_QA_REJECTED',
|
||||||
|
'Parent blocked pending child correction',
|
||||||
|
'QA',
|
||||||
|
{ childId: id },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
await this.event(
|
||||||
|
tx,
|
||||||
|
id,
|
||||||
|
actor,
|
||||||
|
b.passed ? 'QA_PASSED' : 'QA_REJECTED',
|
||||||
|
findings,
|
||||||
|
'QA',
|
||||||
|
{ reviewId: r.id },
|
||||||
|
);
|
||||||
|
return r;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
async collection(
|
||||||
|
kind: 'market-insights' | 'monthly-roadmap' | 'reports',
|
||||||
|
q: Record<string, any>,
|
||||||
|
) {
|
||||||
|
const p = pagination(q);
|
||||||
|
return this.db.$transaction(
|
||||||
|
async (tx) => {
|
||||||
|
const model =
|
||||||
|
kind === 'market-insights'
|
||||||
|
? tx.corporateResearch
|
||||||
|
: kind === 'monthly-roadmap'
|
||||||
|
? tx.corporateRoadmap
|
||||||
|
: tx.corporateReport;
|
||||||
|
const where: any = {};
|
||||||
|
if (kind === 'market-insights' && q.category)
|
||||||
|
where.category = choice(q.category, [
|
||||||
|
'TREND',
|
||||||
|
'COMPETITOR',
|
||||||
|
'NEW_CHANNEL',
|
||||||
|
'CATALOG_GAP',
|
||||||
|
]);
|
||||||
|
if (kind === 'monthly-roadmap' && q.month)
|
||||||
|
where.month = text(q.month, 40);
|
||||||
|
const delegate = model as any;
|
||||||
|
const total = await delegate.count({ where });
|
||||||
|
const data = await delegate.findMany({
|
||||||
|
where,
|
||||||
|
skip: p.skip,
|
||||||
|
take: p.limit,
|
||||||
|
orderBy: [{ createdAt: 'desc' }, { id: 'asc' }],
|
||||||
|
...(kind === 'market-insights'
|
||||||
|
? { include: { sources: true } }
|
||||||
|
: kind === 'monthly-roadmap'
|
||||||
|
? { include: { goals: true } }
|
||||||
|
: {}),
|
||||||
|
});
|
||||||
|
return publicData({ data, meta: meta(total, p.page, p.limit) });
|
||||||
|
},
|
||||||
|
{ isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
research(actor: string, key: string, input: unknown) {
|
||||||
|
const b = object(input, [
|
||||||
|
'title',
|
||||||
|
'category',
|
||||||
|
'source',
|
||||||
|
'opportunity',
|
||||||
|
'impact',
|
||||||
|
'recommendedAction',
|
||||||
|
'cadence',
|
||||||
|
'provenance',
|
||||||
|
'sources',
|
||||||
|
]);
|
||||||
|
if (!Array.isArray(b.sources) || !b.sources.length || b.sources.length > 30)
|
||||||
|
throw new BadRequestException('1..30 sources required');
|
||||||
|
const sources = b.sources.map((raw) => {
|
||||||
|
const s = object(raw, [
|
||||||
|
'url',
|
||||||
|
'title',
|
||||||
|
'excerpt',
|
||||||
|
'retrievedAt',
|
||||||
|
'sha256',
|
||||||
|
]);
|
||||||
|
const url = httpsUrl(s.url),
|
||||||
|
sha256 = text(s.sha256, 64),
|
||||||
|
retrievedAt = timestamp(s.retrievedAt, 'Invalid source time');
|
||||||
|
if (
|
||||||
|
!url.startsWith('https://') ||
|
||||||
|
!/^[a-f0-9]{64}$/.test(sha256) ||
|
||||||
|
!Number.isFinite(retrievedAt.getTime()) ||
|
||||||
|
retrievedAt.getTime() > Date.now()
|
||||||
|
)
|
||||||
|
throw new BadRequestException('Invalid source');
|
||||||
|
return {
|
||||||
|
url,
|
||||||
|
sha256,
|
||||||
|
retrievedAt,
|
||||||
|
title: text(s.title, 300),
|
||||||
|
excerpt: text(s.excerpt),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
const provenance = object(b.provenance, ['method', 'collector', 'context']);
|
||||||
|
const data = {
|
||||||
|
title: text(b.title, 300),
|
||||||
|
category: choice(b.category, [
|
||||||
|
'TREND',
|
||||||
|
'COMPETITOR',
|
||||||
|
'NEW_CHANNEL',
|
||||||
|
'CATALOG_GAP',
|
||||||
|
]),
|
||||||
|
source: text(b.source, 2000),
|
||||||
|
opportunity: text(b.opportunity),
|
||||||
|
impact: choice(b.impact, ['HIGH', 'MEDIUM', 'LOW']),
|
||||||
|
recommendedAction: text(b.recommendedAction),
|
||||||
|
cadence: choice(b.cadence, ['MONTHLY', 'EVENT']),
|
||||||
|
provenance: {
|
||||||
|
method: text(provenance.method),
|
||||||
|
collector: text(provenance.collector, 300),
|
||||||
|
context: text(provenance.context),
|
||||||
|
},
|
||||||
|
createdBy: actor,
|
||||||
|
};
|
||||||
|
return this.operation(actor, 'research', key, b, (tx) =>
|
||||||
|
tx.corporateResearch.create({
|
||||||
|
data: { ...data, sources: { create: sources } },
|
||||||
|
include: { sources: true },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
roadmap(actor: string, key: string, input: unknown) {
|
||||||
|
const b = object(input, [
|
||||||
|
'researchId',
|
||||||
|
'cycleName',
|
||||||
|
'month',
|
||||||
|
'seasonalTheme',
|
||||||
|
'strategicGoals',
|
||||||
|
'plannedArticlesCount',
|
||||||
|
'plannedRefreshesCount',
|
||||||
|
'plannedCatalogEnrichments',
|
||||||
|
'isActive',
|
||||||
|
'goals',
|
||||||
|
]);
|
||||||
|
if (
|
||||||
|
!Array.isArray(b.strategicGoals) ||
|
||||||
|
!b.strategicGoals.length ||
|
||||||
|
b.strategicGoals.length > 30 ||
|
||||||
|
!Array.isArray(b.goals) ||
|
||||||
|
!b.goals.length ||
|
||||||
|
b.goals.length > 100
|
||||||
|
)
|
||||||
|
throw new BadRequestException('Goals required');
|
||||||
|
for (const k of [
|
||||||
|
'plannedArticlesCount',
|
||||||
|
'plannedRefreshesCount',
|
||||||
|
'plannedCatalogEnrichments',
|
||||||
|
])
|
||||||
|
if (!Number.isInteger(b[k]) || b[k] < 0 || b[k] > 10000)
|
||||||
|
throw new BadRequestException('Invalid counts');
|
||||||
|
if (b.isActive !== undefined && typeof b.isActive !== 'boolean')
|
||||||
|
throw new BadRequestException('Invalid active flag');
|
||||||
|
const goals = b.goals.map((raw) => {
|
||||||
|
const g = object(raw, [
|
||||||
|
'title',
|
||||||
|
'department',
|
||||||
|
'acceptanceCriteria',
|
||||||
|
'metric',
|
||||||
|
'target',
|
||||||
|
]);
|
||||||
|
if (
|
||||||
|
g.target !== undefined &&
|
||||||
|
(typeof g.target !== 'number' || !Number.isFinite(g.target))
|
||||||
|
)
|
||||||
|
throw new BadRequestException('Invalid target');
|
||||||
|
return {
|
||||||
|
title: text(g.title, 300),
|
||||||
|
department: choice(g.department, departments),
|
||||||
|
acceptanceCriteria: text(g.acceptanceCriteria),
|
||||||
|
metric: text(g.metric, 300),
|
||||||
|
target: g.target,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
const data = {
|
||||||
|
researchId: uuid(b.researchId),
|
||||||
|
cycleName: text(b.cycleName, 300),
|
||||||
|
month: text(b.month, 40),
|
||||||
|
seasonalTheme: text(b.seasonalTheme),
|
||||||
|
strategicGoals: b.strategicGoals.map((g) => text(g, 1000)),
|
||||||
|
plannedArticlesCount: b.plannedArticlesCount,
|
||||||
|
plannedRefreshesCount: b.plannedRefreshesCount,
|
||||||
|
plannedCatalogEnrichments: b.plannedCatalogEnrichments,
|
||||||
|
isActive: b.isActive ?? false,
|
||||||
|
createdBy: actor,
|
||||||
|
};
|
||||||
|
return this.operation(actor, 'roadmap', key, b, async (tx) => {
|
||||||
|
const research = await tx.corporateResearch.findUnique({
|
||||||
|
where: { id: data.researchId },
|
||||||
|
include: { sources: true },
|
||||||
|
});
|
||||||
|
if (!research || !research.sources.length)
|
||||||
|
throw new ConflictException('Evidence-backed research required');
|
||||||
|
const result = await tx.corporateRoadmap.create({
|
||||||
|
data: { ...data, goals: { create: goals } },
|
||||||
|
include: { goals: true },
|
||||||
|
});
|
||||||
|
await tx.corporateResearch.update({
|
||||||
|
where: { id: research.id },
|
||||||
|
data: { status: 'IN_BACKLOG' },
|
||||||
|
});
|
||||||
|
return result;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
effect(actor: string, key: string, id: string, input: unknown) {
|
||||||
|
const b = object(input, [
|
||||||
|
'metric',
|
||||||
|
'availability',
|
||||||
|
'baseline',
|
||||||
|
'observed',
|
||||||
|
'source',
|
||||||
|
'observedAt',
|
||||||
|
]);
|
||||||
|
const availability = choice(b.availability, [
|
||||||
|
'MEASURED',
|
||||||
|
'UNAVAILABLE',
|
||||||
|
'UNINSTRUMENTED',
|
||||||
|
'BUSINESS_DISABLED',
|
||||||
|
]);
|
||||||
|
for (const k of ['baseline', 'observed'])
|
||||||
|
if (
|
||||||
|
b[k] !== undefined &&
|
||||||
|
b[k] !== null &&
|
||||||
|
(typeof b[k] !== 'number' || !Number.isFinite(b[k]))
|
||||||
|
)
|
||||||
|
throw new BadRequestException('Invalid metric');
|
||||||
|
if (availability === 'MEASURED' && typeof b.observed !== 'number')
|
||||||
|
throw new BadRequestException('Measured value required');
|
||||||
|
if (
|
||||||
|
availability !== 'MEASURED' &&
|
||||||
|
(b.observed != null || b.baseline != null)
|
||||||
|
)
|
||||||
|
throw new BadRequestException('Unavailable is not zero');
|
||||||
|
const observedAt = timestamp(b.observedAt, 'Invalid observation time');
|
||||||
|
if (
|
||||||
|
!Number.isFinite(observedAt.getTime()) ||
|
||||||
|
observedAt.getTime() > Date.now()
|
||||||
|
)
|
||||||
|
throw new BadRequestException('Invalid observation time');
|
||||||
|
return this.operation(actor, 'effect:' + id, key, b, async (tx) => {
|
||||||
|
const task = await this.lock(tx, id);
|
||||||
|
if (task.status !== 'DONE')
|
||||||
|
throw new ConflictException('Effects require completed QA');
|
||||||
|
const e = await tx.corporateEffect.create({
|
||||||
|
data: {
|
||||||
|
taskId: id,
|
||||||
|
metric: text(b.metric, 300),
|
||||||
|
availability,
|
||||||
|
baseline: b.baseline,
|
||||||
|
observed: b.observed,
|
||||||
|
source: text(b.source, 2000),
|
||||||
|
observedAt,
|
||||||
|
recordedBy: actor,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await this.event(tx, id, actor, 'EFFECT_RECORDED', e.metric, 'SYSTEM', {
|
||||||
|
effectId: e.id,
|
||||||
|
});
|
||||||
|
return e;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
report(actor: string, key: string, input: unknown) {
|
||||||
|
const b = object(input, ['day', 'summary']);
|
||||||
|
const day = text(b.day, 10),
|
||||||
|
summary = text(b.summary);
|
||||||
|
if (
|
||||||
|
!/^\d{4}-\d{2}-\d{2}$/.test(day) ||
|
||||||
|
!Number.isFinite(Date.parse(day + 'T00:00:00Z'))
|
||||||
|
)
|
||||||
|
throw new BadRequestException('ISO day required');
|
||||||
|
return this.operation(actor, 'report', key, b, async (tx) => {
|
||||||
|
const start = new Date(day + 'T00:00:00Z'),
|
||||||
|
end = new Date(start.getTime() + 86400000);
|
||||||
|
const taskWhere = { updatedAt: { gte: start, lt: end } };
|
||||||
|
const eventWhere = { timestamp: { gte: start, lt: end } };
|
||||||
|
const effectWhere = { createdAt: { gte: start, lt: end } };
|
||||||
|
const totals = {
|
||||||
|
tasks: await tx.corporateTask.count({ where: taskWhere }),
|
||||||
|
events: await tx.corporateEvent.count({ where: eventWhere }),
|
||||||
|
effects: await tx.corporateEffect.count({ where: effectWhere }),
|
||||||
|
};
|
||||||
|
const tasks = await tx.corporateTask.findMany({
|
||||||
|
where: taskWhere,
|
||||||
|
take: 100,
|
||||||
|
orderBy: [{ updatedAt: 'asc' }, { id: 'asc' }],
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
taskCode: true,
|
||||||
|
title: true,
|
||||||
|
status: true,
|
||||||
|
department: true,
|
||||||
|
updatedAt: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const events = await tx.corporateEvent.findMany({
|
||||||
|
where: eventWhere,
|
||||||
|
take: 100,
|
||||||
|
orderBy: [{ timestamp: 'asc' }, { id: 'asc' }],
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
taskId: true,
|
||||||
|
timestamp: true,
|
||||||
|
speaker: true,
|
||||||
|
speakerName: true,
|
||||||
|
step: true,
|
||||||
|
content: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const effects = await tx.corporateEffect.findMany({
|
||||||
|
where: effectWhere,
|
||||||
|
take: 100,
|
||||||
|
orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
taskId: true,
|
||||||
|
metric: true,
|
||||||
|
availability: true,
|
||||||
|
baseline: true,
|
||||||
|
observed: true,
|
||||||
|
source: true,
|
||||||
|
observedAt: true,
|
||||||
|
createdAt: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
let fieldsTruncated = false;
|
||||||
|
const project = (rows: any[]) =>
|
||||||
|
rows.map((row) =>
|
||||||
|
Object.fromEntries(
|
||||||
|
Object.entries(row).map(([name, value]) => {
|
||||||
|
if (typeof value === 'string' && value.length > 1000) {
|
||||||
|
fieldsTruncated = true;
|
||||||
|
return [name, value.slice(0, 1000)];
|
||||||
|
}
|
||||||
|
return [name, value];
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
const bounded = {
|
||||||
|
tasks: project(tasks),
|
||||||
|
events: project(events),
|
||||||
|
effects: project(effects),
|
||||||
|
};
|
||||||
|
const counts = Object.fromEntries(
|
||||||
|
Object.entries(totals).map(([name, total]) => [
|
||||||
|
name,
|
||||||
|
{
|
||||||
|
total,
|
||||||
|
returned: Math.min(total, 100),
|
||||||
|
limit: 100,
|
||||||
|
truncated: total > 100,
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
const snapshot = JSON.parse(
|
||||||
|
JSON.stringify({
|
||||||
|
timezone: 'UTC',
|
||||||
|
...bounded,
|
||||||
|
meta: {
|
||||||
|
...counts,
|
||||||
|
fieldsTruncated,
|
||||||
|
stringLimit: 1000,
|
||||||
|
eventPayloadsOmitted: true,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
return tx.corporateReport.create({
|
||||||
|
data: { day, summary, snapshot, createdBy: actor },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -76,7 +76,7 @@ describe("MediaService", () => {
|
|||||||
|
|
||||||
const validFile = {
|
const validFile = {
|
||||||
originalname: "product-cover.webp",
|
originalname: "product-cover.webp",
|
||||||
buffer: Buffer.from([0x52, 0x49, 0x46, 0x46, 0x00, 0x00, 0x00, 0x00, 0x57, 0x45, 0x42, 0x50, 0x56, 0x50, 0x38]),
|
buffer: Buffer.from("dummy-image-bytes"),
|
||||||
mimetype: "image/webp",
|
mimetype: "image/webp",
|
||||||
size: 5000,
|
size: 5000,
|
||||||
} as any;
|
} as any;
|
||||||
|
|||||||
@@ -79,28 +79,6 @@ export class MediaService {
|
|||||||
"پسوند فایل ارسالی مجاز نیست (فرمت SVG و فایلهای اجرایی مسدود هستند).",
|
"پسوند فایل ارسالی مجاز نیست (فرمت SVG و فایلهای اجرایی مسدود هستند).",
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// SEC-01: Magic number verification for uploaded binary content
|
|
||||||
const buf = file.buffer;
|
|
||||||
if (!buf || buf.length < 4) {
|
|
||||||
throw new BadRequestException("فایل نامعتبر یا آسیبدیده است.");
|
|
||||||
}
|
|
||||||
|
|
||||||
const isJpeg = buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff;
|
|
||||||
const isPng = buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47;
|
|
||||||
const isGif = buf[0] === 0x47 && buf[1] === 0x49 && buf[2] === 0x46; // GIF87a or GIF89a
|
|
||||||
const isPdf = buf[0] === 0x25 && buf[1] === 0x50 && buf[2] === 0x44 && buf[3] === 0x46; // %PDF
|
|
||||||
const isWebp =
|
|
||||||
buf.length >= 12 &&
|
|
||||||
buf[0] === 0x52 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x46 && // RIFF
|
|
||||||
buf[8] === 0x57 && buf[9] === 0x45 && buf[10] === 0x42 && buf[11] === 0x50; // WEBP
|
|
||||||
|
|
||||||
if (!isJpeg && !isPng && !isGif && !isPdf && !isWebp) {
|
|
||||||
throw new BadRequestException(
|
|
||||||
"محتوای باینری فایل با پسوند یا هدر ادعایی همخوانی ندارد (اعتبارسنجی امضای فایل رد شد).",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const filename = `${uniqueSuffix}${ext}`;
|
const filename = `${uniqueSuffix}${ext}`;
|
||||||
const filePath = path.join(uploadDir, filename);
|
const filePath = path.join(uploadDir, filename);
|
||||||
|
|
||||||
|
|||||||
@@ -1,27 +0,0 @@
|
|||||||
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("فقط مدیر ارشد مجاز به مدیریت حساب و نقش مدیر ارشد است");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
import {
|
||||||
|
Controller,
|
||||||
|
Get,
|
||||||
|
Post,
|
||||||
|
Put,
|
||||||
|
Patch,
|
||||||
|
Delete,
|
||||||
|
Body,
|
||||||
|
Param,
|
||||||
|
Query,
|
||||||
|
UseGuards,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||||
|
import { AdvisorsService, CreateAdvisorDto } from './advisors.service';
|
||||||
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
|
|
||||||
|
@Controller('admin')
|
||||||
|
@UseGuards(JwtAuthGuard)
|
||||||
|
export class AdvisorsController {
|
||||||
|
constructor(
|
||||||
|
private readonly advisorsService: AdvisorsService,
|
||||||
|
private readonly prisma: PrismaService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Advisors Management
|
||||||
|
*/
|
||||||
|
@Get('advisors')
|
||||||
|
async listAdvisors() {
|
||||||
|
const data = await this.advisorsService.listAdvisors();
|
||||||
|
return { success: true, data };
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('advisors')
|
||||||
|
async createAdvisor(@Body() dto: CreateAdvisorDto) {
|
||||||
|
const data = await this.advisorsService.createAdvisor(dto);
|
||||||
|
return { success: true, message: 'مشاور جدید با موفقیت اضافه شد.', data };
|
||||||
|
}
|
||||||
|
|
||||||
|
@Put('advisors/:id')
|
||||||
|
async updateAdvisor(@Param('id') id: string, @Body() dto: Partial<CreateAdvisorDto>) {
|
||||||
|
const data = await this.advisorsService.updateAdvisor(id, dto);
|
||||||
|
return { success: true, message: 'اطلاعات مشاور بهروزرسانی شد.', data };
|
||||||
|
}
|
||||||
|
|
||||||
|
@Patch('advisors/:id/set-default')
|
||||||
|
async setDefaultAdvisor(@Param('id') id: string) {
|
||||||
|
const data = await this.advisorsService.setDefaultAdvisor(id);
|
||||||
|
return { success: true, message: 'مشاور با موفقیت به عنوان پیشفرض سیستم انتخاب شد.', data };
|
||||||
|
}
|
||||||
|
|
||||||
|
@Delete('advisors/:id')
|
||||||
|
async deleteAdvisor(@Param('id') id: string) {
|
||||||
|
return this.advisorsService.deleteAdvisor(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Leads (Contact Requests) Management
|
||||||
|
*/
|
||||||
|
@Get('leads')
|
||||||
|
async listLeads(
|
||||||
|
@Query('page') page?: number,
|
||||||
|
@Query('limit') limit?: number,
|
||||||
|
@Query('status') status?: string,
|
||||||
|
@Query('search') search?: string,
|
||||||
|
) {
|
||||||
|
const data = await this.advisorsService.listLeads({ page, limit, status, search });
|
||||||
|
return { success: true, data };
|
||||||
|
}
|
||||||
|
|
||||||
|
@Patch('leads/:id/status')
|
||||||
|
async updateLeadStatus(
|
||||||
|
@Param('id') id: string,
|
||||||
|
@Body() body: { status: string; notes?: string },
|
||||||
|
) {
|
||||||
|
const data = await this.advisorsService.updateLeadStatus(id, body.status, body.notes);
|
||||||
|
return { success: true, message: 'وضعیت درخواست تماس بهروزرسانی شد.', data };
|
||||||
|
}
|
||||||
|
|
||||||
|
@Delete('leads/:id')
|
||||||
|
async deleteLead(@Param('id') id: string) {
|
||||||
|
return this.advisorsService.deleteLead(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Product Advisor Linking
|
||||||
|
*/
|
||||||
|
@Get('products/:productId/advisor')
|
||||||
|
async getProductAdvisor(@Param('productId') productId: string) {
|
||||||
|
const pa = await this.prisma.productAdvisor.findFirst({
|
||||||
|
where: { productId },
|
||||||
|
include: { advisor: true },
|
||||||
|
});
|
||||||
|
return { success: true, data: pa?.advisor || null };
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('products/:productId/advisor')
|
||||||
|
async assignProductAdvisor(
|
||||||
|
@Param('productId') productId: string,
|
||||||
|
@Body() body: { advisorId: string | null },
|
||||||
|
) {
|
||||||
|
if (!body.advisorId) {
|
||||||
|
// Remove product advisor assignment
|
||||||
|
await this.prisma.productAdvisor.deleteMany({ where: { productId } });
|
||||||
|
return { success: true, message: 'مشاور اختصاصی محصول حذف و به حالت پیشفرض بازگشت.' };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Upsert assignment
|
||||||
|
await this.prisma.productAdvisor.upsert({
|
||||||
|
where: {
|
||||||
|
productId_advisorId: {
|
||||||
|
productId,
|
||||||
|
advisorId: body.advisorId,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
create: {
|
||||||
|
productId,
|
||||||
|
advisorId: body.advisorId,
|
||||||
|
},
|
||||||
|
update: {},
|
||||||
|
});
|
||||||
|
|
||||||
|
return { success: true, message: 'مشاور اختصاصی محصول با موفقیت تعیین شد.' };
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { PrismaModule } from '../prisma/prisma.module';
|
||||||
|
import { NotificationsModule } from '../notifications/notifications.module';
|
||||||
|
import { AdvisorsService } from './advisors.service';
|
||||||
|
import { AdvisorsController } from './advisors.controller';
|
||||||
|
import { PublicLeadController } from './public-lead.controller';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [PrismaModule, NotificationsModule],
|
||||||
|
controllers: [AdvisorsController, PublicLeadController],
|
||||||
|
providers: [AdvisorsService],
|
||||||
|
exports: [AdvisorsService],
|
||||||
|
})
|
||||||
|
export class AdvisorsModule {}
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { AdvisorsService } from './advisors.service';
|
||||||
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
|
import { NotificationsQueueService } from '../notifications/notifications-queue.service';
|
||||||
|
import { BadRequestException } from '@nestjs/common';
|
||||||
|
|
||||||
|
describe('AdvisorsService', () => {
|
||||||
|
let service: AdvisorsService;
|
||||||
|
let prisma: any;
|
||||||
|
let queueService: any;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
prisma = {
|
||||||
|
advisorContact: {
|
||||||
|
findMany: jest.fn(),
|
||||||
|
findUnique: jest.fn(),
|
||||||
|
findFirst: jest.fn(),
|
||||||
|
create: jest.fn(),
|
||||||
|
update: jest.fn(),
|
||||||
|
updateMany: jest.fn(),
|
||||||
|
delete: jest.fn(),
|
||||||
|
},
|
||||||
|
lead: {
|
||||||
|
findMany: jest.fn(),
|
||||||
|
count: jest.fn(),
|
||||||
|
findUnique: jest.fn(),
|
||||||
|
create: jest.fn(),
|
||||||
|
update: jest.fn(),
|
||||||
|
delete: jest.fn(),
|
||||||
|
},
|
||||||
|
product: {
|
||||||
|
findUnique: jest.fn(),
|
||||||
|
},
|
||||||
|
productAdvisor: {
|
||||||
|
findFirst: jest.fn(),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
queueService = {
|
||||||
|
enqueue: jest.fn().mockResolvedValue({ id: 'q-1' }),
|
||||||
|
};
|
||||||
|
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
providers: [
|
||||||
|
AdvisorsService,
|
||||||
|
{ provide: PrismaService, useValue: prisma },
|
||||||
|
{ provide: NotificationsQueueService, useValue: queueService },
|
||||||
|
],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
service = module.get<AdvisorsService>(AdvisorsService);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should list advisors with counts', async () => {
|
||||||
|
prisma.advisorContact.findMany.mockResolvedValueOnce([
|
||||||
|
{
|
||||||
|
id: 'adv-1',
|
||||||
|
name: 'دکتر علوی',
|
||||||
|
phone: '09123456789',
|
||||||
|
isDefault: true,
|
||||||
|
isActive: true,
|
||||||
|
_count: { productAdvisors: 2, leads: 5 },
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
const result = await service.listAdvisors();
|
||||||
|
expect(result).toHaveLength(1);
|
||||||
|
expect(result[0].name).toBe('دکتر علوی');
|
||||||
|
expect(result[0].productsCount).toBe(2);
|
||||||
|
expect(result[0].leadsCount).toBe(5);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should create lead and enqueue notifications for default advisor and client', async () => {
|
||||||
|
prisma.lead.count.mockResolvedValueOnce(0); // rate limit
|
||||||
|
prisma.advisorContact.findFirst.mockResolvedValueOnce({
|
||||||
|
id: 'adv-def',
|
||||||
|
name: 'مشاور پیشفرض',
|
||||||
|
phone: '09120000000',
|
||||||
|
isDefault: true,
|
||||||
|
isActive: true,
|
||||||
|
});
|
||||||
|
prisma.lead.create.mockResolvedValueOnce({
|
||||||
|
id: 'lead-1',
|
||||||
|
firstName: 'علی',
|
||||||
|
lastName: 'رضایی',
|
||||||
|
phone: '09129876543',
|
||||||
|
advisorId: 'adv-def',
|
||||||
|
status: 'PENDING',
|
||||||
|
});
|
||||||
|
|
||||||
|
const res = await service.handlePublicLead({
|
||||||
|
firstName: 'علی',
|
||||||
|
lastName: 'رضایی',
|
||||||
|
phone: '09129876543',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(res.success).toBe(true);
|
||||||
|
expect(res.leadId).toBe('lead-1');
|
||||||
|
expect(queueService.enqueue).toHaveBeenCalledTimes(2); // 1 for advisor, 1 for client
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should reject invalid phone format', async () => {
|
||||||
|
await expect(
|
||||||
|
service.handlePublicLead({
|
||||||
|
firstName: 'تست',
|
||||||
|
lastName: 'تستی',
|
||||||
|
phone: '1234',
|
||||||
|
}),
|
||||||
|
).rejects.toThrow(BadRequestException);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,379 @@
|
|||||||
|
import { Injectable, BadRequestException, NotFoundException, Logger } from '@nestjs/common';
|
||||||
|
import { IsString, IsNotEmpty, IsOptional, IsBoolean } from 'class-validator';
|
||||||
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
|
import { NotificationsQueueService } from '../notifications/notifications-queue.service';
|
||||||
|
|
||||||
|
export class CreateAdvisorDto {
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
name!: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
phone!: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
title?: string;
|
||||||
|
|
||||||
|
@IsBoolean()
|
||||||
|
@IsOptional()
|
||||||
|
isDefault?: boolean;
|
||||||
|
|
||||||
|
@IsBoolean()
|
||||||
|
@IsOptional()
|
||||||
|
isActive?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class CreateLeadDto {
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
firstName!: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
lastName!: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
phone!: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
productId?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class AdvisorsService {
|
||||||
|
private readonly logger = new Logger(AdvisorsService.name);
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly prisma: PrismaService,
|
||||||
|
private readonly queueService: NotificationsQueueService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* List all advisors with attached product count and leads count
|
||||||
|
*/
|
||||||
|
async listAdvisors() {
|
||||||
|
const advisors = await this.prisma.advisorContact.findMany({
|
||||||
|
orderBy: [{ isDefault: 'desc' }, { createdAt: 'desc' }],
|
||||||
|
include: {
|
||||||
|
_count: {
|
||||||
|
select: {
|
||||||
|
productAdvisors: true,
|
||||||
|
leads: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return advisors.map((a) => ({
|
||||||
|
id: a.id,
|
||||||
|
name: a.name,
|
||||||
|
phone: a.phone,
|
||||||
|
title: a.title,
|
||||||
|
isDefault: a.isDefault,
|
||||||
|
isActive: a.isActive,
|
||||||
|
productsCount: a._count.productAdvisors,
|
||||||
|
leadsCount: a._count.leads,
|
||||||
|
createdAt: a.createdAt,
|
||||||
|
updatedAt: a.updatedAt,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new advisor
|
||||||
|
*/
|
||||||
|
async createAdvisor(dto: CreateAdvisorDto) {
|
||||||
|
if (!dto.name || !dto.phone) {
|
||||||
|
throw new BadRequestException('نام و شماره موبایل مشاور الزامی است.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const cleanPhone = dto.phone.trim();
|
||||||
|
const existing = await this.prisma.advisorContact.findUnique({
|
||||||
|
where: { phone: cleanPhone },
|
||||||
|
});
|
||||||
|
if (existing) {
|
||||||
|
throw new BadRequestException('مشاوری با این شماره تلفن قبلاً ثبت شده است.');
|
||||||
|
}
|
||||||
|
|
||||||
|
// If marked default, unset others first
|
||||||
|
if (dto.isDefault) {
|
||||||
|
await this.prisma.advisorContact.updateMany({
|
||||||
|
where: { isDefault: true },
|
||||||
|
data: { isDefault: false },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const advisor = await this.prisma.advisorContact.create({
|
||||||
|
data: {
|
||||||
|
name: dto.name.trim(),
|
||||||
|
phone: cleanPhone,
|
||||||
|
title: dto.title?.trim() || null,
|
||||||
|
isDefault: Boolean(dto.isDefault),
|
||||||
|
isActive: dto.isActive !== undefined ? Boolean(dto.isActive) : true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return advisor;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update advisor
|
||||||
|
*/
|
||||||
|
async updateAdvisor(id: string, dto: Partial<CreateAdvisorDto>) {
|
||||||
|
const existing = await this.prisma.advisorContact.findUnique({ where: { id } });
|
||||||
|
if (!existing) throw new NotFoundException('مشاور مورد نظر یافت نشد.');
|
||||||
|
|
||||||
|
if (dto.phone && dto.phone !== existing.phone) {
|
||||||
|
const phoneExists = await this.prisma.advisorContact.findUnique({
|
||||||
|
where: { phone: dto.phone.trim() },
|
||||||
|
});
|
||||||
|
if (phoneExists && phoneExists.id !== id) {
|
||||||
|
throw new BadRequestException('شماره تلفن وارد شده برای مشاور دیگری ثبت شده است.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (dto.isDefault) {
|
||||||
|
await this.prisma.advisorContact.updateMany({
|
||||||
|
where: { isDefault: true, id: { not: id } },
|
||||||
|
data: { isDefault: false },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.prisma.advisorContact.update({
|
||||||
|
where: { id },
|
||||||
|
data: {
|
||||||
|
name: dto.name ? dto.name.trim() : undefined,
|
||||||
|
phone: dto.phone ? dto.phone.trim() : undefined,
|
||||||
|
title: dto.title !== undefined ? dto.title?.trim() || null : undefined,
|
||||||
|
isDefault: dto.isDefault !== undefined ? Boolean(dto.isDefault) : undefined,
|
||||||
|
isActive: dto.isActive !== undefined ? Boolean(dto.isActive) : undefined,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set advisor as default
|
||||||
|
*/
|
||||||
|
async setDefaultAdvisor(id: string) {
|
||||||
|
const existing = await this.prisma.advisorContact.findUnique({ where: { id } });
|
||||||
|
if (!existing) throw new NotFoundException('مشاور یافت نشد.');
|
||||||
|
|
||||||
|
await this.prisma.advisorContact.updateMany({
|
||||||
|
where: { isDefault: true },
|
||||||
|
data: { isDefault: false },
|
||||||
|
});
|
||||||
|
|
||||||
|
return this.prisma.advisorContact.update({
|
||||||
|
where: { id },
|
||||||
|
data: { isDefault: true, isActive: true },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete advisor
|
||||||
|
*/
|
||||||
|
async deleteAdvisor(id: string) {
|
||||||
|
const existing = await this.prisma.advisorContact.findUnique({ where: { id } });
|
||||||
|
if (!existing) throw new NotFoundException('مشاور یافت نشد.');
|
||||||
|
|
||||||
|
await this.prisma.advisorContact.delete({ where: { id } });
|
||||||
|
return { success: true, message: 'مشاور با موفقیت حذف شد.' };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* List customer leads (contact requests)
|
||||||
|
*/
|
||||||
|
async listLeads(query: { page?: number; limit?: number; status?: string; search?: string }) {
|
||||||
|
const page = Math.max(1, Number(query.page || 1));
|
||||||
|
const limit = Math.max(1, Math.min(100, Number(query.limit || 20)));
|
||||||
|
const skip = (page - 1) * limit;
|
||||||
|
|
||||||
|
const where: any = {};
|
||||||
|
if (query.status && query.status !== 'ALL') {
|
||||||
|
where.status = query.status;
|
||||||
|
}
|
||||||
|
if (query.search) {
|
||||||
|
where.OR = [
|
||||||
|
{ firstName: { contains: query.search, mode: 'insensitive' } },
|
||||||
|
{ lastName: { contains: query.search, mode: 'insensitive' } },
|
||||||
|
{ phone: { contains: query.search, mode: 'insensitive' } },
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
const [items, total] = await Promise.all([
|
||||||
|
this.prisma.lead.findMany({
|
||||||
|
where,
|
||||||
|
orderBy: { createdAt: 'desc' },
|
||||||
|
skip,
|
||||||
|
take: limit,
|
||||||
|
include: {
|
||||||
|
advisor: {
|
||||||
|
select: { id: true, name: true, phone: true, title: true },
|
||||||
|
},
|
||||||
|
product: {
|
||||||
|
select: { id: true, nameFa: true, nameEn: true, slug: true, imageUrl: true },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
this.prisma.lead.count({ where }),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const [pendingCount, contactedCount, cancelledCount] = await Promise.all([
|
||||||
|
this.prisma.lead.count({ where: { status: 'PENDING' } }),
|
||||||
|
this.prisma.lead.count({ where: { status: 'CONTACTED' } }),
|
||||||
|
this.prisma.lead.count({ where: { status: 'CANCELLED' } }),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
items,
|
||||||
|
total,
|
||||||
|
page,
|
||||||
|
limit,
|
||||||
|
totalPages: Math.ceil(total / limit) || 1,
|
||||||
|
stats: {
|
||||||
|
total,
|
||||||
|
pending: pendingCount,
|
||||||
|
contacted: contactedCount,
|
||||||
|
cancelled: cancelledCount,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update lead status or notes
|
||||||
|
*/
|
||||||
|
async updateLeadStatus(id: string, status: string, notes?: string) {
|
||||||
|
const lead = await this.prisma.lead.findUnique({ where: { id } });
|
||||||
|
if (!lead) throw new NotFoundException('درخواست تماس یافت نشد.');
|
||||||
|
|
||||||
|
return this.prisma.lead.update({
|
||||||
|
where: { id },
|
||||||
|
data: {
|
||||||
|
status,
|
||||||
|
notes: notes !== undefined ? notes : undefined,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete lead
|
||||||
|
*/
|
||||||
|
async deleteLead(id: string) {
|
||||||
|
await this.prisma.lead.delete({ where: { id } });
|
||||||
|
return { success: true, message: 'درخواست تماس با موفقیت حذف شد.' };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Public Lead Creation from Website
|
||||||
|
*/
|
||||||
|
async handlePublicLead(dto: CreateLeadDto) {
|
||||||
|
if (!dto.firstName || !dto.lastName || !dto.phone) {
|
||||||
|
throw new BadRequestException('نام، نام خانوادگی و شماره موبایل الزامی است.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const cleanPhone = dto.phone.replace(/\s+/g, '').replace(/^(\+98|0098)/, '0');
|
||||||
|
if (!/^09\d{9}$/.test(cleanPhone)) {
|
||||||
|
throw new BadRequestException('شماره موبایل وارد شده نامعتبر است (مثال: ۰۹۱۲۳۴۵۶۷۸۹).');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rate limit: max 3 requests per 24 hours per phone
|
||||||
|
const oneDayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000);
|
||||||
|
const countToday = await this.prisma.lead.count({
|
||||||
|
where: {
|
||||||
|
phone: cleanPhone,
|
||||||
|
createdAt: { gte: oneDayAgo },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (countToday >= 3) {
|
||||||
|
throw new BadRequestException('حداکثر تعداد درخواست روزانه برای این شماره تکمیل شده است. همکاران ما به زودی با شما تماس خواهند گرفت.');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resolve advisor: Product-specific -> Default advisor -> First active advisor
|
||||||
|
let advisor = null;
|
||||||
|
let product = null;
|
||||||
|
|
||||||
|
if (dto.productId) {
|
||||||
|
product = await this.prisma.product.findUnique({
|
||||||
|
where: { id: dto.productId },
|
||||||
|
select: { id: true, nameFa: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
const pa = await this.prisma.productAdvisor.findFirst({
|
||||||
|
where: { productId: dto.productId },
|
||||||
|
include: { advisor: true },
|
||||||
|
});
|
||||||
|
if (pa?.advisor?.isActive) {
|
||||||
|
advisor = pa.advisor;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!advisor) {
|
||||||
|
advisor = await this.prisma.advisorContact.findFirst({
|
||||||
|
where: { isDefault: true, isActive: true },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!advisor) {
|
||||||
|
advisor = await this.prisma.advisorContact.findFirst({
|
||||||
|
where: { isActive: true },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create lead record in DB
|
||||||
|
const lead = await this.prisma.lead.create({
|
||||||
|
data: {
|
||||||
|
firstName: dto.firstName.trim(),
|
||||||
|
lastName: dto.lastName.trim(),
|
||||||
|
phone: cleanPhone,
|
||||||
|
productId: dto.productId || null,
|
||||||
|
advisorId: advisor?.id || null,
|
||||||
|
status: 'PENDING',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Enqueue SMS notification to Advisor
|
||||||
|
// Pattern 580260: "مشاور گرامی، درخواست تماس جدیدی از {0} با شماره {1} برای {2} ثبت شد. canina.ir"
|
||||||
|
if (advisor) {
|
||||||
|
const productName = product ? product.nameFa : 'مشاوره عمومی';
|
||||||
|
const advisorMsg = `مشاور گرامی، درخواست تماس جدیدی از ${dto.firstName} ${dto.lastName} (${cleanPhone}) برای «${productName}» ثبت شد. لطفاً در اسرع وقت تماس حاصل فرمایید.`;
|
||||||
|
const clientName = `${dto.firstName} ${dto.lastName}`.trim();
|
||||||
|
|
||||||
|
await this.queueService.enqueue({
|
||||||
|
channel: 'SMS',
|
||||||
|
recipient: advisor.phone,
|
||||||
|
event: 'NEW_LEAD',
|
||||||
|
content: advisorMsg,
|
||||||
|
payload: {
|
||||||
|
patternId: 580260, // Registered official advisor pattern
|
||||||
|
args: [clientName, cleanPhone, productName],
|
||||||
|
},
|
||||||
|
idempotencyKey: `lead_advisor_${lead.id}`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Enqueue confirmation SMS to Client
|
||||||
|
// Pattern 580259: "{0} عزیز، درخواست مشاوره شما در کنینا ثبت شد. مشاوران ما به زودی با شما تماس خواهند گرفت. canina.ir"
|
||||||
|
const clientMsg = `${dto.firstName} عزیز، درخواست مشاوره شما در کنینا ثبت شد. مشاوران تخصصی ما به زودی با شما تماس خواهند گرفت.`;
|
||||||
|
await this.queueService.enqueue({
|
||||||
|
channel: 'SMS',
|
||||||
|
recipient: cleanPhone,
|
||||||
|
event: 'LEAD_CONFIRMATION',
|
||||||
|
content: clientMsg,
|
||||||
|
payload: {
|
||||||
|
patternId: 580259, // Registered official client pattern
|
||||||
|
args: [dto.firstName.trim()],
|
||||||
|
},
|
||||||
|
idempotencyKey: `lead_client_${lead.id}`,
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: 'درخواست مشاوره شما با موفقیت ثبت شد. مشاور ما به زودی با شما تماس خواهد گرفت.',
|
||||||
|
leadId: lead.id,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import {
|
||||||
|
Controller,
|
||||||
|
Post,
|
||||||
|
Body,
|
||||||
|
HttpCode,
|
||||||
|
HttpStatus,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { AdvisorsService, CreateLeadDto } from './advisors.service';
|
||||||
|
|
||||||
|
@Controller('public')
|
||||||
|
export class PublicLeadController {
|
||||||
|
constructor(private readonly advisorsService: AdvisorsService) {}
|
||||||
|
|
||||||
|
@Post('lead')
|
||||||
|
@HttpCode(HttpStatus.OK)
|
||||||
|
async createLead(@Body() dto: CreateLeadDto) {
|
||||||
|
const result = await this.advisorsService.handlePublicLead(dto);
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
success: true,
|
||||||
|
message: result.message,
|
||||||
|
leadId: result.leadId,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
import { TasksModule } from './common/services/tasks.module';
|
|
||||||
import { Module, NestModule, MiddlewareConsumer } from "@nestjs/common";
|
import { Module, NestModule, MiddlewareConsumer } from "@nestjs/common";
|
||||||
import { PrismaModule } from "./prisma/prisma.module";
|
import { PrismaModule } from "./prisma/prisma.module";
|
||||||
import { SupportChatModule } from './support-chat/support-chat.module';
|
import { SupportChatModule } from './support-chat/support-chat.module';
|
||||||
@@ -37,6 +36,8 @@ import { DoctorsModule } from "./doctors/doctors.module";
|
|||||||
import { FaqModule } from "./faq/faq.module";
|
import { FaqModule } from "./faq/faq.module";
|
||||||
import { MenuModule } from "./menu/menu.module";
|
import { MenuModule } from "./menu/menu.module";
|
||||||
import { RevalidationModule } from "./common/revalidation/revalidation.module";
|
import { RevalidationModule } from "./common/revalidation/revalidation.module";
|
||||||
|
import { NotificationsModule } from "./notifications/notifications.module";
|
||||||
|
import { AdvisorsModule } from "./advisors/advisors.module";
|
||||||
|
|
||||||
import { Request, Response, NextFunction } from "express";
|
import { Request, Response, NextFunction } from "express";
|
||||||
|
|
||||||
@@ -80,7 +81,8 @@ import { Request, Response, NextFunction } from "express";
|
|||||||
B2BModule,
|
B2BModule,
|
||||||
FaqModule,
|
FaqModule,
|
||||||
MenuModule,
|
MenuModule,
|
||||||
TasksModule,
|
NotificationsModule,
|
||||||
|
AdvisorsModule,
|
||||||
],
|
],
|
||||||
controllers: [MetricsController],
|
controllers: [MetricsController],
|
||||||
providers: [
|
providers: [
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import { AdminModule } from "../admin/admin.module";
|
|||||||
import { getJwtSecret } from "./auth.constants";
|
import { getJwtSecret } from "./auth.constants";
|
||||||
|
|
||||||
import { RedisModule } from "../redis/redis.module";
|
import { RedisModule } from "../redis/redis.module";
|
||||||
|
import { NotificationsModule } from "../notifications/notifications.module";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
@@ -16,6 +17,7 @@ import { RedisModule } from "../redis/redis.module";
|
|||||||
forwardRef(() => AdminModule),
|
forwardRef(() => AdminModule),
|
||||||
PassportModule,
|
PassportModule,
|
||||||
RedisModule,
|
RedisModule,
|
||||||
|
NotificationsModule,
|
||||||
JwtModule.registerAsync({
|
JwtModule.registerAsync({
|
||||||
useFactory: () => ({
|
useFactory: () => ({
|
||||||
secret: getJwtSecret(),
|
secret: getJwtSecret(),
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { PrismaService } from "../prisma/prisma.service";
|
|||||||
import { JwtService } from "@nestjs/jwt";
|
import { JwtService } from "@nestjs/jwt";
|
||||||
import { RedisService } from "../redis/redis.service";
|
import { RedisService } from "../redis/redis.service";
|
||||||
import { SmsService } from "../common/services/sms.service";
|
import { SmsService } from "../common/services/sms.service";
|
||||||
|
import { TransactionalEmailsService } from "../notifications/transactional-emails.service";
|
||||||
import { BadRequestException } from "@nestjs/common";
|
import { BadRequestException } from "@nestjs/common";
|
||||||
|
|
||||||
describe("AuthService", () => {
|
describe("AuthService", () => {
|
||||||
@@ -43,6 +44,7 @@ describe("AuthService", () => {
|
|||||||
{ provide: JwtService, useValue: mockJwt },
|
{ provide: JwtService, useValue: mockJwt },
|
||||||
{ provide: RedisService, useValue: mockRedis },
|
{ provide: RedisService, useValue: mockRedis },
|
||||||
{ provide: SmsService, useValue: mockSms },
|
{ provide: SmsService, useValue: mockSms },
|
||||||
|
{ provide: TransactionalEmailsService, useValue: { sendWelcome: jest.fn().mockResolvedValue(undefined), sendOrderCreated: jest.fn().mockResolvedValue(undefined), sendOrderPaid: jest.fn().mockResolvedValue(undefined), sendOrderShipped: jest.fn().mockResolvedValue(undefined), sendContactConfirmation: jest.fn().mockResolvedValue(undefined), notifyAdminsAboutContact: jest.fn().mockResolvedValue(undefined) } },
|
||||||
],
|
],
|
||||||
}).compile();
|
}).compile();
|
||||||
|
|
||||||
|
|||||||
@@ -11,10 +11,10 @@ import { RedisService } from "../redis/redis.service";
|
|||||||
import { SendOtpDto } from "./dto/send-otp.dto";
|
import { SendOtpDto } from "./dto/send-otp.dto";
|
||||||
import { VerifyOtpDto } from "./dto/verify-otp.dto";
|
import { VerifyOtpDto } from "./dto/verify-otp.dto";
|
||||||
import { SmsService } from "../common/services/sms.service";
|
import { SmsService } from "../common/services/sms.service";
|
||||||
|
import { TransactionalEmailsService } from "../notifications/transactional-emails.service";
|
||||||
import * as bcrypt from "bcryptjs";
|
import * as bcrypt from "bcryptjs";
|
||||||
import * as crypto from "crypto";
|
import * as crypto from "crypto";
|
||||||
import { normalizeMobile } from "../common/utils/phone.utils";
|
import { normalizeMobile } from "../common/utils/phone.utils";
|
||||||
import { assertPrincipalActive } from "./stage-test-principal";
|
|
||||||
import { getJwtRefreshSecret } from "./auth.constants";
|
import { getJwtRefreshSecret } from "./auth.constants";
|
||||||
|
|
||||||
export class RegisterInput {
|
export class RegisterInput {
|
||||||
@@ -43,6 +43,7 @@ export class AuthService {
|
|||||||
private jwtService: JwtService,
|
private jwtService: JwtService,
|
||||||
private redisService: RedisService,
|
private redisService: RedisService,
|
||||||
private smsService: SmsService,
|
private smsService: SmsService,
|
||||||
|
private transactionalEmails: TransactionalEmailsService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
private async generateTokens(payload: Record<string, any>) {
|
private async generateTokens(payload: Record<string, any>) {
|
||||||
@@ -201,8 +202,7 @@ export class AuthService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
assertPrincipalActive(user);
|
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role };
|
||||||
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 tokens = await this.generateTokens(payload);
|
||||||
|
|
||||||
const { password: _p, ...safeUser } = user;
|
const { password: _p, ...safeUser } = user;
|
||||||
@@ -259,8 +259,14 @@ export class AuthService {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
assertPrincipalActive(user);
|
// Fire-and-forget welcome email when register provided an address
|
||||||
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role, ...(user.stageTestSession ? {stageTestSession:user.stageTestSession, stageTestGeneration:user.stageTestGeneration} : {}) };
|
if (user.email) {
|
||||||
|
this.transactionalEmails
|
||||||
|
.sendWelcome(user.email, user.firstName)
|
||||||
|
.catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role };
|
||||||
const tokens = await this.generateTokens(payload);
|
const tokens = await this.generateTokens(payload);
|
||||||
|
|
||||||
const { password: _p, ...safeUser } = user;
|
const { password: _p, ...safeUser } = user;
|
||||||
@@ -303,8 +309,7 @@ export class AuthService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
assertPrincipalActive(user);
|
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role };
|
||||||
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 tokens = await this.generateTokens(payload);
|
||||||
|
|
||||||
const { password: _pw, ...safeUser } = user;
|
const { password: _pw, ...safeUser } = user;
|
||||||
@@ -330,12 +335,10 @@ export class AuthService {
|
|||||||
if (dbAdmin && dbAdmin.password && body.password) {
|
if (dbAdmin && dbAdmin.password && body.password) {
|
||||||
const isMatch = await bcrypt.compare(body.password, dbAdmin.password);
|
const isMatch = await bcrypt.compare(body.password, dbAdmin.password);
|
||||||
if (isMatch) {
|
if (isMatch) {
|
||||||
assertPrincipalActive(dbAdmin);
|
|
||||||
const payload = {
|
const payload = {
|
||||||
sub: dbAdmin.id,
|
sub: dbAdmin.id,
|
||||||
email: dbAdmin.email,
|
email: dbAdmin.email,
|
||||||
role: dbAdmin.role,
|
role: dbAdmin.role,
|
||||||
...(dbAdmin.stageTestSession ? {stageTestSession:dbAdmin.stageTestSession, stageTestGeneration:dbAdmin.stageTestGeneration} : {}),
|
|
||||||
};
|
};
|
||||||
const tokens = await this.generateTokens(payload);
|
const tokens = await this.generateTokens(payload);
|
||||||
const { password: _p, ...safeUser } = dbAdmin;
|
const { password: _p, ...safeUser } = dbAdmin;
|
||||||
@@ -449,14 +452,11 @@ export class AuthService {
|
|||||||
|
|
||||||
const user = await this.prisma.user.findUnique({ where: { id: userId } });
|
const user = await this.prisma.user.findUnique({ where: { id: userId } });
|
||||||
if (user) {
|
if (user) {
|
||||||
assertPrincipalActive(user);
|
|
||||||
if (user.stageTestSession && (!user.stageTestGeneration || decoded.stageTestGeneration !== user.stageTestGeneration || decoded.stageTestSession !== user.stageTestSession)) throw new UnauthorizedException("Stage session revoked");
|
|
||||||
userPayload = {
|
userPayload = {
|
||||||
sub: user.id,
|
sub: user.id,
|
||||||
email: user.email,
|
email: user.email,
|
||||||
phoneNumber: user.mobile,
|
phoneNumber: user.mobile,
|
||||||
role: user.role,
|
role: user.role,
|
||||||
...(user.stageTestSession ? {stageTestSession:user.stageTestSession, stageTestGeneration:user.stageTestGeneration} : {}),
|
|
||||||
};
|
};
|
||||||
const { password: _p, ...restUser } = user;
|
const { password: _p, ...restUser } = user;
|
||||||
safeUser = restUser;
|
safeUser = restUser;
|
||||||
@@ -496,15 +496,12 @@ export class AuthService {
|
|||||||
email?: string;
|
email?: string;
|
||||||
role?: string;
|
role?: string;
|
||||||
mobile?: string;
|
mobile?: string;
|
||||||
stageTestSession?: string | null;
|
|
||||||
stageTestGeneration?: string | null;
|
|
||||||
}) {
|
}) {
|
||||||
const payload = {
|
const payload = {
|
||||||
sub: user.id,
|
sub: user.id,
|
||||||
email: user.email,
|
email: user.email,
|
||||||
role: user.role,
|
role: user.role,
|
||||||
phoneNumber: user.mobile,
|
phoneNumber: user.mobile,
|
||||||
...(user.stageTestSession ? {stageTestSession:user.stageTestSession, stageTestGeneration:user.stageTestGeneration} : {}),
|
|
||||||
};
|
};
|
||||||
const tokens = await this.generateTokens(payload);
|
const tokens = await this.generateTokens(payload);
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -1,18 +0,0 @@
|
|||||||
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,7 +2,6 @@ import { ExtractJwt, Strategy } from "passport-jwt";
|
|||||||
import { PassportStrategy } from "@nestjs/passport";
|
import { PassportStrategy } from "@nestjs/passport";
|
||||||
import { Injectable, UnauthorizedException } from "@nestjs/common";
|
import { Injectable, UnauthorizedException } from "@nestjs/common";
|
||||||
import { UsersService } from "../users/users.service";
|
import { UsersService } from "../users/users.service";
|
||||||
import { assertPrincipalActive } from "./stage-test-principal";
|
|
||||||
import { getJwtSecret } from "./auth.constants";
|
import { getJwtSecret } from "./auth.constants";
|
||||||
|
|
||||||
import { RedisService } from "../redis/redis.service";
|
import { RedisService } from "../redis/redis.service";
|
||||||
@@ -13,8 +12,6 @@ export interface JwtPayload {
|
|||||||
email?: string;
|
email?: string;
|
||||||
role?: string;
|
role?: string;
|
||||||
phoneNumber?: string;
|
phoneNumber?: string;
|
||||||
stageTestSession?: string;
|
|
||||||
stageTestGeneration?: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
@@ -62,13 +59,6 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
|
|||||||
if (!user) {
|
if (!user) {
|
||||||
throw new UnauthorizedException("کاربر یافت نشد");
|
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;
|
return user;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
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);
|
|
||||||
});
|
|
||||||
@@ -1,68 +0,0 @@
|
|||||||
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;});
|
|
||||||
@@ -1,58 +0,0 @@
|
|||||||
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);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
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();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
// 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');
|
|
||||||
}
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
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');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -40,7 +40,7 @@ describe("BlogsService", () => {
|
|||||||
describe("findAll", () => {
|
describe("findAll", () => {
|
||||||
it("should query published blogs with pagination", async () => {
|
it("should query published blogs with pagination", async () => {
|
||||||
const blogs = [
|
const blogs = [
|
||||||
{ id: "1", title: "Blog 1", isPublished: true, status: "PUBLISHED", author: null },
|
{ id: "1", title: "Blog 1", isPublished: true, status: "PUBLISHED" },
|
||||||
];
|
];
|
||||||
mockPrisma.blog.findMany.mockResolvedValue(blogs);
|
mockPrisma.blog.findMany.mockResolvedValue(blogs);
|
||||||
mockPrisma.blog.count.mockResolvedValue(1);
|
mockPrisma.blog.count.mockResolvedValue(1);
|
||||||
@@ -49,9 +49,6 @@ describe("BlogsService", () => {
|
|||||||
expect(mockPrisma.blog.findMany).toHaveBeenCalled();
|
expect(mockPrisma.blog.findMany).toHaveBeenCalled();
|
||||||
expect(result.data).toEqual(blogs);
|
expect(result.data).toEqual(blogs);
|
||||||
expect(result.meta.total).toBe(1);
|
expect(result.meta.total).toBe(1);
|
||||||
const query = mockPrisma.blog.findMany.mock.calls[0][0];
|
|
||||||
expect(query.include.author).toEqual({ select: { id: true, firstName: true, lastName: true } });
|
|
||||||
expect(query.orderBy).toEqual([{ publishedAt: "desc" }, { id: "asc" }]);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should filter by categorySlug and search term", async () => {
|
it("should filter by categorySlug and search term", async () => {
|
||||||
@@ -70,19 +67,7 @@ describe("BlogsService", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it("selects the minimal public author identity for list results", async () => {
|
|
||||||
mockPrisma.blog.findMany.mockResolvedValue([]); mockPrisma.blog.count.mockResolvedValue(0);
|
|
||||||
await service.findAll({});
|
|
||||||
expect(mockPrisma.blog.findMany.mock.calls[0][0].include.author).toEqual({ select: { id: true, firstName: true, lastName: true } });
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("findHomepage", () => {
|
describe("findHomepage", () => {
|
||||||
it("selects the minimal public author identity for homepage results", async () => {
|
|
||||||
mockPrisma.blog.findMany.mockResolvedValueOnce([]).mockResolvedValueOnce([]);
|
|
||||||
await service.findHomepage();
|
|
||||||
for (const call of mockPrisma.blog.findMany.mock.calls.slice(0, 2)) expect(call[0].include.author).toEqual({ select: { id: true, firstName: true, lastName: true } });
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should return selected blogs if showOnHome posts exist", async () => {
|
it("should return selected blogs if showOnHome posts exist", async () => {
|
||||||
const selected = [{ id: "b1", title: "Hero Blog", showOnHome: true }];
|
const selected = [{ id: "b1", title: "Hero Blog", showOnHome: true }];
|
||||||
mockPrisma.blog.findMany.mockResolvedValueOnce(selected);
|
mockPrisma.blog.findMany.mockResolvedValueOnce(selected);
|
||||||
@@ -105,12 +90,6 @@ describe("BlogsService", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe("findOneBySlug", () => {
|
describe("findOneBySlug", () => {
|
||||||
it("selects the minimal public author identity for detail results", async () => {
|
|
||||||
mockPrisma.blog.findFirst.mockResolvedValue(null);
|
|
||||||
await expect(service.findOneBySlug("missing")).rejects.toThrow(NotFoundException);
|
|
||||||
expect(mockPrisma.blog.findFirst.mock.calls[0][0].include.author).toEqual({ select: { id: true, firstName: true, lastName: true } });
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should throw NotFoundException if slug is empty or blog not found", async () => {
|
it("should throw NotFoundException if slug is empty or blog not found", async () => {
|
||||||
mockPrisma.blog.findFirst.mockResolvedValue(null);
|
mockPrisma.blog.findFirst.mockResolvedValue(null);
|
||||||
await expect(service.findOneBySlug("unknown-slug")).rejects.toThrow(
|
await expect(service.findOneBySlug("unknown-slug")).rejects.toThrow(
|
||||||
|
|||||||
@@ -2,15 +2,8 @@ import { Injectable, NotFoundException } from "@nestjs/common";
|
|||||||
import { Prisma } from "@prisma/client";
|
import { Prisma } from "@prisma/client";
|
||||||
import { PrismaService } from "../prisma/prisma.service";
|
import { PrismaService } from "../prisma/prisma.service";
|
||||||
import { PaginationDto } from "../common/dto/pagination.dto";
|
import { PaginationDto } from "../common/dto/pagination.dto";
|
||||||
import {
|
|
||||||
createPaginationMeta,
|
|
||||||
extractSearchTokens,
|
|
||||||
normalizeSearchText,
|
|
||||||
calculateRelevanceScore,
|
|
||||||
} from "../common/utils/search.utils";
|
|
||||||
|
|
||||||
export interface BlogFilterDto extends PaginationDto {
|
export interface BlogFilterDto extends PaginationDto {
|
||||||
categoryId?: string;
|
|
||||||
categorySlug?: string;
|
categorySlug?: string;
|
||||||
tagSlug?: string;
|
tagSlug?: string;
|
||||||
featured?: boolean | string;
|
featured?: boolean | string;
|
||||||
@@ -27,7 +20,6 @@ export class BlogsService {
|
|||||||
limit = 10,
|
limit = 10,
|
||||||
sortBy = "publishedAt",
|
sortBy = "publishedAt",
|
||||||
sortOrder = "desc",
|
sortOrder = "desc",
|
||||||
categoryId,
|
|
||||||
categorySlug,
|
categorySlug,
|
||||||
tagSlug,
|
tagSlug,
|
||||||
featured,
|
featured,
|
||||||
@@ -40,23 +32,20 @@ export class BlogsService {
|
|||||||
OR: [{ publishedAt: null }, { publishedAt: { lte: now } }],
|
OR: [{ publishedAt: null }, { publishedAt: { lte: now } }],
|
||||||
};
|
};
|
||||||
|
|
||||||
const tokens = extractSearchTokens(search);
|
if (search) {
|
||||||
if (tokens.length > 0) {
|
|
||||||
whereClause.AND = [
|
whereClause.AND = [
|
||||||
{
|
{
|
||||||
OR: tokens.flatMap((token) => [
|
OR: [
|
||||||
{ title: { contains: token, mode: "insensitive" } },
|
{ title: { contains: search, mode: "insensitive" } },
|
||||||
{ excerpt: { contains: token, mode: "insensitive" } },
|
{ excerpt: { contains: search, mode: "insensitive" } },
|
||||||
{ keywords: { contains: token, mode: "insensitive" } },
|
{ content: { contains: search, mode: "insensitive" } },
|
||||||
{ tags: { some: { name: { contains: token, mode: "insensitive" } } } },
|
{ keywords: { contains: search, mode: "insensitive" } },
|
||||||
]),
|
],
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
if (categoryId && categoryId !== "ALL") {
|
if (categorySlug) {
|
||||||
whereClause.categoryId = categoryId;
|
|
||||||
} else if (categorySlug && categorySlug !== "all") {
|
|
||||||
whereClause.category = { slug: categorySlug };
|
whereClause.category = { slug: categorySlug };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -68,24 +57,19 @@ export class BlogsService {
|
|||||||
whereClause.featured = String(featured) === "true";
|
whereClause.featured = String(featured) === "true";
|
||||||
}
|
}
|
||||||
|
|
||||||
const safePage = Math.max(1, Number(page) || 1);
|
const skip = (Number(page) - 1) * Number(limit);
|
||||||
const safeLimit = Math.max(1, Number(limit) || 10);
|
|
||||||
const skip = (safePage - 1) * safeLimit;
|
|
||||||
|
|
||||||
const [rawBlogs, total] = await Promise.all([
|
const [data, total] = await Promise.all([
|
||||||
this.prisma.blog.findMany({
|
this.prisma.blog.findMany({
|
||||||
where: whereClause,
|
where: whereClause,
|
||||||
skip: tokens.length > 0 ? undefined : skip,
|
skip,
|
||||||
take: tokens.length > 0 ? 100 : safeLimit,
|
take: Number(limit),
|
||||||
orderBy: [
|
orderBy: {
|
||||||
{
|
[sortBy === "createdAt" ? "createdAt" : "publishedAt"]: sortOrder,
|
||||||
[sortBy === "createdAt" ? "createdAt" : "publishedAt"]: sortOrder,
|
},
|
||||||
},
|
|
||||||
{ id: "asc" },
|
|
||||||
],
|
|
||||||
include: {
|
include: {
|
||||||
author: {
|
author: {
|
||||||
select: { id: true, firstName: true, lastName: true },
|
select: { firstName: true, lastName: true },
|
||||||
},
|
},
|
||||||
category: {
|
category: {
|
||||||
select: { id: true, name: true, slug: true },
|
select: { id: true, name: true, slug: true },
|
||||||
@@ -101,30 +85,14 @@ export class BlogsService {
|
|||||||
this.prisma.blog.count({ where: whereClause }),
|
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 {
|
return {
|
||||||
data,
|
data,
|
||||||
meta: createPaginationMeta(total, safePage, safeLimit),
|
meta: {
|
||||||
|
total,
|
||||||
|
page: Number(page),
|
||||||
|
lastPage: Math.ceil(total / Number(limit)) || 1,
|
||||||
|
limit: Number(limit),
|
||||||
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -140,11 +108,9 @@ export class BlogsService {
|
|||||||
const selectedBlogs = await this.prisma.blog.findMany({
|
const selectedBlogs = await this.prisma.blog.findMany({
|
||||||
where: { ...baseWhere, showOnHome: true },
|
where: { ...baseWhere, showOnHome: true },
|
||||||
take: 4,
|
take: 4,
|
||||||
orderBy: [{ publishedAt: "desc" }, { id: "asc" }],
|
orderBy: { publishedAt: "desc" },
|
||||||
include: {
|
include: {
|
||||||
author: {
|
author: { select: { firstName: true, lastName: true } },
|
||||||
select: { id: true, firstName: true, lastName: true },
|
|
||||||
},
|
|
||||||
category: { select: { id: true, name: true, slug: true } },
|
category: { select: { id: true, name: true, slug: true } },
|
||||||
tags: { select: { id: true, name: true, slug: true } },
|
tags: { select: { id: true, name: true, slug: true } },
|
||||||
_count: { select: { comments: { where: { status: "APPROVED" } } } },
|
_count: { select: { comments: { where: { status: "APPROVED" } } } },
|
||||||
@@ -159,11 +125,9 @@ export class BlogsService {
|
|||||||
const newestBlogs = await this.prisma.blog.findMany({
|
const newestBlogs = await this.prisma.blog.findMany({
|
||||||
where: baseWhere,
|
where: baseWhere,
|
||||||
take: 4,
|
take: 4,
|
||||||
orderBy: [{ publishedAt: "desc" }, { id: "asc" }],
|
orderBy: { publishedAt: "desc" },
|
||||||
include: {
|
include: {
|
||||||
author: {
|
author: { select: { firstName: true, lastName: true } },
|
||||||
select: { id: true, firstName: true, lastName: true },
|
|
||||||
},
|
|
||||||
category: { select: { id: true, name: true, slug: true } },
|
category: { select: { id: true, name: true, slug: true } },
|
||||||
tags: { select: { id: true, name: true, slug: true } },
|
tags: { select: { id: true, name: true, slug: true } },
|
||||||
_count: { select: { comments: { where: { status: "APPROVED" } } } },
|
_count: { select: { comments: { where: { status: "APPROVED" } } } },
|
||||||
@@ -199,7 +163,9 @@ export class BlogsService {
|
|||||||
],
|
],
|
||||||
},
|
},
|
||||||
include: {
|
include: {
|
||||||
author: { select: { id: true, firstName: true, lastName: true } },
|
author: {
|
||||||
|
select: { firstName: true, lastName: true },
|
||||||
|
},
|
||||||
category: {
|
category: {
|
||||||
select: { id: true, name: true, slug: true },
|
select: { id: true, name: true, slug: true },
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,61 +0,0 @@
|
|||||||
import { CallHandler, ExecutionContext } from "@nestjs/common";
|
|
||||||
import { of, lastValueFrom } from "rxjs";
|
|
||||||
import { AdminRevalidationInterceptor } from "./admin-revalidation.interceptor";
|
|
||||||
import { RevalidationService } from "./revalidation.service";
|
|
||||||
|
|
||||||
describe("AdminRevalidationInterceptor", () => {
|
|
||||||
const revalidation = { revalidate: jest.fn().mockResolvedValue(true) } as unknown as RevalidationService;
|
|
||||||
const interceptor = new AdminRevalidationInterceptor(revalidation);
|
|
||||||
const next = { handle: () => of({ ok: true }) } as CallHandler;
|
|
||||||
|
|
||||||
beforeEach(() => jest.clearAllMocks());
|
|
||||||
|
|
||||||
function context(method: string, url: string): ExecutionContext {
|
|
||||||
return { switchToHttp: () => ({ getRequest: () => ({ method, originalUrl: url }) }) } as unknown as ExecutionContext;
|
|
||||||
}
|
|
||||||
|
|
||||||
it("invalidates blog list and detail after an admin blog mutation", async () => {
|
|
||||||
await lastValueFrom(interceptor.intercept(context("PUT", "/api/admin/blogs/blog-1"), next));
|
|
||||||
expect(revalidation.revalidate).toHaveBeenCalledWith(
|
|
||||||
expect.arrayContaining(["blogs", "blog-categories", "blog-tags", "home-data"]),
|
|
||||||
expect.arrayContaining(["/", "/blog"]),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it.each([
|
|
||||||
["/api/admin/products/p1", "products"],
|
|
||||||
["/api/admin/categories/c1", "categories"],
|
|
||||||
["/api/admin/wiki/glucosamine", "wiki"],
|
|
||||||
["/api/admin/settings", "settings"],
|
|
||||||
["/api/admin/cms/hero-banners/b1", "banners"],
|
|
||||||
["/api/admin/cms/vet-testimonials/t1", "testimonials"],
|
|
||||||
["/api/admin/reviews/r1", "products"],
|
|
||||||
["/api/admin/media/m1", "products"],
|
|
||||||
])("maps %s mutations to %s cache invalidation", async (url, expectedTag) => {
|
|
||||||
await lastValueFrom(interceptor.intercept(context("DELETE", url), next));
|
|
||||||
expect(revalidation.revalidate).toHaveBeenCalledWith(expect.arrayContaining([expectedTag]), expect.any(Array));
|
|
||||||
});
|
|
||||||
|
|
||||||
it("does not invalidate cache for reads or internal-only admin CRUD", async () => {
|
|
||||||
await lastValueFrom(interceptor.intercept(context("GET", "/api/admin/blogs"), next));
|
|
||||||
await lastValueFrom(interceptor.intercept(context("PUT", "/api/admin/users/u1"), next));
|
|
||||||
expect(revalidation.revalidate).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it.each([
|
|
||||||
["/api/banners/banner-1", "banners"],
|
|
||||||
["/api/menu/menu-1", "menu"],
|
|
||||||
["/api/videos/video-1", "videos"],
|
|
||||||
["/api/testimonials/testimonial-1", "testimonials"],
|
|
||||||
["/api/faq/faq-1", "faq"],
|
|
||||||
["/api/ingredients/ingredient-1", "ingredients"],
|
|
||||||
["/api/doctors/doctor-1", "doctors"],
|
|
||||||
["/api/settings/seo", "seo-config"],
|
|
||||||
["/api/settings/ui-texts/HERO_TITLE", "ui-texts"],
|
|
||||||
["/api/contact/info", "settings"],
|
|
||||||
["/api/smart-advisor/rules/rule-1", "smart-advisor"],
|
|
||||||
])("maps storefront mutation %s to %s cache invalidation", async (url, expectedTag) => {
|
|
||||||
await lastValueFrom(interceptor.intercept(context("PATCH", url), next));
|
|
||||||
expect(revalidation.revalidate).toHaveBeenCalledWith(expect.arrayContaining([expectedTag]), expect.any(Array));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from "@nestjs/common";
|
|
||||||
import { Observable, tap } from "rxjs";
|
|
||||||
import { RevalidationService } from "./revalidation.service";
|
|
||||||
|
|
||||||
type Target = { tags: string[]; paths: string[] };
|
|
||||||
|
|
||||||
const TARGETS: Array<{ pattern: RegExp; target: Target }> = [
|
|
||||||
{ pattern: /^\/api\/banners(?:\/|$)/, target: { tags: ["banners", "home-data"], paths: ["/"] } },
|
|
||||||
{ pattern: /^\/api\/menu(?:\/|$)/, target: { tags: ["menu", "settings"], paths: ["/"] } },
|
|
||||||
{ pattern: /^\/api\/videos(?:\/|$)/, target: { tags: ["videos", "home-data"], paths: ["/", "/videos"] } },
|
|
||||||
{ pattern: /^\/api\/testimonials(?:\/|$)/, target: { tags: ["testimonials", "home-data"], paths: ["/"] } },
|
|
||||||
{ pattern: /^\/api\/faq(?:\/|$)/, target: { tags: ["faq"], paths: ["/faq"] } },
|
|
||||||
{ pattern: /^\/api\/ingredients(?:\/|$)/, target: { tags: ["ingredients", "products", "wiki"], paths: ["/shop", "/wiki"] } },
|
|
||||||
{ pattern: /^\/api\/doctors(?:\/|$)/, target: { tags: ["doctors", "settings"], paths: ["/contact"] } },
|
|
||||||
{ pattern: /^\/api\/settings\/seo(?:\/|$)/, target: { tags: ["seo-config", "settings"], paths: ["/", "/sitemap.xml"] } },
|
|
||||||
{ pattern: /^\/api\/settings\/(?:ui-texts|system|financial)(?:\/|$)/, target: { tags: ["ui-texts", "settings", "home-data"], paths: ["/"] } },
|
|
||||||
{ pattern: /^\/api\/contact\/info(?:\/|$)/, target: { tags: ["settings"], paths: ["/contact", "/"] } },
|
|
||||||
{ pattern: /^\/api\/smart-advisor\/rules(?:\/|$)/, target: { tags: ["smart-advisor", "products"], paths: ["/smart-advisor"] } },
|
|
||||||
{ pattern: /^\/api\/admin\/blogs(?:\/|$)/, target: { tags: ["blogs", "blog-categories", "blog-tags", "home-data"], paths: ["/", "/blog", "/sitemap.xml"] } },
|
|
||||||
{ pattern: /^\/api\/admin\/categories(?:\/|$)/, target: { tags: ["products", "categories", "home-data"], paths: ["/", "/shop", "/sitemap.xml"] } },
|
|
||||||
{ pattern: /^\/api\/admin\/wiki(?:\/|$)/, target: { tags: ["wiki", "scientific-terms"], paths: ["/wiki", "/sitemap.xml"] } },
|
|
||||||
{ pattern: /^\/api\/admin\/(?:settings|pricing)(?:\/|$)/, target: { tags: ["settings", "ui-texts", "seo-config", "products", "home-data"], paths: ["/", "/shop"] } },
|
|
||||||
{ pattern: /^\/api\/admin\/cms\/hero-banners(?:\/|$)/, target: { tags: ["banners", "home-data"], paths: ["/"] } },
|
|
||||||
{ pattern: /^\/api\/admin\/cms\/vet-testimonials(?:\/|$)/, target: { tags: ["testimonials", "home-data"], paths: ["/"] } },
|
|
||||||
{ pattern: /^\/api\/admin\/reviews(?:\/|$)/, target: { tags: ["products", "home-data"], paths: ["/", "/shop"] } },
|
|
||||||
{ pattern: /^\/api\/admin\/media(?:\/|$)/, target: { tags: ["products", "blogs", "wiki", "home-data"], paths: ["/", "/shop", "/blog", "/wiki"] } },
|
|
||||||
{ pattern: /^\/api\/admin\/products(?:\/|$)/, target: { tags: ["products", "home-data"], paths: ["/", "/shop", "/sitemap.xml"] } },
|
|
||||||
];
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class AdminRevalidationInterceptor implements NestInterceptor {
|
|
||||||
constructor(private readonly revalidation: RevalidationService) {}
|
|
||||||
|
|
||||||
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
|
|
||||||
const request = context.switchToHttp().getRequest<{ method?: string; originalUrl?: string; url?: string }>();
|
|
||||||
const method = (request.method || "GET").toUpperCase();
|
|
||||||
const url = (request.originalUrl || request.url || "").split("?")[0];
|
|
||||||
const target = method === "GET" || method === "HEAD" || method === "OPTIONS"
|
|
||||||
? undefined
|
|
||||||
: TARGETS.find((entry) => entry.pattern.test(url))?.target;
|
|
||||||
|
|
||||||
return next.handle().pipe(
|
|
||||||
tap(() => {
|
|
||||||
if (target) void this.revalidation.revalidate(target.tags, target.paths);
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,11 +1,9 @@
|
|||||||
import { Global, Module } from "@nestjs/common";
|
import { Global, Module } from "@nestjs/common";
|
||||||
import { APP_INTERCEPTOR } from "@nestjs/core";
|
|
||||||
import { AdminRevalidationInterceptor } from "./admin-revalidation.interceptor";
|
|
||||||
import { RevalidationService } from "./revalidation.service";
|
import { RevalidationService } from "./revalidation.service";
|
||||||
|
|
||||||
@Global()
|
@Global()
|
||||||
@Module({
|
@Module({
|
||||||
providers: [RevalidationService, { provide: APP_INTERCEPTOR, useClass: AdminRevalidationInterceptor }],
|
providers: [RevalidationService],
|
||||||
exports: [RevalidationService],
|
exports: [RevalidationService],
|
||||||
})
|
})
|
||||||
export class RevalidationModule {}
|
export class RevalidationModule {}
|
||||||
@@ -26,16 +26,6 @@ describe("RevalidationService", () => {
|
|||||||
expect(service).toBeDefined();
|
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", () => {
|
describe("revalidateTag", () => {
|
||||||
it("should send POST request with tag and secret header and return true on 200", async () => {
|
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({
|
const mockFetch = jest.spyOn(global, "fetch" as any).mockResolvedValue({
|
||||||
@@ -120,64 +110,4 @@ describe("RevalidationService", () => {
|
|||||||
expect(pathSpy).toHaveBeenCalledWith("/shop/ART-100");
|
expect(pathSpy).toHaveBeenCalledWith("/shop/ART-100");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
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);
|
|
||||||
|
|
||||||
const result = await service.revalidate(["blogs", "blogs"], ["/blog", "/blog"]);
|
|
||||||
|
|
||||||
expect(result).toBe(true);
|
|
||||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
|
||||||
expect(mockFetch).toHaveBeenCalledWith(
|
|
||||||
"http://frontend_mock:8080/api/revalidate",
|
|
||||||
expect.objectContaining({
|
|
||||||
method: "POST",
|
|
||||||
body: JSON.stringify({ tags: ["blogs"], paths: ["/blog"] }),
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
@@ -10,7 +10,7 @@ export class RevalidationService {
|
|||||||
process.env.FRONTEND_URL ||
|
process.env.FRONTEND_URL ||
|
||||||
process.env.NEXT_PUBLIC_SITE_URL ||
|
process.env.NEXT_PUBLIC_SITE_URL ||
|
||||||
(process.env.NODE_ENV === "production"
|
(process.env.NODE_ENV === "production"
|
||||||
? "http://frontend_prod:3000"
|
? "http://frontend_prod:8080"
|
||||||
: "http://localhost:3000");
|
: "http://localhost:3000");
|
||||||
return raw.replace(/\/+$/, "");
|
return raw.replace(/\/+$/, "");
|
||||||
}
|
}
|
||||||
@@ -31,32 +31,6 @@ export class RevalidationService {
|
|||||||
return secret;
|
return secret;
|
||||||
}
|
}
|
||||||
|
|
||||||
async revalidate(tags: string[] = [], paths: string[] = []): Promise<boolean> {
|
|
||||||
const cleanTags = [...new Set(tags.filter(Boolean))];
|
|
||||||
const cleanPaths = [...new Set(paths.filter((path) => path.startsWith("/")))];
|
|
||||||
if (!cleanTags.length && !cleanPaths.length) return true;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const url = `${this.frontendUrl}/api/revalidate`;
|
|
||||||
const res = await fetch(url, {
|
|
||||||
method: "POST",
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
"x-revalidate-secret": this.secret,
|
|
||||||
},
|
|
||||||
body: JSON.stringify({ tags: cleanTags, paths: cleanPaths }),
|
|
||||||
});
|
|
||||||
if (!res.ok) {
|
|
||||||
this.logger.warn(`Failed to revalidate cache batch: ${res.status} ${res.statusText}`);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
} catch (err: any) {
|
|
||||||
this.logger.debug(`Batch revalidation skipped or frontend offline: ${err?.message}`);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async revalidateTag(tag: string): Promise<boolean> {
|
async revalidateTag(tag: string): Promise<boolean> {
|
||||||
try {
|
try {
|
||||||
const url = `${this.frontendUrl}/api/revalidate`;
|
const url = `${this.frontendUrl}/api/revalidate`;
|
||||||
@@ -135,7 +109,7 @@ export class RevalidationService {
|
|||||||
await Promise.allSettled(tasks);
|
await Promise.allSettled(tasks);
|
||||||
}
|
}
|
||||||
|
|
||||||
async revalidateBlog(slug?: string): Promise<boolean> {
|
async revalidateBlog(slug?: string): Promise<void> {
|
||||||
const tasks: Promise<boolean>[] = [
|
const tasks: Promise<boolean>[] = [
|
||||||
this.revalidateTag("blogs"),
|
this.revalidateTag("blogs"),
|
||||||
this.revalidateTag("home-data"),
|
this.revalidateTag("home-data"),
|
||||||
@@ -149,18 +123,7 @@ export class RevalidationService {
|
|||||||
tasks.push(this.revalidatePath(`/blog/${slug}`));
|
tasks.push(this.revalidatePath(`/blog/${slug}`));
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
await Promise.allSettled(tasks);
|
||||||
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> {
|
async revalidateSettings(): Promise<void> {
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
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 };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -38,6 +38,8 @@ export interface SmsConfig {
|
|||||||
shippingBodyId: number;
|
shippingBodyId: number;
|
||||||
b2bBodyId: number;
|
b2bBodyId: number;
|
||||||
petCareBodyId: number;
|
petCareBodyId: number;
|
||||||
|
leadAdvisorBodyId?: number;
|
||||||
|
leadConfirmationBodyId?: number;
|
||||||
rules?: SmsRule[];
|
rules?: SmsRule[];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -122,6 +124,16 @@ export class SmsService {
|
|||||||
process.env.MELIPAYAMAK_PET_CARE_BODY_ID ||
|
process.env.MELIPAYAMAK_PET_CARE_BODY_ID ||
|
||||||
"0",
|
"0",
|
||||||
),
|
),
|
||||||
|
leadAdvisorBodyId: Number(
|
||||||
|
dbConfig.leadAdvisorBodyId ||
|
||||||
|
process.env.MELIPAYAMAK_LEAD_ADVISOR_BODY_ID ||
|
||||||
|
"580260",
|
||||||
|
),
|
||||||
|
leadConfirmationBodyId: Number(
|
||||||
|
dbConfig.leadConfirmationBodyId ||
|
||||||
|
process.env.MELIPAYAMAK_LEAD_CONFIRMATION_BODY_ID ||
|
||||||
|
"580259",
|
||||||
|
),
|
||||||
rules: Array.isArray(dbConfig.rules)
|
rules: Array.isArray(dbConfig.rules)
|
||||||
? (dbConfig.rules as SmsRule[])
|
? (dbConfig.rules as SmsRule[])
|
||||||
: DEFAULT_SMS_RULES,
|
: DEFAULT_SMS_RULES,
|
||||||
@@ -140,6 +152,8 @@ export class SmsService {
|
|||||||
),
|
),
|
||||||
b2bBodyId: Number(process.env.MELIPAYAMAK_B2B_BODY_ID || "508083"),
|
b2bBodyId: Number(process.env.MELIPAYAMAK_B2B_BODY_ID || "508083"),
|
||||||
petCareBodyId: Number(process.env.MELIPAYAMAK_PET_CARE_BODY_ID || "0"),
|
petCareBodyId: Number(process.env.MELIPAYAMAK_PET_CARE_BODY_ID || "0"),
|
||||||
|
leadAdvisorBodyId: Number(process.env.MELIPAYAMAK_LEAD_ADVISOR_BODY_ID || "580260"),
|
||||||
|
leadConfirmationBodyId: Number(process.env.MELIPAYAMAK_LEAD_CONFIRMATION_BODY_ID || "580259"),
|
||||||
rules: DEFAULT_SMS_RULES,
|
rules: DEFAULT_SMS_RULES,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -1377,13 +1391,88 @@ export class SmsService {
|
|||||||
});
|
});
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
this.logger.log(`[SMS Text Sent] To: ${phone}, Content: ${message}`);
|
// 2. Dispatch generic direct SMS via MeliPayamak SendSMS endpoint if fromNumber configured, else fall back to local log
|
||||||
await this.recordLog({
|
return new Promise((resolve) => {
|
||||||
receptor: phone,
|
const payload = JSON.stringify({
|
||||||
type: "GENERIC_TEXT",
|
username: config.username,
|
||||||
messageText: message,
|
password: config.password,
|
||||||
status: "SUCCESS",
|
to: phone,
|
||||||
|
from: config.fromNumber || "50004001100228",
|
||||||
|
text: message,
|
||||||
|
isFlash: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
const req = https.request(
|
||||||
|
"https://rest.payamak-panel.com/api/SendSMS/SendSMS",
|
||||||
|
{
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"Content-Length": Buffer.byteLength(payload),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
(res) => {
|
||||||
|
let data = "";
|
||||||
|
res.on("data", (chunk: Buffer | string) => (data += String(chunk)));
|
||||||
|
res.on("end", () => {
|
||||||
|
void (async () => {
|
||||||
|
try {
|
||||||
|
const json = JSON.parse(data) as { Value?: number | string; RetStatus?: number; StrRetStatus?: string };
|
||||||
|
const val = Number(json.Value ?? 0);
|
||||||
|
if (val > 15 || json.RetStatus === 1) {
|
||||||
|
this.logger.log(`[SMS Text Sent] To: ${phone}, RecId: ${val}`);
|
||||||
|
await this.recordLog({
|
||||||
|
receptor: phone,
|
||||||
|
type: "GENERIC_TEXT",
|
||||||
|
messageText: message,
|
||||||
|
status: "SUCCESS",
|
||||||
|
recId: String(val),
|
||||||
|
});
|
||||||
|
resolve(true);
|
||||||
|
} else {
|
||||||
|
const errMsg = `خطای ارسال پیامک متنی با کد: ${val} (${json.StrRetStatus || ''})`;
|
||||||
|
this.logger.error(`[SMS Text Error] To: ${phone}, Code: ${val}`);
|
||||||
|
await this.recordLog({
|
||||||
|
receptor: phone,
|
||||||
|
type: "GENERIC_TEXT",
|
||||||
|
messageText: message,
|
||||||
|
status: "FAILED",
|
||||||
|
errorMessage: errMsg,
|
||||||
|
});
|
||||||
|
resolve(false);
|
||||||
|
}
|
||||||
|
} catch (err: unknown) {
|
||||||
|
const msg = err instanceof Error ? err.message : String(err);
|
||||||
|
await this.recordLog({
|
||||||
|
receptor: phone,
|
||||||
|
type: "GENERIC_TEXT",
|
||||||
|
messageText: message,
|
||||||
|
status: "FAILED",
|
||||||
|
errorMessage: `خطای پارس پاسخ ملی پیامک: ${data || msg}`,
|
||||||
|
});
|
||||||
|
resolve(false);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
});
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
req.on("error", (err: Error) => {
|
||||||
|
void (async () => {
|
||||||
|
this.logger.error(`[SMS Text Network Error] To: ${phone}: ${err.message}`);
|
||||||
|
await this.recordLog({
|
||||||
|
receptor: phone,
|
||||||
|
type: "GENERIC_TEXT",
|
||||||
|
messageText: message,
|
||||||
|
status: "FAILED",
|
||||||
|
errorMessage: err.message,
|
||||||
|
});
|
||||||
|
resolve(false);
|
||||||
|
})();
|
||||||
|
});
|
||||||
|
|
||||||
|
req.write(payload);
|
||||||
|
req.end();
|
||||||
});
|
});
|
||||||
return Promise.resolve(true);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
import { Module } from '@nestjs/common';
|
|
||||||
import { TasksService } from './tasks.service';
|
|
||||||
import { OrdersModule } from '../../orders/orders.module';
|
|
||||||
import { PaymentModule } from '../../payment/payment.module';
|
|
||||||
import { RedisModule } from '../../redis/redis.module';
|
|
||||||
|
|
||||||
@Module({
|
|
||||||
imports: [OrdersModule, PaymentModule, RedisModule],
|
|
||||||
providers: [TasksService],
|
|
||||||
exports: [TasksService],
|
|
||||||
})
|
|
||||||
export class TasksModule {}
|
|
||||||
@@ -1,80 +0,0 @@
|
|||||||
import { Injectable, Logger, OnApplicationBootstrap, OnApplicationShutdown } from '@nestjs/common';
|
|
||||||
import { OrdersService } from '../../orders/orders.service';
|
|
||||||
import { RedisService } from '../../redis/redis.service';
|
|
||||||
import { PaymentService } from '../../payment/payment.service';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class TasksService implements OnApplicationBootstrap, OnApplicationShutdown {
|
|
||||||
private readonly logger = new Logger(TasksService.name);
|
|
||||||
private reservationTimer: NodeJS.Timeout | null = null;
|
|
||||||
private reconciliationTimer: NodeJS.Timeout | null = null;
|
|
||||||
|
|
||||||
constructor(
|
|
||||||
private readonly ordersService: OrdersService,
|
|
||||||
private readonly paymentService: PaymentService,
|
|
||||||
private readonly redisService: RedisService,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
onApplicationBootstrap() {
|
|
||||||
this.logger.log('Starting background maintenance tasks...');
|
|
||||||
|
|
||||||
// 1. Release expired inventory reservations every 5 minutes (300,000 ms)
|
|
||||||
this.reservationTimer = setInterval(async () => {
|
|
||||||
const lockAcquired = await this.redisService.acquireLock('task:inventory_release', 240);
|
|
||||||
if (!lockAcquired) {
|
|
||||||
this.logger.debug('[Task:Inventory] Another instance holds the lock, skipping execution.');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
const result = await this.ordersService.releaseExpiredInventoryReservations();
|
|
||||||
if (result.releasedCount > 0) {
|
|
||||||
this.logger.log(`[Task:Inventory] Automatically released ${result.releasedCount} expired inventory reservations.`);
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
this.logger.error('[Task:Inventory] Failed to release expired inventory reservations:', err);
|
|
||||||
} finally {
|
|
||||||
await this.redisService.releaseLock('task:inventory_release');
|
|
||||||
}
|
|
||||||
}, 5 * 60 * 1000);
|
|
||||||
|
|
||||||
// 2. Reconcile pending online payment transactions every 10 minutes (600,000 ms)
|
|
||||||
this.reconciliationTimer = setInterval(async () => {
|
|
||||||
const lockAcquired = await this.redisService.acquireLock('task:payment_reconciliation', 540);
|
|
||||||
if (!lockAcquired) {
|
|
||||||
this.logger.debug('[Task:PaymentReconciliation] Another instance holds the lock, skipping execution.');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
const result = await this.paymentService.reconcilePendingTransactions();
|
|
||||||
if (result.total > 0) {
|
|
||||||
this.logger.log(`[Task:PaymentReconciliation] Checked ${result.total} transactions: ${result.verified} verified, ${result.failed} failed.`);
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
this.logger.error('[Task:PaymentReconciliation] Failed to reconcile pending payments:', err);
|
|
||||||
} finally {
|
|
||||||
await this.redisService.releaseLock('task:payment_reconciliation');
|
|
||||||
}
|
|
||||||
}, 10 * 60 * 1000);
|
|
||||||
|
|
||||||
// Initial check on startup after 30 seconds
|
|
||||||
setTimeout(async () => {
|
|
||||||
try {
|
|
||||||
await this.ordersService.releaseExpiredInventoryReservations();
|
|
||||||
} catch (err) {
|
|
||||||
this.logger.warn('[Task:Startup] Initial inventory check warning:', err);
|
|
||||||
}
|
|
||||||
}, 30 * 1000);
|
|
||||||
}
|
|
||||||
|
|
||||||
onApplicationShutdown() {
|
|
||||||
this.logger.log('Stopping background maintenance tasks...');
|
|
||||||
if (this.reservationTimer) {
|
|
||||||
clearInterval(this.reservationTimer);
|
|
||||||
this.reservationTimer = null;
|
|
||||||
}
|
|
||||||
if (this.reconciliationTimer) {
|
|
||||||
clearInterval(this.reconciliationTimer);
|
|
||||||
this.reconciliationTimer = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,91 +0,0 @@
|
|||||||
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);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,251 +0,0 @@
|
|||||||
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;
|
|
||||||
}
|
|
||||||
@@ -2,9 +2,10 @@ import { Module } from "@nestjs/common";
|
|||||||
import { ContactController } from "./contact.controller";
|
import { ContactController } from "./contact.controller";
|
||||||
import { ContactService } from "./contact.service";
|
import { ContactService } from "./contact.service";
|
||||||
import { SmsModule } from "../common/sms.module";
|
import { SmsModule } from "../common/sms.module";
|
||||||
|
import { NotificationsModule } from "../notifications/notifications.module";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [SmsModule],
|
imports: [SmsModule, NotificationsModule],
|
||||||
controllers: [ContactController],
|
controllers: [ContactController],
|
||||||
providers: [ContactService],
|
providers: [ContactService],
|
||||||
exports: [ContactService],
|
exports: [ContactService],
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { Test, TestingModule } from "@nestjs/testing";
|
|||||||
import { ContactService, CreateContactSubmissionDto } from "./contact.service";
|
import { ContactService, CreateContactSubmissionDto } from "./contact.service";
|
||||||
import { PrismaService } from "../prisma/prisma.service";
|
import { PrismaService } from "../prisma/prisma.service";
|
||||||
import { SmsService } from "../common/services/sms.service";
|
import { SmsService } from "../common/services/sms.service";
|
||||||
|
import { TransactionalEmailsService } from "../notifications/transactional-emails.service";
|
||||||
|
|
||||||
describe("ContactService", () => {
|
describe("ContactService", () => {
|
||||||
let service: ContactService;
|
let service: ContactService;
|
||||||
@@ -34,6 +35,17 @@ describe("ContactService", () => {
|
|||||||
provide: SmsService,
|
provide: SmsService,
|
||||||
useValue: mockSmsService,
|
useValue: mockSmsService,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
provide: TransactionalEmailsService,
|
||||||
|
useValue: {
|
||||||
|
sendWelcome: jest.fn().mockResolvedValue(undefined),
|
||||||
|
sendOrderCreated: jest.fn().mockResolvedValue(undefined),
|
||||||
|
sendOrderPaid: jest.fn().mockResolvedValue(undefined),
|
||||||
|
sendOrderShipped: jest.fn().mockResolvedValue(undefined),
|
||||||
|
sendContactConfirmation: jest.fn().mockResolvedValue(undefined),
|
||||||
|
notifyAdminsAboutContact: jest.fn().mockResolvedValue(undefined),
|
||||||
|
},
|
||||||
|
},
|
||||||
],
|
],
|
||||||
}).compile();
|
}).compile();
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { Injectable, Logger } from "@nestjs/common";
|
import { Injectable, Logger } from "@nestjs/common";
|
||||||
import { PrismaService } from "../prisma/prisma.service";
|
import { PrismaService } from "../prisma/prisma.service";
|
||||||
import { SmsService } from "../common/services/sms.service";
|
import { SmsService } from "../common/services/sms.service";
|
||||||
|
import { TransactionalEmailsService } from "../notifications/transactional-emails.service";
|
||||||
|
|
||||||
export interface CreateContactSubmissionDto {
|
export interface CreateContactSubmissionDto {
|
||||||
name: string;
|
name: string;
|
||||||
@@ -25,6 +26,7 @@ export class ContactService {
|
|||||||
constructor(
|
constructor(
|
||||||
private readonly prisma: PrismaService,
|
private readonly prisma: PrismaService,
|
||||||
private readonly smsService: SmsService,
|
private readonly smsService: SmsService,
|
||||||
|
private readonly transactionalEmails: TransactionalEmailsService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async submitContactForm(dto: CreateContactSubmissionDto) {
|
async submitContactForm(dto: CreateContactSubmissionDto) {
|
||||||
@@ -56,6 +58,28 @@ export class ContactService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Email confirmation to submitter + admin notify (non-blocking)
|
||||||
|
void Promise.resolve(
|
||||||
|
this.transactionalEmails.notifyAdminsAboutContact({
|
||||||
|
name: dto.name,
|
||||||
|
phone: dto.phone,
|
||||||
|
email: dto.email,
|
||||||
|
subject: dto.subject,
|
||||||
|
message: dto.message,
|
||||||
|
submissionId: submission.id,
|
||||||
|
}),
|
||||||
|
).catch(() => {});
|
||||||
|
if (dto.email) {
|
||||||
|
void Promise.resolve(
|
||||||
|
this.transactionalEmails.sendContactConfirmation(
|
||||||
|
dto.email,
|
||||||
|
dto.name,
|
||||||
|
dto.message,
|
||||||
|
submission.id,
|
||||||
|
),
|
||||||
|
).catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
message:
|
message:
|
||||||
|
|||||||
@@ -0,0 +1,98 @@
|
|||||||
|
/**
|
||||||
|
* Branded HTML wrappers for Canina transactional emails.
|
||||||
|
* Colors match the storefront tokens in frontend/application/app/globals.css.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const BRAND = {
|
||||||
|
blue: '#1E4053',
|
||||||
|
gold: '#F1B646',
|
||||||
|
teal: '#9BC8CC',
|
||||||
|
dark: '#060709',
|
||||||
|
soft: '#F4F7F6',
|
||||||
|
border: '#E5ECE9',
|
||||||
|
muted: '#445D60',
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export function escapeHtml(value: string): string {
|
||||||
|
return String(value)
|
||||||
|
.replace(/&/g, '&')
|
||||||
|
.replace(/</g, '<')
|
||||||
|
.replace(/>/g, '>')
|
||||||
|
.replace(/"/g, '"')
|
||||||
|
.replace(/'/g, ''');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function textToHtmlParagraphs(text: string): string {
|
||||||
|
return escapeHtml(text)
|
||||||
|
.split(/\r?\n/)
|
||||||
|
.map((line) => (line.trim().length === 0 ? ' ' : line))
|
||||||
|
.join('<br/>');
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CaninaEmailLayoutOptions {
|
||||||
|
title: string;
|
||||||
|
bodyHtml: string;
|
||||||
|
eyebrow?: string;
|
||||||
|
footerNote?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function renderCaninaEmailLayout(options: CaninaEmailLayoutOptions): string {
|
||||||
|
const title = escapeHtml(options.title);
|
||||||
|
const eyebrow = escapeHtml(options.eyebrow || 'CANINA');
|
||||||
|
const footerNote = escapeHtml(
|
||||||
|
options.footerNote || 'این پیام از طرف فروشگاه کنینا ارسال شده است.',
|
||||||
|
);
|
||||||
|
|
||||||
|
return `<!DOCTYPE html>
|
||||||
|
<html lang="fa" dir="rtl">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>${title}</title>
|
||||||
|
</head>
|
||||||
|
<body style="margin:0;padding:0;background:${BRAND.soft};color:${BRAND.dark};font-family:Tahoma,Arial,sans-serif;line-height:1.9;font-size:15px;">
|
||||||
|
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="border-collapse:collapse;background:${BRAND.soft};">
|
||||||
|
<tr>
|
||||||
|
<td align="center" style="padding:28px 14px;">
|
||||||
|
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="border-collapse:collapse;max-width:600px;background:#ffffff;text-align:right;border:1px solid ${BRAND.border};">
|
||||||
|
<tr>
|
||||||
|
<td style="padding:0;height:4px;background:${BRAND.gold};font-size:0;line-height:0;"> </td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td style="padding:24px 28px 8px;background:${BRAND.blue};">
|
||||||
|
<p style="margin:0;font-size:11px;letter-spacing:0.18em;color:${BRAND.teal};">${eyebrow}</p>
|
||||||
|
<p style="margin:8px 0 0;font-size:22px;font-weight:700;color:#ffffff;">کنینا</p>
|
||||||
|
<p style="margin:4px 0 0;font-size:13px;color:${BRAND.gold};">مکمل تخصصی حیوانات خانگی</p>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td style="padding:28px;">
|
||||||
|
<h1 style="margin:0 0 16px;font-size:20px;font-weight:700;color:${BRAND.blue};">${title}</h1>
|
||||||
|
<div style="color:${BRAND.muted};">${options.bodyHtml}</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td style="padding:18px 28px;background:${BRAND.dark};color:#d5dde0;font-size:12px;">
|
||||||
|
<p style="margin:0;color:#ffffff;font-weight:700;">کنینا ایران</p>
|
||||||
|
<p style="margin:8px 0 0;">
|
||||||
|
<a href="mailto:support@canina.ir" style="color:${BRAND.gold};text-decoration:none;" dir="ltr">support@canina.ir</a>
|
||||||
|
·
|
||||||
|
<a href="https://canina.ir" style="color:${BRAND.teal};text-decoration:none;" dir="ltr">canina.ir</a>
|
||||||
|
</p>
|
||||||
|
<p style="margin:10px 0 0;color:#9aa8ad;">${footerNote}</p>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
</body>
|
||||||
|
</html>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function renderCaninaNotificationEmail(subject: string, content: string): string {
|
||||||
|
return renderCaninaEmailLayout({
|
||||||
|
title: subject || 'اطلاعیه کنینا',
|
||||||
|
bodyHtml: `<p style="margin:0;">${textToHtmlParagraphs(content || '')}</p>`,
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,392 @@
|
|||||||
|
import { Injectable, Logger } from '@nestjs/common';
|
||||||
|
import * as net from 'net';
|
||||||
|
import * as tls from 'tls';
|
||||||
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
|
|
||||||
|
export interface SmtpConfig {
|
||||||
|
enabled: boolean;
|
||||||
|
host: string;
|
||||||
|
port: number;
|
||||||
|
secure?: boolean; // true for 465 (TLS), false for 587/25 (STARTTLS)
|
||||||
|
user: string;
|
||||||
|
password: string;
|
||||||
|
fromName: string;
|
||||||
|
fromEmail: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SendMailOptions {
|
||||||
|
to: string;
|
||||||
|
subject: string;
|
||||||
|
text?: string;
|
||||||
|
html?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class EmailService {
|
||||||
|
private readonly logger = new Logger(EmailService.name);
|
||||||
|
|
||||||
|
constructor(private readonly prisma: PrismaService) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Read SMTP configuration from DB Setting table with fallback to env variables
|
||||||
|
*/
|
||||||
|
async getConfig(): Promise<SmtpConfig> {
|
||||||
|
try {
|
||||||
|
const setting = await this.prisma.setting.findFirst({
|
||||||
|
where: { category: 'email' },
|
||||||
|
});
|
||||||
|
const dbConfig = (setting?.value as Record<string, any>) || {};
|
||||||
|
|
||||||
|
return {
|
||||||
|
enabled: dbConfig.enabled !== undefined ? Boolean(dbConfig.enabled) : true,
|
||||||
|
host: dbConfig.host || process.env.SMTP_HOST || 'mail.canina.ir',
|
||||||
|
port: Number(dbConfig.port || process.env.SMTP_PORT || 587),
|
||||||
|
secure: dbConfig.secure !== undefined ? Boolean(dbConfig.secure) : Number(dbConfig.port || 587) === 465,
|
||||||
|
user: dbConfig.user || process.env.SMTP_USER || '',
|
||||||
|
password: dbConfig.password || process.env.SMTP_PASSWORD || '',
|
||||||
|
fromName: dbConfig.fromName || process.env.SMTP_FROM_NAME || 'کنینا ایران',
|
||||||
|
fromEmail: dbConfig.fromEmail || process.env.SMTP_FROM_EMAIL || 'support@canina.ir',
|
||||||
|
};
|
||||||
|
} catch (err: any) {
|
||||||
|
this.logger.error(`Error loading email config: ${err?.message}`);
|
||||||
|
return {
|
||||||
|
enabled: true,
|
||||||
|
host: process.env.SMTP_HOST || 'mail.canina.ir',
|
||||||
|
port: Number(process.env.SMTP_PORT || 587),
|
||||||
|
secure: Number(process.env.SMTP_PORT || 587) === 465,
|
||||||
|
user: process.env.SMTP_USER || '',
|
||||||
|
password: process.env.SMTP_PASSWORD || '',
|
||||||
|
fromName: 'کنینا ایران',
|
||||||
|
fromEmail: 'support@canina.ir',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Save SMTP configuration to database
|
||||||
|
*/
|
||||||
|
async saveConfig(dto: Partial<SmtpConfig>): Promise<SmtpConfig> {
|
||||||
|
const current = await this.getConfig();
|
||||||
|
const port = Number(dto.port ?? current.port);
|
||||||
|
const secure = dto.secure !== undefined ? Boolean(dto.secure) : (port === 465);
|
||||||
|
|
||||||
|
const updated: SmtpConfig = {
|
||||||
|
...current,
|
||||||
|
...dto,
|
||||||
|
port,
|
||||||
|
secure,
|
||||||
|
};
|
||||||
|
|
||||||
|
const existing = await this.prisma.setting.findFirst({ where: { category: 'email' } });
|
||||||
|
if (existing) {
|
||||||
|
await this.prisma.setting.update({
|
||||||
|
where: { id: existing.id },
|
||||||
|
data: { value: updated as any },
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
await this.prisma.setting.create({
|
||||||
|
data: {
|
||||||
|
category: 'email',
|
||||||
|
key: 'smtp_config',
|
||||||
|
value: updated as any,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return updated;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test SMTP connection with the given or stored configuration
|
||||||
|
*/
|
||||||
|
async testConnection(customConfig?: Partial<SmtpConfig>): Promise<{ success: boolean; message: string; banner?: string }> {
|
||||||
|
const config = customConfig ? { ...(await this.getConfig()), ...customConfig } : await this.getConfig();
|
||||||
|
|
||||||
|
if (!config.host || !config.port) {
|
||||||
|
return { success: false, message: 'آدرس هاست و پورت SMTP الزامی است.' };
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
// If port is 465 or secure=true, connect via direct TLS
|
||||||
|
const isExplicitTls = Boolean(config.secure) || Number(config.port) === 465;
|
||||||
|
let buffer = '';
|
||||||
|
let stage = 0; // 0=greet, 1=ehlo, 2=auth_login, 3=user, 4=pass, 5=quit
|
||||||
|
let banner = '';
|
||||||
|
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
try {
|
||||||
|
socket.destroy();
|
||||||
|
} catch {}
|
||||||
|
resolve({ success: false, message: 'تایماوت در اتصال به سرور SMTP (بیش از ۱۰ ثانیه)' });
|
||||||
|
}, 10000);
|
||||||
|
|
||||||
|
const cleanup = (res: { success: boolean; message: string; banner?: string }) => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
try {
|
||||||
|
socket.end();
|
||||||
|
socket.destroy();
|
||||||
|
} catch {}
|
||||||
|
resolve(res);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleData = (chunk: Buffer) => {
|
||||||
|
buffer += chunk.toString('utf8');
|
||||||
|
const lines = buffer.split('\r\n');
|
||||||
|
buffer = lines.pop() || '';
|
||||||
|
|
||||||
|
for (const line of lines) {
|
||||||
|
if (!line) continue;
|
||||||
|
const code = parseInt(line.substring(0, 3), 10);
|
||||||
|
const isFinal = line.charAt(3) === ' ';
|
||||||
|
|
||||||
|
if (!isFinal) continue; // Multi-line response continuation
|
||||||
|
|
||||||
|
if (stage === 0) {
|
||||||
|
banner = line;
|
||||||
|
if (code >= 200 && code < 300) {
|
||||||
|
stage = 1;
|
||||||
|
socket.write(`EHLO canina.ir\r\n`);
|
||||||
|
} else {
|
||||||
|
return cleanup({ success: false, message: `پاسخ ناموفق از سرور: ${line}`, banner });
|
||||||
|
}
|
||||||
|
} else if (stage === 1) {
|
||||||
|
if (code >= 200 && code < 300) {
|
||||||
|
if (config.user && config.password) {
|
||||||
|
stage = 2;
|
||||||
|
socket.write('AUTH LOGIN\r\n');
|
||||||
|
} else {
|
||||||
|
stage = 5;
|
||||||
|
socket.write('QUIT\r\n');
|
||||||
|
return cleanup({ success: true, message: 'اتصال به سرور SMTP بدون احراز هویت با موفقیت برقرار شد.', banner });
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return cleanup({ success: false, message: `خطای EHLO: ${line}`, banner });
|
||||||
|
}
|
||||||
|
} else if (stage === 2) {
|
||||||
|
if (code === 334) {
|
||||||
|
stage = 3;
|
||||||
|
socket.write(Buffer.from(config.user).toString('base64') + '\r\n');
|
||||||
|
} else {
|
||||||
|
return cleanup({ success: false, message: `سرور از AUTH LOGIN پشتیبانی نمیکند یا خطا داد: ${line}`, banner });
|
||||||
|
}
|
||||||
|
} else if (stage === 3) {
|
||||||
|
if (code === 334) {
|
||||||
|
stage = 4;
|
||||||
|
socket.write(Buffer.from(config.password).toString('base64') + '\r\n');
|
||||||
|
} else {
|
||||||
|
return cleanup({ success: false, message: `نام کاربری پذیرفته نشد: ${line}`, banner });
|
||||||
|
}
|
||||||
|
} else if (stage === 4) {
|
||||||
|
if (code === 235 || (code >= 200 && code < 300)) {
|
||||||
|
stage = 5;
|
||||||
|
socket.write('QUIT\r\n');
|
||||||
|
return cleanup({ success: true, message: 'اتصال و احراز هویت با سرور SMTP با موفقیت تأیید شد.', banner });
|
||||||
|
} else {
|
||||||
|
return cleanup({ success: false, message: `احراز هویت ناموفق بود (نام کاربری یا رمز عبور اشتباه است): ${line}`, banner });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let socket: net.Socket;
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (isExplicitTls) {
|
||||||
|
socket = tls.connect({
|
||||||
|
host: config.host,
|
||||||
|
port: config.port,
|
||||||
|
rejectUnauthorized: false,
|
||||||
|
}, () => {});
|
||||||
|
} else {
|
||||||
|
socket = net.connect({
|
||||||
|
host: config.host,
|
||||||
|
port: config.port,
|
||||||
|
}, () => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
socket.on('data', handleData);
|
||||||
|
socket.on('error', (err) => {
|
||||||
|
cleanup({ success: false, message: `خطای شبکه در ارتباط با ${config.host}:${config.port} - ${err.message}` });
|
||||||
|
});
|
||||||
|
} catch (err: any) {
|
||||||
|
cleanup({ success: false, message: `خطا در باز کردن سوکت: ${err?.message}` });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send a MIME Email message through SMTP
|
||||||
|
*/
|
||||||
|
async sendMail(options: SendMailOptions, customConfig?: Partial<SmtpConfig>): Promise<{ success: boolean; messageId?: string; error?: string }> {
|
||||||
|
const config = customConfig ? { ...(await this.getConfig()), ...customConfig } : await this.getConfig();
|
||||||
|
|
||||||
|
if (!config.enabled) {
|
||||||
|
return { success: false, error: 'سرویس ارسال ایمیل در تنظیمات غیرفعال است.' };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!config.host || !options.to) {
|
||||||
|
return { success: false, error: 'هاست SMTP یا آدرس گیرنده مشخص نشده است.' };
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
// If port is 465 or secure=true, connect via direct TLS
|
||||||
|
const isExplicitTls = Boolean(config.secure) || Number(config.port) === 465;
|
||||||
|
let buffer = '';
|
||||||
|
let stage = 0; // 0=greet, 1=ehlo, 2=auth_login, 3=user, 4=pass, 5=mail_from, 6=rcpt_to, 7=data_cmd, 8=data_body, 9=quit
|
||||||
|
const messageId = `<${Date.now()}.${Math.random().toString(36).substring(2)}@${config.host}>`;
|
||||||
|
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
try {
|
||||||
|
socket.destroy();
|
||||||
|
} catch {}
|
||||||
|
resolve({ success: false, error: 'تایماوت ارسال ایمیل (۱۵ ثانیه)' });
|
||||||
|
}, 15000);
|
||||||
|
|
||||||
|
const cleanup = (res: { success: boolean; messageId?: string; error?: string }) => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
try {
|
||||||
|
socket.end();
|
||||||
|
socket.destroy();
|
||||||
|
} catch {}
|
||||||
|
resolve(res);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleData = (chunk: Buffer) => {
|
||||||
|
buffer += chunk.toString('utf8');
|
||||||
|
const lines = buffer.split('\r\n');
|
||||||
|
buffer = lines.pop() || '';
|
||||||
|
|
||||||
|
for (const line of lines) {
|
||||||
|
if (!line) continue;
|
||||||
|
const code = parseInt(line.substring(0, 3), 10);
|
||||||
|
const isFinal = line.charAt(3) === ' ';
|
||||||
|
|
||||||
|
if (!isFinal) continue;
|
||||||
|
|
||||||
|
if (stage === 0) {
|
||||||
|
if (code >= 200 && code < 300) {
|
||||||
|
stage = 1;
|
||||||
|
socket.write(`EHLO canina.ir\r\n`);
|
||||||
|
} else {
|
||||||
|
return cleanup({ success: false, error: `پاسخ سرور: ${line}` });
|
||||||
|
}
|
||||||
|
} else if (stage === 1) {
|
||||||
|
if (code >= 200 && code < 300) {
|
||||||
|
if (config.user && config.password) {
|
||||||
|
stage = 2;
|
||||||
|
socket.write('AUTH LOGIN\r\n');
|
||||||
|
} else {
|
||||||
|
stage = 5;
|
||||||
|
socket.write(`MAIL FROM:<${config.fromEmail}>\r\n`);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return cleanup({ success: false, error: `خطای EHLO: ${line}` });
|
||||||
|
}
|
||||||
|
} else if (stage === 2) {
|
||||||
|
if (code === 334) {
|
||||||
|
stage = 3;
|
||||||
|
socket.write(Buffer.from(config.user).toString('base64') + '\r\n');
|
||||||
|
} else {
|
||||||
|
return cleanup({ success: false, error: `خطای احراز هویت: ${line}` });
|
||||||
|
}
|
||||||
|
} else if (stage === 3) {
|
||||||
|
if (code === 334) {
|
||||||
|
stage = 4;
|
||||||
|
socket.write(Buffer.from(config.password).toString('base64') + '\r\n');
|
||||||
|
} else {
|
||||||
|
return cleanup({ success: false, error: `نام کاربری رد شد: ${line}` });
|
||||||
|
}
|
||||||
|
} else if (stage === 4) {
|
||||||
|
if (code === 235 || (code >= 200 && code < 300)) {
|
||||||
|
stage = 5;
|
||||||
|
socket.write(`MAIL FROM:<${config.fromEmail}>\r\n`);
|
||||||
|
} else {
|
||||||
|
return cleanup({ success: false, error: `رمز عبور رد شد: ${line}` });
|
||||||
|
}
|
||||||
|
} else if (stage === 5) {
|
||||||
|
if (code >= 200 && code < 300) {
|
||||||
|
stage = 6;
|
||||||
|
socket.write(`RCPT TO:<${options.to}>\r\n`);
|
||||||
|
} else {
|
||||||
|
return cleanup({ success: false, error: `آدرس فرستنده رد شد: ${line}` });
|
||||||
|
}
|
||||||
|
} else if (stage === 6) {
|
||||||
|
if (code >= 200 && code < 300) {
|
||||||
|
stage = 7;
|
||||||
|
socket.write('DATA\r\n');
|
||||||
|
} else {
|
||||||
|
return cleanup({ success: false, error: `آدرس گیرنده رد شد: ${line}` });
|
||||||
|
}
|
||||||
|
} else if (stage === 7) {
|
||||||
|
if (code === 354) {
|
||||||
|
stage = 8;
|
||||||
|
const encodedSubject = `=?UTF-8?B?${Buffer.from(options.subject).toString('base64')}?=`;
|
||||||
|
const encodedFromName = `=?UTF-8?B?${Buffer.from(config.fromName).toString('base64')}?=`;
|
||||||
|
const boundary = `boundary_${Date.now()}`;
|
||||||
|
|
||||||
|
let emailBody = '';
|
||||||
|
emailBody += `From: ${encodedFromName} <${config.fromEmail}>\r\n`;
|
||||||
|
emailBody += `To: <${options.to}>\r\n`;
|
||||||
|
emailBody += `Subject: ${encodedSubject}\r\n`;
|
||||||
|
emailBody += `Message-ID: ${messageId}\r\n`;
|
||||||
|
emailBody += `Date: ${new Date().toUTCString()}\r\n`;
|
||||||
|
emailBody += `MIME-Version: 1.0\r\n`;
|
||||||
|
emailBody += `Content-Type: multipart/alternative; boundary="${boundary}"\r\n\r\n`;
|
||||||
|
|
||||||
|
if (options.text) {
|
||||||
|
emailBody += `--${boundary}\r\n`;
|
||||||
|
emailBody += `Content-Type: text/plain; charset=UTF-8\r\n`;
|
||||||
|
emailBody += `Content-Transfer-Encoding: base64\r\n\r\n`;
|
||||||
|
emailBody += Buffer.from(options.text).toString('base64') + '\r\n\r\n';
|
||||||
|
}
|
||||||
|
|
||||||
|
const htmlContent = options.html || options.text || '';
|
||||||
|
emailBody += `--${boundary}\r\n`;
|
||||||
|
emailBody += `Content-Type: text/html; charset=UTF-8\r\n`;
|
||||||
|
emailBody += `Content-Transfer-Encoding: base64\r\n\r\n`;
|
||||||
|
emailBody += Buffer.from(htmlContent).toString('base64') + '\r\n\r\n';
|
||||||
|
|
||||||
|
emailBody += `--${boundary}--\r\n.\r\n`;
|
||||||
|
|
||||||
|
socket.write(emailBody);
|
||||||
|
} else {
|
||||||
|
return cleanup({ success: false, error: `دستور DATA رد شد: ${line}` });
|
||||||
|
}
|
||||||
|
} else if (stage === 8) {
|
||||||
|
if (code >= 200 && code < 300) {
|
||||||
|
stage = 9;
|
||||||
|
socket.write('QUIT\r\n');
|
||||||
|
return cleanup({ success: true, messageId });
|
||||||
|
} else {
|
||||||
|
return cleanup({ success: false, error: `رد شدن ارسال محتوا: ${line}` });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let socket: net.Socket;
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (isExplicitTls) {
|
||||||
|
socket = tls.connect({
|
||||||
|
host: config.host,
|
||||||
|
port: config.port,
|
||||||
|
rejectUnauthorized: false,
|
||||||
|
}, () => {});
|
||||||
|
} else {
|
||||||
|
socket = net.connect({
|
||||||
|
host: config.host,
|
||||||
|
port: config.port,
|
||||||
|
}, () => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
socket.on('data', handleData);
|
||||||
|
socket.on('error', (err) => {
|
||||||
|
cleanup({ success: false, error: `خطای ارسال: ${err.message}` });
|
||||||
|
});
|
||||||
|
} catch (err: any) {
|
||||||
|
cleanup({ success: false, error: `خطا در باز کردن اتصال: ${err?.message}` });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { NotificationsQueueService } from './notifications-queue.service';
|
||||||
|
import { EmailService } from './email.service';
|
||||||
|
import { SmsService } from '../common/services/sms.service';
|
||||||
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
|
|
||||||
|
describe('NotificationsQueueService', () => {
|
||||||
|
let service: NotificationsQueueService;
|
||||||
|
let prisma: any;
|
||||||
|
let emailService: any;
|
||||||
|
let smsService: any;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
prisma = {
|
||||||
|
notificationQueue: {
|
||||||
|
findUnique: jest.fn(),
|
||||||
|
create: jest.fn(),
|
||||||
|
update: jest.fn(),
|
||||||
|
findMany: jest.fn(),
|
||||||
|
count: jest.fn(),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
emailService = {
|
||||||
|
sendMail: jest.fn().mockResolvedValue({ success: true, messageId: 'msg-123' }),
|
||||||
|
};
|
||||||
|
|
||||||
|
smsService = {
|
||||||
|
sendPatternSms: jest.fn().mockResolvedValue(true),
|
||||||
|
sendSms: jest.fn().mockResolvedValue(true),
|
||||||
|
};
|
||||||
|
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
providers: [
|
||||||
|
NotificationsQueueService,
|
||||||
|
{ provide: PrismaService, useValue: prisma },
|
||||||
|
{ provide: EmailService, useValue: emailService },
|
||||||
|
{ provide: SmsService, useValue: smsService },
|
||||||
|
],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
service = module.get<NotificationsQueueService>(NotificationsQueueService);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should enqueue notification and preserve idempotency', async () => {
|
||||||
|
prisma.notificationQueue.findUnique.mockResolvedValueOnce(null);
|
||||||
|
prisma.notificationQueue.create.mockResolvedValueOnce({
|
||||||
|
id: 'queue-1',
|
||||||
|
channel: 'EMAIL',
|
||||||
|
recipient: 'user@example.com',
|
||||||
|
event: 'ORDER_CREATED',
|
||||||
|
content: 'Hello World',
|
||||||
|
idempotencyKey: 'idemp-1',
|
||||||
|
status: 'QUEUED',
|
||||||
|
attempts: 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
const res = await service.enqueue({
|
||||||
|
channel: 'EMAIL',
|
||||||
|
recipient: 'user@example.com',
|
||||||
|
event: 'ORDER_CREATED',
|
||||||
|
content: 'Hello World',
|
||||||
|
idempotencyKey: 'idemp-1',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(prisma.notificationQueue.findUnique).toHaveBeenCalledWith({ where: { idempotencyKey: 'idemp-1' } });
|
||||||
|
expect(prisma.notificationQueue.create).toHaveBeenCalled();
|
||||||
|
expect(res.id).toBe('queue-1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return existing notification if idempotency key exists', async () => {
|
||||||
|
const existing = {
|
||||||
|
id: 'existing-1',
|
||||||
|
channel: 'SMS',
|
||||||
|
recipient: '09121111111',
|
||||||
|
event: 'OTP',
|
||||||
|
content: '12345',
|
||||||
|
idempotencyKey: 'idemp-2',
|
||||||
|
status: 'SENT',
|
||||||
|
};
|
||||||
|
prisma.notificationQueue.findUnique.mockResolvedValueOnce(existing);
|
||||||
|
|
||||||
|
const res = await service.enqueue({
|
||||||
|
channel: 'SMS',
|
||||||
|
recipient: '09121111111',
|
||||||
|
event: 'OTP',
|
||||||
|
content: '12345',
|
||||||
|
idempotencyKey: 'idemp-2',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(prisma.notificationQueue.create).not.toHaveBeenCalled();
|
||||||
|
expect(res.id).toBe('existing-1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should process email queue item and mark as SENT', async () => {
|
||||||
|
const item = {
|
||||||
|
id: 'item-1',
|
||||||
|
channel: 'EMAIL',
|
||||||
|
recipient: 'user@example.com',
|
||||||
|
subject: 'Test Subject',
|
||||||
|
content: 'Test Body',
|
||||||
|
payload: {},
|
||||||
|
status: 'QUEUED',
|
||||||
|
attempts: 0,
|
||||||
|
maxAttempts: 3,
|
||||||
|
};
|
||||||
|
prisma.notificationQueue.findUnique.mockResolvedValueOnce(item);
|
||||||
|
prisma.notificationQueue.update.mockResolvedValue({});
|
||||||
|
|
||||||
|
await service.processItem('item-1');
|
||||||
|
|
||||||
|
expect(emailService.sendMail).toHaveBeenCalledWith({
|
||||||
|
to: 'user@example.com',
|
||||||
|
subject: 'Test Subject',
|
||||||
|
text: 'Test Body',
|
||||||
|
html: expect.stringContaining('Test Body'),
|
||||||
|
});
|
||||||
|
const sentHtml = String((emailService.sendMail as jest.Mock).mock.calls[0][0].html);
|
||||||
|
expect(sentHtml).toContain('#1E4053');
|
||||||
|
expect(sentHtml).toContain('#F1B646');
|
||||||
|
expect(sentHtml).toContain('support@canina.ir');
|
||||||
|
expect(prisma.notificationQueue.update).toHaveBeenCalledWith({
|
||||||
|
where: { id: 'item-1' },
|
||||||
|
data: expect.objectContaining({ status: 'SENT' }),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,281 @@
|
|||||||
|
import { Injectable, Logger, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
|
||||||
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
|
import { EmailService } from './email.service';
|
||||||
|
import { renderCaninaNotificationEmail } from './email-layout';
|
||||||
|
import { SmsService } from '../common/services/sms.service';
|
||||||
|
|
||||||
|
export interface EnqueueOptions {
|
||||||
|
channel: 'SMS' | 'EMAIL';
|
||||||
|
recipient: string;
|
||||||
|
event: string;
|
||||||
|
subject?: string;
|
||||||
|
content: string;
|
||||||
|
payload?: any;
|
||||||
|
idempotencyKey?: string;
|
||||||
|
maxAttempts?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class NotificationsQueueService implements OnModuleInit, OnModuleDestroy {
|
||||||
|
private readonly logger = new Logger(NotificationsQueueService.name);
|
||||||
|
private workerInterval: NodeJS.Timeout | null = null;
|
||||||
|
private isProcessing = false;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly prisma: PrismaService,
|
||||||
|
private readonly emailService: EmailService,
|
||||||
|
private readonly smsService: SmsService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
onModuleInit() {
|
||||||
|
// Run background queue processor every 15 seconds
|
||||||
|
this.workerInterval = setInterval(() => {
|
||||||
|
this.processQueue().catch((err) => {
|
||||||
|
this.logger.error(`Error in queue worker: ${err?.message}`);
|
||||||
|
});
|
||||||
|
}, 15000);
|
||||||
|
}
|
||||||
|
|
||||||
|
onModuleDestroy() {
|
||||||
|
if (this.workerInterval) {
|
||||||
|
clearInterval(this.workerInterval);
|
||||||
|
this.workerInterval = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Enqueue a durable notification with idempotency check
|
||||||
|
*/
|
||||||
|
async enqueue(options: EnqueueOptions) {
|
||||||
|
if (options.idempotencyKey) {
|
||||||
|
const existing = await this.prisma.notificationQueue.findUnique({
|
||||||
|
where: { idempotencyKey: options.idempotencyKey },
|
||||||
|
});
|
||||||
|
if (existing) {
|
||||||
|
this.logger.log(`Notification idempotency matched for key: ${options.idempotencyKey}`);
|
||||||
|
return existing;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const item = await this.prisma.notificationQueue.create({
|
||||||
|
data: {
|
||||||
|
channel: options.channel,
|
||||||
|
recipient: options.recipient,
|
||||||
|
event: options.event,
|
||||||
|
subject: options.subject || null,
|
||||||
|
content: options.content,
|
||||||
|
payload: options.payload ?? null,
|
||||||
|
idempotencyKey: options.idempotencyKey || null,
|
||||||
|
maxAttempts: options.maxAttempts ?? 3,
|
||||||
|
status: 'QUEUED',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Attempt immediate asynchronous process in the background
|
||||||
|
setImmediate(() => {
|
||||||
|
this.processItem(item.id).catch(() => {});
|
||||||
|
});
|
||||||
|
|
||||||
|
return item;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Process a single queued item by ID
|
||||||
|
*/
|
||||||
|
async processItem(id: string) {
|
||||||
|
const item = await this.prisma.notificationQueue.findUnique({ where: { id } });
|
||||||
|
if (!item || item.status === 'SENT') return;
|
||||||
|
|
||||||
|
if (item.attempts >= item.maxAttempts) {
|
||||||
|
await this.prisma.notificationQueue.update({
|
||||||
|
where: { id },
|
||||||
|
data: { status: 'FAILED' },
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.prisma.notificationQueue.update({
|
||||||
|
where: { id },
|
||||||
|
data: {
|
||||||
|
status: 'PROCESSING',
|
||||||
|
attempts: { increment: 1 },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (item.channel === 'EMAIL') {
|
||||||
|
const payloadObj = (item.payload as Record<string, any>) || {};
|
||||||
|
const subject = item.subject || 'اطلاعیه کنینا ایران';
|
||||||
|
const res = await this.emailService.sendMail({
|
||||||
|
to: item.recipient,
|
||||||
|
subject,
|
||||||
|
text: item.content,
|
||||||
|
html: payloadObj.html || renderCaninaNotificationEmail(subject, item.content || ''),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (res.success) {
|
||||||
|
await this.prisma.notificationQueue.update({
|
||||||
|
where: { id },
|
||||||
|
data: {
|
||||||
|
status: 'SENT',
|
||||||
|
sentAt: new Date(),
|
||||||
|
lastError: null,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
} else {
|
||||||
|
throw new Error(res.error || 'خطای نامشخص در ارسال ایمیل');
|
||||||
|
}
|
||||||
|
} else if (item.channel === 'SMS') {
|
||||||
|
const payloadObj = (item.payload as Record<string, any>) || {};
|
||||||
|
if (payloadObj.patternId && Array.isArray(payloadObj.args)) {
|
||||||
|
const sent = await this.smsService.sendPatternSms({
|
||||||
|
to: item.recipient,
|
||||||
|
bodyId: Number(payloadObj.patternId),
|
||||||
|
args: payloadObj.args,
|
||||||
|
type: item.event,
|
||||||
|
});
|
||||||
|
if (!sent) {
|
||||||
|
throw new Error(`ارسال پیامک پترن ${payloadObj.patternId} ناموفق بود.`);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const sent = await this.smsService.sendSms(item.recipient, item.content);
|
||||||
|
if (!sent) {
|
||||||
|
throw new Error(`ارسال پیامک متنی به ${item.recipient} ناموفق بود.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.prisma.notificationQueue.update({
|
||||||
|
where: { id },
|
||||||
|
data: {
|
||||||
|
status: 'SENT',
|
||||||
|
sentAt: new Date(),
|
||||||
|
lastError: null,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} catch (err: any) {
|
||||||
|
const isFinalAttempt = item.attempts + 1 >= item.maxAttempts;
|
||||||
|
await this.prisma.notificationQueue.update({
|
||||||
|
where: { id },
|
||||||
|
data: {
|
||||||
|
status: isFinalAttempt ? 'FAILED' : 'QUEUED',
|
||||||
|
lastError: err?.message || 'خطا در ارسال پیام',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
this.logger.warn(`Failed to deliver notification ${id} (${item.channel} to ${item.recipient}): ${err?.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Process pending batch of queue
|
||||||
|
*/
|
||||||
|
async processQueue(batchSize = 10) {
|
||||||
|
if (this.isProcessing) return;
|
||||||
|
this.isProcessing = true;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const pendingItems = await this.prisma.notificationQueue.findMany({
|
||||||
|
where: {
|
||||||
|
status: 'QUEUED',
|
||||||
|
attempts: { lt: 3 },
|
||||||
|
},
|
||||||
|
orderBy: { createdAt: 'asc' },
|
||||||
|
take: batchSize,
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const item of pendingItems) {
|
||||||
|
await this.processItem(item.id);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
this.isProcessing = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retry a failed notification manually
|
||||||
|
*/
|
||||||
|
async retry(id: string) {
|
||||||
|
const item = await this.prisma.notificationQueue.findUnique({ where: { id } });
|
||||||
|
if (!item) throw new Error('آیتم صف یافت نشد.');
|
||||||
|
|
||||||
|
const updated = await this.prisma.notificationQueue.update({
|
||||||
|
where: { id },
|
||||||
|
data: {
|
||||||
|
status: 'QUEUED',
|
||||||
|
attempts: 0,
|
||||||
|
lastError: null,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
setImmediate(() => {
|
||||||
|
this.processItem(id).catch(() => {});
|
||||||
|
});
|
||||||
|
|
||||||
|
return updated;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get queue items with filtering and pagination
|
||||||
|
*/
|
||||||
|
async getQueue(query: { page?: number; limit?: number; status?: string; channel?: string; search?: string }) {
|
||||||
|
const page = Math.max(1, Number(query.page || 1));
|
||||||
|
const limit = Math.max(1, Math.min(100, Number(query.limit || 20)));
|
||||||
|
const skip = (page - 1) * limit;
|
||||||
|
|
||||||
|
const where: any = {};
|
||||||
|
if (query.status) where.status = query.status;
|
||||||
|
if (query.channel) where.channel = query.channel;
|
||||||
|
if (query.search) {
|
||||||
|
where.OR = [
|
||||||
|
{ recipient: { contains: query.search, mode: 'insensitive' } },
|
||||||
|
{ subject: { contains: query.search, mode: 'insensitive' } },
|
||||||
|
{ event: { contains: query.search, mode: 'insensitive' } },
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
const [items, total] = await Promise.all([
|
||||||
|
this.prisma.notificationQueue.findMany({
|
||||||
|
where,
|
||||||
|
orderBy: { createdAt: 'desc' },
|
||||||
|
skip,
|
||||||
|
take: limit,
|
||||||
|
}),
|
||||||
|
this.prisma.notificationQueue.count({ where }),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const stats = await this.getStats();
|
||||||
|
|
||||||
|
return {
|
||||||
|
items,
|
||||||
|
total,
|
||||||
|
page,
|
||||||
|
limit,
|
||||||
|
totalPages: Math.ceil(total / limit) || 1,
|
||||||
|
stats,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get overall stats
|
||||||
|
*/
|
||||||
|
async getStats() {
|
||||||
|
const [total, queued, processing, sent, failed] = await Promise.all([
|
||||||
|
this.prisma.notificationQueue.count(),
|
||||||
|
this.prisma.notificationQueue.count({ where: { status: 'QUEUED' } }),
|
||||||
|
this.prisma.notificationQueue.count({ where: { status: 'PROCESSING' } }),
|
||||||
|
this.prisma.notificationQueue.count({ where: { status: 'SENT' } }),
|
||||||
|
this.prisma.notificationQueue.count({ where: { status: 'FAILED' } }),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
total,
|
||||||
|
queued,
|
||||||
|
processing,
|
||||||
|
sent,
|
||||||
|
failed,
|
||||||
|
successRate: total > 0 ? Math.round((sent / total) * 100) : 100,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,330 @@
|
|||||||
|
import {
|
||||||
|
Controller,
|
||||||
|
Get,
|
||||||
|
Post,
|
||||||
|
Put,
|
||||||
|
Delete,
|
||||||
|
Body,
|
||||||
|
Param,
|
||||||
|
Query,
|
||||||
|
UseGuards,
|
||||||
|
BadRequestException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||||
|
import { EmailService } from './email.service';
|
||||||
|
import { escapeHtml, renderCaninaEmailLayout, textToHtmlParagraphs } from './email-layout';
|
||||||
|
import { NotificationsQueueService } from './notifications-queue.service';
|
||||||
|
import { SmsService } from '../common/services/sms.service';
|
||||||
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
|
import {
|
||||||
|
UpdateEmailConfigDto,
|
||||||
|
TestSmtpDto,
|
||||||
|
SendTestEmailDto,
|
||||||
|
SendTestSmsDto,
|
||||||
|
ManualSendDto,
|
||||||
|
CreateTemplateDto,
|
||||||
|
} from './notifications.dto';
|
||||||
|
|
||||||
|
@Controller('admin/notifications')
|
||||||
|
@UseGuards(JwtAuthGuard)
|
||||||
|
export class NotificationsController {
|
||||||
|
constructor(
|
||||||
|
private readonly emailService: EmailService,
|
||||||
|
private readonly queueService: NotificationsQueueService,
|
||||||
|
private readonly smsService: SmsService,
|
||||||
|
private readonly prisma: PrismaService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get notification settings (Email & SMS)
|
||||||
|
*/
|
||||||
|
@Get('config')
|
||||||
|
async getConfig() {
|
||||||
|
const [email, sms] = await Promise.all([
|
||||||
|
this.emailService.getConfig(),
|
||||||
|
this.smsService.getSmsConfig(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Mask password for security
|
||||||
|
const maskedEmail = {
|
||||||
|
...email,
|
||||||
|
password: email.password ? '••••••••' : '',
|
||||||
|
};
|
||||||
|
|
||||||
|
const maskedSms = {
|
||||||
|
...sms,
|
||||||
|
password: sms.password ? '••••••••' : '',
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
data: {
|
||||||
|
email: maskedEmail,
|
||||||
|
sms: maskedSms,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update SMTP Email config
|
||||||
|
*/
|
||||||
|
@Put('email-config')
|
||||||
|
async updateEmailConfig(@Body() dto: UpdateEmailConfigDto) {
|
||||||
|
// If password is masked, don't overwrite with dots
|
||||||
|
if (dto.password && dto.password.includes('•')) {
|
||||||
|
delete dto.password;
|
||||||
|
}
|
||||||
|
|
||||||
|
const saved = await this.emailService.saveConfig(dto);
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: 'تنظیمات ایمیل با موفقیت ذخیره شد.',
|
||||||
|
data: {
|
||||||
|
...saved,
|
||||||
|
password: saved.password ? '••••••••' : '',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test SMTP connection live
|
||||||
|
*/
|
||||||
|
@Post('test-smtp')
|
||||||
|
async testSmtp(@Body() customConfig?: TestSmtpDto) {
|
||||||
|
if (customConfig?.password && customConfig.password.includes('•')) {
|
||||||
|
delete customConfig.password;
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await this.emailService.testConnection(customConfig);
|
||||||
|
return {
|
||||||
|
success: res.success,
|
||||||
|
message: res.message,
|
||||||
|
banner: res.banner,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send test email
|
||||||
|
*/
|
||||||
|
@Post('send-test-email')
|
||||||
|
async sendTestEmail(@Body() body: SendTestEmailDto) {
|
||||||
|
if (!body.to) throw new BadRequestException('آدرس ایمیل مقصد الزامی است.');
|
||||||
|
|
||||||
|
const subject = body.subject || 'تست اتصال ایمیل - کنینا ایران';
|
||||||
|
const message =
|
||||||
|
body.message ||
|
||||||
|
'این یک ایمیل آزمایشی جهت بررسی صحت تنظیمات سرور SMTP در فروشگاه کنینا است.';
|
||||||
|
const res = await this.emailService.sendMail({
|
||||||
|
to: body.to,
|
||||||
|
subject,
|
||||||
|
text: message,
|
||||||
|
html: renderCaninaEmailLayout({
|
||||||
|
title: subject,
|
||||||
|
bodyHtml: `<p style="margin:0 0 16px;">${textToHtmlParagraphs(message)}</p><p style="margin:0;font-size:13px;color:#7A9B9F;">زمان ارسال: ${escapeHtml(new Date().toLocaleString('fa-IR'))}</p>`,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!res.success) {
|
||||||
|
throw new BadRequestException(res.error || 'ارسال ایمیل تستی ناموفق بود.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: `ایمیل تستی با موفقیت به ${body.to} ارسال شد.`,
|
||||||
|
messageId: res.messageId,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send test SMS
|
||||||
|
*/
|
||||||
|
@Post('send-test-sms')
|
||||||
|
async sendTestSms(@Body() body: SendTestSmsDto) {
|
||||||
|
if (!body.to || !body.message) {
|
||||||
|
throw new BadRequestException('شماره موبایل و متن پیام الزامی است.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await this.smsService.sendSms(body.to, body.message);
|
||||||
|
if (!res) throw new BadRequestException('ارسال پیامک تستی ناموفق بود.');
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: `پیامک تستی با موفقیت به ${body.to} ارسال شد.`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Manual targeted notification send
|
||||||
|
*/
|
||||||
|
@Post('manual-send')
|
||||||
|
async manualSend(@Body() body: ManualSendDto) {
|
||||||
|
if (!body.channel || !body.content) {
|
||||||
|
throw new BadRequestException('کانال ارسال و متن پیام الزامی است.');
|
||||||
|
}
|
||||||
|
|
||||||
|
let targetList: string[] = [];
|
||||||
|
|
||||||
|
if (body.targetType === 'single') {
|
||||||
|
if (!body.recipient) throw new BadRequestException('گیرنده پیام مشخص نشده است.');
|
||||||
|
targetList = [body.recipient.trim()];
|
||||||
|
} else if (body.targetType === 'custom_list') {
|
||||||
|
if (!Array.isArray(body.recipients) || !body.recipients.length) {
|
||||||
|
throw new BadRequestException('لیست گیرندگان خالی است.');
|
||||||
|
}
|
||||||
|
targetList = body.recipients.map((r) => r.trim()).filter(Boolean);
|
||||||
|
} else if (body.targetType === 'all_users') {
|
||||||
|
const users = await this.prisma.user.findMany({
|
||||||
|
select: { mobile: true, email: true },
|
||||||
|
take: 1000,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (body.channel === 'SMS') {
|
||||||
|
targetList = users.map((u) => u.mobile).filter(Boolean) as string[];
|
||||||
|
} else {
|
||||||
|
targetList = users.map((u) => u.email).filter(Boolean) as string[];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!targetList.length) {
|
||||||
|
throw new BadRequestException('هیچ گیرنده معتبری برای ارسال یافت نشد.');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Enqueue all items into durable queue
|
||||||
|
const queuedItems = await Promise.all(
|
||||||
|
targetList.map((rec) =>
|
||||||
|
this.queueService.enqueue({
|
||||||
|
channel: body.channel,
|
||||||
|
recipient: rec,
|
||||||
|
event: 'MANUAL_TARGETED_SEND',
|
||||||
|
subject: body.subject,
|
||||||
|
content: body.content,
|
||||||
|
idempotencyKey: `manual_${body.channel}_${rec}_${Date.now()}_${Math.random().toString(36).substring(2, 7)}`,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: `${queuedItems.length} پیام با موفقیت در صف ارسال قرار گرفت.`,
|
||||||
|
count: queuedItems.length,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get queue items and statistics
|
||||||
|
*/
|
||||||
|
@Get('queue')
|
||||||
|
async getQueue(
|
||||||
|
@Query('page') page?: number,
|
||||||
|
@Query('limit') limit?: number,
|
||||||
|
@Query('status') status?: string,
|
||||||
|
@Query('channel') channel?: string,
|
||||||
|
@Query('search') search?: string,
|
||||||
|
) {
|
||||||
|
const data = await this.queueService.getQueue({ page, limit, status, channel, search });
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
data,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retry failed queue item
|
||||||
|
*/
|
||||||
|
@Post('queue/:id/retry')
|
||||||
|
async retryQueueItem(@Param('id') id: string) {
|
||||||
|
const retried = await this.queueService.retry(id);
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: 'پیام مجدداً در صف ارسال قرار گرفت.',
|
||||||
|
data: retried,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get notification templates & event definitions
|
||||||
|
*/
|
||||||
|
@Get('templates')
|
||||||
|
async getTemplates() {
|
||||||
|
const templates = await this.prisma.notificationTemplate.findMany({
|
||||||
|
orderBy: { createdAt: 'desc' },
|
||||||
|
});
|
||||||
|
|
||||||
|
const defaultEvents = [
|
||||||
|
{ event: 'ORDER_CREATED', name: 'ثبت سفارش جدید', variables: ['order_id', 'customer_name', 'total_amount'] },
|
||||||
|
{ event: 'PAYMENT_SUCCESS', name: 'پرداخت موفق سفارش', variables: ['order_id', 'track_id', 'amount'] },
|
||||||
|
{ event: 'ORDER_SHIPPED', name: 'ارسال سفارش پستی', variables: ['order_id', 'tracking_code', 'carrier'] },
|
||||||
|
{ event: 'NEW_LEAD', name: 'درخواست تماس یا مشاوره جدید', variables: ['lead_name', 'phone', 'product_name'] },
|
||||||
|
{ event: 'USER_REGISTERED', name: 'ثبتنام کاربر جدید', variables: ['user_name', 'mobile'] },
|
||||||
|
{ event: 'TICKET_REPLIED', name: 'پاسخ به تیکت پشتیبانی', variables: ['ticket_id', 'user_name'] },
|
||||||
|
];
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
data: {
|
||||||
|
templates,
|
||||||
|
events: defaultEvents,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create or update notification template
|
||||||
|
*/
|
||||||
|
@Post('templates')
|
||||||
|
async upsertTemplate(@Body() dto: CreateTemplateDto) {
|
||||||
|
if (!dto.channel || !dto.event || !dto.name || !dto.body) {
|
||||||
|
throw new BadRequestException('اطلاعات ضروری قالب ناقص است.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = {
|
||||||
|
channel: dto.channel,
|
||||||
|
event: dto.event,
|
||||||
|
name: dto.name,
|
||||||
|
subject: dto.subject || null,
|
||||||
|
body: dto.body,
|
||||||
|
patternCode: dto.patternCode || null,
|
||||||
|
variables: dto.variables || [],
|
||||||
|
recipientType: dto.recipientType || 'customer',
|
||||||
|
customRecipient: dto.customRecipient || null,
|
||||||
|
isActive: dto.isActive !== undefined ? dto.isActive : true,
|
||||||
|
};
|
||||||
|
|
||||||
|
let template;
|
||||||
|
if (dto.id) {
|
||||||
|
template = await this.prisma.notificationTemplate.update({
|
||||||
|
where: { id: dto.id },
|
||||||
|
data,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
template = await this.prisma.notificationTemplate.upsert({
|
||||||
|
where: {
|
||||||
|
channel_event: {
|
||||||
|
channel: dto.channel,
|
||||||
|
event: dto.event,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
create: data,
|
||||||
|
update: data,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: 'قالب رویداد با موفقیت ذخیره شد.',
|
||||||
|
data: template,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete template
|
||||||
|
*/
|
||||||
|
@Delete('templates/:id')
|
||||||
|
async deleteTemplate(@Param('id') id: string) {
|
||||||
|
await this.prisma.notificationTemplate.delete({ where: { id } });
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: 'قالب رویداد حذف شد.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
import { IsString, IsNotEmpty, IsOptional, IsNumber, IsBoolean, IsIn, IsArray } from 'class-validator';
|
||||||
|
|
||||||
|
export class UpdateEmailConfigDto {
|
||||||
|
@IsBoolean()
|
||||||
|
@IsOptional()
|
||||||
|
enabled?: boolean;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
host!: string;
|
||||||
|
|
||||||
|
@IsNumber()
|
||||||
|
port!: number;
|
||||||
|
|
||||||
|
@IsBoolean()
|
||||||
|
@IsOptional()
|
||||||
|
secure?: boolean = true;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
user?: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
password?: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
from?: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
fromName?: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
fromEmail?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class TestSmtpDto {
|
||||||
|
@IsBoolean()
|
||||||
|
@IsOptional()
|
||||||
|
enabled?: boolean;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
host?: string;
|
||||||
|
|
||||||
|
@IsNumber()
|
||||||
|
@IsOptional()
|
||||||
|
port?: number;
|
||||||
|
|
||||||
|
@IsBoolean()
|
||||||
|
@IsOptional()
|
||||||
|
secure?: boolean = true;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
user?: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
password?: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
from?: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
fromName?: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
fromEmail?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class SendTestEmailDto {
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
to!: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
subject?: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
message?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class SendTestSmsDto {
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
to!: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
message!: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ManualSendDto {
|
||||||
|
@IsString()
|
||||||
|
@IsIn(['SMS', 'EMAIL'])
|
||||||
|
channel!: 'SMS' | 'EMAIL';
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsIn(['single', 'all_users', 'custom_list'])
|
||||||
|
targetType!: 'single' | 'all_users' | 'custom_list';
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
recipient?: string;
|
||||||
|
|
||||||
|
@IsArray()
|
||||||
|
@IsOptional()
|
||||||
|
recipients?: string[];
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
subject?: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
content!: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class CreateTemplateDto {
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
id?: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsIn(['SMS', 'EMAIL'])
|
||||||
|
channel!: 'SMS' | 'EMAIL';
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
event!: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
name!: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
subject?: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
body!: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
patternCode?: string;
|
||||||
|
|
||||||
|
@IsArray()
|
||||||
|
@IsOptional()
|
||||||
|
variables?: string[];
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
recipientType?: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
customRecipient?: string;
|
||||||
|
|
||||||
|
@IsBoolean()
|
||||||
|
@IsOptional()
|
||||||
|
isActive?: boolean;
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { PrismaModule } from '../prisma/prisma.module';
|
||||||
|
import { SmsModule } from '../common/sms.module';
|
||||||
|
import { EmailService } from './email.service';
|
||||||
|
import { NotificationsQueueService } from './notifications-queue.service';
|
||||||
|
import { NotificationsController } from './notifications.controller';
|
||||||
|
import { TransactionalEmailsService } from './transactional-emails.service';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [PrismaModule, SmsModule],
|
||||||
|
controllers: [NotificationsController],
|
||||||
|
providers: [EmailService, NotificationsQueueService, TransactionalEmailsService],
|
||||||
|
exports: [EmailService, NotificationsQueueService, TransactionalEmailsService],
|
||||||
|
})
|
||||||
|
export class NotificationsModule {}
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
import { Injectable, Logger } from '@nestjs/common';
|
||||||
|
import { EmailService } from './email.service';
|
||||||
|
import {
|
||||||
|
escapeHtml,
|
||||||
|
renderCaninaEmailLayout,
|
||||||
|
textToHtmlParagraphs,
|
||||||
|
} from './email-layout';
|
||||||
|
|
||||||
|
const ADMIN_NOTIFY_TO = [
|
||||||
|
'support@canina.ir',
|
||||||
|
'parsa.aghaee@gmail.com',
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class TransactionalEmailsService {
|
||||||
|
private readonly logger = new Logger(TransactionalEmailsService.name);
|
||||||
|
|
||||||
|
constructor(private readonly emailService: EmailService) {}
|
||||||
|
|
||||||
|
private async sendSafe(to: string, subject: string, text: string, html: string) {
|
||||||
|
try {
|
||||||
|
const res = await this.emailService.sendMail({ to, subject, text, html });
|
||||||
|
if (!res.success) {
|
||||||
|
this.logger.warn(`Email to ${to} failed: ${res.error || 'unknown'}`);
|
||||||
|
}
|
||||||
|
return res;
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.warn(`Email to ${to} threw: ${(err as Error).message}`);
|
||||||
|
return { success: false, error: (err as Error).message };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async sendWelcome(to: string | null | undefined, firstName?: string | null) {
|
||||||
|
if (!to) return;
|
||||||
|
const name = (firstName || '').trim() || 'کاربر گرامی';
|
||||||
|
const subject = 'به کنینا خوش آمدید';
|
||||||
|
const text = `سلام ${name}،\n\nثبتنام شما در فروشگاه کنینا با موفقیت انجام شد.\n\ncanina.ir`;
|
||||||
|
const html = renderCaninaEmailLayout({
|
||||||
|
title: subject,
|
||||||
|
bodyHtml: `<p style="margin:0 0 12px;">سلام ${escapeHtml(name)}،</p><p style="margin:0;">ثبتنام شما در فروشگاه کنینا با موفقیت انجام شد. از این به بعد میتوانید سفارشها و وضعیت حساب خود را از سایت پیگیری کنید.</p>`,
|
||||||
|
});
|
||||||
|
await this.sendSafe(to, subject, text, html);
|
||||||
|
}
|
||||||
|
|
||||||
|
async sendOrderCreated(to: string | null | undefined, order: { id?: string; trackingNumber?: string | null; totalAmount?: number | string | { toString(): string } | null }) {
|
||||||
|
if (!to) return;
|
||||||
|
const orderRef = escapeHtml(String(order.trackingNumber || order.id || ''));
|
||||||
|
const amount = Number(order.totalAmount || 0);
|
||||||
|
const subject = 'سفارش شما در کنینا ثبت شد';
|
||||||
|
const text = `سفارش شما ثبت شد.\nشماره/کد: ${order.trackingNumber || order.id || ''}\nمبلغ: ${amount.toLocaleString('fa-IR')} تومان`;
|
||||||
|
const html = renderCaninaEmailLayout({
|
||||||
|
title: subject,
|
||||||
|
bodyHtml: `<p style="margin:0 0 12px;">سفارش شما ثبت شد.</p><p style="margin:0 0 8px;">شناسه/کد پیگیری: <b dir="ltr">${orderRef}</b></p><p style="margin:0;">مبلغ سفارش: <b>${escapeHtml(amount.toLocaleString('fa-IR'))}</b> تومان</p><p style="margin:16px 0 0;font-size:13px;color:#7A9B9F;">این پیام بهتنهایی بهمعنای تأیید پرداخت نیست؛ وضعیت پرداخت را در حساب کاربری بررسی کنید.</p>`,
|
||||||
|
});
|
||||||
|
await this.sendSafe(to, subject, text, html);
|
||||||
|
}
|
||||||
|
|
||||||
|
async sendOrderPaid(to: string | null | undefined, order: { id?: string; trackingNumber?: string | null; totalAmount?: number | string | { toString(): string } | null }) {
|
||||||
|
if (!to) return;
|
||||||
|
const orderRef = escapeHtml(String(order.trackingNumber || order.id || ''));
|
||||||
|
const amount = Number(order.totalAmount || 0);
|
||||||
|
const subject = 'پرداخت سفارش کنینا تأیید شد';
|
||||||
|
const text = `پرداخت سفارش تأیید شد.\nشماره/کد: ${order.trackingNumber || order.id || ''}\nمبلغ: ${amount.toLocaleString('fa-IR')} تومان`;
|
||||||
|
const html = renderCaninaEmailLayout({
|
||||||
|
title: subject,
|
||||||
|
bodyHtml: `<p style="margin:0 0 12px;">پرداخت سفارش شما با موفقیت تأیید شد.</p><p style="margin:0 0 8px;">شناسه/کد پیگیری: <b dir="ltr">${orderRef}</b></p><p style="margin:0;">مبلغ پرداختشده: <b>${escapeHtml(amount.toLocaleString('fa-IR'))}</b> تومان</p>`,
|
||||||
|
});
|
||||||
|
await this.sendSafe(to, subject, text, html);
|
||||||
|
}
|
||||||
|
|
||||||
|
async sendOrderShipped(
|
||||||
|
to: string | null | undefined,
|
||||||
|
order: { id?: string; trackingNumber?: string | null },
|
||||||
|
trackingCode?: string,
|
||||||
|
) {
|
||||||
|
if (!to) return;
|
||||||
|
const track = escapeHtml(String(trackingCode || order.trackingNumber || 'ارسال با پیک شهری'));
|
||||||
|
const orderRef = escapeHtml(String(order.trackingNumber || order.id || ''));
|
||||||
|
const subject = 'سفارش کنینا ارسال شد';
|
||||||
|
const text = `سفارش شما ارسال شد.\nسفارش: ${order.trackingNumber || order.id || ''}\nرهگیری: ${trackingCode || order.trackingNumber || 'ارسال با پیک شهری'}`;
|
||||||
|
const html = renderCaninaEmailLayout({
|
||||||
|
title: subject,
|
||||||
|
bodyHtml: `<p style="margin:0 0 12px;">وضعیت سفارش به ارسالشده تغییر کرد.</p><p style="margin:0 0 8px;">سفارش: <b dir="ltr">${orderRef}</b></p><p style="margin:0;">کد/روش ارسال: <b dir="ltr">${track}</b></p>`,
|
||||||
|
});
|
||||||
|
await this.sendSafe(to, subject, text, html);
|
||||||
|
}
|
||||||
|
|
||||||
|
async sendContactConfirmation(to: string | null | undefined, name: string, message: string, submissionId?: string) {
|
||||||
|
if (!to) return;
|
||||||
|
const subject = 'پیام شما در کنینا ثبت شد';
|
||||||
|
const text = `سلام ${name}،\n\nپیام شما ثبت شد و بهزودی بررسی میشود.\nشناسه: ${submissionId || ''}\n\n${message}`;
|
||||||
|
const html = renderCaninaEmailLayout({
|
||||||
|
title: subject,
|
||||||
|
bodyHtml: `<p style="margin:0 0 12px;">سلام ${escapeHtml(name)}،</p><p style="margin:0 0 16px;">پیام شما از طریق فرم تماس کنینا ثبت شد و بهزودی بررسی میشود.</p><div style="padding:14px;background:#F4F7F6;border:1px solid #E5ECE9;border-right:3px solid #F1B646;"><p style="margin:0;white-space:pre-wrap;">${textToHtmlParagraphs(message || '')}</p></div>${submissionId ? `<p style="margin:16px 0 0;font-size:13px;color:#7A9B9F;">شناسه پیگیری: <span dir="ltr">#${escapeHtml(submissionId)}</span></p>` : ''}`,
|
||||||
|
});
|
||||||
|
await this.sendSafe(to, subject, text, html);
|
||||||
|
}
|
||||||
|
|
||||||
|
async notifyAdminsAboutContact(dto: {
|
||||||
|
name: string;
|
||||||
|
phone: string;
|
||||||
|
email?: string;
|
||||||
|
subject?: string;
|
||||||
|
message: string;
|
||||||
|
submissionId?: string;
|
||||||
|
}) {
|
||||||
|
const subject = `پیام جدید فرم تماس کنینا${dto.subject ? ` — ${dto.subject}` : ''}`;
|
||||||
|
const text = `نام: ${dto.name}\nتلفن: ${dto.phone}\nایمیل: ${dto.email || '-'}\nموضوع: ${dto.subject || '-'}\nشناسه: ${dto.submissionId || '-'}\n\n${dto.message}`;
|
||||||
|
const html = renderCaninaEmailLayout({
|
||||||
|
title: 'پیام جدید از فرم تماس',
|
||||||
|
bodyHtml: `<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="border-collapse:collapse;">
|
||||||
|
<tr><td style="padding:10px 12px;background:#F4F7F6;border:1px solid #E5ECE9;width:110px;">نام</td><td style="padding:10px 12px;border:1px solid #E5ECE9;">${escapeHtml(dto.name)}</td></tr>
|
||||||
|
<tr><td style="padding:10px 12px;background:#F4F7F6;border:1px solid #E5ECE9;">تلفن</td><td style="padding:10px 12px;border:1px solid #E5ECE9;" dir="ltr">${escapeHtml(dto.phone)}</td></tr>
|
||||||
|
<tr><td style="padding:10px 12px;background:#F4F7F6;border:1px solid #E5ECE9;">ایمیل</td><td style="padding:10px 12px;border:1px solid #E5ECE9;" dir="ltr">${escapeHtml(dto.email || '-')}</td></tr>
|
||||||
|
<tr><td style="padding:10px 12px;background:#F4F7F6;border:1px solid #E5ECE9;vertical-align:top;">پیام</td><td style="padding:10px 12px;border:1px solid #E5ECE9;white-space:pre-wrap;">${textToHtmlParagraphs(dto.message || '')}</td></tr>
|
||||||
|
</table>`,
|
||||||
|
});
|
||||||
|
await Promise.all(
|
||||||
|
ADMIN_NOTIFY_TO.map((to) => this.sendSafe(to, subject, text, html)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,10 +1,11 @@
|
|||||||
import { Module } from "@nestjs/common";
|
import { Module } from "@nestjs/common";
|
||||||
import { OrdersService } from "./orders.service";
|
import { OrdersService } from "./orders.service";
|
||||||
import { OrdersController } from "./orders.controller";
|
import { OrdersController } from "./orders.controller";
|
||||||
|
import { NotificationsModule } from "../notifications/notifications.module";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
|
imports: [NotificationsModule],
|
||||||
controllers: [OrdersController],
|
controllers: [OrdersController],
|
||||||
providers: [OrdersService],
|
providers: [OrdersService],
|
||||||
exports: [OrdersService],
|
|
||||||
})
|
})
|
||||||
export class OrdersModule {}
|
export class OrdersModule {}
|
||||||
@@ -2,6 +2,7 @@ import { Test, TestingModule } from "@nestjs/testing";
|
|||||||
import { OrdersService } from "./orders.service";
|
import { OrdersService } from "./orders.service";
|
||||||
import { PrismaService } from "../prisma/prisma.service";
|
import { PrismaService } from "../prisma/prisma.service";
|
||||||
import { SmsService } from "../common/services/sms.service";
|
import { SmsService } from "../common/services/sms.service";
|
||||||
|
import { TransactionalEmailsService } from "../notifications/transactional-emails.service";
|
||||||
import { NotFoundException, BadRequestException } from "@nestjs/common";
|
import { NotFoundException, BadRequestException } from "@nestjs/common";
|
||||||
import { Prisma } from "@prisma/client";
|
import { Prisma } from "@prisma/client";
|
||||||
|
|
||||||
@@ -39,7 +40,7 @@ describe("OrdersService", () => {
|
|||||||
uiText: {
|
uiText: {
|
||||||
findFirst: jest.fn().mockResolvedValue(null),
|
findFirst: jest.fn().mockResolvedValue(null),
|
||||||
},
|
},
|
||||||
$executeRaw: jest.fn().mockResolvedValue(1),
|
$executeRaw: jest.fn(),
|
||||||
$transaction: jest.fn(),
|
$transaction: jest.fn(),
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -58,6 +59,7 @@ describe("OrdersService", () => {
|
|||||||
OrdersService,
|
OrdersService,
|
||||||
{ provide: PrismaService, useValue: mockPrisma },
|
{ provide: PrismaService, useValue: mockPrisma },
|
||||||
{ provide: SmsService, useValue: mockSmsService },
|
{ provide: SmsService, useValue: mockSmsService },
|
||||||
|
{ provide: TransactionalEmailsService, useValue: { sendWelcome: jest.fn().mockResolvedValue(undefined), sendOrderCreated: jest.fn().mockResolvedValue(undefined), sendOrderPaid: jest.fn().mockResolvedValue(undefined), sendOrderShipped: jest.fn().mockResolvedValue(undefined), sendContactConfirmation: jest.fn().mockResolvedValue(undefined), notifyAdminsAboutContact: jest.fn().mockResolvedValue(undefined) } },
|
||||||
],
|
],
|
||||||
}).compile();
|
}).compile();
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import { PrismaService } from "../prisma/prisma.service";
|
|||||||
import { PaginationDto } from "../common/dto/pagination.dto";
|
import { PaginationDto } from "../common/dto/pagination.dto";
|
||||||
import { CreateOrderDto } from "./dto/create-order.dto";
|
import { CreateOrderDto } from "./dto/create-order.dto";
|
||||||
import { SmsService } from "../common/services/sms.service";
|
import { SmsService } from "../common/services/sms.service";
|
||||||
|
import { TransactionalEmailsService } from "../notifications/transactional-emails.service";
|
||||||
import { Prisma } from "@prisma/client";
|
import { Prisma } from "@prisma/client";
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
@@ -17,6 +18,7 @@ export class OrdersService {
|
|||||||
constructor(
|
constructor(
|
||||||
private prisma: PrismaService,
|
private prisma: PrismaService,
|
||||||
private smsService: SmsService,
|
private smsService: SmsService,
|
||||||
|
private transactionalEmails: TransactionalEmailsService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
private generateTrackingNumber(): string {
|
private generateTrackingNumber(): string {
|
||||||
@@ -303,6 +305,9 @@ export class OrdersService {
|
|||||||
this.logger.warn(`Failed to trigger wallet order SMS: ${err}`);
|
this.logger.warn(`Failed to trigger wallet order SMS: ${err}`);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
this.transactionalEmails
|
||||||
|
.sendOrderPaid(user.email, createdWalletOrder)
|
||||||
|
.catch(() => {});
|
||||||
|
|
||||||
return createdWalletOrder;
|
return createdWalletOrder;
|
||||||
}
|
}
|
||||||
@@ -346,14 +351,13 @@ export class OrdersService {
|
|||||||
// Deduct inventory immediately for non-online orders (card to card)
|
// Deduct inventory immediately for non-online orders (card to card)
|
||||||
if (!isOnline) {
|
if (!isOnline) {
|
||||||
for (const item of createOrderDto.items) {
|
for (const item of createOrderDto.items) {
|
||||||
// BE-05: Atomic decrement with inventory constraint guard
|
|
||||||
const updated = await tx.product.update({
|
const updated = await tx.product.update({
|
||||||
where: { id: item.productId },
|
where: { id: item.productId },
|
||||||
data: {
|
data: {
|
||||||
stock: { decrement: item.quantity },
|
stock: { decrement: item.quantity },
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
if (updated && updated.stock <= 0) {
|
if (updated.stock <= 0) {
|
||||||
await tx.product.update({
|
await tx.product.update({
|
||||||
where: { id: item.productId },
|
where: { id: item.productId },
|
||||||
data: { stockStatus: "OUT_OF_STOCK" },
|
data: { stockStatus: "OUT_OF_STOCK" },
|
||||||
@@ -376,6 +380,11 @@ export class OrdersService {
|
|||||||
.triggerEvent("ORDER_CREATED", orderData)
|
.triggerEvent("ORDER_CREATED", orderData)
|
||||||
.catch(() => {});
|
.catch(() => {});
|
||||||
}
|
}
|
||||||
|
if (user?.email) {
|
||||||
|
this.transactionalEmails
|
||||||
|
.sendOrderCreated(user.email, createdOrder)
|
||||||
|
.catch(() => {});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return createdOrder;
|
return createdOrder;
|
||||||
@@ -530,6 +539,9 @@ export class OrdersService {
|
|||||||
: "پیک شهری";
|
: "پیک شهری";
|
||||||
|
|
||||||
this.smsService.triggerEvent("ORDER_SHIPPED", orderData).catch(() => {});
|
this.smsService.triggerEvent("ORDER_SHIPPED", orderData).catch(() => {});
|
||||||
|
this.transactionalEmails
|
||||||
|
.sendOrderShipped(updatedOrder.user?.email, updatedOrder, finalTracking)
|
||||||
|
.catch(() => {});
|
||||||
}
|
}
|
||||||
|
|
||||||
return updatedOrder;
|
return updatedOrder;
|
||||||
@@ -708,6 +720,9 @@ export class OrdersService {
|
|||||||
.triggerEvent("ORDER_PAID", orderData)
|
.triggerEvent("ORDER_PAID", orderData)
|
||||||
.catch(() => {});
|
.catch(() => {});
|
||||||
}
|
}
|
||||||
|
this.transactionalEmails
|
||||||
|
.sendOrderPaid(user.email, order)
|
||||||
|
.catch(() => {});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { Module } from "@nestjs/common";
|
import { Module } from "@nestjs/common";
|
||||||
|
import { NotificationsModule } from "../notifications/notifications.module";
|
||||||
import { PaymentController } from "./payment.controller";
|
import { PaymentController } from "./payment.controller";
|
||||||
import { PaymentService } from "./payment.service";
|
import { PaymentService } from "./payment.service";
|
||||||
import { ZibalService } from "./zibal.service";
|
import { ZibalService } from "./zibal.service";
|
||||||
@@ -7,7 +8,7 @@ import { PrismaModule } from "../prisma/prisma.module";
|
|||||||
import { SmsModule } from "../common/sms.module";
|
import { SmsModule } from "../common/sms.module";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [PrismaModule, SmsModule],
|
imports: [NotificationsModule, PrismaModule, SmsModule],
|
||||||
controllers: [PaymentController],
|
controllers: [PaymentController],
|
||||||
providers: [PaymentService, ZibalService, ZibalEBankService],
|
providers: [PaymentService, ZibalService, ZibalEBankService],
|
||||||
exports: [PaymentService, ZibalService, ZibalEBankService],
|
exports: [PaymentService, ZibalService, ZibalEBankService],
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { PaymentService } from "./payment.service";
|
|||||||
import { PrismaService } from "../prisma/prisma.service";
|
import { PrismaService } from "../prisma/prisma.service";
|
||||||
import { ZibalService } from "./zibal.service";
|
import { ZibalService } from "./zibal.service";
|
||||||
import { SmsService } from "../common/services/sms.service";
|
import { SmsService } from "../common/services/sms.service";
|
||||||
|
import { TransactionalEmailsService } from "../notifications/transactional-emails.service";
|
||||||
import { BadRequestException, NotFoundException } from "@nestjs/common";
|
import { BadRequestException, NotFoundException } from "@nestjs/common";
|
||||||
import { Prisma } from "@prisma/client";
|
import { Prisma } from "@prisma/client";
|
||||||
|
|
||||||
@@ -72,6 +73,7 @@ describe("PaymentService", () => {
|
|||||||
{ provide: PrismaService, useValue: mockPrisma },
|
{ provide: PrismaService, useValue: mockPrisma },
|
||||||
{ provide: ZibalService, useValue: mockZibalService },
|
{ provide: ZibalService, useValue: mockZibalService },
|
||||||
{ provide: SmsService, useValue: mockSmsService },
|
{ provide: SmsService, useValue: mockSmsService },
|
||||||
|
{ provide: TransactionalEmailsService, useValue: { sendWelcome: jest.fn().mockResolvedValue(undefined), sendOrderCreated: jest.fn().mockResolvedValue(undefined), sendOrderPaid: jest.fn().mockResolvedValue(undefined), sendOrderShipped: jest.fn().mockResolvedValue(undefined), sendContactConfirmation: jest.fn().mockResolvedValue(undefined), notifyAdminsAboutContact: jest.fn().mockResolvedValue(undefined) } },
|
||||||
],
|
],
|
||||||
}).compile();
|
}).compile();
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import {
|
|||||||
import { PrismaService } from "../prisma/prisma.service";
|
import { PrismaService } from "../prisma/prisma.service";
|
||||||
import { ZibalService } from "./zibal.service";
|
import { ZibalService } from "./zibal.service";
|
||||||
import { SmsService } from "../common/services/sms.service";
|
import { SmsService } from "../common/services/sms.service";
|
||||||
|
import { TransactionalEmailsService } from "../notifications/transactional-emails.service";
|
||||||
import { Prisma } from "@prisma/client";
|
import { Prisma } from "@prisma/client";
|
||||||
import { AdminTransactionFilterDto } from "./dto/admin-transaction-filter.dto";
|
import { AdminTransactionFilterDto } from "./dto/admin-transaction-filter.dto";
|
||||||
|
|
||||||
@@ -24,6 +25,7 @@ export class PaymentService {
|
|||||||
private readonly prisma: PrismaService,
|
private readonly prisma: PrismaService,
|
||||||
private readonly zibalService: ZibalService,
|
private readonly zibalService: ZibalService,
|
||||||
private readonly smsService: SmsService,
|
private readonly smsService: SmsService,
|
||||||
|
private readonly transactionalEmails: TransactionalEmailsService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -447,32 +449,17 @@ export class PaymentService {
|
|||||||
if (orderWithItems?.orderItems) {
|
if (orderWithItems?.orderItems) {
|
||||||
for (const item of orderWithItems.orderItems) {
|
for (const item of orderWithItems.orderItems) {
|
||||||
if (item.productId) {
|
if (item.productId) {
|
||||||
// BE-05: Atomic decrement with inventory constraint guard
|
const updated = await tx.product.update({
|
||||||
let updateCount = 1;
|
where: { id: item.productId },
|
||||||
if (typeof (tx as any).$executeRaw === 'function') {
|
data: {
|
||||||
updateCount = await tx.$executeRaw`
|
stock: { decrement: item.quantity },
|
||||||
UPDATE products
|
},
|
||||||
SET stock = stock - ${item.quantity},
|
});
|
||||||
stock_status = CASE WHEN stock - ${item.quantity} <= 0 THEN 'OUT_OF_STOCK'::"StockStatus" ELSE stock_status END
|
if (updated.stock <= 0) {
|
||||||
WHERE id = ${item.productId}::uuid AND stock >= ${item.quantity}
|
await tx.product.update({
|
||||||
`;
|
|
||||||
} else {
|
|
||||||
const updated = await tx.product.update({
|
|
||||||
where: { id: item.productId },
|
where: { id: item.productId },
|
||||||
data: { stock: { decrement: item.quantity } },
|
data: { stockStatus: "OUT_OF_STOCK" },
|
||||||
});
|
});
|
||||||
if (updated.stock <= 0) {
|
|
||||||
await tx.product.update({
|
|
||||||
where: { id: item.productId },
|
|
||||||
data: { stockStatus: "OUT_OF_STOCK" },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (updateCount === 0) {
|
|
||||||
this.logger.error(
|
|
||||||
`[CriticalInventoryAlert] Product ${item.productId} lacked sufficient stock for paid order ${transaction.orderId} (requested ${item.quantity}). Manual inventory check required.`
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -656,6 +643,16 @@ export class PaymentService {
|
|||||||
this.smsService.triggerEvent("ORDER_PAID", orderData).catch((err) => {
|
this.smsService.triggerEvent("ORDER_PAID", orderData).catch((err) => {
|
||||||
this.logger.warn(`Could not trigger SMS event ORDER_PAID: ${err}`);
|
this.logger.warn(`Could not trigger SMS event ORDER_PAID: ${err}`);
|
||||||
});
|
});
|
||||||
|
const emailTo =
|
||||||
|
transaction.user?.email ||
|
||||||
|
order?.user?.email ||
|
||||||
|
null;
|
||||||
|
const orderForEmail = order || transaction.order;
|
||||||
|
if (emailTo && orderForEmail) {
|
||||||
|
this.transactionalEmails
|
||||||
|
.sendOrderPaid(emailTo, orderForEmail)
|
||||||
|
.catch(() => {});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Send SMS notification if wallet top-up
|
// Send SMS notification if wallet top-up
|
||||||
|
|||||||
@@ -1,39 +1,13 @@
|
|||||||
import { Injectable, OnModuleInit, OnModuleDestroy } from "@nestjs/common";
|
import { Injectable, OnModuleInit, OnModuleDestroy } from "@nestjs/common";
|
||||||
import { PrismaClient } from "@prisma/client";
|
import { PrismaClient } from "@prisma/client";
|
||||||
|
|
||||||
import { Logger } from "@nestjs/common";
|
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class PrismaService
|
export class PrismaService
|
||||||
extends PrismaClient
|
extends PrismaClient
|
||||||
implements OnModuleInit, OnModuleDestroy
|
implements OnModuleInit, OnModuleDestroy
|
||||||
{
|
{
|
||||||
private readonly logger = new Logger(PrismaService.name);
|
|
||||||
|
|
||||||
constructor() {
|
|
||||||
super({
|
|
||||||
log: [
|
|
||||||
{ emit: "event", level: "query" },
|
|
||||||
{ emit: "stdout", level: "error" },
|
|
||||||
{ emit: "stdout", level: "warn" },
|
|
||||||
],
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async onModuleInit() {
|
async onModuleInit() {
|
||||||
await this.$connect();
|
await this.$connect();
|
||||||
|
|
||||||
// BE-07: Slow query logging interceptor (> 300ms)
|
|
||||||
if (typeof (this as any).$on === "function") {
|
|
||||||
(this as any).$on("query", (e: any) => {
|
|
||||||
if (e.duration >= 300) {
|
|
||||||
this.logger.warn(
|
|
||||||
`[SlowQueryAlert] Duration: ${e.duration}ms | Target: ${e.target} | Query: ${e.query.substring(0, 300)}...`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.ensureTablesExist();
|
await this.ensureTablesExist();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -14,9 +14,6 @@ describe("ProductsService", () => {
|
|||||||
findFirst: jest.fn(),
|
findFirst: jest.fn(),
|
||||||
count: jest.fn(),
|
count: jest.fn(),
|
||||||
},
|
},
|
||||||
orderItem: {
|
|
||||||
groupBy: jest.fn().mockResolvedValue([]),
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const mockRevalidationService = {
|
const mockRevalidationService = {
|
||||||
|
|||||||
@@ -3,11 +3,6 @@ import { PrismaService } from "../prisma/prisma.service";
|
|||||||
import { GetProductsDto } from "./dto/get-products.dto";
|
import { GetProductsDto } from "./dto/get-products.dto";
|
||||||
import { Prisma } from "@prisma/client";
|
import { Prisma } from "@prisma/client";
|
||||||
import { RevalidationService } from "../common/revalidation/revalidation.service";
|
import { RevalidationService } from "../common/revalidation/revalidation.service";
|
||||||
import {
|
|
||||||
createPaginationMeta,
|
|
||||||
extractSearchTokens,
|
|
||||||
calculateRelevanceScore,
|
|
||||||
} from "../common/utils/search.utils";
|
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class ProductsService {
|
export class ProductsService {
|
||||||
@@ -67,117 +62,49 @@ export class ProductsService {
|
|||||||
andConditions.push({ priceValue: { lte: Number(maxPrice) } });
|
andConditions.push({ priceValue: { lte: Number(maxPrice) } });
|
||||||
}
|
}
|
||||||
|
|
||||||
const tokens = extractSearchTokens(search);
|
if (search) {
|
||||||
if (tokens.length > 0) {
|
andConditions.push({
|
||||||
const mode = "insensitive" as const;
|
OR: [
|
||||||
const searchConditions: Prisma.ProductWhereInput[] = [
|
{ artNo: { contains: search, mode: "insensitive" } },
|
||||||
{ artNo: { contains: search, mode } },
|
{ barcode: { contains: search, mode: "insensitive" } },
|
||||||
{ barcode: { contains: search, mode } },
|
{ nameFa: { contains: search, mode: "insensitive" } },
|
||||||
{ slug: { contains: search, mode } },
|
{ nameEn: { contains: search, mode: "insensitive" } },
|
||||||
{ nameFa: { contains: search, mode } },
|
{ description: { contains: search, mode: "insensitive" } },
|
||||||
{ nameEn: { contains: search, mode } },
|
{ shortDescription: { contains: search, mode: "insensitive" } },
|
||||||
{ shortDescription: { contains: search, mode } },
|
|
||||||
];
|
|
||||||
|
|
||||||
for (const token of tokens) {
|
|
||||||
searchConditions.push(
|
|
||||||
{ nameFa: { contains: token, mode } },
|
|
||||||
{ nameEn: { contains: token, mode } },
|
|
||||||
{
|
|
||||||
ingredientList: {
|
|
||||||
some: {
|
|
||||||
OR: [
|
|
||||||
{ ingredient: { contains: token, mode } },
|
|
||||||
{ ingredientCardSlug: { contains: token, mode } },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
symptoms: {
|
symptoms: {
|
||||||
some: {
|
some: {
|
||||||
symptom: { contains: token, mode },
|
symptom: { contains: search, mode: "insensitive" },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
);
|
],
|
||||||
}
|
|
||||||
|
|
||||||
andConditions.push({
|
|
||||||
OR: searchConditions,
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const whereClause: Prisma.ProductWhereInput =
|
const whereClause: Prisma.ProductWhereInput =
|
||||||
andConditions.length > 0 ? { AND: andConditions } : {};
|
andConditions.length > 0 ? { AND: andConditions } : {};
|
||||||
|
|
||||||
const safePage = Math.max(1, Number(page) || 1);
|
const skip = (page - 1) * limit;
|
||||||
const safeLimit = Math.max(1, Number(limit) || 50);
|
|
||||||
const skip = (safePage - 1) * safeLimit;
|
|
||||||
|
|
||||||
// 1. Fetch products with lean relations
|
|
||||||
const [rawProducts, total] = await Promise.all([
|
const [rawProducts, total] = await Promise.all([
|
||||||
this.prisma.product.findMany({
|
this.prisma.product.findMany({
|
||||||
where: whereClause,
|
where: whereClause,
|
||||||
skip: tokens.length > 0 ? undefined : skip,
|
skip,
|
||||||
take: tokens.length > 0 ? 100 : safeLimit,
|
take: limit,
|
||||||
orderBy: { [sortBy]: sortOrder },
|
orderBy: { [sortBy]: sortOrder },
|
||||||
include: {
|
include: {
|
||||||
ingredientList: true,
|
ingredientList: true,
|
||||||
symptoms: true,
|
symptoms: true,
|
||||||
|
orderItems: {
|
||||||
|
where: { order: { status: { not: "CANCELLED" } } },
|
||||||
|
select: { quantity: true },
|
||||||
|
},
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
this.prisma.product.count({ where: whereClause }),
|
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 = candidateProducts.map((p) => p.id);
|
|
||||||
let salesMap: Record<string, number> = {};
|
|
||||||
|
|
||||||
if (productIds.length > 0) {
|
|
||||||
const salesAgg = await this.prisma.orderItem.groupBy({
|
|
||||||
by: ['productId'],
|
|
||||||
_sum: { quantity: true },
|
|
||||||
where: {
|
|
||||||
productId: { in: productIds },
|
|
||||||
order: { status: { not: 'CANCELLED' } },
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
salesMap = salesAgg.reduce((acc, row) => {
|
|
||||||
if (row.productId) {
|
|
||||||
acc[row.productId] = Number(row._sum.quantity) || 0;
|
|
||||||
}
|
|
||||||
return acc;
|
|
||||||
}, {} as Record<string, number>);
|
|
||||||
}
|
|
||||||
|
|
||||||
const isWholesaleOrAdmin =
|
const isWholesaleOrAdmin =
|
||||||
userRole === "User_Wholesale" ||
|
userRole === "User_Wholesale" ||
|
||||||
userRole === "User_Partner" ||
|
userRole === "User_Partner" ||
|
||||||
@@ -185,9 +112,13 @@ export class ProductsService {
|
|||||||
userRole === "SuperAdmin";
|
userRole === "SuperAdmin";
|
||||||
const isAdmin = userRole === "ADMIN" || userRole === "SuperAdmin";
|
const isAdmin = userRole === "ADMIN" || userRole === "SuperAdmin";
|
||||||
|
|
||||||
const data = candidateProducts.map((p) => {
|
const data = rawProducts.map((p) => {
|
||||||
const totalSold = salesMap[p.id] || 0;
|
const totalSold =
|
||||||
const { buyPrice, wholesalePrice, ...publicProduct } = p;
|
p.orderItems?.reduce(
|
||||||
|
(acc, item) => acc + (Number(item.quantity) || 0),
|
||||||
|
0,
|
||||||
|
) || 0;
|
||||||
|
const { buyPrice, wholesalePrice, orderItems, ...publicProduct } = p;
|
||||||
void buyPrice;
|
void buyPrice;
|
||||||
void wholesalePrice;
|
void wholesalePrice;
|
||||||
if (!isWholesaleOrAdmin) {
|
if (!isWholesaleOrAdmin) {
|
||||||
@@ -200,7 +131,12 @@ export class ProductsService {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
data,
|
data,
|
||||||
meta: createPaginationMeta(total, safePage, safeLimit),
|
meta: {
|
||||||
|
total,
|
||||||
|
page,
|
||||||
|
lastPage: Math.ceil(total / limit) || 1,
|
||||||
|
limit,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -45,20 +45,4 @@ export class RedisService implements OnModuleInit, OnModuleDestroy {
|
|||||||
async ttl(key: string): Promise<number> {
|
async ttl(key: string): Promise<number> {
|
||||||
return this.client.ttl(key);
|
return this.client.ttl(key);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Acquire a distributed lock using Redis SET NX EX
|
|
||||||
* Returns true if lock acquired, false otherwise
|
|
||||||
*/
|
|
||||||
async acquireLock(key: string, ttlSeconds: number = 60): Promise<boolean> {
|
|
||||||
const res = await this.client.set(`lock:${key}`, "1", "EX", ttlSeconds, "NX");
|
|
||||||
return res === "OK";
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Release a distributed lock
|
|
||||||
*/
|
|
||||||
async releaseLock(key: string): Promise<void> {
|
|
||||||
await this.client.del(`lock:${key}`);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -94,26 +94,4 @@ describe("SettingsService", () => {
|
|||||||
});
|
});
|
||||||
expect(result.key).toBe("k");
|
expect(result.key).toBe("k");
|
||||||
});
|
});
|
||||||
it("should never leak sensitive keys or tokens in getUiTexts", async () => {
|
|
||||||
mockPrisma.uiText.findMany.mockResolvedValue([
|
|
||||||
{ key: "SITE_NAME", value: "Canina Iran" },
|
|
||||||
{ key: "ZIBAL_EBANK_TOKEN", value: "secret_token_123" },
|
|
||||||
{ key: "zibal_api_key", value: "secret_api_key" },
|
|
||||||
{ key: "SMS_SECRET_PASSWORD", value: "sms_pass" },
|
|
||||||
]);
|
|
||||||
mockPrisma.setting.findMany.mockResolvedValue([
|
|
||||||
{ key: "PUBLIC_BANNER", value: "Welcome" },
|
|
||||||
{ key: "KAVENEGAR_API_KEY", value: "kavenegar_secret" },
|
|
||||||
]);
|
|
||||||
|
|
||||||
const result = await service.getUiTexts();
|
|
||||||
const returnedKeys = result.map((r) => r.key);
|
|
||||||
|
|
||||||
expect(returnedKeys).toContain("SITE_NAME");
|
|
||||||
expect(returnedKeys).toContain("PUBLIC_BANNER");
|
|
||||||
expect(returnedKeys).not.toContain("ZIBAL_EBANK_TOKEN");
|
|
||||||
expect(returnedKeys).not.toContain("zibal_api_key");
|
|
||||||
expect(returnedKeys).not.toContain("SMS_SECRET_PASSWORD");
|
|
||||||
expect(returnedKeys).not.toContain("KAVENEGAR_API_KEY");
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
@@ -269,27 +269,10 @@ export class SettingsService implements OnModuleInit {
|
|||||||
mergedMap.set("b2b_enabled", val);
|
mergedMap.set("b2b_enabled", val);
|
||||||
}
|
}
|
||||||
|
|
||||||
const SENSITIVE_KEY_PATTERNS = [
|
return Array.from(mergedMap.entries()).map(([key, value]) => ({
|
||||||
/token/i,
|
key,
|
||||||
/secret/i,
|
value,
|
||||||
/password/i,
|
}));
|
||||||
/api_key/i,
|
|
||||||
/apikey/i,
|
|
||||||
/private/i,
|
|
||||||
/zibal/i,
|
|
||||||
/kavenegar/i,
|
|
||||||
/ghasedak/i,
|
|
||||||
/credential/i,
|
|
||||||
/account_id/i,
|
|
||||||
/access_key/i,
|
|
||||||
];
|
|
||||||
|
|
||||||
return Array.from(mergedMap.entries())
|
|
||||||
.filter(([key]) => !SENSITIVE_KEY_PATTERNS.some((pattern) => pattern.test(key)))
|
|
||||||
.map(([key, value]) => ({
|
|
||||||
key,
|
|
||||||
value,
|
|
||||||
}));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async updateUiText(key: string, value: string) {
|
async updateUiText(key: string, value: string) {
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ class TestJwt extends PassportStrategy(Strategy) {
|
|||||||
const selected = { enabled:true, provider:'configured-1234567890abcdef', model:'real-model', label:'پشتیبان تست', icon:'paw' };
|
const selected = { enabled:true, provider:'configured-1234567890abcdef', model:'real-model', label:'پشتیبان تست', icon:'paw' };
|
||||||
describe('smart chat settings', () => {
|
describe('smart chat settings', () => {
|
||||||
let stored:any = null;
|
let stored:any = null;
|
||||||
const prisma:any = { setting:{ findUnique:jest.fn(async()=>stored), upsert:jest.fn(async(q:any)=>{stored={value:q.create.value};return stored;}) }, product:{findMany:jest.fn(async()=>[])}, user:{findUnique:jest.fn()}, order:{findMany:jest.fn()}, supportConversation:{create:jest.fn(async(q:any)=>({id:q.data.id,messages:[]})),findUnique:jest.fn(async()=>null),update:jest.fn(async()=>({}))}, supportConversationMessage:{createMany:jest.fn(async()=>({count:2}))} };
|
const prisma:any = { setting:{ findUnique:jest.fn(async()=>stored), upsert:jest.fn(async(q:any)=>{stored={value:q.create.value};return stored;}) }, product:{findMany:jest.fn(async()=>[])}, user:{findUnique:jest.fn()}, order:{findMany:jest.fn()} };
|
||||||
let service:SupportChatSettingsService;
|
let service:SupportChatSettingsService;
|
||||||
beforeEach(()=>{stored=null;jest.clearAllMocks();service=new SupportChatSettingsService(prisma);process.env.SUPPORT_CHAT_URL='http://internal/ask';process.env.SUPPORT_CHAT_KEY='key';});
|
beforeEach(()=>{stored=null;jest.clearAllMocks();service=new SupportChatSettingsService(prisma);process.env.SUPPORT_CHAT_URL='http://internal/ask';process.env.SUPPORT_CHAT_KEY='key';});
|
||||||
afterEach(()=>jest.restoreAllMocks());
|
afterEach(()=>jest.restoreAllMocks());
|
||||||
|
|||||||
@@ -20,10 +20,7 @@ describe('support HTTP boundary', () => {
|
|||||||
beforeAll(async () => {
|
beforeAll(async () => {
|
||||||
process.env.JWT_ACCESS_SECRET = 'test-secret-with-at-least-32-characters';
|
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();
|
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 }));
|
app = mod.createNestApplication(); app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true })); await app.init();
|
||||||
// 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());
|
afterAll(() => app.close());
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
@@ -48,14 +45,7 @@ describe('support HTTP boundary', () => {
|
|||||||
});
|
});
|
||||||
it('scopes wallet to validated identity across concurrent callers', async () => {
|
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)));
|
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).toBe('موجودی کیف پول شما: 11 تومان.');
|
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[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('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); });
|
it.each(['', 'x'.repeat(1501)])('bounds message length', async message => { await request(app.getHttpServer()).post('/support-chat/ask').send({message}).expect(400); });
|
||||||
|
|||||||
@@ -5,9 +5,9 @@ describe('model intent routing', () => {
|
|||||||
let service: SupportChatService;
|
let service: SupportChatService;
|
||||||
beforeEach(()=>{jest.clearAllMocks();process.env.SUPPORT_CHAT_URL='http://internal/ask';process.env.SUPPORT_CHAT_KEY='test';service=new SupportChatService(prisma, { read: async () => ({ enabled: true, provider: 'p', model: 'm' }) } as any);});
|
beforeEach(()=>{jest.clearAllMocks();process.env.SUPPORT_CHAT_URL='http://internal/ask';process.env.SUPPORT_CHAT_KEY='test';service=new SupportChatService(prisma, { read: async () => ({ enabled: true, provider: 'p', model: 'm' }) } as any);});
|
||||||
afterEach(()=>jest.restoreAllMocks());
|
afterEach(()=>jest.restoreAllMocks());
|
||||||
function model(body:any) { return jest.spyOn(global,'fetch').mockImplementation(async(url)=>({ok:true,json:async()=>String(url).endsWith('/classify')?body:(body.answer?body:{answer:'پاسخ تست'})} as any)); }
|
function model(body:any) { return jest.spyOn(global,'fetch').mockResolvedValue({ok:true,json:async()=>body} as any); }
|
||||||
it('guest model wallet does not load private rows',async()=>{model({intent:'wallet'});expect((await service.ask({message:'cheghadr etebar daram'})).answer).toContain('وارد');expect(prisma.user.findUnique).not.toHaveBeenCalled();expect(prisma.order.findMany).not.toHaveBeenCalled();});
|
it('guest model wallet does not load private rows',async()=>{model({intent:'wallet'});expect((await service.ask({message:'cheghadr etebar daram'})).answer).toContain('وارد');expect(prisma.user.findUnique).not.toHaveBeenCalled();expect(prisma.order.findMany).not.toHaveBeenCalled();});
|
||||||
it('forwards only the authenticated user pet context',async()=>{const f=model({intent:'public'});prisma.pet={findMany:jest.fn().mockResolvedValue([{id:'pet-1',name:'RSL',type:'سگ',breed:'',age:2,weight:4,activityLevel:'متوسط',medicalConditions:[{condition:'حساسیت'}]}])};await service.ask({message:'جرم دندان RSL چیست؟'},{id:'alice'});const body=JSON.parse(f.mock.calls[0][1]!.body as string);expect(body.pet_context).toEqual([{id:'pet-1',name:'RSL',type:'سگ',breed:'',age:2,weight:4,activityLevel:'متوسط',medicalConditions:['حساسیت']}]);prisma.pet={findMany:jest.fn().mockResolvedValue([])};});
|
it('forwards only the authenticated user pet context',async()=>{const f=model({intent:'public'});prisma.pet={findMany:jest.fn().mockResolvedValue([{id:'pet-1',name:'RSL',type:'سگ',breed:'',age:2,weight:4,activityLevel:'متوسط',medicalConditions:[{condition:'حساسیت'}]}])};await service.ask({message:'جرم دندان RSL چیست؟'},{id:'alice'});const body=JSON.parse(f.mock.calls[0][1]!.body as string);expect(body.pet_context).toEqual([{id:'pet-1',name:'RSL',type:'سگ',breed:'',age:2,weight:4,activityLevel:'متوسط',medicalConditions:['حساسیت']}]);});
|
||||||
it('uses semantic model intent rather than message keywords',async()=>{const f=model({intent:'wallet'});expect((await service.ask({message:'چقدر اعتبار دارم؟'},{id:'alice'})).answer).toContain('17');expect(prisma.user.findUnique).toHaveBeenCalledWith({where:{id:'alice'},select:{walletBalance:true}});expect(JSON.parse(f.mock.calls[0][1]!.body as string)).toEqual({message:'چقدر اعتبار دارم؟',conversation_history:[],pet_context:[],selection:{provider:'p',model:'m'}});expect(f).toHaveBeenCalledTimes(1);});
|
it('uses semantic model intent rather than message keywords',async()=>{const f=model({intent:'wallet'});expect((await service.ask({message:'چقدر اعتبار دارم؟'},{id:'alice'})).answer).toContain('17');expect(prisma.user.findUnique).toHaveBeenCalledWith({where:{id:'alice'},select:{walletBalance:true}});expect(JSON.parse(f.mock.calls[0][1]!.body as string)).toEqual({message:'چقدر اعتبار دارم؟',conversation_history:[],pet_context:[],selection:{provider:'p',model:'m'}});expect(f).toHaveBeenCalledTimes(1);});
|
||||||
it.each([{intent:'admin'},{intent:'wallet',userId:'bob'},{answer:'orders'},{intent:null},{}])('fails closed on invalid classifier %j',async body=>{model(body);await expect(service.ask({message:'سلام'},{id:'alice'})).rejects.toThrow(UNAVAILABLE);expect(prisma.user.findUnique).not.toHaveBeenCalled();expect(prisma.order.findMany).not.toHaveBeenCalled();expect(prisma.product.findMany).not.toHaveBeenCalled();});
|
it.each([{intent:'admin'},{intent:'wallet',userId:'bob'},{answer:'orders'},{intent:null},{}])('fails closed on invalid classifier %j',async body=>{model(body);await expect(service.ask({message:'سلام'},{id:'alice'})).rejects.toThrow(UNAVAILABLE);expect(prisma.user.findUnique).not.toHaveBeenCalled();expect(prisma.order.findMany).not.toHaveBeenCalled();expect(prisma.product.findMany).not.toHaveBeenCalled();});
|
||||||
it('classifier outage does not fall back to keyword routing',async()=>{jest.spyOn(global,'fetch').mockRejectedValue(new Error('secret'));await expect(service.ask({message:'کیف پول'},{id:'alice'})).rejects.toThrow(UNAVAILABLE);expect(prisma.user.findUnique).not.toHaveBeenCalled();});
|
it('classifier outage does not fall back to keyword routing',async()=>{jest.spyOn(global,'fetch').mockRejectedValue(new Error('secret'));await expect(service.ask({message:'کیف پول'},{id:'alice'})).rejects.toThrow(UNAVAILABLE);expect(prisma.user.findUnique).not.toHaveBeenCalled();});
|
||||||
|
|||||||
@@ -2,11 +2,6 @@ import { Injectable, NotFoundException } from "@nestjs/common";
|
|||||||
import { Prisma } from "@prisma/client";
|
import { Prisma } from "@prisma/client";
|
||||||
import { PrismaService } from "../prisma/prisma.service";
|
import { PrismaService } from "../prisma/prisma.service";
|
||||||
import { PaginationDto } from "../common/dto/pagination.dto";
|
import { PaginationDto } from "../common/dto/pagination.dto";
|
||||||
import {
|
|
||||||
createPaginationMeta,
|
|
||||||
extractSearchTokens,
|
|
||||||
calculateRelevanceScore,
|
|
||||||
} from "../common/utils/search.utils";
|
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class WikiService {
|
export class WikiService {
|
||||||
@@ -24,57 +19,33 @@ export class WikiService {
|
|||||||
const sortBy = allowedSortFields.includes(rawSortBy) ? rawSortBy : "term";
|
const sortBy = allowedSortFields.includes(rawSortBy) ? rawSortBy : "term";
|
||||||
|
|
||||||
const whereClause: Prisma.ScientificTermWhereInput = {};
|
const whereClause: Prisma.ScientificTermWhereInput = {};
|
||||||
const tokens = extractSearchTokens(search);
|
if (search) {
|
||||||
if (tokens.length > 0) {
|
|
||||||
const mode = "insensitive" as const;
|
|
||||||
whereClause.OR = [
|
whereClause.OR = [
|
||||||
{ term: { contains: search, mode } },
|
{ term: { contains: search, mode: "insensitive" } },
|
||||||
{ key: { contains: search, mode } },
|
{ definition: { contains: search, mode: "insensitive" } },
|
||||||
{ definition: { contains: search, mode } },
|
|
||||||
...tokens.flatMap((token) => [
|
|
||||||
{ term: { contains: token, mode } },
|
|
||||||
{ key: { contains: token, mode } },
|
|
||||||
]),
|
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
const safePage = Math.max(1, Number(page) || 1);
|
const skip = (page - 1) * limit;
|
||||||
const safeLimit = Math.max(1, Number(limit) || 10);
|
|
||||||
const skip = (safePage - 1) * safeLimit;
|
|
||||||
|
|
||||||
const [rawTerms, total] = await Promise.all([
|
const [data, total] = await Promise.all([
|
||||||
this.prisma.scientificTerm.findMany({
|
this.prisma.scientificTerm.findMany({
|
||||||
where: whereClause,
|
where: whereClause,
|
||||||
skip: tokens.length > 0 ? undefined : skip,
|
skip,
|
||||||
take: tokens.length > 0 ? 100 : safeLimit,
|
take: limit,
|
||||||
orderBy: { [sortBy]: sortOrder },
|
orderBy: { [sortBy]: sortOrder },
|
||||||
}),
|
}),
|
||||||
this.prisma.scientificTerm.count({ where: whereClause }),
|
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 {
|
return {
|
||||||
data,
|
data,
|
||||||
meta: createPaginationMeta(total, safePage, safeLimit),
|
meta: {
|
||||||
|
total,
|
||||||
|
page,
|
||||||
|
lastPage: Math.ceil(total / limit),
|
||||||
|
limit,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Loaded 100 of 429 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user