Compare commits
335
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dc34c57a0c | ||
|
|
c97ea01ba9 | ||
|
|
00ba4360cf | ||
|
|
8669d183d5 | ||
|
|
66b9d75524 | ||
|
|
d3a0a61d79 | ||
|
|
0ad39bb92c | ||
|
|
0e952ef701 | ||
|
|
f1382e943c | ||
|
|
53fccc2d3c | ||
|
|
9ae839138c | ||
|
|
0fa6abc53d | ||
|
|
2a32f31097 | ||
|
|
52a7aebb51 | ||
|
|
af32ec14e1 | ||
|
|
e34156b2d3 | ||
|
|
721118787a | ||
|
|
292ed7f920 | ||
|
|
432f6a21c7 | ||
|
|
2087001ecd | ||
|
|
ec93af0064 | ||
|
|
effe30ee58 | ||
|
|
99f0c0d626 | ||
|
|
1e27387016 | ||
|
|
c733a806bd | ||
|
|
23cbd693a8 | ||
|
|
366bc9fc88 | ||
|
|
b4420e54b7 | ||
|
|
44d74d35e6 | ||
|
|
5897abcbad | ||
|
|
b3b9e617b5 | ||
|
|
6f9529d31f | ||
|
|
c25b10f7f3 | ||
|
|
c69a779ecc | ||
|
|
688a0e4de5 | ||
|
|
cf9b80bbb3 | ||
|
|
2a341d3969 | ||
|
|
9275233d09 | ||
|
|
13dceaa460 | ||
|
|
0ab2980ff4 | ||
|
|
fd14c05f3a | ||
|
|
cc0358bb12 | ||
|
|
f94ef580fb | ||
|
|
1bb6274b35 | ||
|
|
448c250944 | ||
|
|
5f5c3eb3b9 | ||
|
|
3805057923 | ||
|
|
f4678c48ca | ||
|
|
c40e931168 | ||
|
|
e96a13b255 | ||
|
|
4413c2ef6c | ||
|
|
65063e224a | ||
|
|
c8063b5f2a | ||
|
|
bfeb464bfb | ||
|
|
860324e3a9 | ||
|
|
f705511164 | ||
|
|
70a5449d35 | ||
|
|
80a2e188cf | ||
|
|
e036c5d436 | ||
|
|
ed77f87ab5 | ||
|
|
4712433903 | ||
|
|
f4add07780 | ||
|
|
01b6f1d3d7 | ||
|
|
60a4e14b4b | ||
|
|
6e465663bd | ||
|
|
b1142bd0c0 | ||
|
|
50d0df822c | ||
|
|
ab2f330eb8 | ||
|
|
ca3d4f6a16 | ||
|
|
3321bac22d | ||
|
|
3e78b89cc1 | ||
|
|
bfb1841370 | ||
|
|
6ba2c51403 | ||
|
|
ba0aa5ee4e | ||
|
|
7485c89e9b | ||
|
|
8869ce2583 | ||
|
|
64419f6755 | ||
|
|
8cedc2cd67 | ||
|
|
65a6fe1f0c | ||
|
|
afbee9cf70 | ||
|
|
5984242ce4 | ||
|
|
c523acc9e8 | ||
|
|
c78bdbcdb5 | ||
|
|
7a081e28df | ||
|
|
93d43fb261 | ||
|
|
8c435ab09e | ||
|
|
4388a5c2e6 | ||
|
|
62a7a87378 | ||
|
|
19583c5ad8 | ||
|
|
1858eba3e6 | ||
|
|
cb20c2acb5 | ||
|
|
105ab07fbd | ||
|
|
bf84e5da43 | ||
|
|
02badd0e25 | ||
|
|
aa23c7ef91 | ||
|
|
4b147b0091 | ||
|
|
6950ff0d79 | ||
|
|
cc9ec25388 | ||
|
|
be2ff0719a | ||
|
|
9d93707848 | ||
|
|
aa99216c49 | ||
|
|
58d3794050 | ||
|
|
16f9610027 | ||
|
|
2023dd4e36 | ||
|
|
0bed6e0313 | ||
|
|
f29ba4ab8b | ||
|
|
56b6696ca3 | ||
|
|
0d0c67704c | ||
|
|
09e8a890e0 | ||
|
|
4b17a6fcc3 | ||
|
|
5507fbcb29 | ||
|
|
176cc08a6b | ||
|
|
5953c3cf75 | ||
|
|
0952a482fb | ||
|
|
c7f1d25e98 | ||
|
|
841eab0556 | ||
|
|
ac065fa911 | ||
|
|
70d8128bfb | ||
|
|
8c8ae66c7d | ||
|
|
c8a3f35b0a | ||
|
|
e5c83e87fe | ||
|
|
eb17c8e284 | ||
|
|
459f8b59fe | ||
|
|
e6c705cef7 | ||
|
|
19c4bb451d | ||
|
|
f71b79a17f | ||
|
|
e3eb7ca205 | ||
|
|
2e54163d9e | ||
|
|
344f79039f | ||
|
|
02fe634944 | ||
|
|
7b1f64d727 | ||
|
|
d53e38a48f | ||
|
|
740e738fca | ||
|
|
ee90284129 | ||
|
|
de42b3126b | ||
|
|
71dccbc590 | ||
|
|
4c6127786f | ||
|
|
bf082c59fe | ||
|
|
ee35c10454 | ||
|
|
1651fd00a2 | ||
|
|
d9e4447903 | ||
|
|
f59dd6ebec | ||
|
|
10413547c1 | ||
|
|
2f178db2c6 | ||
|
|
28485d51f7 | ||
|
|
24362b89d7 | ||
|
|
159e4a4cbf | ||
|
|
13a7919c91 | ||
|
|
d670690816 | ||
|
|
62c58c7c89 | ||
|
|
0b4d9a8463 | ||
|
|
51ca8c7e34 | ||
|
|
64047054b8 | ||
|
|
3f5258a76c | ||
|
|
3b93308b71 | ||
|
|
bf53f2e17c | ||
|
|
c2eca11a3b | ||
|
|
4c3f8de1fb | ||
|
|
b3e1869724 | ||
|
|
624f58c723 | ||
|
|
aedc0f6979 | ||
|
|
1e53ceeda6 | ||
|
|
f08ed0c22c | ||
|
|
ee0f877d97 | ||
|
|
b3d4e08914 | ||
|
|
ec9dd83e77 | ||
|
|
4930e2a870 | ||
|
|
5e21cc76fc | ||
|
|
529110a693 | ||
|
|
0b5f2a88cc | ||
|
|
ff6f04fe46 | ||
|
|
2e9a0e30c1 | ||
|
|
ad0acaccc2 | ||
|
|
30019a02d8 | ||
|
|
87999be3d2 | ||
|
|
4ce9f6000c | ||
|
|
0529962391 | ||
|
|
14c45e4f6c | ||
|
|
1c38b95fb0 | ||
|
|
dab66a2dce | ||
|
|
86eb0cfcae | ||
|
|
d3aa10c769 | ||
|
|
15524609fe | ||
|
|
aacb91ac70 | ||
|
|
f91502026b | ||
|
|
7f2f638f38 | ||
|
|
7879ead486 | ||
|
|
dda1caf3e0 | ||
|
|
bb483d3e68 | ||
|
|
73bc79b4bb | ||
|
|
9520426a66 | ||
|
|
b077423ab2 | ||
|
|
94867fbd5a | ||
|
|
6a37f2f4c7 | ||
|
|
b54338f91f | ||
|
|
c7b95b4d2b | ||
|
|
8e4388c325 | ||
|
|
305995cbe2 | ||
|
|
468170349d | ||
|
|
52446592e7 | ||
|
|
7bca0ef335 | ||
|
|
80717680a1 | ||
|
|
bb81f2c944 | ||
|
|
69094a8646 | ||
|
|
bed0b480d7 | ||
|
|
f8f9329c50 | ||
|
|
189e1f1202 | ||
|
|
5cf2863987 | ||
|
|
83cf70ac74 | ||
|
|
87bf867513 | ||
|
|
961bb383db | ||
|
|
5d5cc14f9e | ||
|
|
bfe228adee | ||
|
|
b5b4e64453 | ||
|
|
f23efbf90d | ||
|
|
81d1fa816b | ||
|
|
f5c970f82e | ||
|
|
6d0dea07f8 | ||
|
|
c4d95762f8 | ||
|
|
23724df4e4 | ||
|
|
21f7768cce | ||
|
|
92065cc7f2 | ||
|
|
956ef3b4d3 | ||
|
|
0d8125bd37 | ||
|
|
ea4d33b6bb | ||
|
|
b4fdd7abb8 | ||
|
|
f9d70bc196 | ||
|
|
5b20bab381 | ||
|
|
2c3e4bb752 | ||
|
|
570f0acc66 | ||
|
|
297aaadbe6 | ||
|
|
5573bb3568 | ||
|
|
80d9dc2f45 | ||
|
|
092933860a | ||
|
|
3d45b618ab | ||
|
|
2ab2318732 | ||
|
|
f3806cd6de | ||
|
|
8326e10ce8 | ||
|
|
d77ddd4bb2 | ||
|
|
9149e2b5ab | ||
|
|
5534d050af | ||
|
|
994086e580 | ||
|
|
dbd7d8b37d | ||
|
|
f440c60891 | ||
|
|
8672d4bcac | ||
|
|
87ad359e60 | ||
|
|
5afa2a37be | ||
|
|
d73b2e51c6 | ||
|
|
26f5f68708 | ||
|
|
86cfa4b3c8 | ||
|
|
e2b6d2acae | ||
|
|
8ef98cb415 | ||
|
|
6dbee69601 | ||
|
|
1aad481930 | ||
|
|
4393de5d8f | ||
|
|
5380bb66bb | ||
|
|
9a9ab149ed | ||
|
|
bec76393bb | ||
|
|
427b0d8591 | ||
|
|
1de8fd9a60 | ||
|
|
5c90d1629d | ||
|
|
c1a5223798 | ||
|
|
139aaff86c | ||
|
|
d9ff4aef58 | ||
|
|
a68e9b2c1e | ||
|
|
66cbf4c68d | ||
|
|
30ca17712c | ||
|
|
781b437c11 | ||
|
|
cf8f920aa6 | ||
|
|
c16e34df02 | ||
|
|
e67a4bd51c | ||
|
|
18e59efdcc | ||
|
|
c596c3a8b2 | ||
|
|
1f68210d08 | ||
|
|
fb4669e5a5 | ||
|
|
7b376f1126 | ||
|
|
e3426449e8 | ||
|
|
8795617d7f | ||
|
|
0dbf9cabb5 | ||
|
|
b6ac30d0e3 | ||
|
|
d79612b7e8 | ||
|
|
33c605132b | ||
|
|
686de48a95 | ||
|
|
043488fe55 | ||
|
|
f292195edf | ||
|
|
b61ba761bc | ||
|
|
4d64ad96b2 | ||
|
|
def903734f | ||
|
|
59ab154d0f | ||
|
|
31c55525c3 | ||
|
|
332d400a37 | ||
|
|
b5dcdec18c | ||
|
|
c6cf2e31aa | ||
|
|
b7268d0c47 | ||
|
|
a7b7164fc0 | ||
|
|
73f5d6d278 | ||
|
|
c04f1675f6 | ||
|
|
50cbd5b8ae | ||
|
|
19a029291b | ||
|
|
bd7345078a | ||
|
|
4969ec3fcd | ||
|
|
ec420e6053 | ||
|
|
4749ec91e4 | ||
|
|
679a551243 | ||
|
|
240a176151 | ||
|
|
d2c227c733 | ||
|
|
a532e2c73f | ||
|
|
3ff77d585d | ||
|
|
2a58e0c731 | ||
|
|
200ddda352 | ||
|
|
1cbd210be1 | ||
|
|
419e478489 | ||
|
|
8f8f0c36d5 | ||
|
|
2271291c87 | ||
|
|
ed20f6d089 | ||
|
|
12861288f2 | ||
|
|
73bfe0d893 | ||
|
|
a289c40503 | ||
|
|
b6735b5a9c | ||
|
|
f6736cd43f | ||
|
|
fa4f1124e6 | ||
|
|
30cebb92fa | ||
|
|
d87885826c | ||
|
|
f4e715f2d1 | ||
|
|
33afd7f45a | ||
|
|
e0581f22aa | ||
|
|
612360640c | ||
|
|
1fd2961cf4 | ||
|
|
ccbc495900 | ||
|
|
98f9223798 | ||
|
|
32cda55557 | ||
|
|
ea6d743e7d | ||
|
|
f5ebc6c508 | ||
|
|
969020105a | ||
|
|
dd90ab0f4c |
No files matched your search
@@ -12,3 +12,7 @@ uploads
|
||||
**/uploads
|
||||
*.pdf
|
||||
graphify-out
|
||||
**/.revalidation.env*
|
||||
**/.support*.env*
|
||||
**/*runtime.env
|
||||
**/release.override.json
|
||||
@@ -5,6 +5,7 @@ on:
|
||||
branches:
|
||||
- main
|
||||
- develop
|
||||
- release/blog-timestamp-limited-20261030
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
@@ -12,8 +13,23 @@ jobs:
|
||||
steps:
|
||||
- name: Run deploy.sh from within the scripts folder
|
||||
env:
|
||||
BRANCH: ${{ github.ref_name }}
|
||||
DEPLOY_REF: ${{ github.ref }}
|
||||
DEPLOY_SHA: ${{ github.sha }}
|
||||
GITHUB_ACTIONS: 'true'
|
||||
run: |
|
||||
set -eu
|
||||
case "${DEPLOY_REF}" in
|
||||
refs/heads/main) BRANCH=main; STAGE_SOURCE_REF= ;;
|
||||
refs/heads/develop|refs/heads/release/blog-timestamp-limited-20261030)
|
||||
BRANCH=develop; STAGE_SOURCE_REF="$DEPLOY_REF" ;;
|
||||
*) printf 'Unsupported deployment ref\n' >&2; exit 2 ;;
|
||||
esac
|
||||
# Bind downloads and both release dispatchers to the exact event commit.
|
||||
case "$DEPLOY_SHA" in
|
||||
*[!0-9a-f]*|'') exit 2 ;;
|
||||
esac
|
||||
[ "${#DEPLOY_SHA}" -eq 40 ] || exit 2
|
||||
export BRANCH STAGE_SOURCE_REF
|
||||
# 1. رفع مشکل DNS و غیرفعال کردن پروکسی برای دامنه محلی
|
||||
echo "87.248.133.138 git.parsaaghayi.ir" >> /etc/hosts
|
||||
export http_proxy=""
|
||||
@@ -24,8 +40,10 @@ jobs:
|
||||
|
||||
# 2. دانلود و اجرای اسکریپت deploy.sh بر اساس برنچ جاری
|
||||
mkdir -p scripts
|
||||
wget --no-proxy -qO scripts/deploy.sh https://git.parsaaghayi.ir/parsa/canina/raw/branch/${BRANCH}/scripts/deploy.sh
|
||||
wget --no-proxy -qO scripts/deploy.sh https://git.parsaaghayi.ir/parsa/canina/raw/commit/${DEPLOY_SHA}/scripts/deploy.sh
|
||||
wget --no-proxy -qO scripts/release-cache-stage.sh https://git.parsaaghayi.ir/parsa/canina/raw/commit/${DEPLOY_SHA}/scripts/release-cache-stage.sh
|
||||
|
||||
wget --no-proxy -qO scripts/release-cache-prod.sh https://git.parsaaghayi.ir/parsa/canina/raw/commit/${DEPLOY_SHA}/scripts/release-cache-prod.sh
|
||||
chmod +x scripts/deploy.sh
|
||||
cd scripts
|
||||
./deploy.sh ${BRANCH}
|
||||
./deploy.sh "${BRANCH}"
|
||||
@@ -1,45 +0,0 @@
|
||||
name: E2E Playwright Tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- develop
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
- develop
|
||||
|
||||
jobs:
|
||||
test-e2e:
|
||||
name: Run Full E2E & Security Suites
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout Code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: 'npm'
|
||||
|
||||
- name: Install Monorepo Dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Install Playwright Browsers
|
||||
run: npx playwright install --with-deps chromium
|
||||
|
||||
- name: Run E2E Test Suite
|
||||
run: npx playwright test --project=chromium-desktop --project=admin-chromium
|
||||
env:
|
||||
CI: true
|
||||
NODE_ENV: test
|
||||
|
||||
- name: Upload Test Report
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: playwright-report
|
||||
path: playwright-report/
|
||||
retention-days: 14
|
||||
@@ -16,3 +16,7 @@ playwright-report/
|
||||
playwright/.auth/
|
||||
blob-report/
|
||||
|
||||
|
||||
# Python CI helpers must not dirty immutable release checkouts.
|
||||
__pycache__/
|
||||
*.pyc
|
||||
+9
-9
@@ -1,4 +1,4 @@
|
||||
FROM node:20-alpine AS app-builder
|
||||
FROM node:22-alpine AS app-builder
|
||||
USER root
|
||||
WORKDIR /app
|
||||
ENV NEXT_TELEMETRY_DISABLED=1
|
||||
@@ -7,18 +7,17 @@ ENV NEXT_PUBLIC_API_URL=https://api.canina.ir/api
|
||||
# Optional: Use Nexus as npm registry
|
||||
ARG NPM_REGISTRY=
|
||||
RUN if [ -n "$NPM_REGISTRY" ]; then \
|
||||
npm config set registry "$NPM_REGISTRY" && \
|
||||
npm config set strict-ssl false; \
|
||||
npm config set registry "$NPM_REGISTRY"; \
|
||||
fi
|
||||
|
||||
COPY frontend/application/package*.json ./
|
||||
RUN npm ci --include=dev --prefer-offline --no-audit
|
||||
RUN npm ci --include=dev --prefer-offline --no-audit && test -x node_modules/.bin/next
|
||||
COPY frontend/application ./
|
||||
ARG NEXT_PUBLIC_API_URL
|
||||
ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL
|
||||
RUN npm run build
|
||||
|
||||
FROM node:20-alpine AS admin-builder
|
||||
FROM node:22-alpine AS admin-builder
|
||||
USER root
|
||||
WORKDIR /app
|
||||
ENV VITE_API_URL=https://api.canina.ir/api
|
||||
@@ -26,18 +25,17 @@ ENV VITE_API_URL=https://api.canina.ir/api
|
||||
# Optional: Use Nexus as npm registry (inherits build-arg)
|
||||
ARG NPM_REGISTRY=
|
||||
RUN if [ -n "$NPM_REGISTRY" ]; then \
|
||||
npm config set registry "$NPM_REGISTRY" && \
|
||||
npm config set strict-ssl false; \
|
||||
npm config set registry "$NPM_REGISTRY"; \
|
||||
fi
|
||||
|
||||
COPY frontend/admin-panel/package*.json ./
|
||||
RUN npm ci --include=dev --prefer-offline --no-audit
|
||||
RUN npm ci --include=dev --prefer-offline --no-audit && test -x node_modules/.bin/vite
|
||||
COPY frontend/admin-panel ./
|
||||
ARG VITE_API_URL
|
||||
ENV VITE_API_URL=$VITE_API_URL
|
||||
RUN npm run build
|
||||
|
||||
FROM node:20-alpine
|
||||
FROM node:22-alpine
|
||||
USER root
|
||||
RUN addgroup -S nginx 2>/dev/null || true && adduser -S nginx -G nginx 2>/dev/null || true
|
||||
RUN mkdir -p /var/log/nginx /var/cache/nginx /run/nginx /etc/nginx/conf.d /etc/nginx/http.d
|
||||
@@ -49,6 +47,8 @@ RUN chown -R nginx:nginx /var/log/nginx /var/cache/nginx /run/nginx 2>/dev/null
|
||||
WORKDIR /app
|
||||
COPY --from=app-builder /app .
|
||||
COPY --from=admin-builder /app/dist ./admin_static
|
||||
# Build-context umask must not make public assets unreadable by nginx workers.
|
||||
RUN chmod -R a+rX /app/admin_static
|
||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||
COPY nginx.conf /etc/nginx/http.d/default.conf
|
||||
|
||||
|
||||
+6
-3
@@ -2,6 +2,7 @@ FROM node:20-alpine AS builder
|
||||
USER root
|
||||
RUN http_proxy=http://172.17.0.1:8888 https_proxy=http://172.17.0.1:8888 apk add --no-cache openssl || apk add --no-cache openssl || true
|
||||
WORKDIR /app
|
||||
ENV PRISMA_HIDE_UPDATE_MESSAGE=true
|
||||
ENV PRISMA_SKIP_POSTINSTALL_GENERATE=true
|
||||
ENV PRISMA_ENGINES_MIRROR=https://registry.npmmirror.com/-/binary/prisma
|
||||
ENV DISABLE_OPENCOLLECTIVE=1
|
||||
@@ -11,7 +12,6 @@ ENV npm_config_cache=/tmp/npm-cache
|
||||
ARG NPM_REGISTRY=
|
||||
RUN if [ -n "$NPM_REGISTRY" ]; then \
|
||||
npm config set registry "$NPM_REGISTRY" && \
|
||||
npm config set strict-ssl false && \
|
||||
echo "Using npm registry: $NPM_REGISTRY"; \
|
||||
fi
|
||||
|
||||
@@ -31,8 +31,11 @@ RUN http_proxy=http://172.17.0.1:8888 https_proxy=http://172.17.0.1:8888 \
|
||||
FROM node:20-alpine
|
||||
USER root
|
||||
RUN http_proxy=http://172.17.0.1:8888 https_proxy=http://172.17.0.1:8888 apk add --no-cache openssl || apk add --no-cache openssl || true
|
||||
RUN mkdir -p /app/uploads && chown node:node /app/uploads
|
||||
RUN mkdir -p /app/uploads /app/private-stage-test && chmod 700 /app/private-stage-test && chown node:node /app/uploads /app/private-stage-test
|
||||
WORKDIR /app
|
||||
ARG STAGE_TEST_ARTIFACT_SHA=disabled
|
||||
RUN printf "%s" "$STAGE_TEST_ARTIFACT_SHA" > /app/STAGE_TEST_ARTIFACT_SHA
|
||||
ENV PRISMA_HIDE_UPDATE_MESSAGE=true
|
||||
COPY --chown=node:node --from=builder /app/package*.json ./
|
||||
COPY --chown=node:node --from=builder /app/tsconfig.json ./tsconfig.json
|
||||
COPY --chown=node:node --from=builder /app/eslint.config.mjs ./eslint.config.mjs
|
||||
@@ -45,4 +48,4 @@ COPY --chown=node:node --from=builder /app/src ./src
|
||||
COPY --chown=node:node --from=builder /app/test ./test
|
||||
EXPOSE 3000
|
||||
USER node
|
||||
CMD ["sh", "-c", "npx prisma db push --skip-generate && if [ -f dist/src/main.js ]; then node dist/src/main.js; else node dist/main.js; fi"]
|
||||
CMD ["node", "dist/main.js"]
|
||||
@@ -0,0 +1,28 @@
|
||||
# Prisma migration history and Orchestration v4 rollout boundary
|
||||
|
||||
The checked-in history is **not a complete baseline of the current Prisma schema**. Do not assume that replaying it into an empty database can recreate the application, or that existing production tables imply corresponding migration records. Never use `prisma db push`, reset, or edit applied SQL to reconcile this.
|
||||
|
||||
## Actual tracked history
|
||||
|
||||
| Migration | What its SQL actually does |
|
||||
| --- | --- |
|
||||
| `20260526145407_init` | Creates users, addresses, wallets, products, product ingredients/symptoms, pets and medical conditions, reminders/completions, health logs, coupons, orders and order items, with their indexes/foreign keys. |
|
||||
| `20260526160916_add_ui_texts_and_scientific_terms` | Creates `ui_texts` and `scientific_terms`. |
|
||||
| `20261013210253_add_admin_modules` | Creates only `competitor_price_logs`, `b2b_leads`, `price_suggestions`, and `sms_campaigns`, with indexes and product foreign keys. It does **not** create legacy approvals, department tasks or audit logs. |
|
||||
| `20261015000000_add_support_conversations` | Creates support conversations/messages and their foreign keys. |
|
||||
| `20261020000000_add_blog_freshness_authorship` | Adds three columns to an assumed-existing `blogs` table. No earlier tracked migration creates `blogs`; fresh replay is therefore incomplete before v4. |
|
||||
| `20261022000000_add_orchestration_v4_core` | Additively creates nine `orchestration_*` tables, indexes and internal foreign keys; it neither creates nor copies legacy governance tables. |
|
||||
|
||||
There is no checked-in CREATE TABLE migration for `approval_requests`, `department_tasks`, or `audit_logs`. Their models/controllers are not evidence that either live environment has these tables, nor proof of how any historical database acquired them. The broader missing legacy schema must be reconciled separately. This document does not certify live table existence or migration status.
|
||||
|
||||
## Required rollout safeguards (not authorization to deploy)
|
||||
|
||||
1. Back up each environment and verify restore capability. Capture its actual schema and `_prisma_migrations` history read-only; compare those independently against all tracked SQL, including prerequisites such as `blogs`.
|
||||
2. Rehearse the exact planned chain on a disposable database restored from a reviewed baseline. A failed empty replay is a legacy-history gap, not evidence that the additive v4 SQL alone is faulty. Resolve the missing baseline through a separately reviewed migration/baseline plan, never by skipping errors.
|
||||
3. `prisma migrate resolve --applied <name>` only records history; it creates no objects. Use it only for a specifically verified, fully matching existing migration and reviewed environment-specific plan. Never mark the whole chain applied or mark missing tables as applied.
|
||||
4. After baseline reconciliation and rehearsal pass, apply reviewed pending migrations through CI/CD only using `prisma migrate deploy`. Verify all nine v4 tables, constraints, migration records and application health before considering the read surface ready.
|
||||
5. Keep v4 mutations, chat and runtime capabilities denied. Retiring legacy mutation routes does not authorize a replacement execution path.
|
||||
|
||||
No deployment, live DDL, baseline resolution or migration SQL change is part of this hardening milestone. Schema rollout remains a separate gate, not full-system completion.
|
||||
|
||||
Rollback is application-first: stop use of the new module while retaining append-only records. Do not drop tables in automated rollback; removal requires separately reviewed archival migration.
|
||||
@@ -0,0 +1,8 @@
|
||||
CREATE TABLE support_conversations (id UUID NOT NULL, user_id UUID, anonymous_browser_id VARCHAR(64), entry_path VARCHAR(512), product_slugs JSONB, topics JSONB, unanswered BOOLEAN NOT NULL DEFAULT false, needs_followup BOOLEAN NOT NULL DEFAULT false, escalation_signal BOOLEAN NOT NULL DEFAULT false, summary TEXT, summary_status VARCHAR(20) NOT NULL DEFAULT 'pending', created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, expires_at TIMESTAMPTZ NOT NULL, CONSTRAINT support_conversations_pkey PRIMARY KEY (id));
|
||||
CREATE TABLE support_conversation_messages (id UUID NOT NULL, conversation_id UUID NOT NULL, role VARCHAR(20) NOT NULL, content TEXT NOT NULL, sequence INTEGER NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, CONSTRAINT support_conversation_messages_pkey PRIMARY KEY (id));
|
||||
CREATE UNIQUE INDEX support_conversation_messages_conversation_id_sequence_key ON support_conversation_messages(conversation_id, sequence);
|
||||
CREATE INDEX support_conversations_user_id_updated_at_idx ON support_conversations(user_id, updated_at);
|
||||
CREATE INDEX support_conversations_anonymous_browser_id_updated_at_idx ON support_conversations(anonymous_browser_id, updated_at);
|
||||
CREATE INDEX support_conversation_messages_conversation_id_created_at_idx ON support_conversation_messages(conversation_id, created_at);
|
||||
ALTER TABLE support_conversations ADD CONSTRAINT support_conversations_user_id_fkey FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
ALTER TABLE support_conversation_messages ADD CONSTRAINT support_conversation_messages_conversation_id_fkey FOREIGN KEY (conversation_id) REFERENCES support_conversations(id) ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,3 @@
|
||||
ALTER TABLE blogs ADD COLUMN IF NOT EXISTS author_team VARCHAR(200);
|
||||
ALTER TABLE blogs ADD COLUMN IF NOT EXISTS author_role VARCHAR(200);
|
||||
ALTER TABLE blogs ADD COLUMN IF NOT EXISTS content_updated_at TIMESTAMPTZ;
|
||||
@@ -0,0 +1,211 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_tasks" (
|
||||
"id" UUID NOT NULL,
|
||||
"key" VARCHAR(120) NOT NULL,
|
||||
"title" VARCHAR(255) NOT NULL,
|
||||
"department" VARCHAR(50) NOT NULL,
|
||||
"state" VARCHAR(40) NOT NULL DEFAULT 'DRAFT',
|
||||
"operation_mode" VARCHAR(30) NOT NULL,
|
||||
"model_tier" VARCHAR(2),
|
||||
"budget_limit_cents" INTEGER NOT NULL,
|
||||
"version" INTEGER NOT NULL DEFAULT 1,
|
||||
"metadata" JSONB NOT NULL DEFAULT '{}',
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMPTZ NOT NULL,
|
||||
|
||||
CONSTRAINT "orchestration_tasks_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_runs" (
|
||||
"id" UUID NOT NULL,
|
||||
"task_id" UUID NOT NULL,
|
||||
"attempt" INTEGER NOT NULL DEFAULT 1,
|
||||
"status" VARCHAR(30) NOT NULL DEFAULT 'PENDING',
|
||||
"commit_sha" VARCHAR(64) NOT NULL,
|
||||
"environment" VARCHAR(50) NOT NULL,
|
||||
"retry_class" VARCHAR(30),
|
||||
"idempotency_key" VARCHAR(150) NOT NULL,
|
||||
"started_at" TIMESTAMPTZ,
|
||||
"finished_at" TIMESTAMPTZ,
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "orchestration_runs_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_artifacts" (
|
||||
"id" UUID NOT NULL,
|
||||
"run_id" UUID NOT NULL,
|
||||
"kind" VARCHAR(50) NOT NULL,
|
||||
"uri" TEXT NOT NULL,
|
||||
"sha256" CHAR(64) NOT NULL,
|
||||
"size_bytes" BIGINT,
|
||||
"metadata" JSONB NOT NULL DEFAULT '{}',
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "orchestration_artifacts_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_attestations" (
|
||||
"id" UUID NOT NULL,
|
||||
"run_id" UUID NOT NULL,
|
||||
"kind" VARCHAR(50) NOT NULL,
|
||||
"subject_hash" CHAR(64) NOT NULL,
|
||||
"predicate" JSONB NOT NULL,
|
||||
"signer" VARCHAR(150) NOT NULL,
|
||||
"signature" TEXT,
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "orchestration_attestations_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_dependencies" (
|
||||
"id" UUID NOT NULL,
|
||||
"task_id" UUID NOT NULL,
|
||||
"depends_on_task_id" UUID NOT NULL,
|
||||
"kind" VARCHAR(30) NOT NULL DEFAULT 'BLOCKS',
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "orchestration_dependencies_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_approval_decisions" (
|
||||
"id" UUID NOT NULL,
|
||||
"task_id" UUID NOT NULL,
|
||||
"gate" INTEGER NOT NULL,
|
||||
"decision" VARCHAR(20) NOT NULL,
|
||||
"actor_id" VARCHAR(100) NOT NULL,
|
||||
"notes" TEXT,
|
||||
"expires_at" TIMESTAMPTZ NOT NULL,
|
||||
"idempotency_key" VARCHAR(150) NOT NULL,
|
||||
"run_id" UUID,
|
||||
"artifact_hash" CHAR(64),
|
||||
"commit_sha" VARCHAR(64),
|
||||
"environment" VARCHAR(50),
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "orchestration_approval_decisions_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_events" (
|
||||
"id" UUID NOT NULL,
|
||||
"task_id" UUID,
|
||||
"event_type" VARCHAR(60) NOT NULL,
|
||||
"from_state" VARCHAR(40),
|
||||
"to_state" VARCHAR(40),
|
||||
"sequence" INTEGER NOT NULL,
|
||||
"actor_id" VARCHAR(100) NOT NULL,
|
||||
"idempotency_key" VARCHAR(150),
|
||||
"payload" JSONB NOT NULL DEFAULT '{}',
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "orchestration_events_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_budget_ledger" (
|
||||
"id" UUID NOT NULL,
|
||||
"task_id" UUID NOT NULL,
|
||||
"amount_cents" INTEGER NOT NULL,
|
||||
"kind" VARCHAR(40) NOT NULL,
|
||||
"idempotency_key" VARCHAR(150) NOT NULL,
|
||||
"actor_id" VARCHAR(100) NOT NULL,
|
||||
"metadata" JSONB NOT NULL DEFAULT '{}',
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "orchestration_budget_ledger_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_kill_switches" (
|
||||
"scope" VARCHAR(80) NOT NULL,
|
||||
"level" VARCHAR(30) NOT NULL,
|
||||
"active" BOOLEAN NOT NULL DEFAULT true,
|
||||
"reason" TEXT NOT NULL,
|
||||
"actor_id" VARCHAR(100) NOT NULL,
|
||||
"version" INTEGER NOT NULL DEFAULT 1,
|
||||
"updated_at" TIMESTAMPTZ NOT NULL,
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "orchestration_kill_switches_pkey" PRIMARY KEY ("scope")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_tasks_key_key" ON "orchestration_tasks"("key");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "orchestration_tasks_state_created_at_idx" ON "orchestration_tasks"("state", "created_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "orchestration_tasks_department_state_idx" ON "orchestration_tasks"("department", "state");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_runs_idempotency_key_key" ON "orchestration_runs"("idempotency_key");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "orchestration_runs_task_id_status_idx" ON "orchestration_runs"("task_id", "status");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_runs_task_id_attempt_key" ON "orchestration_runs"("task_id", "attempt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_artifacts_run_id_sha256_key" ON "orchestration_artifacts"("run_id", "sha256");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_attestations_run_id_kind_subject_hash_signer_key" ON "orchestration_attestations"("run_id", "kind", "subject_hash", "signer");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_dependencies_task_id_depends_on_task_id_key" ON "orchestration_dependencies"("task_id", "depends_on_task_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_approval_decisions_idempotency_key_key" ON "orchestration_approval_decisions"("idempotency_key");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "orchestration_approval_decisions_task_id_gate_created_at_idx" ON "orchestration_approval_decisions"("task_id", "gate", "created_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_events_idempotency_key_key" ON "orchestration_events"("idempotency_key");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "orchestration_events_event_type_created_at_idx" ON "orchestration_events"("event_type", "created_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_events_task_id_sequence_key" ON "orchestration_events"("task_id", "sequence");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_budget_ledger_idempotency_key_key" ON "orchestration_budget_ledger"("idempotency_key");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "orchestration_budget_ledger_task_id_created_at_idx" ON "orchestration_budget_ledger"("task_id", "created_at");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_runs" ADD CONSTRAINT "orchestration_runs_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_artifacts" ADD CONSTRAINT "orchestration_artifacts_run_id_fkey" FOREIGN KEY ("run_id") REFERENCES "orchestration_runs"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_attestations" ADD CONSTRAINT "orchestration_attestations_run_id_fkey" FOREIGN KEY ("run_id") REFERENCES "orchestration_runs"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_dependencies" ADD CONSTRAINT "orchestration_dependencies_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_dependencies" ADD CONSTRAINT "orchestration_dependencies_depends_on_task_id_fkey" FOREIGN KEY ("depends_on_task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_approval_decisions" ADD CONSTRAINT "orchestration_approval_decisions_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_approval_decisions" ADD CONSTRAINT "orchestration_approval_decisions_run_id_fkey" FOREIGN KEY ("run_id") REFERENCES "orchestration_runs"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_events" ADD CONSTRAINT "orchestration_events_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_budget_ledger" ADD CONSTRAINT "orchestration_budget_ledger_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,10 @@
|
||||
-- Immutable evidence and accounting; corrections are new entries.
|
||||
CREATE FUNCTION orchestration_append_only() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN RAISE EXCEPTION 'Orchestration append-only record cannot be changed'; END;
|
||||
$$;
|
||||
CREATE TRIGGER orchestration_budget_immutable BEFORE UPDATE OR DELETE ON orchestration_budget_ledger FOR EACH ROW EXECUTE FUNCTION orchestration_append_only();
|
||||
CREATE TRIGGER orchestration_events_immutable BEFORE UPDATE OR DELETE ON orchestration_events FOR EACH ROW EXECUTE FUNCTION orchestration_append_only();
|
||||
CREATE TRIGGER orchestration_approvals_immutable BEFORE UPDATE OR DELETE ON orchestration_approval_decisions FOR EACH ROW EXECUTE FUNCTION orchestration_append_only();
|
||||
CREATE TRIGGER orchestration_artifacts_immutable BEFORE UPDATE OR DELETE ON orchestration_artifacts FOR EACH ROW EXECUTE FUNCTION orchestration_append_only();
|
||||
CREATE TRIGGER orchestration_attestations_immutable BEFORE UPDATE OR DELETE ON orchestration_attestations FOR EACH ROW EXECUTE FUNCTION orchestration_append_only();
|
||||
ALTER TABLE orchestration_tasks ADD CONSTRAINT orchestration_budget_nonnegative CHECK (budget_limit_cents >= 0);
|
||||
@@ -0,0 +1,10 @@
|
||||
CREATE TABLE prepare_workflow_outbox (
|
||||
id uuid PRIMARY KEY, task_id uuid NOT NULL UNIQUE REFERENCES orchestration_tasks(id) ON DELETE RESTRICT,
|
||||
status varchar(20) NOT NULL DEFAULT 'PENDING' CHECK (status IN ('PENDING','DONE')),
|
||||
attempts integer NOT NULL DEFAULT 0 CHECK (attempts BETWEEN 0 AND 3),
|
||||
lease_owner varchar(100), lease_token uuid, lease_until timestamptz, heartbeat_at timestamptz,
|
||||
run_id uuid REFERENCES orchestration_runs(id) ON DELETE RESTRICT,
|
||||
reservation_id uuid REFERENCES orchestration_budget_ledger(id) ON DELETE RESTRICT,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX prepare_workflow_outbox_status_lease_until_idx ON prepare_workflow_outbox(status,lease_until);
|
||||
@@ -0,0 +1,3 @@
|
||||
-- Scheduling is distinct from immutable approval validity. Existing queues run immediately.
|
||||
ALTER TABLE "prepare_workflow_outbox" ADD COLUMN "not_before" TIMESTAMPTZ;
|
||||
CREATE INDEX "prepare_workflow_outbox_due_idx" ON "prepare_workflow_outbox" ("status", "not_before", "created_at");
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "auth_expires_at" TIMESTAMPTZ, ADD COLUMN IF NOT EXISTS "stage_test_session" VARCHAR(64), ADD COLUMN IF NOT EXISTS "stage_test_generation" UUID;
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
-- Drop legacy governance and orchestration tables
|
||||
DROP TABLE IF EXISTS "prepare_workflow_outbox" CASCADE;
|
||||
DROP TABLE IF EXISTS "orchestration_kill_switches" CASCADE;
|
||||
DROP TABLE IF EXISTS "orchestration_budget_ledger" CASCADE;
|
||||
DROP TABLE IF EXISTS "orchestration_events" CASCADE;
|
||||
DROP TABLE IF EXISTS "orchestration_approval_decisions" CASCADE;
|
||||
DROP TABLE IF EXISTS "orchestration_dependencies" CASCADE;
|
||||
DROP TABLE IF EXISTS "orchestration_attestations" CASCADE;
|
||||
DROP TABLE IF EXISTS "orchestration_artifacts" CASCADE;
|
||||
DROP TABLE IF EXISTS "orchestration_runs" CASCADE;
|
||||
DROP TABLE IF EXISTS "orchestration_tasks" CASCADE;
|
||||
DROP TABLE IF EXISTS "department_tasks" CASCADE;
|
||||
DROP TABLE IF EXISTS "audit_logs" CASCADE;
|
||||
DROP TABLE IF EXISTS "approval_requests" CASCADE;
|
||||
@@ -16,6 +16,9 @@ model User {
|
||||
mobile String @unique @db.VarChar(15)
|
||||
password String? @db.VarChar(255)
|
||||
role String @default("User_PetOwner") @db.VarChar(30)
|
||||
authExpiresAt DateTime? @map("auth_expires_at") @db.Timestamptz()
|
||||
stageTestGeneration String? @map("stage_test_generation") @db.Uuid
|
||||
stageTestSession String? @map("stage_test_session") @db.VarChar(64)
|
||||
walletBalance Decimal @default(0.00) @map("wallet_balance") @db.Decimal(15, 2)
|
||||
charityDonationTotal Decimal @default(0.00) @map("charity_donation_total") @db.Decimal(15, 2)
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
@@ -32,12 +35,49 @@ model User {
|
||||
tickets Ticket[]
|
||||
reviews ProductReview[]
|
||||
blogComments BlogComment[]
|
||||
supportConversations SupportConversation[]
|
||||
|
||||
@@index([role])
|
||||
@@index([createdAt])
|
||||
@@map("users")
|
||||
}
|
||||
|
||||
model SupportConversation {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
userId String? @map("user_id") @db.Uuid
|
||||
anonymousBrowserId String? @map("anonymous_browser_id") @db.VarChar(64)
|
||||
entryPath String? @map("entry_path") @db.VarChar(512)
|
||||
productSlugs Json? @map("product_slugs")
|
||||
topics Json?
|
||||
unanswered Boolean @default(false)
|
||||
needsFollowup Boolean @default(false) @map("needs_followup")
|
||||
escalationSignal Boolean @default(false) @map("escalation_signal")
|
||||
summary String? @db.Text
|
||||
summaryStatus String @default("pending") @map("summary_status") @db.VarChar(20)
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz()
|
||||
expiresAt DateTime @map("expires_at") @db.Timestamptz()
|
||||
|
||||
user User? @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
messages SupportConversationMessage[]
|
||||
@@index([userId, updatedAt])
|
||||
@@index([anonymousBrowserId, updatedAt])
|
||||
@@map("support_conversations")
|
||||
}
|
||||
|
||||
model SupportConversationMessage {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
conversationId String @map("conversation_id") @db.Uuid
|
||||
role String @db.VarChar(20)
|
||||
content String @db.Text
|
||||
sequence Int
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
conversation SupportConversation @relation(fields: [conversationId], references: [id], onDelete: Cascade)
|
||||
@@unique([conversationId, sequence])
|
||||
@@index([conversationId, createdAt])
|
||||
@@map("support_conversation_messages")
|
||||
}
|
||||
|
||||
model UserAddress {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
userId String @map("user_id") @db.Uuid
|
||||
@@ -141,7 +181,9 @@ model Blog {
|
||||
slug String @unique @db.VarChar(200)
|
||||
content 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
|
||||
imageUrl String? @map("image_url") @db.Text
|
||||
imageAlt String? @map("image_alt") @db.VarChar(255)
|
||||
@@ -161,6 +203,7 @@ model Blog {
|
||||
isPublished Boolean @default(true) @map("is_published")
|
||||
publishedAt DateTime? @map("published_at") @db.Timestamptz()
|
||||
scheduledAt DateTime? @map("scheduled_at") @db.Timestamptz()
|
||||
contentUpdatedAt DateTime? @map("content_updated_at") @db.Timestamptz()
|
||||
readingTime Int @default(3) @map("reading_time")
|
||||
featured Boolean @default(false)
|
||||
allowComments Boolean @default(true) @map("allow_comments")
|
||||
@@ -172,7 +215,7 @@ model Blog {
|
||||
createdAt DateTime @default(now()) @map("created_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)
|
||||
tags BlogTag[]
|
||||
comments BlogComment[]
|
||||
@@ -977,77 +1020,3 @@ model SmsCampaign {
|
||||
@@map("sms_campaigns")
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// 5. ApprovalRequest (CEO Governance & Decision Gate)
|
||||
// ------------------------------------------------------------------------------
|
||||
model ApprovalRequest {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
department String @db.VarChar(50)
|
||||
category String @db.VarChar(50)
|
||||
title String @db.VarChar(255)
|
||||
payload Json @db.JsonB
|
||||
testContext Json? @map("test_context") @db.JsonB
|
||||
status String @default("PENDING") @db.VarChar(30)
|
||||
ceoNotes String? @map("ceo_notes") @db.Text
|
||||
executedAt DateTime? @map("executed_at") @db.Timestamptz()
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
|
||||
|
||||
@@index([department])
|
||||
@@index([category])
|
||||
@@index([status])
|
||||
@@index([createdAt])
|
||||
@@map("approval_requests")
|
||||
}
|
||||
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// 6. AuditLog (System & Database Changes History)
|
||||
// ------------------------------------------------------------------------------
|
||||
model AuditLog {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
entity String @db.VarChar(50) // e.g. product, blog, order, approval, settings
|
||||
entityId String? @map("entity_id") @db.VarChar(100)
|
||||
action String @db.VarChar(50) // CREATE, UPDATE, DELETE, EXECUTE, APPROVE, REJECT
|
||||
department String? @db.VarChar(50) // devops, seo, content, vet, commerce, pmo
|
||||
actor String @default("SYSTEM") @db.VarChar(100)
|
||||
summary String @db.VarChar(255)
|
||||
oldValues Json? @map("old_values") @db.JsonB
|
||||
newValues Json? @map("new_values") @db.JsonB
|
||||
metadata Json? @db.JsonB
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
|
||||
@@index([entity])
|
||||
@@index([action])
|
||||
@@index([department])
|
||||
@@index([createdAt])
|
||||
@@map("audit_logs")
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// 7. DepartmentTask (Autonomous Corporate Task & Kanban Manager)
|
||||
// ------------------------------------------------------------------------------
|
||||
model 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")
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { ForbiddenException } from "@nestjs/common";
|
||||
import { AdminService } from "./admin.service";
|
||||
import { AdminController } from "./admin.controller";
|
||||
|
||||
// All identities and credentials here are disposable test fixtures.
|
||||
describe("admin user privilege boundary", () => {
|
||||
let service: any;
|
||||
let prisma: any;
|
||||
const owner = { id: "owner-fixture", role: "SUPER_ADMIN" };
|
||||
const admin = { id: "admin-fixture", role: "ADMIN" };
|
||||
beforeEach(() => {
|
||||
prisma = {
|
||||
user: {
|
||||
findUnique: jest.fn().mockResolvedValue({ id: "target-fixture", role: "SUPER_ADMIN" }),
|
||||
update: jest.fn().mockImplementation(async ({ data }) => ({ role: "SUPER_ADMIN", ...data })),
|
||||
create: jest.fn(),
|
||||
},
|
||||
walletTransaction: { create: jest.fn() },
|
||||
$transaction: jest.fn(),
|
||||
};
|
||||
service = new AdminService(prisma, {} as never, {} as never);
|
||||
});
|
||||
it("allows an authenticated superadmin password-only edit without changing the exact role", async () => {
|
||||
const result = await service.updateUser("target-fixture", { password: "Fixture-only-123" }, owner);
|
||||
expect(result.role).toBe("SUPER_ADMIN");
|
||||
expect(prisma.user.update.mock.calls[0][0].data).not.toHaveProperty("role");
|
||||
});
|
||||
it.each(["ADMIN", "Admin", "User_PetOwner"])("denies %s assigning superadmin on create", async role => {
|
||||
prisma.user.findUnique.mockResolvedValue(null);
|
||||
await expect(service.createUser({ firstName: "Test", lastName: "Fixture", mobile: "09120000001", role: "SUPER_ADMIN" }, { id: "actor", role })).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(prisma.user.create).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each(["SUPER_ADMIN", "super-admin", "AdminSuper"])("denies ordinary admin escalation to %s", async role => {
|
||||
prisma.user.findUnique.mockResolvedValue({ id: admin.id, role: "Admin" });
|
||||
await expect(service.updateUser(admin.id, { role }, admin)).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(prisma.user.update).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each([{ password: "Fixture-only-123" }, { email: "fixture@example.test" }, { mobile: "09120000001" }, { role: "Admin" }, { walletBalance: 1 }, { firstName: "Changed" }])("denies ordinary admin editing superadmin", async dto => {
|
||||
await expect(service.updateUser("target-fixture", dto, admin)).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(prisma.user.update).not.toHaveBeenCalled();
|
||||
});
|
||||
it("denies alternate role endpoint revocation", async () => {
|
||||
await expect(service.updateUserRole("target-fixture", "Admin", admin)).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(prisma.user.update).not.toHaveBeenCalled();
|
||||
});
|
||||
it("denies deleting superadmin", async () => {
|
||||
await expect(service.deleteUser("target-fixture", admin)).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(prisma.$transaction).not.toHaveBeenCalled();
|
||||
});
|
||||
it("denies changing superadmin wallet", async () => {
|
||||
await expect(service.adjustUserWallet("target-fixture", 1, "deposit", "fixture", admin)).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(prisma.walletTransaction.create).not.toHaveBeenCalled();
|
||||
});
|
||||
it("accepts ADMIN alias for ordinary CRUD and authorized promotion/revocation", async () => {
|
||||
prisma.user.findUnique.mockResolvedValue({ id: "target-fixture", role: "User_PetOwner" });
|
||||
await service.updateUser("target-fixture", { role: "ADMIN" }, admin);
|
||||
await service.updateUser("target-fixture", { role: "SUPER_ADMIN" }, owner);
|
||||
prisma.user.findUnique.mockResolvedValue({ id: "target-fixture", role: "SUPER_ADMIN" });
|
||||
await service.updateUserRole("target-fixture", "Admin", owner);
|
||||
expect(prisma.user.update).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
it("fails closed without authenticated actor or with API key superadmin", async () => {
|
||||
await expect(service.updateUser("target-fixture", { role: "Admin" })).rejects.toBeInstanceOf(ForbiddenException);
|
||||
await expect(service.updateUser("target-fixture", { role: "Admin" }, { ...owner, isApiKey: true })).rejects.toBeInstanceOf(ForbiddenException);
|
||||
});
|
||||
it("controller forwards authenticated request identity, not DTO identity", async () => {
|
||||
const svc = { updateUser: jest.fn().mockResolvedValue({}) };
|
||||
const controller: any = new AdminController(svc as never, {} as never);
|
||||
const dto = { firstName: "Test" };
|
||||
await controller.updateUser("target-fixture", dto, { user: admin });
|
||||
expect(svc.updateUser).toHaveBeenCalledWith("target-fixture", dto, admin);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
import { Test } from "@nestjs/testing";
|
||||
import { ExecutionContext } from "@nestjs/common";
|
||||
import { firstValueFrom, of } from "rxjs";
|
||||
import { AdminService } from "./admin.service";
|
||||
import { AdminController } from "./admin.controller";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
import { RedisService } from "../redis/redis.service";
|
||||
import { RevalidationService } from "../common/revalidation/revalidation.service";
|
||||
import { DecimalInterceptor } from "../common/interceptors/decimal.interceptor";
|
||||
import { Prisma } from "@prisma/client";
|
||||
|
||||
describe("admin users list contract", () => {
|
||||
const prisma = { user: { findMany: jest.fn(), count: jest.fn() } };
|
||||
let service: AdminService;
|
||||
|
||||
beforeEach(async () => {
|
||||
jest.clearAllMocks();
|
||||
const module = await Test.createTestingModule({
|
||||
providers: [
|
||||
AdminService,
|
||||
{ provide: PrismaService, useValue: prisma },
|
||||
{ provide: RedisService, useValue: {} },
|
||||
{ provide: RevalidationService, useValue: {} },
|
||||
],
|
||||
}).compile();
|
||||
service = module.get(AdminService);
|
||||
});
|
||||
|
||||
it("returns only allowlisted list fields with aggregates through the controller and decimal interceptor", async () => {
|
||||
// Deliberately return extra fields even if the query selects safely.
|
||||
prisma.user.findMany.mockResolvedValue([{
|
||||
id: "fixture-user", firstName: "Fixture", lastName: "User",
|
||||
mobile: "fixture-mobile", email: null, role: "ADMIN",
|
||||
walletBalance: new Prisma.Decimal(0), charityDonationTotal: new Prisma.Decimal(12),
|
||||
createdAt: new Date("2026-01-01T00:00:00Z"),
|
||||
password: "test-only-password-hash", passwordHash: "test-only-hash",
|
||||
refreshToken: "test-only-token", futureSecret: "must-not-leak",
|
||||
walletTransactions: [{ transactionReference: "private-reference" }],
|
||||
addresses: [], orders: [{ totalAmount: new Prisma.Decimal(100) }, { totalAmount: 25 }],
|
||||
_count: { orders: 3, reviews: 2, blogComments: 1, pets: 4 },
|
||||
}]);
|
||||
prisma.user.count.mockResolvedValue(11);
|
||||
const controller = new AdminController(service, {} as never);
|
||||
const result = await controller.getUsers({ page: 2, limit: 10 });
|
||||
const body = await firstValueFrom(new DecimalInterceptor().intercept({} as ExecutionContext, { handle: () => of(result) }));
|
||||
expect(body).toEqual({
|
||||
data: [{
|
||||
id: "fixture-user", firstName: "Fixture", lastName: "User", mobile: "fixture-mobile",
|
||||
email: null, role: "ADMIN", walletBalance: "0", charityDonationTotal: "12",
|
||||
createdAt: new Date("2026-01-01T00:00:00Z"), addresses: [],
|
||||
totalSpent: 125, ordersCount: 3, reviewsCount: 3, petsCount: 4,
|
||||
}],
|
||||
meta: { total: 11, page: 2, limit: 10, lastPage: 2 },
|
||||
});
|
||||
const query = prisma.user.findMany.mock.calls[0][0];
|
||||
expect(query.select).toBeDefined();
|
||||
expect(query.select.password).toBeUndefined();
|
||||
expect(query.include).toBeUndefined();
|
||||
expect(query.skip).toBe(10);
|
||||
});
|
||||
|
||||
it("preserves the empty paginated list contract and filters", async () => {
|
||||
prisma.user.findMany.mockResolvedValue([]);
|
||||
prisma.user.count.mockResolvedValue(0);
|
||||
expect(await service.getUsers({ search: "fixture", role: "ADMIN" })).toEqual({
|
||||
data: [], meta: { total: 0, page: 1, limit: 10, lastPage: 1 },
|
||||
});
|
||||
expect(prisma.user.findMany).toHaveBeenCalledWith(expect.objectContaining({
|
||||
where: expect.objectContaining({ role: "ADMIN", OR: expect.any(Array) }),
|
||||
}));
|
||||
});
|
||||
});
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
Body,
|
||||
Param,
|
||||
Query,
|
||||
Req,
|
||||
UseGuards,
|
||||
BadRequestException,
|
||||
} from "@nestjs/common";
|
||||
@@ -27,6 +28,7 @@ import {
|
||||
} from "@nestjs/swagger";
|
||||
|
||||
import { CreateUserDto, UpdateUserDto } from "./dto/user.dto";
|
||||
import type { UserAdminActor } from "./user-role-policy";
|
||||
import { SettingsService } from "../settings/settings.service";
|
||||
|
||||
import { RolesGuard } from "../common/guards/roles.guard";
|
||||
@@ -57,13 +59,13 @@ export class AdminController {
|
||||
@ApiQuery({ name: "search", required: false, description: "جستجو" })
|
||||
async getUsers(@Query() query: AdminQueryDto) {
|
||||
const result = await this.adminService.getUsers(query);
|
||||
return { success: true, ...result };
|
||||
return result;
|
||||
}
|
||||
|
||||
@Post("users")
|
||||
@ApiOperation({ summary: "ایجاد کاربر جدید توسط ادمین" })
|
||||
async createUser(@Body() dto: CreateUserDto) {
|
||||
const user = await this.adminService.createUser(dto);
|
||||
async createUser(@Body() dto: CreateUserDto, @Req() req?: { user?: UserAdminActor }) {
|
||||
const user = await this.adminService.createUser(dto, req?.user);
|
||||
return {
|
||||
success: true,
|
||||
message: "کاربر جدید با موفقیت ایجاد شد",
|
||||
@@ -80,8 +82,8 @@ export class AdminController {
|
||||
|
||||
@Put("users/:id")
|
||||
@ApiOperation({ summary: "ویرایش مشخصات کامل کاربر" })
|
||||
async updateUser(@Param("id") id: string, @Body() dto: UpdateUserDto) {
|
||||
const user = await this.adminService.updateUser(id, dto);
|
||||
async updateUser(@Param("id") id: string, @Body() dto: UpdateUserDto, @Req() req?: { user?: UserAdminActor }) {
|
||||
const user = await this.adminService.updateUser(id, dto, req?.user);
|
||||
return {
|
||||
success: true,
|
||||
message: "اطلاعات کاربر با موفقیت ویرایش شد",
|
||||
@@ -91,8 +93,8 @@ export class AdminController {
|
||||
|
||||
@Delete("users/:id")
|
||||
@ApiOperation({ summary: "حذف کاربر و دادههای مرتبط" })
|
||||
async deleteUser(@Param("id") id: string) {
|
||||
await this.adminService.deleteUser(id);
|
||||
async deleteUser(@Param("id") id: string, @Req() req?: { user?: UserAdminActor }) {
|
||||
await this.adminService.deleteUser(id, req?.user);
|
||||
return {
|
||||
success: true,
|
||||
message: "کاربر با موفقیت از سیستم حذف شد",
|
||||
@@ -101,8 +103,8 @@ export class AdminController {
|
||||
|
||||
@Put("users/:id/role")
|
||||
@ApiOperation({ summary: "تغییر نقش کاربر" })
|
||||
async updateUserRole(@Param("id") id: string, @Body("role") role: string) {
|
||||
const user = await this.adminService.updateUserRole(id, role);
|
||||
async updateUserRole(@Param("id") id: string, @Body("role") role: string, @Req() req?: { user?: UserAdminActor }) {
|
||||
const user = await this.adminService.updateUserRole(id, role, req?.user);
|
||||
return { success: true, data: user };
|
||||
}
|
||||
|
||||
@@ -113,6 +115,7 @@ export class AdminController {
|
||||
@Body("amount") amount: number,
|
||||
@Body("type") type: "deposit" | "withdrawal" | "refund",
|
||||
@Body("description") description?: string,
|
||||
@Req() req?: { user?: UserAdminActor },
|
||||
) {
|
||||
const numAmount = Number(amount);
|
||||
if (!numAmount || isNaN(numAmount) || numAmount <= 0) {
|
||||
@@ -130,6 +133,7 @@ export class AdminController {
|
||||
numAmount,
|
||||
type,
|
||||
description,
|
||||
req?.user,
|
||||
);
|
||||
return {
|
||||
success: true,
|
||||
@@ -145,7 +149,7 @@ export class AdminController {
|
||||
@ApiQuery({ name: "search", required: false, description: "جستجو" })
|
||||
async getProducts(@Query() query: AdminQueryDto) {
|
||||
const result = await this.adminService.getProducts(query);
|
||||
return { success: true, ...result };
|
||||
return result;
|
||||
}
|
||||
|
||||
@Post("products")
|
||||
@@ -206,7 +210,7 @@ export class AdminController {
|
||||
@ApiQuery({ name: "status", required: false, description: "فیلتر وضعیت" })
|
||||
async getOrders(@Query() query: AdminQueryDto) {
|
||||
const result = await this.adminService.getOrders(query);
|
||||
return { success: true, ...result };
|
||||
return result;
|
||||
}
|
||||
|
||||
@Get("orders/:id")
|
||||
@@ -354,4 +358,34 @@ export class AdminController {
|
||||
await this.settingsService.updateBulkUiTexts(body);
|
||||
return { success: true, data: body };
|
||||
}
|
||||
|
||||
|
||||
@Get("symptoms")
|
||||
@ApiOperation({ summary: "لیست کامل علائم درمانی با صفحهبندی، جستجو و متادیتا" })
|
||||
async getSymptoms(@Query() query: { page?: number; limit?: number; search?: string }) {
|
||||
const res = await this.adminService.getSymptoms(query);
|
||||
return res;
|
||||
}
|
||||
|
||||
@Post("symptoms")
|
||||
@ApiOperation({ summary: "افزودن علامت درمانی جدید" })
|
||||
async createSymptom(@Body() body: { name: string; slug?: string; description?: string; metaTitle?: string; metaDescription?: string; keywords?: string }) {
|
||||
const res = await this.adminService.createSymptom(body);
|
||||
return { success: true, data: res };
|
||||
}
|
||||
|
||||
@Put("symptoms/:id")
|
||||
@ApiOperation({ summary: "ویرایش کامل علامت درمانی و متادیتاهای سئو" })
|
||||
async updateSymptom(@Param("id") id: string, @Body() body: any) {
|
||||
const res = await this.adminService.updateSymptom(id, body);
|
||||
return { success: true, data: res };
|
||||
}
|
||||
|
||||
@Delete("symptoms/:id")
|
||||
@ApiOperation({ summary: "حذف علامت درمانی" })
|
||||
async deleteSymptom(@Param("id") id: string) {
|
||||
const res = await this.adminService.deleteSymptom(id);
|
||||
return res;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -21,12 +21,11 @@ import { CompetitorPricingController } from "./competitor-pricing.controller";
|
||||
import { B2BLeadsController } from "./b2b-leads.controller";
|
||||
import { PricingSuggestionsController } from "./pricing-suggestions.controller";
|
||||
import { SmsCampaignsController } from "./sms-campaigns.controller";
|
||||
import { ApprovalsController } from "./approvals.controller";
|
||||
import { AuditLogsController } from "./audit-logs.controller";
|
||||
import { DepartmentTasksController } from "./department-tasks.controller";
|
||||
import { PrismaModule } from "../prisma/prisma.module";
|
||||
import { RedisModule } from "../redis/redis.module";
|
||||
import { SettingsModule } from "../settings/settings.module";
|
||||
import { SupportChatAnalyticsController } from "./support-chat-analytics.controller";
|
||||
import { SupportChatAnalyticsService } from "./support-chat-analytics.service";
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule, RedisModule, SettingsModule],
|
||||
@@ -44,9 +43,7 @@ import { SettingsModule } from "../settings/settings.module";
|
||||
B2BLeadsController,
|
||||
PricingSuggestionsController,
|
||||
SmsCampaignsController,
|
||||
ApprovalsController,
|
||||
AuditLogsController,
|
||||
DepartmentTasksController,
|
||||
SupportChatAnalyticsController,
|
||||
],
|
||||
providers: [
|
||||
AdminService,
|
||||
@@ -58,6 +55,7 @@ import { SettingsModule } from "../settings/settings.module";
|
||||
PetsService,
|
||||
SslService,
|
||||
ApiKeysService,
|
||||
SupportChatAnalyticsService,
|
||||
],
|
||||
exports: [ApiKeysService, MediaService],
|
||||
})
|
||||
|
||||
@@ -61,15 +61,10 @@ export class CouponInput {
|
||||
targets?: CouponTargetInput[];
|
||||
}
|
||||
|
||||
const ALLOWED_USER_ROLES = [
|
||||
"User_PetOwner",
|
||||
"User_Vet",
|
||||
"User_Clinic",
|
||||
"User_PetShop",
|
||||
"Customer",
|
||||
"Admin",
|
||||
"SUPER_ADMIN",
|
||||
];
|
||||
import { ALLOWED_USER_ROLES, assertUserMutationAllowed } from "./user-role-policy";
|
||||
import type { UserAdminActor } from "./user-role-policy";
|
||||
import { randomUUID } from "crypto";
|
||||
import { authorizeStageSession, STAGE_TEST_ID, STAGE_TEST_EMAIL, STAGE_TEST_MOBILE } from "../auth/stage-test-principal";
|
||||
|
||||
@Injectable()
|
||||
export class AdminService {
|
||||
@@ -168,12 +163,17 @@ export class AdminService {
|
||||
skip,
|
||||
take: limit,
|
||||
orderBy: { [sortField]: sortDirection },
|
||||
include: {
|
||||
select: {
|
||||
id: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
mobile: true,
|
||||
email: true,
|
||||
role: true,
|
||||
walletBalance: true,
|
||||
charityDonationTotal: true,
|
||||
createdAt: true,
|
||||
addresses: true,
|
||||
walletTransactions: {
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 20,
|
||||
},
|
||||
orders: {
|
||||
where: { status: { not: "CANCELLED" } },
|
||||
select: { totalAmount: true },
|
||||
@@ -197,9 +197,19 @@ export class AdminService {
|
||||
(acc, curr) => acc + (Number(curr.totalAmount) || 0),
|
||||
0,
|
||||
) || 0;
|
||||
const { orders: _orders, ...rest } = u;
|
||||
// Explicit response allowlist: never expose authentication fields or
|
||||
// new model columns implicitly through this administrative list.
|
||||
return {
|
||||
...rest,
|
||||
id: u.id,
|
||||
firstName: u.firstName,
|
||||
lastName: u.lastName,
|
||||
mobile: u.mobile,
|
||||
email: u.email,
|
||||
role: u.role,
|
||||
walletBalance: u.walletBalance,
|
||||
charityDonationTotal: u.charityDonationTotal,
|
||||
createdAt: u.createdAt,
|
||||
addresses: u.addresses,
|
||||
totalSpent,
|
||||
ordersCount: u._count?.orders || 0,
|
||||
reviewsCount: (u._count?.reviews || 0) + (u._count?.blogComments || 0),
|
||||
@@ -227,7 +237,12 @@ export class AdminService {
|
||||
return user;
|
||||
}
|
||||
|
||||
async createUser(dto: CreateUserDto) {
|
||||
async createUser(dto: CreateUserDto, actor?: UserAdminActor) {
|
||||
assertUserMutationAllowed(actor, undefined, dto.role);
|
||||
return this.persistUser(dto);
|
||||
}
|
||||
|
||||
private async persistUser(dto: CreateUserDto, stage?: { session: string; expiresAt: Date; generation?: string }) {
|
||||
const mobile = normalizeMobile(dto.mobile);
|
||||
const existingMobile = await this.prisma.user.findUnique({
|
||||
where: { mobile },
|
||||
@@ -260,6 +275,7 @@ export class AdminService {
|
||||
|
||||
return this.prisma.user.create({
|
||||
data: {
|
||||
...(stage ? { id: STAGE_TEST_ID, stageTestGeneration:stage.generation || randomUUID(), stageTestSession: stage.session, authExpiresAt: stage.expiresAt } : {}),
|
||||
firstName: dto.firstName.trim(),
|
||||
lastName: dto.lastName.trim(),
|
||||
mobile,
|
||||
@@ -274,7 +290,30 @@ export class AdminService {
|
||||
});
|
||||
}
|
||||
|
||||
async updateUser(id: string, dto: UpdateUserDto) {
|
||||
// Explicit CI seed authority, NOT a fabricated SUPER_ADMIN actor. Not controller-exposed.
|
||||
async provisionStageTestPrincipal(env: NodeJS.ProcessEnv, sha: string, password: string) {
|
||||
const grant = authorizeStageSession(env, sha);
|
||||
const existing = await this.prisma.user.findFirst({where:{OR:[{id:STAGE_TEST_ID},{email:STAGE_TEST_EMAIL},{mobile:STAGE_TEST_MOBILE}]}});
|
||||
if (existing) {
|
||||
if (existing.id !== STAGE_TEST_ID || existing.email !== STAGE_TEST_EMAIL || existing.mobile !== STAGE_TEST_MOBILE || existing.stageTestSession !== grant.session || (env.STAGE_TEST_GENERATION && existing.stageTestGeneration !== env.STAGE_TEST_GENERATION) || existing.role !== 'SUPER_ADMIN' || !existing.authExpiresAt || existing.authExpiresAt.getTime() <= Date.now() || !await bcrypt.compare(password, existing.password || '')) throw new Error('Refusing existing or unowned principal');
|
||||
return existing; // Never renew TTL on retry.
|
||||
}
|
||||
if (password.length < 32) throw new Error('Server generated secret required');
|
||||
return this.persistUser({firstName:'Stage',lastName:'CI independent reviewer',email:STAGE_TEST_EMAIL,mobile:STAGE_TEST_MOBILE,role:'SUPER_ADMIN',password}, {session:grant.session,expiresAt:new Date(Date.now()+grant.ttl*1000),generation:env.STAGE_TEST_GENERATION});
|
||||
}
|
||||
|
||||
async cleanupStageTestPrincipal(env: NodeJS.ProcessEnv, sha: string, onRevoked: () => void = () => undefined) {
|
||||
const grant = authorizeStageSession(env, sha);
|
||||
const existing = await this.prisma.user.findUnique({where:{id:STAGE_TEST_ID}});
|
||||
if (!existing) { onRevoked(); return; }
|
||||
if (existing.email !== STAGE_TEST_EMAIL || existing.mobile !== STAGE_TEST_MOBILE || existing.stageTestSession !== grant.session || !existing.authExpiresAt || (env.STAGE_TEST_GENERATION && existing.stageTestGeneration !== env.STAGE_TEST_GENERATION)) throw new Error('Refusing unowned principal cleanup');
|
||||
// Revoke before relational cleanup; failed cleanup cannot leave valid tokens.
|
||||
await this.prisma.user.update({where:{id:STAGE_TEST_ID,stageTestSession:grant.session,stageTestGeneration:existing.stageTestGeneration},data:{authExpiresAt:new Date(0),password:''}});
|
||||
onRevoked();
|
||||
return this.deleteUserRecords(STAGE_TEST_ID, {session:grant.session,generation:existing.stageTestGeneration});
|
||||
}
|
||||
|
||||
async updateUser(id: string, dto: UpdateUserDto, actor?: UserAdminActor) {
|
||||
if (id === "12345678-1234-1234-1234-123456789012") {
|
||||
throw new BadRequestException(
|
||||
"امکان ویرایش حساب ادمین پیشفرض وجود ندارد",
|
||||
@@ -286,6 +325,8 @@ export class AdminService {
|
||||
throw new NotFoundException(`کاربری با شناسه ${id} یافت نشد`);
|
||||
}
|
||||
|
||||
assertUserMutationAllowed(actor, user.role, dto.role);
|
||||
|
||||
const normalizedMobile = dto.mobile
|
||||
? normalizeMobile(dto.mobile)
|
||||
: undefined;
|
||||
@@ -340,17 +381,11 @@ export class AdminService {
|
||||
});
|
||||
}
|
||||
|
||||
async updateUserRole(id: string, role: string) {
|
||||
if (!ALLOWED_USER_ROLES.includes(role)) {
|
||||
throw new BadRequestException("نقش کاربری مشخص شده نامعتبر است");
|
||||
}
|
||||
return this.prisma.user.update({
|
||||
where: { id },
|
||||
data: { role },
|
||||
});
|
||||
async updateUserRole(id: string, role: string, actor?: UserAdminActor) {
|
||||
return this.updateUser(id, { role }, actor);
|
||||
}
|
||||
|
||||
async deleteUser(id: string) {
|
||||
async deleteUser(id: string, actor?: UserAdminActor) {
|
||||
if (id === "12345678-1234-1234-1234-123456789012") {
|
||||
throw new BadRequestException("امکان حذف حساب ادمین پیشفرض وجود ندارد");
|
||||
}
|
||||
@@ -360,7 +395,17 @@ export class AdminService {
|
||||
throw new NotFoundException(`کاربری با شناسه ${id} یافت نشد`);
|
||||
}
|
||||
|
||||
assertUserMutationAllowed(actor, user.role);
|
||||
|
||||
return this.deleteUserRecords(id);
|
||||
}
|
||||
|
||||
private async deleteUserRecords(id: string, stage?: {session:string; generation:string|null}) {
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
if (stage) {
|
||||
// Acquire the row lock with an exact fence before deleting any related rows.
|
||||
await tx.user.update({where:{id,stageTestSession:stage.session,stageTestGeneration:stage.generation},data:{authExpiresAt:new Date(0),password:''}});
|
||||
}
|
||||
await tx.userAddress.deleteMany({ where: { userId: id } });
|
||||
await tx.walletTransaction.deleteMany({ where: { userId: id } });
|
||||
await tx.pet.deleteMany({ where: { userId: id } });
|
||||
@@ -1397,12 +1442,15 @@ export class AdminService {
|
||||
amount: number,
|
||||
type: "deposit" | "withdrawal" | "refund",
|
||||
description?: string,
|
||||
actor?: UserAdminActor,
|
||||
) {
|
||||
const user = await this.prisma.user.findUnique({ where: { id: userId } });
|
||||
if (!user) {
|
||||
throw new NotFoundException(`کاربری با شناسه ${userId} یافت نشد.`);
|
||||
}
|
||||
|
||||
assertUserMutationAllowed(actor, user.role);
|
||||
|
||||
const transaction = await this.prisma.walletTransaction.create({
|
||||
data: {
|
||||
userId,
|
||||
@@ -1869,4 +1917,164 @@ export class AdminService {
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
async getSymptoms(params?: { page?: number; limit?: number; search?: string }) {
|
||||
const page = Math.max(1, Number(params?.page) || 1);
|
||||
const limit = Math.max(1, Number(params?.limit) || 20);
|
||||
const offset = (page - 1) * limit;
|
||||
const search = params?.search?.trim() || '';
|
||||
|
||||
let items: any[] = [];
|
||||
let total = 0;
|
||||
|
||||
if (search) {
|
||||
const searchPattern = `%${search}%`;
|
||||
const [listResult, countResult] = await Promise.all([
|
||||
this.prisma.$queryRaw<any[]>`
|
||||
SELECT
|
||||
s.id,
|
||||
s.name,
|
||||
s.slug,
|
||||
s.description,
|
||||
s.meta_title as "metaTitle",
|
||||
s.meta_description as "metaDescription",
|
||||
s.keywords,
|
||||
s.icon,
|
||||
s.created_at as "createdAt",
|
||||
COALESCE(COUNT(ps.product_id), 0)::int as "productsCount"
|
||||
FROM symptoms s
|
||||
LEFT JOIN product_symptoms ps ON ps.symptom = s.name
|
||||
WHERE s.name ILIKE ${searchPattern} OR s.slug ILIKE ${searchPattern}
|
||||
GROUP BY s.id, s.name, s.slug, s.description, s.meta_title, s.meta_description, s.keywords, s.icon, s.created_at
|
||||
ORDER BY s.name ASC
|
||||
LIMIT ${limit} OFFSET ${offset};
|
||||
`,
|
||||
this.prisma.$queryRaw<any[]>`
|
||||
SELECT COUNT(*)::int as total
|
||||
FROM symptoms s
|
||||
WHERE s.name ILIKE ${searchPattern} OR s.slug ILIKE ${searchPattern};
|
||||
`,
|
||||
]);
|
||||
items = listResult;
|
||||
total = countResult[0]?.total || 0;
|
||||
} else {
|
||||
const [listResult, countResult] = await Promise.all([
|
||||
this.prisma.$queryRaw<any[]>`
|
||||
SELECT
|
||||
s.id,
|
||||
s.name,
|
||||
s.slug,
|
||||
s.description,
|
||||
s.meta_title as "metaTitle",
|
||||
s.meta_description as "metaDescription",
|
||||
s.keywords,
|
||||
s.icon,
|
||||
s.created_at as "createdAt",
|
||||
COALESCE(COUNT(ps.product_id), 0)::int as "productsCount"
|
||||
FROM symptoms s
|
||||
LEFT JOIN product_symptoms ps ON ps.symptom = s.name
|
||||
GROUP BY s.id, s.name, s.slug, s.description, s.meta_title, s.meta_description, s.keywords, s.icon, s.created_at
|
||||
ORDER BY s.name ASC
|
||||
LIMIT ${limit} OFFSET ${offset};
|
||||
`,
|
||||
this.prisma.$queryRaw<any[]>`
|
||||
SELECT COUNT(*)::int as total
|
||||
FROM symptoms s;
|
||||
`,
|
||||
]);
|
||||
items = listResult;
|
||||
total = countResult[0]?.total || 0;
|
||||
}
|
||||
|
||||
const lastPage = Math.ceil(total / limit) || 1;
|
||||
|
||||
return {
|
||||
data: items,
|
||||
meta: {
|
||||
page,
|
||||
limit,
|
||||
total,
|
||||
lastPage,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async createSymptom(dto: { name: string; slug?: string; description?: string; metaTitle?: string; metaDescription?: string; keywords?: string }) {
|
||||
if (!dto.name?.trim()) throw new BadRequestException('نام علامت الزامی است');
|
||||
const name = dto.name.trim();
|
||||
const slug = dto.slug?.trim() || name.replace(/\s+/g, '-').toLowerCase();
|
||||
|
||||
return await this.prisma.$queryRawUnsafe(`
|
||||
INSERT INTO symptoms (name, slug, description, meta_title, meta_description, keywords)
|
||||
VALUES ($1, $2, $3, $4, $5, $6)
|
||||
RETURNING id, name, slug, description, meta_title as "metaTitle", meta_description as "metaDescription", keywords;
|
||||
`, name, slug, dto.description || '', dto.metaTitle || '', dto.metaDescription || '', dto.keywords || '');
|
||||
}
|
||||
|
||||
async updateSymptom(id: string, dto: { name?: string; slug?: string; description?: string; metaTitle?: string; metaDescription?: string; keywords?: string }) {
|
||||
// 1. Get existing symptom
|
||||
const existing = await this.prisma.$queryRawUnsafe<any[]>(`SELECT * FROM symptoms WHERE id = $1::uuid LIMIT 1`, id);
|
||||
if (!existing || existing.length === 0) throw new NotFoundException('علامت یافت نشد');
|
||||
const oldName = existing[0].name;
|
||||
const newName = dto.name?.trim() || oldName;
|
||||
const newSlug = dto.slug?.trim() || existing[0].slug;
|
||||
|
||||
return await this.prisma.$transaction(async (tx) => {
|
||||
// Update symptoms table
|
||||
const updated = await tx.$queryRawUnsafe(`
|
||||
UPDATE symptoms
|
||||
SET
|
||||
name = $2,
|
||||
slug = $3,
|
||||
description = $4,
|
||||
meta_title = $5,
|
||||
meta_description = $6,
|
||||
keywords = $7,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = $1::uuid
|
||||
RETURNING id, name, slug, description, meta_title as "metaTitle", meta_description as "metaDescription", keywords;
|
||||
`, id, newName, newSlug, dto.description ?? existing[0].description, dto.metaTitle ?? existing[0].meta_title, dto.metaDescription ?? existing[0].meta_description, dto.keywords ?? existing[0].keywords);
|
||||
|
||||
// If name changed, cascade update across product_symptoms & products JSON
|
||||
if (oldName !== newName) {
|
||||
await tx.$executeRaw`UPDATE product_symptoms SET symptom = ${newName} WHERE symptom = ${oldName};`;
|
||||
await tx.$executeRaw`
|
||||
UPDATE products
|
||||
SET dosage_config = jsonb_set(
|
||||
dosage_config,
|
||||
'{symptoms}',
|
||||
(
|
||||
SELECT jsonb_agg(
|
||||
CASE
|
||||
WHEN elem::text = to_jsonb(${oldName}::text)::text THEN to_jsonb(${newName}::text)
|
||||
ELSE elem
|
||||
END
|
||||
)
|
||||
FROM jsonb_array_elements(dosage_config->'symptoms') AS elem
|
||||
)
|
||||
)
|
||||
WHERE dosage_config ? 'symptoms'
|
||||
AND dosage_config->'symptoms' @> to_jsonb(${oldName}::text);
|
||||
`;
|
||||
}
|
||||
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
|
||||
async deleteSymptom(id: string) {
|
||||
const existing = await this.prisma.$queryRawUnsafe<any[]>(`SELECT * FROM symptoms WHERE id = $1::uuid LIMIT 1`, id);
|
||||
if (!existing || existing.length === 0) throw new NotFoundException('علامت یافت نشد');
|
||||
const name = existing[0].name;
|
||||
|
||||
return await this.prisma.$transaction(async (tx) => {
|
||||
// Delete join links
|
||||
await tx.$executeRaw`DELETE FROM product_symptoms WHERE symptom = ${name};`;
|
||||
// Delete symptom row
|
||||
await tx.$queryRawUnsafe(`DELETE FROM symptoms WHERE id = $1::uuid;`, id);
|
||||
return { success: true, message: `علامت «${name}» با موفقیت حذف شد` };
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,176 +0,0 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Put,
|
||||
Delete,
|
||||
Body,
|
||||
Param,
|
||||
Query,
|
||||
UseGuards,
|
||||
NotFoundException,
|
||||
BadRequestException,
|
||||
} from "@nestjs/common";
|
||||
import { ApiTags, ApiBearerAuth, ApiOperation } from "@nestjs/swagger";
|
||||
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
|
||||
import { RolesGuard } from "../common/guards/roles.guard";
|
||||
import { Roles } from "../common/decorators/roles.decorator";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
import {
|
||||
CreateApprovalRequestDto,
|
||||
DecideApprovalDto,
|
||||
QueryApprovalDto,
|
||||
} from "./dto/approval-request.dto";
|
||||
|
||||
@ApiTags("Admin - CEO Approvals & Governance")
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles("Admin", "SUPER_ADMIN")
|
||||
@Controller("admin/approvals")
|
||||
export class ApprovalsController {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: "لیست موارد کارتابل تاییدات مدیریت" })
|
||||
async findAll(@Query() query: QueryApprovalDto) {
|
||||
const page = Number(query.page) || 1;
|
||||
const limit = Number(query.limit) || 100;
|
||||
const skip = (page - 1) * limit;
|
||||
|
||||
const where: any = {};
|
||||
if (query.department) where.department = query.department;
|
||||
if (query.category) where.category = query.category;
|
||||
if (query.status) where.status = query.status;
|
||||
|
||||
const [total, items, pendingCount] = await Promise.all([
|
||||
(this.prisma as any).approvalRequest.count({ where }),
|
||||
(this.prisma as any).approvalRequest.findMany({
|
||||
where,
|
||||
skip,
|
||||
take: limit,
|
||||
orderBy: { createdAt: "desc" },
|
||||
}),
|
||||
(this.prisma as any).approvalRequest.count({
|
||||
where: { status: "PENDING" },
|
||||
}),
|
||||
]);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: items,
|
||||
meta: {
|
||||
total,
|
||||
page,
|
||||
limit,
|
||||
totalPages: Math.ceil(total / limit),
|
||||
pendingCount,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@Get(":id")
|
||||
@ApiOperation({ summary: "دریافت جزییات یک آیتم کارتابل" })
|
||||
async findOne(@Param("id") id: string) {
|
||||
const item = await (this.prisma as any).approvalRequest.findUnique({
|
||||
where: { id },
|
||||
});
|
||||
if (!item) {
|
||||
throw new NotFoundException(`Approval request ${id} not found`);
|
||||
}
|
||||
return { success: true, data: item };
|
||||
}
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: "ثبت آیتم جدید جهت تایید مدیریت (از طرف سیستم یا دپارتمانها)" })
|
||||
async create(@Body() dto: CreateApprovalRequestDto) {
|
||||
const item = await (this.prisma as any).approvalRequest.create({
|
||||
data: {
|
||||
department: dto.department,
|
||||
category: dto.category,
|
||||
title: dto.title,
|
||||
payload: dto.payload,
|
||||
testContext: dto.testContext || {},
|
||||
status: "PENDING",
|
||||
},
|
||||
});
|
||||
return { success: true, data: item };
|
||||
}
|
||||
|
||||
@Post(":id/test")
|
||||
@ApiOperation({ summary: "اجرای شبیهسازی تست زنده برای آیتم کارتابل" })
|
||||
async runTestSimulation(@Param("id") id: string) {
|
||||
const item = await (this.prisma as any).approvalRequest.findUnique({
|
||||
where: { id },
|
||||
});
|
||||
if (!item) {
|
||||
throw new NotFoundException(`Approval request ${id} not found`);
|
||||
}
|
||||
|
||||
// شبیهسازی بسته به دستهبندی
|
||||
let testResult: any = { status: "SIMULATION_SUCCESS" };
|
||||
if (item.category === "PRICING") {
|
||||
const payload = item.payload as any;
|
||||
testResult = {
|
||||
impact: "Price change simulation",
|
||||
currentPrice: payload.currentPrice,
|
||||
newPrice: payload.newPrice,
|
||||
marginDiff: payload.newPrice && payload.buyPrice
|
||||
? (((payload.newPrice - payload.buyPrice) / payload.newPrice) * 100).toFixed(1) + "%"
|
||||
: "N/A",
|
||||
torobFeedReflectEstimate: "< 5 seconds",
|
||||
};
|
||||
} else if (item.category === "PURCHASE_ORDER") {
|
||||
const payload = item.payload as any;
|
||||
testResult = {
|
||||
document: "PO Pre-check",
|
||||
itemsCount: payload.items ? payload.items.length : 1,
|
||||
totalEstimatedCost: payload.totalCost || "محاسبه بر اساس نرخ خرید",
|
||||
fulfillmentCapacity: "انبار آماده پذیرش",
|
||||
};
|
||||
} else {
|
||||
testResult = {
|
||||
executionSafe: true,
|
||||
summary: "تست سلامت اولیه و اعتبارسنجی مقادیر با موفقیت انجام شد.",
|
||||
};
|
||||
}
|
||||
|
||||
return { success: true, testResult };
|
||||
}
|
||||
|
||||
@Put(":id/decide")
|
||||
@ApiOperation({ summary: "تصمیمگیری مدیرعامل (تایید یا رد همراه با یادداشت)" })
|
||||
async decide(@Param("id") id: string, @Body() dto: DecideApprovalDto) {
|
||||
if (!["APPROVED", "REJECTED"].includes(dto.decision)) {
|
||||
throw new BadRequestException("Decision must be either APPROVED or REJECTED");
|
||||
}
|
||||
|
||||
const item = await (this.prisma as any).approvalRequest.findUnique({
|
||||
where: { id },
|
||||
});
|
||||
if (!item) {
|
||||
throw new NotFoundException(`Approval request ${id} not found`);
|
||||
}
|
||||
|
||||
const updated = await (this.prisma as any).approvalRequest.update({
|
||||
where: { id },
|
||||
data: {
|
||||
status: dto.decision,
|
||||
ceoNotes: dto.ceoNotes || null,
|
||||
executedAt: dto.decision === "APPROVED" ? new Date() : null,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: dto.decision === "APPROVED" ? "درخواست با موفقیت تایید شد." : "درخواست رد شد.",
|
||||
data: updated,
|
||||
};
|
||||
}
|
||||
|
||||
@Delete(":id")
|
||||
@ApiOperation({ summary: "حذف آیتم از کارتابل" })
|
||||
async remove(@Param("id") id: string) {
|
||||
await (this.prisma as any).approvalRequest.delete({ where: { id } });
|
||||
return { success: true, message: "Deleted successfully" };
|
||||
}
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Body,
|
||||
Query,
|
||||
UseGuards,
|
||||
Param,
|
||||
} from "@nestjs/common";
|
||||
import { ApiTags, ApiBearerAuth, ApiOperation } from "@nestjs/swagger";
|
||||
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
|
||||
import { RolesGuard } from "../common/guards/roles.guard";
|
||||
import { Roles } from "../common/decorators/roles.decorator";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
|
||||
@ApiTags("Admin - System Audit & History")
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles("Admin", "SUPER_ADMIN")
|
||||
@Controller("admin/audit-logs")
|
||||
export class AuditLogsController {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: "لیست لاگهای تغییرات دیتابیس و سیستم" })
|
||||
async findAll(@Query() query: any) {
|
||||
const page = Number(query.page) || 1;
|
||||
const limit = Number(query.limit) || 30;
|
||||
const skip = (page - 1) * limit;
|
||||
|
||||
const where: any = {};
|
||||
if (query.entity) where.entity = query.entity;
|
||||
if (query.action) where.action = query.action;
|
||||
if (query.department) where.department = query.department;
|
||||
if (query.search) {
|
||||
where.OR = [
|
||||
{ summary: { contains: query.search, mode: "insensitive" } },
|
||||
{ actor: { contains: query.search, mode: "insensitive" } },
|
||||
{ entityId: { contains: query.search, mode: "insensitive" } },
|
||||
];
|
||||
}
|
||||
|
||||
const [total, items] = await Promise.all([
|
||||
(this.prisma as any).auditLog.count({ where }),
|
||||
(this.prisma as any).auditLog.findMany({
|
||||
where,
|
||||
skip,
|
||||
take: limit,
|
||||
orderBy: { createdAt: "desc" },
|
||||
}),
|
||||
]);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: items,
|
||||
meta: {
|
||||
total,
|
||||
page,
|
||||
limit,
|
||||
totalPages: Math.ceil(total / limit),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@Get("recent")
|
||||
@ApiOperation({ summary: "آخرین رخدادهای سیستم برای ویجت داشبورد" })
|
||||
async getRecent(@Query("limit") limitParam?: string) {
|
||||
const limit = Number(limitParam) || 10;
|
||||
const items = await (this.prisma as any).auditLog.findMany({
|
||||
take: limit,
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
return { success: true, data: items };
|
||||
}
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: "ثبت لاگ جدید در تاریخچه سیستم" })
|
||||
async create(@Body() body: any) {
|
||||
const item = await (this.prisma as any).auditLog.create({
|
||||
data: {
|
||||
entity: body.entity,
|
||||
entityId: body.entityId ? String(body.entityId) : null,
|
||||
action: body.action || "UPDATE",
|
||||
department: body.department || "system",
|
||||
actor: body.actor || "ADMIN",
|
||||
summary: body.summary,
|
||||
oldValues: body.oldValues || null,
|
||||
newValues: body.newValues || null,
|
||||
metadata: body.metadata || null,
|
||||
},
|
||||
});
|
||||
return { success: true, data: item };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import { BadRequestException, ConflictException, NotFoundException } from "@nestjs/common";
|
||||
import { BlogsService } from "./blogs.service";
|
||||
|
||||
// Stateful transactional double: deliberately interleave after snapshot read.
|
||||
// Complements the DB integration test; it does not assert PostgreSQL locking.
|
||||
describe("BlogsService atomic optimistic update", () => {
|
||||
const token = "2026-10-24T23:36:08.501Z";
|
||||
let row: any;
|
||||
let service: BlogsService;
|
||||
let prisma: any;
|
||||
let revalidate: jest.Mock;
|
||||
let afterRead: (() => void) | undefined;
|
||||
let failRelations: boolean;
|
||||
beforeEach(() => {
|
||||
row = { id: "b1", slug: "post", title: "Original", updatedAt: new Date(token), tags: ["old"] };
|
||||
afterRead = undefined;
|
||||
failRelations = false;
|
||||
const blog = {
|
||||
findUnique: jest.fn(async () => {
|
||||
const snapshot = { ...row };
|
||||
afterRead?.();
|
||||
return snapshot;
|
||||
}),
|
||||
updateMany: jest.fn(async ({ where, data }) => {
|
||||
if (row.updatedAt >= where.updatedAt.gte && row.updatedAt < where.updatedAt.lt) {
|
||||
row = { ...row, ...data };
|
||||
return { count: 1 };
|
||||
}
|
||||
return { count: 0 };
|
||||
}),
|
||||
update: jest.fn(async ({ data }) => {
|
||||
if (failRelations) throw new Error("relation failure");
|
||||
row = { ...row, ...data };
|
||||
return { ...row };
|
||||
}),
|
||||
};
|
||||
// Serialize transactions like row locks. Rollback restores only transaction writes.
|
||||
let tail = Promise.resolve();
|
||||
prisma = { blog, $transaction: jest.fn((cb) => {
|
||||
const next = tail.then(async () => {
|
||||
const before = { ...row };
|
||||
try { return await cb({ blog }); } catch (error) { row = before; throw error; }
|
||||
});
|
||||
tail = next.catch(() => undefined);
|
||||
return next;
|
||||
}) };
|
||||
revalidate = jest.fn().mockResolvedValue(true);
|
||||
service = new BlogsService(prisma, { revalidateBlog: revalidate } as any);
|
||||
});
|
||||
|
||||
it.each([null, 0, 123, true, {}, [], "", "garbage", "2026-02-30T00:00:00.000Z", "2026-10-24", "2026-10-24T23:36:08.501001Z"])("rejects invalid token %p without mutations", async (value) => {
|
||||
await expect(service.updateBlog("b1", { title: "bad", expectedUpdatedAt: value })).rejects.toBeInstanceOf(ConflictException);
|
||||
expect(prisma.blog.update).not.toHaveBeenCalled();
|
||||
expect(prisma.blog.updateMany).not.toHaveBeenCalled();
|
||||
expect(revalidate).not.toHaveBeenCalled();
|
||||
});
|
||||
it("rejects stale token and leaves all relations untouched", async () => {
|
||||
await expect(service.updateBlog("b1", { expectedUpdatedAt: "2026-10-20T00:00:00.000Z", tagNames: ["new"], categoryId: "c" })).rejects.toBeInstanceOf(ConflictException);
|
||||
expect(row.tags).toEqual(["old"]);
|
||||
expect(prisma.blog.update).not.toHaveBeenCalled();
|
||||
expect(revalidate).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each([token, "2026-10-25T01:36:08.501+02:00"])("accepts current token %s and atomically includes relations", async (expectedUpdatedAt) => {
|
||||
const result = await service.updateBlog("b1", { title: "new", expectedUpdatedAt, authorId: "a", categoryId: "c", tagNames: ["new"] });
|
||||
expect(result.title).toBe("new");
|
||||
expect(prisma.$transaction).toHaveBeenCalledTimes(1);
|
||||
expect(prisma.blog.updateMany).toHaveBeenCalledWith({ where: { id: "b1", updatedAt: { gte: new Date(token), lt: new Date(new Date(token).getTime() + 1) } }, data: { updatedAt: expect.any(Date) } });
|
||||
expect(prisma.blog.update.mock.calls[0][0].data).toMatchObject({ author: { connect: { id: "a" } }, category: { connect: { id: "c" } }, tags: { set: [], connectOrCreate: expect.any(Array) } });
|
||||
expect(prisma.blog.update.mock.calls[0][0].data).not.toHaveProperty("expectedUpdatedAt");
|
||||
expect(result.updatedAt.getTime()).toBeGreaterThan(new Date(token).getTime());
|
||||
expect(revalidate).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it("detects writer interleaving after read before write", async () => {
|
||||
afterRead = () => { row = { ...row, title: "winner", updatedAt: new Date("2026-10-24T23:36:08.502Z"), tags: ["winner"] }; };
|
||||
await expect(service.updateBlog("b1", { expectedUpdatedAt: token, title: "loser", tagNames: ["loser"] })).rejects.toBeInstanceOf(ConflictException);
|
||||
expect(row.title).toBe("winner");
|
||||
expect(row.tags).toEqual(["winner"]);
|
||||
expect(prisma.blog.update).not.toHaveBeenCalled();
|
||||
expect(revalidate).not.toHaveBeenCalled();
|
||||
});
|
||||
it("permits exactly one of two requests sharing a token", async () => {
|
||||
const results = await Promise.allSettled([service.updateBlog("b1", { expectedUpdatedAt: token, title: "a" }), service.updateBlog("b1", { expectedUpdatedAt: token, title: "b" })]);
|
||||
expect(results.filter(r => r.status === "fulfilled")).toHaveLength(1);
|
||||
const rejected = results.find(r => r.status === "rejected") as PromiseRejectedResult;
|
||||
expect(rejected.reason).toBeInstanceOf(ConflictException);
|
||||
expect(revalidate).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it("advances token even when clock is within same millisecond", async () => {
|
||||
jest.useFakeTimers().setSystemTime(new Date(token));
|
||||
try {
|
||||
await service.updateBlog("b1", { expectedUpdatedAt: token, title: "first" });
|
||||
await expect(service.updateBlog("b1", { expectedUpdatedAt: token, title: "second" })).rejects.toBeInstanceOf(ConflictException);
|
||||
} finally { jest.useRealTimers(); }
|
||||
});
|
||||
it("rolls back claim on nested relation failure without invalidating cache", async () => {
|
||||
failRelations = true;
|
||||
await expect(service.updateBlog("b1", { expectedUpdatedAt: token, tagNames: ["new"] })).rejects.toThrow("relation failure");
|
||||
expect(row.updatedAt.toISOString()).toBe(token);
|
||||
expect(row.tags).toEqual(["old"]);
|
||||
expect(revalidate).not.toHaveBeenCalled();
|
||||
});
|
||||
it("preserves legacy omission without demanding a token", async () => {
|
||||
await service.updateBlog("b1", { title: "legacy" });
|
||||
expect(row.title).toBe("legacy");
|
||||
expect(prisma.$transaction).not.toHaveBeenCalled();
|
||||
});
|
||||
it("returns 404 for a missing blog", async () => {
|
||||
prisma.blog.findUnique.mockResolvedValue(null);
|
||||
await expect(service.updateBlog("missing", { expectedUpdatedAt: token })).rejects.toBeInstanceOf(NotFoundException);
|
||||
});
|
||||
it("does not fail committed writes if revalidation throws", async () => {
|
||||
revalidate.mockRejectedValue(new Error("cache down"));
|
||||
const result = await service.updateBlog("b1", { expectedUpdatedAt: token, title: "saved" });
|
||||
expect(result.cacheRevalidation).toBe("failed");
|
||||
expect(row.title).toBe("saved");
|
||||
});
|
||||
});
|
||||
@@ -229,6 +229,15 @@ describe("BlogsController (Admin)", () => {
|
||||
expect(result).toEqual({ success: true, data: createdBlog });
|
||||
});
|
||||
|
||||
it("propagates create validation failures", async () => {
|
||||
const req = { user: { id: "admin-user-id" } };
|
||||
const body = { title: "Bad date", contentUpdatedAt: "invalid", createdAt: "2000-01-01" };
|
||||
mockBlogsService.createBlog.mockRejectedValueOnce(new Error("Invalid contentUpdatedAt"));
|
||||
|
||||
await expect(controller.createBlog(body, req)).rejects.toThrow("Invalid contentUpdatedAt");
|
||||
expect(service.createBlog).toHaveBeenCalledWith(body, req.user.id);
|
||||
});
|
||||
|
||||
it("updateBlog should update blog details and return success: true", async () => {
|
||||
const blogId = "blog-10";
|
||||
const body = {
|
||||
@@ -244,6 +253,14 @@ describe("BlogsController (Admin)", () => {
|
||||
expect(result).toEqual({ success: true, data: updatedBlog });
|
||||
});
|
||||
|
||||
it("propagates invalid content timestamp rejection without accepting createdAt", async () => {
|
||||
const body = { contentUpdatedAt: "invalid", createdAt: "2000-01-01" };
|
||||
mockBlogsService.updateBlog.mockRejectedValueOnce(new Error("Invalid contentUpdatedAt"));
|
||||
|
||||
await expect(controller.updateBlog("blog-10", body)).rejects.toThrow("Invalid contentUpdatedAt");
|
||||
expect(service.updateBlog).toHaveBeenCalledWith("blog-10", body);
|
||||
});
|
||||
|
||||
it("deleteBlog should delete blog and return success: true", async () => {
|
||||
const blogId = "blog-10";
|
||||
mockBlogsService.deleteBlog.mockResolvedValue(undefined);
|
||||
|
||||
@@ -54,6 +54,8 @@ describe("Admin BlogsService", () => {
|
||||
}).compile();
|
||||
|
||||
service = module.get<BlogsService>(BlogsService);
|
||||
mockRevalidationService.revalidateBlog.mockReset();
|
||||
mockRevalidationService.revalidateBlog.mockResolvedValue(true);
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
@@ -200,7 +202,54 @@ describe("Admin BlogsService", () => {
|
||||
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith(
|
||||
"new-health-post",
|
||||
);
|
||||
expect(result).toEqual(createdBlog);
|
||||
expect(result).toEqual({
|
||||
...createdBlog,
|
||||
cacheRevalidation: "success",
|
||||
});
|
||||
});
|
||||
|
||||
it("allowlists create fields and blocks server-owned and unknown fields", async () => {
|
||||
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 () => {
|
||||
@@ -228,6 +277,66 @@ describe("Admin BlogsService", () => {
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("should expose cacheRevalidation status on create result without failing persistence", async () => {
|
||||
const blogData = {
|
||||
title: "Health Post",
|
||||
slug: "health-post",
|
||||
content: "Content",
|
||||
};
|
||||
const createdBlog = { id: "blog-1", ...blogData };
|
||||
mockPrisma.blog.create.mockResolvedValue(createdBlog);
|
||||
mockRevalidationService.revalidateBlog.mockResolvedValue(true);
|
||||
|
||||
const result = await service.createBlog(blogData, "user-admin-1");
|
||||
|
||||
expect(mockPrisma.blog.create).toHaveBeenCalled();
|
||||
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith("health-post");
|
||||
expect(result).toEqual({
|
||||
...createdBlog,
|
||||
cacheRevalidation: "success",
|
||||
});
|
||||
});
|
||||
|
||||
it("should return cacheRevalidation 'failed' when revalidation fails without failing persistence", async () => {
|
||||
const blogData = {
|
||||
title: "Health Post",
|
||||
slug: "health-post",
|
||||
content: "Content",
|
||||
};
|
||||
const createdBlog = { id: "blog-1", ...blogData };
|
||||
mockPrisma.blog.create.mockResolvedValue(createdBlog);
|
||||
mockRevalidationService.revalidateBlog.mockResolvedValue(false);
|
||||
|
||||
const result = await service.createBlog(blogData, "user-admin-1");
|
||||
|
||||
expect(mockPrisma.blog.create).toHaveBeenCalled();
|
||||
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith("health-post");
|
||||
expect(result).toEqual({
|
||||
...createdBlog,
|
||||
cacheRevalidation: "failed",
|
||||
});
|
||||
});
|
||||
|
||||
it("should catch unexpected revalidation exceptions on create and return cacheRevalidation 'failed'", async () => {
|
||||
const blogData = {
|
||||
title: "Health Post",
|
||||
slug: "health-post",
|
||||
content: "Content",
|
||||
};
|
||||
const createdBlog = { id: "blog-1", ...blogData };
|
||||
mockPrisma.blog.create.mockResolvedValue(createdBlog);
|
||||
mockRevalidationService.revalidateBlog.mockRejectedValue(new Error("Frontend offline"));
|
||||
|
||||
const result = await service.createBlog(blogData, "user-admin-1");
|
||||
|
||||
expect(mockPrisma.blog.create).toHaveBeenCalled();
|
||||
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith("health-post");
|
||||
expect(result).toEqual({
|
||||
...createdBlog,
|
||||
cacheRevalidation: "failed",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("updateBlog", () => {
|
||||
@@ -270,7 +379,136 @@ describe("Admin BlogsService", () => {
|
||||
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith(
|
||||
"my-post",
|
||||
);
|
||||
expect(result).toEqual(updated);
|
||||
expect(result).toEqual({
|
||||
...updated,
|
||||
cacheRevalidation: "success",
|
||||
});
|
||||
});
|
||||
|
||||
it("should expose cacheRevalidation status on update result without failing persistence", async () => {
|
||||
const existing = { id: "b1", slug: "my-post", title: "Old Title" };
|
||||
mockPrisma.blog.findUnique.mockResolvedValue(existing);
|
||||
const updated = { ...existing, title: "New Title" };
|
||||
mockPrisma.blog.update.mockResolvedValue(updated);
|
||||
mockRevalidationService.revalidateBlog.mockResolvedValue(true);
|
||||
|
||||
const result = await service.updateBlog("b1", { title: "New Title" });
|
||||
|
||||
expect(mockPrisma.blog.update).toHaveBeenCalled();
|
||||
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith("my-post");
|
||||
expect(result).toEqual({
|
||||
...updated,
|
||||
cacheRevalidation: "success",
|
||||
});
|
||||
});
|
||||
|
||||
it("should return cacheRevalidation 'failed' when revalidation fails on update without failing persistence", async () => {
|
||||
const existing = { id: "b1", slug: "my-post", title: "Old Title" };
|
||||
mockPrisma.blog.findUnique.mockResolvedValue(existing);
|
||||
const updated = { ...existing, title: "New Title" };
|
||||
mockPrisma.blog.update.mockResolvedValue(updated);
|
||||
mockRevalidationService.revalidateBlog.mockResolvedValue(false);
|
||||
|
||||
const result = await service.updateBlog("b1", { title: "New Title" });
|
||||
|
||||
expect(mockPrisma.blog.update).toHaveBeenCalled();
|
||||
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith("my-post");
|
||||
expect(result).toEqual({
|
||||
...updated,
|
||||
cacheRevalidation: "failed",
|
||||
});
|
||||
});
|
||||
|
||||
it("should catch unexpected revalidation exceptions on update and return cacheRevalidation 'failed'", async () => {
|
||||
const existing = { id: "b1", slug: "my-post", title: "Old Title" };
|
||||
mockPrisma.blog.findUnique.mockResolvedValue(existing);
|
||||
const updated = { ...existing, title: "New Title" };
|
||||
mockPrisma.blog.update.mockResolvedValue(updated);
|
||||
mockRevalidationService.revalidateBlog.mockRejectedValue(new Error("Revalidation timeout"));
|
||||
|
||||
const result = await service.updateBlog("b1", { title: "New Title" });
|
||||
|
||||
expect(mockPrisma.blog.update).toHaveBeenCalled();
|
||||
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith("my-post");
|
||||
expect(result).toEqual({
|
||||
...updated,
|
||||
cacheRevalidation: "failed",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
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));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -468,7 +706,6 @@ describe("Admin BlogsService", () => {
|
||||
status: "PUBLISHED",
|
||||
isPublished: true,
|
||||
publishedAt: scheduledDate,
|
||||
createdAt: scheduledDate,
|
||||
},
|
||||
});
|
||||
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith(
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
OnModuleInit,
|
||||
@@ -141,16 +143,31 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
|
||||
async createBlog(data: any, currentUserId: string) {
|
||||
const {
|
||||
tags,
|
||||
tagNames,
|
||||
categoryId,
|
||||
authorId,
|
||||
publishedAt,
|
||||
scheduledAt,
|
||||
readingTime,
|
||||
...rest
|
||||
markContentUpdated,
|
||||
contentUpdatedAt,
|
||||
} = data;
|
||||
|
||||
const parseOptionalDate = (value: unknown, field: string): Date | null => {
|
||||
if (value === undefined || value === null || value === "") return null;
|
||||
const parsed = new Date(value as string | number | Date);
|
||||
if (!Number.isFinite(parsed.getTime())) {
|
||||
throw new BadRequestException(`Invalid ${field}`);
|
||||
}
|
||||
return parsed;
|
||||
};
|
||||
|
||||
const parsedPublishedAt = parseOptionalDate(publishedAt, "publishedAt");
|
||||
const parsedScheduledAt = parseOptionalDate(scheduledAt, "scheduledAt");
|
||||
const parsedContentUpdatedAt = markContentUpdated
|
||||
? new Date()
|
||||
: parseOptionalDate(contentUpdatedAt, "contentUpdatedAt");
|
||||
|
||||
// Connect or create tags
|
||||
const tagConnectOrCreate = [];
|
||||
if (Array.isArray(tagNames) && tagNames.length > 0) {
|
||||
@@ -171,13 +188,12 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
|
||||
const targetAuthorId = authorId || currentUserId;
|
||||
const now = new Date();
|
||||
const parsedScheduledAt = scheduledAt ? new Date(scheduledAt) : null;
|
||||
const isFutureSchedule = parsedScheduledAt && parsedScheduledAt > now;
|
||||
|
||||
let finalStatus = rest.status || "PUBLISHED";
|
||||
let finalStatus = data.status || "PUBLISHED";
|
||||
let finalIsPublished =
|
||||
rest.isPublished !== undefined ? rest.isPublished : true;
|
||||
let finalPublishedAt = publishedAt ? new Date(publishedAt) : null;
|
||||
data.isPublished !== undefined ? data.isPublished : true;
|
||||
let finalPublishedAt = parsedPublishedAt;
|
||||
|
||||
if (isFutureSchedule) {
|
||||
finalStatus = "SCHEDULED";
|
||||
@@ -191,19 +207,45 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
finalPublishedAt = now;
|
||||
}
|
||||
|
||||
const createPayload: Prisma.BlogCreateInput = {
|
||||
...rest,
|
||||
const createPayload = {
|
||||
title: data.title,
|
||||
slug: data.slug,
|
||||
content: data.content,
|
||||
excerpt: data.excerpt,
|
||||
authorTeam: data.authorTeam,
|
||||
authorRole: data.authorRole,
|
||||
imageUrl: data.imageUrl,
|
||||
imageAlt: data.imageAlt,
|
||||
imageCaption: data.imageCaption,
|
||||
metaTitle: data.metaTitle,
|
||||
metaDescription: data.metaDescription,
|
||||
keywords: data.keywords,
|
||||
focusKeywords: data.focusKeywords,
|
||||
canonicalUrl: data.canonicalUrl,
|
||||
noIndex: data.noIndex,
|
||||
noFollow: data.noFollow,
|
||||
schemaType: data.schemaType,
|
||||
ogTitle: data.ogTitle,
|
||||
ogDescription: data.ogDescription,
|
||||
ogImage: data.ogImage,
|
||||
status: finalStatus,
|
||||
isPublished: finalIsPublished,
|
||||
readingTime: readingTime ? Number(readingTime) : 3,
|
||||
featured: data.featured,
|
||||
allowComments: data.allowComments,
|
||||
showOnHome: data.showOnHome,
|
||||
homeDisplayMode: data.homeDisplayMode,
|
||||
relatedProductIds: data.relatedProductIds,
|
||||
relatedBlogIds: data.relatedBlogIds,
|
||||
readingTime: readingTime !== undefined ? Number(readingTime) : 3,
|
||||
publishedAt: finalPublishedAt,
|
||||
scheduledAt: parsedScheduledAt,
|
||||
contentUpdatedAt: parsedContentUpdatedAt,
|
||||
author: { connect: { id: targetAuthorId } },
|
||||
...(categoryId ? { category: { connect: { id: categoryId } } } : {}),
|
||||
...(tagConnectOrCreate.length > 0
|
||||
? { tags: { connectOrCreate: tagConnectOrCreate } }
|
||||
: {}),
|
||||
};
|
||||
} satisfies Prisma.BlogCreateInput;
|
||||
|
||||
const created = await this.prisma.blog.create({
|
||||
data: createPayload,
|
||||
@@ -214,8 +256,21 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
},
|
||||
});
|
||||
|
||||
await this.revalidationService.revalidateBlog(created.slug);
|
||||
return created;
|
||||
let cacheRevalidation: "success" | "failed" = "failed";
|
||||
try {
|
||||
const revalidated = await this.revalidationService.revalidateBlog(created.slug);
|
||||
cacheRevalidation = revalidated ? "success" : "failed";
|
||||
} catch (err: any) {
|
||||
this.logger.warn(
|
||||
`Cache revalidation failed for created blog [${created.slug}]: ${err?.message}`,
|
||||
);
|
||||
cacheRevalidation = "failed";
|
||||
}
|
||||
|
||||
return {
|
||||
...created,
|
||||
cacheRevalidation,
|
||||
};
|
||||
}
|
||||
|
||||
async updateBlog(id: string, data: any) {
|
||||
@@ -223,19 +278,105 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
if (!blog) throw new NotFoundException("Blog not found");
|
||||
|
||||
const {
|
||||
tags,
|
||||
tagNames,
|
||||
categoryId,
|
||||
authorId,
|
||||
publishedAt,
|
||||
scheduledAt,
|
||||
readingTime,
|
||||
...rest
|
||||
markContentUpdated,
|
||||
contentUpdatedAt,
|
||||
expectedUpdatedAt,
|
||||
} = data;
|
||||
|
||||
const conflict = () => new ConflictException(
|
||||
"CONCURRENT_MODIFICATION: Blog has been modified by another process",
|
||||
);
|
||||
let expectedTime: number | undefined;
|
||||
if (expectedUpdatedAt !== undefined) {
|
||||
// Only accept the millisecond, timezone-qualified ISO token returned by GET
|
||||
// (or an equivalent offset). Avoid Date's coercion of null, numbers, arrays,
|
||||
// and its normalization of impossible calendar dates.
|
||||
const match = typeof expectedUpdatedAt === "string" && expectedUpdatedAt.match(
|
||||
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?(Z|[+-]\d{2}:\d{2})$/,
|
||||
);
|
||||
if (!match) throw conflict();
|
||||
expectedTime = Date.parse(expectedUpdatedAt);
|
||||
const calendar = new Date(`${match[1]}-${match[2]}-${match[3]}T00:00:00.000Z`);
|
||||
if (!Number.isFinite(expectedTime) ||
|
||||
calendar.toISOString().slice(0, 10) !== `${match[1]}-${match[2]}-${match[3]}` ||
|
||||
Number(match[4]) > 23 || Number(match[5]) > 59 || Number(match[6]) > 59) {
|
||||
throw conflict();
|
||||
}
|
||||
}
|
||||
|
||||
const mutableScalarFields = [
|
||||
"title",
|
||||
"slug",
|
||||
"content",
|
||||
"excerpt",
|
||||
"authorTeam",
|
||||
"authorRole",
|
||||
"imageUrl",
|
||||
"imageAlt",
|
||||
"imageCaption",
|
||||
"metaTitle",
|
||||
"metaDescription",
|
||||
"keywords",
|
||||
"focusKeywords",
|
||||
"canonicalUrl",
|
||||
"noIndex",
|
||||
"noFollow",
|
||||
"schemaType",
|
||||
"ogTitle",
|
||||
"ogDescription",
|
||||
"ogImage",
|
||||
"status",
|
||||
"isPublished",
|
||||
"featured",
|
||||
"allowComments",
|
||||
"showOnHome",
|
||||
"homeDisplayMode",
|
||||
"relatedProductIds",
|
||||
"relatedBlogIds",
|
||||
] as const;
|
||||
const updatePayload: Prisma.BlogUpdateInput = {};
|
||||
for (const field of mutableScalarFields) {
|
||||
if (data[field] !== undefined) {
|
||||
(updatePayload as Record<string, unknown>)[field] = data[field];
|
||||
}
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const updatePayload: Prisma.BlogUpdateInput = {
|
||||
...rest,
|
||||
const materialContentFields = [
|
||||
"title",
|
||||
"content",
|
||||
"excerpt",
|
||||
"imageUrl",
|
||||
"imageAlt",
|
||||
"imageCaption",
|
||||
] as const;
|
||||
const hasMaterialContentChange = materialContentFields.some(
|
||||
(field) => data[field] !== undefined && data[field] !== blog[field],
|
||||
);
|
||||
if (markContentUpdated || (contentUpdatedAt === undefined && hasMaterialContentChange)) {
|
||||
(updatePayload as Record<string, unknown>).contentUpdatedAt = now;
|
||||
} else if (contentUpdatedAt !== undefined) {
|
||||
if (contentUpdatedAt === null || contentUpdatedAt === "") {
|
||||
(updatePayload as Record<string, unknown>).contentUpdatedAt = null;
|
||||
} else {
|
||||
const parsedContentUpdatedAt = new Date(contentUpdatedAt);
|
||||
if (!Number.isFinite(parsedContentUpdatedAt.getTime())) {
|
||||
throw new BadRequestException("Invalid contentUpdatedAt");
|
||||
}
|
||||
(updatePayload as Record<string, unknown>).contentUpdatedAt = parsedContentUpdatedAt;
|
||||
}
|
||||
}
|
||||
|
||||
Object.assign(updatePayload, {
|
||||
...(readingTime !== undefined
|
||||
? { readingTime: Number(readingTime) }
|
||||
: {}),
|
||||
...(readingTime !== undefined
|
||||
? { readingTime: Number(readingTime) }
|
||||
: {}),
|
||||
@@ -245,7 +386,7 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
? { category: { connect: { id: categoryId } } }
|
||||
: { category: { disconnect: true } }
|
||||
: {}),
|
||||
};
|
||||
});
|
||||
|
||||
if (scheduledAt !== undefined) {
|
||||
const parsedScheduledAt = scheduledAt ? new Date(scheduledAt) : null;
|
||||
@@ -259,7 +400,6 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
updatePayload.status = "PUBLISHED";
|
||||
updatePayload.isPublished = true;
|
||||
updatePayload.publishedAt = parsedScheduledAt;
|
||||
updatePayload.createdAt = parsedScheduledAt;
|
||||
}
|
||||
} else if (publishedAt !== undefined) {
|
||||
updatePayload.publishedAt = publishedAt ? new Date(publishedAt) : null;
|
||||
@@ -286,25 +426,68 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
};
|
||||
}
|
||||
|
||||
const updated = await this.prisma.blog.update({
|
||||
where: { id },
|
||||
data: updatePayload,
|
||||
include: {
|
||||
author: { select: { firstName: true, lastName: true } },
|
||||
category: true,
|
||||
tags: true,
|
||||
},
|
||||
});
|
||||
const include = {
|
||||
author: { select: { firstName: true, lastName: true } },
|
||||
category: true,
|
||||
tags: true,
|
||||
};
|
||||
// Legacy UI requests without a token intentionally retain last-write-wins.
|
||||
// Guarded requests claim the row using a DB predicate, not the earlier read.
|
||||
const updated = expectedTime === undefined
|
||||
? await this.prisma.blog.update({ where: { id }, data: updatePayload, include })
|
||||
: await this.prisma.$transaction(async (tx) => {
|
||||
// PostgreSQL timestamptz defaults to microseconds; JSON/JS Dates expose
|
||||
// milliseconds. Match the entire represented millisecond, then move
|
||||
// strictly beyond it (including same-ms writes and clock rollback).
|
||||
const claimedAt = new Date(Math.max(Date.now(), expectedTime + 1));
|
||||
const claim = await tx.blog.updateMany({
|
||||
where: {
|
||||
id,
|
||||
updatedAt: {
|
||||
gte: new Date(expectedTime),
|
||||
lt: new Date(expectedTime + 1),
|
||||
},
|
||||
},
|
||||
data: { updatedAt: claimedAt },
|
||||
});
|
||||
if (claim.count !== 1) throw conflict();
|
||||
// The claim holds the row lock until this nested mutation commits.
|
||||
// Any relation failure rolls back both the claim and all data writes.
|
||||
return tx.blog.update({
|
||||
where: { id },
|
||||
data: { ...updatePayload, updatedAt: claimedAt },
|
||||
include,
|
||||
});
|
||||
});
|
||||
|
||||
await this.revalidationService.revalidateBlog(updated.slug);
|
||||
return updated;
|
||||
let cacheRevalidation: "success" | "failed" = "failed";
|
||||
try {
|
||||
const revalidated = await this.revalidationService.revalidateBlog(updated.slug);
|
||||
cacheRevalidation = revalidated ? "success" : "failed";
|
||||
} catch (err: any) {
|
||||
this.logger.warn(
|
||||
`Cache revalidation failed for updated blog [${updated.slug}]: ${err?.message}`,
|
||||
);
|
||||
cacheRevalidation = "failed";
|
||||
}
|
||||
|
||||
return {
|
||||
...updated,
|
||||
cacheRevalidation,
|
||||
};
|
||||
}
|
||||
|
||||
async deleteBlog(id: string) {
|
||||
const blog = await this.prisma.blog.findUnique({ where: { id } });
|
||||
if (!blog) throw new NotFoundException("Blog not found");
|
||||
const res = await this.prisma.blog.delete({ where: { id } });
|
||||
await this.revalidationService.revalidateBlog(blog.slug);
|
||||
try {
|
||||
await this.revalidationService.revalidateBlog(blog.slug);
|
||||
} catch (err: any) {
|
||||
this.logger.warn(
|
||||
`Cache revalidation failed for deleted blog [${blog.slug}]: ${err?.message}`,
|
||||
);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
@@ -472,7 +655,6 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
status: "PUBLISHED",
|
||||
isPublished: true,
|
||||
publishedAt: publishDate,
|
||||
createdAt: publishDate,
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -1,202 +0,0 @@
|
||||
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> = {
|
||||
BACKLOG: 0,
|
||||
IN_PROGRESS: 0,
|
||||
IN_REVIEW: 0,
|
||||
APPROVED: 0,
|
||||
DEPLOYING: 0,
|
||||
DONE: 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 || "BACKLOG",
|
||||
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();
|
||||
|
||||
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" };
|
||||
}
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsString, IsOptional, IsObject } from "class-validator";
|
||||
|
||||
export class CreateApprovalRequestDto {
|
||||
@ApiProperty({ description: "دپارتمان مبدا (DEV, SUPPLY, FINANCE, SEO, CRM, CONTENT)" })
|
||||
@IsString()
|
||||
department: string;
|
||||
|
||||
@ApiProperty({ description: "دستهبندی (PRICING, PURCHASE_ORDER, CAMPAIGN, DEPLOY, etc)" })
|
||||
@IsString()
|
||||
category: string;
|
||||
|
||||
@ApiProperty({ description: "عنوان مورد تایید" })
|
||||
@IsString()
|
||||
title: string;
|
||||
|
||||
@ApiProperty({ description: "دادههای تغییرات پیشنهادی" })
|
||||
@IsObject()
|
||||
payload: Record<string, any>;
|
||||
|
||||
@ApiPropertyOptional({ description: "دادههای سناریوی تست و ارزیابی" })
|
||||
@IsOptional()
|
||||
@IsObject()
|
||||
testContext?: Record<string, any>;
|
||||
}
|
||||
|
||||
export class DecideApprovalDto {
|
||||
@ApiProperty({ description: "تصمیم: APPROVED یا REJECTED" })
|
||||
@IsString()
|
||||
decision: "APPROVED" | "REJECTED";
|
||||
|
||||
@ApiPropertyOptional({ description: "توضیحات و یادداشت مدیرعامل" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
ceoNotes?: string;
|
||||
}
|
||||
|
||||
export class QueryApprovalDto {
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
department?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
category?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
status?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
page?: number;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
limit?: number;
|
||||
}
|
||||
@@ -5,9 +5,12 @@ import {
|
||||
IsEmail,
|
||||
MinLength,
|
||||
IsNumber,
|
||||
IsIn,
|
||||
} from "class-validator";
|
||||
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||
|
||||
import { ALLOWED_USER_ROLES } from "../user-role-policy";
|
||||
|
||||
export class CreateUserDto {
|
||||
@ApiProperty({ description: "نام کاربر", example: "علی" })
|
||||
@IsNotEmpty({ message: "نام الزامی است" })
|
||||
@@ -41,6 +44,7 @@ export class CreateUserDto {
|
||||
@ApiPropertyOptional({ description: "نقش کاربر", example: "User_PetOwner" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@IsIn(ALLOWED_USER_ROLES)
|
||||
role?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "موجودی اولیه کیف پول", example: 0 })
|
||||
@@ -85,6 +89,7 @@ export class UpdateUserDto {
|
||||
@ApiPropertyOptional({ description: "نقش کاربر", example: "User_PetOwner" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@IsIn(ALLOWED_USER_ROLES)
|
||||
role?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "موجودی کیف پول", example: 500000 })
|
||||
|
||||
@@ -76,7 +76,7 @@ describe("MediaService", () => {
|
||||
|
||||
const validFile = {
|
||||
originalname: "product-cover.webp",
|
||||
buffer: Buffer.from("dummy-image-bytes"),
|
||||
buffer: Buffer.from([0x52, 0x49, 0x46, 0x46, 0x00, 0x00, 0x00, 0x00, 0x57, 0x45, 0x42, 0x50, 0x56, 0x50, 0x38]),
|
||||
mimetype: "image/webp",
|
||||
size: 5000,
|
||||
} as any;
|
||||
|
||||
@@ -79,6 +79,28 @@ export class MediaService {
|
||||
"پسوند فایل ارسالی مجاز نیست (فرمت SVG و فایلهای اجرایی مسدود هستند).",
|
||||
);
|
||||
}
|
||||
|
||||
// SEC-01: Magic number verification for uploaded binary content
|
||||
const buf = file.buffer;
|
||||
if (!buf || buf.length < 4) {
|
||||
throw new BadRequestException("فایل نامعتبر یا آسیبدیده است.");
|
||||
}
|
||||
|
||||
const isJpeg = buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff;
|
||||
const isPng = buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47;
|
||||
const isGif = buf[0] === 0x47 && buf[1] === 0x49 && buf[2] === 0x46; // GIF87a or GIF89a
|
||||
const isPdf = buf[0] === 0x25 && buf[1] === 0x50 && buf[2] === 0x44 && buf[3] === 0x46; // %PDF
|
||||
const isWebp =
|
||||
buf.length >= 12 &&
|
||||
buf[0] === 0x52 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x46 && // RIFF
|
||||
buf[8] === 0x57 && buf[9] === 0x45 && buf[10] === 0x42 && buf[11] === 0x50; // WEBP
|
||||
|
||||
if (!isJpeg && !isPng && !isGif && !isPdf && !isWebp) {
|
||||
throw new BadRequestException(
|
||||
"محتوای باینری فایل با پسوند یا هدر ادعایی همخوانی ندارد (اعتبارسنجی امضای فایل رد شد).",
|
||||
);
|
||||
}
|
||||
|
||||
const filename = `${uniqueSuffix}${ext}`;
|
||||
const filePath = path.join(uploadDir, filename);
|
||||
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import { Controller, Get, Query, 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 { SupportChatAnalyticsService } from "./support-chat-analytics.service";
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles("Admin", "SUPER_ADMIN")
|
||||
@Controller("admin/support-chat")
|
||||
export class SupportChatAnalyticsController {
|
||||
constructor(private readonly analytics: SupportChatAnalyticsService) {}
|
||||
@Get("stats") stats(@Query("startDate") startDate?: string, @Query("endDate") endDate?: string) { return this.analytics.stats(startDate, endDate).then(data => ({ success: true, data })); }
|
||||
@Get("conversations") conversations(@Query("page") page?: string, @Query("limit") limit?: string, @Query("startDate") startDate?: string, @Query("endDate") endDate?: string, @Query("onlyUnanswered") onlyUnanswered?: string) { return this.analytics.conversations(Number(page), Number(limit), startDate, endDate, onlyUnanswered === "true").then(data => ({ success: true, ...data })); }
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
|
||||
@Injectable()
|
||||
export class SupportChatAnalyticsService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async stats(startDate?: string, endDate?: string) {
|
||||
const where = this.range(startDate, endDate);
|
||||
const [conversations, messages, authenticated, unanswered, followup, escalated, topics] = await Promise.all([
|
||||
this.prisma.supportConversation.count({ where }),
|
||||
this.prisma.supportConversationMessage.count({ where: { conversation: where } }),
|
||||
this.prisma.supportConversation.count({ where: { ...where, userId: { not: null } } }),
|
||||
this.prisma.supportConversation.count({ where: { ...where, unanswered: true } }),
|
||||
this.prisma.supportConversation.count({ where: { ...where, needsFollowup: true } }),
|
||||
this.prisma.supportConversation.count({ where: { ...where, escalationSignal: true } }),
|
||||
this.prisma.supportConversation.findMany({ where, select: { topics: true }, take: 5000 }),
|
||||
]);
|
||||
const topicCounts: Record<string, number> = {};
|
||||
for (const row of topics) for (const topic of Array.isArray(row.topics) ? row.topics : []) if (typeof topic === "string") topicCounts[topic] = (topicCounts[topic] || 0) + 1;
|
||||
return { conversations, messages, authenticated, anonymous: conversations - authenticated, unanswered, followup, escalated, topics: topicCounts };
|
||||
}
|
||||
|
||||
async conversations(page = 1, limit = 25, startDate?: string, endDate?: string, onlyUnanswered = false) {
|
||||
const safePage = Math.max(1, Math.min(10000, Number(page) || 1));
|
||||
const safeLimit = Math.max(1, Math.min(100, Number(limit) || 25));
|
||||
const where = { ...this.range(startDate, endDate), ...(onlyUnanswered ? { unanswered: true } : {}) };
|
||||
const [data, total] = await Promise.all([
|
||||
this.prisma.supportConversation.findMany({ where, orderBy: { updatedAt: "desc" }, skip: (safePage - 1) * safeLimit, take: safeLimit, include: { user: { select: { id: true, firstName: true, lastName: true, mobile: true, email: true } }, messages: { orderBy: { sequence: "asc" }, take: 40 } } }),
|
||||
this.prisma.supportConversation.count({ where }),
|
||||
]);
|
||||
return { data, meta: { total, page: safePage, limit: safeLimit, lastPage: Math.ceil(total / safeLimit) } };
|
||||
}
|
||||
|
||||
private range(startDate?: string, endDate?: string) {
|
||||
const createdAt: any = {};
|
||||
if (startDate && /^\d{4}-\d{2}-\d{2}$/.test(startDate)) createdAt.gte = new Date(`${startDate}T00:00:00.000Z`);
|
||||
if (endDate && /^\d{4}-\d{2}-\d{2}$/.test(endDate)) { const end = new Date(`${endDate}T00:00:00.000Z`); end.setUTCDate(end.getUTCDate() + 1); createdAt.lt = end; }
|
||||
return Object.keys(createdAt).length ? { createdAt } : {};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { ForbiddenException } from "@nestjs/common";
|
||||
|
||||
export const ALLOWED_USER_ROLES = [
|
||||
"User_PetOwner", "User_Vet", "User_Clinic", "User_PetShop",
|
||||
"User_Wholesale", "User_B2B", "Customer", "Admin", "ADMIN", "SUPER_ADMIN",
|
||||
];
|
||||
|
||||
export interface UserAdminActor {
|
||||
id?: string;
|
||||
role?: string;
|
||||
isApiKey?: boolean;
|
||||
}
|
||||
|
||||
// Match RolesGuard semantics; keep stored values unchanged.
|
||||
export function isSuperAdminRole(role?: string): boolean {
|
||||
const normalized = typeof role === "string" ? role.toLowerCase().replace(/[_-]/g, "") : "";
|
||||
return normalized === "superadmin" || normalized === "adminsuper";
|
||||
}
|
||||
|
||||
export function assertUserMutationAllowed(actor?: UserAdminActor, currentRole?: string, nextRole?: string): void {
|
||||
const role = actor?.role?.toLowerCase().replace(/[_-]/g, "");
|
||||
const isSuperAdmin = !!actor?.id && !actor.isApiKey && isSuperAdminRole(actor.role);
|
||||
if ((!actor?.id && !actor?.isApiKey) || (role !== "admin" && !isSuperAdmin) ||
|
||||
((isSuperAdminRole(currentRole) || isSuperAdminRole(nextRole)) && !isSuperAdmin)) {
|
||||
throw new ForbiddenException("فقط مدیر ارشد مجاز به مدیریت حساب و نقش مدیر ارشد است");
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { TasksModule } from './common/services/tasks.module';
|
||||
import { Module, NestModule, MiddlewareConsumer } from "@nestjs/common";
|
||||
import { PrismaModule } from "./prisma/prisma.module";
|
||||
import { SupportChatModule } from './support-chat/support-chat.module';
|
||||
@@ -79,6 +80,7 @@ import { Request, Response, NextFunction } from "express";
|
||||
B2BModule,
|
||||
FaqModule,
|
||||
MenuModule,
|
||||
TasksModule,
|
||||
],
|
||||
controllers: [MetricsController],
|
||||
providers: [
|
||||
|
||||
@@ -14,6 +14,7 @@ import { SmsService } from "../common/services/sms.service";
|
||||
import * as bcrypt from "bcryptjs";
|
||||
import * as crypto from "crypto";
|
||||
import { normalizeMobile } from "../common/utils/phone.utils";
|
||||
import { assertPrincipalActive } from "./stage-test-principal";
|
||||
import { getJwtRefreshSecret } from "./auth.constants";
|
||||
|
||||
export class RegisterInput {
|
||||
@@ -200,7 +201,8 @@ export class AuthService {
|
||||
});
|
||||
}
|
||||
|
||||
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role };
|
||||
assertPrincipalActive(user);
|
||||
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role, ...(user.stageTestSession ? {stageTestSession:user.stageTestSession, stageTestGeneration:user.stageTestGeneration} : {}) };
|
||||
const tokens = await this.generateTokens(payload);
|
||||
|
||||
const { password: _p, ...safeUser } = user;
|
||||
@@ -257,7 +259,8 @@ export class AuthService {
|
||||
},
|
||||
});
|
||||
|
||||
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role };
|
||||
assertPrincipalActive(user);
|
||||
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role, ...(user.stageTestSession ? {stageTestSession:user.stageTestSession, stageTestGeneration:user.stageTestGeneration} : {}) };
|
||||
const tokens = await this.generateTokens(payload);
|
||||
|
||||
const { password: _p, ...safeUser } = user;
|
||||
@@ -300,7 +303,8 @@ export class AuthService {
|
||||
});
|
||||
}
|
||||
|
||||
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role };
|
||||
assertPrincipalActive(user);
|
||||
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role, ...(user.stageTestSession ? {stageTestSession:user.stageTestSession, stageTestGeneration:user.stageTestGeneration} : {}) };
|
||||
const tokens = await this.generateTokens(payload);
|
||||
|
||||
const { password: _pw, ...safeUser } = user;
|
||||
@@ -326,10 +330,12 @@ export class AuthService {
|
||||
if (dbAdmin && dbAdmin.password && body.password) {
|
||||
const isMatch = await bcrypt.compare(body.password, dbAdmin.password);
|
||||
if (isMatch) {
|
||||
assertPrincipalActive(dbAdmin);
|
||||
const payload = {
|
||||
sub: dbAdmin.id,
|
||||
email: dbAdmin.email,
|
||||
role: dbAdmin.role,
|
||||
...(dbAdmin.stageTestSession ? {stageTestSession:dbAdmin.stageTestSession, stageTestGeneration:dbAdmin.stageTestGeneration} : {}),
|
||||
};
|
||||
const tokens = await this.generateTokens(payload);
|
||||
const { password: _p, ...safeUser } = dbAdmin;
|
||||
@@ -443,11 +449,14 @@ export class AuthService {
|
||||
|
||||
const user = await this.prisma.user.findUnique({ where: { id: userId } });
|
||||
if (user) {
|
||||
assertPrincipalActive(user);
|
||||
if (user.stageTestSession && (!user.stageTestGeneration || decoded.stageTestGeneration !== user.stageTestGeneration || decoded.stageTestSession !== user.stageTestSession)) throw new UnauthorizedException("Stage session revoked");
|
||||
userPayload = {
|
||||
sub: user.id,
|
||||
email: user.email,
|
||||
phoneNumber: user.mobile,
|
||||
role: user.role,
|
||||
...(user.stageTestSession ? {stageTestSession:user.stageTestSession, stageTestGeneration:user.stageTestGeneration} : {}),
|
||||
};
|
||||
const { password: _p, ...restUser } = user;
|
||||
safeUser = restUser;
|
||||
@@ -487,12 +496,15 @@ export class AuthService {
|
||||
email?: string;
|
||||
role?: string;
|
||||
mobile?: string;
|
||||
stageTestSession?: string | null;
|
||||
stageTestGeneration?: string | null;
|
||||
}) {
|
||||
const payload = {
|
||||
sub: user.id,
|
||||
email: user.email,
|
||||
role: user.role,
|
||||
phoneNumber: user.mobile,
|
||||
...(user.stageTestSession ? {stageTestSession:user.stageTestSession, stageTestGeneration:user.stageTestGeneration} : {}),
|
||||
};
|
||||
const tokens = await this.generateTokens(payload);
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { AdminService } from '../admin/admin.service';
|
||||
import { STAGE_TEST_ID, STAGE_TEST_EMAIL, STAGE_TEST_MOBILE } from './stage-test-principal';
|
||||
const sha='a'.repeat(40), generation='8311eb41-23b4-4aab-ade2-e97b90debc11';
|
||||
const env={APP_ENV:'stage',CI:'true',STAGE_TEST_PRINCIPAL_ENABLED:'true',STAGE_TEST_APPROVAL:'owner-authorized-stage-editorial',STAGE_TEST_SHA:sha,STAGE_TEST_SESSION:'cleanup-session',STAGE_TEST_TTL_SECONDS:'600',STAGE_TEST_GENERATION:generation};
|
||||
describe('durable cleanup ownership fence',()=>{
|
||||
it('does not revoke a replacement generation',async()=>{
|
||||
const update=jest.fn();
|
||||
const db={user:{findUnique:async()=>({id:STAGE_TEST_ID,email:STAGE_TEST_EMAIL,mobile:STAGE_TEST_MOBILE,stageTestSession:env.STAGE_TEST_SESSION,stageTestGeneration:'replacement',authExpiresAt:new Date()}),update}};
|
||||
await expect(new AdminService(db as any,undefined as any,undefined as any).cleanupStageTestPrincipal(env,sha)).rejects.toThrow('Refusing');
|
||||
expect(update).not.toHaveBeenCalled();
|
||||
});
|
||||
it('confirms revocation before relational deletion failure',async()=>{
|
||||
const events:string[]=[];
|
||||
const db={user:{findUnique:async()=>({id:STAGE_TEST_ID,email:STAGE_TEST_EMAIL,mobile:STAGE_TEST_MOBILE,stageTestSession:env.STAGE_TEST_SESSION,stageTestGeneration:generation,authExpiresAt:new Date()}),update:async()=>events.push('revoke')},$transaction:async()=>{events.push('delete');throw Error('FK failure');}};
|
||||
await expect((new AdminService(db as any,undefined as any,undefined as any).cleanupStageTestPrincipal as any)(env,sha,()=>events.push('handle-removed'))).rejects.toThrow('FK failure');
|
||||
expect(events).toEqual(['revoke','handle-removed','delete']);
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import { ExtractJwt, Strategy } from "passport-jwt";
|
||||
import { PassportStrategy } from "@nestjs/passport";
|
||||
import { Injectable, UnauthorizedException } from "@nestjs/common";
|
||||
import { UsersService } from "../users/users.service";
|
||||
import { assertPrincipalActive } from "./stage-test-principal";
|
||||
import { getJwtSecret } from "./auth.constants";
|
||||
|
||||
import { RedisService } from "../redis/redis.service";
|
||||
@@ -12,6 +13,8 @@ export interface JwtPayload {
|
||||
email?: string;
|
||||
role?: string;
|
||||
phoneNumber?: string;
|
||||
stageTestSession?: string;
|
||||
stageTestGeneration?: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
@@ -59,6 +62,13 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
|
||||
if (!user) {
|
||||
throw new UnauthorizedException("کاربر یافت نشد");
|
||||
}
|
||||
try { assertPrincipalActive(user); } catch { throw new UnauthorizedException("Principal expired"); }
|
||||
if (user.stageTestSession) {
|
||||
if (!user.stageTestGeneration || payload.stageTestGeneration !== user.stageTestGeneration || payload.stageTestSession !== user.stageTestSession) throw new UnauthorizedException("Stage session revoked");
|
||||
const path = req.originalUrl?.split('?')[0] || '';
|
||||
const allowed = req.method === 'GET' && /^\/api\/admin\/orchestration\/tasks(?:\/[a-f0-9-]+)?$/.test(path) || req.method === 'POST' && (/^\/api\/admin\/orchestration\/tasks$/.test(path) || /^\/api\/admin\/orchestration\/tasks\/[a-f0-9-]+\/(?:gates\/1\/decide|editorial-failure|editorial-completed-recovery)$/.test(path));
|
||||
if (!allowed) throw new UnauthorizedException('Stage test scope denied');
|
||||
}
|
||||
return user;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { AuthService } from './auth.service';
|
||||
import { RedisService } from '../redis/redis.service';
|
||||
import { STAGE_TEST_ID } from './stage-test-principal';
|
||||
import { createServer, Server } from 'http';
|
||||
import { execFile } from 'child_process';
|
||||
import { promisify } from 'util';
|
||||
import { readFileSync, writeFileSync, existsSync } from 'fs';
|
||||
const enabled=process.env.STAGE_PRINCIPAL_DISPOSABLE_TEST==='true';
|
||||
(enabled?describe:describe.skip)('actual internal CLI disposable lifecycle',()=>{
|
||||
const sha='a'.repeat(40), generation='b411eb41-23b4-4aab-ade2-e97b90debc11', session='cli-integration-session';
|
||||
const handle=`/app/private-stage-test/${session}.json`;
|
||||
const db=new PrismaClient({log:[]}), redis=new RedisService(); let server:Server;
|
||||
const env={...process.env,APP_ENV:'stage',CI:'true',STAGE_TEST_PRINCIPAL_ENABLED:'true',STAGE_TEST_APPROVAL:'owner-authorized-stage-editorial',STAGE_TEST_SHA:sha,STAGE_TEST_SESSION:session,STAGE_TEST_TTL_SECONDS:'600',STAGE_TEST_GENERATION:generation};
|
||||
const cli=(action:string)=>promisify(execFile)(process.execPath,['-r','ts-node/register','src/auth/stage-test-principal.cli.ts',action],{env,timeout:90000});
|
||||
beforeAll(async()=>{
|
||||
if(!process.env.DATABASE_URL?.endsWith('/principal_disposable')) throw Error('Disposable database only');
|
||||
writeFileSync('/app/STAGE_TEST_ARTIFACT_SHA',sha); redis.onModuleInit();
|
||||
const auth=new AuthService(db as any,new JwtService({secret:process.env.JWT_SECRET,signOptions:{expiresIn:'2h'}}),redis,undefined as any);
|
||||
server=createServer(async(req,res)=>{
|
||||
try {let body='';for await(const chunk of req) body+=chunk;
|
||||
if(req.url!=='/api/auth/admin-login') {res.writeHead(404).end();return;}
|
||||
const login=await auth.adminLogin(JSON.parse(body));res.setHeader('content-type','application/json');res.end(JSON.stringify(login));
|
||||
} catch {res.writeHead(401).end();}
|
||||
});
|
||||
await new Promise<void>(r=>server.listen(3000,'127.0.0.1',r));
|
||||
},120000);
|
||||
afterAll(async()=>{await new Promise<void>(r=>server.close(()=>r()));redis.onModuleDestroy();await db.$disconnect();});
|
||||
it('logs in using persisted credentials and removes handle on confirmed revocation despite failed delete',async()=>{
|
||||
await cli('open'); expect(existsSync(handle)).toBe(true);
|
||||
const credential=JSON.parse(readFileSync(handle,'utf8'));expect(credential.accessToken).toBeTruthy();
|
||||
expect((await db.user.findUnique({where:{id:STAGE_TEST_ID}}))?.stageTestGeneration).toBe(generation);
|
||||
await db.$executeRawUnsafe(`CREATE FUNCTION deny_principal_delete() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'test FK deletion failure'; END $$`);
|
||||
await db.$executeRawUnsafe(`CREATE TRIGGER deny_principal_delete BEFORE DELETE ON users FOR EACH ROW EXECUTE FUNCTION deny_principal_delete()`);
|
||||
try {
|
||||
await expect(cli('close')).rejects.toThrow();
|
||||
expect(existsSync(handle)).toBe(false);
|
||||
const revoked=await db.user.findUnique({where:{id:STAGE_TEST_ID}});
|
||||
expect(revoked?.authExpiresAt?.getTime()).toBe(0);expect(revoked?.password).toBe('');
|
||||
} finally {await db.$executeRawUnsafe(`DROP TRIGGER deny_principal_delete ON users`);await db.$executeRawUnsafe(`DROP FUNCTION deny_principal_delete()`);}
|
||||
await cli('close');expect(await db.user.findUnique({where:{id:STAGE_TEST_ID}})).toBeNull();
|
||||
},240000);
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
import 'reflect-metadata';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { randomBytes } from 'crypto';
|
||||
import { mkdirSync, openSync, writeFileSync, closeSync, readFileSync, statSync, unlinkSync, constants } from 'fs';
|
||||
import { AdminService } from '../admin/admin.service';
|
||||
import { authorizeStageSession, STAGE_TEST_EMAIL } from './stage-test-principal';
|
||||
|
||||
// CI-only internal seed command; deliberately not registered in AppModule.
|
||||
async function main() {
|
||||
const sha = readFileSync('/app/STAGE_TEST_ARTIFACT_SHA', 'utf8').trim();
|
||||
const grant = authorizeStageSession(process.env, sha);
|
||||
const action = process.argv[2];
|
||||
if (action === 'cleanup-capability') { process.stdout.write('stage-generation-cleanup-v1'); return; }
|
||||
if (!['open','close'].includes(action)) throw new Error('Unknown command');
|
||||
const root = '/app/private-stage-test';
|
||||
mkdirSync(root,{recursive:true,mode:0o700});
|
||||
const st = statSync(root);
|
||||
if (st.uid !== process.getuid!() || (st.mode & 0o777) !== 0o700) throw new Error('Unsafe private directory');
|
||||
if (!/^[a-f0-9-]{36}$/.test(process.env.STAGE_TEST_GENERATION || '')) throw new Error('Generation required');
|
||||
const handle = `${root}/${grant.session}.json`;
|
||||
const removeHandle = () => { try {unlinkSync(handle);} catch(e:any) {if(e.code !== 'ENOENT') throw e;} };
|
||||
const audit = (event:string) => {
|
||||
const fd = openSync(`${root}/audit.jsonl`, constants.O_WRONLY|constants.O_CREAT|constants.O_APPEND|constants.O_NOFOLLOW,0o600);
|
||||
try { writeFileSync(fd,JSON.stringify({event,sha,session:grant.session,at:new Date().toISOString()})+'\n'); } finally {closeSync(fd);}
|
||||
};
|
||||
const db = new PrismaClient({log:[]});
|
||||
const service = new AdminService(db as any,undefined as any,undefined as any);
|
||||
try {
|
||||
audit(`${action}-requested`);
|
||||
if(action === 'close') {
|
||||
await service.cleanupStageTestPrincipal(process.env,sha,removeHandle);
|
||||
audit('revoked-and-deleted');
|
||||
return;
|
||||
}
|
||||
let fd:number;
|
||||
let password:string;
|
||||
try {
|
||||
fd = openSync(handle,constants.O_WRONLY|constants.O_CREAT|constants.O_EXCL|constants.O_NOFOLLOW,0o600);
|
||||
password = randomBytes(48).toString('base64url');
|
||||
try {writeFileSync(fd,JSON.stringify({password}));} finally {closeSync(fd);}
|
||||
} catch(e:any) {
|
||||
if(e.code !== 'EEXIST') throw e;
|
||||
fd = openSync(handle,constants.O_RDONLY|constants.O_NOFOLLOW);
|
||||
try {
|
||||
const {fstatSync} = await import('fs'); const s=fstatSync(fd);
|
||||
if(!s.isFile() || s.uid !== process.getuid!() || (s.mode & 0o777) !== 0o600) throw new Error('Unsafe handle');
|
||||
password=JSON.parse(readFileSync(fd,'utf8')).password;
|
||||
} finally {closeSync(fd);}
|
||||
}
|
||||
const user=await service.provisionStageTestPrincipal(process.env,sha,password);
|
||||
// Use deployed persisted-account HTTP login, never sign tokens here.
|
||||
const response=await fetch('http://127.0.0.1:3000/api/auth/admin-login',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({email:STAGE_TEST_EMAIL,password}),signal:AbortSignal.timeout(15000)});
|
||||
if(!response.ok) throw new Error('Persisted login failed');
|
||||
const result:any=await response.json();
|
||||
if(result.data?.user?.id !== user.id || result.data?.user?.role !== 'SUPER_ADMIN' || !result.data?.accessToken) throw new Error('Persisted login mismatch');
|
||||
fd=openSync(handle,constants.O_WRONLY|constants.O_TRUNC|constants.O_NOFOLLOW);
|
||||
try {writeFileSync(fd,JSON.stringify({password,...result.data,expiresAt:user.authExpiresAt}));} finally {closeSync(fd);}
|
||||
audit('created-and-login-verified');
|
||||
// Only an opaque local path is public. Never upload this file as a CI artifact.
|
||||
process.stdout.write(`Stage credential handle: ${handle}\n`);
|
||||
} catch {
|
||||
audit('failed');
|
||||
// Leave only a revoked account if relational cleanup fails.
|
||||
await service.cleanupStageTestPrincipal(process.env,sha,removeHandle).catch(()=>undefined);
|
||||
throw new Error('Stage test principal operation failed; inspect private audit');
|
||||
} finally {await db.$disconnect();}
|
||||
}
|
||||
main().catch(()=>{process.stderr.write('Stage test principal denied or failed\n');process.exitCode=1;});
|
||||
@@ -0,0 +1,58 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { randomBytes } from 'crypto';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { AdminService } from '../admin/admin.service';
|
||||
import { AuthService } from './auth.service';
|
||||
import { UsersService } from '../users/users.service';
|
||||
import { JwtStrategy } from './jwt.strategy';
|
||||
import { RedisService } from '../redis/redis.service';
|
||||
import { STAGE_TEST_ID, STAGE_TEST_EMAIL, STAGE_TEST_MOBILE } from './stage-test-principal';
|
||||
const enabled=process.env.STAGE_PRINCIPAL_DISPOSABLE_TEST === 'true';
|
||||
(enabled ? describe : describe.skip)('disposable persisted Stage principal lifecycle',()=>{
|
||||
const sha='a'.repeat(40), grant={APP_ENV:'stage',CI:'true',STAGE_TEST_PRINCIPAL_ENABLED:'true',STAGE_TEST_APPROVAL:'owner-authorized-stage-editorial',STAGE_TEST_SHA:sha,STAGE_TEST_SESSION:'integration-session',STAGE_TEST_TTL_SECONDS:'600'};
|
||||
const db=new PrismaClient({log:[]}); const redis=new RedisService();
|
||||
let admin:AdminService,auth:AuthService,strategy:JwtStrategy,password:string;
|
||||
beforeAll(async()=>{
|
||||
// Deliberately require a disposable database name; never point this suite at Stage.
|
||||
if(!process.env.DATABASE_URL?.endsWith('/principal_disposable')) throw new Error('Disposable database required');
|
||||
redis.onModuleInit(); password=randomBytes(48).toString('base64url');
|
||||
admin=new AdminService(db as any,redis,undefined as any);
|
||||
auth=new AuthService(db as any,new JwtService({secret:process.env.JWT_SECRET,signOptions:{expiresIn:'2h'}}),redis,undefined as any);
|
||||
strategy=new JwtStrategy(new UsersService(db as any),redis);
|
||||
});
|
||||
afterAll(async()=>{await admin.cleanupStageTestPrincipal(grant,sha); await db.$disconnect();redis.onModuleDestroy();});
|
||||
it('rejects unowned collision and never changes it',async()=>{
|
||||
const collision=await db.user.create({data:{firstName:'Unowned',lastName:'Account',email:STAGE_TEST_EMAIL,mobile:STAGE_TEST_MOBILE}});
|
||||
try {
|
||||
await expect(admin.provisionStageTestPrincipal(grant,sha,password)).rejects.toThrow('Refusing');
|
||||
expect((await db.user.findUnique({where:{id:collision.id}}))?.role).toBe('User_PetOwner');
|
||||
} finally {await db.user.delete({where:{id:collision.id}});}
|
||||
});
|
||||
it('creates through account service, logs in, verifies signed tokens, never renews retry TTL',async()=>{
|
||||
const u=await admin.provisionStageTestPrincipal(grant,sha,password);
|
||||
expect(u.id).toBe(STAGE_TEST_ID); expect(u.role).toBe('SUPER_ADMIN'); expect(u.password).not.toBe(password);
|
||||
const retry=await admin.provisionStageTestPrincipal(grant,sha,password); expect(retry.authExpiresAt).toEqual(u.authExpiresAt);
|
||||
await expect(admin.provisionStageTestPrincipal({...grant,STAGE_TEST_SESSION:'different-session'},sha,password)).rejects.toThrow('Refusing');
|
||||
const login=await auth.adminLogin({email:STAGE_TEST_EMAIL,password});
|
||||
const jwt=new JwtService({secret:process.env.JWT_SECRET});
|
||||
const payload=jwt.verify(login.data.accessToken); expect(payload.sub).toBe(u.id);expect(payload.role).toBe('SUPER_ADMIN');
|
||||
const req:any={method:'GET',originalUrl:'/api/admin/orchestration/tasks',headers:{authorization:`Bearer ${login.data.accessToken}`}};
|
||||
expect((await strategy.validate(req,payload)).id).toBe(u.id);
|
||||
await expect(strategy.validate({...req,originalUrl:'/api/admin/users'},payload)).rejects.toThrow('scope denied');
|
||||
await expect(strategy.validate({...req,method:'POST',originalUrl:'/api/admin/orchestration/tasks/abcd/gates/2/decide'},payload)).rejects.toThrow('scope denied');
|
||||
// Fixture time travel: persisted expiry is enforced independently of the long-lived signed token.
|
||||
await db.user.update({where:{id:u.id},data:{authExpiresAt:new Date(0)}});
|
||||
await expect(strategy.validate(req,payload)).rejects.toThrow();
|
||||
await expect(auth.adminLogin({email:STAGE_TEST_EMAIL,password})).rejects.toThrow();
|
||||
await expect(auth.refreshToken(login.data.refreshToken)).rejects.toThrow();
|
||||
await admin.cleanupStageTestPrincipal(grant,sha);
|
||||
await expect(strategy.validate(req,payload)).rejects.toThrow();
|
||||
expect(await db.user.findUnique({where:{id:u.id}})).toBeNull();
|
||||
const replacement=await admin.provisionStageTestPrincipal(grant,sha,password);
|
||||
expect(replacement.stageTestGeneration).not.toBe(u.stageTestGeneration);
|
||||
await expect(strategy.validate(req,payload)).rejects.toThrow();
|
||||
await expect(auth.refreshToken(login.data.refreshToken)).rejects.toThrow();
|
||||
const fresh=await auth.adminLogin({email:STAGE_TEST_EMAIL,password});
|
||||
expect((await strategy.validate(req,jwt.verify(fresh.data.accessToken))).id).toBe(u.id);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
import { assertPrincipalActive, authorizeStageSession } from './stage-test-principal';
|
||||
const sha = 'a'.repeat(40);
|
||||
const valid = { APP_ENV: 'stage', STAGE_TEST_PRINCIPAL_ENABLED: 'true', CI: 'true', STAGE_TEST_APPROVAL: 'owner-authorized-stage-editorial', STAGE_TEST_SHA: sha, STAGE_TEST_SESSION: 'editorial-20261024', STAGE_TEST_TTL_SECONDS: '600' };
|
||||
describe('Stage CI authority', () => {
|
||||
it('denies by default and in Production despite opt in', () => {
|
||||
expect(() => authorizeStageSession({}, sha)).toThrow();
|
||||
expect(() => authorizeStageSession({...valid, APP_ENV:'production'}, sha)).toThrow();
|
||||
});
|
||||
it('requires immutable matching SHA and bounded explicit authorization', () => {
|
||||
expect(authorizeStageSession(valid, sha).ttl).toBe(600);
|
||||
for(const patch of [{STAGE_TEST_SHA:'main'}, {STAGE_TEST_SHA:'b'.repeat(40)}, {STAGE_TEST_TTL_SECONDS:'3601'}, {STAGE_TEST_TTL_SECONDS:'0'}, {STAGE_TEST_APPROVAL:''}, {CI:''}]) expect(() => authorizeStageSession({...valid,...patch},sha)).toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
// Internal seed authority only. No controller, JWT actor, or owner impersonation.
|
||||
export const STAGE_TEST_ID = 'e876e7a0-738f-4e59-b6db-e270512ababc';
|
||||
export const STAGE_TEST_EMAIL = 'stage-editorial-reviewer@ci.canina.invalid';
|
||||
export const STAGE_TEST_MOBILE = '09999999071';
|
||||
export function authorizeStageSession(env: NodeJS.ProcessEnv, artifactSha: string) {
|
||||
if (env.APP_ENV !== 'stage' || env.STAGE_TEST_PRINCIPAL_ENABLED !== 'true' || env.CI !== 'true' || env.STAGE_TEST_APPROVAL !== 'owner-authorized-stage-editorial' || !/^[a-f0-9]{40}$/.test(artifactSha) || env.STAGE_TEST_SHA !== artifactSha || !/^[a-z0-9-]{8,64}$/.test(env.STAGE_TEST_SESSION || '')) throw new Error('Stage CI authority denied');
|
||||
const ttl = Number(env.STAGE_TEST_TTL_SECONDS);
|
||||
if (!Number.isInteger(ttl) || ttl < 60 || ttl > 3600) throw new Error('Bounded TTL required');
|
||||
return {ttl, session:env.STAGE_TEST_SESSION!, sha:artifactSha};
|
||||
}
|
||||
export function assertPrincipalActive(user: { authExpiresAt?: Date | null }, now = Date.now()) {
|
||||
if (user.authExpiresAt && user.authExpiresAt.getTime() <= now) throw new Error('Principal expired');
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { JwtStrategy } from './jwt.strategy';
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
describe('Stage credentials remain fenced to their creation session', () => {
|
||||
const id='e876e7a0-738f-4e59-b6db-e270512ababc';
|
||||
const current={id, role:'SUPER_ADMIN', stageTestSession:'new-session', stageTestGeneration:'fresh-generation', authExpiresAt:new Date(Date.now()+600000)};
|
||||
const redis:any={get:jest.fn(async()=> '1'),del:jest.fn(),set:jest.fn()};
|
||||
beforeAll(()=> {process.env.JWT_SECRET='disposable-only-test-secret-at-least-32-characters';process.env.JWT_REFRESH_SECRET='disposable-only-refresh-secret-at-least-32-characters';});
|
||||
it('rejects an old-session access token after fixed account ID is recreated',async()=>{
|
||||
const strategy=new JwtStrategy({findById:async()=>current} as any,{get:async()=>null} as any);
|
||||
const req:any={method:'GET',originalUrl:'/api/admin/orchestration/tasks',headers:{}};
|
||||
await expect(strategy.validate(req,{sub:id,stageTestSession:'old-session'} as any)).rejects.toThrow();
|
||||
await expect(strategy.validate(req,{sub:id})).rejects.toThrow();
|
||||
await expect(strategy.validate(req,{sub:id,stageTestSession:'new-session',stageTestGeneration:'old-generation'} as any)).rejects.toThrow();
|
||||
await expect(strategy.validate(req,{sub:id,stageTestSession:'new-session',stageTestGeneration:'fresh-generation'} as any)).resolves.toMatchObject({id});
|
||||
});
|
||||
it('rejects an old-session refresh token even while its Redis entry remains active',async()=>{
|
||||
const jwt=new JwtService({secret:process.env.JWT_SECRET});
|
||||
const auth=new AuthService({user:{findUnique:async()=>current}} as any,jwt,redis,undefined as any);
|
||||
const token=jwt.sign({sub:id,jti:'old-refresh',role:'SUPER_ADMIN',stageTestSession:'old-session'},{secret:process.env.JWT_REFRESH_SECRET});
|
||||
await expect(auth.refreshToken(token)).rejects.toThrow();
|
||||
});
|
||||
it('includes session fencing in newly issued credentials',async()=>{
|
||||
const jwt=new JwtService({secret:process.env.JWT_SECRET});
|
||||
const auth=new AuthService({} as any,jwt,redis,undefined as any);
|
||||
const result=await auth.refresh(current);
|
||||
expect(jwt.verify(result.data.accessToken).stageTestGeneration).toBe('fresh-generation');
|
||||
expect(jwt.verify(result.data.accessToken).stageTestSession).toBe('new-session');
|
||||
expect(jwt.verify(result.data.refreshToken,{secret:process.env.JWT_REFRESH_SECRET}).stageTestSession).toBe('new-session');
|
||||
});
|
||||
});
|
||||
@@ -40,7 +40,7 @@ describe("BlogsService", () => {
|
||||
describe("findAll", () => {
|
||||
it("should query published blogs with pagination", async () => {
|
||||
const blogs = [
|
||||
{ id: "1", title: "Blog 1", isPublished: true, status: "PUBLISHED" },
|
||||
{ id: "1", title: "Blog 1", isPublished: true, status: "PUBLISHED", author: null },
|
||||
];
|
||||
mockPrisma.blog.findMany.mockResolvedValue(blogs);
|
||||
mockPrisma.blog.count.mockResolvedValue(1);
|
||||
@@ -49,6 +49,9 @@ describe("BlogsService", () => {
|
||||
expect(mockPrisma.blog.findMany).toHaveBeenCalled();
|
||||
expect(result.data).toEqual(blogs);
|
||||
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 () => {
|
||||
@@ -67,7 +70,19 @@ describe("BlogsService", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("selects the minimal public author identity for list results", async () => {
|
||||
mockPrisma.blog.findMany.mockResolvedValue([]); mockPrisma.blog.count.mockResolvedValue(0);
|
||||
await service.findAll({});
|
||||
expect(mockPrisma.blog.findMany.mock.calls[0][0].include.author).toEqual({ select: { id: true, firstName: true, lastName: true } });
|
||||
});
|
||||
|
||||
describe("findHomepage", () => {
|
||||
it("selects the minimal public author identity for homepage results", async () => {
|
||||
mockPrisma.blog.findMany.mockResolvedValueOnce([]).mockResolvedValueOnce([]);
|
||||
await service.findHomepage();
|
||||
for (const call of mockPrisma.blog.findMany.mock.calls.slice(0, 2)) expect(call[0].include.author).toEqual({ select: { id: true, firstName: true, lastName: true } });
|
||||
});
|
||||
|
||||
it("should return selected blogs if showOnHome posts exist", async () => {
|
||||
const selected = [{ id: "b1", title: "Hero Blog", showOnHome: true }];
|
||||
mockPrisma.blog.findMany.mockResolvedValueOnce(selected);
|
||||
@@ -90,6 +105,12 @@ describe("BlogsService", () => {
|
||||
});
|
||||
|
||||
describe("findOneBySlug", () => {
|
||||
it("selects the minimal public author identity for detail results", async () => {
|
||||
mockPrisma.blog.findFirst.mockResolvedValue(null);
|
||||
await expect(service.findOneBySlug("missing")).rejects.toThrow(NotFoundException);
|
||||
expect(mockPrisma.blog.findFirst.mock.calls[0][0].include.author).toEqual({ select: { id: true, firstName: true, lastName: true } });
|
||||
});
|
||||
|
||||
it("should throw NotFoundException if slug is empty or blog not found", async () => {
|
||||
mockPrisma.blog.findFirst.mockResolvedValue(null);
|
||||
await expect(service.findOneBySlug("unknown-slug")).rejects.toThrow(
|
||||
|
||||
@@ -2,8 +2,15 @@ import { Injectable, NotFoundException } from "@nestjs/common";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
import { PaginationDto } from "../common/dto/pagination.dto";
|
||||
import {
|
||||
createPaginationMeta,
|
||||
extractSearchTokens,
|
||||
normalizeSearchText,
|
||||
calculateRelevanceScore,
|
||||
} from "../common/utils/search.utils";
|
||||
|
||||
export interface BlogFilterDto extends PaginationDto {
|
||||
categoryId?: string;
|
||||
categorySlug?: string;
|
||||
tagSlug?: string;
|
||||
featured?: boolean | string;
|
||||
@@ -20,6 +27,7 @@ export class BlogsService {
|
||||
limit = 10,
|
||||
sortBy = "publishedAt",
|
||||
sortOrder = "desc",
|
||||
categoryId,
|
||||
categorySlug,
|
||||
tagSlug,
|
||||
featured,
|
||||
@@ -32,20 +40,23 @@ export class BlogsService {
|
||||
OR: [{ publishedAt: null }, { publishedAt: { lte: now } }],
|
||||
};
|
||||
|
||||
if (search) {
|
||||
const tokens = extractSearchTokens(search);
|
||||
if (tokens.length > 0) {
|
||||
whereClause.AND = [
|
||||
{
|
||||
OR: [
|
||||
{ title: { contains: search, mode: "insensitive" } },
|
||||
{ excerpt: { contains: search, mode: "insensitive" } },
|
||||
{ content: { contains: search, mode: "insensitive" } },
|
||||
{ keywords: { contains: search, mode: "insensitive" } },
|
||||
],
|
||||
OR: tokens.flatMap((token) => [
|
||||
{ title: { contains: token, mode: "insensitive" } },
|
||||
{ excerpt: { contains: token, mode: "insensitive" } },
|
||||
{ keywords: { contains: token, mode: "insensitive" } },
|
||||
{ tags: { some: { name: { contains: token, mode: "insensitive" } } } },
|
||||
]),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (categorySlug) {
|
||||
if (categoryId && categoryId !== "ALL") {
|
||||
whereClause.categoryId = categoryId;
|
||||
} else if (categorySlug && categorySlug !== "all") {
|
||||
whereClause.category = { slug: categorySlug };
|
||||
}
|
||||
|
||||
@@ -57,19 +68,24 @@ export class BlogsService {
|
||||
whereClause.featured = String(featured) === "true";
|
||||
}
|
||||
|
||||
const skip = (Number(page) - 1) * Number(limit);
|
||||
const safePage = Math.max(1, Number(page) || 1);
|
||||
const safeLimit = Math.max(1, Number(limit) || 10);
|
||||
const skip = (safePage - 1) * safeLimit;
|
||||
|
||||
const [data, total] = await Promise.all([
|
||||
const [rawBlogs, total] = await Promise.all([
|
||||
this.prisma.blog.findMany({
|
||||
where: whereClause,
|
||||
skip,
|
||||
take: Number(limit),
|
||||
orderBy: {
|
||||
[sortBy === "createdAt" ? "createdAt" : "publishedAt"]: sortOrder,
|
||||
},
|
||||
skip: tokens.length > 0 ? undefined : skip,
|
||||
take: tokens.length > 0 ? 100 : safeLimit,
|
||||
orderBy: [
|
||||
{
|
||||
[sortBy === "createdAt" ? "createdAt" : "publishedAt"]: sortOrder,
|
||||
},
|
||||
{ id: "asc" },
|
||||
],
|
||||
include: {
|
||||
author: {
|
||||
select: { firstName: true, lastName: true },
|
||||
select: { id: true, firstName: true, lastName: true },
|
||||
},
|
||||
category: {
|
||||
select: { id: true, name: true, slug: true },
|
||||
@@ -85,14 +101,30 @@ export class BlogsService {
|
||||
this.prisma.blog.count({ where: whereClause }),
|
||||
]);
|
||||
|
||||
let data = rawBlogs;
|
||||
if (tokens.length > 0 && search) {
|
||||
data = [...rawBlogs]
|
||||
.map((b) => ({
|
||||
blog: b,
|
||||
score: calculateRelevanceScore(
|
||||
{
|
||||
title: b.title,
|
||||
slug: b.slug,
|
||||
shortDescription: b.excerpt,
|
||||
tags: b.tags,
|
||||
},
|
||||
search,
|
||||
tokens,
|
||||
),
|
||||
}))
|
||||
.sort((a, b) => b.score - a.score)
|
||||
.map((item) => item.blog)
|
||||
.slice(skip, skip + safeLimit);
|
||||
}
|
||||
|
||||
return {
|
||||
data,
|
||||
meta: {
|
||||
total,
|
||||
page: Number(page),
|
||||
lastPage: Math.ceil(total / Number(limit)) || 1,
|
||||
limit: Number(limit),
|
||||
},
|
||||
meta: createPaginationMeta(total, safePage, safeLimit),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -108,9 +140,11 @@ export class BlogsService {
|
||||
const selectedBlogs = await this.prisma.blog.findMany({
|
||||
where: { ...baseWhere, showOnHome: true },
|
||||
take: 4,
|
||||
orderBy: { publishedAt: "desc" },
|
||||
orderBy: [{ publishedAt: "desc" }, { id: "asc" }],
|
||||
include: {
|
||||
author: { select: { firstName: true, lastName: true } },
|
||||
author: {
|
||||
select: { id: true, firstName: true, lastName: true },
|
||||
},
|
||||
category: { select: { id: true, name: true, slug: true } },
|
||||
tags: { select: { id: true, name: true, slug: true } },
|
||||
_count: { select: { comments: { where: { status: "APPROVED" } } } },
|
||||
@@ -125,9 +159,11 @@ export class BlogsService {
|
||||
const newestBlogs = await this.prisma.blog.findMany({
|
||||
where: baseWhere,
|
||||
take: 4,
|
||||
orderBy: { publishedAt: "desc" },
|
||||
orderBy: [{ publishedAt: "desc" }, { id: "asc" }],
|
||||
include: {
|
||||
author: { select: { firstName: true, lastName: true } },
|
||||
author: {
|
||||
select: { id: true, firstName: true, lastName: true },
|
||||
},
|
||||
category: { select: { id: true, name: true, slug: true } },
|
||||
tags: { select: { id: true, name: true, slug: true } },
|
||||
_count: { select: { comments: { where: { status: "APPROVED" } } } },
|
||||
@@ -163,9 +199,7 @@ export class BlogsService {
|
||||
],
|
||||
},
|
||||
include: {
|
||||
author: {
|
||||
select: { firstName: true, lastName: true },
|
||||
},
|
||||
author: { select: { id: true, firstName: true, lastName: true } },
|
||||
category: {
|
||||
select: { id: true, name: true, slug: true },
|
||||
},
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { CallHandler, ExecutionContext } from "@nestjs/common";
|
||||
import { of, lastValueFrom } from "rxjs";
|
||||
import { AdminRevalidationInterceptor } from "./admin-revalidation.interceptor";
|
||||
import { RevalidationService } from "./revalidation.service";
|
||||
|
||||
describe("AdminRevalidationInterceptor", () => {
|
||||
const revalidation = { revalidate: jest.fn().mockResolvedValue(true) } as unknown as RevalidationService;
|
||||
const interceptor = new AdminRevalidationInterceptor(revalidation);
|
||||
const next = { handle: () => of({ ok: true }) } as CallHandler;
|
||||
|
||||
beforeEach(() => jest.clearAllMocks());
|
||||
|
||||
function context(method: string, url: string): ExecutionContext {
|
||||
return { switchToHttp: () => ({ getRequest: () => ({ method, originalUrl: url }) }) } as unknown as ExecutionContext;
|
||||
}
|
||||
|
||||
it("invalidates blog list and detail after an admin blog mutation", async () => {
|
||||
await lastValueFrom(interceptor.intercept(context("PUT", "/api/admin/blogs/blog-1"), next));
|
||||
expect(revalidation.revalidate).toHaveBeenCalledWith(
|
||||
expect.arrayContaining(["blogs", "blog-categories", "blog-tags", "home-data"]),
|
||||
expect.arrayContaining(["/", "/blog"]),
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["/api/admin/products/p1", "products"],
|
||||
["/api/admin/categories/c1", "categories"],
|
||||
["/api/admin/wiki/glucosamine", "wiki"],
|
||||
["/api/admin/settings", "settings"],
|
||||
["/api/admin/cms/hero-banners/b1", "banners"],
|
||||
["/api/admin/cms/vet-testimonials/t1", "testimonials"],
|
||||
["/api/admin/reviews/r1", "products"],
|
||||
["/api/admin/media/m1", "products"],
|
||||
])("maps %s mutations to %s cache invalidation", async (url, expectedTag) => {
|
||||
await lastValueFrom(interceptor.intercept(context("DELETE", url), next));
|
||||
expect(revalidation.revalidate).toHaveBeenCalledWith(expect.arrayContaining([expectedTag]), expect.any(Array));
|
||||
});
|
||||
|
||||
it("does not invalidate cache for reads or internal-only admin CRUD", async () => {
|
||||
await lastValueFrom(interceptor.intercept(context("GET", "/api/admin/blogs"), next));
|
||||
await lastValueFrom(interceptor.intercept(context("PUT", "/api/admin/users/u1"), next));
|
||||
expect(revalidation.revalidate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["/api/banners/banner-1", "banners"],
|
||||
["/api/menu/menu-1", "menu"],
|
||||
["/api/videos/video-1", "videos"],
|
||||
["/api/testimonials/testimonial-1", "testimonials"],
|
||||
["/api/faq/faq-1", "faq"],
|
||||
["/api/ingredients/ingredient-1", "ingredients"],
|
||||
["/api/doctors/doctor-1", "doctors"],
|
||||
["/api/settings/seo", "seo-config"],
|
||||
["/api/settings/ui-texts/HERO_TITLE", "ui-texts"],
|
||||
["/api/contact/info", "settings"],
|
||||
["/api/smart-advisor/rules/rule-1", "smart-advisor"],
|
||||
])("maps storefront mutation %s to %s cache invalidation", async (url, expectedTag) => {
|
||||
await lastValueFrom(interceptor.intercept(context("PATCH", url), next));
|
||||
expect(revalidation.revalidate).toHaveBeenCalledWith(expect.arrayContaining([expectedTag]), expect.any(Array));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from "@nestjs/common";
|
||||
import { Observable, tap } from "rxjs";
|
||||
import { RevalidationService } from "./revalidation.service";
|
||||
|
||||
type Target = { tags: string[]; paths: string[] };
|
||||
|
||||
const TARGETS: Array<{ pattern: RegExp; target: Target }> = [
|
||||
{ pattern: /^\/api\/banners(?:\/|$)/, target: { tags: ["banners", "home-data"], paths: ["/"] } },
|
||||
{ pattern: /^\/api\/menu(?:\/|$)/, target: { tags: ["menu", "settings"], paths: ["/"] } },
|
||||
{ pattern: /^\/api\/videos(?:\/|$)/, target: { tags: ["videos", "home-data"], paths: ["/", "/videos"] } },
|
||||
{ pattern: /^\/api\/testimonials(?:\/|$)/, target: { tags: ["testimonials", "home-data"], paths: ["/"] } },
|
||||
{ pattern: /^\/api\/faq(?:\/|$)/, target: { tags: ["faq"], paths: ["/faq"] } },
|
||||
{ pattern: /^\/api\/ingredients(?:\/|$)/, target: { tags: ["ingredients", "products", "wiki"], paths: ["/shop", "/wiki"] } },
|
||||
{ pattern: /^\/api\/doctors(?:\/|$)/, target: { tags: ["doctors", "settings"], paths: ["/contact"] } },
|
||||
{ pattern: /^\/api\/settings\/seo(?:\/|$)/, target: { tags: ["seo-config", "settings"], paths: ["/", "/sitemap.xml"] } },
|
||||
{ pattern: /^\/api\/settings\/(?:ui-texts|system|financial)(?:\/|$)/, target: { tags: ["ui-texts", "settings", "home-data"], paths: ["/"] } },
|
||||
{ pattern: /^\/api\/contact\/info(?:\/|$)/, target: { tags: ["settings"], paths: ["/contact", "/"] } },
|
||||
{ pattern: /^\/api\/smart-advisor\/rules(?:\/|$)/, target: { tags: ["smart-advisor", "products"], paths: ["/smart-advisor"] } },
|
||||
{ pattern: /^\/api\/admin\/blogs(?:\/|$)/, target: { tags: ["blogs", "blog-categories", "blog-tags", "home-data"], paths: ["/", "/blog", "/sitemap.xml"] } },
|
||||
{ pattern: /^\/api\/admin\/categories(?:\/|$)/, target: { tags: ["products", "categories", "home-data"], paths: ["/", "/shop", "/sitemap.xml"] } },
|
||||
{ pattern: /^\/api\/admin\/wiki(?:\/|$)/, target: { tags: ["wiki", "scientific-terms"], paths: ["/wiki", "/sitemap.xml"] } },
|
||||
{ pattern: /^\/api\/admin\/(?:settings|pricing)(?:\/|$)/, target: { tags: ["settings", "ui-texts", "seo-config", "products", "home-data"], paths: ["/", "/shop"] } },
|
||||
{ pattern: /^\/api\/admin\/cms\/hero-banners(?:\/|$)/, target: { tags: ["banners", "home-data"], paths: ["/"] } },
|
||||
{ pattern: /^\/api\/admin\/cms\/vet-testimonials(?:\/|$)/, target: { tags: ["testimonials", "home-data"], paths: ["/"] } },
|
||||
{ pattern: /^\/api\/admin\/reviews(?:\/|$)/, target: { tags: ["products", "home-data"], paths: ["/", "/shop"] } },
|
||||
{ pattern: /^\/api\/admin\/media(?:\/|$)/, target: { tags: ["products", "blogs", "wiki", "home-data"], paths: ["/", "/shop", "/blog", "/wiki"] } },
|
||||
{ pattern: /^\/api\/admin\/products(?:\/|$)/, target: { tags: ["products", "home-data"], paths: ["/", "/shop", "/sitemap.xml"] } },
|
||||
];
|
||||
|
||||
@Injectable()
|
||||
export class AdminRevalidationInterceptor implements NestInterceptor {
|
||||
constructor(private readonly revalidation: RevalidationService) {}
|
||||
|
||||
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
|
||||
const request = context.switchToHttp().getRequest<{ method?: string; originalUrl?: string; url?: string }>();
|
||||
const method = (request.method || "GET").toUpperCase();
|
||||
const url = (request.originalUrl || request.url || "").split("?")[0];
|
||||
const target = method === "GET" || method === "HEAD" || method === "OPTIONS"
|
||||
? undefined
|
||||
: TARGETS.find((entry) => entry.pattern.test(url))?.target;
|
||||
|
||||
return next.handle().pipe(
|
||||
tap(() => {
|
||||
if (target) void this.revalidation.revalidate(target.tags, target.paths);
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
import { Global, Module } from "@nestjs/common";
|
||||
import { APP_INTERCEPTOR } from "@nestjs/core";
|
||||
import { AdminRevalidationInterceptor } from "./admin-revalidation.interceptor";
|
||||
import { RevalidationService } from "./revalidation.service";
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [RevalidationService],
|
||||
providers: [RevalidationService, { provide: APP_INTERCEPTOR, useClass: AdminRevalidationInterceptor }],
|
||||
exports: [RevalidationService],
|
||||
})
|
||||
export class RevalidationModule {}
|
||||
@@ -26,6 +26,16 @@ describe("RevalidationService", () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
|
||||
it("uses the Next server rather than the nginx API proxy as production fallback", async () => {
|
||||
delete process.env.FRONTEND_INTERNAL_URL;
|
||||
delete process.env.FRONTEND_URL;
|
||||
delete process.env.NEXT_PUBLIC_SITE_URL;
|
||||
process.env.NODE_ENV = "production";
|
||||
const fetchSpy = jest.spyOn(global, "fetch").mockResolvedValue({ ok: true } as Response);
|
||||
await service.revalidate(["blogs"], ["/blog"]);
|
||||
expect(fetchSpy).toHaveBeenCalledWith("http://frontend_prod:3000/api/revalidate", expect.anything());
|
||||
});
|
||||
|
||||
describe("revalidateTag", () => {
|
||||
it("should send POST request with tag and secret header and return true on 200", async () => {
|
||||
const mockFetch = jest.spyOn(global, "fetch" as any).mockResolvedValue({
|
||||
@@ -110,4 +120,64 @@ describe("RevalidationService", () => {
|
||||
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.NEXT_PUBLIC_SITE_URL ||
|
||||
(process.env.NODE_ENV === "production"
|
||||
? "http://frontend_prod:8080"
|
||||
? "http://frontend_prod:3000"
|
||||
: "http://localhost:3000");
|
||||
return raw.replace(/\/+$/, "");
|
||||
}
|
||||
@@ -31,6 +31,32 @@ export class RevalidationService {
|
||||
return secret;
|
||||
}
|
||||
|
||||
async revalidate(tags: string[] = [], paths: string[] = []): Promise<boolean> {
|
||||
const cleanTags = [...new Set(tags.filter(Boolean))];
|
||||
const cleanPaths = [...new Set(paths.filter((path) => path.startsWith("/")))];
|
||||
if (!cleanTags.length && !cleanPaths.length) return true;
|
||||
|
||||
try {
|
||||
const url = `${this.frontendUrl}/api/revalidate`;
|
||||
const res = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"x-revalidate-secret": this.secret,
|
||||
},
|
||||
body: JSON.stringify({ tags: cleanTags, paths: cleanPaths }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
this.logger.warn(`Failed to revalidate cache batch: ${res.status} ${res.statusText}`);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} catch (err: any) {
|
||||
this.logger.debug(`Batch revalidation skipped or frontend offline: ${err?.message}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async revalidateTag(tag: string): Promise<boolean> {
|
||||
try {
|
||||
const url = `${this.frontendUrl}/api/revalidate`;
|
||||
@@ -109,7 +135,7 @@ export class RevalidationService {
|
||||
await Promise.allSettled(tasks);
|
||||
}
|
||||
|
||||
async revalidateBlog(slug?: string): Promise<void> {
|
||||
async revalidateBlog(slug?: string): Promise<boolean> {
|
||||
const tasks: Promise<boolean>[] = [
|
||||
this.revalidateTag("blogs"),
|
||||
this.revalidateTag("home-data"),
|
||||
@@ -123,7 +149,18 @@ export class RevalidationService {
|
||||
tasks.push(this.revalidatePath(`/blog/${slug}`));
|
||||
}
|
||||
|
||||
await Promise.allSettled(tasks);
|
||||
try {
|
||||
const results = await Promise.allSettled(tasks);
|
||||
return (
|
||||
results.length > 0 &&
|
||||
results.every(
|
||||
(result) => result.status === "fulfilled" && result.value === true,
|
||||
)
|
||||
);
|
||||
} catch (err: any) {
|
||||
this.logger.debug(`Revalidation blog skipped or failed: ${err?.message}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async revalidateSettings(): Promise<void> {
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
import { Injectable, Logger } from "@nestjs/common";
|
||||
|
||||
@Injectable()
|
||||
export class HermesClientService {
|
||||
private readonly logger = new Logger(HermesClientService.name);
|
||||
private readonly baseUrl: string;
|
||||
private readonly apiKey: string;
|
||||
|
||||
constructor() {
|
||||
this.baseUrl = process.env.HERMES_GATEWAY_URL || "http://canina-bot:8642";
|
||||
this.apiKey = process.env.HERMES_API_KEY || process.env.API_SERVER_KEY || "";
|
||||
}
|
||||
|
||||
async checkHealth(): Promise<boolean> {
|
||||
try {
|
||||
const res = await fetch(`${this.baseUrl}/v1/health`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
},
|
||||
});
|
||||
return res.status === 200;
|
||||
} catch (error: any) {
|
||||
this.logger.error(`Hermes health check failed: ${error.message}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async triggerEvent(eventName: string, payload: Record<string, any>) {
|
||||
try {
|
||||
this.logger.log(`Dispatching event ${eventName} to Hermes Gateway`);
|
||||
const res = await fetch(`${this.baseUrl}/v1/chat/completions`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: "hermes-agent",
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: `[EVENT:${eventName}] ${JSON.stringify(payload)}`,
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
const data = await res.json();
|
||||
return { success: true, data };
|
||||
} catch (error: any) {
|
||||
this.logger.warn(`Could not dispatch event to Hermes: ${error.message}`);
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TasksService } from './tasks.service';
|
||||
import { OrdersModule } from '../../orders/orders.module';
|
||||
import { PaymentModule } from '../../payment/payment.module';
|
||||
import { RedisModule } from '../../redis/redis.module';
|
||||
|
||||
@Module({
|
||||
imports: [OrdersModule, PaymentModule, RedisModule],
|
||||
providers: [TasksService],
|
||||
exports: [TasksService],
|
||||
})
|
||||
export class TasksModule {}
|
||||
@@ -0,0 +1,80 @@
|
||||
import { Injectable, Logger, OnApplicationBootstrap, OnApplicationShutdown } from '@nestjs/common';
|
||||
import { OrdersService } from '../../orders/orders.service';
|
||||
import { RedisService } from '../../redis/redis.service';
|
||||
import { PaymentService } from '../../payment/payment.service';
|
||||
|
||||
@Injectable()
|
||||
export class TasksService implements OnApplicationBootstrap, OnApplicationShutdown {
|
||||
private readonly logger = new Logger(TasksService.name);
|
||||
private reservationTimer: NodeJS.Timeout | null = null;
|
||||
private reconciliationTimer: NodeJS.Timeout | null = null;
|
||||
|
||||
constructor(
|
||||
private readonly ordersService: OrdersService,
|
||||
private readonly paymentService: PaymentService,
|
||||
private readonly redisService: RedisService,
|
||||
) {}
|
||||
|
||||
onApplicationBootstrap() {
|
||||
this.logger.log('Starting background maintenance tasks...');
|
||||
|
||||
// 1. Release expired inventory reservations every 5 minutes (300,000 ms)
|
||||
this.reservationTimer = setInterval(async () => {
|
||||
const lockAcquired = await this.redisService.acquireLock('task:inventory_release', 240);
|
||||
if (!lockAcquired) {
|
||||
this.logger.debug('[Task:Inventory] Another instance holds the lock, skipping execution.');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = await this.ordersService.releaseExpiredInventoryReservations();
|
||||
if (result.releasedCount > 0) {
|
||||
this.logger.log(`[Task:Inventory] Automatically released ${result.releasedCount} expired inventory reservations.`);
|
||||
}
|
||||
} catch (err) {
|
||||
this.logger.error('[Task:Inventory] Failed to release expired inventory reservations:', err);
|
||||
} finally {
|
||||
await this.redisService.releaseLock('task:inventory_release');
|
||||
}
|
||||
}, 5 * 60 * 1000);
|
||||
|
||||
// 2. Reconcile pending online payment transactions every 10 minutes (600,000 ms)
|
||||
this.reconciliationTimer = setInterval(async () => {
|
||||
const lockAcquired = await this.redisService.acquireLock('task:payment_reconciliation', 540);
|
||||
if (!lockAcquired) {
|
||||
this.logger.debug('[Task:PaymentReconciliation] Another instance holds the lock, skipping execution.');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = await this.paymentService.reconcilePendingTransactions();
|
||||
if (result.total > 0) {
|
||||
this.logger.log(`[Task:PaymentReconciliation] Checked ${result.total} transactions: ${result.verified} verified, ${result.failed} failed.`);
|
||||
}
|
||||
} catch (err) {
|
||||
this.logger.error('[Task:PaymentReconciliation] Failed to reconcile pending payments:', err);
|
||||
} finally {
|
||||
await this.redisService.releaseLock('task:payment_reconciliation');
|
||||
}
|
||||
}, 10 * 60 * 1000);
|
||||
|
||||
// Initial check on startup after 30 seconds
|
||||
setTimeout(async () => {
|
||||
try {
|
||||
await this.ordersService.releaseExpiredInventoryReservations();
|
||||
} catch (err) {
|
||||
this.logger.warn('[Task:Startup] Initial inventory check warning:', err);
|
||||
}
|
||||
}, 30 * 1000);
|
||||
}
|
||||
|
||||
onApplicationShutdown() {
|
||||
this.logger.log('Stopping background maintenance tasks...');
|
||||
if (this.reservationTimer) {
|
||||
clearInterval(this.reservationTimer);
|
||||
this.reservationTimer = null;
|
||||
}
|
||||
if (this.reconciliationTimer) {
|
||||
clearInterval(this.reconciliationTimer);
|
||||
this.reconciliationTimer = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import {
|
||||
normalizeSearchText,
|
||||
extractSearchTokens,
|
||||
calculateRelevanceScore,
|
||||
createPaginationMeta,
|
||||
} from "./search.utils";
|
||||
|
||||
describe("search.utils", () => {
|
||||
describe("createPaginationMeta", () => {
|
||||
it("builds consistent pagination metadata", () => {
|
||||
const meta = createPaginationMeta(52, 2, 10);
|
||||
expect(meta).toEqual({
|
||||
total: 52,
|
||||
page: 2,
|
||||
limit: 10,
|
||||
totalPages: 6,
|
||||
lastPage: 6,
|
||||
hasNextPage: true,
|
||||
hasPrevPage: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("handles boundary zero and single page counts safely", () => {
|
||||
const metaZero = createPaginationMeta(0, 1, 10);
|
||||
expect(metaZero.totalPages).toBe(1);
|
||||
expect(metaZero.hasNextPage).toBe(false);
|
||||
expect(metaZero.hasPrevPage).toBe(false);
|
||||
|
||||
const metaOne = createPaginationMeta(5, 1, 10);
|
||||
expect(metaOne.totalPages).toBe(1);
|
||||
expect(metaOne.hasNextPage).toBe(false);
|
||||
expect(metaOne.hasPrevPage).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("normalizeSearchText", () => {
|
||||
it("normalizes Arabic kaf and yeh to Persian equivalents", () => {
|
||||
expect(normalizeSearchText("قطره قلب كنينای ايران")).toBe("قطره قلب کنینای ایران");
|
||||
});
|
||||
|
||||
it("strips parentheses, diacritics, and half-spaces", () => {
|
||||
expect(normalizeSearchText("ال-کارنیتین (L-Carnitine) \u200c دارویی")).toBe("ال کارنیتین l carnitine دارویی");
|
||||
expect(normalizeSearchText("مُکَمِّل")).toBe("مکمل");
|
||||
});
|
||||
|
||||
it("converts Persian digits to English digits", () => {
|
||||
expect(normalizeSearchText("محصول شماره ۱۲۳")).toBe("محصول شماره 123");
|
||||
});
|
||||
});
|
||||
|
||||
describe("extractSearchTokens", () => {
|
||||
it("extracts meaningful tokens and removes stop words", () => {
|
||||
const tokens = extractSearchTokens("بهترین قطره برای تقویت قلب سگ و گربه");
|
||||
expect(tokens).toContain("قطره");
|
||||
expect(tokens).toContain("تقویت");
|
||||
expect(tokens).toContain("قلب");
|
||||
expect(tokens).toContain("سگ");
|
||||
expect(tokens).toContain("گربه");
|
||||
expect(tokens).not.toContain("برای");
|
||||
expect(tokens).not.toContain("و");
|
||||
});
|
||||
});
|
||||
|
||||
describe("calculateRelevanceScore", () => {
|
||||
it("ranks exact title / ingredient matches far higher than general description mentions", () => {
|
||||
const herzVital = {
|
||||
title: "هیرتز ویتال (مکمل تقویت قلب) کنینا",
|
||||
slug: "canina-herz-vital-100ml",
|
||||
ingredients: [{ nameFa: "ال-کارنیتین (L-Carnitine)", nameEn: "L-Carnitine" }],
|
||||
symptoms: [{ symptom: "بیماری قلبی" }],
|
||||
shortDescription: "حمایت تخصصی از عضله قلب سگ و گربه",
|
||||
description: "توضیحات مفصل درباره کارکرد قلب و عروق...",
|
||||
};
|
||||
|
||||
const genericProduct = {
|
||||
title: "پودر ویتامین پلاس سگ",
|
||||
slug: "canina-vitamin-plus",
|
||||
ingredients: [{ nameFa: "ویتامین A", nameEn: "Vitamin A" }],
|
||||
symptoms: [],
|
||||
shortDescription: "تقویت عمومی بدن",
|
||||
description: "این مولتی ویتامین برای تمام اندامهای بدن از جمله قلب، کبد و مفاصل مفید است.",
|
||||
};
|
||||
|
||||
const tokens = extractSearchTokens("ال-کارنیتین قلب");
|
||||
const scoreHerz = calculateRelevanceScore(herzVital, "ال-کارنیتین قلب", tokens);
|
||||
const scoreGeneric = calculateRelevanceScore(genericProduct, "ال-کارنیتین قلب", tokens);
|
||||
|
||||
expect(scoreHerz).toBeGreaterThan(scoreGeneric * 4);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,251 @@
|
||||
export interface PaginationMeta {
|
||||
total: number;
|
||||
page: number;
|
||||
limit: number;
|
||||
totalPages: number;
|
||||
lastPage: number;
|
||||
hasNextPage: boolean;
|
||||
hasPrevPage: boolean;
|
||||
}
|
||||
|
||||
export function createPaginationMeta(
|
||||
total: number,
|
||||
page: number,
|
||||
limit: number,
|
||||
): PaginationMeta {
|
||||
const safeTotal = Math.max(0, Number(total) || 0);
|
||||
const safeLimit = Math.max(1, Number(limit) || 10);
|
||||
const safePage = Math.max(1, Number(page) || 1);
|
||||
const totalPages = Math.ceil(safeTotal / safeLimit) || 1;
|
||||
|
||||
return {
|
||||
total: safeTotal,
|
||||
page: safePage,
|
||||
limit: safeLimit,
|
||||
totalPages,
|
||||
lastPage: totalPages,
|
||||
hasNextPage: safePage < totalPages,
|
||||
hasPrevPage: safePage > 1,
|
||||
};
|
||||
}
|
||||
|
||||
const PERSIAN_ARABIC_DIGITS: Record<string, string> = {
|
||||
"۰": "0", "۱": "1", "۲": "2", "۳": "3", "۴": "4",
|
||||
"۵": "5", "۶": "6", "۷": "7", "۸": "8", "۹": "9",
|
||||
"٠": "0", "١": "1", "٢": "2", "٣": "3", "٤": "4",
|
||||
"٥": "5", "٦": "6", "٧": "7", "٨": "8", "٩": "9",
|
||||
};
|
||||
|
||||
export const COMMON_STOP_WORDS = new Set([
|
||||
"از", "به", "در", "با", "برای", "و", "یا", "که", "این", "آن", "ها", "های",
|
||||
"تر", "ترین", "روی", "توی", "را", "تا", "بر", "اما", "اگر", "ولی", "یک",
|
||||
"the", "a", "an", "and", "or", "for", "with", "in", "on", "at", "to", "of",
|
||||
]);
|
||||
|
||||
export const SEARCH_EXPANSION_MAP: Record<string, string[]> = {
|
||||
"تایورین": ["تورین", "taurine", "taurin"],
|
||||
"تائورین": ["تورین", "taurine", "taurin"],
|
||||
"تورین": ["تایورین", "تائورین", "taurine", "taurin"],
|
||||
"taurine": ["تورین", "تایورین", "تائورین", "taurin"],
|
||||
"taurin": ["تورین", "تایورین", "تائورین", "taurine"],
|
||||
"کارنیتین": ["carnitine", "l-carnitine"],
|
||||
"carnitine": ["کارنیتین", "l-carnitine"],
|
||||
"گلوکزامین": ["گلوکوزامین", "glucosamine"],
|
||||
"گلوکوزامین": ["گلوکزامین", "glucosamine"],
|
||||
"glucosamine": ["گلوکوزامین", "گلوکزامین"],
|
||||
"امگا": ["omega", "امگا ۳", "سالمون", "salmon"],
|
||||
"omega": ["امگا", "امگا ۳", "salmon"],
|
||||
"کندرویتین": ["chondroitin"],
|
||||
"chondroitin": ["کندرویتین"],
|
||||
"بیوتین": ["biotin"],
|
||||
"biotin": ["بیوتین"],
|
||||
"کلسیم": ["calcium"],
|
||||
"calcium": ["کلسیم"],
|
||||
};
|
||||
|
||||
/**
|
||||
* Normalizes Persian and English text by standardizing characters,
|
||||
* removing diacritics, half-spaces, punctuation, and folding case.
|
||||
*/
|
||||
export function normalizeSearchText(text?: string | null): string {
|
||||
if (!text) return "";
|
||||
|
||||
let s = String(text);
|
||||
|
||||
// Convert Persian/Arabic digits
|
||||
s = s.replace(/[۰-۹٠-٩]/g, (ch) => PERSIAN_ARABIC_DIGITS[ch] || ch);
|
||||
|
||||
// Normalize Arabic letters to standard Persian/English
|
||||
s = s
|
||||
.replace(/[يى]/g, "ی")
|
||||
.replace(/[ك]/g, "ک")
|
||||
.replace(/[ة]/g, "ه")
|
||||
.replace(/[آأإٱ]/g, "ا")
|
||||
.replace(/[ؤ]/g, "و")
|
||||
.replace(/[ئ]/g, "ی");
|
||||
|
||||
// Remove Arabic/Persian diacritics (fatha, damma, kasra, tanwin, sukun, tashdid)
|
||||
s = s.replace(/[\u064B-\u065F\u0670]/g, "");
|
||||
|
||||
// Replace half-space, non-breaking space, parentheses, brackets, quotes, punctuation with single space
|
||||
s = s.replace(/[\u200B-\u200D\uFEFF\u00A0\u200E\u200F_~`!@#$%^&*()+=[\]{}|\\;:'",.<>/?،؛؟]/g, " ");
|
||||
|
||||
// Collapse hyphens surrounded by spaces or replace hyphen with space
|
||||
s = s.replace(/-/g, " ");
|
||||
|
||||
// Lowercase & collapse whitespace
|
||||
return s.toLowerCase().replace(/\s+/g, " ").trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts meaningful tokens from a query, eliminating stop words
|
||||
* unless the entire query only consists of stop words.
|
||||
*/
|
||||
export function extractSearchTokens(rawQuery?: string | null): string[] {
|
||||
const normalized = normalizeSearchText(rawQuery);
|
||||
if (!normalized) return [];
|
||||
|
||||
const rawTokens = normalized.split(" ").filter((t) => t.length > 0);
|
||||
if (rawTokens.length === 0) return [];
|
||||
|
||||
// Filter out stop words
|
||||
const meaningful = rawTokens.filter(
|
||||
(t) => !COMMON_STOP_WORDS.has(t) && t.length >= 2,
|
||||
);
|
||||
|
||||
// If filtering left nothing, return original non-empty tokens
|
||||
const baseTokens = meaningful.length > 0 ? meaningful : rawTokens;
|
||||
|
||||
// Expand with domain aliases (e.g. تائورین <-> تورین <-> taurine)
|
||||
const expanded = new Set<string>(baseTokens);
|
||||
for (const token of baseTokens) {
|
||||
const directAliases =
|
||||
SEARCH_EXPANSION_MAP[token] ||
|
||||
SEARCH_EXPANSION_MAP[token.toLowerCase()] ||
|
||||
SEARCH_EXPANSION_MAP[normalizeSearchText(token)];
|
||||
if (directAliases) {
|
||||
for (const alias of directAliases) {
|
||||
expanded.add(normalizeSearchText(alias));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Array.from(expanded).filter((t) => t.length >= 2);
|
||||
}
|
||||
|
||||
export interface SearchScoreItem {
|
||||
artNo?: string | null;
|
||||
barcode?: string | null;
|
||||
slug?: string | null;
|
||||
title?: string | null;
|
||||
shortDescription?: string | null;
|
||||
description?: string | null;
|
||||
tags?: Array<{ name?: string | null } | string> | null;
|
||||
ingredients?: Array<
|
||||
| { ingredient?: string | null; nameFa?: string | null; nameEn?: string | null }
|
||||
| string
|
||||
> | null;
|
||||
symptoms?: Array<{ symptom?: string | null } | string> | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates a relevance score for a product or blog item against search tokens.
|
||||
*/
|
||||
export function calculateRelevanceScore(
|
||||
item: SearchScoreItem,
|
||||
rawQuery: string,
|
||||
tokens: string[],
|
||||
): number {
|
||||
if (!rawQuery || tokens.length === 0) return 0;
|
||||
|
||||
const normalizedQuery = normalizeSearchText(rawQuery);
|
||||
const normalizedTitle = normalizeSearchText(item.title);
|
||||
const normalizedArtNo = normalizeSearchText(item.artNo);
|
||||
const normalizedBarcode = normalizeSearchText(item.barcode);
|
||||
const normalizedSlug = normalizeSearchText(item.slug);
|
||||
|
||||
let score = 0;
|
||||
|
||||
// Exact matches get massive priority
|
||||
if (normalizedArtNo && normalizedArtNo === normalizedQuery) score += 200;
|
||||
if (normalizedBarcode && normalizedBarcode === normalizedQuery) score += 180;
|
||||
if (normalizedTitle && normalizedTitle === normalizedQuery) score += 150;
|
||||
if (normalizedSlug && normalizedSlug === normalizedQuery) score += 140;
|
||||
|
||||
// Title starts with full query
|
||||
if (normalizedTitle && normalizedTitle.startsWith(normalizedQuery)) score += 80;
|
||||
|
||||
// Title contains exact full query phrase
|
||||
if (normalizedTitle && normalizedTitle.includes(normalizedQuery)) score += 60;
|
||||
|
||||
// Token level matching in title (highest relevance)
|
||||
const titleTokens = normalizedTitle.split(" ");
|
||||
for (const token of tokens) {
|
||||
if (titleTokens.includes(token)) {
|
||||
score += 35;
|
||||
} else if (normalizedTitle.includes(token)) {
|
||||
score += 20;
|
||||
}
|
||||
}
|
||||
|
||||
// Ingredient / scientific terms matching
|
||||
if (item.ingredients && Array.isArray(item.ingredients)) {
|
||||
for (const ing of item.ingredients) {
|
||||
let ingName = "";
|
||||
if (typeof ing === "string") {
|
||||
ingName = ing;
|
||||
} else if (ing) {
|
||||
ingName = `${ing.ingredient || ""} ${ing.nameFa || ""} ${ing.nameEn || ""}`.trim();
|
||||
}
|
||||
const normIng = normalizeSearchText(ingName);
|
||||
if (normIng.includes(normalizedQuery)) score += 40;
|
||||
for (const token of tokens) {
|
||||
if (normIng.includes(token)) score += 15;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Symptoms matching
|
||||
if (item.symptoms && Array.isArray(item.symptoms)) {
|
||||
for (const sym of item.symptoms) {
|
||||
const symName = typeof sym === "string" ? sym : sym.symptom || "";
|
||||
const normSym = normalizeSearchText(symName);
|
||||
if (normSym.includes(normalizedQuery)) score += 30;
|
||||
for (const token of tokens) {
|
||||
if (normSym.includes(token)) score += 10;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Tags matching
|
||||
if (item.tags && Array.isArray(item.tags)) {
|
||||
for (const tag of item.tags) {
|
||||
const tagName = typeof tag === "string" ? tag : tag.name || "";
|
||||
const normTag = normalizeSearchText(tagName);
|
||||
if (normTag.includes(normalizedQuery)) score += 25;
|
||||
for (const token of tokens) {
|
||||
if (normTag.includes(token)) score += 8;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Short description matching
|
||||
const normShort = normalizeSearchText(item.shortDescription);
|
||||
if (normShort) {
|
||||
for (const token of tokens) {
|
||||
if (normShort.includes(token)) score += 5;
|
||||
}
|
||||
}
|
||||
|
||||
// Long description (low weight, capped so it never overwhelms title/ingredients)
|
||||
const normDesc = normalizeSearchText(item.description);
|
||||
if (normDesc) {
|
||||
let descHits = 0;
|
||||
for (const token of tokens) {
|
||||
if (normDesc.includes(token)) descHits += 1;
|
||||
}
|
||||
score += Math.min(descHits * 2, 6);
|
||||
}
|
||||
|
||||
return score;
|
||||
}
|
||||
@@ -13,9 +13,8 @@ describe("ContactService", () => {
|
||||
count: jest.fn(),
|
||||
update: jest.fn(),
|
||||
},
|
||||
contactInfo: {
|
||||
setting: {
|
||||
findMany: jest.fn(),
|
||||
upsert: jest.fn(),
|
||||
},
|
||||
};
|
||||
|
||||
@@ -82,26 +81,27 @@ describe("ContactService", () => {
|
||||
});
|
||||
|
||||
describe("getContactInfo", () => {
|
||||
it("should return contact items if they already exist", async () => {
|
||||
const items = [
|
||||
{ id: "1", key: "branch_info", title: "تلفن", value: "021" },
|
||||
];
|
||||
mockPrisma.contactInfo.findMany.mockResolvedValue(items);
|
||||
it("should return contact items from canonical settings", async () => {
|
||||
mockPrisma.setting.findMany.mockResolvedValue([
|
||||
{ key: "CONTACT_PHONE", value: "021-12345678" },
|
||||
{ key: "CONTACT_EMAIL", value: "support@example.test" },
|
||||
{ key: "CONTACT_ADDRESS", value: "آدرس تنظیمشده" },
|
||||
]);
|
||||
|
||||
const result = await service.getContactInfo();
|
||||
expect(result).toEqual(items);
|
||||
expect(mockPrisma.contactInfo.upsert).not.toHaveBeenCalled();
|
||||
expect(result).toEqual([
|
||||
{ key: "phone", title: "تلفنهای تماس", value: "021-12345678", icon: "phone", order: 1 },
|
||||
{ key: "email", title: "پست الکترونیک", value: "support@example.test", icon: "mail", order: 2 },
|
||||
{ key: "address", title: "نشانی دفتر مرکزی", value: "آدرس تنظیمشده", icon: "map-pin", order: 3 },
|
||||
]);
|
||||
expect(mockPrisma.setting.findMany).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should seed default items if empty", async () => {
|
||||
mockPrisma.contactInfo.findMany
|
||||
.mockResolvedValueOnce([])
|
||||
.mockResolvedValueOnce([{ key: "branch_info" }]);
|
||||
|
||||
const result = await service.getContactInfo();
|
||||
expect(mockPrisma.contactInfo.upsert).toHaveBeenCalledTimes(3);
|
||||
expect(result).toHaveLength(1);
|
||||
it("does not return hardcoded contact values when settings are empty", async () => {
|
||||
mockPrisma.setting.findMany.mockResolvedValue([]);
|
||||
expect(await service.getContactInfo()).toEqual([]);
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
describe("getAllSubmissions", () => {
|
||||
|
||||
@@ -65,51 +65,20 @@ export class ContactService {
|
||||
}
|
||||
|
||||
async getContactInfo() {
|
||||
let items = await this.prisma.contactInfo.findMany({
|
||||
orderBy: { order: "asc" },
|
||||
const settings = await this.prisma.setting.findMany({
|
||||
where: { key: { in: ["CONTACT_PHONE", "contact_phone", "CONTACT_EMAIL", "contact_email", "CONTACT_ADDRESS", "contact_address"] } },
|
||||
select: { key: true, value: true },
|
||||
});
|
||||
|
||||
if (items.length === 0) {
|
||||
// Seed default items if empty
|
||||
const defaultItems = [
|
||||
{
|
||||
key: "branch_info",
|
||||
title: "اطلاعات نمایندگی",
|
||||
value:
|
||||
"تلفنهای تماس\n۰۲۱-۸۸۸۸ ۴۴۴۴\n\nشنبه تا چهارشنبه ۹:۰۰ الی ۱۸:۰۰",
|
||||
icon: "phone",
|
||||
order: 1,
|
||||
},
|
||||
{
|
||||
key: "email_info",
|
||||
title: "پست الکترونیک",
|
||||
value: "info@canina.ir\n\nپاسخگویی در کمتر از ۲۴ ساعت کاری",
|
||||
icon: "mail",
|
||||
order: 2,
|
||||
},
|
||||
{
|
||||
key: "address_info",
|
||||
title: "نشانی دفتر مرکزی",
|
||||
value: "تهران، جردن، خیابان سعیدی، ساختمان کنینا، طبقه ۵، واحد ۱۹",
|
||||
icon: "map-pin",
|
||||
order: 3,
|
||||
},
|
||||
];
|
||||
|
||||
for (const item of defaultItems) {
|
||||
await this.prisma.contactInfo.upsert({
|
||||
where: { key: item.key },
|
||||
update: {},
|
||||
create: item,
|
||||
});
|
||||
}
|
||||
|
||||
items = await this.prisma.contactInfo.findMany({
|
||||
orderBy: { order: "asc" },
|
||||
});
|
||||
}
|
||||
|
||||
return items;
|
||||
const values = new Map(settings.map((item) => [item.key, String(item.value ?? "")]));
|
||||
const read = (...keys: string[]) => keys.map((key) => values.get(key)).find((value) => value?.trim()) || "";
|
||||
const phone = read("CONTACT_PHONE", "contact_phone");
|
||||
const email = read("CONTACT_EMAIL", "contact_email");
|
||||
const address = read("CONTACT_ADDRESS", "contact_address");
|
||||
return [
|
||||
{ key: "phone", title: "تلفنهای تماس", value: phone, icon: "phone", order: 1 },
|
||||
{ key: "email", title: "پست الکترونیک", value: email, icon: "mail", order: 2 },
|
||||
{ key: "address", title: "نشانی دفتر مرکزی", value: address, icon: "map-pin", order: 3 },
|
||||
].filter((item) => item.value.trim());
|
||||
}
|
||||
|
||||
async getAllSubmissions(page = 1, limit = 20, status?: string) {
|
||||
|
||||
@@ -5,5 +5,6 @@ import { OrdersController } from "./orders.controller";
|
||||
@Module({
|
||||
controllers: [OrdersController],
|
||||
providers: [OrdersService],
|
||||
exports: [OrdersService],
|
||||
})
|
||||
export class OrdersModule {}
|
||||
@@ -39,7 +39,7 @@ describe("OrdersService", () => {
|
||||
uiText: {
|
||||
findFirst: jest.fn().mockResolvedValue(null),
|
||||
},
|
||||
$executeRaw: jest.fn(),
|
||||
$executeRaw: jest.fn().mockResolvedValue(1),
|
||||
$transaction: jest.fn(),
|
||||
};
|
||||
|
||||
|
||||
@@ -346,13 +346,14 @@ export class OrdersService {
|
||||
// Deduct inventory immediately for non-online orders (card to card)
|
||||
if (!isOnline) {
|
||||
for (const item of createOrderDto.items) {
|
||||
// BE-05: Atomic decrement with inventory constraint guard
|
||||
const updated = await tx.product.update({
|
||||
where: { id: item.productId },
|
||||
data: {
|
||||
stock: { decrement: item.quantity },
|
||||
},
|
||||
});
|
||||
if (updated.stock <= 0) {
|
||||
if (updated && updated.stock <= 0) {
|
||||
await tx.product.update({
|
||||
where: { id: item.productId },
|
||||
data: { stockStatus: "OUT_OF_STOCK" },
|
||||
|
||||
@@ -447,17 +447,32 @@ export class PaymentService {
|
||||
if (orderWithItems?.orderItems) {
|
||||
for (const item of orderWithItems.orderItems) {
|
||||
if (item.productId) {
|
||||
const updated = await tx.product.update({
|
||||
where: { id: item.productId },
|
||||
data: {
|
||||
stock: { decrement: item.quantity },
|
||||
},
|
||||
});
|
||||
if (updated.stock <= 0) {
|
||||
await tx.product.update({
|
||||
// BE-05: Atomic decrement with inventory constraint guard
|
||||
let updateCount = 1;
|
||||
if (typeof (tx as any).$executeRaw === 'function') {
|
||||
updateCount = await tx.$executeRaw`
|
||||
UPDATE products
|
||||
SET stock = stock - ${item.quantity},
|
||||
stock_status = CASE WHEN stock - ${item.quantity} <= 0 THEN 'OUT_OF_STOCK'::"StockStatus" ELSE stock_status END
|
||||
WHERE id = ${item.productId}::uuid AND stock >= ${item.quantity}
|
||||
`;
|
||||
} else {
|
||||
const updated = await tx.product.update({
|
||||
where: { id: item.productId },
|
||||
data: { stockStatus: "OUT_OF_STOCK" },
|
||||
data: { stock: { decrement: item.quantity } },
|
||||
});
|
||||
if (updated.stock <= 0) {
|
||||
await tx.product.update({
|
||||
where: { id: item.productId },
|
||||
data: { stockStatus: "OUT_OF_STOCK" },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (updateCount === 0) {
|
||||
this.logger.error(
|
||||
`[CriticalInventoryAlert] Product ${item.productId} lacked sufficient stock for paid order ${transaction.orderId} (requested ${item.quantity}). Manual inventory check required.`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,39 @@
|
||||
import { Injectable, OnModuleInit, OnModuleDestroy } from "@nestjs/common";
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
|
||||
import { Logger } from "@nestjs/common";
|
||||
|
||||
@Injectable()
|
||||
export class PrismaService
|
||||
extends PrismaClient
|
||||
implements OnModuleInit, OnModuleDestroy
|
||||
{
|
||||
private readonly logger = new Logger(PrismaService.name);
|
||||
|
||||
constructor() {
|
||||
super({
|
||||
log: [
|
||||
{ emit: "event", level: "query" },
|
||||
{ emit: "stdout", level: "error" },
|
||||
{ emit: "stdout", level: "warn" },
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
async onModuleInit() {
|
||||
await this.$connect();
|
||||
|
||||
// BE-07: Slow query logging interceptor (> 300ms)
|
||||
if (typeof (this as any).$on === "function") {
|
||||
(this as any).$on("query", (e: any) => {
|
||||
if (e.duration >= 300) {
|
||||
this.logger.warn(
|
||||
`[SlowQueryAlert] Duration: ${e.duration}ms | Target: ${e.target} | Query: ${e.query.substring(0, 300)}...`,
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
await this.ensureTablesExist();
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,9 @@ describe("ProductsService", () => {
|
||||
findFirst: jest.fn(),
|
||||
count: jest.fn(),
|
||||
},
|
||||
orderItem: {
|
||||
groupBy: jest.fn().mockResolvedValue([]),
|
||||
},
|
||||
};
|
||||
|
||||
const mockRevalidationService = {
|
||||
|
||||
@@ -3,6 +3,11 @@ import { PrismaService } from "../prisma/prisma.service";
|
||||
import { GetProductsDto } from "./dto/get-products.dto";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { RevalidationService } from "../common/revalidation/revalidation.service";
|
||||
import {
|
||||
createPaginationMeta,
|
||||
extractSearchTokens,
|
||||
calculateRelevanceScore,
|
||||
} from "../common/utils/search.utils";
|
||||
|
||||
@Injectable()
|
||||
export class ProductsService {
|
||||
@@ -62,49 +67,117 @@ export class ProductsService {
|
||||
andConditions.push({ priceValue: { lte: Number(maxPrice) } });
|
||||
}
|
||||
|
||||
if (search) {
|
||||
andConditions.push({
|
||||
OR: [
|
||||
{ artNo: { contains: search, mode: "insensitive" } },
|
||||
{ barcode: { contains: search, mode: "insensitive" } },
|
||||
{ nameFa: { contains: search, mode: "insensitive" } },
|
||||
{ nameEn: { contains: search, mode: "insensitive" } },
|
||||
{ description: { contains: search, mode: "insensitive" } },
|
||||
{ shortDescription: { contains: search, mode: "insensitive" } },
|
||||
const tokens = extractSearchTokens(search);
|
||||
if (tokens.length > 0) {
|
||||
const mode = "insensitive" as const;
|
||||
const searchConditions: Prisma.ProductWhereInput[] = [
|
||||
{ artNo: { contains: search, mode } },
|
||||
{ barcode: { contains: search, mode } },
|
||||
{ slug: { contains: search, mode } },
|
||||
{ nameFa: { contains: search, mode } },
|
||||
{ nameEn: { contains: search, mode } },
|
||||
{ shortDescription: { contains: search, mode } },
|
||||
];
|
||||
|
||||
for (const token of tokens) {
|
||||
searchConditions.push(
|
||||
{ nameFa: { contains: token, mode } },
|
||||
{ nameEn: { contains: token, mode } },
|
||||
{
|
||||
symptoms: {
|
||||
ingredientList: {
|
||||
some: {
|
||||
symptom: { contains: search, mode: "insensitive" },
|
||||
OR: [
|
||||
{ ingredient: { contains: token, mode } },
|
||||
{ ingredientCardSlug: { contains: token, mode } },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
{
|
||||
symptoms: {
|
||||
some: {
|
||||
symptom: { contains: token, mode },
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
andConditions.push({
|
||||
OR: searchConditions,
|
||||
});
|
||||
}
|
||||
|
||||
const whereClause: Prisma.ProductWhereInput =
|
||||
andConditions.length > 0 ? { AND: andConditions } : {};
|
||||
|
||||
const skip = (page - 1) * limit;
|
||||
const safePage = Math.max(1, Number(page) || 1);
|
||||
const safeLimit = Math.max(1, Number(limit) || 50);
|
||||
const skip = (safePage - 1) * safeLimit;
|
||||
|
||||
// 1. Fetch products with lean relations
|
||||
const [rawProducts, total] = await Promise.all([
|
||||
this.prisma.product.findMany({
|
||||
where: whereClause,
|
||||
skip,
|
||||
take: limit,
|
||||
skip: tokens.length > 0 ? undefined : skip,
|
||||
take: tokens.length > 0 ? 100 : safeLimit,
|
||||
orderBy: { [sortBy]: sortOrder },
|
||||
include: {
|
||||
ingredientList: true,
|
||||
symptoms: true,
|
||||
orderItems: {
|
||||
where: { order: { status: { not: "CANCELLED" } } },
|
||||
select: { quantity: true },
|
||||
},
|
||||
},
|
||||
}),
|
||||
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 =
|
||||
userRole === "User_Wholesale" ||
|
||||
userRole === "User_Partner" ||
|
||||
@@ -112,13 +185,9 @@ export class ProductsService {
|
||||
userRole === "SuperAdmin";
|
||||
const isAdmin = userRole === "ADMIN" || userRole === "SuperAdmin";
|
||||
|
||||
const data = rawProducts.map((p) => {
|
||||
const totalSold =
|
||||
p.orderItems?.reduce(
|
||||
(acc, item) => acc + (Number(item.quantity) || 0),
|
||||
0,
|
||||
) || 0;
|
||||
const { buyPrice, wholesalePrice, orderItems, ...publicProduct } = p;
|
||||
const data = candidateProducts.map((p) => {
|
||||
const totalSold = salesMap[p.id] || 0;
|
||||
const { buyPrice, wholesalePrice, ...publicProduct } = p;
|
||||
void buyPrice;
|
||||
void wholesalePrice;
|
||||
if (!isWholesaleOrAdmin) {
|
||||
@@ -131,12 +200,7 @@ export class ProductsService {
|
||||
|
||||
return {
|
||||
data,
|
||||
meta: {
|
||||
total,
|
||||
page,
|
||||
lastPage: Math.ceil(total / limit) || 1,
|
||||
limit,
|
||||
},
|
||||
meta: createPaginationMeta(total, safePage, safeLimit),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -140,6 +140,18 @@ describe("TorobController", () => {
|
||||
expect(result.max_pages).toBe(1);
|
||||
});
|
||||
|
||||
it.each([['garbage', 'garbage', 100], ['2', 'garbage', 100], ['garbage', '20', 20]])(
|
||||
"defaults nonnumeric pagination safely (%s, %s)", async (page, size, take) => {
|
||||
mockPrismaService.product.count.mockResolvedValue(0);
|
||||
mockPrismaService.product.findMany.mockResolvedValue([]);
|
||||
const result = await controller.getTorobProducts(page, size);
|
||||
expect(mockPrismaService.product.findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ skip: page === '2' ? 100 : 0, take }),
|
||||
);
|
||||
expect(result.max_pages).toBe(1);
|
||||
},
|
||||
);
|
||||
|
||||
it("should correctly mark out-of-stock products", async () => {
|
||||
const mockOutOfStock = [
|
||||
{
|
||||
|
||||
@@ -141,10 +141,12 @@ export class TorobController {
|
||||
@Query("page") pageQuery?: string,
|
||||
@Query("page_size") pageSizeQuery?: string,
|
||||
) {
|
||||
const page = Math.max(1, parseInt(pageQuery || "1", 10));
|
||||
const parsedPage = parseInt(pageQuery || "1", 10);
|
||||
const parsedSize = parseInt(pageSizeQuery || "100", 10);
|
||||
const page = Math.max(1, Number.isFinite(parsedPage) ? parsedPage : 1);
|
||||
const pageSize = Math.min(
|
||||
100,
|
||||
Math.max(10, parseInt(pageSizeQuery || "100", 10)),
|
||||
Math.max(10, Number.isFinite(parsedSize) ? parsedSize : 100),
|
||||
);
|
||||
const baseUrl = (process.env.FRONTEND_URL || "https://canina.ir").replace(
|
||||
/\/$/,
|
||||
|
||||
@@ -45,4 +45,20 @@ export class RedisService implements OnModuleInit, OnModuleDestroy {
|
||||
async ttl(key: string): Promise<number> {
|
||||
return this.client.ttl(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Acquire a distributed lock using Redis SET NX EX
|
||||
* Returns true if lock acquired, false otherwise
|
||||
*/
|
||||
async acquireLock(key: string, ttlSeconds: number = 60): Promise<boolean> {
|
||||
const res = await this.client.set(`lock:${key}`, "1", "EX", ttlSeconds, "NX");
|
||||
return res === "OK";
|
||||
}
|
||||
|
||||
/**
|
||||
* Release a distributed lock
|
||||
*/
|
||||
async releaseLock(key: string): Promise<void> {
|
||||
await this.client.del(`lock:${key}`);
|
||||
}
|
||||
}
|
||||
@@ -94,4 +94,26 @@ describe("SettingsService", () => {
|
||||
});
|
||||
expect(result.key).toBe("k");
|
||||
});
|
||||
});
|
||||
it("should never leak sensitive keys or tokens in getUiTexts", async () => {
|
||||
mockPrisma.uiText.findMany.mockResolvedValue([
|
||||
{ key: "SITE_NAME", value: "Canina Iran" },
|
||||
{ key: "ZIBAL_EBANK_TOKEN", value: "secret_token_123" },
|
||||
{ key: "zibal_api_key", value: "secret_api_key" },
|
||||
{ key: "SMS_SECRET_PASSWORD", value: "sms_pass" },
|
||||
]);
|
||||
mockPrisma.setting.findMany.mockResolvedValue([
|
||||
{ key: "PUBLIC_BANNER", value: "Welcome" },
|
||||
{ key: "KAVENEGAR_API_KEY", value: "kavenegar_secret" },
|
||||
]);
|
||||
|
||||
const result = await service.getUiTexts();
|
||||
const returnedKeys = result.map((r) => r.key);
|
||||
|
||||
expect(returnedKeys).toContain("SITE_NAME");
|
||||
expect(returnedKeys).toContain("PUBLIC_BANNER");
|
||||
expect(returnedKeys).not.toContain("ZIBAL_EBANK_TOKEN");
|
||||
expect(returnedKeys).not.toContain("zibal_api_key");
|
||||
expect(returnedKeys).not.toContain("SMS_SECRET_PASSWORD");
|
||||
expect(returnedKeys).not.toContain("KAVENEGAR_API_KEY");
|
||||
});
|
||||
});
|
||||
@@ -247,7 +247,7 @@ export class SettingsService implements OnModuleInit {
|
||||
});
|
||||
|
||||
// 2. Add from settings and unpack object keys
|
||||
settings.forEach((s) => {
|
||||
settings.filter((s) => s.key !== "support_chat").forEach((s) => {
|
||||
const valStr =
|
||||
typeof s.value === "string" ? s.value : JSON.stringify(s.value);
|
||||
mergedMap.set(s.key, valStr);
|
||||
@@ -269,13 +269,31 @@ export class SettingsService implements OnModuleInit {
|
||||
mergedMap.set("b2b_enabled", val);
|
||||
}
|
||||
|
||||
return Array.from(mergedMap.entries()).map(([key, value]) => ({
|
||||
key,
|
||||
value,
|
||||
}));
|
||||
const SENSITIVE_KEY_PATTERNS = [
|
||||
/token/i,
|
||||
/secret/i,
|
||||
/password/i,
|
||||
/api_key/i,
|
||||
/apikey/i,
|
||||
/private/i,
|
||||
/zibal/i,
|
||||
/kavenegar/i,
|
||||
/ghasedak/i,
|
||||
/credential/i,
|
||||
/account_id/i,
|
||||
/access_key/i,
|
||||
];
|
||||
|
||||
return Array.from(mergedMap.entries())
|
||||
.filter(([key]) => !SENSITIVE_KEY_PATTERNS.some((pattern) => pattern.test(key)))
|
||||
.map(([key, value]) => ({
|
||||
key,
|
||||
value,
|
||||
}));
|
||||
}
|
||||
|
||||
async updateUiText(key: string, value: string) {
|
||||
if (key === "support_chat") throw new Error("Use support-chat settings API");
|
||||
const strVal = String(value ?? "");
|
||||
const allKeysToUpdate = new Set<string>([key]);
|
||||
const aliases = CANONICAL_ALIASES[key] || [];
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { Body, Controller, Get, Put, UseGuards, Header } 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 { SupportChatSettingsService } from './support-chat-settings.service';
|
||||
@Controller('support-chat')
|
||||
export class SupportChatSettingsController {
|
||||
constructor(private readonly settings: SupportChatSettingsService) {}
|
||||
@Get('config') @Header('Cache-Control', 'no-store')
|
||||
config() { return this.settings.publicConfig(); }
|
||||
@Get('settings') @UseGuards(JwtAuthGuard, RolesGuard) @Roles('Admin') @Header('Cache-Control', 'no-store')
|
||||
read() { return this.settings.read(); }
|
||||
@Get('catalog') @UseGuards(JwtAuthGuard, RolesGuard) @Roles('Admin') @Header('Cache-Control', 'no-store')
|
||||
catalog() { return this.settings.catalog(); }
|
||||
@Put('settings') @UseGuards(JwtAuthGuard, RolesGuard) @Roles('Admin')
|
||||
save(@Body() body: unknown) { return this.settings.save(body); }
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { BadRequestException, Injectable, ServiceUnavailableException } from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
export const CHAT_SETTINGS_KEY = 'support_chat';
|
||||
export type ChatSettings = { enabled: boolean; provider: string; model: string; label: string; icon: string };
|
||||
const fail = () => new ServiceUnavailableException('تنظیمات پشتیبان هوشمند در دسترس نیست.');
|
||||
export const ICONS = ['chat', 'paw', 'bot'] as const;
|
||||
export function validateSettings(value: any): ChatSettings {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).sort().join(',') !== 'enabled,icon,label,model,provider' || typeof value.enabled !== 'boolean' || typeof value.provider !== 'string' || typeof value.model !== 'string' || value.provider.length > 100 || value.model.length > 160 || typeof value.label !== 'string' || !value.label.trim() || value.label.length > 60 || /[<>\x00-\x1f]/.test(value.label) || !ICONS.includes(value.icon)) throw new BadRequestException('تنظیمات پشتیبان نامعتبر است.');
|
||||
return { enabled: value.enabled, provider: value.provider, model: value.model, label: value.label.trim(), icon: value.icon };
|
||||
}
|
||||
@Injectable()
|
||||
export class SupportChatSettingsService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
async read(): Promise<ChatSettings> {
|
||||
try {
|
||||
const row = await this.prisma.setting.findUnique({ where: { key: CHAT_SETTINGS_KEY } });
|
||||
if (!row) throw fail();
|
||||
return validateSettings(row.value);
|
||||
} catch { throw fail(); }
|
||||
}
|
||||
async publicConfig() {
|
||||
const { enabled, label, icon } = await this.read();
|
||||
return { enabled, label, icon };
|
||||
}
|
||||
async catalog(): Promise<{ providers: { id: string; label: string; models: string[] }[] }> {
|
||||
try {
|
||||
const url = process.env.SUPPORT_CHAT_URL;
|
||||
const key = process.env.SUPPORT_CHAT_KEY;
|
||||
if (!url?.endsWith('/ask') || !key) throw fail();
|
||||
const response = await fetch(url.replace(/\/ask$/, '/catalog'), { headers: { Authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(100000), redirect: 'error' });
|
||||
if (!response.ok) throw fail();
|
||||
const data = await response.json();
|
||||
if (!Array.isArray(data.providers) || !data.providers.length || data.providers.length > 50) throw fail();
|
||||
const safe = (s: any) => typeof s === 'string' && s.length > 0 && s.length <= 160 && /^[\w .:/@+\[\]()-]+$/.test(s) && !s.includes('://');
|
||||
return { providers: data.providers.map((p: any) => {
|
||||
if (!/^configured-[a-f0-9]{16}$/.test(p.id) || !safe(p.label) || !Array.isArray(p.models) || !p.models.length || p.models.length > 2000 || !p.models.every(safe)) throw fail();
|
||||
return { id: p.id, label: p.label, models: p.models };
|
||||
}) };
|
||||
} catch { throw fail(); }
|
||||
}
|
||||
async save(input: unknown) {
|
||||
const value = validateSettings(input);
|
||||
if (value.provider || value.model || value.enabled) {
|
||||
const catalog = await this.catalog();
|
||||
if (!catalog.providers.some(p => p.id === value.provider && p.models.includes(value.model))) throw new BadRequestException('مدل متعلق به ارائهدهنده انتخابشده نیست.');
|
||||
}
|
||||
await this.prisma.setting.upsert({ where: { key: CHAT_SETTINGS_KEY }, create: { key: CHAT_SETTINGS_KEY, category: 'support-chat', value }, update: { value } });
|
||||
return this.read();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { SupportChatSettingsService, validateSettings } from './support-chat-settings.service';
|
||||
import { SupportChatService } from './support-chat.service';
|
||||
import { SupportChatSettingsController } from './support-chat-settings.controller';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { PassportModule, PassportStrategy } from '@nestjs/passport';
|
||||
import { ExtractJwt, Strategy } from 'passport-jwt';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import request from 'supertest';
|
||||
class TestJwt extends PassportStrategy(Strategy) {
|
||||
constructor() { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), secretOrKey:'test' }); }
|
||||
validate(p: any) { return { id:p.sub, role:p.role }; }
|
||||
}
|
||||
const selected = { enabled:true, provider:'configured-1234567890abcdef', model:'real-model', label:'پشتیبان تست', icon:'paw' };
|
||||
describe('smart chat settings', () => {
|
||||
let stored:any = null;
|
||||
const prisma:any = { setting:{ findUnique:jest.fn(async()=>stored), upsert:jest.fn(async(q:any)=>{stored={value:q.create.value};return stored;}) }, product:{findMany:jest.fn(async()=>[])}, user:{findUnique:jest.fn()}, order:{findMany:jest.fn()}, supportConversation:{create:jest.fn(async(q:any)=>({id:q.data.id,messages:[]})),findUnique:jest.fn(async()=>null),update:jest.fn(async()=>({}))}, supportConversationMessage:{createMany:jest.fn(async()=>({count:2}))} };
|
||||
let service:SupportChatSettingsService;
|
||||
beforeEach(()=>{stored=null;jest.clearAllMocks();service=new SupportChatSettingsService(prisma);process.env.SUPPORT_CHAT_URL='http://internal/ask';process.env.SUPPORT_CHAT_KEY='key';});
|
||||
afterEach(()=>jest.restoreAllMocks());
|
||||
const catalog=()=>jest.spyOn(global,'fetch').mockResolvedValue({ok:true,json:async()=>({providers:[{id:selected.provider,label:'Configured',models:[selected.model]}]})} as any);
|
||||
it('persists and reads exact fields and projects safe public config',async()=>{catalog();expect(await service.save(selected)).toEqual(selected);expect(await service.read()).toEqual(selected);expect(await service.publicConfig()).toEqual({enabled:true,label:selected.label,icon:'paw'});});
|
||||
it.each([{...selected,model:'unknown'},{...selected,provider:'http://127.0.0.1'},{...selected,provider:'configured-ffffffffffffffff'}])('rejects invalid combination %j',async s=>{catalog();await expect(service.save(s)).rejects.toThrow();expect(prisma.setting.upsert).not.toHaveBeenCalled();});
|
||||
it.each(['https://evil/a.svg','<svg onload=alert(1)>','data:image/svg+xml,abc','/uploads/x.svg'])('rejects unsafe icon %s',icon=>{expect(()=>validateSettings({...selected,icon})).toThrow();});
|
||||
it('rejects unknown fields and invalid label',()=>{expect(()=>validateSettings({...selected,baseUrl:'https://evil'})).toThrow();expect(()=>validateSettings({...selected,label:'<script>'})).toThrow();});
|
||||
it('fails closed without configuration',async()=>{await expect(service.read()).rejects.toThrow();});
|
||||
it('fails closed on catalog outage',async()=>{jest.spyOn(global,'fetch').mockRejectedValue(new Error('secret'));await expect(service.save(selected)).rejects.toThrow();expect(prisma.setting.upsert).not.toHaveBeenCalled();});
|
||||
it('rejects sanitized catalog violations',async()=>{jest.spyOn(global,'fetch').mockResolvedValue({ok:true,json:async()=>({providers:[{id:selected.provider,label:'https://internal',models:['m'],api_key:'secret'}]})} as any);await expect(service.catalog()).rejects.toThrow();});
|
||||
it('disabling rejects ask before model and private DB calls',async()=>{stored={value:{...selected,enabled:false}};const f=jest.spyOn(global,'fetch');await expect(new SupportChatService(prisma,service).ask({message:'کیف پول'},{id:'alice'})).rejects.toThrow();expect(f).not.toHaveBeenCalled();expect(prisma.user.findUnique).not.toHaveBeenCalled();expect(prisma.product.findMany).not.toHaveBeenCalled();});
|
||||
it('uses identical stored selection for classify and answer with no identity leakage',async()=>{stored={value:selected};const f=jest.spyOn(global,'fetch').mockImplementation(async(url)=>({ok:true,json:async()=>String(url).endsWith('/classify')?{intent:'public'}:{answer:'سلام'}} as any));await new SupportChatService(prisma,service).ask({message:'سلام'},{id:'alice'});const bodies=f.mock.calls.map(c=>JSON.parse(c[1]!.body as string));expect(bodies.map(b=>b.selection)).toEqual([{provider:selected.provider,model:selected.model},{provider:selected.provider,model:selected.model}]);expect(JSON.stringify(bodies)).not.toContain('alice');});
|
||||
});
|
||||
describe('settings HTTP admin boundary',()=>{
|
||||
let app:any;
|
||||
const jwt=new JwtService({secret:'test'});
|
||||
const service={read:jest.fn(async()=>selected),publicConfig:jest.fn(async()=>({enabled:true,label:'test',icon:'bot'})),save:jest.fn(async()=>selected),catalog:jest.fn(async()=>({providers:[]}))};
|
||||
beforeAll(async()=>{const mod=await Test.createTestingModule({imports:[PassportModule],controllers:[SupportChatSettingsController],providers:[TestJwt,{provide:SupportChatSettingsService,useValue:service}]}).compile();app=mod.createNestApplication();await app.init();});
|
||||
afterAll(()=>app.close());
|
||||
it.each(['settings','catalog'])('rejects anonymous %s',async path=>{await request(app.getHttpServer()).get('/support-chat/'+path).expect(401);});
|
||||
it.each(['settings','catalog'])('rejects customer %s',async path=>{await request(app.getHttpServer()).get('/support-chat/'+path).set('Authorization','Bearer '+jwt.sign({sub:'customer',role:'Customer'})).expect(403);});
|
||||
it('rejects anonymous and customer writes',async()=>{await request(app.getHttpServer()).put('/support-chat/settings').send(selected).expect(401);await request(app.getHttpServer()).put('/support-chat/settings').set('Authorization','Bearer '+jwt.sign({sub:'customer',role:'Customer'})).send(selected).expect(403);});
|
||||
it('allows Admin reads and writes',async()=>{const auth='Bearer '+jwt.sign({sub:'admin',role:'Admin'});await request(app.getHttpServer()).get('/support-chat/settings').set('Authorization',auth).expect(200);await request(app.getHttpServer()).get('/support-chat/catalog').set('Authorization',auth).expect(200);await request(app.getHttpServer()).put('/support-chat/settings').set('Authorization',auth).send(selected).expect(200);});
|
||||
it('public configuration only returns safe fields',async()=>{const r=await request(app.getHttpServer()).get('/support-chat/config').expect(200);expect(Object.keys(r.body).sort()).toEqual(['enabled','icon','label']);});
|
||||
});
|
||||
@@ -1,13 +1,13 @@
|
||||
import { Body, Controller, Post, Req, UseGuards, Header } from '@nestjs/common';
|
||||
import { Body, Controller, Get, Header, Param, ParseUUIDPipe, Post, Req, UseGuards } from '@nestjs/common';
|
||||
import { Throttle } from '@nestjs/throttler';
|
||||
import { SupportChatService } from './support-chat.service';
|
||||
import { SupportChatDto } from './support-chat.dto';
|
||||
import { OptionalCustomerJwtGuard } from './support-chat.guard';
|
||||
@Controller('support-chat')
|
||||
export class SupportChatController {
|
||||
constructor(private readonly service: SupportChatService) {}
|
||||
@Post('ask') @UseGuards(OptionalCustomerJwtGuard)
|
||||
@Throttle({ default: { limit: 10, ttl: 60000 } })
|
||||
@Header('Cache-Control', 'no-store')
|
||||
ask(@Body() dto: SupportChatDto, @Req() req: { user?: { id: string } }) { return this.service.ask(dto, req.user); }
|
||||
constructor(private readonly service: SupportChatService) {}
|
||||
@Get(':id') @UseGuards(OptionalCustomerJwtGuard) @Header('Cache-Control', 'no-store')
|
||||
history(@Param('id', ParseUUIDPipe) id: string, @Req() req: { user?: { id: string } }) { return this.service.history(id, req.user); }
|
||||
@Post('ask') @UseGuards(OptionalCustomerJwtGuard) @Throttle({ default: { limit: 10, ttl: 60000 } }) @Header('Cache-Control', 'no-store')
|
||||
ask(@Body() dto: SupportChatDto, @Req() req: { user?: { id: string } }) { return this.service.ask(dto, req.user); }
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
import { IsIn, IsString, Length } from 'class-validator';
|
||||
import { IsOptional, IsString, Length, Matches } from 'class-validator';
|
||||
export class SupportChatDto {
|
||||
@IsString() @Length(1, 1500) message!: string;
|
||||
@IsIn(['public', 'orders', 'wallet']) scope: 'public' | 'orders' | 'wallet' = 'public';
|
||||
@IsOptional() @IsString() @Length(36, 36) @Matches(/^[0-9a-f-]{36}$/i) conversationId?: string;
|
||||
@IsOptional() @IsString() @Length(1, 512) entryPath?: string;
|
||||
@IsOptional() @IsString() @Length(1, 64) @Matches(/^[A-Za-z0-9_-]+$/) anonymousBrowserId?: string;
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { SupportChatSettingsService } from './support-chat-settings.service';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { INestApplication, ValidationPipe } from '@nestjs/common';
|
||||
import { PassportModule, PassportStrategy } from '@nestjs/passport';
|
||||
@@ -14,28 +15,51 @@ class TestJwt extends PassportStrategy(Strategy) {
|
||||
}
|
||||
describe('support HTTP boundary', () => {
|
||||
let app: INestApplication;
|
||||
const prisma: any = { product: { findMany: jest.fn().mockResolvedValue([]) }, order: { findMany: jest.fn().mockImplementation(({where}) => [{ id: where.userId + '-order', status: 'processing', totalAmount: '19' }]) }, user: { findUnique: jest.fn().mockImplementation(({where}) => ({ walletBalance: where.id === 'alice' ? '11' : '22' })) } };
|
||||
const prisma: any = { supportConversation: { create: jest.fn().mockResolvedValue({ id: '11111111-1111-4111-8111-111111111111', userId: null, messages: [] }), findUnique: jest.fn().mockResolvedValue(null), update: jest.fn().mockResolvedValue({}) }, supportConversationMessage: { createMany: jest.fn().mockResolvedValue({}) }, product: { findMany: jest.fn().mockResolvedValue([]) }, order: { findMany: jest.fn().mockImplementation(({where}) => [{ id: where.userId + '-order', status: 'processing', totalAmount: '19' }]) }, user: { findUnique: jest.fn().mockImplementation(({where}) => ({ walletBalance: where.id === 'alice' ? '11' : '22', mobile: where.id+'-mobile', email: where.id+'@example.test', firstName: 'Test', lastName: 'User' })) } };
|
||||
const jwt = new JwtService({ secret: 'test-secret' });
|
||||
beforeAll(async () => {
|
||||
process.env.JWT_ACCESS_SECRET = 'test-secret-with-at-least-32-characters';
|
||||
const mod = await Test.createTestingModule({ imports: [PassportModule], controllers: [SupportChatController], providers: [SupportChatService, OptionalCustomerJwtGuard, TestJwt, { provide: PrismaService, useValue: prisma }] }).compile();
|
||||
app = mod.createNestApplication(); app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true })); await app.init();
|
||||
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 }));
|
||||
// Own the listener for the entire suite. Otherwise Supertest lets the first
|
||||
// request start the server and close it while its concurrent peer is using it.
|
||||
await app.listen(0, '127.0.0.1');
|
||||
});
|
||||
afterAll(() => app.close());
|
||||
beforeEach(() => { jest.clearAllMocks(); });
|
||||
it.each(['userId','history','context','sessionId','conversationId'])('rejects untrusted %s', async field => { await request(app.getHttpServer()).post('/support-chat/ask').send({message:'سلام', [field]:'alice'}).expect(400); });
|
||||
beforeEach(() => {
|
||||
jest.restoreAllMocks(); jest.clearAllMocks();
|
||||
process.env.SUPPORT_CHAT_URL='http://internal/ask'; process.env.SUPPORT_CHAT_KEY='test';
|
||||
jest.spyOn(global,'fetch').mockImplementation(async (url, opts) => {
|
||||
const message=JSON.parse(opts!.body as string).message;
|
||||
const intent=message==='کیف پول'?'wallet':message==='سفارش من'||message==='سفارش'?'orders':message.includes('شماره تماس')?'profile':'public';
|
||||
return {ok:true,status:200,json:async()=>String(url).endsWith('/classify')?{intent}:{answer:'راهنمای محصولات کنینا'}} as any;
|
||||
});
|
||||
});
|
||||
it.each(['scope','userId','history','context','sessionId','conversationId'])('rejects untrusted %s', async field => { await request(app.getHttpServer()).post('/support-chat/ask').send({message:'سلام', [field]:'alice'}).expect(400); });
|
||||
it.each(['Bearer broken','Basic abc','', 'Bearer '])('rejects supplied invalid auth %j', async auth => { await request(app.getHttpServer()).post('/support-chat/ask').set('Authorization',auth).send({message:'سلام'}).expect(401); });
|
||||
it('fails closed when configured JWT secret is missing', async () => { const saved=process.env.JWT_ACCESS_SECRET; delete process.env.JWT_ACCESS_SECRET; await request(app.getHttpServer()).post('/support-chat/ask').set('Authorization','Bearer '+jwt.sign({sub:'alice'})).send({message:'کیف پول',scope:'wallet'}).expect(401); process.env.JWT_ACCESS_SECRET=saved; });
|
||||
it('fails closed when configured JWT secret is missing', async () => { const saved=process.env.JWT_ACCESS_SECRET; delete process.env.JWT_ACCESS_SECRET; await request(app.getHttpServer()).post('/support-chat/ask').set('Authorization','Bearer '+jwt.sign({sub:'alice'})).send({message:'کیف پول'}).expect(401); process.env.JWT_ACCESS_SECRET=saved; });
|
||||
it('rejects expired JWT', async () => { await request(app.getHttpServer()).post('/support-chat/ask').set('Authorization','Bearer '+jwt.sign({sub:'alice'}, {expiresIn:-1})).send({message:'سلام'}).expect(401); });
|
||||
it('rejects cookie JWT rather than downgrading to guest', async () => { await request(app.getHttpServer()).post('/support-chat/ask').set('Cookie','accessToken=broken').send({message:'سلام'}).expect(401); });
|
||||
it('guest orders do not touch any private rows', async () => { const r=await request(app.getHttpServer()).post('/support-chat/ask').send({message:'سفارش من',scope:'orders'}).expect(201); expect(r.body.answer).toContain('وارد'); expect(prisma.order.findMany).not.toHaveBeenCalled(); });
|
||||
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:'کیف پول',scope:'wallet'}).expect(201)));
|
||||
expect(replies[0].body.answer).toContain('11'); expect(replies[0].body.answer).not.toContain('22'); expect(replies[1].body.answer).toContain('22'); expect(prisma.product.findMany).not.toHaveBeenCalled();
|
||||
it('guest orders do not touch any private rows', async () => { const r=await request(app.getHttpServer()).post('/support-chat/ask').send({message:'سفارش من'}).expect(201); expect(r.body.answer).toContain('وارد'); expect(prisma.order.findMany).not.toHaveBeenCalled(); });
|
||||
it('returns only the authenticated user profile contact data', async () => {
|
||||
const r=await request(app.getHttpServer()).post('/support-chat/ask').set('Authorization','Bearer '+jwt.sign({sub:'alice'})).send({message:'شماره تماس و ایمیل ثبتشده من چیست؟'}).expect(201);
|
||||
expect(r.body.answer).toContain('alice-mobile'); expect(r.body.answer).toContain('alice@example.test');
|
||||
expect(prisma.user.findUnique).toHaveBeenCalledWith(expect.objectContaining({where:{id:'alice'}}));
|
||||
});
|
||||
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:'سفارش',scope:'orders'}).expect(201); expect(r.body.answer).toContain('bob-order'); expect(prisma.order.findMany).toHaveBeenCalledWith(expect.objectContaining({ where:{userId:'bob'}, take:5 })); });
|
||||
it('scopes wallet to validated identity across concurrent callers', async () => {
|
||||
const replies=await Promise.all(['alice','bob'].map(sub => request(app.getHttpServer()).post('/support-chat/ask').set('Authorization','Bearer '+jwt.sign({sub})).send({message:'کیف پول'}).expect(201)));
|
||||
expect(replies[0].body.answer).toBe('موجودی کیف پول شما: 11 تومان.');
|
||||
expect(replies[1].body.answer).toBe('موجودی کیف پول شما: 22 تومان.');
|
||||
expect(prisma.user.findUnique).toHaveBeenCalledTimes(2);
|
||||
for (const id of ['alice', 'bob']) {
|
||||
expect(prisma.user.findUnique).toHaveBeenCalledWith({ where: { id }, select: { walletBalance: true } });
|
||||
}
|
||||
expect(prisma.product.findMany).not.toHaveBeenCalled();
|
||||
expect(prisma.order.findMany).not.toHaveBeenCalled();
|
||||
});
|
||||
it('scopes bounded orders to identity', async () => { const r=await request(app.getHttpServer()).post('/support-chat/ask').set('Authorization','Bearer '+jwt.sign({sub:'bob'})).send({message:'سفارش'}).expect(201); expect(r.body.answer).toContain('bob-order'); expect(prisma.order.findMany).toHaveBeenCalledWith(expect.objectContaining({ where:{userId:'bob'}, take:5 })); });
|
||||
it.each(['', 'x'.repeat(1501)])('bounds message length', async message => { await request(app.getHttpServer()).post('/support-chat/ask').send({message}).expect(400); });
|
||||
it('does not query private data in public scope even with valid JWT', async () => { await request(app.getHttpServer()).post('/support-chat/ask').set('Authorization','Bearer '+jwt.sign({sub:'alice'})).send({message:'سلام',scope:'public'}); expect(prisma.user.findUnique).not.toHaveBeenCalled(); expect(prisma.order.findMany).not.toHaveBeenCalled(); });
|
||||
it('does not query private data in public scope even with valid JWT', async () => { await request(app.getHttpServer()).post('/support-chat/ask').set('Authorization','Bearer '+jwt.sign({sub:'alice'})).send({message:'سلام'}); expect(prisma.user.findUnique).not.toHaveBeenCalled(); expect(prisma.order.findMany).not.toHaveBeenCalled(); });
|
||||
it.each([{error:'upstream-secret'}, {answer:'Provider authentication failed Hermes'}, {answer:''}])('filters malformed and default upstream failures', async body => { process.env.SUPPORT_CHAT_URL='http://internal/ask'; process.env.SUPPORT_CHAT_KEY='test'; const f=jest.spyOn(global,'fetch').mockResolvedValue({ok:true,json:async()=>body} as any); const r=await request(app.getHttpServer()).post('/support-chat/ask').send({message:'مکمل سگ'}).expect(503); expect(r.body.message).toBe(UNAVAILABLE); expect(JSON.stringify(r.body)).not.toContain('upstream-secret'); f.mockRestore(); });
|
||||
it('returns safe unavailable on network errors', async () => { const f=jest.spyOn(global,'fetch').mockRejectedValue(new Error('private-secret')); const r=await request(app.getHttpServer()).post('/support-chat/ask').send({message:'مکمل سگ'}).expect(503); expect(r.body.message).toBe(UNAVAILABLE); f.mockRestore(); });
|
||||
});
|
||||
@@ -1,8 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { SupportChatSettingsService } from './support-chat-settings.service';
|
||||
import { SupportChatSettingsController } from './support-chat-settings.controller';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { PrismaModule } from '../prisma/prisma.module';
|
||||
import { SupportChatController } from './support-chat.controller';
|
||||
import { SupportChatService } from './support-chat.service';
|
||||
import { OptionalCustomerJwtGuard } from './support-chat.guard';
|
||||
@Module({ imports: [AuthModule, PrismaModule], controllers: [SupportChatController], providers: [SupportChatService, OptionalCustomerJwtGuard] })
|
||||
@Module({ imports: [AuthModule, PrismaModule], controllers: [SupportChatSettingsController, SupportChatController], providers: [SupportChatService, SupportChatSettingsService, OptionalCustomerJwtGuard] })
|
||||
export class SupportChatModule {}
|
||||
@@ -1,13 +1,36 @@
|
||||
import { SupportChatService, UNAVAILABLE } from './support-chat.service';
|
||||
|
||||
describe('SupportChatService', () => {
|
||||
const prisma: any = { product: { findMany: jest.fn().mockResolvedValue([]) }, order: { findMany: jest.fn().mockResolvedValue([]) }, user: { findUnique: jest.fn().mockResolvedValue({ walletBalance: '17' }) } };
|
||||
let service: SupportChatService;
|
||||
beforeEach(() => { jest.clearAllMocks(); service = new SupportChatService(prisma); });
|
||||
it('does not load private rows for a guest asking about wallet', async () => {
|
||||
const result = await service.ask({ message: 'موجودی کیف پول من', scope: 'wallet' });
|
||||
expect(result.answer).toContain('وارد');
|
||||
expect(prisma.user.findUnique).not.toHaveBeenCalled();
|
||||
expect(prisma.order.findMany).not.toHaveBeenCalled();
|
||||
describe('model intent routing', () => {
|
||||
const prisma: any = { supportConversation: { create: jest.fn().mockResolvedValue({id:'11111111-1111-4111-8111-111111111111',userId:null,messages:[]}), findUnique: jest.fn().mockResolvedValue(null), update: jest.fn().mockResolvedValue({}) }, supportConversationMessage: { createMany: jest.fn().mockResolvedValue({}) }, pet:{findMany:jest.fn().mockResolvedValue([])}, product:{findMany:jest.fn().mockResolvedValue([])}, order:{findMany:jest.fn().mockResolvedValue([])}, user:{findUnique:jest.fn().mockResolvedValue({walletBalance:'17', mobile:'0912', email:'a@example.test', firstName:'A', lastName:'B'})} };
|
||||
let service: SupportChatService;
|
||||
beforeEach(()=>{jest.clearAllMocks();process.env.SUPPORT_CHAT_URL='http://internal/ask';process.env.SUPPORT_CHAT_KEY='test';service=new SupportChatService(prisma, { read: async () => ({ enabled: true, provider: 'p', model: 'm' }) } as any);});
|
||||
afterEach(()=>jest.restoreAllMocks());
|
||||
function model(body:any) { return jest.spyOn(global,'fetch').mockImplementation(async(url)=>({ok:true,json:async()=>String(url).endsWith('/classify')?body:(body.answer?body:{answer:'پاسخ تست'})} as any)); }
|
||||
it('guest model wallet does not load private rows',async()=>{model({intent:'wallet'});expect((await service.ask({message:'cheghadr etebar daram'})).answer).toContain('وارد');expect(prisma.user.findUnique).not.toHaveBeenCalled();expect(prisma.order.findMany).not.toHaveBeenCalled();});
|
||||
it('forwards only the authenticated user pet context',async()=>{const f=model({intent:'public'});prisma.pet={findMany:jest.fn().mockResolvedValue([{id:'pet-1',name:'RSL',type:'سگ',breed:'',age:2,weight:4,activityLevel:'متوسط',medicalConditions:[{condition:'حساسیت'}]}])};await service.ask({message:'جرم دندان RSL چیست؟'},{id:'alice'});const body=JSON.parse(f.mock.calls[0][1]!.body as string);expect(body.pet_context).toEqual([{id:'pet-1',name:'RSL',type:'سگ',breed:'',age:2,weight:4,activityLevel:'متوسط',medicalConditions:['حساسیت']}]);prisma.pet={findMany:jest.fn().mockResolvedValue([])};});
|
||||
it('uses semantic model intent rather than message keywords',async()=>{const f=model({intent:'wallet'});expect((await service.ask({message:'چقدر اعتبار دارم؟'},{id:'alice'})).answer).toContain('17');expect(prisma.user.findUnique).toHaveBeenCalledWith({where:{id:'alice'},select:{walletBalance:true}});expect(JSON.parse(f.mock.calls[0][1]!.body as string)).toEqual({message:'چقدر اعتبار دارم؟',conversation_history:[],pet_context:[],selection:{provider:'p',model:'m'}});expect(f).toHaveBeenCalledTimes(1);});
|
||||
it.each([{intent:'admin'},{intent:'wallet',userId:'bob'},{answer:'orders'},{intent:null},{}])('fails closed on invalid classifier %j',async body=>{model(body);await expect(service.ask({message:'سلام'},{id:'alice'})).rejects.toThrow(UNAVAILABLE);expect(prisma.user.findUnique).not.toHaveBeenCalled();expect(prisma.order.findMany).not.toHaveBeenCalled();expect(prisma.product.findMany).not.toHaveBeenCalled();});
|
||||
it('classifier outage does not fall back to keyword routing',async()=>{jest.spyOn(global,'fetch').mockRejectedValue(new Error('secret'));await expect(service.ask({message:'کیف پول'},{id:'alice'})).rejects.toThrow(UNAVAILABLE);expect(prisma.user.findUnique).not.toHaveBeenCalled();});
|
||||
});
|
||||
|
||||
|
||||
describe('persistent conversations', () => {
|
||||
it('creates a conversation and stores both messages without blocking the answer', async () => {
|
||||
const conversation = { id: '11111111-1111-4111-8111-111111111111', userId: null };
|
||||
const prisma: any = {
|
||||
product: { findMany: jest.fn().mockResolvedValue([]) },
|
||||
supportConversation: { create: jest.fn().mockResolvedValue(conversation), update: jest.fn().mockResolvedValue(conversation), findUnique: jest.fn().mockResolvedValue(conversation) },
|
||||
supportConversationMessage: { createMany: jest.fn().mockResolvedValue({}) },
|
||||
};
|
||||
process.env.SUPPORT_CHAT_URL = 'http://internal/ask';
|
||||
process.env.SUPPORT_CHAT_KEY = 'test';
|
||||
jest.spyOn(global, 'fetch').mockImplementation(async (url, opts: any) => ({
|
||||
ok: true, status: 200, json: async () => String(url).endsWith('/classify') ? { intent: 'public' } : { answer: 'پاسخ' },
|
||||
}) as any);
|
||||
const service = new SupportChatService(prisma, { read: async () => ({ enabled: true, provider: 'p', model: 'm' }) } as any);
|
||||
const result = await service.ask({ message: 'سلام', entryPath: '/products' } as any);
|
||||
expect(result).toMatchObject({ conversationId: conversation.id, answer: 'پاسخ' });
|
||||
expect(prisma.supportConversation.create).toHaveBeenCalled();
|
||||
expect(prisma.supportConversationMessage.createMany).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -1,34 +1,95 @@
|
||||
import { Injectable, ServiceUnavailableException } from '@nestjs/common';
|
||||
import { Injectable, NotFoundException, ServiceUnavailableException } from '@nestjs/common';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { SupportChatDto } from './support-chat.dto';
|
||||
import { SupportChatSettingsService } from './support-chat-settings.service';
|
||||
|
||||
export const UNAVAILABLE = 'پشتیبان هوشمند فعلاً در دسترس نیست. لطفاً کمی بعد دوباره تلاش کنید یا تیکت پشتیبانی ثبت کنید.';
|
||||
const MAX_HISTORY = 20;
|
||||
const safePath = (v?: string) => v?.split('?')[0].slice(0, 512);
|
||||
const safeBrowserId = (v?: string) => v && /^[A-Za-z0-9_-]{1,64}$/.test(v) ? v : undefined;
|
||||
const resolvePageContext = async (db: any, entryPath?: string) => {
|
||||
const path = safePath(entryPath);
|
||||
if (!path || !path.startsWith('/') || path.includes('..') || /[?#]/.test(path)) return { type: 'unknown', path: path || '/' };
|
||||
const match = path.match(/^\/(shop|blog|wiki)\/([A-Za-z0-9_-]+)$/);
|
||||
if (!match) return { type: path === '/contact' ? 'contact' : 'other', path };
|
||||
const [type, slug] = match.slice(1);
|
||||
if (type === 'shop') {
|
||||
const row = await db.product.findFirst({ where: { slug }, select: { slug: true, nameFa: true, shortDescription: true, description: true } });
|
||||
return row ? { type: 'product', slug: row.slug, title: row.nameFa, contentExcerpt: String(row.shortDescription || row.description || '').slice(0, 1200), path } : { type: 'product', slug, path };
|
||||
}
|
||||
if (type === 'blog') {
|
||||
const row = await db.blog.findFirst({ where: { slug, status: 'PUBLISHED' }, select: { slug: true, title: true, excerpt: true, content: true } });
|
||||
return row ? { type: 'blog', slug: row.slug, title: row.title, contentExcerpt: String(row.excerpt || row.content || '').replace(/<[^>]*>/g, '').slice(0, 1200), path } : { type: 'blog', slug, path };
|
||||
}
|
||||
const row = await db.wiki.findFirst({ where: { key: slug }, select: { key: true, term: true, description: true } });
|
||||
return row ? { type: 'wiki', slug: row.key, title: row.term, contentExcerpt: String(row.description || '').slice(0, 1200), path } : { type: 'wiki', slug, path };
|
||||
};
|
||||
|
||||
const extract = (question: string, answer: string, products: any[]) => {
|
||||
const q = question.toLowerCase();
|
||||
const topics = ['nutrition','supplement','health','order','wallet','product','shipping'].filter(x => q.includes(x));
|
||||
if (/تغذ|غذا|مکمل|ویتامین/.test(q)) topics.push('nutrition');
|
||||
if (/سلامت|بیمار|دامپزشک/.test(q)) topics.push('health');
|
||||
if (/سفارش|ارسال/.test(q)) topics.push('order');
|
||||
const productSlugs = (products || []).filter(p => p.slug && (q.includes(String(p.slug).toLowerCase()) || q.includes(String(p.nameFa || '').toLowerCase()))).map(p => p.slug).slice(0, 20);
|
||||
const uniqueTopics = [...new Set(topics)].slice(0, 20);
|
||||
const unanswered = /نمی.?دانم|اطلاعاتی ندارم|پاسخ ندارم|متوجه نشدم/i.test(answer);
|
||||
const needsFollowup = unanswered || /دامپزشک|پشتیبانی|تیکت|پیگیری/i.test(answer);
|
||||
const escalationSignal = /فوری|شکایت|مشکل جدی|خطر|اورژانس/i.test(question + ' ' + answer);
|
||||
const summary = `موضوع: ${uniqueTopics.join(', ') || 'عمومی'}؛ محصولات: ${productSlugs.join(', ') || 'ندارد'}؛ نیاز به پیگیری: ${needsFollowup ? 'بله' : 'خیر'}`;
|
||||
return { productSlugs, topics: uniqueTopics, unanswered, needsFollowup, escalationSignal, summary };
|
||||
};
|
||||
@Injectable()
|
||||
export class SupportChatService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
constructor(private readonly prisma: PrismaService, private readonly settings: SupportChatSettingsService) {}
|
||||
private db() { return this.prisma as any; }
|
||||
async history(id: string, user?: { id: string }) {
|
||||
const row = await this.db().supportConversation.findUnique({ where: { id }, include: { messages: { orderBy: { sequence: 'asc' }, take: MAX_HISTORY } } });
|
||||
if (!row || (user?.id ? row.userId !== user.id : row.userId !== null)) throw new NotFoundException('گفتگو یافت نشد.');
|
||||
return { conversationId: id, messages: row.messages.map((m: any) => ({ role: m.role, content: m.content, createdAt: m.createdAt })) };
|
||||
}
|
||||
async ask(input: SupportChatDto, user?: { id: string }) {
|
||||
if (input.scope !== 'public' && !user) return { answer: 'برای مشاهده سفارشها یا کیف پول خود ابتدا وارد حساب کاربری شوید.' };
|
||||
if (input.scope === 'wallet') {
|
||||
const row = await this.prisma.user.findUnique({ where: { id: user!.id }, select: { walletBalance: true } });
|
||||
if (!row) throw new ServiceUnavailableException(UNAVAILABLE);
|
||||
return { answer: `موجودی کیف پول شما: ${row.walletBalance.toString()} تومان.` };
|
||||
const config = await this.settings.read(); if (!config.enabled) throw new ServiceUnavailableException(UNAVAILABLE);
|
||||
const db = this.db(); let conversation: any;
|
||||
if (input.conversationId) {
|
||||
conversation = await db.supportConversation.findUnique({ where: { id: input.conversationId }, include: { messages: { orderBy: { sequence: 'asc' }, take: MAX_HISTORY } } });
|
||||
if (!conversation || (user?.id ? conversation.userId !== user.id : conversation.userId !== null)) throw new NotFoundException('گفتگو یافت نشد.');
|
||||
} else {
|
||||
conversation = await db.supportConversation.create({ data: { id: randomUUID(), userId: user?.id ?? null, anonymousBrowserId: safeBrowserId(input.anonymousBrowserId), entryPath: safePath(input.entryPath), expiresAt: new Date(Date.now() + 90 * 86400000) }, include: { messages: true } });
|
||||
}
|
||||
if (input.scope === 'orders') {
|
||||
const rows = await this.prisma.order.findMany({ where: { userId: user!.id }, select: { id: true, status: true, totalAmount: true, createdAt: true }, take: 5, orderBy: { createdAt: 'desc' } });
|
||||
return { answer: rows.length ? rows.map(r => `سفارش ${r.id}: ${r.status} — ${r.totalAmount.toString()} تومان`).join('\n') : 'سفارشی برای حساب شما ثبت نشده است.' };
|
||||
}
|
||||
// Private account rows never leave the backend, even when the model is compromised.
|
||||
const conversationHistory = (conversation.messages || []).slice(-MAX_HISTORY).map((m: any) => ({ role: m.role, content: m.content }));
|
||||
const selection = { provider: config.provider, model: config.model };
|
||||
const pageContext = await resolvePageContext(db, input.entryPath); const url = process.env.SUPPORT_CHAT_URL; const key = process.env.SUPPORT_CHAT_KEY;
|
||||
const pets = user && db.pet?.findMany ? await db.pet.findMany({ where: { userId: user.id }, select: { id: true, name: true, type: true, breed: true, age: true, weight: true, activityLevel: true, medicalConditions: { select: { condition: true } } }, take: 20, orderBy: { createdAt: 'asc' } }) : [];
|
||||
const petContext = pets.map((pet: any) => ({ ...pet, medicalConditions: pet.medicalConditions.map((item: any) => item.condition) }));
|
||||
let intent: 'public' | 'orders' | 'wallet' | 'profile';
|
||||
try {
|
||||
const products = await this.prisma.product.findMany({ take: 80, orderBy: { nameFa: 'asc' }, select: { nameFa: true, nameEn: true, slug: true, priceValue: true, stock: true, stockStatus: true, suitableFor: true, shortDescription: true } });
|
||||
const url = process.env.SUPPORT_CHAT_URL;
|
||||
const key = process.env.SUPPORT_CHAT_KEY;
|
||||
if (!url || !key) throw new Error('disabled');
|
||||
const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(45000), body: JSON.stringify({ message: input.message, catalog: products }) });
|
||||
if (response.status === 400) return { answer: 'فقط درباره محصولات و سلامت حیوانات خانگی و خدمات کنینا پاسخ میدهم. پیوند دلخواه یا موضوع خارج از این حوزه پذیرفته نمیشود.' };
|
||||
if (!response.ok) throw new Error('upstream');
|
||||
const data = await response.json();
|
||||
if (typeof data.answer !== 'string' || !data.answer.trim() || data.answer.length > 6000 || /traceback|api.?key|provider|rate.?limit|hermes|authentication|exception|https?:\/\/(?:localhost|127\.)/i.test(data.answer)) throw new Error('unsafe');
|
||||
return { answer: data.answer };
|
||||
if (!url || !key || !url.endsWith('/ask')) throw new Error('disabled');
|
||||
const response = await fetch(url.replace(/\/ask$/, '/classify'), { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(45000), body: JSON.stringify({ message: input.message, conversation_history: conversationHistory, pet_context: petContext, selection }) });
|
||||
if (response.status === 400) return { answer: 'فقط درباره محصولات و سلامت حیوانات خانگی و خدمات کنینا پاسخ میدهم.' };
|
||||
if (!response.ok) throw new Error('upstream'); const data = await response.json();
|
||||
if (!data || Object.keys(data).length !== 1 || !['public','orders','wallet','profile'].includes(data.intent)) throw new Error('intent'); intent = data.intent;
|
||||
} catch { throw new ServiceUnavailableException(UNAVAILABLE); }
|
||||
if (intent !== 'public' && !user) return { answer: 'برای مشاهده اطلاعات حساب، سفارشها یا کیف پول خود ابتدا وارد حساب کاربری شوید.', conversationId: conversation.id, contextLimited: conversationHistory.length >= MAX_HISTORY };
|
||||
let answer: string; let products: any[] = [];
|
||||
try {
|
||||
if (intent === 'wallet') { const row = await this.prisma.user.findUnique({ where: { id: user!.id }, select: { walletBalance: true } }); if (!row) throw new Error('missing'); answer = `موجودی کیف پول شما: ${row.walletBalance.toString()} تومان.`; } else if (intent === 'profile') { const row = await this.prisma.user.findUnique({ where: { id: user!.id }, select: { firstName: true, lastName: true, mobile: true, email: true } }); if (!row) throw new Error('missing'); answer = `اطلاعات تماس ثبتشده برای حساب شما:
|
||||
شماره موبایل: ${row.mobile || 'ثبت نشده'}
|
||||
ایمیل: ${row.email || 'ثبت نشده'}.`; }
|
||||
else if (intent === 'orders') { const rows = await this.prisma.order.findMany({ where: { userId: user!.id }, select: { id: true, status: true, totalAmount: true }, take: 5, orderBy: { createdAt: 'desc' } }); answer = rows.length ? rows.map(r => `سفارش ${r.id}: ${r.status} — ${r.totalAmount.toString()} تومان`).join('\n') : 'سفارشی برای حساب شما ثبت نشده است.'; }
|
||||
else {
|
||||
products = await this.prisma.product.findMany({ take: 80, orderBy: { nameFa: 'asc' }, select: { nameFa: true, nameEn: true, slug: true, priceValue: true, stock: true, stockStatus: true, suitableFor: true, shortDescription: true } });
|
||||
const response = await fetch(url!, { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(45000), body: JSON.stringify({ message: input.message, catalog: products, conversation_history: conversationHistory, page_context: pageContext, pet_context: petContext, selection }) });
|
||||
if (response.status === 400) return { answer: 'فقط درباره محصولات و سلامت حیوانات خانگی و خدمات کنینا پاسخ میدهم.', conversationId: conversation.id };
|
||||
if (!response.ok) throw new Error('upstream'); const data = await response.json(); answer = data.answer;
|
||||
if (typeof answer !== 'string' || !answer.trim() || answer.length > 6000 || /traceback|api.?key|provider|rate.?limit|hermes|authentication|exception|https?:\/\/(?:localhost|127\.)/i.test(answer)) throw new Error('unsafe');
|
||||
}
|
||||
} catch { throw new ServiceUnavailableException(UNAVAILABLE); }
|
||||
const analytics = extract(input.message + ' ' + JSON.stringify(pageContext), answer!, products);
|
||||
analytics.summary = `${analytics.summary}; صفحه: ${pageContext.type} ${pageContext.slug || pageContext.path || ''}`.slice(0, 1000);
|
||||
await db.supportConversationMessage.createMany({ data: [{ conversationId: conversation.id, role: 'user', content: input.message, sequence: conversationHistory.length }, { conversationId: conversation.id, role: 'assistant', content: answer!, sequence: conversationHistory.length + 1 }] });
|
||||
await db.supportConversation.update({ where: { id: conversation.id }, data: { productSlugs: analytics.productSlugs, topics: analytics.topics, unanswered: analytics.unanswered, needsFollowup: analytics.needsFollowup, escalationSignal: analytics.escalationSignal, summary: analytics.summary, summaryStatus: 'completed' } });
|
||||
return { answer: answer!, conversationId: conversation.id, contextLimited: conversationHistory.length + 2 >= MAX_HISTORY };
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,11 @@ import { Injectable, NotFoundException } from "@nestjs/common";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
import { PaginationDto } from "../common/dto/pagination.dto";
|
||||
import {
|
||||
createPaginationMeta,
|
||||
extractSearchTokens,
|
||||
calculateRelevanceScore,
|
||||
} from "../common/utils/search.utils";
|
||||
|
||||
@Injectable()
|
||||
export class WikiService {
|
||||
@@ -19,33 +24,57 @@ export class WikiService {
|
||||
const sortBy = allowedSortFields.includes(rawSortBy) ? rawSortBy : "term";
|
||||
|
||||
const whereClause: Prisma.ScientificTermWhereInput = {};
|
||||
if (search) {
|
||||
const tokens = extractSearchTokens(search);
|
||||
if (tokens.length > 0) {
|
||||
const mode = "insensitive" as const;
|
||||
whereClause.OR = [
|
||||
{ term: { contains: search, mode: "insensitive" } },
|
||||
{ definition: { contains: search, mode: "insensitive" } },
|
||||
{ term: { contains: search, mode } },
|
||||
{ key: { contains: search, mode } },
|
||||
{ definition: { contains: search, mode } },
|
||||
...tokens.flatMap((token) => [
|
||||
{ term: { contains: token, mode } },
|
||||
{ key: { contains: token, mode } },
|
||||
]),
|
||||
];
|
||||
}
|
||||
|
||||
const skip = (page - 1) * limit;
|
||||
const safePage = Math.max(1, Number(page) || 1);
|
||||
const safeLimit = Math.max(1, Number(limit) || 10);
|
||||
const skip = (safePage - 1) * safeLimit;
|
||||
|
||||
const [data, total] = await Promise.all([
|
||||
const [rawTerms, total] = await Promise.all([
|
||||
this.prisma.scientificTerm.findMany({
|
||||
where: whereClause,
|
||||
skip,
|
||||
take: limit,
|
||||
skip: tokens.length > 0 ? undefined : skip,
|
||||
take: tokens.length > 0 ? 100 : safeLimit,
|
||||
orderBy: { [sortBy]: sortOrder },
|
||||
}),
|
||||
this.prisma.scientificTerm.count({ where: whereClause }),
|
||||
]);
|
||||
|
||||
let data = rawTerms;
|
||||
if (tokens.length > 0 && search) {
|
||||
data = [...rawTerms]
|
||||
.map((t) => ({
|
||||
term: t,
|
||||
score: calculateRelevanceScore(
|
||||
{
|
||||
slug: t.key,
|
||||
title: t.term,
|
||||
description: t.definition,
|
||||
},
|
||||
search,
|
||||
tokens,
|
||||
),
|
||||
}))
|
||||
.sort((a, b) => b.score - a.score)
|
||||
.map((item) => item.term)
|
||||
.slice(skip, skip + safeLimit);
|
||||
}
|
||||
|
||||
return {
|
||||
data,
|
||||
meta: {
|
||||
total,
|
||||
page,
|
||||
lastPage: Math.ceil(total / limit),
|
||||
limit,
|
||||
},
|
||||
meta: createPaginationMeta(total, safePage, safeLimit),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"moduleFileExtensions": [
|
||||
"js",
|
||||
"json",
|
||||
"ts"
|
||||
],
|
||||
"rootDir": "..",
|
||||
"testRegex": "test/torob.integration.ts$",
|
||||
"transform": {
|
||||
"^.+\\.(t|j)s$": "ts-jest"
|
||||
},
|
||||
"testEnvironment": "node"
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { TorobController } from '../src/products/torob.controller';
|
||||
import { PrismaService } from '../src/prisma/prisma.service';
|
||||
|
||||
// Dedicated disposable DB only. Never initializes PrismaService's DDL hooks.
|
||||
describe('Torob real PostgreSQL regression', () => {
|
||||
let db: PrismaClient;
|
||||
let controller: TorobController;
|
||||
const originalUrl = process.env.FRONTEND_URL;
|
||||
beforeAll(async () => {
|
||||
const url = new URL(process.env.DATABASE_URL || '');
|
||||
if (url.hostname !== 'torob-test-db' || url.pathname !== '/torob_test') {
|
||||
throw new Error('Refusing any DB other than disposable torob-test-db/torob_test');
|
||||
}
|
||||
process.env.FRONTEND_URL = 'https://stage.canina.ir';
|
||||
db = new PrismaClient();
|
||||
await db.$connect();
|
||||
const category = await db.category.create({data: {name: 'Fixture', slug: 'fixture'}});
|
||||
const common = {categoryId: category.id, categorySlug: category.slug, nameFa: 'آزمون', nameEn: 'Fixture', description: 'test fixture', priceValue: '123456.78', priceDisplay: 'fixture', unit: 'g', packageSize: 10, suitableFor: 'DOG', imageUrl: '/uploads/fixture.png'};
|
||||
await db.product.createMany({data: [
|
||||
{...common, artNo: 'T1', slug: 'fixture-in', stock: 3, stockStatus: 'IN_STOCK'},
|
||||
{...common, artNo: 'T2', slug: 'fixture-zero', stock: 0, stockStatus: 'IN_STOCK'},
|
||||
{...common, artNo: 'T3', slug: 'fixture-out', stock: 3, stockStatus: 'OUT_OF_STOCK'},
|
||||
{...common, artNo: 'T4', slug: 'fixture-hidden', noIndex: true},
|
||||
{...common, artNo: 'T5', slug: 'fixture-discontinued', stockStatus: 'DISCONTINUED'},
|
||||
]});
|
||||
controller = new TorobController(db as PrismaService);
|
||||
});
|
||||
afterAll(async () => {
|
||||
if (db) await db.$disconnect();
|
||||
if (originalUrl === undefined) delete process.env.FRONTEND_URL;
|
||||
else process.env.FRONTEND_URL = originalUrl;
|
||||
});
|
||||
it('filters hidden/discontinued rows and preserves DB decimal price, stock and URLs', async () => {
|
||||
const result = await controller.getTorobProducts();
|
||||
expect(result.count).toBe(3);
|
||||
expect(result.results.map(p => p.product_id).sort()).toEqual(['T1', 'T2', 'T3']);
|
||||
for (const item of result.results) {
|
||||
const row = await db.product.findUniqueOrThrow({where: {artNo: item.product_id}});
|
||||
expect(item.price).toBe(Number(row.priceValue));
|
||||
expect(item.old_price).toBe(Number(row.priceValue));
|
||||
expect(item.availability).toBe(row.artNo === 'T1' ? 'instock' : 'outofstock');
|
||||
expect(item.page_url).toBe(`https://stage.canina.ir/shop/${row.slug}`);
|
||||
expect(item.image_link).toBe('https://stage.canina.ir/api/uploads/fixture.png');
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
# Canina UX Modernization — Task Register
|
||||
|
||||
Source: live Chromium audits, source audit at `bec76393b`, and QA/SEO/content reviews.
|
||||
Status model: TODO -> IN_PROGRESS -> TEST -> DONE. Estimates are engineering hours, not elapsed calendar time.
|
||||
|
||||
| ID | Owner departments | Pri | Estimate | Dependencies | Acceptance summary | Status |
|
||||
|---|---|---:|---:|---|---|---|
|
||||
| UX-PMO-001 | PMO | P0 | 4h | audits | Register, owners, dependencies, release gates and evidence contract are versioned | DONE |
|
||||
| UX-DEV-001 | Dev + QA | P0 | 12h | none | `/login` and `/cart` are real routes, no 404, mobile/desktop smoke tests pass | IN_PROGRESS |
|
||||
| UX-CAT-001 | Dev + UX + QA | P0 | 24h | UX-DEV-001 | Shop has deterministic SSR/client data states: success/loading/empty/error/retry | TODO |
|
||||
| UX-CAT-002 | Dev + Product + QA | P0 | 24h | UX-CAT-001 | Catalog uses typed pagination/query URL state; no limit-999 hydration | TODO |
|
||||
| UX-DATA-001 | Dev + DevOps | P0 | 20h | UX-CAT-001 | API errors are typed/actionable; cache tags and invalidation are verified | TODO |
|
||||
| UX-A11Y-001 | UX + Dev + QA | P0 | 16h | UX-DEV-001 | Forms/buttons/overlays have names, labels, focus return and keyboard operation | TODO |
|
||||
| UX-RESP-001 | UX + Dev + QA | P1 | 20h | UX-CAT-001 | 360/390/768/1024/1440 layouts have no unintended overflow and 44px targets | TODO |
|
||||
| UX-PDP-001 | Product + UX + Dev + QA | P1 | 20h | UX-CAT-001 | PDP has one H1 and above-fold image/name/price/stock/CTA at all viewports | TODO |
|
||||
| UX-CHECKOUT-001 | Payments + Dev + QA | P1 | 20h | UX-A11Y-001 | Checkout fields have labels/autocomplete/inputmode and announced errors | TODO |
|
||||
| UX-NAV-001 | UX + Product + Dev | P1 | 16h | UX-RESP-001 | Mobile/desktop navigation is canonical, active state and cart state are consistent | TODO |
|
||||
| UX-SEARCH-001 | Product + UX + SEO + Dev | P1 | 16h | UX-CAT-002 | Search landmark, Persian normalization, result count and actionable no-results state | TODO |
|
||||
| UX-CONTENT-001 | Content + UX | P1 | 12h | UX-NAV-001 | Persian CTA/glossary unified across shop, wiki, auth, cart and footer | TODO |
|
||||
| UX-CONTACT-001 | Support + Dev + Product | P1 | 4h | settings readback | No empty `tel:`/`mailto:` targets; official values verified live | TODO |
|
||||
| UX-SEO-001 | SEO + Dev + QA | P1 | 16h | UX-CAT-002 | Category URLs, canonical/H1/meta and sitemap parity are tested | TODO |
|
||||
| UX-SEO-002 | SEO + Dev + Content | P1 | 12h | UX-SEO-001 | Product 404 is real 404; Product/Offer/Breadcrumb JSON-LD matches facts | TODO |
|
||||
| UX-MEDIA-001 | Content + SEO + Dev | P2 | 12h | UX-PDP-001 | Product/blog/feed images are valid, same-item, HTTPS and have useful alt text | TODO |
|
||||
| UX-PERF-001 | Dev + DevOps + QA | P0 | 24h | UX-CAT-002, UX-RESP-001 | Mobile LCP/CLS/INP budgets, reduced-motion and image dimensions are verified | TODO |
|
||||
| UX-ARCH-001 | Dev + UX | P1 | 24h | UX-CAT-001 | ArchivePage/global shell split into typed, independently testable feature modules | TODO |
|
||||
| UX-STATE-001 | Dev + Commerce + QA | P0 | 24h | UX-DATA-001 | Cart price/stock/order state is backend-authoritative and persisted safely | TODO |
|
||||
| UX-TEST-001 | Dev + QA | P0 | 16h | UX-DEV-001 | npm test/typecheck/lint scripts and coverage gates execute in clean checkout | TODO |
|
||||
| UX-E2E-001 | QA + DevOps | P1 | 20h | UX-TEST-001, UX-RESP-001 | Chromium desktop/mobile smoke covers shop/PDP/cart/login/checkout/errors | TODO |
|
||||
| UX-CI-001 | DevOps + Dev + QA | P0 | 20h | UX-TEST-001, UX-E2E-001 | CI gates lint/type/unit/build/E2E/perf and publishes evidence | TODO |
|
||||
| UX-DEPLOY-001 | DevOps + QA | P1 | 24h | UX-CI-001 | Immutable SHA deployment, health checks, smoke gate and rollback are documented/tested | TODO |
|
||||
| UX-CLAIMS-001 | R&D + Content + Compliance + human vet review | P1 | 32h | legal/vet access | 35 product/media medical claims have evidence/status and no unsupported claims publish | BLOCKED_EXTERNAL_REVIEW |
|
||||
| UX-VERIFY-001 | PMO + QA + Analytics | P2 | 16h | all release tasks | Live release checklist, CWV/error/catalog/checkout telemetry and go/no-go evidence | TODO |
|
||||
|
||||
**Current program estimate:** 396 engineering/review hours; critical path is lower with parallel teams. External legal/human-veterinarian review, recruited user panel, GSC/GA4 access and payment sandbox are explicit blockers where applicable.
|
||||
|
||||
## Immediate execution order
|
||||
|
||||
1. UX-DEV-001 — restore login/cart routes (current)
|
||||
2. UX-TEST-001 — make frontend test/typecheck gates executable
|
||||
3. UX-A11Y-001 + UX-RESP-001 — fix shared interaction and responsive foundations
|
||||
4. UX-CAT-001/002 + UX-DATA-001 — reliable catalog flow
|
||||
5. UX-PDP-001 + UX-CHECKOUT-001 + UX-STATE-001 — conversion journey
|
||||
6. SEO/content/media/performance/CI/deployment gates
|
||||
7. Live verification and release decision
|
||||
@@ -0,0 +1,30 @@
|
||||
# Narrow auth schema operation — approval required
|
||||
|
||||
## Exact scope
|
||||
`auth-schema-reconcile.sql` adds only users.auth_expires_at TIMESTAMPTZ NULL, stage_test_session VARCHAR(64) NULL, stage_test_generation UUID NULL (no defaults/backfill), and prepare_workflow_outbox with its original CHECKs, three RESTRICT FKs, task uniqueness, lease and due indexes, including nullable not_before. No existing rows changed, no auth behavior disabled, no Prisma metadata altered.
|
||||
|
||||
Read-only production PostgreSQL 16.14 catalogs verified all three users columns and outbox absent; users.id and orchestration_tasks/runs/budget_ledger.id are UUID PKs. Existing users wallet CHECK and orchestration constraints stay intact. Production has six ledger rows (one historical rolled-back admin_modules attempt), no Oct22–24 entries despite orchestration objects existing. Never run generic migrate deploy or mark whole pending history applied.
|
||||
|
||||
Historical principal migration at e036c5d has two columns, SHA256 8b4fe1fdedd2ae459b720f78479cfcb13da465eec821b422ece5e9bb41dc47ae; 80a2e18 edited it to three, SHA256 a458a94329b1ad078298b042ae0bd2e25439c1f0bb5a086beb55c517d9e0aa28. Read-only Stage ledger records the latter, not the former. Preserve both historical files unchanged here. This operation is separately journaled by CI/backup receipt, not invented Prisma history. Broader baseline/history repair remains separate work.
|
||||
|
||||
## Execution contract
|
||||
Dedicated push workflow `auth-schema-reconcile.yml` uses DEPLOY_KEY and pinned DEPLOY_KNOWN_HOSTS, fixed SSH endpoint, isolated immutable Git checkout; it does not deploy applications. It accepts only exact branches `ops/auth-schema-stage` and `ops/auth-schema-production`, mapping their full refs to Stage and production respectively. It requires REVIEWED_AUTH_SCHEMA_COMMIT matching the event SHA and checks detached checkout HEAD equals that SHA. SQL digest is fixed to `8a22f3e89efb3dacc24f3ed9337ae87d0b4345da003a607bc1994478f69c6feb`, approval ID to `CEO-AUTH-SCHEMA-20261025`; neither is push-supplied input. Production additionally requires PRODUCTION_AUTH_SCHEMA_APPROVAL = SHA:SQL_SHA256:APPROVAL_ID and STAGE_AUTH_SCHEMA_ACCEPTANCE = SHA:SQL_SHA256, provisioned only after real review and Stage auth acceptance. These are explicit approval records, not automatically issued receipts. The repository's workflow/secret permissions must restrict dedicated-ref mutation to trusted maintainers; unrestricted malicious workflow edits can bypass any workflow-local gate. Review/protect this boundary before provisioning production approval.
|
||||
|
||||
Stage already has the DDL: Stage mode backs up production read-only, restores into isolated network-none temporary PostgreSQL, applies exact SQL there, compares resulting catalog with Stage read-only, and writes a SHA-bound structural receipt only. Production requires that receipt, repeats fresh full backup and restore/patch rehearsal, then executes only exact approved SQL. Full dumps remain mode600 host-only under /opt/backups/canina-auth-reconcile; never upload/log PII. Backup nonempty and pg_restore TOC checked. Restore errors/capacity failure stop before DDL. tmpfs is capped at 1GiB: if full restore exceeds capacity, separately review capacity rather than skipping restore. Existing read-only schema backup was 94,694 bytes / 67 tables, no PII copied; its restored PostgreSQL rehearsal is genuine, not a full data-backup recovery claim.
|
||||
|
||||
SQL lock_timeout 3s, statement_timeout 30s, idle transaction 60s; advisory lock plus host flock. DDL transactional; lock/contention failure aborts all. No automatic retries. Re-execution with existing outbox fails closed pending comparison, rather than silently accepting drift. Stage/production outputs compare columns/types/nullability/defaults, all outbox constraints/indexes to fresh rehearsed expected schema.
|
||||
|
||||
## Gitea 1.22.6 trigger semantics and operator sequence
|
||||
Gitea [1.22 comparison](https://docs.gitea.com/1.22/usage/actions/comparison) explicitly marks `workflow_dispatch` ignored. The [v1.22.6 notifier implementation](https://github.com/go-gitea/gitea/blob/v1.22.6/services/actions/notifier_helper.go) resolves the pushed ref's commit, detects workflows at that commit and records `Ref` and `CommitSHA` on the run. Push is not default-branch-only. The dedicated branch must therefore contain this workflow and point to the **final integrated reviewed commit**, not a new trigger-only commit. Existing app deployment listens only to `main`/`develop`, not either operations branch.
|
||||
|
||||
After independent review/authorization, a trusted operator can push `<REVIEWED_FULL_SHA>:refs/heads/ops/auth-schema-stage` to origin. Inspect that CI run's SHA and structural receipt, then complete real Stage auth tests. Only after separate production and Stage acceptance approval records exist for the **same** SHA/digest may the operator push `<REVIEWED_FULL_SHA>:refs/heads/ops/auth-schema-production`. No empty commits, merges, arbitrary ref inputs, secret updates by this workflow, automatic acceptance, or app promotion. A no-op push does not retrigger; do not change the reviewed SHA to manufacture a run. Any SHA change requires fresh review, approval bindings and Stage evidence. Workflow preparation has not pushed either branch, changed secrets/protections or executed the operation.
|
||||
|
||||
## Acceptance and rollback
|
||||
1. Parent DBA review exact commit/diff plus SQL hash and workflow trusted-ref/secret permissions. Approve read-only production full backup + isolated full restore scope separately from production DDL.
|
||||
2. Run Stage workflow from exact commit; inspect successful backup/restore/catalog comparison. Existing Stage backend must pass ordinary admin password login + protected dashboard, OTP flow with authorized principal, refresh, and expiry/session/generation rejection tests. Do not manufacture acceptance if no approved credential/test principal is available. Record actual test run identifiers before setting Stage acceptance approval.
|
||||
3. Obtain explicit approval: execute only this commit's SQL in caninodb_prod, three nullable users columns + empty outbox and declared constraints/indexes, 3s lock/30s statement budgets, no unrelated migrations/history writes/seeds. Provision approval binding SHA, SQL digest, approval record. Trigger production workflow, inspect terminal CI log. No production execution has been performed during preparation.
|
||||
4. Release separately via existing code-only develop→Stage→main CI, using actual regenerated backend client, runtime-image/schema guard, immutable image receipts and authenticated login/OTP/refresh/protected data acceptance. Keep current compatible backend until this passes. Schema approval alone does not authorize application promotion.
|
||||
5. Before commit failure: transaction rollback. After successful DDL: leave additive nullable fields/table intact, roll back application to known compatible immutable image via approved CI; do not DROP columns or outbox after writes. Restore full backup only under separately approved incident/data-loss recovery process. Existing backup tables remain untouched.
|
||||
|
||||
## Verified preparation / limitations
|
||||
Disposable network-none PG16 schema-only restore and exact SQL executed successfully (see JSON). Missing-column SELECT failed before patch and passed after; invalid status rejected; second application rejected without changes; container removed. Independent reviewer found SQL definition matched history; requested stronger gating, Stage preexisting-schema handling, capacity awareness and postcondition validation, addressed or explicit prerequisites above. Full-data restore and dedicated workflow SSH path are implemented but not yet executed in actual CI. No production writes or deployments occurred. Approval/environment gates must not be represented as production repair completion.
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"schema_backup_bytes": 94694,
|
||||
"schema_backup_sha256": "9c6367a06acaf97c1afe9355e4306d2a10f878b7fe156c7dbc5d58d675262c72",
|
||||
"schema_tables": 67,
|
||||
"pii_copied": false,
|
||||
"postgres": "16.14",
|
||||
"restore_and_patch_seconds": 3.669,
|
||||
"pre_patch_missing_columns_failed": true,
|
||||
"post_patch_queries": " auth_expires_at | stage_test_session | stage_test_generation \n-----------------+--------------------+-----------------------\n(0 rows)\n\n count \n-------\n 0\n(1 row)\n\n count \n-------\n 0\n(1 row)\n\n",
|
||||
"constraints": " conname | pg_get_constraintdef \n---------------------------------------------+-----------------------------------------------------------------------------------------------------------\n prepare_workflow_outbox_attempts_check | CHECK (((attempts >= 0) AND (attempts <= 3)))\n prepare_workflow_outbox_pkey | PRIMARY KEY (id)\n prepare_workflow_outbox_reservation_id_fkey | FOREIGN KEY (reservation_id) REFERENCES orchestration_budget_ledger(id) ON DELETE RESTRICT\n prepare_workflow_outbox_run_id_fkey | FOREIGN KEY (run_id) REFERENCES orchestration_runs(id) ON DELETE RESTRICT\n prepare_workflow_outbox_status_check | CHECK (((status)::text = ANY ((ARRAY['PENDING'::character varying, 'DONE'::character varying])::text[])))\n prepare_workflow_outbox_task_id_fkey | FOREIGN KEY (task_id) REFERENCES orchestration_tasks(id) ON DELETE RESTRICT\n prepare_workflow_outbox_task_id_key | UNIQUE (task_id)\n(7 rows)\n\n",
|
||||
"invalid_status_rejected": true,
|
||||
"repeat_execution_rejected_without_writes": true,
|
||||
"production_writes": false
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
# Host disk retention
|
||||
|
||||
Successful authenticated CI rollout runs release-retention.py. Default keep policy is only the current active release per environment; Docker mounts and Compose working directories always protect older still-used artifacts. Dry/unpublished source and unknown ignored files are preserved, so this is not a hard quota. CI restores only its own tracked nginx/dockerignore render changes after successful acceptance. New clones use sparse checkout to omit the 85 MiB tracked graphify-out history. No node_modules were bundled in the audited releases: their ~218 MiB is tracked source/assets plus an independent ~44 MiB Git store. Historical dirty releases require individual source review; never reset them for cleanup.
|
||||
|
||||
Retained small private runtime configuration is copied mode0600 under .retained-runtime before deleting a clean obsolete release. This avoids secret deletion; this archive is not a release rollback and requires explicit secret retention review separately. No volumes, databases, sessions, evidence, images or build cache are deleted.
|
||||
|
||||
The CI-installed canina-disk-watch.timer checks every five minutes with stdlib Python, no model calls. It logs daemon.err and returns nonzero at >=85% usage or <10GiB free. This is local detection, NOT off-host paging. systemctl status canina-disk-watch.service and journalctl -t canina-disk-watch expose alarms. Monitoring does not guarantee the disk cannot fill.
|
||||
|
||||
Audit 2026-10-26: Docker daemon already bounds new json-file containers to 3x10MiB and BuildKit GC to 6GB. Fifteen pre-existing containers (including Nexus, Gitea, databases and proxy) have empty LogConfig and remain unbounded until their owners roll them through their own Git/CI. Journald has no explicit SystemMaxUse and currently occupies 1.3GB. Nexus data is real persistent storage; retention tasks were not authenticated/audited and no blobs were deleted. Neither unrelated service config nor daemon/journal configuration is changed by Canina CI. Worktree branches with unpushed commits remain intentionally retained. These residual growth mechanisms prevent any honest claim of a globally bounded host or <50GB total.
|
||||
@@ -0,0 +1,69 @@
|
||||
# Orchestration v4: Hermes runtime seam (review-only)
|
||||
|
||||
## Installed evidence / compatibility
|
||||
|
||||
Read-only inspection of `canina-hermes` source at `/opt/hermes` and Docker metadata:
|
||||
|
||||
- Running image ID: `sha256:373ddd5e6649f525b17993e1c885cdf1352127f8e98fd329140a73237125e52f`.
|
||||
- Registry digest (pinned template): `nousresearch/hermes-agent@sha256:9774f4f39a9bb8c2f68ce728ed5e99ddbad282163be56764afacf88ed952b784`.
|
||||
- Current command is `gateway run`, **not** `serve`. Loopback 9119 connection refused. This implementation does not claim a live dashboard integration or start one.
|
||||
- Existing `/opt/data` mount is external volume `canina-hermes_canina_hermes_data`; preserve it. Read-only cron JSON count: **17 jobs, 0 enabled**. Paused state is `enabled:false`, not a `paused` boolean. No cron/runtime/config mutation was made.
|
||||
- Existing untracked `/opt/services/ai/canina-hermes/compose.yml` remains untouched.
|
||||
|
||||
Sources inspected: `hermes_cli/web_routers/{status,profiles,models,sessions,analytics,cron,chat_ws}.py`, cron scoping helpers, `cron/jobs.py`, `hermes_cli/inventory.py`, `hermes_cli/dashboard_auth/{routes,middleware}.py`, `hermes_cli/web_server{,_chat}.py`, `tui_gateway/ws.py`.
|
||||
|
||||
## Supported allowlist
|
||||
|
||||
| Service method | Installed upstream contract | Public projection |
|
||||
|---|---|---|
|
||||
| health | GET /api/health | ok/version/commit/auth_required |
|
||||
| status | GET /api/status?profile= | version/gateway_running/gateway_state/overall/active_agents |
|
||||
| profiles | GET /api/profiles -> {profiles:[]} | name/is_default/gateway_running, filtered by backend scope |
|
||||
| modelInfo | GET /api/model/info?profile= | model/provider/effective_context_length |
|
||||
| modelOptions | GET /api/model/options?profile= | provider slug/name + model ID strings |
|
||||
| usage | GET /api/analytics/usage?profile=&days= | period_days and four numeric totals |
|
||||
| sessions | GET /api/sessions?profile=&limit=&offset=&full=false&order=recent | ID/profile/source/is_active, total |
|
||||
| crons | GET /api/cron/jobs?profile= -> array | ID/profile/enabled |
|
||||
| pauseCron | POST /api/cron/jobs/{id}/pause?profile= | ID/profile/enabled |
|
||||
| resumeCron | POST /api/cron/jobs/{id}/resume?profile= | implemented adapter; **disabled in registered service** |
|
||||
|
||||
No generic route/HTTP/RPC proxy. No model setter, config, secrets, PTY, trigger, deletion, raw transcript or raw logs. Status is not fabricated if unavailable. Numeric nulls/malformed/missing required fields produce CONTRACT (some empty analytics stores may therefore be unavailable). Unknown upstream fields are dropped, never forwarded; this is intentional forward-compatible redaction, not raw JSON passthrough. Scope mismatch is forbidden. Arrays cap at 1000, upstream bytes at 256 KiB, in-flight requests at 4, whole request/token budget at 5 seconds, no retries, redirects forbidden. The production fetch honors AbortSignal. Error messages never include upstream response/URL/token/exception. Do not log request headers or config objects.
|
||||
|
||||
Upstream GET /api/sessions can auto-archive internally; we inspected source only and did not call it against production. Some model inventory endpoints warm caches/probe providers. Classify these as managed reads, not guaranteed filesystem-pure operations.
|
||||
|
||||
## Authentication and WS discovery
|
||||
|
||||
- Non-loopback dashboard binds engage the provider-verified auth gate. REST supports provider-verified Bearer session tokens. Legacy loopback accepts session header/Bearer; **a Canina JWT or API_SERVER_KEY is not interchangeable**.
|
||||
- POST `/api/auth/ws-ticket` needs verified `request.state.session`; response `{ticket,ttl_seconds}` is single-use / 30 seconds. Do not mint tickets for a browser or copy credentials into browser URLs.
|
||||
- Installed WS: `/api/ws`, `/api/console`, `/api/events`, `/api/pub`, `/api/pty`; **no assumed `/api/chat/ws`**.
|
||||
- `/api/ws` uses newline-delimited JSON-RPC and `gateway.ready`; same dispatcher as TUI, broad privilege. Gated admission supports a ticket, including subprotocols `hermes-gateway-v1` and `hermes-gateway-ticket.<ticket>`; legacy process token is rejected in gated mode. Internal process credentials must never be extracted.
|
||||
- We deliberately do not bridge a powerful socket without a verified session/run ownership and event allowlist contract. `chat`/`control` return UNSUPPORTED after policy; event dispatch returns FORBIDDEN even with policy approval. No WS dependency, background connection, reconnect, or ticket endpoint is exposed.
|
||||
|
||||
## Wiring (owner integration step, no app.module.ts changes here)
|
||||
|
||||
Import `HermesManagementModule.register(config, authorizer)` in the owning backend module, then inject **HermesIntegrationService**, never the adapter into browser controllers. Registration exports the service only and defaults to deny-all policy. Example configuration:
|
||||
|
||||
```ts
|
||||
HermesManagementModule.register({
|
||||
origin: 'http://canina-hermes:9119',
|
||||
token: () => secretStore.read('hermes_dashboard_access_token'),
|
||||
}, backendRuntimeAuthorizer)
|
||||
```
|
||||
|
||||
Supply a provider-verified, short-lived Hermes token through backend secret storage (template references `/run/secrets/hermes_dashboard_access_token` only). Provision/refresh is an operator responsibility; this change neither extracts existing runtime secrets nor invents a login flow. No token in database/UI/env templates.
|
||||
|
||||
Controllers must verify Canina admin JWT, resolve subject/profile scopes from trusted backend data (not request DTO), enforce permission and rate limit/audit, translate HermesError codes to safe API errors (AUTH_REQUIRED/UNAVAILABLE -> 503, FORBIDDEN ->403, LIMIT ->429, CONTRACT/UNSUPPORTED ->502/501). Never forward upstream errors. `RuntimePrincipal` is an internal context, not a user input DTO. Authorizer must independently verify subject/action/profile. Missing/throwing authorizer denies. Registered module hard-disables resume; enabling requires an explicit reviewed code change. Resume can immediately make overdue recurring jobs due: never test it on production.
|
||||
|
||||
## Disabled event dispatch design
|
||||
|
||||
No listener, cron, poller, outbox consumer or webhook is registered. A future dispatcher must use backend-verified event identity, durable outbox and idempotency, server-resolved department/profile/run ownership, permission per action, payload minimization/redaction, budget and approval policy. Then use a tested narrow execution transport; never map arbitrary event text to TUI RPC or `/api/pub`. Unknown event/schema/principal/approval/ownership -> reject with no IO. Do not enable before isolated acceptance proves interruption, stream bounds and safe tool-output projection.
|
||||
|
||||
## Manifests and verification
|
||||
|
||||
`infra/hermes-runtime/compose.template.yml` is **not a deployable replacement yet**: manual-only profile, no automatic restart/public ports/socket/credentials, preserves external data volume, dedicated external backend network. It intentionally retains `gateway run`; dashboard/auth/network topology and gateway egress need an approved migration design. Do not run alongside current service sharing the same writable state. Never `down -v`.
|
||||
|
||||
`.gitea/workflows/hermes-runtime-contract.yml` is manual contract review only, no deploy job, SSH, runtime secret or event dispatch. Existing deploy workflow untouched. Compose parsed with `docker compose ... config --quiet`; no containers deployed.
|
||||
|
||||
Tests: `cd backend && npm test -- --runInBand hermes-management` (14 assertions across 4 suites); strict isolated typecheck/build `npx tsc -p src/hermes-management/tsconfig.contract.json [--noEmit]`; full backend `npm run build` after isolated `npx prisma generate`. All passed. Local HTTP transport is exercised on ephemeral loopback, not production. TDD failures were observed for missing adapter, inventory methods, integration service, module and concurrency limit before implementations. No live authenticated dashboard or WS execution was exercised. Host has no Node; disposable node:22-bookworm runners used. Initial shared dependency resolution and offline Prisma binary download failed; fresh worktree dependencies and isolated network-enabled Prisma generation resolved them, without DB connection/migration.
|
||||
|
||||
Final verification: full backend Jest regression **93 suites / 771 tests passed**; scoped ESLint and strict typecheck passed, full `tsc -b` build passed. Existing SSL/payment negative tests print expected error logs despite passing. No deploy or production action performed.
|
||||
@@ -0,0 +1,95 @@
|
||||
**Superseded wiring/provenance: see [snapshot repair](hermes-snapshot-provenance.md). Do not use literal grants or the old DNS alias below.**
|
||||
|
||||
# Runtime read vertical slice (not deployed)
|
||||
|
||||
Branch feature/v4-runtime-completion, base 5507fbc. No AppModule, live gateway,
|
||||
production database, cron, dispatch, or existing compose was changed.
|
||||
|
||||
## Parent registration
|
||||
|
||||
Import `RuntimeReadModule.register({ '<verified-user-id>': ['default', '<department>'] })`
|
||||
from `backend/src/hermes-management/runtime-read.module` into AppModule.
|
||||
This module uses the existing Passport `jwt` strategy (DB-resolved user identity),
|
||||
not the API-key fallback. Parent must retain AuthModule/JwtStrategy initialization.
|
||||
Missing grants deny. Never construct grants from browser body, JWT profile claims,
|
||||
or unreviewed environment input. Allowlist is copied/frozen. Admin/SUPER_ADMIN
|
||||
role AND exact subject grant required; API-key identities forbidden.
|
||||
|
||||
GET `/admin/orchestration/runtime/{health,profiles,status,usage,sessions,schedules,model-info}`.
|
||||
All except health/profiles require exactly one allowed `profile` query string.
|
||||
Usage accepts days 1..365 (30); sessions limit 1..100 (20), offset 0..10000 (0).
|
||||
Unknown parameters on profile routes rejected. Profiles is filtered to server grants.
|
||||
Responses use existing adapter projections, no prompts/transcripts/config/tokens.
|
||||
Missing/forged JWT ->401; missing grant/role/profile ->403; runtime auth/network/
|
||||
contract failure ->503 `Runtime unavailable`; limits ->429. No browser Hermes
|
||||
cookie, credential, socket ticket or mutation handler is provided.
|
||||
|
||||
Mount backend `/run/secrets/hermes_username` and `hermes_password` as files.
|
||||
Only these fixed secret paths are read, after authorization. Broker login/cache
|
||||
stays server-side. Backend and isolated inventory runtime must receive matching
|
||||
credentials. Runtime additionally mounts `hermes_signing_key` (>=32 random chars).
|
||||
Do not put credentials in YAML/env, commands, logs or Git. Rotate key to invalidate
|
||||
sessions; rotate password and restart inventory plus backend to clear cached access.
|
||||
Stateless old sessions remain valid until TTL/key rotation.
|
||||
|
||||
## Deliberately separate snapshot topology
|
||||
|
||||
Installed Hermes `serve` lifespan starts reconciliation and hosted-room recovery;
|
||||
GET sessions auto-archives. Sharing its writable home with existing gateway is
|
||||
therefore NOT a safe read-only sidecar. `serve.py` runs the pinned installed app
|
||||
with lifespan OFF and an outer exact GET allowlist, password-login only and all
|
||||
WebSockets denied1008. It does NOT start scheduler/gateway/MCP/rooms/provider chat.
|
||||
The existing gateway and external volume `canina-hermes_canina_hermes_data` remain
|
||||
unchanged, solely owned by existing gateway. Inventory mounts an independently
|
||||
provisioned snapshot volume `canina_hermes_inventory_snapshot`; it NEVER mounts
|
||||
original home. Its incidental session auto-archive writes affect only snapshot.
|
||||
This is snapshot inventory, NOT live runtime freshness/status acceptance. A copy
|
||||
of gateway PID state is not evidence of live gateway health. UI must not claim live
|
||||
readiness from this deployment. Parent should expose snapshot provenance/freshness
|
||||
before enabling it for business use.
|
||||
|
||||
Provisioning must use an approved consistent SQLite backup/checkpoint/export and
|
||||
redacted profile config inventory, not raw `cp` of changing SQLite/WAL or credentials.
|
||||
No automatic snapshot job is installed here. No secrets need be copied from live
|
||||
home. Review which configs the model/status APIs need and omit auth.json/.env.
|
||||
Missing store/schema -> unavailable, not fabricated empty healthy telemetry.
|
||||
Dedicated internal network must contain only backend and inventory; do NOT connect
|
||||
existing gateway with same `canina-hermes` DNS alias. Backend name resolves inventory.
|
||||
Inventory network must have no external egress. Compose refers to external network;
|
||||
operator must create it `--internal`. No host ports/socket are published.
|
||||
|
||||
## CI ownership / apply
|
||||
|
||||
`compose.readonly.yml` is deployable ONLY after external snapshot, internal network,
|
||||
secret files and backend mounts/registration are provisioned. `ci-apply.sh` requires
|
||||
CI=true, exact reviewed HEAD SHA, clean checkout, snapshot-reviewed assertion,
|
||||
existing volume/network/files, then compose config/up. Never run alongside any
|
||||
other inventory instance writing same snapshot. CI job fragment is tracked under
|
||||
infra ownership; parent owns real workflow wiring and approval environment. No
|
||||
active deployment trigger added. Existing review-only compose template is unchanged.
|
||||
|
||||
## Executed evidence
|
||||
|
||||
Remote `/opt/services/canina/validation/v4-runtime-completion/`:
|
||||
- read-red.log missing controller regression; read-green.log 6 suites/27 tests.
|
||||
- read-http-green.log 7 suites/30 tests: real Nest HTTP with signed JWT strategy,
|
||||
bad signature/no auth401, ungranted admin403, allowed admin200, no cookie,
|
||||
mutation404. This uses a mocked runtime service, not live Canina credentials.
|
||||
- pinned-http.log exact installed image FastAPI login/protected inventory:
|
||||
wrong password401, real login200/HttpOnly provider-verifiable token, profiles200,
|
||||
tampered token401. No lifespan/live home.
|
||||
- serve-http.log actual loopback TCP9119 in network-none disposable pinned image:
|
||||
unauth inventory401, wrong password401, login200, profiles200, health auth true,
|
||||
mutation/config/ws HTTP404. Generated test-only credentials. No live volume.
|
||||
- ws-red.log existing socket rejection code differed; ws-green.log explicit
|
||||
outer boundary denies authenticated sockets1008 independently of upstream tickets.
|
||||
- build.log private Prisma generation and full backend tsc build exit0.
|
||||
|
||||
Pinned local exact image ID sha256:373ddd5e6649f525b17993e1c885cdf1352127f8e98fd329140a73237125e52f;
|
||||
tracked registry digest sha256:9774f4f39a9bb8c2f68ce728ed5e99ddbad282163be56764afacf88ed952b784.
|
||||
Node22 disposable runner copied read-only source/dependency donor privately;
|
||||
no DB migration. broker-pinned-e2e.log proves actual compiled Node broker -> TCP pinned Hermes login -> adapter -> policy-filtered inventory (and deny zero secret reads). Nest HTTP authentication tested separately; these tests do not establish full Canina application E2E, snapshot
|
||||
refresh, CI deployment, live gateway truth or business workflow acceptance.
|
||||
Those remain explicit integration/provisioning gates, not claimed completion.
|
||||
|
||||
Final full non-DB regression: 106 suites / 850 tests pass; expected legacy negative SSL/payment logs. Scoped ESLint has zero errors, six type-safety warnings; full build passes. No RELEASE_AUTHORIZE integration suite run.
|
||||
@@ -0,0 +1,86 @@
|
||||
# Snapshot provenance repair — integration contract
|
||||
|
||||
This is independent snapshot inventory, **not a live Hermes executor**. No Production,
|
||||
deployment, live gateway edits, or RELEASE_AUTHORIZE execution is included.
|
||||
|
||||
## Parent-owned application wiring
|
||||
|
||||
Keep AuthModule/JwtStrategy. Replace literal user grants in parent-owned app.module.ts with:
|
||||
|
||||
```ts
|
||||
RuntimeReadModule.registerFromFile('/run/secrets/hermes_runtime_grants')
|
||||
```
|
||||
|
||||
Nest supports the resulting Promise<DynamicModule> in imports. Alternatively pass the
|
||||
reviewed nonsecret file `/etc/canina/runtime-grants.json`. No env/JWT/browser grant
|
||||
input is accepted by this registration. File is JSON object mapping exact verified DB
|
||||
user IDs to nonempty unique profile arrays; `{}` explicitly denies everyone. Missing,
|
||||
malformed, symlinked, group/world-writable, oversized files fail startup closed. Mount
|
||||
read-only and provision via reviewed configuration/secrets management; do not commit
|
||||
real user grants. Existing explicit register(grants) remains for tests/legacy consumers.
|
||||
Backend also mounts `/run/secrets/hermes_username` and `hermes_password` read-only.
|
||||
No app.module.ts modification belongs to this commit.
|
||||
|
||||
## Required coordinated origin change
|
||||
|
||||
Authenticated management module and broker now exclusively use
|
||||
`http://canina-hermes-inventory:9119`. compose.readonly.yml uses the distinct alias
|
||||
`canina-hermes-inventory`, NEVER `canina-hermes`. Generic adapter allowlist retains
|
||||
both reviewed exact origins for compatibility with separate existing consumers.
|
||||
No arbitrary origin/env URL accepted. Parent must cherry-pick broker/module/adapter
|
||||
and inventory compose together; do not add an alias to the existing gateway.
|
||||
No deployment performed. External network should still be internal and only contain
|
||||
backend/inventory; the distinct alias cannot shadow the live canina-hermes hostname.
|
||||
|
||||
## Snapshot exporter/operator gate
|
||||
|
||||
Every independent inventory root must include `snapshot-manifest.json`:
|
||||
|
||||
```json
|
||||
{"schemaVersion":1,"source":"snapshot","capturedAt":"2026-10-23T12:00:00Z"}
|
||||
```
|
||||
|
||||
The example is a schema example, NOT an actual capture attestation. Exporter must
|
||||
write the real capture instant from the approved consistent export. Never copy the
|
||||
example, use startup time, filesystem mtime, or claim this change captures/refreshes
|
||||
snapshots. Missing/invalid/future manifest prevents startup. It is revalidated per
|
||||
successful GET; invalid after startup returns503. Manifest is exporter metadata,
|
||||
not a cryptographic proof of consistency. Immutable reviewed export provisioning
|
||||
remains required. Fresh means age <=3600 seconds, otherwise stale; even fresh is
|
||||
NOT live readiness. No snapshot scheduler installed.
|
||||
|
||||
## Additive public response fields / panel handoff
|
||||
|
||||
All object read DTOs (health/status/usage/sessions/model-info) add:
|
||||
`provenance:{source:'snapshot',capturedAt:string,ageSeconds:number,freshness:'fresh'|'stale',liveProcess:'unknown'}`.
|
||||
Profile and schedule array shapes are preserved: provenance is on each row. Empty
|
||||
arrays have no rows to annotate; use the health response to display snapshot metadata.
|
||||
Profile rows add `liveGatewayState:'unknown'`; status adds the same plus
|
||||
`liveActiveAgents:null`. Existing required scalars remain typed but are conservative
|
||||
placeholders: `gateway_running:false`, `active_agents:0`, `gateway_state:null`,
|
||||
`overall:'unknown'`. False/zero MUST NOT render as measured offline/idle: when
|
||||
provenance.source is snapshot use the explicit unknown fields, label snapshot and
|
||||
show capturedAt/freshness. Health.ok only means inventory HTTP app responsiveness,
|
||||
never live gateway readiness. Profile existence is inventory availability, NOT
|
||||
process readiness. Adapter enforces provenance on dedicated snapshot origin and
|
||||
conservatively overwrites copied PID-derived status/profile scalars again.
|
||||
|
||||
Installed status handler was unsafe here: it probes gateway HTTP/PIDs/platforms and
|
||||
can stall despite this being an independent snapshot. Snapshot server replaces that
|
||||
route with measured package version and explicit unknown process fields; no status
|
||||
probe is run. Password auth/mutation denial/WebSocket denial remain intact.
|
||||
|
||||
## Executed acceptance
|
||||
|
||||
Remote disposable network-none exact pinned Hermes image, no original volumes:
|
||||
manifest-missing regression failed first; TCP login/profile/health/status provenance
|
||||
and stale capture assertions now pass; authenticated sockets denied1008. Disposable
|
||||
Node22 copy of source/dependencies: 9 hermes-management suites /34 tests pass and
|
||||
full backend tsc build passes. Adapter copied-live-state regression failed first;
|
||||
grants-loader missing-function regression failed first. Compiled actual Node broker
|
||||
-> TCP pinned server -> adapter -> policy-filtered profiles/status passes, deny reads
|
||||
zero credentials. Test timestamps/credentials are fixtures, not live telemetry.
|
||||
The first HTTP retry raced fixture startup and returned UNAVAILABLE; retry after
|
||||
server startup passed. No claim of full app/user-flow or live runtime integration.
|
||||
|
||||
Full non-DB Jest regression: 108 suites/854 tests passed; 1 suite/18 tests skipped. No RELEASE_AUTHORIZE suite was enabled.
|
||||
@@ -0,0 +1,21 @@
|
||||
# Queued Gate1 validity correction
|
||||
|
||||
## Read-only Stage evidence (2026-10-24)
|
||||
|
||||
Task `565ace1f-8cfc-4447-b978-66c36e7b767b`: READY, version 4, PREPARE/STAGE_PREPARE, proposer `pmo`. Approval `30f8ce5c-ce00-4885-8eea-3c1bb5a7e8b0`: gate 1 APPROVED by independent actor `4a0afc72-0fd4-4d76-825b-aea13f00e880`, created 05:37:54.808Z, **expires 06:37:00Z**. runId/artifactHash/commitSha/environment on that Gate1 decision are null (normal Gate1 task binding, not Gate2 binding). Recovery event sequence 4 queued the valid approval at 06:22:06.891Z; outbox PENDING, attempts 0, runId null, notBefore null. At 09:15Z it was truly expired. Editorial claim queries newest decision for this task/gate, not a version-specific approval; it correctly rejects it. No evidence of a binding/version mismatch.
|
||||
|
||||
## Behavior
|
||||
|
||||
Persisted state remains READY; separate displayState reports blocked/renewal-required on reads. No approval is extended automatically. Existing independent reviewer authorization and task row lock protect a new ordinary Gate1 APPROVED decision. Renewal is limited to READY with a latest expired independent APPROVED decision and an unstarted PENDING outbox. It appends a decision and PREPARE_GATE1_RENEWED event, increments task version, preserves task scope/commit/budget and the existing outbox/notBefore. It rejects scheduling changes, active/attempted execution, valid approvals and self-review. Claim logic and its kill/budget/lease checks remain unchanged.
|
||||
|
||||
## Owner steps after parent CI integration
|
||||
|
||||
1. Sign in normally as an independent SUPER_ADMIN (or existing provisioned canonical owner reviewer); do not use worker identity or impersonation.
|
||||
2. Open orchestration, refresh server state, find this same task in owner decisions marked `مسدود — تأیید Gate1 منقضی شده؛ نیازمند تأیید مجدد مالک`.
|
||||
3. Review immutable scope, acceptance criteria, commit, environment and 20-cent budget; open ordinary Gate1 approval. Confirm bounded work explicitly. Renewal keeps the previous schedule; no new scheduled-start input is shown.
|
||||
4. Confirm once. The existing POST `/api/admin/orchestration/tasks/565ace1f-8cfc-4447-b978-66c36e7b767b/gates/1/decide` uses `{decision:"APPROVED",expectedVersion:4,idempotencyKey:<fresh unique key>}` (use refreshed version if changed). Notes optional; omit expiresAt for backend 24-hour validity. Retry only the identical payload/key after an ambiguous response; 409 requires refresh.
|
||||
5. Verify new independent decision, PREPARE_GATE1_RENEWED event and version increment. Do not recreate task or enqueue another outbox. Parent performs separately authorized runner/live acceptance.
|
||||
|
||||
## Verification
|
||||
|
||||
Frozen 09:15Z regression observed RED before implementation for READY representation and ordinary renewal; editorial exact 403/read mismatch observed RED; UI owner queue observed RED. GREEN: 41 backend scoped tests, 25 admin scoped tests. Disposable PostgreSQL test passes real simultaneous renewal/replay and claim serialization, expired denial, immutable old approval retention, one outbox/one claim. Backend build, Prisma client generation, admin build and application TypeScript check passed in Node22 with private donor dependencies. Initial build permission/stale-generated-client setup failures corrected only in private worktree copies. No Stage/Production DB mutation, approval, runner invocation, push or deploy.
|
||||
@@ -0,0 +1,22 @@
|
||||
# Orchestration v4 read-only integration verification
|
||||
|
||||
Base e5c83e87fe2d52d06eb36532fa9e354570678c43 plus cherry-picks admin a34c2a9, runtime bd58cc4, router b0f4636. Separate remote worktree; no dirty core edits, pushes, deploys, DB access or runtime changes.
|
||||
|
||||
## RED → GREEN proof
|
||||
- New backend HTTP boundary suite initially failed 4/4: mutation returned 201, BigInt serialization returned 500, overview missing (404). After integration: 4/4 pass, covering all mutation routes, anonymous/customer rejection, secret projection, actual overview and unavailable resources.
|
||||
- New UI fail-closed capability test initially failed because Create bounded work was visible without authorization. After capability gating: 7/7 command-center tests pass. Existing explicit action/binding/retry tests retained.
|
||||
|
||||
## Disposable remote validation
|
||||
Node 22 bookworm, network none, userns host (host Docker remapping prevents normal bind mounts), worktree source mounts, read-only sibling dependency cache. Vite cache directories are ephemeral tmpfs; no existing dependency trees changed.
|
||||
- Backend focused aggregate: **13 suites, 65 tests pass** (orchestration, Hermes, router usage).
|
||||
- Backend `tsc --noEmit`: exit 0. `npm run build`: exit 0.
|
||||
- Backend changed controller/HTTP spec ESLint: exit 0, 8 unsafe-argument warnings (7 test harness, 1 existing any-typed Prisma result). Baseline subsystem lint had 256 errors/8 warnings largely inherited formatting; no full lint pass claimed.
|
||||
- Admin focused aggregate: **5 files, 19 tests pass** (command center, orchestration/router adapters, creation, navigation).
|
||||
- Admin `npm run build`: exit 0, existing unresolved font warning remains.
|
||||
- Admin `tsc --noEmit -p tsconfig.app.json`: exit 2 with **33 inherited diagnostics** outside this change: legacy Approvals/Audit/HQ/Dashboard/ManagerActions/Tasks unused imports, Orders requiresRx missing, Symptoms ConfirmModal props/unused setter. No changed-file diagnostics. Full admin typecheck is NOT green.
|
||||
|
||||
## Security/release blockers
|
||||
The committed legacy core permits gate-state bypass through generic transitions and lacks hardened replay/authorization/budget/kill-switch boundaries. It is retained unchanged for parent integration; every exposed v4 mutation is unconditionally denied by controller. Do not restore controller calls or enable execution until hardened core is merged and reverified.
|
||||
Runtime dashboard not listening per parent investigation; no fabricated health or live availability claim. No trusted runtime identity/profile policy or runtime auth configured. Chat, cron mutations, execution/event dispatch, release execution stay disabled. Read-only inventory still requires orchestration schema migration through approved CI/CD, never manual DB changes. Backend read queries are currently full inventory and release evidence uses per-task reads; pagination/scaling remains future work.
|
||||
|
||||
Parent must inspect this commit and reconcile hardened core before any mutation milestone. No Stage promotion performed by this worker; admin typecheck failures remain explicit verification blockers for parent decision.
|
||||
@@ -0,0 +1,50 @@
|
||||
# Stage v4 rollout safety
|
||||
|
||||
## Scope and deployment boundary
|
||||
|
||||
Only a push to `develop` followed by the existing Gitea workflow may roll out this change. Do not run `deploy.sh` manually. Its CI marker is an accident guard, not an authentication boundary: runner permissions remain the security boundary. `main`, unknown branches and the former `stage-backend-only` bypass fail before Docker operations. Production is intentionally blocked pending separate review; no silent baseline/resolve is permitted.
|
||||
|
||||
## Tracked sequence
|
||||
|
||||
1. Acquire the Stage rollout lock (same lock as the retired backend-only path).
|
||||
2. Fetch the branch and build images using the existing workflow. Build failure leaves old applications running.
|
||||
3. Stop Stage frontend and backend (maintenance/outage; no promise of a custom 503 page).
|
||||
4. Run the newly built backend image as an isolated one-off Prisma CLI job (`compose run --rm --no-deps --entrypoint ... migrate deploy`). No app command, published service ports or automatic baseline. Existing DB must already be running.
|
||||
5. Only on migration success start backend. Require all nine v4 tables, the successful tracked migration receipt and an actual HTTP catalog response with the catalog envelope. HTTP acceptance has bounded retries and timeouts; no response body is logged.
|
||||
6. On backend acceptance failure stop both applications and fail. Only after acceptance start frontend. CI success marker follows these gates. The shared support bot is not rebuilt/replaced by this Stage rollout.
|
||||
|
||||
Migration failure leaves maintenance in place; do not auto-restart old apps against a partly migrated schema. Diagnose from CI logs, restore from an authorized backup or ship a reviewed forward fix through CI/CD. Never `db push`, seed, silently `migrate resolve`, or manually apply live DDL.
|
||||
|
||||
## Verification (2026-10-22)
|
||||
|
||||
Strict RED/GREEN cycles captured missing rollout function, migration failure ordering, missing backend acceptance and missing CI/Production guard before implementation. `python3 scripts/tests/test_stage_rollout.py`: 3 passed. Shell tests simulate Docker failures to prove sequencing only; they do NOT certify a healthy release. `node --test scripts/tests/test_rollout_health.cjs`: 4 passed using a local HTTP server (503, HTML, incorrect envelope rejected; valid empty catalog shape accepted). These fixtures are not live health evidence.
|
||||
|
||||
`python3 scripts/tests/rehearse_rollout.py` performs only schema-only `pg_dump` and migration-history-only data dump from Stage. It restores into a fresh PostgreSQL 16 container with no network, no host ports, no persistent volume, and no customer rows. Prisma runs in that disposable container's network namespace using an existing generated v4 client/dependencies read-only from the core test worktree. Dumps have a private temporary directory and are removed on exit.
|
||||
|
||||
Observed output:
|
||||
|
||||
```
|
||||
Applying migration `20261022000000_add_orchestration_v4_core`
|
||||
All migrations have been successfully applied.
|
||||
No pending migrations to apply.
|
||||
PASS: actual Prisma legacy catalog/support and v4 relation queries
|
||||
Restored 61 legacy tables; all business tables empty
|
||||
PASS: unchanged legacy column definitions; 61 legacy queries; 9 v4 tables; migrate deploy repeatable
|
||||
Disposable database/container removed; no live DDL performed
|
||||
```
|
||||
|
||||
The first rehearsal hit a read-only nested mount creation error, cleaned up, and was corrected to mount only `prisma/` plus dependencies; subsequent rehearsals passed.
|
||||
|
||||
## Remaining acceptance constraints
|
||||
|
||||
- No push, actual deployment, live DDL, customer export, or Production change was performed. No live v4 health success is claimed.
|
||||
- Schema-only rehearsal proves schema/query compatibility, not row-volume performance, locks under traffic, or business-data backfill behavior. All 61 legacy business tables were verified empty.
|
||||
- Full image build/start and public frontend/admin/API acceptance still require the authorized CI rollout. The gate currently covers backend schema/catalog; frontend start success is not browser acceptance.
|
||||
- Workflow now downloads the deployment entrypoint by triggering `github.sha` and passes `DEPLOY_SHA`. The entrypoint rejects missing/malformed SHA values, verifies that the commit belongs to the fetched deployment branch, and checks out that exact commit. Six disposable rollout tests cover sequencing, CI/Production guards, pin wiring and SHA validation. Actual runner execution and strong artifact/release attestation still require live CI acceptance; SHA pinning alone does not authenticate artifact evidence.
|
||||
- Existing compose credentials are out of scope; no new credentials are added. Continue restricting runner access and runtime env files. Orchestration mutation/chat/runtime remain disabled in the integration base; this rollout does not enable them.
|
||||
|
||||
## Completion-branch rehearsal
|
||||
|
||||
The repository-relative rehearsal applied both `20261022000000_add_orchestration_v4_core` and `20261022190000_harden_orchestration_ledger` to a disposable database restored from Stage schema/history only. All 61 legacy business tables were empty, their column definitions were unchanged, nine v4 tables and actual Prisma queries passed, and a second deploy found no pending migrations. No live DDL or release execution occurred.
|
||||
|
||||
The workflow shell now stops on download failure. SHA-pinning and six rollout tests plus four HTTP fixtures are verified locally in disposable containers; they are not proof of an actual CI rollout or frontend acceptance.
|
||||
@@ -0,0 +1,41 @@
|
||||
# 9router admin consumption adapter
|
||||
|
||||
## Wiring (integration owner)
|
||||
Import `RouterUsageModule` from `backend/src/router-usage/router-usage.module` into the root application's imports. This branch deliberately does not edit app.module.ts. Existing AuthModule/JWT strategy must be registered by the application. Route requires a JWT bearer user with admin/superadmin role; API-key authentication is deliberately not enabled for this sensitive endpoint.
|
||||
|
||||
Set backend-only `ROUTER_USAGE_CLI_TOKEN` using the existing router CLI auth token from the operator secret store. Optional `ROUTER_USAGE_BASE_URL` must be exactly `https://nr.parsaaghayi.ir` (an origin slash is accepted). Do not ship this token to the frontend. No environment/configuration was changed during implementation. No push/deploy performed; integration follows CI/CD and production needs separate Gate2.
|
||||
|
||||
## Exact API
|
||||
`GET /admin/router-usage?period=7d` (plus the existing application global prefix, if any).
|
||||
Allowed periods: `today`, `24h`, `7d`, `30d`, `60d`, `all`; default `7d`. Unknown query properties/custom from/to ranges and invalid periods return 400. Missing/invalid JWT is rejected by Passport; authenticated non-admin gets 403. Response is private/no-store.
|
||||
|
||||
Response fields:
|
||||
- `source: "9router"`, `period`
|
||||
- `status: "available" | "unavailable"`
|
||||
- `reason: null | "not_configured" | "invalid_configuration" | "busy" | "upstream_unavailable"`
|
||||
- `attribution: {scope:"9router_total", hermes:null, additive:false}`
|
||||
- `freshness: {retrievedAt: ISO8601|null, sourceUpdatedAt:null, stale:null}`. Retrieval time is NOT a guarantee of provider freshness. The source exposes no authoritative updated-at for aggregates. No last-good cache is served.
|
||||
- `capabilities: {errors:false, reasoningTokens:false, cacheWriteTokens:false, quota:false, customTimeRange:false}`
|
||||
- `data: null | {totals, providers:[], models:[], accounts:[]}`
|
||||
|
||||
Every metrics object contains `requests`, `inputTokens`, `outputTokens`, `cacheReadTokens`, `cacheWriteTokens`, `reasoningTokens`, `errors` (number|null). Zero is retained only if upstream reported zero; absent/invalid counters remain null. Input/output/cache map to promptTokens/completionTokens/cachedTokens; cache-read is a subset of input, never add it again. Cache-write/reasoning/errors are always null because the stats contract does not expose these aggregates.
|
||||
|
||||
Provider rows: `{provider,...metrics}`. Model rows: `{model,provider,...metrics}`. Account rows: `{accountId,model,provider,...metrics,quota:{status:"unknown",remaining:null,resetAt:null,reason:"upstream_quota_get_mutates_credentials"}}`. Account rows are upstream account/model summaries, NOT unique account inventory; accounts without usage are absent. IDs are validated, nullable if unsafe; account names/emails are never returned. No raw upstream maps, logs, prompts, provider data or credentials are returned. Dimensions are different views of the same consumption: do NOT sum totals+models+accounts. Hermes attribution remains unknown; do NOT add Hermes telemetry to router totals.
|
||||
|
||||
## Deployed-source inspection and real probe
|
||||
Read-only inspected running `9router` image `decolua/9router:vpn`: compiled `/app/.next/server/app/api/usage/stats/route.js`, `/app/.next/server/chunks/9100.js`, `/app/.next/server/middleware.js`, `/app/.next/server/chunks/7211.js`, providers routes and `/app/open-sse/services/usage.js`. No credential tables or router DB contents were dumped/modified.
|
||||
|
||||
Verified stats route accepts the periods above. `today` uses router-local midnight, `24h` rolling history; 7/30/60d use router-local daily buckets, `all` all retained daily aggregates. This is not arbitrary UTC timestamp filtering; retention/completeness is upstream-owned.
|
||||
|
||||
Authenticated internal GET probe returned HTTP 200, 5 provider summaries, 21 model summaries, 21 account/model summaries. Verified model fields: requests, promptTokens, completionTokens, cachedTokens, cost, rawModel, provider, lastUsed. Account fields additionally include connectionId/accountName. Only schema/counts printed; no keys or account values printed. Public HTTPS reverse proxy path was not live-authenticated, so its separate proxy authentication/network reachability remains an operator verification step.
|
||||
|
||||
Dashboard routes authenticate using `x-9r-cli-token` or valid `auth_token` session cookie. Normal inference API Bearer keys do NOT authenticate these dashboard routes. CLI token is NOT the contents of cli-secret: deployed middleware computes first 16 hex characters of SHA256(machine-id + "9r-cli-auth" + cli-secret). Probe derived it only inside the router process command and never emitted it; no new token or configuration was created.
|
||||
|
||||
**Security finding:** stats `byApiKey` map keys contain raw inference keys, even when row fields are masked. Adapter discards this map entirely and never logs response bodies/errors.
|
||||
|
||||
**Quota blocker:** `GET /api/usage/[connectionId]` calls refreshAndUpdateCredentials, including updateProviderConnection; OAuth refresh/retry can persist credentials. It is NOT read-only despite being GET. Therefore adapter does NOT call it. Provider quota handlers can return quotas (used/total/remaining/resetAt), messages or synthesized unlimited defaults; these cannot safely be treated as verified provider truth here. Quota reset grants exist in provider helpers but must never be consumed by this adapter. No safe deployed cache-only provider quota route was established. A separately reviewed router-side non-mutating, provenance/timestamp-bearing quota snapshot API is required before exposing live remaining/reset. Quota is unknown, never zero/unlimited fabricated. Connection inventory/status refresh is also not represented as quota truth.
|
||||
|
||||
## Bounds and verification
|
||||
Only fixed-origin authenticated GET `/api/usage/stats` is invoked; redirect:error, abort after 5 seconds, streaming cap 1 MiB, <=2000 rows per dimension, <=4 concurrent requests per backend process. No retries or stale cache. Schema/transport/auth/rate-limit/oversize failures produce unavailable + null data without raw errors. No SQL, POST or token refresh.
|
||||
|
||||
Strict test-first slices observed missing contract, adapter, module failures before implementation. Disposable containers used existing backend image dependencies, read-only source mounts, network disabled and copied source into ephemeral /work; no host dependencies/build output or running containers changed. `npm run build` passed. Focused: 3 suites/24 tests passed. Full backend regression: 92 suites/781 tests passed (existing negative-path tests log expected payment/SSL errors). HTTP guard tests replace JWT authentication only and exercise real RolesGuard; deployed JWT strategy remains application-owned.
|
||||
@@ -0,0 +1,53 @@
|
||||
# Durable Stage cleanup verification
|
||||
|
||||
This change replaces the SHA-pinned transient timer with a root-owned intent journal
|
||||
and a fixed host systemd retry worker. No host service is installed or enabled by
|
||||
the CI credential command. The tracked `deploy.yml` → `ci-host-deploy.sh` →
|
||||
`deploy.sh` path invokes `install-stage-principal-cleanup.py` from the verified
|
||||
immutable release before `stage_rollout`. It atomically installs the root-owned
|
||||
worker (0755) and supplied systemd units (0644), reloads systemd, enables/starts
|
||||
the timer and verifies enabled/active state. Failure aborts rollout. No manual
|
||||
sudo provisioning is required or permitted during review. The open wrapper refuses to operate
|
||||
without an enabled and active timer. Never overwrite or delete the 0700 root-owned
|
||||
`/opt/services/canina/stage-principal-cleanup` journal during deployments.
|
||||
|
||||
A journal entry is fsynced before provisioning and contains the exact session,
|
||||
random generation, creation SHA, bounded TTL and immutable cleanup deadline.
|
||||
Repeated opens fail rather than replace an intent or renew TTL. Close and the
|
||||
30-second boot/periodic retry worker retain intents on lock contention, unavailable
|
||||
containers/DB, and relational deletion failures. Cleanup resolves the current Stage
|
||||
container ID once, verifies its cleanup capability, and authenticates against its
|
||||
current artifact SHA while retaining original session/generation ownership. Older
|
||||
artifacts without generation cleanup support fail closed; never roll back to one
|
||||
with a pending principal. Persisted expiry remains independently enforced at login,
|
||||
refresh and every scoped JWT request.
|
||||
|
||||
Revocation commits before private-handle removal; relational deletion is subsequent.
|
||||
A transaction acquires a generation/session-fenced row lock before touching related
|
||||
records. Failed deletion retains a revoked row and a pending retry intent, but no
|
||||
credential handle. Wrong ownership/generation never invokes the handle callback.
|
||||
The CLI requires the generation supplied by the private journal; no broader admin
|
||||
or production authority was introduced.
|
||||
|
||||
Verification performed in a new isolated worktree and disposable Docker network:
|
||||
- Cleanup fence tests: RED (replacement generation was revoked; callback missing),
|
||||
then GREEN (2 tests).
|
||||
- Python simulated worker tests: restart/redeploy, failed-delete retry, lock
|
||||
contention, immutable container ID/current artifact and old-CLI refusal (4 tests).
|
||||
- Persisted account lifecycle plus delete/recreate access AND refresh regression.
|
||||
- Actual CLI via ts-node with real disposable Postgres/Redis and HTTP adminLogin
|
||||
handler, injected PostgreSQL delete trigger failure: confirmed revocation,
|
||||
private handle removal, then successful repeated cleanup after trigger removal.
|
||||
- TypeScript `tsc --noEmit`: passed.
|
||||
- Full migration chain attempt on fresh disposable database: baseline failure in
|
||||
20261020000000_add_blog_freshness_authorship (`blogs` missing). Not concealed.
|
||||
Independent migration test constructed the pre-Stage schema excluding all three
|
||||
new fields, then applied the EXACT committed 20261024090000 migration with psql
|
||||
ON_ERROR_STOP before exercising persisted lifecycle. Not db-push-only testing.
|
||||
|
||||
No live account, Stage/Production DB mutation, deployment, push, host service change,
|
||||
or retry of the previous pending-approval operation was performed.
|
||||
|
||||
Invocation after normal reviewed deployment and host prerequisite provisioning:
|
||||
`sudo -n env CI=true STAGE_TEST_APPROVAL=owner-authorized-stage-editorial bash /opt/services/canina/releases/<promoted-sha>/scripts/stage-test-principal-host.sh <promoted-sha> <unique-session> 600 open`
|
||||
Use the same command with `close` immediately after the authorized test.
|
||||
@@ -0,0 +1,145 @@
|
||||
# Opt-in Stage runtime provisioning (parent wiring contract)
|
||||
|
||||
This provisions **snapshot inventory** and credentials for the existing PREPARE
|
||||
transport. It does NOT create a real LLM executor. The current deterministic worker
|
||||
is still `llmPilot:false`. No provider credentials are collected, no cron installed,
|
||||
no task claimed and no worker polling/service started by the provisioner.
|
||||
|
||||
## CI-only host invocation
|
||||
|
||||
Parent owns workflow/deploy.sh/AppModule; none are changed here. Run only through
|
||||
the existing pinned authenticated SSH CI boundary, under its Stage environment
|
||||
approval and serialized rollout lock. `CI=true` is an accident guard, not an auth
|
||||
boundary. Provisioner checks clean HEAD equals the full approved commit; no branch
|
||||
promotion, push, Production, RELEASE_AUTHORIZE, Docker or DB writes are performed.
|
||||
Only the CI account should be able to invoke this on a root-owned trusted parent.
|
||||
|
||||
From the clean pinned release checkout on the host (not the dirty Stage checkout):
|
||||
|
||||
```sh
|
||||
CI=true STAGE_PROVISION_ENABLED=true STAGE_PROVISION_APPROVED_SHA="$DEPLOY_SHA" \
|
||||
python3 scripts/provision-stage-runtime.py --uid 1000 --gid 1000
|
||||
```
|
||||
|
||||
Default output root is `/opt/services/canina/stage-runtime` and its parent must
|
||||
already exist. First creation is staged and atomically renamed. Repeating validates
|
||||
existing state without rotating credentials. Corrupt/missing/unsafe files fail
|
||||
closed, not repaired. CI MUST serialize execution and prevent untrusted edits to
|
||||
source/output parents; this is not a hostile-filesystem sandbox. `--root` is for
|
||||
CI-reviewed test/Stage locations only, not arbitrary browser input. Secure backup
|
||||
and separately approved rotation are parent/operator responsibilities.
|
||||
|
||||
- `secrets/` 0700, files 0400 owned by the runtime UID (1000 in the current backend
|
||||
image); `hermes_username/password/signing_key` are new independent random values.
|
||||
- `prepare_worker_grants` contains SHA256 only, exact separate service identities
|
||||
`stage-prepare-worker`/WORKFLOW_WORKER and `stage-evidence-ci`/STAGE_CI. These are
|
||||
transport service identities, **not invented DB admin users**.
|
||||
- Raw `credentials/prepare_worker_token` and `credentials/stage_ci_token` stay in a
|
||||
CI-owner-only 0700 directory, 0400 files. Do NOT mount either into inventory or
|
||||
backend, log them, upload them as artifacts or send them to browsers. A later
|
||||
reviewed one-shot executor receives only its own token through a private file.
|
||||
- `artifacts/` is 0700 owned by backend UID; backend alone writes it. Persistent
|
||||
local disk is not object storage or external publication evidence.
|
||||
- `hermes_runtime_grants` is `{}`: deny all. No live admin query was needed/performed.
|
||||
Parent must separately query actual Stage admin IDs read-only, review exact ID to
|
||||
profile mapping and provision a private replacement via configuration management
|
||||
before claiming panel access. Never infer identities from usernames or JWT input.
|
||||
Deliberately changed grants require separate review; default provisioner refuses
|
||||
nonempty runtime grants on repeat.
|
||||
- Compose file-backed secrets preserve host permissions/ownership; `uid/gid/mode`
|
||||
declarations do not fix bind mount ownership. Verify effective host IDs if Docker
|
||||
uses userns remapping; do not chmod 0444 as a workaround.
|
||||
|
||||
## Consistent restricted export
|
||||
|
||||
After approval, the SAME CI invocation may explicitly request one profile's source
|
||||
SQLite DB. Resolve its real `HERMES_HOME/state.db` through reviewed host mounts;
|
||||
never guess a gateway volume path or mount the original home into inventory.
|
||||
|
||||
```sh
|
||||
CI=true STAGE_PROVISION_ENABLED=true STAGE_PROVISION_APPROVED_SHA="$DEPLOY_SHA" \
|
||||
python3 scripts/provision-stage-runtime.py --uid 1000 --gid 1000 \
|
||||
--snapshot-db "$REVIEWED_STATE_DB" --profile default \
|
||||
--snapshot-name "$UNIQUE_CI_CAPTURE_ID"
|
||||
```
|
||||
|
||||
SQLite online `Connection.backup()` reads committed WAL frames into memory (never
|
||||
`cp state.db`, never `immutable=1`). A 30-second callback deadline bounds busy
|
||||
backup. Only explicit source/time/token/cost columns from `sessions` are projected.
|
||||
Private session IDs become capture-local ordinal IDs; sources use an enum; no
|
||||
messages, titles, prompts, user/chat IDs, paths, URLs, model config, credentials,
|
||||
config.yaml, auth.json, .env, cron commands, memory or skills are exported. Unknown
|
||||
schema/nonnumeric metadata fails. One profile per immutable capture; there is no
|
||||
multi-DB atomicity claim. A source DB may be large: backup is memory-bound, so size
|
||||
and host resources need operator review before a real capture.
|
||||
|
||||
Output directory is new/immutable (0500, 0400 files), never overwritten:
|
||||
`inventory.json`, exact three-field `snapshot-manifest.json` and `export-report.json`.
|
||||
Manifest `capturedAt` is measured immediately after successful backup, not startup,
|
||||
mtime or an example. Report records actual projected row count, inventory digest,
|
||||
method/exclusions; it is not a signature or proof of source authenticity. No live
|
||||
capture was performed in this change. Never reuse fixture manifests as evidence.
|
||||
|
||||
Projected HTTP readers never consult gateway config, state DB or cron files:
|
||||
model/provider are explicit `unknown`, context length is a placeholder zero,
|
||||
cron arrays empty mean **not captured**, session activity false is a placeholder,
|
||||
profile inventory doesn't establish live process availability. Status retains
|
||||
`liveProcess:unknown`. Usage days are relative to actual capture time. Snapshot
|
||||
fresh/stale provenance from the existing adapter remains mandatory. No real LLM
|
||||
pilot readiness follows from this inventory responding 200.
|
||||
|
||||
## Exact parent compose/application wiring
|
||||
|
||||
`infra/hermes-runtime/compose.stage-provision.yml` is an opt-in merge fragment,
|
||||
NOT called by the existing deploy script or ci-apply.sh. Parent must include it
|
||||
in **every** Stage compose command after provisioning, using the existing stable
|
||||
Compose project identity and existing release isolation/volume rules:
|
||||
|
||||
```sh
|
||||
export STAGE_RUNTIME_SERVE_FILE="$PINNED_RELEASE/infra/hermes-runtime/serve.py"
|
||||
export STAGE_RUNTIME_SNAPSHOT="/opt/services/canina/stage-runtime/snapshots/$UNIQUE_CI_CAPTURE_ID"
|
||||
# Only inside approved CI rollout, never manually:
|
||||
# docker compose -p <existing-stage-project> -f <parent-stage-compose> \
|
||||
# -f "$PINNED_RELEASE/infra/hermes-runtime/compose.stage-provision.yml" \
|
||||
# --profile stage-runtime-inventory <parent-approved command>
|
||||
```
|
||||
|
||||
The fragment adds backend `PREPARE_WORKER_ENABLED=true`, fixed-path secrets
|
||||
`/run/secrets/prepare_worker_grants`, `/run/secrets/hermes_runtime_grants`,
|
||||
`hermes_username/password`, and artifact bind at
|
||||
`/var/lib/canina/prepare-artifacts`. It adds a project-scoped **internal** network
|
||||
between backend and inventory only, alias `canina-hermes-inventory` (not the live
|
||||
`canina-hermes`). No host port, Docker socket or live gateway volume. Inventory is
|
||||
read-only, nonroot, no capabilities, restricted tmpfs and pinned image, mounts only
|
||||
its immutable projected export and script. `create_host_path:false` fails on missing
|
||||
exports/storage. Original compose.readonly.yml/ci-apply.sh remain legacy review-only;
|
||||
do not combine those with this provisioning fragment.
|
||||
|
||||
AppModule must keep AuthModule/JwtStrategy, import
|
||||
`RuntimeReadModule.registerFromFile('/run/secrets/hermes_runtime_grants')` for reads,
|
||||
and spread `...registerPrepareWorker()` for the opt-in worker transport (verify
|
||||
existing AppModule before adding duplicates). The latter defaults to no module
|
||||
unless exact env `true`; enabling compose alone cannot add missing imports. Routes
|
||||
remain service-authenticated. Artifact base is fixed to
|
||||
`https://stageapi.canina.ir/api/internal/prepare-worker/artifacts`; parent must verify
|
||||
its actual global `/api` prefix/proxy/authenticated retrieval after CI deployment.
|
||||
No URL here is asserted externally reachable by disposable tests.
|
||||
|
||||
Parent still must implement/review a bounded one-shot real LLM executor separately;
|
||||
this commit intentionally adds neither model/provider secrets nor automatic polling.
|
||||
After CI rollout verify backend UID/secret readability by names only, deny-all reads,
|
||||
worker unauth denial, snapshot provenance and authenticated artifact digest readback
|
||||
before a separately authorized task. Do not call RELEASE_AUTHORIZE.
|
||||
|
||||
## Executed disposable validation
|
||||
|
||||
Pinned Hermes image, `--network none`, repository mounted read-only; private
|
||||
TemporaryDirectory fixtures only. RED observed missing provisioner, missing exporter,
|
||||
wrong projected profile and acceptance of malformed credential; GREEN: four
|
||||
provision/export/security/CI-guard unittest cases; projected HTTP auth/profile/session/
|
||||
wrong-profile/model/cron assertions; existing exact-image HTTP acceptance, TCP serve
|
||||
mutation denial and authenticated WebSocket 1008 denial. Compose merged config
|
||||
`--quiet` passed without applying it. An initial test mount mismatch was corrected
|
||||
(`/source` for repo-relative tests, `/contract` for legacy tests). No application
|
||||
backend code changed; full backend suites not rerun. No host credentials, artifact
|
||||
storage, snapshots, DB users, services or networks were provisioned live.
|
||||
@@ -0,0 +1,44 @@
|
||||
# Temporary Stage editorial reviewer (disabled by default)
|
||||
|
||||
Authority: repository write/CI-dispatch permission plus the existing authenticated,
|
||||
pinned Stage deployment SSH boundary. This is a narrowly scoped seed operation,
|
||||
not an API-key actor, owner JWT, or a public bootstrap endpoint. The destructive
|
||||
legacy seed is not used. `AdminService` shares its normal hashing/persistence and
|
||||
relational cleanup implementation with the internal command; normal user mutation
|
||||
role checks remain unchanged. The canonical default administrator is untouched.
|
||||
|
||||
## Activation after independent review
|
||||
|
||||
1. Promote this commit through the normal Git/CI Stage deployment. Do not run the
|
||||
seed command against an old image: the embedded immutable SHA must match.
|
||||
Apply the additive migration through the existing migration deployment step.
|
||||
2. Dispatch **Owner authorized Stage test principal** on develop with `approval`
|
||||
exactly `owner-authorized-stage-editorial`, unique `session` such as
|
||||
`editorial-20261024-a`, `ttl` explicitly 600 (maximum 3600), and `action=open`.
|
||||
The workflow uses existing DEPLOY_KEY / pinned DEPLOY_KNOWN_HOSTS only.
|
||||
3. CI reports only `/app/private-stage-test/<session>.json` inside
|
||||
`canino_backend_stage`. This mode-0600 file in a mode-0700 directory contains
|
||||
the process-generated password and real persisted-account login tokens.
|
||||
Consume it only from an approved in-container CI HTTP process; never print,
|
||||
download, publish as an artifact, or type it into a browser. No owner secret is
|
||||
needed. Audit records contain events, session and SHA, never credentials.
|
||||
4. Use this independent reviewer for Gate1 only; the proposer/PMO must be a
|
||||
distinct actor. Existing self-review checks are not changed. This session does
|
||||
NOT authorize Gate2, publication, release, general admin APIs, worker identity
|
||||
replacement, or budget increases. Approve a separate explicit bounded test
|
||||
budget before running inference; unknown prior reservations remain retained.
|
||||
5. Dispatch the same workflow/session/ttl with `action=close` immediately after
|
||||
tests. This revokes persisted authentication BEFORE relational deletion and
|
||||
removes the private credential file. Close is idempotent when absent.
|
||||
|
||||
A durable root-owned host cleanup journal and boot/periodic systemd retry worker must be provisioned before opening a session. Cleanup follows the current Stage artifact but retains the original exact session and generation fence; persisted expiry cannot be extended. See [cleanup verification and promotion prerequisites](stage-principal-cleanup-verification.md). No live host services are changed by review tests.
|
||||
|
||||
## Verification
|
||||
|
||||
Unit guards and existing independent self-review/role tests run with Jest.
|
||||
`stage-test-principal.integration.spec.ts` is opt-in via
|
||||
`STAGE_PRINCIPAL_DISPOSABLE_TEST=true` and requires a database URL ending in
|
||||
`/principal_disposable`; use a new isolated Postgres and Redis, then remove both.
|
||||
It verifies real account persistence/hash, signed access/refresh login tokens,
|
||||
collision refusal, nonrenewing retries, request scope, expiry, deletion/revocation.
|
||||
Never run it against Stage or Production.
|
||||
@@ -7,7 +7,10 @@
|
||||
"dev": "vite --port 3400 --host 127.0.0.1",
|
||||
"build": "vite build",
|
||||
"lint": "eslint .",
|
||||
"preview": "vite preview"
|
||||
"preview": "vite preview",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tanstack/react-query": "^5.101.0",
|
||||
@@ -42,4 +45,4 @@
|
||||
"typescript-eslint": "^8.59.2",
|
||||
"vitest": "^4.1.11"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -109,16 +109,7 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side
|
||||
items: [
|
||||
{ icon: LayoutDashboard, label: 'نمای کلی داشبورد', path: '/' },
|
||||
{ icon: TrendingUp, label: 'گزارشات و تحلیل فروش', path: '/reports' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'governance',
|
||||
title: 'حاکمیت، تاییدات و وظایف',
|
||||
icon: CheckSquare,
|
||||
items: [
|
||||
{ icon: CheckSquare, label: 'کارتابل تاییدات مدیریت', path: '/approvals' },
|
||||
{ icon: Briefcase, label: 'وظایف دپارتمانها و ایجنتها', path: '/tasks' },
|
||||
{ icon: History, label: 'تاریخچه تغییرات دیتابیس (Audit)', path: '/history' },
|
||||
{ icon: MessageSquare, label: 'تحلیل مشاوره سایت', path: '/settings/smart-chat' },
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -156,6 +147,7 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side
|
||||
{ icon: Package, label: 'لیست محصولات', path: '/products' },
|
||||
{ icon: Star, label: 'نظرات و امتیازات', path: '/reviews' },
|
||||
{ icon: FolderTree, label: 'دستهبندیهای تخصصی', path: '/categories' },
|
||||
{ icon: Activity, label: 'علائم بالینی و درمانی', path: '/symptoms' },
|
||||
{ icon: Tag, label: 'کدهای تخفیف', path: '/coupons' },
|
||||
{ icon: Sparkles, label: 'مشاور هوشمند بالینی', path: '/smart-advisor' },
|
||||
{ icon: FileText, label: 'نسخههای دریافتی', path: '/prescriptions' },
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
import React from 'react';
|
||||
import { HelpCircle, Plus, Trash2 } from 'lucide-react';
|
||||
import Button from '../ui/Button';
|
||||
|
||||
interface ProductFaqTabProps {
|
||||
activeTab: string;
|
||||
formData: any;
|
||||
setFormData: React.Dispatch<React.SetStateAction<any>>;
|
||||
}
|
||||
|
||||
export const ProductFaqTab: React.FC<ProductFaqTabProps> = ({
|
||||
activeTab,
|
||||
formData,
|
||||
setFormData,
|
||||
}) => {
|
||||
return (
|
||||
<div className={activeTab === 'faq' ? 'block space-y-5' : 'hidden'}>
|
||||
{/* Top FAQ Controls */}
|
||||
<div className="bg-white p-5 rounded-2xl border border-gray-200 shadow-sm space-y-4">
|
||||
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 border-b pb-4">
|
||||
<div>
|
||||
<h4 className="text-sm font-black text-gray-800 flex items-center gap-2">
|
||||
<HelpCircle className="w-4 h-4 text-purple-600" />
|
||||
<span>بخش پرسش و پاسخهای متداول محصول (Product FAQs)</span>
|
||||
</h4>
|
||||
<p className="text-xs text-gray-500 mt-0.5">مدیریت آکاردئون پرسشهای متداول در صفحه کالا و ثبت خودکار در سئوی گوگل (FAQPage Schema)</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
<label className="relative inline-flex items-center cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="sr-only peer"
|
||||
checked={formData.showFaqs}
|
||||
onChange={(e) => setFormData({ ...formData, showFaqs: e.target.checked })}
|
||||
/>
|
||||
<div className="w-11 h-6 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-purple-600"></div>
|
||||
</label>
|
||||
<span className="text-xs font-bold text-gray-700">
|
||||
{formData.showFaqs ? 'بخش FAQ فعال است' : 'بخش FAQ غیرفعال است'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between flex-wrap gap-2 pt-1">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
startIcon={Plus}
|
||||
onClick={() => {
|
||||
setFormData({
|
||||
...formData,
|
||||
faqs: [...(formData.faqs || []), { question: '', answer: '' }]
|
||||
});
|
||||
}}
|
||||
className="border-purple-200 text-purple-700 hover:bg-purple-50 text-xs font-bold"
|
||||
>
|
||||
افزودن سوال جدید
|
||||
</Button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
const defaultFaqs = [
|
||||
{ question: `آیا مصرف ${formData.nameFa || 'این محصول'} برای تولهها یا بچهگربهها مجاز است؟`, answer: 'بله، مطابق دوز اعلامشده روی قوطی و بر اساس وزن دقیق حیوان قابل مصرف است.' },
|
||||
{ question: 'دوره درمان یا مصرف استاندارد چقدر است؟', answer: 'معمولاً دورههای درمانی بین ۴ الی ۶ هفته توصیه میشود تا اثربخشی فیزیولوژیک کامل حاصل شود.' },
|
||||
{ question: 'آیا با سایر داروها یا غذاهای خشک تداخل دارد؟', answer: 'خیر، ترکیبات ارگانیک کنینا فاقد عوارض دارویی تداخلی با رژیمهای غذایی خشک و مرطوب استاندارد هستند.' }
|
||||
];
|
||||
setFormData({
|
||||
...formData,
|
||||
faqs: [...(formData.faqs || []), ...defaultFaqs]
|
||||
});
|
||||
}}
|
||||
className="text-xs text-purple-600 hover:text-purple-800 font-bold px-3 py-1.5 rounded-lg hover:bg-purple-50 transition-colors"
|
||||
>
|
||||
+ درج سوالات پیشنهادی هوشمند
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* FAQs List */}
|
||||
<div className="space-y-4">
|
||||
{(!formData.faqs || formData.faqs.length === 0) ? (
|
||||
<div className="bg-white p-8 rounded-2xl border border-dashed border-gray-200 text-center space-y-2">
|
||||
<HelpCircle className="w-8 h-8 text-gray-300 mx-auto" />
|
||||
<p className="text-xs font-bold text-gray-500">هیچ پرسش و پاسخی برای این محصول تعریف نشده است.</p>
|
||||
<p className="text-[11px] text-gray-400">با کلیک روی دکمه «افزودن سوال جدید» یا «درج سوالات پیشنهادی»، متداولترین پرسشهای خریداران را ثبت کنید.</p>
|
||||
</div>
|
||||
) : (
|
||||
formData.faqs.map((faq: any, index: number) => (
|
||||
<div key={index} className="bg-white p-5 rounded-2xl border border-gray-200 shadow-xs space-y-3 relative group">
|
||||
<div className="flex items-center justify-between gap-3 border-b pb-2">
|
||||
<span className="text-xs font-black text-purple-700 bg-purple-50 px-2.5 py-1 rounded-lg">
|
||||
پرسش شماره {index + 1}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
const newFaqs = [...formData.faqs];
|
||||
newFaqs.splice(index, 1);
|
||||
setFormData({ ...formData, faqs: newFaqs });
|
||||
}}
|
||||
className="p-1.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors"
|
||||
title="حذف این پرسش"
|
||||
>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<label className="text-xs font-bold text-gray-700">عنوان پرسش *</label>
|
||||
<input
|
||||
type="text"
|
||||
value={faq.question}
|
||||
onChange={(e) => {
|
||||
const newFaqs = [...formData.faqs];
|
||||
newFaqs[index].question = e.target.value;
|
||||
setFormData({ ...formData, faqs: newFaqs });
|
||||
}}
|
||||
placeholder="مثال: نحوه مصرف همراه با غذاست یا با معده خالی؟"
|
||||
className="w-full px-4 py-2.5 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-xs font-bold"
|
||||
dir="rtl"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<label className="text-xs font-bold text-gray-700">پاسخ تشریحی و تخصصی *</label>
|
||||
<textarea
|
||||
rows={2}
|
||||
value={faq.answer}
|
||||
onChange={(e) => {
|
||||
const newFaqs = [...formData.faqs];
|
||||
newFaqs[index].answer = e.target.value;
|
||||
setFormData({ ...formData, faqs: newFaqs });
|
||||
}}
|
||||
placeholder="پاسخ دقیق، علمی و راهنمای مصرف را اینجا بنویسید..."
|
||||
className="w-full px-4 py-2.5 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-xs font-medium leading-relaxed"
|
||||
dir="rtl"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
Loaded 100 of 400 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user