Compare commits
No commits in common. "main" and "preparation_prod" have entirely different histories.
main
...
preparatio
@ -1,2 +0,0 @@
|
|||||||
# All jobs use the existing ubuntu-latest runner label.
|
|
||||||
{}
|
|
||||||
@ -1,44 +0,0 @@
|
|||||||
name: Notify security gate failure
|
|
||||||
description: Posts a Discord alert when the Security gate fails and stops the pipeline.
|
|
||||||
inputs:
|
|
||||||
webhook-url:
|
|
||||||
description: Discord webhook URL.
|
|
||||||
required: true
|
|
||||||
pipeline:
|
|
||||||
description: Human-readable pipeline name shown in the alert.
|
|
||||||
required: true
|
|
||||||
runs:
|
|
||||||
using: composite
|
|
||||||
steps:
|
|
||||||
- name: Discord
|
|
||||||
shell: bash
|
|
||||||
env:
|
|
||||||
WEBHOOK_URL: ${{ inputs.webhook-url }}
|
|
||||||
PIPELINE: ${{ inputs.pipeline }}
|
|
||||||
REF_NAME: ${{ github.ref_name }}
|
|
||||||
ACTOR: ${{ github.actor }}
|
|
||||||
SHA: ${{ github.sha }}
|
|
||||||
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
|
|
||||||
run: |
|
|
||||||
# Payload built with json.dumps: branch or author names cannot break the JSON.
|
|
||||||
payload=$(python3 - <<'PY'
|
|
||||||
import json, os
|
|
||||||
print(json.dumps({
|
|
||||||
"content": "@here Security gate en échec — pipeline arrêté",
|
|
||||||
"embeds": [{
|
|
||||||
"title": f"🔒 Security gate en échec — {os.environ['PIPELINE']}",
|
|
||||||
"description": "Aucun lint, test, build ni déploiement n'a été lancé. Consultez l'artefact `security-reports`.",
|
|
||||||
"color": 15158332,
|
|
||||||
"fields": [
|
|
||||||
{"name": "Branche", "value": f"`{os.environ['REF_NAME']}`", "inline": True},
|
|
||||||
{"name": "Auteur", "value": os.environ["ACTOR"], "inline": True},
|
|
||||||
{"name": "Commit", "value": f"`{os.environ['SHA'][:7]}`", "inline": True},
|
|
||||||
{"name": "Workflow", "value": f"[Voir le run]({os.environ['RUN_URL']})", "inline": False},
|
|
||||||
],
|
|
||||||
"footer": {"text": f"Xpeditis CI/CD • {os.environ['PIPELINE']}"},
|
|
||||||
}],
|
|
||||||
}))
|
|
||||||
PY
|
|
||||||
)
|
|
||||||
curl -fsS --max-time 15 -H "Content-Type: application/json" -d "$payload" "$WEBHOOK_URL" \
|
|
||||||
|| echo "::warning::Notification Discord non envoyée."
|
|
||||||
@ -1,31 +0,0 @@
|
|||||||
name: Security gate
|
|
||||||
description: Dependency, secrets, infrastructure and workflow checks for Gitea 1.22.
|
|
||||||
runs:
|
|
||||||
using: composite
|
|
||||||
steps:
|
|
||||||
- uses: ./.gitea/actions/setup-node
|
|
||||||
- name: Install Trivy
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
trivy_bin=$(bash scripts/ci/install-tool.sh trivy)
|
|
||||||
"$trivy_bin" --version
|
|
||||||
- name: Validate workflows and deployment checks
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
actionlint_bin=$(bash scripts/ci/install-tool.sh actionlint)
|
|
||||||
ACTIONLINT_BIN="$actionlint_bin" bash scripts/ci/validate-workflows.sh
|
|
||||||
- name: Audit dependencies, secrets and infrastructure
|
|
||||||
shell: bash
|
|
||||||
run: bash scripts/ci/security-audit.sh
|
|
||||||
- name: Show security results
|
|
||||||
if: always()
|
|
||||||
shell: bash
|
|
||||||
run: python3 scripts/ci/summarize-security.py
|
|
||||||
- name: Save security reports on Gitea
|
|
||||||
if: always()
|
|
||||||
uses: https://github.com/actions/upload-artifact@ff15f0306b3f739f7b6fd43fb5d26cd321bd4de5 # v3, Gitea artifact protocol
|
|
||||||
with:
|
|
||||||
name: security-reports
|
|
||||||
path: ${{ runner.temp }}/security-reports/*.json
|
|
||||||
retention-days: 7
|
|
||||||
if-no-files-found: error
|
|
||||||
@ -1,11 +0,0 @@
|
|||||||
name: Install and activate Node 22
|
|
||||||
description: Set up Node and verify the executable selected by the Gitea runner.
|
|
||||||
runs:
|
|
||||||
using: composite
|
|
||||||
steps:
|
|
||||||
- uses: https://github.com/actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
|
||||||
with:
|
|
||||||
node-version: '22'
|
|
||||||
- name: Activate and verify Node 22
|
|
||||||
shell: bash
|
|
||||||
run: bash scripts/ci/activate-node.sh
|
|
||||||
@ -1,9 +0,0 @@
|
|||||||
name: Install verified Trivy
|
|
||||||
description: Install a pinned native scanner with a checked SHA256.
|
|
||||||
runs:
|
|
||||||
using: composite
|
|
||||||
steps:
|
|
||||||
- shell: bash
|
|
||||||
run: |
|
|
||||||
trivy_bin=$(bash scripts/ci/install-tool.sh trivy)
|
|
||||||
"$trivy_bin" --version
|
|
||||||
@ -1,414 +0,0 @@
|
|||||||
name: CD Production
|
|
||||||
|
|
||||||
# Pipeline de production — Hetzner k3s (infra/prod/).
|
|
||||||
#
|
|
||||||
# Enchaînement : sécurité → qualité → vérification → promotion/rebuild → déploiement → contrôle
|
|
||||||
#
|
|
||||||
# TROIS RÈGLES STRUCTURANTES
|
|
||||||
#
|
|
||||||
# 1. Le BACKEND est PROMU depuis la preprod, jamais reconstruit.
|
|
||||||
# Promouvoir garantit que le binaire déployé en production est exactement
|
|
||||||
# celui qui a passé la chaîne de preprod (lint, tests unitaires, tests
|
|
||||||
# d'intégration, build). Un rebuild casserait cette garantie.
|
|
||||||
#
|
|
||||||
# 2. Le FRONTEND est RECONSTRUIT pour la production.
|
|
||||||
# next.config.js fige NEXT_PUBLIC_API_URL au moment du build. Promouvoir
|
|
||||||
# l'image de preprod livrerait une application qui appelle
|
|
||||||
# api.preprod.xpeditis.com en production. C'est la raison pour laquelle ce
|
|
||||||
# workflow ne peut pas se contenter de re-taguer.
|
|
||||||
#
|
|
||||||
# 3. Le déploiement passe par SSH, pas par l'API Kubernetes.
|
|
||||||
# L'API k3s (6443) n'est ouverte qu'aux IP d'administration. Les runners
|
|
||||||
# Gitea n'ont pas d'IP fixe : le job ouvre le port 22 pour la seule IP du
|
|
||||||
# runner via un firewall Hetzner dédié, puis le referme systématiquement.
|
|
||||||
#
|
|
||||||
# Secrets, runners et limites Gitea : voir docs/CI-CD-SECURITY.md
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches: [main]
|
|
||||||
|
|
||||||
env:
|
|
||||||
REGISTRY: rg.fr-par.scw.cloud/weworkstudio
|
|
||||||
K8S_NAMESPACE: xpeditis-prod
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
security:
|
|
||||||
name: Security gate
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
- uses: ./.gitea/actions/setup-node
|
|
||||||
- name: Install Trivy
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
trivy_bin=$(bash scripts/ci/install-tool.sh trivy)
|
|
||||||
"$trivy_bin" --version
|
|
||||||
- name: Validate workflows and deployment checks
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
actionlint_bin=$(bash scripts/ci/install-tool.sh actionlint)
|
|
||||||
ACTIONLINT_BIN="$actionlint_bin" bash scripts/ci/validate-workflows.sh
|
|
||||||
- name: Audit dependencies, secrets and infrastructure
|
|
||||||
shell: bash
|
|
||||||
run: bash scripts/ci/security-audit.sh
|
|
||||||
- name: Show security results
|
|
||||||
if: always()
|
|
||||||
shell: bash
|
|
||||||
run: python3 scripts/ci/summarize-security.py
|
|
||||||
- name: Save security reports on Gitea
|
|
||||||
if: always()
|
|
||||||
uses: https://github.com/actions/upload-artifact@ff15f0306b3f739f7b6fd43fb5d26cd321bd4de5 # v3, Gitea artifact protocol
|
|
||||||
with:
|
|
||||||
name: security-reports
|
|
||||||
path: ${{ runner.temp }}/security-reports/*.json
|
|
||||||
retention-days: 7
|
|
||||||
if-no-files-found: error
|
|
||||||
- name: Notify Discord
|
|
||||||
if: failure()
|
|
||||||
uses: ./.gitea/actions/notify-security-failure
|
|
||||||
with:
|
|
||||||
webhook-url: ${{ secrets.DISCORD_WEBHOOK_URL }}
|
|
||||||
pipeline: Production
|
|
||||||
|
|
||||||
# ═══ 1. Qualité ══════════════════════════════════════════════════════════
|
|
||||||
backend-quality:
|
|
||||||
name: Backend — Lint
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: security
|
|
||||||
defaults:
|
|
||||||
run:
|
|
||||||
working-directory: apps/backend
|
|
||||||
steps:
|
|
||||||
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
- uses: ./.gitea/actions/setup-node
|
|
||||||
- run: npm ci --legacy-peer-deps
|
|
||||||
- run: npm run lint -- --no-fix
|
|
||||||
|
|
||||||
frontend-quality:
|
|
||||||
name: Frontend — Lint & Type-check
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: security
|
|
||||||
defaults:
|
|
||||||
run:
|
|
||||||
working-directory: apps/frontend
|
|
||||||
steps:
|
|
||||||
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
- uses: ./.gitea/actions/setup-node
|
|
||||||
- run: npm ci --legacy-peer-deps
|
|
||||||
- run: npm run lint
|
|
||||||
- run: npm run type-check
|
|
||||||
|
|
||||||
backend-tests:
|
|
||||||
name: Backend — Tests unitaires
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: backend-quality
|
|
||||||
defaults:
|
|
||||||
run:
|
|
||||||
working-directory: apps/backend
|
|
||||||
steps:
|
|
||||||
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
- uses: ./.gitea/actions/setup-node
|
|
||||||
- run: npm ci --legacy-peer-deps
|
|
||||||
- run: npm test -- --ci --runInBand
|
|
||||||
|
|
||||||
frontend-tests:
|
|
||||||
name: Frontend — Tests unitaires
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: frontend-quality
|
|
||||||
defaults:
|
|
||||||
run:
|
|
||||||
working-directory: apps/frontend
|
|
||||||
steps:
|
|
||||||
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
- uses: ./.gitea/actions/setup-node
|
|
||||||
- run: npm ci --legacy-peer-deps
|
|
||||||
- run: npm test -- --ci --runInBand
|
|
||||||
|
|
||||||
# ═══ 2. Vérification de la provenance ════════════════════════════════════
|
|
||||||
# Exige un pipeline preprod réussi ET un arbre Git identique au code testé ici.
|
|
||||||
verify-image:
|
|
||||||
name: Vérifier l'image de preprod
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: [security, backend-tests, frontend-tests]
|
|
||||||
outputs:
|
|
||||||
sha: ${{ steps.sha.outputs.short }}
|
|
||||||
backend_digest: ${{ steps.sha.outputs.backend_digest }}
|
|
||||||
log_exporter_digest: ${{ steps.sha.outputs.log_exporter_digest }}
|
|
||||||
steps:
|
|
||||||
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
|
||||||
with:
|
|
||||||
fetch-depth: 0
|
|
||||||
persist-credentials: false
|
|
||||||
- uses: https://github.com/docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3
|
|
||||||
- uses: https://github.com/docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3
|
|
||||||
with:
|
|
||||||
registry: ${{ env.REGISTRY }}
|
|
||||||
username: nologin
|
|
||||||
password: ${{ secrets.REGISTRY_TOKEN }}
|
|
||||||
- name: Resolve validated preprod release
|
|
||||||
id: sha
|
|
||||||
run: bash scripts/ci/resolve-release.sh
|
|
||||||
|
|
||||||
# ═══ 3b. Reconstruction du frontend avec les URLs de production ══════════
|
|
||||||
build-frontend:
|
|
||||||
name: Reconstruire le frontend (URLs de production)
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: verify-image
|
|
||||||
outputs:
|
|
||||||
digest: ${{ steps.build.outputs.digest }}
|
|
||||||
steps:
|
|
||||||
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
# Cet arbre Git est identique à celui de la release preprod vérifiée.
|
|
||||||
ref: ${{ github.sha }}
|
|
||||||
- uses: https://github.com/docker/setup-qemu-action@c7c53464625b32c7a7e944ae62b3e17d2b600130 # v3
|
|
||||||
with:
|
|
||||||
platforms: amd64,arm64
|
|
||||||
cache-image: false
|
|
||||||
- uses: https://github.com/docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3
|
|
||||||
- uses: https://github.com/docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3
|
|
||||||
with:
|
|
||||||
registry: ${{ env.REGISTRY }}
|
|
||||||
username: nologin
|
|
||||||
password: ${{ secrets.REGISTRY_TOKEN }}
|
|
||||||
- id: build
|
|
||||||
uses: https://github.com/docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6
|
|
||||||
with:
|
|
||||||
context: ./apps/frontend
|
|
||||||
file: ./apps/frontend/Dockerfile
|
|
||||||
push: true
|
|
||||||
platforms: linux/amd64
|
|
||||||
tags: |
|
|
||||||
${{ env.REGISTRY }}/xpeditis-frontend:candidate-prod-${{ github.sha }}-${{ github.run_id }}
|
|
||||||
cache-from: type=registry,ref=${{ env.REGISTRY }}/xpeditis-frontend:buildcache-prod
|
|
||||||
cache-to: type=registry,ref=${{ env.REGISTRY }}/xpeditis-frontend:buildcache-prod,mode=max
|
|
||||||
build-args: |
|
|
||||||
NEXT_PUBLIC_API_URL=${{ secrets.NEXT_PUBLIC_API_URL_PROD }}
|
|
||||||
NEXT_PUBLIC_APP_URL=${{ secrets.NEXT_PUBLIC_APP_URL_PROD }}
|
|
||||||
|
|
||||||
- name: Contrôle — l'URL de preprod ne doit pas figurer dans le bundle
|
|
||||||
run: |
|
|
||||||
IMAGE="${{ env.REGISTRY }}/xpeditis-frontend@${{ steps.build.outputs.digest }}"
|
|
||||||
CID=$(docker create --platform linux/amd64 "$IMAGE")
|
|
||||||
trap 'docker rm "$CID" >/dev/null' EXIT
|
|
||||||
docker cp "$CID:/app/.next" /tmp/next-check
|
|
||||||
test -d /tmp/next-check
|
|
||||||
trap - EXIT
|
|
||||||
docker rm "$CID" >/dev/null
|
|
||||||
if grep -rq "api.preprod.xpeditis.com" /tmp/next-check 2>/dev/null; then
|
|
||||||
echo "::error::L'URL de preprod est figée dans le bundle de production."
|
|
||||||
echo "Vérifiez le secret NEXT_PUBLIC_API_URL_PROD."
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
echo "Aucune URL de preprod dans le bundle."
|
|
||||||
|
|
||||||
image-security:
|
|
||||||
name: Image security (${{ matrix.service }}, ${{ matrix.arch }})
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: [verify-image, build-frontend]
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
|
||||||
service: [backend, frontend, log-exporter]
|
|
||||||
arch: [amd64]
|
|
||||||
steps:
|
|
||||||
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
- uses: ./.gitea/actions/setup-trivy
|
|
||||||
- uses: https://github.com/docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3
|
|
||||||
with:
|
|
||||||
registry: ${{ env.REGISTRY }}
|
|
||||||
username: nologin
|
|
||||||
password: ${{ secrets.REGISTRY_TOKEN }}
|
|
||||||
- name: Scan the exact image before deployment
|
|
||||||
env:
|
|
||||||
IMAGE: ${{ env.REGISTRY }}/xpeditis-${{ matrix.service }}@${{ matrix.service == 'frontend' && needs.build-frontend.outputs.digest || (matrix.service == 'backend' && needs.verify-image.outputs.backend_digest || needs.verify-image.outputs.log_exporter_digest) }}
|
|
||||||
PLATFORM: linux/${{ matrix.arch }}
|
|
||||||
run: |
|
|
||||||
trivy image --platform "$PLATFORM" --scanners vuln --severity HIGH,CRITICAL \
|
|
||||||
--ignore-unfixed=false --exit-code 1 --timeout 15m --no-progress --format json \
|
|
||||||
--output "$RUNNER_TEMP/image-security.json" "$IMAGE"
|
|
||||||
- name: Show image scan results
|
|
||||||
if: always()
|
|
||||||
run: python3 scripts/ci/summarize-image-security.py
|
|
||||||
- name: Save image report
|
|
||||||
if: always()
|
|
||||||
uses: https://github.com/actions/upload-artifact@ff15f0306b3f739f7b6fd43fb5d26cd321bd4de5 # v3, Gitea artifact protocol
|
|
||||||
with:
|
|
||||||
name: image-security-${{ matrix.service }}-${{ matrix.arch }}
|
|
||||||
path: ${{ runner.temp }}/image-security.json
|
|
||||||
retention-days: 14
|
|
||||||
if-no-files-found: error
|
|
||||||
|
|
||||||
# ═══ 4. Déploiement ══════════════════════════════════════════════════════
|
|
||||||
deploy:
|
|
||||||
name: Déployer en production
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: [verify-image, build-frontend, image-security]
|
|
||||||
steps:
|
|
||||||
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
|
|
||||||
- uses: https://github.com/docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3
|
|
||||||
- uses: https://github.com/docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3
|
|
||||||
with:
|
|
||||||
registry: ${{ env.REGISTRY }}
|
|
||||||
username: nologin
|
|
||||||
password: ${{ secrets.REGISTRY_TOKEN }}
|
|
||||||
- name: Publish scanned production images
|
|
||||||
env:
|
|
||||||
IMAGE_SHA: ${{ needs.verify-image.outputs.sha }}
|
|
||||||
BACKEND_DIGEST: ${{ needs.verify-image.outputs.backend_digest }}
|
|
||||||
FRONTEND_DIGEST: ${{ needs.build-frontend.outputs.digest }}
|
|
||||||
LOG_EXPORTER_DIGEST: ${{ needs.verify-image.outputs.log_exporter_digest }}
|
|
||||||
run: |
|
|
||||||
for service in backend frontend log-exporter; do
|
|
||||||
case "$service" in
|
|
||||||
backend) digest="$BACKEND_DIGEST" ;;
|
|
||||||
frontend) digest="$FRONTEND_DIGEST" ;;
|
|
||||||
log-exporter) digest="$LOG_EXPORTER_DIGEST" ;;
|
|
||||||
esac
|
|
||||||
docker buildx imagetools create \
|
|
||||||
--tag "$REGISTRY/xpeditis-$service:prod-$IMAGE_SHA" \
|
|
||||||
--tag "$REGISTRY/xpeditis-$service:latest" \
|
|
||||||
"$REGISTRY/xpeditis-$service@$digest"
|
|
||||||
done
|
|
||||||
|
|
||||||
- name: Installer le client Hetzner
|
|
||||||
run: |
|
|
||||||
hcloud_bin=$(bash scripts/ci/install-tool.sh hcloud)
|
|
||||||
"$hcloud_bin" version
|
|
||||||
|
|
||||||
- name: Ouvrir le port 22 pour l'IP de ce runner
|
|
||||||
env:
|
|
||||||
HCLOUD_TOKEN: ${{ secrets.HCLOUD_TOKEN_CICD }}
|
|
||||||
run: |
|
|
||||||
RUNNER_IP="$(curl -fsS --max-time 10 https://ifconfig.me)"
|
|
||||||
echo "IP du runner : ${RUNNER_IP}"
|
|
||||||
cat > /tmp/fw-open.json <<JSON
|
|
||||||
[{
|
|
||||||
"direction": "in",
|
|
||||||
"protocol": "tcp",
|
|
||||||
"port": "22",
|
|
||||||
"source_ips": ["${RUNNER_IP}/32"],
|
|
||||||
"description": "Gitea Actions run ${{ github.run_id }}"
|
|
||||||
}]
|
|
||||||
JSON
|
|
||||||
hcloud firewall replace-rules "${{ vars.HCLOUD_CICD_FIREWALL }}" --rules-file /tmp/fw-open.json
|
|
||||||
|
|
||||||
- name: Préparer SSH
|
|
||||||
env:
|
|
||||||
DEPLOY_SSH_KEY: ${{ secrets.PROD_SSH_KEY }}
|
|
||||||
DEPLOY_KNOWN_HOSTS: ${{ secrets.PROD_SSH_KNOWN_HOSTS }}
|
|
||||||
run: |
|
|
||||||
mkdir -p "$RUNNER_TEMP/deploy-ssh" && chmod 700 "$RUNNER_TEMP/deploy-ssh"
|
|
||||||
printf '%s\n' "$DEPLOY_SSH_KEY" > "$RUNNER_TEMP/deploy-ssh/id_ed25519"
|
|
||||||
chmod 600 "$RUNNER_TEMP/deploy-ssh/id_ed25519"
|
|
||||||
# Empreinte épinglée : un détournement DNS ou BGP ne peut pas
|
|
||||||
# rediriger le déploiement vers une machine tierce.
|
|
||||||
printf '%s\n' "$DEPLOY_KNOWN_HOSTS" > "$RUNNER_TEMP/deploy-ssh/known_hosts"
|
|
||||||
chmod 600 "$RUNNER_TEMP/deploy-ssh/known_hosts"
|
|
||||||
|
|
||||||
- name: Synchroniser infra/prod sur le serveur
|
|
||||||
run: |
|
|
||||||
rsync -az --delete \
|
|
||||||
--exclude '.terraform' --exclude '*.tfstate*' --exclude '*.tfvars' \
|
|
||||||
-e "ssh -o StrictHostKeyChecking=yes -o UserKnownHostsFile=\"$RUNNER_TEMP/deploy-ssh/known_hosts\" -i \"$RUNNER_TEMP/deploy-ssh/id_ed25519\"" \
|
|
||||||
infra/prod/ \
|
|
||||||
"${{ secrets.PROD_SSH_USER }}@${{ secrets.PROD_SSH_HOST }}:/opt/xpeditis/infra-prod/"
|
|
||||||
|
|
||||||
- name: Déployer
|
|
||||||
id: deploy
|
|
||||||
run: |
|
|
||||||
SHA="${{ needs.verify-image.outputs.sha }}"
|
|
||||||
ssh -o StrictHostKeyChecking=yes -o UserKnownHostsFile="$RUNNER_TEMP/deploy-ssh/known_hosts" -i "$RUNNER_TEMP/deploy-ssh/id_ed25519" \
|
|
||||||
"${{ secrets.PROD_SSH_USER }}@${{ secrets.PROD_SSH_HOST }}" \
|
|
||||||
"deploy prod-${SHA}"
|
|
||||||
|
|
||||||
- name: Tests de fumée depuis l'extérieur
|
|
||||||
id: smoke
|
|
||||||
env:
|
|
||||||
PROD_API_URL: ${{ vars.PROD_API_URL }}
|
|
||||||
PROD_APP_URL: ${{ vars.PROD_APP_URL }}
|
|
||||||
run: bash infra/prod/scripts/smoke-test.sh
|
|
||||||
|
|
||||||
- name: Retour arrière si le déploiement a échoué
|
|
||||||
if: failure() && (steps.deploy.conclusion == 'failure' || steps.smoke.conclusion == 'failure')
|
|
||||||
run: |
|
|
||||||
ssh -o StrictHostKeyChecking=yes -o UserKnownHostsFile="$RUNNER_TEMP/deploy-ssh/known_hosts" -i "$RUNNER_TEMP/deploy-ssh/id_ed25519" \
|
|
||||||
"${{ secrets.PROD_SSH_USER }}@${{ secrets.PROD_SSH_HOST }}" \
|
|
||||||
"rollback" || true
|
|
||||||
|
|
||||||
- name: Refermer le firewall
|
|
||||||
# `always()` : la fenêtre d'exposition se referme même si le
|
|
||||||
# déploiement a échoué, si le job a été annulé ou s'il a expiré.
|
|
||||||
if: always()
|
|
||||||
env:
|
|
||||||
HCLOUD_TOKEN: ${{ secrets.HCLOUD_TOKEN_CICD }}
|
|
||||||
run: |
|
|
||||||
echo '[]' > /tmp/fw-close.json
|
|
||||||
hcloud firewall replace-rules "${{ vars.HCLOUD_CICD_FIREWALL }}" --rules-file /tmp/fw-close.json
|
|
||||||
echo "Firewall CI refermé."
|
|
||||||
|
|
||||||
- name: Effacer la clé SSH
|
|
||||||
if: always()
|
|
||||||
run: shred -u "$RUNNER_TEMP/deploy-ssh/id_ed25519" 2>/dev/null || rm -f "$RUNNER_TEMP/deploy-ssh/id_ed25519"
|
|
||||||
|
|
||||||
# ═══ 5. Notifications ════════════════════════════════════════════════════
|
|
||||||
notify-success:
|
|
||||||
name: Notifier le succès
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: [verify-image, deploy]
|
|
||||||
if: success()
|
|
||||||
steps:
|
|
||||||
- run: |
|
|
||||||
curl -sf -H "Content-Type: application/json" -d '{
|
|
||||||
"embeds": [{
|
|
||||||
"title": "Production déployée et saine",
|
|
||||||
"color": 3066993,
|
|
||||||
"fields": [
|
|
||||||
{"name": "Auteur", "value": "${{ github.actor }}", "inline": true},
|
|
||||||
{"name": "Version", "value": "`prod-${{ needs.verify-image.outputs.sha }}`", "inline": true},
|
|
||||||
{"name": "Cible", "value": "Hetzner k3s — xpeditis-prod", "inline": false},
|
|
||||||
{"name": "Workflow", "value": "[${{ github.run_id }}](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})", "inline": false}
|
|
||||||
],
|
|
||||||
"footer": {"text": "Xpeditis CI/CD - Production"}
|
|
||||||
}]
|
|
||||||
}' ${{ secrets.DISCORD_WEBHOOK_URL }}
|
|
||||||
|
|
||||||
notify-failure:
|
|
||||||
name: Notifier l'échec
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: [security, backend-quality, frontend-quality, backend-tests, frontend-tests, verify-image, build-frontend, image-security, deploy]
|
|
||||||
# Security gate failures are already reported by the security job itself.
|
|
||||||
if: failure() && needs.security.result != 'failure'
|
|
||||||
steps:
|
|
||||||
- run: |
|
|
||||||
curl -sf -H "Content-Type: application/json" -d '{
|
|
||||||
"content": "@here ECHEC DU PIPELINE DE PRODUCTION",
|
|
||||||
"embeds": [{
|
|
||||||
"title": "Pipeline de production en échec",
|
|
||||||
"description": "Un retour arrière a été tenté si l échec est survenu pendant le déploiement. Vérifiez l état réel avant toute nouvelle tentative.",
|
|
||||||
"color": 15158332,
|
|
||||||
"fields": [
|
|
||||||
{"name": "Auteur", "value": "${{ github.actor }}", "inline": true},
|
|
||||||
{"name": "Workflow", "value": "[${{ github.run_id }}](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})", "inline": false},
|
|
||||||
{"name": "A vérifier", "value": "Le firewall CI est-il bien refermé ? `hcloud firewall describe xpeditis-prod-fw-cicd`", "inline": false}
|
|
||||||
],
|
|
||||||
"footer": {"text": "Xpeditis CI/CD - Production"}
|
|
||||||
}]
|
|
||||||
}' ${{ secrets.DISCORD_WEBHOOK_URL }}
|
|
||||||
@ -1,451 +0,0 @@
|
|||||||
name: CD Preprod
|
|
||||||
|
|
||||||
# Full pipeline triggered on every push to preprod.
|
|
||||||
# Flow: security gate → lint → unit tests → integration tests → docker build → deploy → notify
|
|
||||||
#
|
|
||||||
# Secrets required:
|
|
||||||
# REGISTRY_TOKEN — Scaleway registry (read/write)
|
|
||||||
# NEXT_PUBLIC_API_URL — https://api.preprod.xpeditis.com
|
|
||||||
# NEXT_PUBLIC_APP_URL — https://preprod.xpeditis.com
|
|
||||||
# PORTAINER_WEBHOOK_BACKEND — Portainer webhook (preprod backend)
|
|
||||||
# PORTAINER_WEBHOOK_FRONTEND— Portainer webhook (preprod frontend)
|
|
||||||
# DISCORD_WEBHOOK_URL
|
|
||||||
# Optional health URL overrides (secrets, then repository variables):
|
|
||||||
# PREPROD_BACKEND_URL — defaults to https://api.preprod.xpeditis.com
|
|
||||||
# PREPROD_FRONTEND_URL — defaults to https://app.preprod.xpeditis.com
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches: [preprod]
|
|
||||||
|
|
||||||
env:
|
|
||||||
REGISTRY: rg.fr-par.scw.cloud/weworkstudio
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
security:
|
|
||||||
name: Security gate
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
- uses: ./.gitea/actions/setup-node
|
|
||||||
- name: Install Trivy
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
trivy_bin=$(bash scripts/ci/install-tool.sh trivy)
|
|
||||||
"$trivy_bin" --version
|
|
||||||
- name: Validate workflows and deployment checks
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
actionlint_bin=$(bash scripts/ci/install-tool.sh actionlint)
|
|
||||||
ACTIONLINT_BIN="$actionlint_bin" bash scripts/ci/validate-workflows.sh
|
|
||||||
- name: Audit dependencies, secrets and infrastructure
|
|
||||||
shell: bash
|
|
||||||
run: bash scripts/ci/security-audit.sh
|
|
||||||
- name: Show security results
|
|
||||||
if: always()
|
|
||||||
shell: bash
|
|
||||||
run: python3 scripts/ci/summarize-security.py
|
|
||||||
- name: Save security reports on Gitea
|
|
||||||
if: always()
|
|
||||||
uses: https://github.com/actions/upload-artifact@ff15f0306b3f739f7b6fd43fb5d26cd321bd4de5 # v3, Gitea artifact protocol
|
|
||||||
with:
|
|
||||||
name: security-reports
|
|
||||||
path: ${{ runner.temp }}/security-reports/*.json
|
|
||||||
retention-days: 7
|
|
||||||
if-no-files-found: error
|
|
||||||
- name: Notify Discord
|
|
||||||
if: failure()
|
|
||||||
uses: ./.gitea/actions/notify-security-failure
|
|
||||||
with:
|
|
||||||
webhook-url: ${{ secrets.DISCORD_WEBHOOK_URL }}
|
|
||||||
pipeline: Preprod
|
|
||||||
|
|
||||||
# ── 1. Lint ─────────────────────────────────────────────────────────
|
|
||||||
backend-quality:
|
|
||||||
name: Backend — Lint
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: security
|
|
||||||
defaults:
|
|
||||||
run:
|
|
||||||
working-directory: apps/backend
|
|
||||||
steps:
|
|
||||||
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
- uses: ./.gitea/actions/setup-node
|
|
||||||
- run: npm ci --legacy-peer-deps
|
|
||||||
- run: npm run lint -- --no-fix
|
|
||||||
|
|
||||||
frontend-quality:
|
|
||||||
name: Frontend — Lint & Type-check
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: security
|
|
||||||
defaults:
|
|
||||||
run:
|
|
||||||
working-directory: apps/frontend
|
|
||||||
steps:
|
|
||||||
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
- uses: ./.gitea/actions/setup-node
|
|
||||||
- run: npm ci --legacy-peer-deps
|
|
||||||
- run: npm run lint
|
|
||||||
- run: npm run type-check
|
|
||||||
|
|
||||||
# ── 2. Unit Tests ────────────────────────────────────────────────────
|
|
||||||
backend-tests:
|
|
||||||
name: Backend — Unit Tests
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: backend-quality
|
|
||||||
defaults:
|
|
||||||
run:
|
|
||||||
working-directory: apps/backend
|
|
||||||
steps:
|
|
||||||
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
- uses: ./.gitea/actions/setup-node
|
|
||||||
- run: npm ci --legacy-peer-deps
|
|
||||||
- run: npm test -- --ci --runInBand
|
|
||||||
|
|
||||||
frontend-tests:
|
|
||||||
name: Frontend — Unit Tests
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: frontend-quality
|
|
||||||
defaults:
|
|
||||||
run:
|
|
||||||
working-directory: apps/frontend
|
|
||||||
steps:
|
|
||||||
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
- uses: ./.gitea/actions/setup-node
|
|
||||||
- run: npm ci --legacy-peer-deps
|
|
||||||
- run: npm test -- --ci --runInBand
|
|
||||||
|
|
||||||
# ── 3. Integration Tests ─────────────────────────────────────────────
|
|
||||||
integration-tests:
|
|
||||||
name: Backend — Integration Tests
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: [backend-tests, frontend-tests]
|
|
||||||
defaults:
|
|
||||||
run:
|
|
||||||
working-directory: apps/backend
|
|
||||||
|
|
||||||
services:
|
|
||||||
postgres:
|
|
||||||
image: postgres:15-alpine
|
|
||||||
env:
|
|
||||||
POSTGRES_USER: xpeditis_test
|
|
||||||
POSTGRES_PASSWORD: xpeditis_test_password
|
|
||||||
POSTGRES_DB: xpeditis_test
|
|
||||||
options: >-
|
|
||||||
--health-cmd pg_isready
|
|
||||||
--health-interval 5s
|
|
||||||
--health-timeout 5s
|
|
||||||
--health-retries 10
|
|
||||||
redis:
|
|
||||||
image: redis:7-alpine
|
|
||||||
options: >-
|
|
||||||
--health-cmd "redis-cli ping"
|
|
||||||
--health-interval 5s
|
|
||||||
--health-timeout 5s
|
|
||||||
--health-retries 10
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
- uses: ./.gitea/actions/setup-node
|
|
||||||
- run: npm ci --legacy-peer-deps
|
|
||||||
- name: Run integration tests
|
|
||||||
env:
|
|
||||||
NODE_ENV: test
|
|
||||||
TEST_DB_HOST: postgres
|
|
||||||
TEST_DB_PORT: 5432
|
|
||||||
TEST_DB_USER: xpeditis_test
|
|
||||||
TEST_DB_PASSWORD: xpeditis_test_password
|
|
||||||
TEST_DB_NAME: xpeditis_test
|
|
||||||
DATABASE_HOST: postgres
|
|
||||||
DATABASE_PORT: 5432
|
|
||||||
DATABASE_USER: xpeditis_test
|
|
||||||
DATABASE_PASSWORD: xpeditis_test_password
|
|
||||||
DATABASE_NAME: xpeditis_test
|
|
||||||
DATABASE_SYNCHRONIZE: 'false'
|
|
||||||
REDIS_HOST: redis
|
|
||||||
REDIS_PORT: 6379
|
|
||||||
REDIS_PASSWORD: ''
|
|
||||||
JWT_SECRET: test-secret-key-ci
|
|
||||||
SMTP_HOST: localhost
|
|
||||||
SMTP_PORT: 1025
|
|
||||||
SMTP_FROM: test@xpeditis.com
|
|
||||||
run: npm run test:integration -- --ci --runInBand
|
|
||||||
|
|
||||||
# ── 4. Docker Build & Push ───────────────────────────────────────────
|
|
||||||
# Tags: preprod (latest for this env) + preprod-SHA (used by prod for exact promotion)
|
|
||||||
build-backend:
|
|
||||||
name: Build Backend
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: [security, integration-tests]
|
|
||||||
outputs:
|
|
||||||
sha: ${{ steps.sha.outputs.short }}
|
|
||||||
digest: ${{ steps.build.outputs.digest }}
|
|
||||||
steps:
|
|
||||||
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
- name: Short SHA
|
|
||||||
id: sha
|
|
||||||
run: echo "short=$(echo ${{ github.sha }} | cut -c1-7)" >> $GITHUB_OUTPUT
|
|
||||||
- uses: https://github.com/docker/setup-qemu-action@c7c53464625b32c7a7e944ae62b3e17d2b600130 # v3
|
|
||||||
with:
|
|
||||||
platforms: amd64,arm64
|
|
||||||
cache-image: false
|
|
||||||
- uses: https://github.com/docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3
|
|
||||||
- uses: https://github.com/docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3
|
|
||||||
with:
|
|
||||||
registry: ${{ env.REGISTRY }}
|
|
||||||
username: nologin
|
|
||||||
password: ${{ secrets.REGISTRY_TOKEN }}
|
|
||||||
- id: build
|
|
||||||
uses: https://github.com/docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6
|
|
||||||
with:
|
|
||||||
context: ./apps/backend
|
|
||||||
file: ./apps/backend/Dockerfile
|
|
||||||
push: true
|
|
||||||
tags: |
|
|
||||||
${{ env.REGISTRY }}/xpeditis-backend:preprod-${{ steps.sha.outputs.short }}
|
|
||||||
cache-from: type=registry,ref=${{ env.REGISTRY }}/xpeditis-backend:buildcache
|
|
||||||
cache-to: type=registry,ref=${{ env.REGISTRY }}/xpeditis-backend:buildcache,mode=max
|
|
||||||
platforms: linux/amd64,linux/arm64
|
|
||||||
|
|
||||||
build-frontend:
|
|
||||||
name: Build Frontend
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: [security, integration-tests]
|
|
||||||
outputs:
|
|
||||||
sha: ${{ steps.sha.outputs.short }}
|
|
||||||
digest: ${{ steps.build.outputs.digest }}
|
|
||||||
steps:
|
|
||||||
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
- name: Short SHA
|
|
||||||
id: sha
|
|
||||||
run: echo "short=$(echo ${{ github.sha }} | cut -c1-7)" >> $GITHUB_OUTPUT
|
|
||||||
- uses: https://github.com/docker/setup-qemu-action@c7c53464625b32c7a7e944ae62b3e17d2b600130 # v3
|
|
||||||
with:
|
|
||||||
platforms: amd64,arm64
|
|
||||||
cache-image: false
|
|
||||||
- uses: https://github.com/docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3
|
|
||||||
- uses: https://github.com/docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3
|
|
||||||
with:
|
|
||||||
registry: ${{ env.REGISTRY }}
|
|
||||||
username: nologin
|
|
||||||
password: ${{ secrets.REGISTRY_TOKEN }}
|
|
||||||
- id: build
|
|
||||||
uses: https://github.com/docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6
|
|
||||||
with:
|
|
||||||
context: ./apps/frontend
|
|
||||||
file: ./apps/frontend/Dockerfile
|
|
||||||
push: true
|
|
||||||
tags: |
|
|
||||||
${{ env.REGISTRY }}/xpeditis-frontend:preprod-${{ steps.sha.outputs.short }}
|
|
||||||
cache-from: type=registry,ref=${{ env.REGISTRY }}/xpeditis-frontend:buildcache
|
|
||||||
cache-to: type=registry,ref=${{ env.REGISTRY }}/xpeditis-frontend:buildcache,mode=max
|
|
||||||
platforms: linux/amd64,linux/arm64
|
|
||||||
build-args: |
|
|
||||||
NEXT_PUBLIC_API_URL=${{ secrets.NEXT_PUBLIC_API_URL }}
|
|
||||||
NEXT_PUBLIC_APP_URL=${{ secrets.NEXT_PUBLIC_APP_URL }}
|
|
||||||
|
|
||||||
build-log-exporter:
|
|
||||||
name: Build Log Exporter
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: [security, integration-tests]
|
|
||||||
outputs:
|
|
||||||
sha: ${{ steps.sha.outputs.short }}
|
|
||||||
digest: ${{ steps.build.outputs.digest }}
|
|
||||||
steps:
|
|
||||||
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
- name: Short SHA
|
|
||||||
id: sha
|
|
||||||
run: echo "short=$(echo ${{ github.sha }} | cut -c1-7)" >> $GITHUB_OUTPUT
|
|
||||||
- uses: https://github.com/docker/setup-qemu-action@c7c53464625b32c7a7e944ae62b3e17d2b600130 # v3
|
|
||||||
with:
|
|
||||||
platforms: amd64,arm64
|
|
||||||
cache-image: false
|
|
||||||
- uses: https://github.com/docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3
|
|
||||||
- uses: https://github.com/docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3
|
|
||||||
with:
|
|
||||||
registry: ${{ env.REGISTRY }}
|
|
||||||
username: nologin
|
|
||||||
password: ${{ secrets.REGISTRY_TOKEN }}
|
|
||||||
- id: build
|
|
||||||
uses: https://github.com/docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6
|
|
||||||
with:
|
|
||||||
context: ./apps/log-exporter
|
|
||||||
file: ./apps/log-exporter/Dockerfile
|
|
||||||
push: true
|
|
||||||
tags: |
|
|
||||||
${{ env.REGISTRY }}/xpeditis-log-exporter:preprod-${{ steps.sha.outputs.short }}
|
|
||||||
cache-from: type=registry,ref=${{ env.REGISTRY }}/xpeditis-log-exporter:buildcache
|
|
||||||
cache-to: type=registry,ref=${{ env.REGISTRY }}/xpeditis-log-exporter:buildcache,mode=max
|
|
||||||
platforms: linux/amd64,linux/arm64
|
|
||||||
|
|
||||||
image-security:
|
|
||||||
name: Image security (${{ matrix.service }}, ${{ matrix.arch }})
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: [build-backend, build-frontend, build-log-exporter]
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
|
||||||
service: [backend, frontend, log-exporter]
|
|
||||||
arch: [amd64, arm64]
|
|
||||||
steps:
|
|
||||||
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
- uses: ./.gitea/actions/setup-trivy
|
|
||||||
- uses: https://github.com/docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3
|
|
||||||
with:
|
|
||||||
registry: ${{ env.REGISTRY }}
|
|
||||||
username: nologin
|
|
||||||
password: ${{ secrets.REGISTRY_TOKEN }}
|
|
||||||
- name: Scan the exact image before deployment
|
|
||||||
env:
|
|
||||||
IMAGE: ${{ env.REGISTRY }}/xpeditis-${{ matrix.service }}@${{ needs[format('build-{0}', matrix.service)].outputs.digest }}
|
|
||||||
PLATFORM: linux/${{ matrix.arch }}
|
|
||||||
run: |
|
|
||||||
trivy image --platform "$PLATFORM" --scanners vuln --severity HIGH,CRITICAL \
|
|
||||||
--ignore-unfixed=false --exit-code 1 --timeout 15m --no-progress --format json \
|
|
||||||
--output "$RUNNER_TEMP/image-security.json" "$IMAGE"
|
|
||||||
- name: Show image scan results
|
|
||||||
if: always()
|
|
||||||
run: python3 scripts/ci/summarize-image-security.py
|
|
||||||
- name: Save image report
|
|
||||||
if: always()
|
|
||||||
uses: https://github.com/actions/upload-artifact@ff15f0306b3f739f7b6fd43fb5d26cd321bd4de5 # v3, Gitea artifact protocol
|
|
||||||
with:
|
|
||||||
name: image-security-${{ matrix.service }}-${{ matrix.arch }}
|
|
||||||
path: ${{ runner.temp }}/image-security.json
|
|
||||||
retention-days: 14
|
|
||||||
if-no-files-found: error
|
|
||||||
|
|
||||||
# ── 5. Deploy via Portainer ──────────────────────────────────────────
|
|
||||||
deploy:
|
|
||||||
name: Deploy to Preprod
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: [build-backend, build-frontend, build-log-exporter, image-security]
|
|
||||||
steps:
|
|
||||||
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
- uses: https://github.com/docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3
|
|
||||||
- uses: https://github.com/docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3
|
|
||||||
with:
|
|
||||||
registry: ${{ env.REGISTRY }}
|
|
||||||
username: nologin
|
|
||||||
password: ${{ secrets.REGISTRY_TOKEN }}
|
|
||||||
- name: Publish scanned preprod images
|
|
||||||
env:
|
|
||||||
BACKEND_DIGEST: ${{ needs.build-backend.outputs.digest }}
|
|
||||||
FRONTEND_DIGEST: ${{ needs.build-frontend.outputs.digest }}
|
|
||||||
LOG_EXPORTER_DIGEST: ${{ needs.build-log-exporter.outputs.digest }}
|
|
||||||
run: |
|
|
||||||
for service in backend frontend log-exporter; do
|
|
||||||
case "$service" in
|
|
||||||
backend) digest="$BACKEND_DIGEST" ;;
|
|
||||||
frontend) digest="$FRONTEND_DIGEST" ;;
|
|
||||||
log-exporter) digest="$LOG_EXPORTER_DIGEST" ;;
|
|
||||||
esac
|
|
||||||
docker buildx imagetools create \
|
|
||||||
--tag "$REGISTRY/xpeditis-$service:preprod" \
|
|
||||||
"$REGISTRY/xpeditis-$service@$digest"
|
|
||||||
done
|
|
||||||
- name: Deploy backend
|
|
||||||
run: |
|
|
||||||
HTTP_CODE=$(curl --connect-timeout 10 --max-time 30 -s -o /dev/null -w "%{http_code}" -X POST "${{ secrets.PORTAINER_WEBHOOK_BACKEND }}")
|
|
||||||
echo "Portainer response: HTTP $HTTP_CODE"
|
|
||||||
if [[ "$HTTP_CODE" != "2"* ]]; then
|
|
||||||
echo "ERROR: Portainer webhook failed with HTTP $HTTP_CODE"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
echo "Backend webhook triggered."
|
|
||||||
- name: Wait for backend startup
|
|
||||||
run: sleep 20
|
|
||||||
- name: Deploy frontend
|
|
||||||
run: |
|
|
||||||
HTTP_CODE=$(curl --connect-timeout 10 --max-time 30 -s -o /dev/null -w "%{http_code}" -X POST "${{ secrets.PORTAINER_WEBHOOK_FRONTEND }}")
|
|
||||||
echo "Portainer response: HTTP $HTTP_CODE"
|
|
||||||
if [[ "$HTTP_CODE" != "2"* ]]; then
|
|
||||||
echo "ERROR: Portainer webhook failed with HTTP $HTTP_CODE"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
echo "Frontend webhook triggered."
|
|
||||||
|
|
||||||
- name: Verify backend health
|
|
||||||
env:
|
|
||||||
BASE_URL: ${{ secrets.PREPROD_BACKEND_URL || vars.PREPROD_BACKEND_URL || 'https://api.preprod.xpeditis.com' }}
|
|
||||||
run: bash scripts/ci/health-check.sh "${BASE_URL%/}/api/v1/health"
|
|
||||||
- name: Verify frontend health
|
|
||||||
env:
|
|
||||||
BASE_URL: ${{ secrets.PREPROD_FRONTEND_URL || vars.PREPROD_FRONTEND_URL || 'https://app.preprod.xpeditis.com' }}
|
|
||||||
run: bash scripts/ci/health-check.sh "${BASE_URL%/}/api/health"
|
|
||||||
|
|
||||||
- name: Mark successfully deployed preprod images
|
|
||||||
env:
|
|
||||||
BACKEND_DIGEST: ${{ needs.build-backend.outputs.digest }}
|
|
||||||
LOG_EXPORTER_DIGEST: ${{ needs.build-log-exporter.outputs.digest }}
|
|
||||||
run: |
|
|
||||||
docker buildx imagetools create \
|
|
||||||
--tag "$REGISTRY/xpeditis-backend:validated-preprod-$GITHUB_SHA" \
|
|
||||||
"$REGISTRY/xpeditis-backend@$BACKEND_DIGEST"
|
|
||||||
docker buildx imagetools create \
|
|
||||||
--tag "$REGISTRY/xpeditis-log-exporter:validated-preprod-$GITHUB_SHA" \
|
|
||||||
"$REGISTRY/xpeditis-log-exporter@$LOG_EXPORTER_DIGEST"
|
|
||||||
|
|
||||||
# ── Notifications ────────────────────────────────────────────────────
|
|
||||||
notify-success:
|
|
||||||
name: Notify Success
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: [build-backend, build-frontend, deploy]
|
|
||||||
if: success()
|
|
||||||
steps:
|
|
||||||
- run: |
|
|
||||||
curl -s -H "Content-Type: application/json" -d '{
|
|
||||||
"embeds": [{
|
|
||||||
"title": "✅ Preprod Deployed & Healthy",
|
|
||||||
"color": 3066993,
|
|
||||||
"fields": [
|
|
||||||
{"name": "Author", "value": "${{ github.actor }}", "inline": true},
|
|
||||||
{"name": "SHA", "value": "`${{ needs.build-backend.outputs.sha }}`", "inline": true},
|
|
||||||
{"name": "Workflow", "value": "[${{ github.run_id }}](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})", "inline": false}
|
|
||||||
],
|
|
||||||
"footer": {"text": "Xpeditis CI/CD • Preprod"}
|
|
||||||
}]
|
|
||||||
}' ${{ secrets.DISCORD_WEBHOOK_URL }}
|
|
||||||
|
|
||||||
notify-failure:
|
|
||||||
name: Notify Failure
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: [security, backend-quality, frontend-quality, backend-tests, frontend-tests, integration-tests, build-backend, build-frontend, build-log-exporter, image-security, deploy]
|
|
||||||
# Security gate failures are already reported by the security job itself.
|
|
||||||
if: failure() && needs.security.result != 'failure'
|
|
||||||
steps:
|
|
||||||
- run: |
|
|
||||||
curl -s -H "Content-Type: application/json" -d '{
|
|
||||||
"embeds": [{
|
|
||||||
"title": "❌ Preprod Pipeline Failed",
|
|
||||||
"description": "Pipeline en échec. Vérifiez les rapports et l état réel des services avant de relancer.",
|
|
||||||
"color": 15158332,
|
|
||||||
"fields": [
|
|
||||||
{"name": "Author", "value": "${{ github.actor }}", "inline": true},
|
|
||||||
{"name": "Workflow", "value": "[${{ github.run_id }}](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})", "inline": false}
|
|
||||||
],
|
|
||||||
"footer": {"text": "Xpeditis CI/CD • Preprod"}
|
|
||||||
}]
|
|
||||||
}' ${{ secrets.DISCORD_WEBHOOK_URL }}
|
|
||||||
@ -1,131 +0,0 @@
|
|||||||
name: Dev CI
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches: [dev]
|
|
||||||
pull_request:
|
|
||||||
branches: [dev]
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
security:
|
|
||||||
name: Security gate
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
- uses: ./.gitea/actions/setup-node
|
|
||||||
- name: Install Trivy
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
trivy_bin=$(bash scripts/ci/install-tool.sh trivy)
|
|
||||||
"$trivy_bin" --version
|
|
||||||
- name: Validate workflows and deployment checks
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
actionlint_bin=$(bash scripts/ci/install-tool.sh actionlint)
|
|
||||||
ACTIONLINT_BIN="$actionlint_bin" bash scripts/ci/validate-workflows.sh
|
|
||||||
- name: Audit dependencies, secrets and infrastructure
|
|
||||||
shell: bash
|
|
||||||
run: bash scripts/ci/security-audit.sh
|
|
||||||
- name: Show security results
|
|
||||||
if: always()
|
|
||||||
shell: bash
|
|
||||||
run: python3 scripts/ci/summarize-security.py
|
|
||||||
- name: Save security reports on Gitea
|
|
||||||
if: always()
|
|
||||||
uses: https://github.com/actions/upload-artifact@ff15f0306b3f739f7b6fd43fb5d26cd321bd4de5 # v3, Gitea artifact protocol
|
|
||||||
with:
|
|
||||||
name: security-reports
|
|
||||||
path: ${{ runner.temp }}/security-reports/*.json
|
|
||||||
retention-days: 7
|
|
||||||
if-no-files-found: error
|
|
||||||
- name: Notify Discord
|
|
||||||
if: failure()
|
|
||||||
uses: ./.gitea/actions/notify-security-failure
|
|
||||||
with:
|
|
||||||
webhook-url: ${{ secrets.DISCORD_WEBHOOK_URL }}
|
|
||||||
pipeline: Dev
|
|
||||||
|
|
||||||
backend-quality:
|
|
||||||
name: Backend — Lint
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: security
|
|
||||||
defaults:
|
|
||||||
run:
|
|
||||||
working-directory: apps/backend
|
|
||||||
steps:
|
|
||||||
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
- uses: ./.gitea/actions/setup-node
|
|
||||||
- run: npm ci --legacy-peer-deps
|
|
||||||
- run: npm run lint -- --no-fix
|
|
||||||
|
|
||||||
frontend-quality:
|
|
||||||
name: Frontend — Lint & Type-check
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: security
|
|
||||||
defaults:
|
|
||||||
run:
|
|
||||||
working-directory: apps/frontend
|
|
||||||
steps:
|
|
||||||
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
- uses: ./.gitea/actions/setup-node
|
|
||||||
- run: npm ci --legacy-peer-deps
|
|
||||||
- run: npm run lint
|
|
||||||
- run: npm run type-check
|
|
||||||
|
|
||||||
backend-tests:
|
|
||||||
name: Backend — Unit Tests
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: backend-quality
|
|
||||||
defaults:
|
|
||||||
run:
|
|
||||||
working-directory: apps/backend
|
|
||||||
steps:
|
|
||||||
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
- uses: ./.gitea/actions/setup-node
|
|
||||||
- run: npm ci --legacy-peer-deps
|
|
||||||
- run: npm test -- --ci --runInBand
|
|
||||||
|
|
||||||
frontend-tests:
|
|
||||||
name: Frontend — Unit Tests
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: frontend-quality
|
|
||||||
defaults:
|
|
||||||
run:
|
|
||||||
working-directory: apps/frontend
|
|
||||||
steps:
|
|
||||||
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
- uses: ./.gitea/actions/setup-node
|
|
||||||
- run: npm ci --legacy-peer-deps
|
|
||||||
- run: npm test -- --ci --runInBand
|
|
||||||
|
|
||||||
notify-failure:
|
|
||||||
name: Notify Failure
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: [security, backend-quality, frontend-quality, backend-tests, frontend-tests]
|
|
||||||
# Security gate failures are already reported by the security job itself.
|
|
||||||
if: failure() && needs.security.result != 'failure'
|
|
||||||
steps:
|
|
||||||
- name: Discord
|
|
||||||
run: |
|
|
||||||
curl -s -H "Content-Type: application/json" -d '{
|
|
||||||
"embeds": [{
|
|
||||||
"title": "❌ Dev CI Failed",
|
|
||||||
"color": 15158332,
|
|
||||||
"fields": [
|
|
||||||
{"name": "Branch", "value": "`${{ github.ref_name }}`", "inline": true},
|
|
||||||
{"name": "Author", "value": "${{ github.actor }}", "inline": true},
|
|
||||||
{"name": "Workflow", "value": "[${{ github.run_id }}](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})", "inline": false}
|
|
||||||
],
|
|
||||||
"footer": {"text": "Xpeditis CI • Dev"}
|
|
||||||
}]
|
|
||||||
}' ${{ secrets.DISCORD_WEBHOOK_URL }}
|
|
||||||
@ -1,169 +0,0 @@
|
|||||||
name: PR Checks
|
|
||||||
|
|
||||||
# Required status checks — configure these in branch protection rules.
|
|
||||||
# PRs to preprod : lint + type-check + unit tests + integration tests
|
|
||||||
# PRs to main : same checks, including integration and security
|
|
||||||
|
|
||||||
on:
|
|
||||||
pull_request:
|
|
||||||
branches: [preprod, main]
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
security:
|
|
||||||
name: Security gate
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
- uses: ./.gitea/actions/setup-node
|
|
||||||
- name: Install Trivy
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
trivy_bin=$(bash scripts/ci/install-tool.sh trivy)
|
|
||||||
"$trivy_bin" --version
|
|
||||||
- name: Validate workflows and deployment checks
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
actionlint_bin=$(bash scripts/ci/install-tool.sh actionlint)
|
|
||||||
ACTIONLINT_BIN="$actionlint_bin" bash scripts/ci/validate-workflows.sh
|
|
||||||
- name: Audit dependencies, secrets and infrastructure
|
|
||||||
shell: bash
|
|
||||||
run: bash scripts/ci/security-audit.sh
|
|
||||||
- name: Show security results
|
|
||||||
if: always()
|
|
||||||
shell: bash
|
|
||||||
run: python3 scripts/ci/summarize-security.py
|
|
||||||
- name: Save security reports on Gitea
|
|
||||||
if: always()
|
|
||||||
uses: https://github.com/actions/upload-artifact@ff15f0306b3f739f7b6fd43fb5d26cd321bd4de5 # v3, Gitea artifact protocol
|
|
||||||
with:
|
|
||||||
name: security-reports
|
|
||||||
path: ${{ runner.temp }}/security-reports/*.json
|
|
||||||
retention-days: 7
|
|
||||||
if-no-files-found: error
|
|
||||||
- name: Notify Discord
|
|
||||||
if: failure()
|
|
||||||
uses: ./.gitea/actions/notify-security-failure
|
|
||||||
with:
|
|
||||||
webhook-url: ${{ secrets.DISCORD_WEBHOOK_URL }}
|
|
||||||
pipeline: PR Checks
|
|
||||||
|
|
||||||
backend-quality:
|
|
||||||
name: Backend — Lint
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: security
|
|
||||||
defaults:
|
|
||||||
run:
|
|
||||||
working-directory: apps/backend
|
|
||||||
steps:
|
|
||||||
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
- uses: ./.gitea/actions/setup-node
|
|
||||||
- run: npm ci --legacy-peer-deps
|
|
||||||
- run: npm run lint -- --no-fix
|
|
||||||
|
|
||||||
frontend-quality:
|
|
||||||
name: Frontend — Lint & Type-check
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: security
|
|
||||||
defaults:
|
|
||||||
run:
|
|
||||||
working-directory: apps/frontend
|
|
||||||
steps:
|
|
||||||
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
- uses: ./.gitea/actions/setup-node
|
|
||||||
- run: npm ci --legacy-peer-deps
|
|
||||||
- run: npm run lint
|
|
||||||
- run: npm run type-check
|
|
||||||
|
|
||||||
backend-tests:
|
|
||||||
name: Backend — Unit Tests
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: backend-quality
|
|
||||||
defaults:
|
|
||||||
run:
|
|
||||||
working-directory: apps/backend
|
|
||||||
steps:
|
|
||||||
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
- uses: ./.gitea/actions/setup-node
|
|
||||||
- run: npm ci --legacy-peer-deps
|
|
||||||
- run: npm test -- --ci --runInBand
|
|
||||||
|
|
||||||
frontend-tests:
|
|
||||||
name: Frontend — Unit Tests
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: frontend-quality
|
|
||||||
defaults:
|
|
||||||
run:
|
|
||||||
working-directory: apps/frontend
|
|
||||||
steps:
|
|
||||||
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
- uses: ./.gitea/actions/setup-node
|
|
||||||
- run: npm ci --legacy-peer-deps
|
|
||||||
- run: npm test -- --ci --runInBand
|
|
||||||
|
|
||||||
# Integration tests validate the actual merge candidate for both branches.
|
|
||||||
integration-tests:
|
|
||||||
name: Backend — Integration Tests
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: backend-tests
|
|
||||||
defaults:
|
|
||||||
run:
|
|
||||||
working-directory: apps/backend
|
|
||||||
|
|
||||||
services:
|
|
||||||
postgres:
|
|
||||||
image: postgres:15-alpine
|
|
||||||
env:
|
|
||||||
POSTGRES_USER: xpeditis_test
|
|
||||||
POSTGRES_PASSWORD: xpeditis_test_password
|
|
||||||
POSTGRES_DB: xpeditis_test
|
|
||||||
options: >-
|
|
||||||
--health-cmd pg_isready
|
|
||||||
--health-interval 5s
|
|
||||||
--health-timeout 5s
|
|
||||||
--health-retries 10
|
|
||||||
redis:
|
|
||||||
image: redis:7-alpine
|
|
||||||
options: >-
|
|
||||||
--health-cmd "redis-cli ping"
|
|
||||||
--health-interval 5s
|
|
||||||
--health-timeout 5s
|
|
||||||
--health-retries 10
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
- uses: ./.gitea/actions/setup-node
|
|
||||||
- run: npm ci --legacy-peer-deps
|
|
||||||
- name: Run integration tests
|
|
||||||
env:
|
|
||||||
NODE_ENV: test
|
|
||||||
TEST_DB_HOST: postgres
|
|
||||||
TEST_DB_PORT: 5432
|
|
||||||
TEST_DB_USER: xpeditis_test
|
|
||||||
TEST_DB_PASSWORD: xpeditis_test_password
|
|
||||||
TEST_DB_NAME: xpeditis_test
|
|
||||||
DATABASE_HOST: postgres
|
|
||||||
DATABASE_PORT: 5432
|
|
||||||
DATABASE_USER: xpeditis_test
|
|
||||||
DATABASE_PASSWORD: xpeditis_test_password
|
|
||||||
DATABASE_NAME: xpeditis_test
|
|
||||||
DATABASE_SYNCHRONIZE: 'false'
|
|
||||||
REDIS_HOST: redis
|
|
||||||
REDIS_PORT: 6379
|
|
||||||
REDIS_PASSWORD: ''
|
|
||||||
JWT_SECRET: test-secret-key-ci
|
|
||||||
SMTP_HOST: localhost
|
|
||||||
SMTP_PORT: 1025
|
|
||||||
SMTP_FROM: test@xpeditis.com
|
|
||||||
run: npm run test:integration -- --ci --runInBand
|
|
||||||
361
.github/workflows/cd-main.yml
vendored
Normal file
361
.github/workflows/cd-main.yml
vendored
Normal file
@ -0,0 +1,361 @@
|
|||||||
|
name: CD Production
|
||||||
|
|
||||||
|
# Pipeline de production — Hetzner k3s (infra/prod/).
|
||||||
|
#
|
||||||
|
# Enchaînement : qualité → vérification → promotion/rebuild → déploiement → contrôle
|
||||||
|
#
|
||||||
|
# TROIS RÈGLES STRUCTURANTES
|
||||||
|
#
|
||||||
|
# 1. Le BACKEND est PROMU depuis la preprod, jamais reconstruit.
|
||||||
|
# Promouvoir garantit que le binaire déployé en production est exactement
|
||||||
|
# celui qui a passé la chaîne de preprod (lint, tests unitaires, tests
|
||||||
|
# d'intégration, build). Un rebuild casserait cette garantie.
|
||||||
|
#
|
||||||
|
# 2. Le FRONTEND est RECONSTRUIT pour la production.
|
||||||
|
# next.config.js fige NEXT_PUBLIC_API_URL au moment du build. Promouvoir
|
||||||
|
# l'image de preprod livrerait une application qui appelle
|
||||||
|
# api.preprod.xpeditis.com en production. C'est la raison pour laquelle ce
|
||||||
|
# workflow ne peut pas se contenter de re-taguer.
|
||||||
|
#
|
||||||
|
# 3. Le déploiement passe par SSH, pas par l'API Kubernetes.
|
||||||
|
# L'API k3s (6443) n'est ouverte qu'aux IP d'administration. Les runners
|
||||||
|
# GitHub n'ont pas d'IP fixe : le job ouvre le port 22 pour la seule IP du
|
||||||
|
# runner via un firewall Hetzner dédié, puis le referme systématiquement.
|
||||||
|
#
|
||||||
|
# Secrets et variables : voir infra/prod/env/github-secrets.md
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
tag:
|
||||||
|
description: "SHA court à déployer (laisser vide = HEAD de main)"
|
||||||
|
required: false
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: cd-production
|
||||||
|
cancel-in-progress: false
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
env:
|
||||||
|
REGISTRY: rg.fr-par.scw.cloud/weworkstudio
|
||||||
|
NODE_VERSION: '20'
|
||||||
|
K8S_NAMESPACE: xpeditis-prod
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
# ═══ 1. Qualité ══════════════════════════════════════════════════════════
|
||||||
|
backend-quality:
|
||||||
|
name: Backend — Lint
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: apps/backend
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: ${{ env.NODE_VERSION }}
|
||||||
|
cache: 'npm'
|
||||||
|
cache-dependency-path: apps/backend/package-lock.json
|
||||||
|
- run: npm install --legacy-peer-deps
|
||||||
|
- run: npm run lint
|
||||||
|
|
||||||
|
frontend-quality:
|
||||||
|
name: Frontend — Lint & Type-check
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: apps/frontend
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: ${{ env.NODE_VERSION }}
|
||||||
|
cache: 'npm'
|
||||||
|
cache-dependency-path: apps/frontend/package-lock.json
|
||||||
|
- run: npm ci --legacy-peer-deps
|
||||||
|
- run: npm run lint
|
||||||
|
- run: npm run type-check
|
||||||
|
|
||||||
|
backend-tests:
|
||||||
|
name: Backend — Tests unitaires
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: backend-quality
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: apps/backend
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: ${{ env.NODE_VERSION }}
|
||||||
|
cache: 'npm'
|
||||||
|
cache-dependency-path: apps/backend/package-lock.json
|
||||||
|
- run: npm install --legacy-peer-deps
|
||||||
|
- run: npm test -- --passWithNoTests
|
||||||
|
|
||||||
|
frontend-tests:
|
||||||
|
name: Frontend — Tests unitaires
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: frontend-quality
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: apps/frontend
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: ${{ env.NODE_VERSION }}
|
||||||
|
cache: 'npm'
|
||||||
|
cache-dependency-path: apps/frontend/package-lock.json
|
||||||
|
- run: npm ci --legacy-peer-deps
|
||||||
|
- run: npm test -- --passWithNoTests
|
||||||
|
|
||||||
|
# ═══ 2. Vérification de la provenance ════════════════════════════════════
|
||||||
|
# Si l'image preprod-SHA n'existe pas, c'est que ce commit n'est jamais passé
|
||||||
|
# par la chaîne de preprod. Le déploiement est alors bloqué net.
|
||||||
|
verify-image:
|
||||||
|
name: Vérifier l'image de preprod
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: [backend-tests, frontend-tests]
|
||||||
|
outputs:
|
||||||
|
sha: ${{ steps.sha.outputs.short }}
|
||||||
|
steps:
|
||||||
|
- name: SHA court
|
||||||
|
id: sha
|
||||||
|
run: |
|
||||||
|
RAW="${{ github.event.inputs.tag }}"
|
||||||
|
[ -n "$RAW" ] || RAW="${{ github.sha }}"
|
||||||
|
echo "short=$(echo "$RAW" | cut -c1-7)" >> $GITHUB_OUTPUT
|
||||||
|
|
||||||
|
- uses: docker/setup-buildx-action@v3
|
||||||
|
- uses: docker/login-action@v3
|
||||||
|
with:
|
||||||
|
registry: ${{ env.REGISTRY }}
|
||||||
|
username: nologin
|
||||||
|
password: ${{ secrets.REGISTRY_TOKEN }}
|
||||||
|
|
||||||
|
- name: Image backend preprod-SHA présente
|
||||||
|
run: |
|
||||||
|
TAG="${{ env.REGISTRY }}/xpeditis-backend:preprod-${{ steps.sha.outputs.short }}"
|
||||||
|
docker buildx imagetools inspect "$TAG" || {
|
||||||
|
echo "::error::$TAG introuvable. Ce commit n'a pas été construit par la chaîne de preprod."
|
||||||
|
echo "Fusionnez d'abord sur preprod et attendez que le pipeline passe au vert."
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
- name: Image log-exporter preprod-SHA présente
|
||||||
|
run: |
|
||||||
|
TAG="${{ env.REGISTRY }}/xpeditis-log-exporter:preprod-${{ steps.sha.outputs.short }}"
|
||||||
|
docker buildx imagetools inspect "$TAG" || {
|
||||||
|
echo "::error::$TAG introuvable."
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
# ═══ 3a. Promotion du backend (aucun rebuild) ════════════════════════════
|
||||||
|
promote-backend:
|
||||||
|
name: Promouvoir le backend
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: verify-image
|
||||||
|
steps:
|
||||||
|
- uses: docker/setup-buildx-action@v3
|
||||||
|
- uses: docker/login-action@v3
|
||||||
|
with:
|
||||||
|
registry: ${{ env.REGISTRY }}
|
||||||
|
username: nologin
|
||||||
|
password: ${{ secrets.REGISTRY_TOKEN }}
|
||||||
|
- name: preprod-SHA → prod-SHA
|
||||||
|
run: |
|
||||||
|
SHA="${{ needs.verify-image.outputs.sha }}"
|
||||||
|
# Opération au niveau du manifeste : aucune couche n'est retransférée,
|
||||||
|
# le condensat de l'image reste identique à celui validé en preprod.
|
||||||
|
docker buildx imagetools create \
|
||||||
|
--tag ${{ env.REGISTRY }}/xpeditis-backend:prod-${SHA} \
|
||||||
|
--tag ${{ env.REGISTRY }}/xpeditis-backend:latest \
|
||||||
|
${{ env.REGISTRY }}/xpeditis-backend:preprod-${SHA}
|
||||||
|
docker buildx imagetools create \
|
||||||
|
--tag ${{ env.REGISTRY }}/xpeditis-log-exporter:prod-${SHA} \
|
||||||
|
--tag ${{ env.REGISTRY }}/xpeditis-log-exporter:latest \
|
||||||
|
${{ env.REGISTRY }}/xpeditis-log-exporter:preprod-${SHA}
|
||||||
|
|
||||||
|
# ═══ 3b. Reconstruction du frontend avec les URLs de production ══════════
|
||||||
|
build-frontend:
|
||||||
|
name: Reconstruire le frontend (URLs de production)
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: verify-image
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
# On construit EXACTEMENT le commit vérifié, pas HEAD.
|
||||||
|
ref: ${{ github.sha }}
|
||||||
|
- uses: docker/setup-buildx-action@v3
|
||||||
|
- uses: docker/login-action@v3
|
||||||
|
with:
|
||||||
|
registry: ${{ env.REGISTRY }}
|
||||||
|
username: nologin
|
||||||
|
password: ${{ secrets.REGISTRY_TOKEN }}
|
||||||
|
- uses: docker/build-push-action@v5
|
||||||
|
with:
|
||||||
|
context: ./apps/frontend
|
||||||
|
file: ./apps/frontend/Dockerfile
|
||||||
|
push: true
|
||||||
|
platforms: linux/amd64
|
||||||
|
tags: |
|
||||||
|
${{ env.REGISTRY }}/xpeditis-frontend:prod-${{ needs.verify-image.outputs.sha }}
|
||||||
|
${{ env.REGISTRY }}/xpeditis-frontend:latest
|
||||||
|
cache-from: type=registry,ref=${{ env.REGISTRY }}/xpeditis-frontend:buildcache-prod
|
||||||
|
cache-to: type=registry,ref=${{ env.REGISTRY }}/xpeditis-frontend:buildcache-prod,mode=max
|
||||||
|
build-args: |
|
||||||
|
NEXT_PUBLIC_API_URL=${{ secrets.NEXT_PUBLIC_API_URL_PROD }}
|
||||||
|
NEXT_PUBLIC_APP_URL=${{ secrets.NEXT_PUBLIC_APP_URL_PROD }}
|
||||||
|
|
||||||
|
- name: Contrôle — l'URL de preprod ne doit pas figurer dans le bundle
|
||||||
|
run: |
|
||||||
|
IMAGE="${{ env.REGISTRY }}/xpeditis-frontend:prod-${{ needs.verify-image.outputs.sha }}"
|
||||||
|
CID=$(docker create "$IMAGE")
|
||||||
|
docker cp "$CID:/app/.next" /tmp/next-check 2>/dev/null || true
|
||||||
|
docker rm "$CID" >/dev/null
|
||||||
|
if grep -rq "api.preprod.xpeditis.com" /tmp/next-check 2>/dev/null; then
|
||||||
|
echo "::error::L'URL de preprod est figée dans le bundle de production."
|
||||||
|
echo "Vérifiez le secret NEXT_PUBLIC_API_URL_PROD."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "Aucune URL de preprod dans le bundle."
|
||||||
|
|
||||||
|
# ═══ 4. Déploiement ══════════════════════════════════════════════════════
|
||||||
|
deploy:
|
||||||
|
name: Déployer en production
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: [verify-image, promote-backend, build-frontend]
|
||||||
|
# Environnement protégé : activez « Required reviewers » pour exiger une
|
||||||
|
# validation humaine avant toute mise en production.
|
||||||
|
environment:
|
||||||
|
name: production
|
||||||
|
url: https://app.xpeditis.com
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Installer le client Hetzner
|
||||||
|
run: |
|
||||||
|
curl -fsSL https://github.com/hetznercloud/cli/releases/download/v1.49.0/hcloud-linux-amd64.tar.gz \
|
||||||
|
| tar -xz -C /tmp hcloud
|
||||||
|
sudo install -m 0755 /tmp/hcloud /usr/local/bin/hcloud
|
||||||
|
hcloud version
|
||||||
|
|
||||||
|
- name: Ouvrir le port 22 pour l'IP de ce runner
|
||||||
|
env:
|
||||||
|
HCLOUD_TOKEN: ${{ secrets.HCLOUD_TOKEN_CICD }}
|
||||||
|
run: |
|
||||||
|
RUNNER_IP="$(curl -fsS --max-time 10 https://ifconfig.me)"
|
||||||
|
echo "IP du runner : ${RUNNER_IP}"
|
||||||
|
cat > /tmp/fw-open.json <<JSON
|
||||||
|
[{
|
||||||
|
"direction": "in",
|
||||||
|
"protocol": "tcp",
|
||||||
|
"port": "22",
|
||||||
|
"source_ips": ["${RUNNER_IP}/32"],
|
||||||
|
"description": "GitHub Actions run ${{ github.run_id }}"
|
||||||
|
}]
|
||||||
|
JSON
|
||||||
|
hcloud firewall replace-rules "${{ vars.HCLOUD_CICD_FIREWALL }}" --rules-file /tmp/fw-open.json
|
||||||
|
|
||||||
|
- name: Préparer SSH
|
||||||
|
run: |
|
||||||
|
mkdir -p ~/.ssh && chmod 700 ~/.ssh
|
||||||
|
echo "${{ secrets.PROD_SSH_KEY }}" > ~/.ssh/id_ed25519
|
||||||
|
chmod 600 ~/.ssh/id_ed25519
|
||||||
|
# Empreinte épinglée : un détournement DNS ou BGP ne peut pas
|
||||||
|
# rediriger le déploiement vers une machine tierce.
|
||||||
|
echo "${{ secrets.PROD_SSH_KNOWN_HOSTS }}" > ~/.ssh/known_hosts
|
||||||
|
chmod 600 ~/.ssh/known_hosts
|
||||||
|
|
||||||
|
- name: Synchroniser infra/prod sur le serveur
|
||||||
|
run: |
|
||||||
|
rsync -az --delete \
|
||||||
|
--exclude '.terraform' --exclude '*.tfstate*' --exclude '*.tfvars' \
|
||||||
|
-e "ssh -o StrictHostKeyChecking=yes -i ~/.ssh/id_ed25519" \
|
||||||
|
infra/prod/ \
|
||||||
|
"${{ secrets.PROD_SSH_USER }}@${{ secrets.PROD_SSH_HOST }}:/opt/xpeditis/infra-prod/"
|
||||||
|
|
||||||
|
- name: Déployer
|
||||||
|
id: deploy
|
||||||
|
run: |
|
||||||
|
SHA="${{ needs.verify-image.outputs.sha }}"
|
||||||
|
ssh -o StrictHostKeyChecking=yes -i ~/.ssh/id_ed25519 \
|
||||||
|
"${{ secrets.PROD_SSH_USER }}@${{ secrets.PROD_SSH_HOST }}" \
|
||||||
|
"deploy prod-${SHA}"
|
||||||
|
|
||||||
|
- name: Tests de fumée depuis l'extérieur
|
||||||
|
env:
|
||||||
|
PROD_API_URL: ${{ vars.PROD_API_URL }}
|
||||||
|
PROD_APP_URL: ${{ vars.PROD_APP_URL }}
|
||||||
|
run: bash infra/prod/scripts/smoke-test.sh
|
||||||
|
|
||||||
|
- name: Retour arrière si le déploiement a échoué
|
||||||
|
if: failure() && steps.deploy.conclusion == 'failure'
|
||||||
|
run: |
|
||||||
|
ssh -o StrictHostKeyChecking=yes -i ~/.ssh/id_ed25519 \
|
||||||
|
"${{ secrets.PROD_SSH_USER }}@${{ secrets.PROD_SSH_HOST }}" \
|
||||||
|
"rollback" || true
|
||||||
|
|
||||||
|
- name: Refermer le firewall
|
||||||
|
# `always()` : la fenêtre d'exposition se referme même si le
|
||||||
|
# déploiement a échoué, si le job a été annulé ou s'il a expiré.
|
||||||
|
if: always()
|
||||||
|
env:
|
||||||
|
HCLOUD_TOKEN: ${{ secrets.HCLOUD_TOKEN_CICD }}
|
||||||
|
run: |
|
||||||
|
echo '[]' > /tmp/fw-close.json
|
||||||
|
hcloud firewall replace-rules "${{ vars.HCLOUD_CICD_FIREWALL }}" --rules-file /tmp/fw-close.json
|
||||||
|
echo "Firewall CI refermé."
|
||||||
|
|
||||||
|
- name: Effacer la clé SSH
|
||||||
|
if: always()
|
||||||
|
run: shred -u ~/.ssh/id_ed25519 2>/dev/null || rm -f ~/.ssh/id_ed25519
|
||||||
|
|
||||||
|
# ═══ 5. Notifications ════════════════════════════════════════════════════
|
||||||
|
notify-success:
|
||||||
|
name: Notifier le succès
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: [verify-image, deploy]
|
||||||
|
if: success()
|
||||||
|
steps:
|
||||||
|
- run: |
|
||||||
|
curl -sf -H "Content-Type: application/json" -d '{
|
||||||
|
"embeds": [{
|
||||||
|
"title": "Production déployée et saine",
|
||||||
|
"color": 3066993,
|
||||||
|
"fields": [
|
||||||
|
{"name": "Auteur", "value": "${{ github.actor }}", "inline": true},
|
||||||
|
{"name": "Version", "value": "`prod-${{ needs.verify-image.outputs.sha }}`", "inline": true},
|
||||||
|
{"name": "Cible", "value": "Hetzner k3s — xpeditis-prod", "inline": false},
|
||||||
|
{"name": "Workflow", "value": "[${{ github.run_id }}](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})", "inline": false}
|
||||||
|
],
|
||||||
|
"footer": {"text": "Xpeditis CI/CD - Production"}
|
||||||
|
}]
|
||||||
|
}' ${{ secrets.DISCORD_WEBHOOK_URL }}
|
||||||
|
|
||||||
|
notify-failure:
|
||||||
|
name: Notifier l'échec
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: [backend-quality, frontend-quality, backend-tests, frontend-tests, verify-image, promote-backend, build-frontend, deploy]
|
||||||
|
if: failure()
|
||||||
|
steps:
|
||||||
|
- run: |
|
||||||
|
curl -sf -H "Content-Type: application/json" -d '{
|
||||||
|
"content": "@here ECHEC DU PIPELINE DE PRODUCTION",
|
||||||
|
"embeds": [{
|
||||||
|
"title": "Pipeline de production en échec",
|
||||||
|
"description": "Un retour arrière a été tenté si l échec est survenu pendant le déploiement. Vérifiez l état réel avant toute nouvelle tentative.",
|
||||||
|
"color": 15158332,
|
||||||
|
"fields": [
|
||||||
|
{"name": "Auteur", "value": "${{ github.actor }}", "inline": true},
|
||||||
|
{"name": "Workflow", "value": "[${{ github.run_id }}](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})", "inline": false},
|
||||||
|
{"name": "A vérifier", "value": "Le firewall CI est-il bien refermé ? `hcloud firewall describe xpeditis-prod-fw-cicd`", "inline": false}
|
||||||
|
],
|
||||||
|
"footer": {"text": "Xpeditis CI/CD - Production"}
|
||||||
|
}]
|
||||||
|
}' ${{ secrets.DISCORD_WEBHOOK_URL }}
|
||||||
316
.github/workflows/cd-preprod.yml
vendored
Normal file
316
.github/workflows/cd-preprod.yml
vendored
Normal file
@ -0,0 +1,316 @@
|
|||||||
|
name: CD Preprod
|
||||||
|
|
||||||
|
# Full pipeline triggered on every push to preprod.
|
||||||
|
# Flow: lint → unit tests → integration tests → docker build → deploy → notify
|
||||||
|
#
|
||||||
|
# Secrets required:
|
||||||
|
# REGISTRY_TOKEN — Scaleway registry (read/write)
|
||||||
|
# NEXT_PUBLIC_API_URL — https://api.preprod.xpeditis.com
|
||||||
|
# NEXT_PUBLIC_APP_URL — https://preprod.xpeditis.com
|
||||||
|
# PORTAINER_WEBHOOK_BACKEND — Portainer webhook (preprod backend)
|
||||||
|
# PORTAINER_WEBHOOK_FRONTEND— Portainer webhook (preprod frontend)
|
||||||
|
# PREPROD_BACKEND_URL — https://api.preprod.xpeditis.com
|
||||||
|
# PREPROD_FRONTEND_URL — https://preprod.xpeditis.com
|
||||||
|
# DISCORD_WEBHOOK_URL
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [preprod]
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: cd-preprod
|
||||||
|
cancel-in-progress: false
|
||||||
|
|
||||||
|
env:
|
||||||
|
REGISTRY: rg.fr-par.scw.cloud/weworkstudio
|
||||||
|
NODE_VERSION: '20'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
# ── 1. Lint ─────────────────────────────────────────────────────────
|
||||||
|
backend-quality:
|
||||||
|
name: Backend — Lint
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: apps/backend
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: ${{ env.NODE_VERSION }}
|
||||||
|
cache: 'npm'
|
||||||
|
cache-dependency-path: apps/backend/package-lock.json
|
||||||
|
- run: npm install --legacy-peer-deps
|
||||||
|
- run: npm run lint
|
||||||
|
|
||||||
|
frontend-quality:
|
||||||
|
name: Frontend — Lint & Type-check
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: apps/frontend
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: ${{ env.NODE_VERSION }}
|
||||||
|
cache: 'npm'
|
||||||
|
cache-dependency-path: apps/frontend/package-lock.json
|
||||||
|
- run: npm ci --legacy-peer-deps
|
||||||
|
- run: npm run lint
|
||||||
|
- run: npm run type-check
|
||||||
|
|
||||||
|
# ── 2. Unit Tests ────────────────────────────────────────────────────
|
||||||
|
backend-tests:
|
||||||
|
name: Backend — Unit Tests
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: backend-quality
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: apps/backend
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: ${{ env.NODE_VERSION }}
|
||||||
|
cache: 'npm'
|
||||||
|
cache-dependency-path: apps/backend/package-lock.json
|
||||||
|
- run: npm install --legacy-peer-deps
|
||||||
|
- run: npm test -- --passWithNoTests
|
||||||
|
|
||||||
|
frontend-tests:
|
||||||
|
name: Frontend — Unit Tests
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: frontend-quality
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: apps/frontend
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: ${{ env.NODE_VERSION }}
|
||||||
|
cache: 'npm'
|
||||||
|
cache-dependency-path: apps/frontend/package-lock.json
|
||||||
|
- run: npm ci --legacy-peer-deps
|
||||||
|
- run: npm test -- --passWithNoTests
|
||||||
|
|
||||||
|
# ── 3. Integration Tests ─────────────────────────────────────────────
|
||||||
|
integration-tests:
|
||||||
|
name: Backend — Integration Tests
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: [backend-tests, frontend-tests]
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: apps/backend
|
||||||
|
|
||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
image: postgres:15-alpine
|
||||||
|
env:
|
||||||
|
POSTGRES_USER: xpeditis_test
|
||||||
|
POSTGRES_PASSWORD: xpeditis_test_password
|
||||||
|
POSTGRES_DB: xpeditis_test
|
||||||
|
options: >-
|
||||||
|
--health-cmd pg_isready
|
||||||
|
--health-interval 5s
|
||||||
|
--health-timeout 5s
|
||||||
|
--health-retries 10
|
||||||
|
ports:
|
||||||
|
- 5432:5432
|
||||||
|
redis:
|
||||||
|
image: redis:7-alpine
|
||||||
|
options: >-
|
||||||
|
--health-cmd "redis-cli ping"
|
||||||
|
--health-interval 5s
|
||||||
|
--health-timeout 5s
|
||||||
|
--health-retries 10
|
||||||
|
ports:
|
||||||
|
- 6379:6379
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: ${{ env.NODE_VERSION }}
|
||||||
|
cache: 'npm'
|
||||||
|
cache-dependency-path: apps/backend/package-lock.json
|
||||||
|
- run: npm install --legacy-peer-deps
|
||||||
|
- name: Run integration tests
|
||||||
|
env:
|
||||||
|
NODE_ENV: test
|
||||||
|
DATABASE_HOST: localhost
|
||||||
|
DATABASE_PORT: 5432
|
||||||
|
DATABASE_USER: xpeditis_test
|
||||||
|
DATABASE_PASSWORD: xpeditis_test_password
|
||||||
|
DATABASE_NAME: xpeditis_test
|
||||||
|
DATABASE_SYNCHRONIZE: 'false'
|
||||||
|
REDIS_HOST: localhost
|
||||||
|
REDIS_PORT: 6379
|
||||||
|
REDIS_PASSWORD: ''
|
||||||
|
JWT_SECRET: test-secret-key-ci
|
||||||
|
SMTP_HOST: localhost
|
||||||
|
SMTP_PORT: 1025
|
||||||
|
SMTP_FROM: test@xpeditis.com
|
||||||
|
run: npm run test:integration -- --passWithNoTests
|
||||||
|
|
||||||
|
# ── 4. Docker Build & Push ───────────────────────────────────────────
|
||||||
|
# Tags: preprod (latest for this env) + preprod-SHA (used by prod for exact promotion)
|
||||||
|
build-backend:
|
||||||
|
name: Build Backend
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: integration-tests
|
||||||
|
outputs:
|
||||||
|
sha: ${{ steps.sha.outputs.short }}
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: Short SHA
|
||||||
|
id: sha
|
||||||
|
run: echo "short=$(echo ${{ github.sha }} | cut -c1-7)" >> $GITHUB_OUTPUT
|
||||||
|
- uses: docker/setup-buildx-action@v3
|
||||||
|
- uses: docker/login-action@v3
|
||||||
|
with:
|
||||||
|
registry: ${{ env.REGISTRY }}
|
||||||
|
username: nologin
|
||||||
|
password: ${{ secrets.REGISTRY_TOKEN }}
|
||||||
|
- uses: docker/build-push-action@v5
|
||||||
|
with:
|
||||||
|
context: ./apps/backend
|
||||||
|
file: ./apps/backend/Dockerfile
|
||||||
|
push: true
|
||||||
|
tags: |
|
||||||
|
${{ env.REGISTRY }}/xpeditis-backend:preprod
|
||||||
|
${{ env.REGISTRY }}/xpeditis-backend:preprod-${{ steps.sha.outputs.short }}
|
||||||
|
cache-from: type=registry,ref=${{ env.REGISTRY }}/xpeditis-backend:buildcache
|
||||||
|
cache-to: type=registry,ref=${{ env.REGISTRY }}/xpeditis-backend:buildcache,mode=max
|
||||||
|
platforms: linux/amd64,linux/arm64
|
||||||
|
|
||||||
|
build-frontend:
|
||||||
|
name: Build Frontend
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: integration-tests
|
||||||
|
outputs:
|
||||||
|
sha: ${{ steps.sha.outputs.short }}
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: Short SHA
|
||||||
|
id: sha
|
||||||
|
run: echo "short=$(echo ${{ github.sha }} | cut -c1-7)" >> $GITHUB_OUTPUT
|
||||||
|
- uses: docker/setup-buildx-action@v3
|
||||||
|
- uses: docker/login-action@v3
|
||||||
|
with:
|
||||||
|
registry: ${{ env.REGISTRY }}
|
||||||
|
username: nologin
|
||||||
|
password: ${{ secrets.REGISTRY_TOKEN }}
|
||||||
|
- uses: docker/build-push-action@v5
|
||||||
|
with:
|
||||||
|
context: ./apps/frontend
|
||||||
|
file: ./apps/frontend/Dockerfile
|
||||||
|
push: true
|
||||||
|
tags: |
|
||||||
|
${{ env.REGISTRY }}/xpeditis-frontend:preprod
|
||||||
|
${{ env.REGISTRY }}/xpeditis-frontend:preprod-${{ steps.sha.outputs.short }}
|
||||||
|
cache-from: type=registry,ref=${{ env.REGISTRY }}/xpeditis-frontend:buildcache
|
||||||
|
cache-to: type=registry,ref=${{ env.REGISTRY }}/xpeditis-frontend:buildcache,mode=max
|
||||||
|
platforms: linux/amd64,linux/arm64
|
||||||
|
build-args: |
|
||||||
|
NEXT_PUBLIC_API_URL=${{ secrets.NEXT_PUBLIC_API_URL }}
|
||||||
|
NEXT_PUBLIC_APP_URL=${{ secrets.NEXT_PUBLIC_APP_URL }}
|
||||||
|
|
||||||
|
build-log-exporter:
|
||||||
|
name: Build Log Exporter
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: integration-tests
|
||||||
|
outputs:
|
||||||
|
sha: ${{ steps.sha.outputs.short }}
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: Short SHA
|
||||||
|
id: sha
|
||||||
|
run: echo "short=$(echo ${{ github.sha }} | cut -c1-7)" >> $GITHUB_OUTPUT
|
||||||
|
- uses: docker/setup-buildx-action@v3
|
||||||
|
- uses: docker/login-action@v3
|
||||||
|
with:
|
||||||
|
registry: ${{ env.REGISTRY }}
|
||||||
|
username: nologin
|
||||||
|
password: ${{ secrets.REGISTRY_TOKEN }}
|
||||||
|
- uses: docker/build-push-action@v5
|
||||||
|
with:
|
||||||
|
context: ./apps/log-exporter
|
||||||
|
file: ./apps/log-exporter/Dockerfile
|
||||||
|
push: true
|
||||||
|
tags: |
|
||||||
|
${{ env.REGISTRY }}/xpeditis-log-exporter:preprod
|
||||||
|
${{ env.REGISTRY }}/xpeditis-log-exporter:preprod-${{ steps.sha.outputs.short }}
|
||||||
|
cache-from: type=registry,ref=${{ env.REGISTRY }}/xpeditis-log-exporter:buildcache
|
||||||
|
cache-to: type=registry,ref=${{ env.REGISTRY }}/xpeditis-log-exporter:buildcache,mode=max
|
||||||
|
platforms: linux/amd64,linux/arm64
|
||||||
|
|
||||||
|
# ── 5. Deploy via Portainer ──────────────────────────────────────────
|
||||||
|
deploy:
|
||||||
|
name: Deploy to Preprod
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: [build-backend, build-frontend, build-log-exporter]
|
||||||
|
environment: preprod
|
||||||
|
steps:
|
||||||
|
- name: Deploy backend
|
||||||
|
run: |
|
||||||
|
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" -X POST "${{ secrets.PORTAINER_WEBHOOK_BACKEND }}")
|
||||||
|
echo "Portainer response: HTTP $HTTP_CODE"
|
||||||
|
if [[ "$HTTP_CODE" != "2"* ]]; then
|
||||||
|
echo "ERROR: Portainer webhook failed with HTTP $HTTP_CODE"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "Backend webhook triggered."
|
||||||
|
- name: Wait for backend startup
|
||||||
|
run: sleep 20
|
||||||
|
- name: Deploy frontend
|
||||||
|
run: |
|
||||||
|
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" -X POST "${{ secrets.PORTAINER_WEBHOOK_FRONTEND }}")
|
||||||
|
echo "Portainer response: HTTP $HTTP_CODE"
|
||||||
|
if [[ "$HTTP_CODE" != "2"* ]]; then
|
||||||
|
echo "ERROR: Portainer webhook failed with HTTP $HTTP_CODE"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "Frontend webhook triggered."
|
||||||
|
|
||||||
|
# ── Notifications ────────────────────────────────────────────────────
|
||||||
|
notify-success:
|
||||||
|
name: Notify Success
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: [build-backend, build-frontend, deploy]
|
||||||
|
if: success()
|
||||||
|
steps:
|
||||||
|
- run: |
|
||||||
|
curl -s -H "Content-Type: application/json" -d '{
|
||||||
|
"embeds": [{
|
||||||
|
"title": "✅ Preprod Deployed & Healthy",
|
||||||
|
"color": 3066993,
|
||||||
|
"fields": [
|
||||||
|
{"name": "Author", "value": "${{ github.actor }}", "inline": true},
|
||||||
|
{"name": "SHA", "value": "`${{ needs.build-backend.outputs.sha }}`", "inline": true},
|
||||||
|
{"name": "Workflow", "value": "[${{ github.run_id }}](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})", "inline": false}
|
||||||
|
],
|
||||||
|
"footer": {"text": "Xpeditis CI/CD • Preprod"}
|
||||||
|
}]
|
||||||
|
}' ${{ secrets.DISCORD_WEBHOOK_URL }}
|
||||||
|
|
||||||
|
notify-failure:
|
||||||
|
name: Notify Failure
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: [backend-quality, frontend-quality, backend-tests, frontend-tests, integration-tests, build-backend, build-frontend, deploy]
|
||||||
|
if: failure()
|
||||||
|
steps:
|
||||||
|
- run: |
|
||||||
|
curl -s -H "Content-Type: application/json" -d '{
|
||||||
|
"embeds": [{
|
||||||
|
"title": "❌ Preprod Pipeline Failed",
|
||||||
|
"description": "Preprod was NOT deployed.",
|
||||||
|
"color": 15158332,
|
||||||
|
"fields": [
|
||||||
|
{"name": "Author", "value": "${{ github.actor }}", "inline": true},
|
||||||
|
{"name": "Workflow", "value": "[${{ github.run_id }}](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})", "inline": false}
|
||||||
|
],
|
||||||
|
"footer": {"text": "Xpeditis CI/CD • Preprod"}
|
||||||
|
}]
|
||||||
|
}' ${{ secrets.DISCORD_WEBHOOK_URL }}
|
||||||
103
.github/workflows/ci.yml
vendored
Normal file
103
.github/workflows/ci.yml
vendored
Normal file
@ -0,0 +1,103 @@
|
|||||||
|
name: Dev CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [dev]
|
||||||
|
pull_request:
|
||||||
|
branches: [dev]
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: dev-ci-${{ github.ref }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
env:
|
||||||
|
NODE_VERSION: '20'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
backend-quality:
|
||||||
|
name: Backend — Lint
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: apps/backend
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: ${{ env.NODE_VERSION }}
|
||||||
|
cache: 'npm'
|
||||||
|
cache-dependency-path: apps/backend/package-lock.json
|
||||||
|
- run: npm install --legacy-peer-deps
|
||||||
|
- run: npm run lint
|
||||||
|
|
||||||
|
frontend-quality:
|
||||||
|
name: Frontend — Lint & Type-check
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: apps/frontend
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: ${{ env.NODE_VERSION }}
|
||||||
|
cache: 'npm'
|
||||||
|
cache-dependency-path: apps/frontend/package-lock.json
|
||||||
|
- run: npm ci --legacy-peer-deps
|
||||||
|
- run: npm run lint
|
||||||
|
- run: npm run type-check
|
||||||
|
|
||||||
|
backend-tests:
|
||||||
|
name: Backend — Unit Tests
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: backend-quality
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: apps/backend
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: ${{ env.NODE_VERSION }}
|
||||||
|
cache: 'npm'
|
||||||
|
cache-dependency-path: apps/backend/package-lock.json
|
||||||
|
- run: npm install --legacy-peer-deps
|
||||||
|
- run: npm test -- --passWithNoTests
|
||||||
|
|
||||||
|
frontend-tests:
|
||||||
|
name: Frontend — Unit Tests
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: frontend-quality
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: apps/frontend
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: ${{ env.NODE_VERSION }}
|
||||||
|
cache: 'npm'
|
||||||
|
cache-dependency-path: apps/frontend/package-lock.json
|
||||||
|
- run: npm ci --legacy-peer-deps
|
||||||
|
- run: npm test -- --passWithNoTests
|
||||||
|
|
||||||
|
notify-failure:
|
||||||
|
name: Notify Failure
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: [backend-quality, frontend-quality, backend-tests, frontend-tests]
|
||||||
|
if: failure()
|
||||||
|
steps:
|
||||||
|
- name: Discord
|
||||||
|
run: |
|
||||||
|
curl -s -H "Content-Type: application/json" -d '{
|
||||||
|
"embeds": [{
|
||||||
|
"title": "❌ Dev CI Failed",
|
||||||
|
"color": 15158332,
|
||||||
|
"fields": [
|
||||||
|
{"name": "Branch", "value": "`${{ github.ref_name }}`", "inline": true},
|
||||||
|
{"name": "Author", "value": "${{ github.actor }}", "inline": true},
|
||||||
|
{"name": "Workflow", "value": "[${{ github.run_id }}](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})", "inline": false}
|
||||||
|
],
|
||||||
|
"footer": {"text": "Xpeditis CI • Dev"}
|
||||||
|
}]
|
||||||
|
}' ${{ secrets.DISCORD_WEBHOOK_URL }}
|
||||||
145
.github/workflows/pr-checks.yml
vendored
Normal file
145
.github/workflows/pr-checks.yml
vendored
Normal file
@ -0,0 +1,145 @@
|
|||||||
|
name: PR Checks
|
||||||
|
|
||||||
|
# Required status checks — configure these in branch protection rules.
|
||||||
|
# PRs to preprod : lint + type-check + unit tests + integration tests
|
||||||
|
# PRs to main : lint + type-check + unit tests only
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
branches: [preprod, main]
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: pr-${{ github.event.pull_request.number }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
env:
|
||||||
|
NODE_VERSION: '20'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
backend-quality:
|
||||||
|
name: Backend — Lint
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: apps/backend
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: ${{ env.NODE_VERSION }}
|
||||||
|
cache: 'npm'
|
||||||
|
cache-dependency-path: apps/backend/package-lock.json
|
||||||
|
- run: npm install --legacy-peer-deps
|
||||||
|
- run: npm run lint
|
||||||
|
|
||||||
|
frontend-quality:
|
||||||
|
name: Frontend — Lint & Type-check
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: apps/frontend
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: ${{ env.NODE_VERSION }}
|
||||||
|
cache: 'npm'
|
||||||
|
cache-dependency-path: apps/frontend/package-lock.json
|
||||||
|
- run: npm ci --legacy-peer-deps
|
||||||
|
- run: npm run lint
|
||||||
|
- run: npm run type-check
|
||||||
|
|
||||||
|
backend-tests:
|
||||||
|
name: Backend — Unit Tests
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: backend-quality
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: apps/backend
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: ${{ env.NODE_VERSION }}
|
||||||
|
cache: 'npm'
|
||||||
|
cache-dependency-path: apps/backend/package-lock.json
|
||||||
|
- run: npm install --legacy-peer-deps
|
||||||
|
- run: npm test -- --passWithNoTests
|
||||||
|
|
||||||
|
frontend-tests:
|
||||||
|
name: Frontend — Unit Tests
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: frontend-quality
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: apps/frontend
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: ${{ env.NODE_VERSION }}
|
||||||
|
cache: 'npm'
|
||||||
|
cache-dependency-path: apps/frontend/package-lock.json
|
||||||
|
- run: npm ci --legacy-peer-deps
|
||||||
|
- run: npm test -- --passWithNoTests
|
||||||
|
|
||||||
|
# Integration tests — PRs to preprod only
|
||||||
|
# Code going to main was already integration-tested when it passed through preprod
|
||||||
|
integration-tests:
|
||||||
|
name: Backend — Integration Tests
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: backend-tests
|
||||||
|
if: github.base_ref == 'preprod'
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: apps/backend
|
||||||
|
|
||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
image: postgres:15-alpine
|
||||||
|
env:
|
||||||
|
POSTGRES_USER: xpeditis_test
|
||||||
|
POSTGRES_PASSWORD: xpeditis_test_password
|
||||||
|
POSTGRES_DB: xpeditis_test
|
||||||
|
options: >-
|
||||||
|
--health-cmd pg_isready
|
||||||
|
--health-interval 5s
|
||||||
|
--health-timeout 5s
|
||||||
|
--health-retries 10
|
||||||
|
ports:
|
||||||
|
- 5432:5432
|
||||||
|
redis:
|
||||||
|
image: redis:7-alpine
|
||||||
|
options: >-
|
||||||
|
--health-cmd "redis-cli ping"
|
||||||
|
--health-interval 5s
|
||||||
|
--health-timeout 5s
|
||||||
|
--health-retries 10
|
||||||
|
ports:
|
||||||
|
- 6379:6379
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: ${{ env.NODE_VERSION }}
|
||||||
|
cache: 'npm'
|
||||||
|
cache-dependency-path: apps/backend/package-lock.json
|
||||||
|
- run: npm install --legacy-peer-deps
|
||||||
|
- name: Run integration tests
|
||||||
|
env:
|
||||||
|
NODE_ENV: test
|
||||||
|
DATABASE_HOST: localhost
|
||||||
|
DATABASE_PORT: 5432
|
||||||
|
DATABASE_USER: xpeditis_test
|
||||||
|
DATABASE_PASSWORD: xpeditis_test_password
|
||||||
|
DATABASE_NAME: xpeditis_test
|
||||||
|
DATABASE_SYNCHRONIZE: 'false'
|
||||||
|
REDIS_HOST: localhost
|
||||||
|
REDIS_PORT: 6379
|
||||||
|
REDIS_PASSWORD: ''
|
||||||
|
JWT_SECRET: test-secret-key-ci
|
||||||
|
SMTP_HOST: localhost
|
||||||
|
SMTP_PORT: 1025
|
||||||
|
SMTP_FROM: test@xpeditis.com
|
||||||
|
run: npm run test:integration -- --passWithNoTests
|
||||||
@ -126,7 +126,7 @@ jobs:
|
|||||||
docker buildx imagetools inspect "$BACKEND" || { echo "ERROR: $BACKEND not found"; exit 1; }
|
docker buildx imagetools inspect "$BACKEND" || { echo "ERROR: $BACKEND not found"; exit 1; }
|
||||||
docker buildx imagetools inspect "$FRONTEND" || { echo "ERROR: $FRONTEND not found"; exit 1; }
|
docker buildx imagetools inspect "$FRONTEND" || { echo "ERROR: $FRONTEND not found"; exit 1; }
|
||||||
|
|
||||||
kubectl set image deployment/xpeditis-backend backend="$BACKEND" seed-rates="$BACKEND" -n ${{ env.K8S_NAMESPACE }}
|
kubectl set image deployment/xpeditis-backend backend="$BACKEND" -n ${{ env.K8S_NAMESPACE }}
|
||||||
kubectl rollout status deployment/xpeditis-backend -n ${{ env.K8S_NAMESPACE }} --timeout=180s
|
kubectl rollout status deployment/xpeditis-backend -n ${{ env.K8S_NAMESPACE }} --timeout=180s
|
||||||
|
|
||||||
kubectl set image deployment/xpeditis-frontend frontend="$FRONTEND" -n ${{ env.K8S_NAMESPACE }}
|
kubectl set image deployment/xpeditis-frontend frontend="$FRONTEND" -n ${{ env.K8S_NAMESPACE }}
|
||||||
1
.gitignore
vendored
1
.gitignore
vendored
@ -46,7 +46,6 @@ lerna-debug.log*
|
|||||||
docker-compose.override.yml
|
docker-compose.override.yml
|
||||||
stack-portainer.yaml
|
stack-portainer.yaml
|
||||||
tmp.stack-portainer.yaml
|
tmp.stack-portainer.yaml
|
||||||
stack-portainer-preprod.yaml
|
|
||||||
|
|
||||||
# Uploads
|
# Uploads
|
||||||
uploads/
|
uploads/
|
||||||
|
|||||||
@ -1,22 +0,0 @@
|
|||||||
# Approved monitoring exceptions, reviewed 2026-09-24. No dependency/secret exclusions.
|
|
||||||
misconfigurations:
|
|
||||||
- id: AVD-KSV-0047
|
|
||||||
paths: [infra/prod/k8s/monitoring/03-prometheus.yaml]
|
|
||||||
expired_at: 2026-10-24
|
|
||||||
statement: Prometheus scrapes kubelet cAdvisor through the API server node proxy; retain until direct authenticated kubelet scraping is validated.
|
|
||||||
- id: AVD-KSV-0009
|
|
||||||
paths: [infra/prod/k8s/monitoring/04-node-exporter.yaml]
|
|
||||||
expired_at: 2026-10-24
|
|
||||||
statement: Node exporter observes host network metrics; isolated to the monitoring DaemonSet.
|
|
||||||
- id: AVD-KSV-0010
|
|
||||||
paths: [infra/prod/k8s/monitoring/04-node-exporter.yaml]
|
|
||||||
expired_at: 2026-10-24
|
|
||||||
statement: Node exporter observes host processes; runs as non-root with all capabilities dropped.
|
|
||||||
- id: AVD-KSV-0024
|
|
||||||
paths: [infra/prod/k8s/monitoring/04-node-exporter.yaml]
|
|
||||||
expired_at: 2026-10-24
|
|
||||||
statement: Existing host-network exporter listens on port 9101; access remains constrained by infrastructure firewall rules.
|
|
||||||
- id: AVD-KSV-0121
|
|
||||||
paths: [infra/prod/k8s/monitoring/04-node-exporter.yaml]
|
|
||||||
expired_at: 2026-10-24
|
|
||||||
statement: Host proc/sys/root mounts provide disk and system metrics and are read-only; required for disk-full alerts.
|
|
||||||
@ -24,7 +24,6 @@ e2e
|
|||||||
|
|
||||||
# Environment files
|
# Environment files
|
||||||
.env
|
.env
|
||||||
.env.*
|
|
||||||
.env.local
|
.env.local
|
||||||
.env.development
|
.env.development
|
||||||
.env.test
|
.env.test
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
# ===============================================
|
# ===============================================
|
||||||
# Stage 1: Dependencies Installation
|
# Stage 1: Dependencies Installation
|
||||||
# ===============================================
|
# ===============================================
|
||||||
FROM node:22-alpine AS dependencies
|
FROM node:20-alpine AS dependencies
|
||||||
|
|
||||||
# Install build dependencies
|
# Install build dependencies
|
||||||
RUN apk add --no-cache python3 make g++ libc6-compat
|
RUN apk add --no-cache python3 make g++ libc6-compat
|
||||||
@ -19,7 +19,7 @@ RUN npm ci --legacy-peer-deps
|
|||||||
# ===============================================
|
# ===============================================
|
||||||
# Stage 2: Build Application
|
# Stage 2: Build Application
|
||||||
# ===============================================
|
# ===============================================
|
||||||
FROM node:22-alpine AS builder
|
FROM node:20-alpine AS builder
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
@ -38,11 +38,7 @@ RUN npm prune --production --legacy-peer-deps
|
|||||||
# ===============================================
|
# ===============================================
|
||||||
# Stage 3: Production Image
|
# Stage 3: Production Image
|
||||||
# ===============================================
|
# ===============================================
|
||||||
FROM node:22-alpine AS production
|
FROM node:20-alpine AS production
|
||||||
|
|
||||||
# Runtime starts with node; remove the base image package manager and its dependencies.
|
|
||||||
# npm remains available in the dependency and build stages.
|
|
||||||
RUN npm uninstall --global npm
|
|
||||||
|
|
||||||
# Install dumb-init for proper signal handling
|
# Install dumb-init for proper signal handling
|
||||||
RUN apk add --no-cache dumb-init
|
RUN apk add --no-cache dumb-init
|
||||||
@ -65,10 +61,6 @@ COPY --from=builder --chown=nestjs:nodejs /app/src ./src
|
|||||||
# Copy startup script (includes migrations)
|
# Copy startup script (includes migrations)
|
||||||
COPY --chown=nestjs:nodejs scripts/setup/startup.js ./startup.js
|
COPY --chown=nestjs:nodejs scripts/setup/startup.js ./startup.js
|
||||||
|
|
||||||
# Recovery command: set an admin password without SMTP
|
|
||||||
# docker exec -it <backend-container> node admin-password.js <email>
|
|
||||||
COPY --chown=nestjs:nodejs scripts/setup/admin-password.js ./admin-password.js
|
|
||||||
|
|
||||||
# Create logs and uploads directories
|
# Create logs and uploads directories
|
||||||
RUN mkdir -p /app/logs && \
|
RUN mkdir -p /app/logs && \
|
||||||
mkdir -p /app/src/infrastructure/storage/csv-storage/rates && \
|
mkdir -p /app/src/infrastructure/storage/csv-storage/rates && \
|
||||||
|
|||||||
@ -1,26 +1,26 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
echo "Starting Xpeditis Backend..."
|
echo "Starting Xpeditis Backend..."
|
||||||
echo "Waiting for PostgreSQL..."
|
echo "Waiting for PostgreSQL..."
|
||||||
max_attempts=30
|
max_attempts=30
|
||||||
attempt=0
|
attempt=0
|
||||||
while [ $attempt -lt $max_attempts ]; do
|
while [ $attempt -lt $max_attempts ]; do
|
||||||
if node -e "const { Client } = require('pg'); const { databaseTlsOptions } = require('/app/dist/infrastructure/persistence/typeorm/database-tls'); const client = new Client({ host: process.env.DATABASE_HOST, port: process.env.DATABASE_PORT, user: process.env.DATABASE_USER, password: process.env.DATABASE_PASSWORD, database: process.env.DATABASE_NAME, ssl: databaseTlsOptions(process.env.DATABASE_SSL, process.env.DATABASE_SSL_CA, process.env.DATABASE_HOST) }); client.connect().then(() => { client.end(); process.exit(0); }).catch(() => process.exit(1));" 2>/dev/null; then
|
if node -e "const { Client } = require('pg'); const client = new Client({ host: process.env.DATABASE_HOST, port: process.env.DATABASE_PORT, user: process.env.DATABASE_USER, password: process.env.DATABASE_PASSWORD, database: process.env.DATABASE_NAME }); client.connect().then(() => { client.end(); process.exit(0); }).catch(() => process.exit(1));" 2>/dev/null; then
|
||||||
echo "PostgreSQL is ready"
|
echo "PostgreSQL is ready"
|
||||||
break
|
break
|
||||||
fi
|
fi
|
||||||
attempt=$((attempt + 1))
|
attempt=$((attempt + 1))
|
||||||
echo "Attempt $attempt/$max_attempts - Retrying..."
|
echo "Attempt $attempt/$max_attempts - Retrying..."
|
||||||
sleep 2
|
sleep 2
|
||||||
done
|
done
|
||||||
if [ $attempt -eq $max_attempts ]; then
|
if [ $attempt -eq $max_attempts ]; then
|
||||||
echo "Failed to connect to PostgreSQL"
|
echo "Failed to connect to PostgreSQL"
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
echo "Running database migrations..."
|
echo "Running database migrations..."
|
||||||
node /app/run-migrations.js
|
node /app/run-migrations.js
|
||||||
if [ $? -ne 0 ]; then
|
if [ $? -ne 0 ]; then
|
||||||
echo "Migrations failed"
|
echo "Migrations failed"
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
echo "Starting NestJS application..."
|
echo "Starting NestJS application..."
|
||||||
exec "$@"
|
exec "$@"
|
||||||
|
|||||||
5200
apps/backend/package-lock.json
generated
5200
apps/backend/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@ -29,21 +29,22 @@
|
|||||||
"@aws-sdk/lib-storage": "^3.906.0",
|
"@aws-sdk/lib-storage": "^3.906.0",
|
||||||
"@aws-sdk/s3-request-presigner": "^3.906.0",
|
"@aws-sdk/s3-request-presigner": "^3.906.0",
|
||||||
"@nestjs/axios": "^4.0.1",
|
"@nestjs/axios": "^4.0.1",
|
||||||
"@nestjs/common": "^11.2.6",
|
"@nestjs/common": "^10.2.10",
|
||||||
"@nestjs/config": "^4.0.4",
|
"@nestjs/config": "^3.1.1",
|
||||||
"@nestjs/core": "^11.2.6",
|
"@nestjs/core": "^10.2.10",
|
||||||
"@nestjs/jwt": "^11.0.2",
|
"@nestjs/jwt": "^10.2.0",
|
||||||
"@nestjs/passport": "^11.0.5",
|
"@nestjs/passport": "^10.0.3",
|
||||||
"@nestjs/platform-express": "^11.2.6",
|
"@nestjs/platform-express": "^10.2.10",
|
||||||
"@nestjs/platform-socket.io": "^11.2.6",
|
"@nestjs/platform-socket.io": "^10.4.20",
|
||||||
"@nestjs/schedule": "^6.1.3",
|
"@nestjs/schedule": "^4.1.2",
|
||||||
"@nestjs/swagger": "^11.4.7",
|
"@nestjs/swagger": "^7.1.16",
|
||||||
"@nestjs/throttler": "^6.4.0",
|
"@nestjs/throttler": "^6.4.0",
|
||||||
"@nestjs/typeorm": "^11.0.3",
|
"@nestjs/typeorm": "^10.0.1",
|
||||||
"@nestjs/websockets": "^11.2.6",
|
"@nestjs/websockets": "^10.4.20",
|
||||||
"@sentry/node": "^10.19.0",
|
"@sentry/node": "^10.19.0",
|
||||||
"@sentry/profiling-node": "^10.19.0",
|
"@sentry/profiling-node": "^10.19.0",
|
||||||
"@types/leaflet": "^1.9.21",
|
"@types/leaflet": "^1.9.21",
|
||||||
|
"@types/mjml": "^4.7.4",
|
||||||
"@types/nodemailer": "^7.0.2",
|
"@types/nodemailer": "^7.0.2",
|
||||||
"@types/opossum": "^8.1.9",
|
"@types/opossum": "^8.1.9",
|
||||||
"@types/pdfkit": "^0.17.3",
|
"@types/pdfkit": "^0.17.3",
|
||||||
@ -60,10 +61,10 @@
|
|||||||
"ioredis": "^5.8.1",
|
"ioredis": "^5.8.1",
|
||||||
"joi": "^17.11.0",
|
"joi": "^17.11.0",
|
||||||
"leaflet": "^1.9.4",
|
"leaflet": "^1.9.4",
|
||||||
"mjml": "^5.4.1",
|
"mjml": "^4.16.1",
|
||||||
"nestjs-i18n": "^10.6.5",
|
"nestjs-i18n": "^10.6.5",
|
||||||
"nestjs-pino": "^4.4.1",
|
"nestjs-pino": "^4.4.1",
|
||||||
"nodemailer": "^10.0.10",
|
"nodemailer": "^7.0.9",
|
||||||
"opossum": "^8.1.3",
|
"opossum": "^8.1.3",
|
||||||
"passport": "^0.7.0",
|
"passport": "^0.7.0",
|
||||||
"passport-google-oauth20": "^2.0.0",
|
"passport-google-oauth20": "^2.0.0",
|
||||||
@ -85,15 +86,14 @@
|
|||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@faker-js/faker": "^10.0.0",
|
"@faker-js/faker": "^10.0.0",
|
||||||
"@nestjs/cli": "^11.0.20",
|
"@nestjs/cli": "^10.2.1",
|
||||||
"@nestjs/schematics": "^11.1.0",
|
"@nestjs/schematics": "^10.0.3",
|
||||||
"@nestjs/testing": "^11.2.6",
|
"@nestjs/testing": "^10.2.10",
|
||||||
"@types/bcrypt": "^5.0.2",
|
"@types/bcrypt": "^5.0.2",
|
||||||
"@types/compression": "^1.8.1",
|
"@types/compression": "^1.8.1",
|
||||||
"@types/cookie-parser": "^1.4.10",
|
"@types/cookie-parser": "^1.4.10",
|
||||||
"@types/express": "^5.0.6",
|
"@types/express": "^4.17.21",
|
||||||
"@types/jest": "^29.5.11",
|
"@types/jest": "^29.5.11",
|
||||||
"@types/mjml": "^5.0.0",
|
|
||||||
"@types/multer": "^2.0.0",
|
"@types/multer": "^2.0.0",
|
||||||
"@types/node": "^20.10.5",
|
"@types/node": "^20.10.5",
|
||||||
"@types/passport-google-oauth20": "^2.0.14",
|
"@types/passport-google-oauth20": "^2.0.14",
|
||||||
|
|||||||
@ -1,167 +0,0 @@
|
|||||||
#!/usr/bin/env node
|
|
||||||
/**
|
|
||||||
* Commande de secours : définit le mot de passe d'un administrateur, sans SMTP.
|
|
||||||
*
|
|
||||||
* Dans le conteneur backend (le script est copié dans l'image) :
|
|
||||||
* docker exec -it <conteneur-backend> node admin-password.js admin@xpeditis.com
|
|
||||||
* En local :
|
|
||||||
* cd apps/backend && node scripts/setup/admin-password.js admin@xpeditis.com
|
|
||||||
*
|
|
||||||
* Le compte est créé s'il n'existe pas, sinon promu ADMIN et réactivé, puis son
|
|
||||||
* mot de passe est remplacé. Le mot de passe est saisi sans écho : ni argument
|
|
||||||
* de ligne de commande (visible dans `ps` et l'historique du shell), ni
|
|
||||||
* variable d'environnement. Il peut aussi être passé sur l'entrée standard
|
|
||||||
* pour une exécution scriptée.
|
|
||||||
*
|
|
||||||
* Connexion à la base : variables DATABASE_* déjà présentes dans le conteneur.
|
|
||||||
*/
|
|
||||||
|
|
||||||
'use strict';
|
|
||||||
|
|
||||||
const readline = require('readline');
|
|
||||||
const argon2 = require('argon2');
|
|
||||||
const { Client } = require('pg');
|
|
||||||
|
|
||||||
// Mêmes paramètres que auth.service.ts.
|
|
||||||
const ARGON2_OPTIONS = { type: argon2.argon2id, memoryCost: 65536, timeCost: 3, parallelism: 4 };
|
|
||||||
const MIN_LENGTH = 12;
|
|
||||||
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
||||||
|
|
||||||
/** Saisie masquée sur un terminal ; lecture directe si l'entrée est redirigée. */
|
|
||||||
function readSecret(prompt) {
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
if (!process.stdin.isTTY) {
|
|
||||||
let data = '';
|
|
||||||
process.stdin.setEncoding('utf8');
|
|
||||||
process.stdin.on('data', chunk => (data += chunk));
|
|
||||||
process.stdin.on('end', () => resolve(data.replace(/\r?\n$/, '')));
|
|
||||||
process.stdin.on('error', reject);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
||||||
const onKeypress = () => {
|
|
||||||
readline.clearLine(process.stdout, 0);
|
|
||||||
readline.cursorTo(process.stdout, 0);
|
|
||||||
process.stdout.write(prompt);
|
|
||||||
};
|
|
||||||
process.stdout.write(prompt);
|
|
||||||
process.stdin.on('data', onKeypress);
|
|
||||||
rl.question('', answer => {
|
|
||||||
process.stdin.removeListener('data', onKeypress);
|
|
||||||
rl.close();
|
|
||||||
process.stdout.write('\n');
|
|
||||||
resolve(answer);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function strengthProblems(password) {
|
|
||||||
const problems = [];
|
|
||||||
if (password.length < MIN_LENGTH) problems.push(`au moins ${MIN_LENGTH} caractères`);
|
|
||||||
if (!/[a-z]/.test(password)) problems.push('une minuscule');
|
|
||||||
if (!/[A-Z]/.test(password)) problems.push('une majuscule');
|
|
||||||
if (!/[0-9]/.test(password)) problems.push('un chiffre');
|
|
||||||
return problems;
|
|
||||||
}
|
|
||||||
|
|
||||||
function env(name, fallback) {
|
|
||||||
const value = (process.env[name] || '').trim();
|
|
||||||
return value || fallback;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function main() {
|
|
||||||
const email = (process.argv[2] || '').trim().toLowerCase();
|
|
||||||
if (!EMAIL_PATTERN.test(email)) {
|
|
||||||
console.error('Usage : node admin-password.js <email-administrateur>');
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
const password = await readSecret(`Nouveau mot de passe pour ${email} : `);
|
|
||||||
if (process.stdin.isTTY) {
|
|
||||||
const confirmation = await readSecret('Confirmation : ');
|
|
||||||
if (confirmation !== password) {
|
|
||||||
console.error('Les deux saisies diffèrent.');
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const problems = strengthProblems(password);
|
|
||||||
if (problems.length > 0) {
|
|
||||||
console.error(`Mot de passe refusé. Il manque : ${problems.join(', ')}.`);
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
const passwordHash = await argon2.hash(password, ARGON2_OPTIONS);
|
|
||||||
|
|
||||||
const client = new Client({
|
|
||||||
host: env('DATABASE_HOST', 'localhost'),
|
|
||||||
port: Number(env('DATABASE_PORT', '5432')),
|
|
||||||
user: env('DATABASE_USER', 'xpeditis'),
|
|
||||||
password: process.env.DATABASE_PASSWORD,
|
|
||||||
database: env('DATABASE_NAME', 'xpeditis_dev'),
|
|
||||||
// Même règle que data-source.ts : en production, pg_hba n'accepte que SSL.
|
|
||||||
ssl: process.env.DATABASE_SSL === 'true' ? { rejectUnauthorized: false } : false,
|
|
||||||
});
|
|
||||||
|
|
||||||
await client.connect();
|
|
||||||
try {
|
|
||||||
await client.query('BEGIN');
|
|
||||||
|
|
||||||
const existing = await client.query('SELECT "id" FROM "users" WHERE "email" = $1', [email]);
|
|
||||||
|
|
||||||
if (existing.rows.length > 0) {
|
|
||||||
// Réactiver ou promouvoir n'est jamais bloqué par le déclencheur
|
|
||||||
// « au moins un administrateur actif ».
|
|
||||||
await client.query(
|
|
||||||
`UPDATE "users"
|
|
||||||
SET "password_hash" = $2, "role" = 'ADMIN', "is_active" = true, "updated_at" = NOW()
|
|
||||||
WHERE "id" = $1`,
|
|
||||||
[existing.rows[0].id, passwordHash]
|
|
||||||
);
|
|
||||||
console.log(`Compte ${email} : mot de passe défini, rôle ADMIN, compte actif.`);
|
|
||||||
} else {
|
|
||||||
const organization = await client.query(
|
|
||||||
`INSERT INTO "organizations"
|
|
||||||
("name", "type", "address_street", "address_city", "address_postal_code", "address_country")
|
|
||||||
VALUES ($1, 'FREIGHT_FORWARDER', $2, $3, $4, $5)
|
|
||||||
ON CONFLICT ("name") DO UPDATE SET "updated_at" = NOW()
|
|
||||||
RETURNING "id"`,
|
|
||||||
[
|
|
||||||
env('BOOTSTRAP_ADMIN_ORG_NAME', 'Xpeditis'),
|
|
||||||
env('BOOTSTRAP_ADMIN_ORG_STREET', 'A completer'),
|
|
||||||
env('BOOTSTRAP_ADMIN_ORG_CITY', 'A completer'),
|
|
||||||
env('BOOTSTRAP_ADMIN_ORG_POSTAL_CODE', '00000'),
|
|
||||||
env('BOOTSTRAP_ADMIN_ORG_COUNTRY', 'FR').toUpperCase(),
|
|
||||||
]
|
|
||||||
);
|
|
||||||
await client.query(
|
|
||||||
`INSERT INTO "users"
|
|
||||||
("organization_id", "email", "password_hash", "role", "first_name", "last_name",
|
|
||||||
"is_email_verified", "is_active")
|
|
||||||
VALUES ($1, $2, $3, 'ADMIN', $4, $5, true, true)`,
|
|
||||||
[
|
|
||||||
organization.rows[0].id,
|
|
||||||
email,
|
|
||||||
passwordHash,
|
|
||||||
env('BOOTSTRAP_ADMIN_FIRST_NAME', 'Admin'),
|
|
||||||
env('BOOTSTRAP_ADMIN_LAST_NAME', 'Xpeditis'),
|
|
||||||
]
|
|
||||||
);
|
|
||||||
console.log(`Administrateur ${email} créé et actif.`);
|
|
||||||
}
|
|
||||||
|
|
||||||
await client.query('COMMIT');
|
|
||||||
console.log('Vous pouvez vous connecter. Changez ce mot de passe depuis l’interface si besoin.');
|
|
||||||
} catch (error) {
|
|
||||||
await client.query('ROLLBACK').catch(() => undefined);
|
|
||||||
throw error;
|
|
||||||
} finally {
|
|
||||||
await client.end();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
main().catch(error => {
|
|
||||||
console.error('Échec :', error.message);
|
|
||||||
process.exit(1);
|
|
||||||
});
|
|
||||||
@ -8,15 +8,12 @@
|
|||||||
* argument de ligne de commande (visible dans `ps` et dans l'historique du
|
* argument de ligne de commande (visible dans `ps` et dans l'historique du
|
||||||
* shell), ni variable d'environnement, ni fichier temporaire.
|
* shell), ni variable d'environnement, ni fichier temporaire.
|
||||||
*
|
*
|
||||||
* Le hash est appliqué à CHAQUE lancement du backend (AdminBootstrapService) :
|
* RAPPEL — le mode SANS mot de passe est préférable.
|
||||||
* - au compte BOOTSTRAP_ADMIN_EMAIL s'il ne s'est encore jamais connecté ;
|
* Si votre chaîne SMTP fonctionne, ne renseignez que BOOTSTRAP_ADMIN_EMAIL :
|
||||||
* - à tout compte si BOOTSTRAP_ADMIN_RESET_PASSWORD=true (retirez ensuite
|
* le compte est alors créé sans mot de passe utilisable et vous le définissez
|
||||||
* les deux variables, sinon un mot de passe changé depuis l'interface
|
* via « mot de passe oublié ». Aucun secret n'existe nulle part, il n'y a donc
|
||||||
* serait remplacé au lancement suivant).
|
* rien à faire fuiter. Ce script n'est utile que si vous devez pouvoir vous
|
||||||
*
|
* connecter avant que l'envoi de courriels ne soit opérationnel.
|
||||||
* Sans hash, le compte est créé sans mot de passe utilisable : il faut alors
|
|
||||||
* « mot de passe oublié » (SMTP requis) ou, sans SMTP, la commande de secours :
|
|
||||||
* docker exec -it <conteneur-backend> node admin-password.js <email>
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|||||||
@ -5,10 +5,10 @@
|
|||||||
|
|
||||||
const Stripe = require('stripe');
|
const Stripe = require('stripe');
|
||||||
|
|
||||||
if (!process.env.STRIPE_SECRET_KEY) {
|
const stripe = new Stripe(
|
||||||
throw new Error('STRIPE_SECRET_KEY is required');
|
process.env.STRIPE_SECRET_KEY ||
|
||||||
}
|
'sk_test_51R8p8R4atifoBlu1U9sMJh3rkQbO1G1xeguwFMQYMIMeaLNrTX7YFO5Ovu3P1VfbwcOoEmiy6I0UWi4DThNNzHG100YF75TnJr'
|
||||||
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
|
);
|
||||||
|
|
||||||
async function listPrices() {
|
async function listPrices() {
|
||||||
console.log('Fetching Stripe prices...\n');
|
console.log('Fetching Stripe prices...\n');
|
||||||
|
|||||||
@ -1,15 +1,5 @@
|
|||||||
const { DataSource } = require('typeorm');
|
const { DataSource } = require('typeorm');
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
const { existsSync } = require('fs');
|
|
||||||
const applicationRoot = existsSync(path.join(__dirname, 'dist'))
|
|
||||||
? __dirname
|
|
||||||
: path.resolve(__dirname, '../..');
|
|
||||||
const { databaseTlsOptions } = require(
|
|
||||||
path.join(applicationRoot, 'dist/infrastructure/persistence/typeorm/database-tls')
|
|
||||||
);
|
|
||||||
const { SafeDatabaseLogger } = require(
|
|
||||||
path.join(applicationRoot, 'dist/infrastructure/persistence/typeorm/safe-database-logger')
|
|
||||||
);
|
|
||||||
|
|
||||||
const AppDataSource = new DataSource({
|
const AppDataSource = new DataSource({
|
||||||
type: 'postgres',
|
type: 'postgres',
|
||||||
@ -18,19 +8,10 @@ const AppDataSource = new DataSource({
|
|||||||
username: process.env.DATABASE_USER,
|
username: process.env.DATABASE_USER,
|
||||||
password: process.env.DATABASE_PASSWORD,
|
password: process.env.DATABASE_PASSWORD,
|
||||||
database: process.env.DATABASE_NAME,
|
database: process.env.DATABASE_NAME,
|
||||||
ssl: databaseTlsOptions(
|
entities: [path.join(__dirname, 'dist/**/*.orm-entity.js')],
|
||||||
process.env.DATABASE_SSL,
|
migrations: [path.join(__dirname, 'dist/infrastructure/persistence/typeorm/migrations/*.js')],
|
||||||
process.env.DATABASE_SSL_CA,
|
|
||||||
process.env.DATABASE_HOST
|
|
||||||
),
|
|
||||||
entities: [path.join(applicationRoot, 'dist/**/*.orm-entity.js')],
|
|
||||||
migrations: [
|
|
||||||
path.join(applicationRoot, 'dist/infrastructure/persistence/typeorm/migrations/*.js'),
|
|
||||||
],
|
|
||||||
synchronize: false,
|
synchronize: false,
|
||||||
logging: true,
|
logging: true,
|
||||||
logger: new SafeDatabaseLogger(true),
|
|
||||||
migrationsTransactionMode: 'all',
|
|
||||||
});
|
});
|
||||||
|
|
||||||
console.log('🚀 Starting Xpeditis Backend Migration Script...');
|
console.log('🚀 Starting Xpeditis Backend Migration Script...');
|
||||||
@ -58,6 +39,6 @@ AppDataSource.initialize()
|
|||||||
})
|
})
|
||||||
.catch(error => {
|
.catch(error => {
|
||||||
console.error('❌ Error during migration:');
|
console.error('❌ Error during migration:');
|
||||||
console.error('Check migration prerequisites and database availability.');
|
console.error(error);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
});
|
});
|
||||||
|
|||||||
@ -4,17 +4,6 @@ const { Client } = require('pg');
|
|||||||
const { DataSource } = require('typeorm');
|
const { DataSource } = require('typeorm');
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
const { spawn } = require('child_process');
|
const { spawn } = require('child_process');
|
||||||
const { existsSync } = require('fs');
|
|
||||||
// Docker copies this script to /app/startup.js; local copies stay in scripts/setup.
|
|
||||||
const applicationRoot = existsSync(path.join(__dirname, 'dist'))
|
|
||||||
? __dirname
|
|
||||||
: path.resolve(__dirname, '../..');
|
|
||||||
const { databaseTlsOptions } = require(
|
|
||||||
path.join(applicationRoot, 'dist/infrastructure/persistence/typeorm/database-tls')
|
|
||||||
);
|
|
||||||
const { SafeDatabaseLogger } = require(
|
|
||||||
path.join(applicationRoot, 'dist/infrastructure/persistence/typeorm/safe-database-logger')
|
|
||||||
);
|
|
||||||
|
|
||||||
async function waitForPostgres(maxAttempts = 30) {
|
async function waitForPostgres(maxAttempts = 30) {
|
||||||
console.log('⏳ Waiting for PostgreSQL to be ready...');
|
console.log('⏳ Waiting for PostgreSQL to be ready...');
|
||||||
@ -27,11 +16,6 @@ async function waitForPostgres(maxAttempts = 30) {
|
|||||||
user: process.env.DATABASE_USER,
|
user: process.env.DATABASE_USER,
|
||||||
password: process.env.DATABASE_PASSWORD,
|
password: process.env.DATABASE_PASSWORD,
|
||||||
database: process.env.DATABASE_NAME,
|
database: process.env.DATABASE_NAME,
|
||||||
ssl: databaseTlsOptions(
|
|
||||||
process.env.DATABASE_SSL,
|
|
||||||
process.env.DATABASE_SSL_CA,
|
|
||||||
process.env.DATABASE_HOST
|
|
||||||
),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
await client.connect();
|
await client.connect();
|
||||||
@ -58,19 +42,10 @@ async function runMigrations() {
|
|||||||
username: process.env.DATABASE_USER,
|
username: process.env.DATABASE_USER,
|
||||||
password: process.env.DATABASE_PASSWORD,
|
password: process.env.DATABASE_PASSWORD,
|
||||||
database: process.env.DATABASE_NAME,
|
database: process.env.DATABASE_NAME,
|
||||||
ssl: databaseTlsOptions(
|
entities: [path.join(__dirname, 'dist/**/*.orm-entity.js')],
|
||||||
process.env.DATABASE_SSL,
|
migrations: [path.join(__dirname, 'dist/infrastructure/persistence/typeorm/migrations/*.js')],
|
||||||
process.env.DATABASE_SSL_CA,
|
|
||||||
process.env.DATABASE_HOST
|
|
||||||
),
|
|
||||||
entities: [path.join(applicationRoot, 'dist/**/*.orm-entity.js')],
|
|
||||||
migrations: [
|
|
||||||
path.join(applicationRoot, 'dist/infrastructure/persistence/typeorm/migrations/*.js'),
|
|
||||||
],
|
|
||||||
synchronize: false,
|
synchronize: false,
|
||||||
logging: true,
|
logging: true,
|
||||||
logger: new SafeDatabaseLogger(true),
|
|
||||||
migrationsTransactionMode: 'all',
|
|
||||||
});
|
});
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@ -92,7 +67,7 @@ async function runMigrations() {
|
|||||||
console.log('✅ Database migrations completed');
|
console.log('✅ Database migrations completed');
|
||||||
return true;
|
return true;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('❌ Migration failed. Check migration prerequisites and database availability.');
|
console.error('❌ Error during migration:', error);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -103,7 +78,6 @@ function startApplication() {
|
|||||||
const app = spawn('node', ['dist/main'], {
|
const app = spawn('node', ['dist/main'], {
|
||||||
stdio: 'inherit',
|
stdio: 'inherit',
|
||||||
env: process.env,
|
env: process.env,
|
||||||
cwd: applicationRoot,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
app.on('exit', code => {
|
app.on('exit', code => {
|
||||||
@ -122,11 +96,7 @@ async function main() {
|
|||||||
startApplication();
|
startApplication();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (require.main === module) {
|
main().catch(error => {
|
||||||
main().catch(error => {
|
console.error('❌ Startup failed:', error);
|
||||||
console.error('❌ Startup failed. Check migration prerequisites and database availability.');
|
process.exit(1);
|
||||||
process.exit(1);
|
});
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { waitForPostgres, runMigrations };
|
|
||||||
|
|||||||
@ -1,5 +1,3 @@
|
|||||||
import { SafeDatabaseLogger } from './infrastructure/persistence/typeorm/safe-database-logger';
|
|
||||||
import { safeHttpSerializers } from './application/logging/safe-http-log';
|
|
||||||
import { TradeAssistantModule } from './application/trade-assistant/trade-assistant.module';
|
import { TradeAssistantModule } from './application/trade-assistant/trade-assistant.module';
|
||||||
import { McpModule } from './application/mcp/mcp.module';
|
import { McpModule } from './application/mcp/mcp.module';
|
||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
@ -18,7 +16,6 @@ import {
|
|||||||
import * as path from 'path';
|
import * as path from 'path';
|
||||||
import * as Joi from 'joi';
|
import * as Joi from 'joi';
|
||||||
import { UserPreferenceResolver } from './infrastructure/i18n/user-preference.resolver';
|
import { UserPreferenceResolver } from './infrastructure/i18n/user-preference.resolver';
|
||||||
import { databaseTlsOptions } from './infrastructure/persistence/typeorm/database-tls';
|
|
||||||
|
|
||||||
// Import feature modules
|
// Import feature modules
|
||||||
import { AuthModule } from './application/auth/auth.module';
|
import { AuthModule } from './application/auth/auth.module';
|
||||||
@ -42,7 +39,6 @@ import { CacheModule } from './infrastructure/cache/cache.module';
|
|||||||
import { CarrierModule } from './infrastructure/carriers/carrier.module';
|
import { CarrierModule } from './infrastructure/carriers/carrier.module';
|
||||||
import { SecurityModule } from './infrastructure/security/security.module';
|
import { SecurityModule } from './infrastructure/security/security.module';
|
||||||
import { CsvRateModule } from './infrastructure/carriers/csv-loader/csv-rate.module';
|
import { CsvRateModule } from './infrastructure/carriers/csv-loader/csv-rate.module';
|
||||||
import { AdminBootstrapModule } from './infrastructure/persistence/typeorm/admin-bootstrap.module';
|
|
||||||
|
|
||||||
// Import global guards
|
// Import global guards
|
||||||
import { ApiKeyOrJwtGuard } from './application/guards/api-key-or-jwt.guard';
|
import { ApiKeyOrJwtGuard } from './application/guards/api-key-or-jwt.guard';
|
||||||
@ -65,8 +61,6 @@ import { CustomThrottlerGuard } from './application/guards/throttle.guard';
|
|||||||
DATABASE_USER: Joi.string().required(),
|
DATABASE_USER: Joi.string().required(),
|
||||||
DATABASE_PASSWORD: Joi.string().required(),
|
DATABASE_PASSWORD: Joi.string().required(),
|
||||||
DATABASE_NAME: Joi.string().required(),
|
DATABASE_NAME: Joi.string().required(),
|
||||||
DATABASE_SSL: Joi.boolean().default(false),
|
|
||||||
DATABASE_SSL_CA: Joi.string().optional(),
|
|
||||||
REDIS_HOST: Joi.string().required(),
|
REDIS_HOST: Joi.string().required(),
|
||||||
REDIS_PORT: Joi.number().default(6379),
|
REDIS_PORT: Joi.number().default(6379),
|
||||||
REDIS_PASSWORD: Joi.string().required(),
|
REDIS_PASSWORD: Joi.string().required(),
|
||||||
@ -103,13 +97,6 @@ import { CustomThrottlerGuard } from './application/guards/throttle.guard';
|
|||||||
STRIPE_PLATINIUM_MONTHLY_PRICE_ID: Joi.string().optional(),
|
STRIPE_PLATINIUM_MONTHLY_PRICE_ID: Joi.string().optional(),
|
||||||
STRIPE_PLATINIUM_YEARLY_PRICE_ID: Joi.string().optional(),
|
STRIPE_PLATINIUM_YEARLY_PRICE_ID: Joi.string().optional(),
|
||||||
LOG_EXPORTER_URL: Joi.string().uri().default('http://xpeditis-log-exporter:3200'),
|
LOG_EXPORTER_URL: Joi.string().uri().default('http://xpeditis-log-exporter:3200'),
|
||||||
// Administrateur garanti a chaque lancement (AdminBootstrapService).
|
|
||||||
// Pas de .email() ici : Joi rejette les TLD hors liste IANA et une
|
|
||||||
// adresse refusee empecherait l'API entiere de demarrer. Le service
|
|
||||||
// valide l'adresse et journalise une erreur sans bloquer.
|
|
||||||
BOOTSTRAP_ADMIN_EMAIL: Joi.string().allow('').optional(),
|
|
||||||
BOOTSTRAP_ADMIN_PASSWORD_HASH: Joi.string().allow('').optional(),
|
|
||||||
BOOTSTRAP_ADMIN_RESET_PASSWORD: Joi.string().valid('true', 'false', '').default('false'),
|
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
|
|
||||||
@ -123,7 +110,6 @@ import { CustomThrottlerGuard } from './application/guards/throttle.guard';
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
pinoHttp: {
|
pinoHttp: {
|
||||||
serializers: safeHttpSerializers,
|
|
||||||
transport: usePretty
|
transport: usePretty
|
||||||
? {
|
? {
|
||||||
target: 'pino-pretty',
|
target: 'pino-pretty',
|
||||||
@ -184,15 +170,9 @@ import { CustomThrottlerGuard } from './application/guards/throttle.guard';
|
|||||||
username: configService.get('DATABASE_USER'),
|
username: configService.get('DATABASE_USER'),
|
||||||
password: configService.get('DATABASE_PASSWORD'),
|
password: configService.get('DATABASE_PASSWORD'),
|
||||||
database: configService.get('DATABASE_NAME'),
|
database: configService.get('DATABASE_NAME'),
|
||||||
ssl: databaseTlsOptions(
|
|
||||||
configService.get<boolean>('DATABASE_SSL'),
|
|
||||||
configService.get<string>('DATABASE_SSL_CA'),
|
|
||||||
configService.get<string>('DATABASE_HOST')
|
|
||||||
),
|
|
||||||
entities: [__dirname + '/**/*.orm-entity{.ts,.js}'],
|
entities: [__dirname + '/**/*.orm-entity{.ts,.js}'],
|
||||||
synchronize: false, // ✅ Force false - use migrations instead
|
synchronize: false, // ✅ Force false - use migrations instead
|
||||||
logging: configService.get('DATABASE_LOGGING', false),
|
logging: configService.get('DATABASE_LOGGING', false),
|
||||||
logger: new SafeDatabaseLogger(configService.get('DATABASE_LOGGING', false)),
|
|
||||||
autoLoadEntities: true, // Auto-load entities from forFeature()
|
autoLoadEntities: true, // Auto-load entities from forFeature()
|
||||||
}),
|
}),
|
||||||
inject: [ConfigService],
|
inject: [ConfigService],
|
||||||
@ -203,8 +183,6 @@ import { CustomThrottlerGuard } from './application/guards/throttle.guard';
|
|||||||
CacheModule,
|
CacheModule,
|
||||||
CarrierModule,
|
CarrierModule,
|
||||||
CsvRateModule,
|
CsvRateModule,
|
||||||
// Un administrateur exploitable a chaque lancement (base neuve comprise)
|
|
||||||
AdminBootstrapModule,
|
|
||||||
|
|
||||||
// Feature modules
|
// Feature modules
|
||||||
AuthModule,
|
AuthModule,
|
||||||
|
|||||||
@ -35,9 +35,6 @@ import { BlogModule } from '../blog/blog.module';
|
|||||||
// Storage
|
// Storage
|
||||||
import { StorageModule } from '@infrastructure/storage/storage.module';
|
import { StorageModule } from '@infrastructure/storage/storage.module';
|
||||||
|
|
||||||
// User deletion (GDPR erasure)
|
|
||||||
import { GDPRModule } from '../gdpr/gdpr.module';
|
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
TypeOrmModule.forFeature([UserOrmEntity, OrganizationOrmEntity, CsvBookingOrmEntity]),
|
TypeOrmModule.forFeature([UserOrmEntity, OrganizationOrmEntity, CsvBookingOrmEntity]),
|
||||||
@ -46,7 +43,6 @@ import { GDPRModule } from '../gdpr/gdpr.module';
|
|||||||
EmailModule,
|
EmailModule,
|
||||||
BlogModule,
|
BlogModule,
|
||||||
StorageModule,
|
StorageModule,
|
||||||
GDPRModule,
|
|
||||||
],
|
],
|
||||||
controllers: [AdminController],
|
controllers: [AdminController],
|
||||||
providers: [
|
providers: [
|
||||||
|
|||||||
@ -1,88 +0,0 @@
|
|||||||
import { ForbiddenException } from '@nestjs/common';
|
|
||||||
import { ApiKey } from '@domain/entities/api-key.entity';
|
|
||||||
import { Subscription } from '@domain/entities/subscription.entity';
|
|
||||||
import { SubscriptionPlan } from '@domain/value-objects/subscription-plan.vo';
|
|
||||||
import {
|
|
||||||
SubscriptionStatus,
|
|
||||||
SubscriptionStatusType,
|
|
||||||
} from '@domain/value-objects/subscription-status.vo';
|
|
||||||
import { ApiKeyRepository } from '@domain/ports/out/api-key.repository';
|
|
||||||
import { UserRepository } from '@domain/ports/out/user.repository';
|
|
||||||
import { SubscriptionRepository } from '@domain/ports/out/subscription.repository';
|
|
||||||
import { ApiKeysService } from './api-keys.service';
|
|
||||||
|
|
||||||
describe('API key current entitlement', () => {
|
|
||||||
const setup = () => {
|
|
||||||
let subscription = Subscription.create({
|
|
||||||
id: 'sub',
|
|
||||||
organizationId: 'org',
|
|
||||||
plan: SubscriptionPlan.gold(),
|
|
||||||
});
|
|
||||||
const key = ApiKey.create({
|
|
||||||
id: 'key',
|
|
||||||
userId: 'user',
|
|
||||||
organizationId: 'org',
|
|
||||||
name: 'test',
|
|
||||||
keyHash: 'hash',
|
|
||||||
keyPrefix: 'xped_live_test',
|
|
||||||
});
|
|
||||||
const keys = {
|
|
||||||
findByKeyHash: jest.fn().mockResolvedValue(key),
|
|
||||||
save: jest.fn().mockImplementation(async value => value),
|
|
||||||
};
|
|
||||||
const users = {
|
|
||||||
findById: jest
|
|
||||||
.fn()
|
|
||||||
.mockResolvedValue({ id: 'user', organizationId: 'org', isActive: true, role: 'MANAGER' }),
|
|
||||||
};
|
|
||||||
const subscriptions = {
|
|
||||||
findByOrganizationId: jest.fn().mockImplementation(async () => subscription),
|
|
||||||
};
|
|
||||||
return {
|
|
||||||
service: new ApiKeysService(
|
|
||||||
keys as unknown as ApiKeyRepository,
|
|
||||||
users as unknown as UserRepository,
|
|
||||||
subscriptions as unknown as SubscriptionRepository
|
|
||||||
),
|
|
||||||
keys,
|
|
||||||
setStatus: (status: SubscriptionStatusType) => {
|
|
||||||
subscription = subscription.updateStatus(SubscriptionStatus.create(status));
|
|
||||||
},
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
it.each<SubscriptionStatusType>([
|
|
||||||
'UNPAID',
|
|
||||||
'PAUSED',
|
|
||||||
'INCOMPLETE',
|
|
||||||
'INCOMPLETE_EXPIRED',
|
|
||||||
'CANCELED',
|
|
||||||
])('%s invalidates an existing key and forbids creation', async status => {
|
|
||||||
const { service, keys, setStatus } = setup();
|
|
||||||
await expect(service.validateAndGetUser('xped_live_test')).resolves.toMatchObject({
|
|
||||||
plan: 'GOLD',
|
|
||||||
});
|
|
||||||
keys.save.mockClear();
|
|
||||||
setStatus(status);
|
|
||||||
await expect(service.validateAndGetUser('xped_live_test')).resolves.toBeNull();
|
|
||||||
await expect(service.generateApiKey('user', 'org', { name: 'new' })).rejects.toBeInstanceOf(
|
|
||||||
ForbiddenException
|
|
||||||
);
|
|
||||||
expect(keys.save).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it.each<SubscriptionStatusType>(['ACTIVE', 'TRIALING', 'PAST_DUE'])(
|
|
||||||
'%s permits keys',
|
|
||||||
async status => {
|
|
||||||
const { service, setStatus } = setup();
|
|
||||||
setStatus(status);
|
|
||||||
await expect(service.validateAndGetUser('xped_live_test')).resolves.toMatchObject({
|
|
||||||
plan: 'GOLD',
|
|
||||||
});
|
|
||||||
await expect(service.generateApiKey('user', 'org', { name: 'new' })).resolves.toMatchObject({
|
|
||||||
name: 'new',
|
|
||||||
isActive: true,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
);
|
|
||||||
});
|
|
||||||
@ -154,8 +154,8 @@ export class ApiKeysService {
|
|||||||
organizationId: user.organizationId,
|
organizationId: user.organizationId,
|
||||||
firstName: user.firstName,
|
firstName: user.firstName,
|
||||||
lastName: user.lastName,
|
lastName: user.lastName,
|
||||||
plan: subscription.accessPlan.value,
|
plan: subscription.plan.value,
|
||||||
planFeatures: [...subscription.accessPlan.planFeatures],
|
planFeatures: [...subscription.plan.planFeatures],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -1,69 +0,0 @@
|
|||||||
import { ConfigService } from '@nestjs/config';
|
|
||||||
import { JwtService } from '@nestjs/jwt';
|
|
||||||
import { Repository } from 'typeorm';
|
|
||||||
import { AuthService, JwtPayload } from './auth.service';
|
|
||||||
import { User, UserRole } from '@domain/entities/user.entity';
|
|
||||||
import { UserRepository } from '@domain/ports/out/user.repository';
|
|
||||||
import { OrganizationRepository } from '@domain/ports/out/organization.repository';
|
|
||||||
import { EmailPort } from '@domain/ports/out/email.port';
|
|
||||||
import { CachePort } from '@domain/ports/out/cache.port';
|
|
||||||
import { PasswordResetTokenOrmEntity } from '@infrastructure/persistence/typeorm/entities/password-reset-token.orm-entity';
|
|
||||||
import { SubscriptionService } from '../services/subscription.service';
|
|
||||||
|
|
||||||
jest.mock('argon2', () => ({ verify: jest.fn().mockResolvedValue(true) }));
|
|
||||||
|
|
||||||
describe('password-bound sessions', () => {
|
|
||||||
let user: User;
|
|
||||||
let auth: AuthService;
|
|
||||||
let jwt: JwtService;
|
|
||||||
beforeEach(() => {
|
|
||||||
user = User.create({
|
|
||||||
id: 'user-1',
|
|
||||||
organizationId: 'org-1',
|
|
||||||
email: 'test@example.org',
|
|
||||||
firstName: 'Test',
|
|
||||||
lastName: 'User',
|
|
||||||
role: UserRole.ADMIN,
|
|
||||||
passwordHash: 'old-salted-hash',
|
|
||||||
});
|
|
||||||
jwt = new JwtService({ secret: 'test-only-session-secret' });
|
|
||||||
auth = new AuthService(
|
|
||||||
{
|
|
||||||
findById: jest.fn(async () => user),
|
|
||||||
findByEmail: jest.fn(async () => user),
|
|
||||||
} as unknown as UserRepository,
|
|
||||||
{} as OrganizationRepository,
|
|
||||||
{} as EmailPort,
|
|
||||||
{ get: jest.fn(async () => null) } as unknown as CachePort,
|
|
||||||
{} as Repository<PasswordResetTokenOrmEntity>,
|
|
||||||
jwt,
|
|
||||||
new ConfigService({ JWT_SECRET: 'test-only-session-secret' }),
|
|
||||||
{} as SubscriptionService
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('rejects old access and refresh tokens after a password change, but accepts a new login', async () => {
|
|
||||||
const tokens = await auth.login(user.email, 'password');
|
|
||||||
const payload = jwt.verify<JwtPayload>(tokens.accessToken);
|
|
||||||
expect(await auth.validateUser(payload)).toBe(user);
|
|
||||||
expect(payload.credentialVersion).not.toContain(user.passwordHash);
|
|
||||||
user.updatePassword('new-salted-hash');
|
|
||||||
expect(await auth.validateUser(payload)).toBeNull();
|
|
||||||
await expect(auth.refreshAccessToken(tokens.refreshToken)).rejects.toThrow();
|
|
||||||
const fresh = await auth.login(user.email, 'new-password');
|
|
||||||
expect(await auth.validateUser(jwt.verify<JwtPayload>(fresh.accessToken))).toBe(user);
|
|
||||||
await expect(auth.refreshAccessToken(fresh.refreshToken)).resolves.toHaveProperty(
|
|
||||||
'accessToken'
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('preserves sessions after a profile change and rejects legacy or disabled sessions', async () => {
|
|
||||||
const tokens = await auth.login(user.email, 'password');
|
|
||||||
const payload = jwt.verify<JwtPayload>(tokens.accessToken);
|
|
||||||
user.updateFirstName('New name');
|
|
||||||
expect(await auth.validateUser(payload)).toBe(user);
|
|
||||||
expect(await auth.validateUser({ ...payload, credentialVersion: undefined })).toBeNull();
|
|
||||||
user.deactivate();
|
|
||||||
expect(await auth.validateUser(payload)).toBeNull();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@ -1,5 +1,5 @@
|
|||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
import { JwtModule, JwtSignOptions } from '@nestjs/jwt';
|
import { JwtModule } from '@nestjs/jwt';
|
||||||
import { PassportModule } from '@nestjs/passport';
|
import { PassportModule } from '@nestjs/passport';
|
||||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
@ -36,7 +36,7 @@ import { AuditModule } from '../audit/audit.module';
|
|||||||
useFactory: async (configService: ConfigService) => ({
|
useFactory: async (configService: ConfigService) => ({
|
||||||
secret: configService.get<string>('JWT_SECRET'),
|
secret: configService.get<string>('JWT_SECRET'),
|
||||||
signOptions: {
|
signOptions: {
|
||||||
expiresIn: configService.get<JwtSignOptions['expiresIn']>('JWT_ACCESS_EXPIRATION', '15m'),
|
expiresIn: configService.get<string>('JWT_ACCESS_EXPIRATION', '15m'),
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
|
|||||||
@ -35,7 +35,6 @@ export interface JwtPayload {
|
|||||||
plan?: string; // subscription plan (BRONZE, SILVER, GOLD, PLATINIUM)
|
plan?: string; // subscription plan (BRONZE, SILVER, GOLD, PLATINIUM)
|
||||||
planFeatures?: string[]; // plan feature flags
|
planFeatures?: string[]; // plan feature flags
|
||||||
type: 'access' | 'refresh';
|
type: 'access' | 'refresh';
|
||||||
credentialVersion?: string;
|
|
||||||
rememberMe?: boolean; // drives auth cookie persistence across refreshes
|
rememberMe?: boolean; // drives auth cookie persistence across refreshes
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -208,16 +207,6 @@ export class AuthService {
|
|||||||
throw new UnauthorizedException('Invalid credentials');
|
throw new UnauthorizedException('Invalid credentials');
|
||||||
}
|
}
|
||||||
|
|
||||||
// last_login_at n'etait jamais renseigne. L'amorcage de l'administrateur
|
|
||||||
// s'en sert pour ne jamais ecraser le mot de passe d'un compte deja utilise.
|
|
||||||
try {
|
|
||||||
user.recordLogin();
|
|
||||||
await this.userRepository.save(user);
|
|
||||||
} catch (error: unknown) {
|
|
||||||
const message = error instanceof Error ? error.message : String(error);
|
|
||||||
this.logger.warn(`Could not record last login for ${email}: ${message}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const tokens = await this.generateTokens(user, rememberMe);
|
const tokens = await this.generateTokens(user, rememberMe);
|
||||||
|
|
||||||
this.logger.log(`User logged in successfully: ${email}`);
|
this.logger.log(`User logged in successfully: ${email}`);
|
||||||
@ -254,7 +243,7 @@ export class AuthService {
|
|||||||
throw new UnauthorizedException('Refresh token has been revoked');
|
throw new UnauthorizedException('Refresh token has been revoked');
|
||||||
}
|
}
|
||||||
|
|
||||||
const user = await this.validateUser(payload);
|
const user = await this.userRepository.findById(payload.sub);
|
||||||
|
|
||||||
if (!user || !user.isActive) {
|
if (!user || !user.isActive) {
|
||||||
throw new UnauthorizedException('User not found or inactive');
|
throw new UnauthorizedException('User not found or inactive');
|
||||||
@ -414,22 +403,13 @@ export class AuthService {
|
|||||||
async validateUser(payload: JwtPayload): Promise<User | null> {
|
async validateUser(payload: JwtPayload): Promise<User | null> {
|
||||||
const user = await this.userRepository.findById(payload.sub);
|
const user = await this.userRepository.findById(payload.sub);
|
||||||
|
|
||||||
if (!user || !user.isActive || payload.credentialVersion !== this.credentialVersion(user)) {
|
if (!user || !user.isActive) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return user;
|
return user;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Bind sessions to the current password hash without exposing the hash in JWTs.
|
|
||||||
// Tokens minted before this binding was introduced require a fresh login.
|
|
||||||
private credentialVersion(user: User): string {
|
|
||||||
return crypto
|
|
||||||
.createHmac('sha256', this.configService.getOrThrow<string>('JWT_SECRET'))
|
|
||||||
.update(JSON.stringify(['credential-version-v1', user.id, user.passwordHash]))
|
|
||||||
.digest('hex');
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Generate access and refresh tokens
|
* Generate access and refresh tokens
|
||||||
*/
|
*/
|
||||||
@ -457,8 +437,8 @@ export class AuthService {
|
|||||||
const subscription = await this.subscriptionService.getOrCreateSubscription(
|
const subscription = await this.subscriptionService.getOrCreateSubscription(
|
||||||
user.organizationId
|
user.organizationId
|
||||||
);
|
);
|
||||||
plan = subscription.accessPlan.value;
|
plan = subscription.plan.value;
|
||||||
planFeatures = [...subscription.accessPlan.planFeatures];
|
planFeatures = [...subscription.plan.planFeatures];
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.logger.warn(`Failed to fetch subscription for JWT: ${error}`);
|
this.logger.warn(`Failed to fetch subscription for JWT: ${error}`);
|
||||||
}
|
}
|
||||||
@ -472,7 +452,6 @@ export class AuthService {
|
|||||||
plan,
|
plan,
|
||||||
planFeatures,
|
planFeatures,
|
||||||
type: 'access',
|
type: 'access',
|
||||||
credentialVersion: this.credentialVersion(user),
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const refreshPayload: JwtPayload = {
|
const refreshPayload: JwtPayload = {
|
||||||
@ -483,7 +462,6 @@ export class AuthService {
|
|||||||
plan,
|
plan,
|
||||||
planFeatures,
|
planFeatures,
|
||||||
type: 'refresh',
|
type: 'refresh',
|
||||||
credentialVersion: this.credentialVersion(user),
|
|
||||||
rememberMe,
|
rememberMe,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@ -13,7 +13,6 @@ export interface JwtPayload {
|
|||||||
role: string;
|
role: string;
|
||||||
organizationId: string;
|
organizationId: string;
|
||||||
type: 'access' | 'refresh';
|
type: 'access' | 'refresh';
|
||||||
credentialVersion?: string;
|
|
||||||
iat?: number; // issued at
|
iat?: number; // issued at
|
||||||
exp?: number; // expiration
|
exp?: number; // expiration
|
||||||
}
|
}
|
||||||
|
|||||||
@ -75,11 +75,6 @@ import type { BlogPostCategory } from '@domain/entities/blog-post.entity';
|
|||||||
// Storage imports
|
// Storage imports
|
||||||
import { StoragePort, STORAGE_PORT } from '@domain/ports/out/storage.port';
|
import { StoragePort, STORAGE_PORT } from '@domain/ports/out/storage.port';
|
||||||
|
|
||||||
// User deletion
|
|
||||||
import { UserDeletionService } from '../services/user-deletion.service';
|
|
||||||
import { AdminContinuityService } from '../services/admin-continuity.service';
|
|
||||||
import { isAnonymisedEmail } from '@domain/services/data-retention';
|
|
||||||
|
|
||||||
const BLOG_IMAGES_BUCKET = 'xpeditis-blog';
|
const BLOG_IMAGES_BUCKET = 'xpeditis-blog';
|
||||||
const ALLOWED_IMAGE_MIMETYPES = [
|
const ALLOWED_IMAGE_MIMETYPES = [
|
||||||
'image/jpeg',
|
'image/jpeg',
|
||||||
@ -116,9 +111,7 @@ export class AdminController {
|
|||||||
private readonly siretVerificationPort: SiretVerificationPort,
|
private readonly siretVerificationPort: SiretVerificationPort,
|
||||||
@Inject(EMAIL_PORT) private readonly emailPort: EmailPort,
|
@Inject(EMAIL_PORT) private readonly emailPort: EmailPort,
|
||||||
private readonly blogService: BlogService,
|
private readonly blogService: BlogService,
|
||||||
@Inject(STORAGE_PORT) private readonly storage: StoragePort,
|
@Inject(STORAGE_PORT) private readonly storage: StoragePort
|
||||||
private readonly userDeletionService: UserDeletionService,
|
|
||||||
private readonly adminContinuity: AdminContinuityService
|
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
// ==================== USERS ENDPOINTS ====================
|
// ==================== USERS ENDPOINTS ====================
|
||||||
@ -150,9 +143,7 @@ export class AdminController {
|
|||||||
async getAllUsers(@CurrentUser() user: UserPayload): Promise<UserListResponseDto> {
|
async getAllUsers(@CurrentUser() user: UserPayload): Promise<UserListResponseDto> {
|
||||||
this.logger.log(`[ADMIN: ${user.email}] Fetching ALL users from database`);
|
this.logger.log(`[ADMIN: ${user.email}] Fetching ALL users from database`);
|
||||||
|
|
||||||
// Erased accounts stay in the table (their bookings reference them) but are
|
let users = await this.userRepository.findAll();
|
||||||
// no longer users: they must not come back in the list after a deletion.
|
|
||||||
let users = (await this.userRepository.findAll()).filter(u => !isAnonymisedEmail(u.email));
|
|
||||||
|
|
||||||
// Security: Non-admin users (MANAGER and below) cannot see ADMIN users
|
// Security: Non-admin users (MANAGER and below) cannot see ADMIN users
|
||||||
if (user.role !== 'ADMIN') {
|
if (user.role !== 'ADMIN') {
|
||||||
@ -246,12 +237,6 @@ export class AdminController {
|
|||||||
throw new BadRequestException('You cannot change your own role');
|
throw new BadRequestException('You cannot change your own role');
|
||||||
}
|
}
|
||||||
|
|
||||||
// At least one active admin must remain: refuse demoting or deactivating the last one
|
|
||||||
await this.adminContinuity.assertKeepsAnActiveAdmin(foundUser, {
|
|
||||||
role: dto.role ?? foundUser.role,
|
|
||||||
isActive: dto.isActive ?? foundUser.isActive,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Apply updates
|
// Apply updates
|
||||||
if (dto.firstName) {
|
if (dto.firstName) {
|
||||||
foundUser.updateFirstName(dto.firstName);
|
foundUser.updateFirstName(dto.firstName);
|
||||||
@ -283,10 +268,7 @@ export class AdminController {
|
|||||||
@HttpCode(HttpStatus.NO_CONTENT)
|
@HttpCode(HttpStatus.NO_CONTENT)
|
||||||
@ApiOperation({
|
@ApiOperation({
|
||||||
summary: 'Delete user (Admin only)',
|
summary: 'Delete user (Admin only)',
|
||||||
description:
|
description: 'Permanently delete a user from the database',
|
||||||
'Erase a user (any role, including another ADMIN): personal data is deleted or anonymised, ' +
|
|
||||||
'the account is disabled and its license revoked. Bookings are kept. ' +
|
|
||||||
'An admin cannot delete their own account here, nor the last active admin.',
|
|
||||||
})
|
})
|
||||||
@ApiParam({
|
@ApiParam({
|
||||||
name: 'id',
|
name: 'id',
|
||||||
@ -305,7 +287,12 @@ export class AdminController {
|
|||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
this.logger.log(`[ADMIN: ${user.email}] Deleting user: ${id}`);
|
this.logger.log(`[ADMIN: ${user.email}] Deleting user: ${id}`);
|
||||||
|
|
||||||
await this.userDeletionService.deleteByAdmin(id, user);
|
const foundUser = await this.userRepository.findById(id);
|
||||||
|
if (!foundUser) {
|
||||||
|
throw new NotFoundException(`User ${id} not found`);
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.userRepository.deleteById(id);
|
||||||
this.logger.log(`[ADMIN] User deleted successfully: ${id}`);
|
this.logger.log(`[ADMIN] User deleted successfully: ${id}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -802,8 +789,12 @@ export class AdminController {
|
|||||||
this.logger.log(`[ADMIN: ${user.email}] Sending test email to ${body.to}`);
|
this.logger.log(`[ADMIN: ${user.email}] Sending test email to ${body.to}`);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Même gabarit que les vrais emails : le test valide aussi leur affichage.
|
await this.emailPort.send({
|
||||||
await this.emailPort.sendSmtpTest(body.to, user.email);
|
to: body.to,
|
||||||
|
subject: '[Xpeditis] Test SMTP',
|
||||||
|
html: `<p>Email de test envoyé depuis le panel admin par <strong>${user.email}</strong>.</p><p>Si vous lisez ceci, la configuration SMTP fonctionne correctement.</p>`,
|
||||||
|
text: `Email de test envoyé par ${user.email}. Si vous lisez ceci, le SMTP fonctionne.`,
|
||||||
|
});
|
||||||
|
|
||||||
this.logger.log(`[ADMIN] Test email sent successfully to ${body.to}`);
|
this.logger.log(`[ADMIN] Test email sent successfully to ${body.to}`);
|
||||||
return { success: true, message: `Email envoyé avec succès à ${body.to}` };
|
return { success: true, message: `Email envoyé avec succès à ${body.to}` };
|
||||||
|
|||||||
@ -25,9 +25,9 @@ class AuditLogResponseDto {
|
|||||||
id: string;
|
id: string;
|
||||||
action: string;
|
action: string;
|
||||||
status: string;
|
status: string;
|
||||||
userId: string | null;
|
userId: string;
|
||||||
userEmail: string;
|
userEmail: string;
|
||||||
organizationId: string | null;
|
organizationId: string;
|
||||||
resourceType?: string;
|
resourceType?: string;
|
||||||
resourceId?: string;
|
resourceId?: string;
|
||||||
resourceName?: string;
|
resourceName?: string;
|
||||||
|
|||||||
@ -43,6 +43,18 @@ import {
|
|||||||
|
|
||||||
const REFRESH_COOKIE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000; // 7 days
|
const REFRESH_COOKIE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000; // 7 days
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Escape user-provided text before interpolating it into HTML emails
|
||||||
|
*/
|
||||||
|
function escapeHtml(value: string): string {
|
||||||
|
return value
|
||||||
|
.replace(/&/g, '&')
|
||||||
|
.replace(/</g, '<')
|
||||||
|
.replace(/>/g, '>')
|
||||||
|
.replace(/"/g, '"')
|
||||||
|
.replace(/'/g, ''');
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Authentication Controller
|
* Authentication Controller
|
||||||
*
|
*
|
||||||
@ -250,13 +262,12 @@ export class AuthController {
|
|||||||
};
|
};
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
// Audit log: record failed login attempts (the attempted email is the
|
// Audit log: record failed login attempts (the attempted email is the
|
||||||
// only identity we have — the credentials did not match a valid user,
|
// only identity we have — the credentials did not match a valid user)
|
||||||
// so user and organization are recorded as null)
|
|
||||||
await this.auditService.logFailure(
|
await this.auditService.logFailure(
|
||||||
AuditAction.USER_LOGIN,
|
AuditAction.USER_LOGIN,
|
||||||
null,
|
'unknown',
|
||||||
dto.email,
|
dto.email,
|
||||||
null,
|
'unknown',
|
||||||
error?.message || 'Invalid credentials',
|
error?.message || 'Invalid credentials',
|
||||||
{
|
{
|
||||||
resourceType: 'user',
|
resourceType: 'user',
|
||||||
@ -314,16 +325,7 @@ export class AuthController {
|
|||||||
throw new UnauthorizedException('No refresh token provided');
|
throw new UnauthorizedException('No refresh token provided');
|
||||||
}
|
}
|
||||||
|
|
||||||
let result: Awaited<ReturnType<typeof this.authService.refreshAccessToken>>;
|
const result = await this.authService.refreshAccessToken(refreshToken);
|
||||||
try {
|
|
||||||
result = await this.authService.refreshAccessToken(refreshToken);
|
|
||||||
} catch (error) {
|
|
||||||
// The refresh token is expired/revoked: wipe every auth cookie (including
|
|
||||||
// the readable session flag) so the client stops believing a session
|
|
||||||
// exists. Without this the frontend keeps retrying and reloading.
|
|
||||||
this.clearAuthCookies(res);
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.setAuthCookies(res, result, result.rememberMe);
|
this.setAuthCookies(res, result, result.rememberMe);
|
||||||
|
|
||||||
@ -402,16 +404,53 @@ export class AuthController {
|
|||||||
other: 'Autre',
|
other: 'Autre',
|
||||||
};
|
};
|
||||||
|
|
||||||
// Le gabarit échappe lui-même chaque champ saisi par le visiteur.
|
const subjectLabel = escapeHtml(subjectLabels[dto.subject] || dto.subject);
|
||||||
|
const firstName = escapeHtml(dto.firstName);
|
||||||
|
const lastName = escapeHtml(dto.lastName);
|
||||||
|
const email = escapeHtml(dto.email);
|
||||||
|
const company = dto.company ? escapeHtml(dto.company) : undefined;
|
||||||
|
const phone = dto.phone ? escapeHtml(dto.phone) : undefined;
|
||||||
|
const message = escapeHtml(dto.message);
|
||||||
|
|
||||||
|
const html = `
|
||||||
|
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
|
||||||
|
<div style="background: #10183A; padding: 24px; border-radius: 8px 8px 0 0;">
|
||||||
|
<h1 style="color: #34CCCD; margin: 0; font-size: 20px;">Nouveau message de contact</h1>
|
||||||
|
</div>
|
||||||
|
<div style="background: #f9f9f9; padding: 24px; border: 1px solid #e0e0e0;">
|
||||||
|
<table style="width: 100%; border-collapse: collapse;">
|
||||||
|
<tr>
|
||||||
|
<td style="padding: 8px 0; color: #666; width: 130px; font-size: 14px;">Nom</td>
|
||||||
|
<td style="padding: 8px 0; color: #222; font-weight: bold; font-size: 14px;">${firstName} ${lastName}</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td style="padding: 8px 0; color: #666; font-size: 14px;">Email</td>
|
||||||
|
<td style="padding: 8px 0; font-size: 14px;"><a href="mailto:${email}" style="color: #34CCCD;">${email}</a></td>
|
||||||
|
</tr>
|
||||||
|
${company ? `<tr><td style="padding: 8px 0; color: #666; font-size: 14px;">Entreprise</td><td style="padding: 8px 0; color: #222; font-size: 14px;">${company}</td></tr>` : ''}
|
||||||
|
${phone ? `<tr><td style="padding: 8px 0; color: #666; font-size: 14px;">Téléphone</td><td style="padding: 8px 0; color: #222; font-size: 14px;">${phone}</td></tr>` : ''}
|
||||||
|
<tr>
|
||||||
|
<td style="padding: 8px 0; color: #666; font-size: 14px;">Sujet</td>
|
||||||
|
<td style="padding: 8px 0; color: #222; font-size: 14px;">${subjectLabel}</td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
<div style="margin-top: 16px; padding-top: 16px; border-top: 1px solid #ddd;">
|
||||||
|
<p style="color: #666; font-size: 14px; margin: 0 0 8px 0;">Message :</p>
|
||||||
|
<p style="color: #222; font-size: 14px; white-space: pre-wrap; margin: 0;">${message}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div style="background: #f0f0f0; padding: 12px 24px; border-radius: 0 0 8px 8px; text-align: center;">
|
||||||
|
<p style="color: #999; font-size: 12px; margin: 0;">Xpeditis — Formulaire de contact</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await this.emailService.sendContactMessage('contact@xpeditis.com', {
|
await this.emailService.send({
|
||||||
firstName: dto.firstName,
|
to: 'contact@xpeditis.com',
|
||||||
lastName: dto.lastName,
|
replyTo: dto.email,
|
||||||
email: dto.email,
|
subject: `[Contact] ${subjectLabels[dto.subject] || dto.subject} — ${dto.firstName} ${dto.lastName}`,
|
||||||
company: dto.company || undefined,
|
html,
|
||||||
phone: dto.phone || undefined,
|
|
||||||
subjectLabel: subjectLabels[dto.subject] || dto.subject,
|
|
||||||
message: dto.message,
|
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.logger.error(`Failed to send contact email: ${error}`);
|
this.logger.error(`Failed to send contact email: ${error}`);
|
||||||
|
|||||||
@ -117,7 +117,7 @@ export class BookingsController {
|
|||||||
const subscription = await this.subscriptionService.getOrCreateSubscription(
|
const subscription = await this.subscriptionService.getOrCreateSubscription(
|
||||||
user.organizationId
|
user.organizationId
|
||||||
);
|
);
|
||||||
const maxShipments = subscription.maxShipmentsPerYear;
|
const maxShipments = subscription.plan.maxShipmentsPerYear;
|
||||||
if (maxShipments !== -1) {
|
if (maxShipments !== -1) {
|
||||||
const currentYear = new Date().getFullYear();
|
const currentYear = new Date().getFullYear();
|
||||||
const count = await this.shipmentCounter.countShipmentsForOrganizationInYear(
|
const count = await this.shipmentCounter.countShipmentsForOrganizationInYear(
|
||||||
|
|||||||
@ -31,8 +31,6 @@ import {
|
|||||||
ApiParam,
|
ApiParam,
|
||||||
} from '@nestjs/swagger';
|
} from '@nestjs/swagger';
|
||||||
import { JwtAuthGuard } from '../guards/jwt-auth.guard';
|
import { JwtAuthGuard } from '../guards/jwt-auth.guard';
|
||||||
import { RolesGuard } from '../guards/roles.guard';
|
|
||||||
import { Roles } from '../decorators/roles.decorator';
|
|
||||||
import { Public } from '../decorators/public.decorator';
|
import { Public } from '../decorators/public.decorator';
|
||||||
import { CsvBookingService } from '../services/csv-booking.service';
|
import { CsvBookingService } from '../services/csv-booking.service';
|
||||||
import { SubscriptionService } from '../services/subscription.service';
|
import { SubscriptionService } from '../services/subscription.service';
|
||||||
@ -86,20 +84,8 @@ export class CsvBookingsController {
|
|||||||
* POST /api/v1/csv-bookings
|
* POST /api/v1/csv-bookings
|
||||||
*/
|
*/
|
||||||
@Post()
|
@Post()
|
||||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
|
||||||
@Roles('ADMIN', 'MANAGER', 'USER')
|
|
||||||
@ApiBearerAuth()
|
@ApiBearerAuth()
|
||||||
@UseInterceptors(
|
@UseInterceptors(FilesInterceptor('documents', 10))
|
||||||
FilesInterceptor('documents', 10, {
|
|
||||||
limits: {
|
|
||||||
fileSize: 10 * 1024 * 1024,
|
|
||||||
files: 10,
|
|
||||||
fields: 40,
|
|
||||||
parts: 50,
|
|
||||||
fieldSize: 64 * 1024,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
)
|
|
||||||
@ApiConsumes('multipart/form-data')
|
@ApiConsumes('multipart/form-data')
|
||||||
@ApiOperation({
|
@ApiOperation({
|
||||||
summary: 'Create a new CSV booking request',
|
summary: 'Create a new CSV booking request',
|
||||||
@ -158,6 +144,13 @@ export class CsvBookingsController {
|
|||||||
@Request() req: any
|
@Request() req: any
|
||||||
): Promise<CsvBookingResponseDto> {
|
): Promise<CsvBookingResponseDto> {
|
||||||
// Debug: Log request details
|
// Debug: Log request details
|
||||||
|
console.log('=== CSV Booking Request Debug ===');
|
||||||
|
console.log('req.user:', req.user);
|
||||||
|
console.log('req.body:', req.body);
|
||||||
|
console.log('dto:', dto);
|
||||||
|
console.log('files:', files?.length);
|
||||||
|
console.log('================================');
|
||||||
|
|
||||||
if (!files || files.length === 0) {
|
if (!files || files.length === 0) {
|
||||||
throw new BadRequestException('At least one document is required');
|
throw new BadRequestException('At least one document is required');
|
||||||
}
|
}
|
||||||
@ -178,7 +171,7 @@ export class CsvBookingsController {
|
|||||||
if (req.user.role !== 'ADMIN') {
|
if (req.user.role !== 'ADMIN') {
|
||||||
// Check the paid-reservation limit (free/Bronze plan = 5 paid shipments/year)
|
// Check the paid-reservation limit (free/Bronze plan = 5 paid shipments/year)
|
||||||
const subscription = await this.subscriptionService.getOrCreateSubscription(organizationId);
|
const subscription = await this.subscriptionService.getOrCreateSubscription(organizationId);
|
||||||
const maxShipments = subscription.maxShipmentsPerYear;
|
const maxShipments = subscription.plan.maxShipmentsPerYear;
|
||||||
if (maxShipments !== -1) {
|
if (maxShipments !== -1) {
|
||||||
const currentYear = new Date().getFullYear();
|
const currentYear = new Date().getFullYear();
|
||||||
const count = await this.shipmentCounter.countPaidShipmentsForOrganizationInYear(
|
const count = await this.shipmentCounter.countPaidShipmentsForOrganizationInYear(
|
||||||
@ -255,7 +248,7 @@ export class CsvBookingsController {
|
|||||||
): Promise<{ max: number; used: number; unlimited: boolean; limitReached: boolean }> {
|
): Promise<{ max: number; used: number; unlimited: boolean; limitReached: boolean }> {
|
||||||
const organizationId = req.user.organizationId;
|
const organizationId = req.user.organizationId;
|
||||||
const subscription = await this.subscriptionService.getOrCreateSubscription(organizationId);
|
const subscription = await this.subscriptionService.getOrCreateSubscription(organizationId);
|
||||||
const max = subscription.maxShipmentsPerYear;
|
const max = subscription.plan.maxShipmentsPerYear;
|
||||||
const unlimited = max === -1;
|
const unlimited = max === -1;
|
||||||
const currentYear = new Date().getFullYear();
|
const currentYear = new Date().getFullYear();
|
||||||
const used = await this.shipmentCounter.countPaidShipmentsForOrganizationInYear(
|
const used = await this.shipmentCounter.countPaidShipmentsForOrganizationInYear(
|
||||||
@ -295,8 +288,6 @@ export class CsvBookingsController {
|
|||||||
* GET /api/v1/csv-bookings/stats/organization
|
* GET /api/v1/csv-bookings/stats/organization
|
||||||
*/
|
*/
|
||||||
@Get('stats/organization')
|
@Get('stats/organization')
|
||||||
@UseGuards(RolesGuard)
|
|
||||||
@Roles('ADMIN', 'MANAGER')
|
|
||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
@ApiBearerAuth()
|
@ApiBearerAuth()
|
||||||
@ApiOperation({
|
@ApiOperation({
|
||||||
@ -320,15 +311,12 @@ export class CsvBookingsController {
|
|||||||
* GET /api/v1/csv-bookings/organization/all
|
* GET /api/v1/csv-bookings/organization/all
|
||||||
*/
|
*/
|
||||||
@Get('organization/all')
|
@Get('organization/all')
|
||||||
@UseGuards(RolesGuard)
|
|
||||||
@Roles('ADMIN', 'MANAGER')
|
|
||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
@ApiBearerAuth()
|
@ApiBearerAuth()
|
||||||
@ApiOperation({
|
@ApiOperation({
|
||||||
summary: 'Get organization bookings',
|
summary: 'Get organization bookings',
|
||||||
description:
|
description:
|
||||||
"Retrieve all bookings and quotes of the user's organization, whoever created them, " +
|
"Retrieve all bookings for the user's organization with pagination. For managers/admins.",
|
||||||
'with the name of their creator. Available to every member of the organization.',
|
|
||||||
})
|
})
|
||||||
@ApiQuery({ name: 'page', required: false, type: Number, example: 1 })
|
@ApiQuery({ name: 'page', required: false, type: Number, example: 1 })
|
||||||
@ApiQuery({ name: 'limit', required: false, type: Number, example: 10 })
|
@ApiQuery({ name: 'limit', required: false, type: Number, example: 10 })
|
||||||
@ -428,8 +416,6 @@ export class CsvBookingsController {
|
|||||||
* POST /api/v1/csv-bookings/:id/pay
|
* POST /api/v1/csv-bookings/:id/pay
|
||||||
*/
|
*/
|
||||||
@Post(':id/pay')
|
@Post(':id/pay')
|
||||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
|
||||||
@Roles('ADMIN', 'MANAGER', 'USER')
|
|
||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
@ApiBearerAuth()
|
@ApiBearerAuth()
|
||||||
@ApiOperation({
|
@ApiOperation({
|
||||||
@ -450,7 +436,7 @@ export class CsvBookingsController {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
@ApiResponse({ status: 400, description: 'Booking not in QUOTE status' })
|
@ApiResponse({ status: 400, description: 'Booking not in PENDING_PAYMENT status' })
|
||||||
@ApiResponse({ status: 404, description: 'Booking not found' })
|
@ApiResponse({ status: 404, description: 'Booking not found' })
|
||||||
async payCommission(@Param('id') id: string, @Request() req: any) {
|
async payCommission(@Param('id') id: string, @Request() req: any) {
|
||||||
const userId = req.user.id;
|
const userId = req.user.id;
|
||||||
@ -478,8 +464,6 @@ export class CsvBookingsController {
|
|||||||
* POST /api/v1/csv-bookings/:id/confirm-payment
|
* POST /api/v1/csv-bookings/:id/confirm-payment
|
||||||
*/
|
*/
|
||||||
@Post(':id/confirm-payment')
|
@Post(':id/confirm-payment')
|
||||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
|
||||||
@Roles('ADMIN', 'MANAGER', 'USER')
|
|
||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
@ApiBearerAuth()
|
@ApiBearerAuth()
|
||||||
@ApiOperation({
|
@ApiOperation({
|
||||||
@ -523,8 +507,6 @@ export class CsvBookingsController {
|
|||||||
* POST /api/v1/csv-bookings/:id/declare-transfer
|
* POST /api/v1/csv-bookings/:id/declare-transfer
|
||||||
*/
|
*/
|
||||||
@Post(':id/declare-transfer')
|
@Post(':id/declare-transfer')
|
||||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
|
||||||
@Roles('ADMIN', 'MANAGER', 'USER')
|
|
||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
@ApiBearerAuth()
|
@ApiBearerAuth()
|
||||||
@ApiOperation({
|
@ApiOperation({
|
||||||
@ -538,7 +520,7 @@ export class CsvBookingsController {
|
|||||||
description: 'Bank transfer declared, booking awaiting admin validation',
|
description: 'Bank transfer declared, booking awaiting admin validation',
|
||||||
type: CsvBookingResponseDto,
|
type: CsvBookingResponseDto,
|
||||||
})
|
})
|
||||||
@ApiResponse({ status: 400, description: 'Booking not in QUOTE status' })
|
@ApiResponse({ status: 400, description: 'Booking not in PENDING_PAYMENT status' })
|
||||||
@ApiResponse({ status: 404, description: 'Booking not found' })
|
@ApiResponse({ status: 404, description: 'Booking not found' })
|
||||||
async declareTransfer(
|
async declareTransfer(
|
||||||
@Param('id') id: string,
|
@Param('id') id: string,
|
||||||
@ -565,9 +547,7 @@ export class CsvBookingsController {
|
|||||||
@ApiBearerAuth()
|
@ApiBearerAuth()
|
||||||
@ApiOperation({
|
@ApiOperation({
|
||||||
summary: 'Get booking by ID',
|
summary: 'Get booking by ID',
|
||||||
description:
|
description: 'Retrieve a specific CSV booking by its ID. Only accessible by the booking owner.',
|
||||||
'Retrieve a specific CSV booking by its ID. Readable by any member of the booking organization ' +
|
|
||||||
'and by the assigned carrier; changes remain reserved to the booking owner.',
|
|
||||||
})
|
})
|
||||||
@ApiParam({ name: 'id', description: 'Booking ID (UUID)' })
|
@ApiParam({ name: 'id', description: 'Booking ID (UUID)' })
|
||||||
@ApiResponse({
|
@ApiResponse({
|
||||||
@ -580,12 +560,7 @@ export class CsvBookingsController {
|
|||||||
async getBooking(@Param('id') id: string, @Request() req: any): Promise<CsvBookingResponseDto> {
|
async getBooking(@Param('id') id: string, @Request() req: any): Promise<CsvBookingResponseDto> {
|
||||||
const userId = req.user.id;
|
const userId = req.user.id;
|
||||||
const carrierId = req.user.carrierId; // May be undefined if not a carrier
|
const carrierId = req.user.carrierId; // May be undefined if not a carrier
|
||||||
return await this.csvBookingService.getBookingById(
|
return await this.csvBookingService.getBookingById(id, userId, carrierId);
|
||||||
id,
|
|
||||||
userId,
|
|
||||||
carrierId,
|
|
||||||
req.user.organizationId
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -594,8 +569,6 @@ export class CsvBookingsController {
|
|||||||
* PATCH /api/v1/csv-bookings/:id/cancel
|
* PATCH /api/v1/csv-bookings/:id/cancel
|
||||||
*/
|
*/
|
||||||
@Patch(':id/cancel')
|
@Patch(':id/cancel')
|
||||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
|
||||||
@Roles('ADMIN', 'MANAGER', 'USER')
|
|
||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
@ApiBearerAuth()
|
@ApiBearerAuth()
|
||||||
@ApiOperation({
|
@ApiOperation({
|
||||||
@ -625,8 +598,6 @@ export class CsvBookingsController {
|
|||||||
* DELETE /api/v1/csv-bookings/:id
|
* DELETE /api/v1/csv-bookings/:id
|
||||||
*/
|
*/
|
||||||
@Delete(':id')
|
@Delete(':id')
|
||||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
|
||||||
@Roles('ADMIN', 'MANAGER', 'USER')
|
|
||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
@ApiBearerAuth()
|
@ApiBearerAuth()
|
||||||
@ApiOperation({
|
@ApiOperation({
|
||||||
@ -652,14 +623,12 @@ export class CsvBookingsController {
|
|||||||
* PATCH /api/v1/csv-bookings/:id/details
|
* PATCH /api/v1/csv-bookings/:id/details
|
||||||
*/
|
*/
|
||||||
@Patch(':id/details')
|
@Patch(':id/details')
|
||||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
|
||||||
@Roles('ADMIN', 'MANAGER', 'USER')
|
|
||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
@ApiBearerAuth()
|
@ApiBearerAuth()
|
||||||
@ApiOperation({
|
@ApiOperation({
|
||||||
summary: 'Update booking details before payment',
|
summary: 'Update booking details before payment',
|
||||||
description:
|
description:
|
||||||
'Edit cargo characteristics (volume, weight, pallets, notes) of a booking awaiting payment. Only the owner can edit, and only while the booking is QUOTE.',
|
'Edit cargo characteristics (volume, weight, pallets, notes) of a booking awaiting payment. Only the owner can edit, and only while the booking is PENDING_PAYMENT.',
|
||||||
})
|
})
|
||||||
@ApiParam({ name: 'id', description: 'Booking ID (UUID)' })
|
@ApiParam({ name: 'id', description: 'Booking ID (UUID)' })
|
||||||
@ApiResponse({
|
@ApiResponse({
|
||||||
@ -685,14 +654,12 @@ export class CsvBookingsController {
|
|||||||
* PATCH /api/v1/csv-bookings/:id/rate
|
* PATCH /api/v1/csv-bookings/:id/rate
|
||||||
*/
|
*/
|
||||||
@Patch(':id/rate')
|
@Patch(':id/rate')
|
||||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
|
||||||
@Roles('ADMIN', 'MANAGER', 'USER')
|
|
||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
@ApiBearerAuth()
|
@ApiBearerAuth()
|
||||||
@ApiOperation({
|
@ApiOperation({
|
||||||
summary: 'Update booking rate/route before payment',
|
summary: 'Update booking rate/route before payment',
|
||||||
description:
|
description:
|
||||||
'Re-apply a rate selection (carrier, route, container, transit, cargo, price) to a QUOTE booking. Only the owner can edit.',
|
'Re-apply a rate selection (carrier, route, container, transit, cargo, price) to a PENDING_PAYMENT booking. Only the owner can edit.',
|
||||||
})
|
})
|
||||||
@ApiParam({ name: 'id', description: 'Booking ID (UUID)' })
|
@ApiParam({ name: 'id', description: 'Booking ID (UUID)' })
|
||||||
@ApiResponse({
|
@ApiResponse({
|
||||||
@ -718,21 +685,9 @@ export class CsvBookingsController {
|
|||||||
* POST /api/v1/csv-bookings/:id/documents
|
* POST /api/v1/csv-bookings/:id/documents
|
||||||
*/
|
*/
|
||||||
@Post(':id/documents')
|
@Post(':id/documents')
|
||||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
|
||||||
@Roles('ADMIN', 'MANAGER', 'USER')
|
|
||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
@ApiBearerAuth()
|
@ApiBearerAuth()
|
||||||
@UseInterceptors(
|
@UseInterceptors(FilesInterceptor('documents', 10))
|
||||||
FilesInterceptor('documents', 10, {
|
|
||||||
limits: {
|
|
||||||
fileSize: 10 * 1024 * 1024,
|
|
||||||
files: 10,
|
|
||||||
fields: 40,
|
|
||||||
parts: 50,
|
|
||||||
fieldSize: 64 * 1024,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
)
|
|
||||||
@ApiConsumes('multipart/form-data')
|
@ApiConsumes('multipart/form-data')
|
||||||
@ApiOperation({
|
@ApiOperation({
|
||||||
summary: 'Add documents to an existing booking',
|
summary: 'Add documents to an existing booking',
|
||||||
@ -786,15 +741,9 @@ export class CsvBookingsController {
|
|||||||
* PUT /api/v1/csv-bookings/:bookingId/documents/:documentId
|
* PUT /api/v1/csv-bookings/:bookingId/documents/:documentId
|
||||||
*/
|
*/
|
||||||
@Patch(':bookingId/documents/:documentId')
|
@Patch(':bookingId/documents/:documentId')
|
||||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
|
||||||
@Roles('ADMIN', 'MANAGER', 'USER')
|
|
||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
@ApiBearerAuth()
|
@ApiBearerAuth()
|
||||||
@UseInterceptors(
|
@UseInterceptors(FilesInterceptor('document', 1))
|
||||||
FilesInterceptor('document', 1, {
|
|
||||||
limits: { fileSize: 10 * 1024 * 1024, files: 1, fields: 10, parts: 11, fieldSize: 64 * 1024 },
|
|
||||||
})
|
|
||||||
)
|
|
||||||
@ApiConsumes('multipart/form-data')
|
@ApiConsumes('multipart/form-data')
|
||||||
@ApiOperation({
|
@ApiOperation({
|
||||||
summary: 'Replace a document in a booking',
|
summary: 'Replace a document in a booking',
|
||||||
@ -861,8 +810,6 @@ export class CsvBookingsController {
|
|||||||
* DELETE /api/v1/csv-bookings/:bookingId/documents/:documentId
|
* DELETE /api/v1/csv-bookings/:bookingId/documents/:documentId
|
||||||
*/
|
*/
|
||||||
@Delete(':bookingId/documents/:documentId')
|
@Delete(':bookingId/documents/:documentId')
|
||||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
|
||||||
@Roles('ADMIN', 'MANAGER', 'USER')
|
|
||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
@ApiBearerAuth()
|
@ApiBearerAuth()
|
||||||
@ApiOperation({
|
@ApiOperation({
|
||||||
|
|||||||
@ -1,119 +0,0 @@
|
|||||||
import { ExecutionContext, INestApplication } from '@nestjs/common';
|
|
||||||
import { Test } from '@nestjs/testing';
|
|
||||||
import { ConfigService } from '@nestjs/config';
|
|
||||||
import request from 'supertest';
|
|
||||||
import { Subscription } from '@domain/entities/subscription.entity';
|
|
||||||
import { SubscriptionPlan } from '@domain/value-objects/subscription-plan.vo';
|
|
||||||
import { ShipmentLimitExceededException } from '@domain/exceptions/shipment-limit-exceeded.exception';
|
|
||||||
import { CreateCsvBookingDto } from '../dto/csv-booking.dto';
|
|
||||||
import { SubscriptionStatus } from '@domain/value-objects/subscription-status.vo';
|
|
||||||
import { CsvBookingsController } from './csv-bookings.controller';
|
|
||||||
import { JwtAuthGuard } from '../guards/jwt-auth.guard';
|
|
||||||
import { CsvBookingService } from '../services/csv-booking.service';
|
|
||||||
import { SubscriptionService } from '../services/subscription.service';
|
|
||||||
import { SHIPMENT_COUNTER_PORT } from '@domain/ports/out/shipment-counter.port';
|
|
||||||
import { ORGANIZATION_REPOSITORY } from '@domain/ports/out/organization.repository';
|
|
||||||
|
|
||||||
describe('CSV booking HTTP security', () => {
|
|
||||||
let app: INestApplication;
|
|
||||||
let subscription: Subscription;
|
|
||||||
const countPaidShipmentsForOrganizationInYear = jest.fn().mockResolvedValue(0);
|
|
||||||
const createBooking = jest.fn(async () => ({ id: 'booking' }));
|
|
||||||
const getUserBookings = jest.fn(async () => ({ bookings: [] }));
|
|
||||||
beforeAll(async () => {
|
|
||||||
const module = await Test.createTestingModule({
|
|
||||||
controllers: [CsvBookingsController],
|
|
||||||
providers: [
|
|
||||||
{ provide: CsvBookingService, useValue: { createBooking, getUserBookings } },
|
|
||||||
{
|
|
||||||
provide: SubscriptionService,
|
|
||||||
useValue: {
|
|
||||||
getOrCreateSubscription: async () => subscription,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{ provide: ConfigService, useValue: {} },
|
|
||||||
{ provide: SHIPMENT_COUNTER_PORT, useValue: { countPaidShipmentsForOrganizationInYear } },
|
|
||||||
{ provide: ORGANIZATION_REPOSITORY, useValue: {} },
|
|
||||||
],
|
|
||||||
})
|
|
||||||
.overrideGuard(JwtAuthGuard)
|
|
||||||
.useValue({
|
|
||||||
canActivate: (context: ExecutionContext) => {
|
|
||||||
const req = context.switchToHttp().getRequest();
|
|
||||||
req.user = {
|
|
||||||
id: 'user',
|
|
||||||
organizationId: 'org',
|
|
||||||
role: req.headers['x-test-role'] || 'USER',
|
|
||||||
};
|
|
||||||
return true;
|
|
||||||
},
|
|
||||||
})
|
|
||||||
.compile();
|
|
||||||
app = module.createNestApplication({ logger: false });
|
|
||||||
await app.init();
|
|
||||||
await app.listen(0, '127.0.0.1');
|
|
||||||
});
|
|
||||||
afterAll(async () => {
|
|
||||||
await app?.close();
|
|
||||||
});
|
|
||||||
beforeEach(() => {
|
|
||||||
jest.clearAllMocks();
|
|
||||||
subscription = Subscription.create({
|
|
||||||
id: 'sub',
|
|
||||||
organizationId: 'org',
|
|
||||||
plan: SubscriptionPlan.gold(),
|
|
||||||
});
|
|
||||||
countPaidShipmentsForOrganizationInYear.mockResolvedValue(0);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('rejects VIEWER mutations before invoking the booking service', async () => {
|
|
||||||
await request(app.getHttpServer())
|
|
||||||
.post('/csv-bookings')
|
|
||||||
.set('x-test-role', 'VIEWER')
|
|
||||||
.attach('documents', Buffer.from('document'), 'test.pdf')
|
|
||||||
.expect(403);
|
|
||||||
expect(createBooking).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
it('preserves VIEWER reads', async () => {
|
|
||||||
await request(app.getHttpServer())
|
|
||||||
.get('/csv-bookings')
|
|
||||||
.set('x-test-role', 'VIEWER')
|
|
||||||
.expect(200);
|
|
||||||
expect(getUserBookings).toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
it('rejects organization-wide reads for an ordinary member', async () => {
|
|
||||||
await request(app.getHttpServer()).get('/csv-bookings/organization/all').expect(403);
|
|
||||||
});
|
|
||||||
it('rejects oversized documents before invoking the service', async () => {
|
|
||||||
await request(app.getHttpServer())
|
|
||||||
.post('/csv-bookings')
|
|
||||||
.attach('documents', Buffer.alloc(10 * 1024 * 1024 + 1), 'large.pdf')
|
|
||||||
.expect(413);
|
|
||||||
expect(createBooking).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
it('applies the Bronze quota after a paid subscription is suspended', async () => {
|
|
||||||
subscription = subscription.updateStatus(SubscriptionStatus.create('UNPAID'));
|
|
||||||
countPaidShipmentsForOrganizationInYear.mockResolvedValue(
|
|
||||||
SubscriptionPlan.bronze().maxShipmentsPerYear
|
|
||||||
);
|
|
||||||
await expect(
|
|
||||||
app
|
|
||||||
.get(CsvBookingsController)
|
|
||||||
.createBooking({} as CreateCsvBookingDto, [{} as Express.Multer.File], {
|
|
||||||
user: { id: 'user', organizationId: 'org', role: 'USER' },
|
|
||||||
})
|
|
||||||
).rejects.toBeInstanceOf(ShipmentLimitExceededException);
|
|
||||||
expect(createBooking).not.toHaveBeenCalled();
|
|
||||||
expect(countPaidShipmentsForOrganizationInYear).toHaveBeenCalledWith(
|
|
||||||
'org',
|
|
||||||
new Date().getFullYear()
|
|
||||||
);
|
|
||||||
});
|
|
||||||
it('preserves permitted uploads', async () => {
|
|
||||||
await request(app.getHttpServer())
|
|
||||||
.post('/csv-bookings')
|
|
||||||
.attach('documents', Buffer.from('document'), 'test.pdf')
|
|
||||||
.expect(201);
|
|
||||||
expect(createBooking).toHaveBeenCalledTimes(1);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@ -25,7 +25,6 @@ import { GDPRService, GDPRDataExport, GDPRErasureReport } from '../services/gdpr
|
|||||||
import { UpdateConsentDto, ConsentResponseDto, WithdrawConsentDto } from '../dto/consent.dto';
|
import { UpdateConsentDto, ConsentResponseDto, WithdrawConsentDto } from '../dto/consent.dto';
|
||||||
import { DeleteAccountDto } from '../dto/delete-account.dto';
|
import { DeleteAccountDto } from '../dto/delete-account.dto';
|
||||||
import { RetentionService, RetentionReport } from '../services/retention.service';
|
import { RetentionService, RetentionReport } from '../services/retention.service';
|
||||||
import { AdminContinuityService } from '../services/admin-continuity.service';
|
|
||||||
import { RETENTION_RULES } from '@domain/services/data-retention';
|
import { RETENTION_RULES } from '@domain/services/data-retention';
|
||||||
|
|
||||||
@ApiTags('GDPR')
|
@ApiTags('GDPR')
|
||||||
@ -35,8 +34,7 @@ import { RETENTION_RULES } from '@domain/services/data-retention';
|
|||||||
export class GDPRController {
|
export class GDPRController {
|
||||||
constructor(
|
constructor(
|
||||||
private readonly gdprService: GDPRService,
|
private readonly gdprService: GDPRService,
|
||||||
private readonly retentionService: RetentionService,
|
private readonly retentionService: RetentionService
|
||||||
private readonly adminContinuity: AdminContinuityService
|
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
/** Export de portabilité au format JSON (art. 20). */
|
/** Export de portabilité au format JSON (art. 20). */
|
||||||
@ -98,10 +96,6 @@ export class GDPRController {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Le dernier administrateur actif ne peut pas effacer son propre compte :
|
|
||||||
// la plateforme resterait sans personne pour l'administrer.
|
|
||||||
await this.adminContinuity.assertCanErase(user.id);
|
|
||||||
|
|
||||||
return this.gdprService.deleteUserData(user.id, body.reason);
|
return this.gdprService.deleteUserData(user.id, body.reason);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -119,7 +119,7 @@ export class InvitationsController {
|
|||||||
description: 'Invitation expired or already used',
|
description: 'Invitation expired or already used',
|
||||||
})
|
})
|
||||||
async verifyInvitation(@Param('token') token: string): Promise<InvitationResponseDto> {
|
async verifyInvitation(@Param('token') token: string): Promise<InvitationResponseDto> {
|
||||||
this.logger.log('Verifying invitation token');
|
this.logger.log(`Verifying invitation token: ${token}`);
|
||||||
|
|
||||||
const invitation = await this.invitationService.verifyInvitation(token);
|
const invitation = await this.invitationService.verifyInvitation(token);
|
||||||
|
|
||||||
|
|||||||
@ -152,7 +152,7 @@ export class NotificationsController {
|
|||||||
throw new NotFoundException('Notification not found');
|
throw new NotFoundException('Notification not found');
|
||||||
}
|
}
|
||||||
|
|
||||||
await this.notificationService.markAsRead(id, user.id);
|
await this.notificationService.markAsRead(id);
|
||||||
return { success: true };
|
return { success: true };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -1,67 +0,0 @@
|
|||||||
import { ForbiddenException, NotFoundException } from '@nestjs/common';
|
|
||||||
import { Organization, OrganizationType } from '@domain/entities/organization.entity';
|
|
||||||
import { OrganizationRepository } from '@domain/ports/out/organization.repository';
|
|
||||||
import { UserRepository } from '@domain/ports/out/user.repository';
|
|
||||||
import { OrganizationsController } from './organizations.controller';
|
|
||||||
import { NotificationService } from '../services/notification.service';
|
|
||||||
import { UserPayload } from '../decorators/current-user.decorator';
|
|
||||||
|
|
||||||
describe('OrganizationsController tenant authorization', () => {
|
|
||||||
const actor = (role: string): UserPayload => ({
|
|
||||||
id: 'user-id',
|
|
||||||
email: 'manager@example.org',
|
|
||||||
role,
|
|
||||||
organizationId: 'own-org',
|
|
||||||
firstName: 'Test',
|
|
||||||
lastName: 'User',
|
|
||||||
});
|
|
||||||
const makeOrganization = (id: string) =>
|
|
||||||
Organization.create({
|
|
||||||
id,
|
|
||||||
name: 'Original',
|
|
||||||
type: OrganizationType.FREIGHT_FORWARDER,
|
|
||||||
address: { street: '1 rue Test', city: 'Paris', postalCode: '75001', country: 'FR' },
|
|
||||||
documents: [],
|
|
||||||
isActive: true,
|
|
||||||
});
|
|
||||||
const findById = jest.fn();
|
|
||||||
const save = jest.fn(async (organization: Organization) => organization);
|
|
||||||
const controller = new OrganizationsController(
|
|
||||||
{ findById, save } as unknown as OrganizationRepository,
|
|
||||||
{} as UserRepository,
|
|
||||||
{} as NotificationService
|
|
||||||
);
|
|
||||||
|
|
||||||
beforeEach(() => jest.clearAllMocks());
|
|
||||||
|
|
||||||
it.each(['MANAGER', 'manager', 'USER', 'VIEWER'])(
|
|
||||||
'rejects foreign organization for %s',
|
|
||||||
async role => {
|
|
||||||
const target = makeOrganization('other-org');
|
|
||||||
findById.mockResolvedValue(target);
|
|
||||||
await expect(
|
|
||||||
controller.updateOrganization(target.id, { name: 'Changed' }, actor(role))
|
|
||||||
).rejects.toBeInstanceOf(ForbiddenException);
|
|
||||||
expect(target.name).toBe('Original');
|
|
||||||
expect(save).not.toHaveBeenCalled();
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
it.each([
|
|
||||||
['MANAGER', 'own-org'],
|
|
||||||
['ADMIN', 'other-org'],
|
|
||||||
])('allows %s to update %s', async (role, id) => {
|
|
||||||
findById.mockResolvedValue(makeOrganization(id));
|
|
||||||
const result = await controller.updateOrganization(id, { name: 'Changed' }, actor(role));
|
|
||||||
expect(result.name).toBe('Changed');
|
|
||||||
expect(save).toHaveBeenCalledTimes(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('preserves missing organization response', async () => {
|
|
||||||
findById.mockResolvedValue(null);
|
|
||||||
await expect(
|
|
||||||
controller.updateOrganization('missing', {}, actor('ADMIN'))
|
|
||||||
).rejects.toBeInstanceOf(NotFoundException);
|
|
||||||
expect(save).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@ -42,7 +42,6 @@ import {
|
|||||||
ORGANIZATION_REPOSITORY,
|
ORGANIZATION_REPOSITORY,
|
||||||
} from '@domain/ports/out/organization.repository';
|
} from '@domain/ports/out/organization.repository';
|
||||||
import { Organization, OrganizationType } from '@domain/entities/organization.entity';
|
import { Organization, OrganizationType } from '@domain/entities/organization.entity';
|
||||||
import { UserRole } from '@domain/entities/user.entity';
|
|
||||||
import { NotificationType, NotificationPriority } from '@domain/entities/notification.entity';
|
import { NotificationType, NotificationPriority } from '@domain/entities/notification.entity';
|
||||||
import { UserRepository, USER_REPOSITORY } from '@domain/ports/out/user.repository';
|
import { UserRepository, USER_REPOSITORY } from '@domain/ports/out/user.repository';
|
||||||
import { JwtAuthGuard } from '../guards/jwt-auth.guard';
|
import { JwtAuthGuard } from '../guards/jwt-auth.guard';
|
||||||
@ -252,7 +251,7 @@ export class OrganizationsController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Authorization: Managers can only update their own organization
|
// Authorization: Managers can only update their own organization
|
||||||
if (user.role !== UserRole.ADMIN && organization.id !== user.organizationId) {
|
if (user.role === 'manager' && organization.id !== user.organizationId) {
|
||||||
throw new ForbiddenException('You can only update your own organization');
|
throw new ForbiddenException('You can only update your own organization');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -24,8 +24,6 @@ import {
|
|||||||
Req,
|
Req,
|
||||||
Inject,
|
Inject,
|
||||||
ForbiddenException,
|
ForbiddenException,
|
||||||
BadRequestException,
|
|
||||||
InternalServerErrorException,
|
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import {
|
import {
|
||||||
ApiTags,
|
ApiTags,
|
||||||
@ -271,7 +269,7 @@ export class SubscriptionsController {
|
|||||||
const rawBody = req.rawBody;
|
const rawBody = req.rawBody;
|
||||||
if (!rawBody) {
|
if (!rawBody) {
|
||||||
this.logger.error('No raw body found in request');
|
this.logger.error('No raw body found in request');
|
||||||
throw new BadRequestException('Missing webhook body');
|
return { received: false };
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@ -279,7 +277,7 @@ export class SubscriptionsController {
|
|||||||
return { received: true };
|
return { received: true };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.logger.error('Webhook processing failed', error);
|
this.logger.error('Webhook processing failed', error);
|
||||||
throw new InternalServerErrorException('Webhook processing failed');
|
return { received: false };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,96 +0,0 @@
|
|||||||
import { Logger } from '@nestjs/common';
|
|
||||||
import { UsersController } from './users.controller';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Creation d'un compte depuis le panel admin : l'email d'acces n'etait jamais
|
|
||||||
* envoye (TODO), et le mot de passe temporaire etait ecrit dans les journaux.
|
|
||||||
*/
|
|
||||||
|
|
||||||
const ADMIN = {
|
|
||||||
id: 'admin-1',
|
|
||||||
email: 'admin@xpeditis.com',
|
|
||||||
role: 'ADMIN',
|
|
||||||
organizationId: 'org-1',
|
|
||||||
} as never;
|
|
||||||
|
|
||||||
function buildController(options: { emailFails?: boolean } = {}) {
|
|
||||||
const userRepository = {
|
|
||||||
findByEmail: jest.fn(async () => null),
|
|
||||||
save: jest.fn(async (user: unknown) => user),
|
|
||||||
findById: jest.fn(async () => ({ firstName: 'Paul', lastName: 'Martin' })),
|
|
||||||
};
|
|
||||||
const emailPort = {
|
|
||||||
sendUserInvitation: jest.fn(async () => {
|
|
||||||
if (options.emailFails) throw new Error('550 sender not valid');
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
const organizationRepository = { findById: jest.fn(async () => ({ name: 'Acme' })) };
|
|
||||||
const unused = {} as never;
|
|
||||||
|
|
||||||
const controller = new UsersController(
|
|
||||||
userRepository as never,
|
|
||||||
unused,
|
|
||||||
unused,
|
|
||||||
unused,
|
|
||||||
emailPort as never,
|
|
||||||
organizationRepository as never
|
|
||||||
);
|
|
||||||
return { controller, emailPort };
|
|
||||||
}
|
|
||||||
|
|
||||||
const dto = {
|
|
||||||
email: 'marie@acme.test',
|
|
||||||
firstName: 'Marie',
|
|
||||||
lastName: 'Dupont',
|
|
||||||
role: 'USER',
|
|
||||||
organizationId: '550e8400-e29b-41d4-a716-446655440000',
|
|
||||||
password: 'Temp-Password-42',
|
|
||||||
} as never;
|
|
||||||
|
|
||||||
describe('UsersController.createUser — email d’acces', () => {
|
|
||||||
let logs: string[];
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
logs = [];
|
|
||||||
const capture = (message: unknown) => {
|
|
||||||
logs.push(String(message));
|
|
||||||
};
|
|
||||||
jest.spyOn(Logger.prototype, 'log').mockImplementation(capture);
|
|
||||||
jest.spyOn(Logger.prototype, 'warn').mockImplementation(capture);
|
|
||||||
jest.spyOn(Logger.prototype, 'error').mockImplementation(capture);
|
|
||||||
});
|
|
||||||
|
|
||||||
afterEach(() => jest.restoreAllMocks());
|
|
||||||
|
|
||||||
it("envoie l'email d'acces au compte cree", async () => {
|
|
||||||
const { controller, emailPort } = buildController();
|
|
||||||
|
|
||||||
const result = await controller.createUser(dto, ADMIN);
|
|
||||||
|
|
||||||
expect(emailPort.sendUserInvitation).toHaveBeenCalledWith(
|
|
||||||
'marie@acme.test',
|
|
||||||
'Acme',
|
|
||||||
'Paul Martin',
|
|
||||||
'Temp-Password-42'
|
|
||||||
);
|
|
||||||
expect(result.invitationEmailSent).toBe(true);
|
|
||||||
}, 20000);
|
|
||||||
|
|
||||||
it("n'ecrit jamais le mot de passe temporaire dans les journaux", async () => {
|
|
||||||
const { controller } = buildController();
|
|
||||||
|
|
||||||
await controller.createUser(dto, ADMIN);
|
|
||||||
|
|
||||||
expect(logs.join('\n')).not.toContain('Temp-Password-42');
|
|
||||||
}, 20000);
|
|
||||||
|
|
||||||
it("cree le compte meme si l'email echoue, et le signale", async () => {
|
|
||||||
const { controller } = buildController({ emailFails: true });
|
|
||||||
|
|
||||||
const result = await controller.createUser(dto, ADMIN);
|
|
||||||
|
|
||||||
expect(result.email).toBe('marie@acme.test');
|
|
||||||
expect(result.invitationEmailSent).toBe(false);
|
|
||||||
expect(logs.join('\n')).not.toContain('Temp-Password-42');
|
|
||||||
}, 20000);
|
|
||||||
});
|
|
||||||
@ -52,14 +52,6 @@ import { v4 as uuidv4 } from 'uuid';
|
|||||||
import * as argon2 from 'argon2';
|
import * as argon2 from 'argon2';
|
||||||
import * as crypto from 'crypto';
|
import * as crypto from 'crypto';
|
||||||
import { SubscriptionService } from '../services/subscription.service';
|
import { SubscriptionService } from '../services/subscription.service';
|
||||||
import { UserDeletionService } from '../services/user-deletion.service';
|
|
||||||
import { AdminContinuityService } from '../services/admin-continuity.service';
|
|
||||||
import { EmailPort, EMAIL_PORT } from '@domain/ports/out/email.port';
|
|
||||||
import {
|
|
||||||
OrganizationRepository,
|
|
||||||
ORGANIZATION_REPOSITORY,
|
|
||||||
} from '@domain/ports/out/organization.repository';
|
|
||||||
import { isAnonymisedEmail } from '@domain/services/data-retention';
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Users Controller
|
* Users Controller
|
||||||
@ -82,12 +74,7 @@ export class UsersController {
|
|||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
@Inject(USER_REPOSITORY) private readonly userRepository: UserRepository,
|
@Inject(USER_REPOSITORY) private readonly userRepository: UserRepository,
|
||||||
private readonly subscriptionService: SubscriptionService,
|
private readonly subscriptionService: SubscriptionService
|
||||||
private readonly userDeletionService: UserDeletionService,
|
|
||||||
private readonly adminContinuity: AdminContinuityService,
|
|
||||||
@Inject(EMAIL_PORT) private readonly emailPort: EmailPort,
|
|
||||||
@Inject(ORGANIZATION_REPOSITORY)
|
|
||||||
private readonly organizationRepository: OrganizationRepository
|
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -124,7 +111,7 @@ export class UsersController {
|
|||||||
async createUser(
|
async createUser(
|
||||||
@Body() dto: CreateUserDto,
|
@Body() dto: CreateUserDto,
|
||||||
@CurrentUser() user: UserPayload
|
@CurrentUser() user: UserPayload
|
||||||
): Promise<UserResponseDto & { invitationEmailSent: boolean }> {
|
): Promise<UserResponseDto> {
|
||||||
this.logger.log(`[User: ${user.email}] Creating user: ${dto.email} (${dto.role})`);
|
this.logger.log(`[User: ${user.email}] Creating user: ${dto.email} (${dto.role})`);
|
||||||
|
|
||||||
// Authorization: Only ADMIN can assign ADMIN role
|
// Authorization: Only ADMIN can assign ADMIN role
|
||||||
@ -173,44 +160,12 @@ export class UsersController {
|
|||||||
|
|
||||||
this.logger.log(`User created successfully: ${savedUser.id}`);
|
this.logger.log(`User created successfully: ${savedUser.id}`);
|
||||||
|
|
||||||
// L'email d'accès n'etait jamais envoye (TODO), et le mot de passe
|
// TODO: Send invitation email with temporary password
|
||||||
// temporaire etait ecrit en clair dans les journaux. Il part desormais par
|
this.logger.warn(
|
||||||
// email, et n'apparait plus nulle part ailleurs.
|
`TODO: Send invitation email to ${dto.email} with temp password: ${tempPassword}`
|
||||||
const invitationEmailSent = await this.sendAccountCreatedEmail(savedUser, tempPassword, user);
|
);
|
||||||
|
|
||||||
return { ...UserMapper.toDto(savedUser), invitationEmailSent };
|
return UserMapper.toDto(savedUser);
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Envoie au nouveau compte ses identifiants et le lien de connexion.
|
|
||||||
* Un echec n'annule pas la creation : il est signale a l'administrateur.
|
|
||||||
*/
|
|
||||||
private async sendAccountCreatedEmail(
|
|
||||||
newUser: User,
|
|
||||||
tempPassword: string,
|
|
||||||
creator: UserPayload
|
|
||||||
): Promise<boolean> {
|
|
||||||
try {
|
|
||||||
const [organization, creatorAccount] = await Promise.all([
|
|
||||||
this.organizationRepository.findById(newUser.organizationId),
|
|
||||||
this.userRepository.findById(creator.id),
|
|
||||||
]);
|
|
||||||
const inviterName = creatorAccount
|
|
||||||
? `${creatorAccount.firstName} ${creatorAccount.lastName}`.trim()
|
|
||||||
: creator.email;
|
|
||||||
|
|
||||||
await this.emailPort.sendUserInvitation(
|
|
||||||
newUser.email,
|
|
||||||
organization?.name ?? 'Xpeditis',
|
|
||||||
inviterName || creator.email,
|
|
||||||
tempPassword
|
|
||||||
);
|
|
||||||
this.logger.log(`Access email sent to new user ${newUser.email}`);
|
|
||||||
return true;
|
|
||||||
} catch (error: unknown) {
|
|
||||||
this.logger.error('User created but the access email failed');
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -298,10 +253,6 @@ export class UsersController {
|
|||||||
throw new BadRequestException('You cannot change your own role');
|
throw new BadRequestException('You cannot change your own role');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (user.role === DomainUserRole.ADMIN && currentUser.role !== DomainUserRole.ADMIN) {
|
|
||||||
throw new ForbiddenException('Only platform administrators can update ADMIN users');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Authorization: Only ADMIN can assign ADMIN role
|
// Authorization: Only ADMIN can assign ADMIN role
|
||||||
if (dto.role === 'ADMIN' && currentUser.role !== 'ADMIN') {
|
if (dto.role === 'ADMIN' && currentUser.role !== 'ADMIN') {
|
||||||
throw new ForbiddenException('Only platform administrators can assign ADMIN role');
|
throw new ForbiddenException('Only platform administrators can assign ADMIN role');
|
||||||
@ -312,13 +263,6 @@ export class UsersController {
|
|||||||
throw new ForbiddenException('You can only update users in your own organization');
|
throw new ForbiddenException('You can only update users in your own organization');
|
||||||
}
|
}
|
||||||
|
|
||||||
// At least one active admin must remain. Checked before any write — the
|
|
||||||
// license would otherwise be revoked for a change that is then refused.
|
|
||||||
await this.adminContinuity.assertKeepsAnActiveAdmin(user, {
|
|
||||||
role: dto.role ?? user.role,
|
|
||||||
isActive: dto.isActive ?? user.isActive,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Update fields
|
// Update fields
|
||||||
if (dto.firstName) {
|
if (dto.firstName) {
|
||||||
user.updateFirstName(dto.firstName);
|
user.updateFirstName(dto.firstName);
|
||||||
@ -369,10 +313,7 @@ export class UsersController {
|
|||||||
@Roles('admin')
|
@Roles('admin')
|
||||||
@ApiOperation({
|
@ApiOperation({
|
||||||
summary: 'Delete user',
|
summary: 'Delete user',
|
||||||
description:
|
description: 'Deactivate a user account. Admin only.',
|
||||||
'Erase a user (any role, including another ADMIN): personal data is deleted or anonymised, ' +
|
|
||||||
'the account is disabled and its license revoked. Bookings are kept. Admin only; ' +
|
|
||||||
'an admin cannot delete their own account here, nor the last active admin.',
|
|
||||||
})
|
})
|
||||||
@ApiParam({
|
@ApiParam({
|
||||||
name: 'id',
|
name: 'id',
|
||||||
@ -395,8 +336,17 @@ export class UsersController {
|
|||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
this.logger.log(`[Admin: ${currentUser.email}] Deleting user: ${id}`);
|
this.logger.log(`[Admin: ${currentUser.email}] Deleting user: ${id}`);
|
||||||
|
|
||||||
// GDPR erasure (bookings kept) + license revocation — see UserDeletionService
|
const user = await this.userRepository.findById(id);
|
||||||
await this.userDeletionService.deleteByAdmin(id, currentUser);
|
if (!user) {
|
||||||
|
throw new NotFoundException(`User ${id} not found`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Revoke license before deleting user
|
||||||
|
await this.subscriptionService.revokeLicense(id);
|
||||||
|
this.logger.log(`License revoked for user being deleted: ${id}`);
|
||||||
|
|
||||||
|
// Permanently delete user from database
|
||||||
|
await this.userRepository.deleteById(id);
|
||||||
|
|
||||||
this.logger.log(`User deleted successfully: ${id}`);
|
this.logger.log(`User deleted successfully: ${id}`);
|
||||||
}
|
}
|
||||||
@ -448,11 +398,7 @@ export class UsersController {
|
|||||||
this.logger.log(
|
this.logger.log(
|
||||||
`[User: ${currentUser.email}] Fetching users from organization: ${currentUser.organizationId}`
|
`[User: ${currentUser.email}] Fetching users from organization: ${currentUser.organizationId}`
|
||||||
);
|
);
|
||||||
// Erased accounts stay in the table (their bookings reference them) but are
|
let users = await this.userRepository.findByOrganization(currentUser.organizationId);
|
||||||
// no longer users: hide them from the list.
|
|
||||||
let users = (await this.userRepository.findByOrganization(currentUser.organizationId)).filter(
|
|
||||||
u => !isAnonymisedEmail(u.email)
|
|
||||||
);
|
|
||||||
|
|
||||||
// Security: Non-admin users cannot see ADMIN users
|
// Security: Non-admin users cannot see ADMIN users
|
||||||
if (currentUser.role !== 'ADMIN') {
|
if (currentUser.role !== 'ADMIN') {
|
||||||
|
|||||||
@ -1,88 +0,0 @@
|
|||||||
import { ForbiddenException, Logger } from '@nestjs/common';
|
|
||||||
import { User, UserRole } from '@domain/entities/user.entity';
|
|
||||||
import { UserRepository } from '@domain/ports/out/user.repository';
|
|
||||||
import { UsersController } from './users.controller';
|
|
||||||
import { SubscriptionService } from '../services/subscription.service';
|
|
||||||
import { UserPayload } from '../decorators/current-user.decorator';
|
|
||||||
import { UserRole as DtoUserRole } from '../dto/user.dto';
|
|
||||||
|
|
||||||
describe('administrator target protection', () => {
|
|
||||||
it('does not log a temporary password when creating an account', async () => {
|
|
||||||
const log = jest.spyOn(Logger.prototype, 'log').mockImplementation(() => undefined);
|
|
||||||
const warn = jest.spyOn(Logger.prototype, 'warn').mockImplementation(() => undefined);
|
|
||||||
try {
|
|
||||||
const controller = new UsersController(
|
|
||||||
{
|
|
||||||
findByEmail: async () => null,
|
|
||||||
save: async (user: User) => user,
|
|
||||||
} as unknown as UserRepository,
|
|
||||||
{} as SubscriptionService,
|
|
||||||
{} as never,
|
|
||||||
{ assertKeepsAnActiveAdmin: jest.fn() } as never,
|
|
||||||
{ sendUserInvitation: jest.fn().mockResolvedValue(undefined) } as never,
|
|
||||||
{ findById: jest.fn().mockResolvedValue(null) } as never
|
|
||||||
);
|
|
||||||
await controller.createUser(
|
|
||||||
{
|
|
||||||
email: 'new@example.org',
|
|
||||||
firstName: 'New',
|
|
||||||
lastName: 'User',
|
|
||||||
organizationId: 'org-1',
|
|
||||||
role: DtoUserRole.USER,
|
|
||||||
password: 'test-only-Temporary-password-42',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 'admin',
|
|
||||||
email: 'admin@example.org',
|
|
||||||
role: 'ADMIN',
|
|
||||||
organizationId: 'org-1',
|
|
||||||
firstName: 'A',
|
|
||||||
lastName: 'B',
|
|
||||||
}
|
|
||||||
);
|
|
||||||
expect(JSON.stringify([...log.mock.calls, ...warn.mock.calls])).not.toContain(
|
|
||||||
'test-only-Temporary-password-42'
|
|
||||||
);
|
|
||||||
} finally {
|
|
||||||
log.mockRestore();
|
|
||||||
warn.mockRestore();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
const actor: UserPayload = {
|
|
||||||
id: 'manager',
|
|
||||||
role: 'MANAGER',
|
|
||||||
organizationId: 'org-1',
|
|
||||||
email: 'manager@example.org',
|
|
||||||
firstName: 'Test',
|
|
||||||
lastName: 'Manager',
|
|
||||||
};
|
|
||||||
it.each([UserRole.ADMIN, UserRole.USER])('enforces target hierarchy for %s', async role => {
|
|
||||||
const user = User.create({
|
|
||||||
id: 'target',
|
|
||||||
role,
|
|
||||||
organizationId: actor.organizationId,
|
|
||||||
email: 'target@example.org',
|
|
||||||
firstName: 'Original',
|
|
||||||
lastName: 'User',
|
|
||||||
passwordHash: 'test-hash',
|
|
||||||
});
|
|
||||||
const save = jest.fn(async () => user);
|
|
||||||
const controller = new UsersController(
|
|
||||||
{ findById: jest.fn(async () => user), save } as unknown as UserRepository,
|
|
||||||
{} as SubscriptionService,
|
|
||||||
{} as never,
|
|
||||||
{ assertKeepsAnActiveAdmin: jest.fn() } as never,
|
|
||||||
{ sendUserInvitation: jest.fn().mockResolvedValue(undefined) } as never,
|
|
||||||
{ findById: jest.fn().mockResolvedValue(null) } as never
|
|
||||||
);
|
|
||||||
const result = controller.updateUser(user.id, { firstName: 'Changed' }, actor);
|
|
||||||
if (role === UserRole.ADMIN) {
|
|
||||||
await expect(result).rejects.toBeInstanceOf(ForbiddenException);
|
|
||||||
expect(save).not.toHaveBeenCalled();
|
|
||||||
expect(user.firstName).toBe('Original');
|
|
||||||
} else {
|
|
||||||
await expect(result).resolves.toHaveProperty('firstName', 'Changed');
|
|
||||||
expect(save).toHaveBeenCalled();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@ -1,28 +0,0 @@
|
|||||||
import 'reflect-metadata';
|
|
||||||
import { I18nValidationPipe } from 'nestjs-i18n';
|
|
||||||
import { WebhooksController } from './webhooks.controller';
|
|
||||||
|
|
||||||
describe('Current webhook configuration boundary (OBS-02)', () => {
|
|
||||||
it.each([
|
|
||||||
['createWebhook', 0],
|
|
||||||
['updateWebhook', 1],
|
|
||||||
])('%s rejects an unvalidated destination at the global pipe', async (method, index) => {
|
|
||||||
const types = Reflect.getMetadata(
|
|
||||||
'design:paramtypes',
|
|
||||||
WebhooksController.prototype,
|
|
||||||
method as string
|
|
||||||
);
|
|
||||||
const pipe = new I18nValidationPipe({
|
|
||||||
whitelist: true,
|
|
||||||
forbidNonWhitelisted: true,
|
|
||||||
transform: true,
|
|
||||||
transformOptions: { enableImplicitConversion: true },
|
|
||||||
});
|
|
||||||
await expect(
|
|
||||||
pipe.transform(
|
|
||||||
{ url: 'http://127.0.0.1/internal', events: ['booking.created'] },
|
|
||||||
{ type: 'body', metatype: types[index as number] }
|
|
||||||
)
|
|
||||||
).rejects.toMatchObject({ status: 400 });
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@ -265,7 +265,7 @@ export class UpdateCsvBookingDetailsDto {
|
|||||||
*
|
*
|
||||||
* Full re-selection of a rate before payment (carrier + route + container +
|
* Full re-selection of a rate before payment (carrier + route + container +
|
||||||
* transit + cargo + price). Used when the user re-runs the search and picks a
|
* transit + cargo + price). Used when the user re-runs the search and picks a
|
||||||
* (possibly different) rate for a QUOTE booking.
|
* (possibly different) rate for a PENDING_PAYMENT booking.
|
||||||
*/
|
*/
|
||||||
export class UpdateCsvBookingRateDto {
|
export class UpdateCsvBookingRateDto {
|
||||||
@ApiProperty({ example: 'SSC Consolidation' })
|
@ApiProperty({ example: 'SSC Consolidation' })
|
||||||
@ -451,23 +451,6 @@ export class CsvBookingResponseDto {
|
|||||||
})
|
})
|
||||||
organizationId: string;
|
organizationId: string;
|
||||||
|
|
||||||
@ApiPropertyOptional({
|
|
||||||
description:
|
|
||||||
'Full name of the user who created the booking (organization listing). ' +
|
|
||||||
'Null when that account has been deleted.',
|
|
||||||
example: 'Marie Dupont',
|
|
||||||
nullable: true,
|
|
||||||
})
|
|
||||||
createdByName?: string | null;
|
|
||||||
|
|
||||||
@ApiPropertyOptional({
|
|
||||||
description:
|
|
||||||
'Bank transfer validation only: whether the booking request email reached the SMTP relay. ' +
|
|
||||||
'When false, the booking is active but the admin should resend the carrier email.',
|
|
||||||
example: true,
|
|
||||||
})
|
|
||||||
carrierEmailSent?: boolean;
|
|
||||||
|
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
description: 'Carrier/Company name',
|
description: 'Carrier/Company name',
|
||||||
example: 'SSC Consolidation',
|
example: 'SSC Consolidation',
|
||||||
@ -543,8 +526,8 @@ export class CsvBookingResponseDto {
|
|||||||
|
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
description: 'Booking status',
|
description: 'Booking status',
|
||||||
enum: ['QUOTE', 'PENDING', 'ACCEPTED', 'REJECTED', 'CANCELLED'],
|
enum: ['PENDING_PAYMENT', 'PENDING', 'ACCEPTED', 'REJECTED', 'CANCELLED'],
|
||||||
example: 'QUOTE',
|
example: 'PENDING_PAYMENT',
|
||||||
})
|
})
|
||||||
status: string;
|
status: string;
|
||||||
|
|
||||||
@ -554,6 +537,12 @@ export class CsvBookingResponseDto {
|
|||||||
})
|
})
|
||||||
documents: CsvBookingDocumentDto[];
|
documents: CsvBookingDocumentDto[];
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
description: 'Confirmation token for accept/reject actions',
|
||||||
|
example: 'abc123-def456-ghi789',
|
||||||
|
})
|
||||||
|
confirmationToken: string;
|
||||||
|
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
description: 'Booking request timestamp',
|
description: 'Booking request timestamp',
|
||||||
example: '2025-10-23T14:30:00Z',
|
example: '2025-10-23T14:30:00Z',
|
||||||
@ -700,10 +689,10 @@ export class CsvBookingListResponseDto {
|
|||||||
*/
|
*/
|
||||||
export class CsvBookingStatsDto {
|
export class CsvBookingStatsDto {
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
description: 'Number of quotes (bookings whose booking fee is unpaid)',
|
description: 'Number of bookings awaiting payment',
|
||||||
example: 1,
|
example: 1,
|
||||||
})
|
})
|
||||||
quote: number;
|
pendingPayment: number;
|
||||||
|
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
description: 'Number of pending bookings',
|
description: 'Number of pending bookings',
|
||||||
|
|||||||
@ -11,7 +11,7 @@ import { IsEmail, IsOptional, IsString, MaxLength } from 'class-validator';
|
|||||||
export class DeleteAccountDto {
|
export class DeleteAccountDto {
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
example: 'personne@example.com',
|
example: 'personne@example.com',
|
||||||
description: 'Adresse du compte, ressaisie pour confirmer un acte irréversible',
|
description: "Adresse du compte, ressaisie pour confirmer un acte irréversible",
|
||||||
})
|
})
|
||||||
@IsEmail({}, { message: 'Une adresse email valide est requise pour confirmer.' })
|
@IsEmail({}, { message: 'Une adresse email valide est requise pour confirmer.' })
|
||||||
confirmEmail: string;
|
confirmEmail: string;
|
||||||
|
|||||||
@ -1,4 +1,3 @@
|
|||||||
import { safeRequestRoute } from '../logging/safe-http-log';
|
|
||||||
/**
|
/**
|
||||||
* DomainExceptionFilter
|
* DomainExceptionFilter
|
||||||
*
|
*
|
||||||
@ -39,7 +38,7 @@ export class DomainExceptionFilter implements ExceptionFilter {
|
|||||||
error: exception.name,
|
error: exception.name,
|
||||||
message: typeof translated === 'string' ? translated : exception.message,
|
message: typeof translated === 'string' ? translated : exception.message,
|
||||||
timestamp: new Date().toISOString(),
|
timestamp: new Date().toISOString(),
|
||||||
path: safeRequestRoute(request),
|
path: request.url,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -75,38 +75,6 @@ describe('UnhandledExceptionFilter', () => {
|
|||||||
expect(JSON.stringify(payload)).not.toContain('stack');
|
expect(JSON.stringify(payload)).not.toContain('stack');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('turns the last-active-admin trigger refusal into an explained 409', () => {
|
|
||||||
// Deux admins qui se suppriment l'un l'autre au meme instant : le controle
|
|
||||||
// applicatif passe des deux cotes, le declencheur PostgreSQL refuse le second.
|
|
||||||
const { host, status, body } = hostFor({}, '/api/v1/admin/users/abc');
|
|
||||||
const triggerError = Object.assign(
|
|
||||||
new Error('Au moins un administrateur actif doit subsister'),
|
|
||||||
{
|
|
||||||
code: 'XP001',
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
filter.catch(triggerError, host);
|
|
||||||
|
|
||||||
expect(status).toHaveBeenCalledWith(HttpStatus.CONFLICT);
|
|
||||||
expect(body()).toMatchObject({
|
|
||||||
code: 'last_active_admin',
|
|
||||||
message: 'translated:error.LAST_ACTIVE_ADMIN',
|
|
||||||
});
|
|
||||||
expect(body().reference).toBeUndefined();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('recognises the trigger refusal through driverError as well', () => {
|
|
||||||
const { host, status } = hostFor();
|
|
||||||
|
|
||||||
filter.catch(
|
|
||||||
Object.assign(new Error('query failed'), { driverError: { code: 'XP001' } }),
|
|
||||||
host
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(status).toHaveBeenCalledWith(HttpStatus.CONFLICT);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('gives each incident its own reference', () => {
|
it('gives each incident its own reference', () => {
|
||||||
const first = hostFor();
|
const first = hostFor();
|
||||||
const second = hostFor();
|
const second = hostFor();
|
||||||
|
|||||||
@ -1,4 +1,3 @@
|
|||||||
import { safeRequestRoute } from '../logging/safe-http-log';
|
|
||||||
import {
|
import {
|
||||||
ArgumentsHost,
|
ArgumentsHost,
|
||||||
Catch,
|
Catch,
|
||||||
@ -11,10 +10,6 @@ import { randomUUID } from 'crypto';
|
|||||||
import { Request, Response } from 'express';
|
import { Request, Response } from 'express';
|
||||||
import { I18nContext, I18nService } from 'nestjs-i18n';
|
import { I18nContext, I18nService } from 'nestjs-i18n';
|
||||||
import { DEFAULT_LOCALE, Locale, isLocale } from '@domain/value-objects/locale.vo';
|
import { DEFAULT_LOCALE, Locale, isLocale } from '@domain/value-objects/locale.vo';
|
||||||
import {
|
|
||||||
LAST_ACTIVE_ADMIN_CODE,
|
|
||||||
LAST_ACTIVE_ADMIN_SQLSTATE,
|
|
||||||
} from '@domain/services/admin-continuity';
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Dernier recours avant la reponse HTTP.
|
* Dernier recours avant la reponse HTTP.
|
||||||
@ -56,22 +51,6 @@ export class UnhandledExceptionFilter implements ExceptionFilter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const lang = resolveLocale(request);
|
const lang = resolveLocale(request);
|
||||||
|
|
||||||
// Le declencheur PostgreSQL a refuse de retirer le dernier administrateur
|
|
||||||
// actif (cas concurrent que le controle applicatif ne peut pas voir) : c'est
|
|
||||||
// un conflit explicable, pas une panne.
|
|
||||||
if (isLastActiveAdminViolation(exception)) {
|
|
||||||
response.status(HttpStatus.CONFLICT).json({
|
|
||||||
statusCode: HttpStatus.CONFLICT,
|
|
||||||
error: 'Conflict',
|
|
||||||
code: LAST_ACTIVE_ADMIN_CODE,
|
|
||||||
message: this.translate('error.LAST_ACTIVE_ADMIN', lang),
|
|
||||||
timestamp: new Date().toISOString(),
|
|
||||||
path: request.url,
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const unavailable = isDependencyUnavailable(exception);
|
const unavailable = isDependencyUnavailable(exception);
|
||||||
const status = unavailable ? HttpStatus.SERVICE_UNAVAILABLE : HttpStatus.INTERNAL_SERVER_ERROR;
|
const status = unavailable ? HttpStatus.SERVICE_UNAVAILABLE : HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
const key = unavailable ? 'error.SERVICE_UNAVAILABLE' : 'error.UNEXPECTED_ERROR';
|
const key = unavailable ? 'error.SERVICE_UNAVAILABLE' : 'error.UNEXPECTED_ERROR';
|
||||||
@ -81,7 +60,8 @@ export class UnhandledExceptionFilter implements ExceptionFilter {
|
|||||||
const reference = randomUUID().slice(0, 8);
|
const reference = randomUUID().slice(0, 8);
|
||||||
|
|
||||||
this.logger.error(
|
this.logger.error(
|
||||||
`[${reference}] ${request.method} ${safeRequestRoute(request)} — ${unavailable ? 'dependency unavailable' : 'unexpected error'}`
|
`[${reference}] ${request.method} ${request.url} — ${describe(exception)}`,
|
||||||
|
exception instanceof Error ? exception.stack : undefined
|
||||||
);
|
);
|
||||||
|
|
||||||
response.status(status).json({
|
response.status(status).json({
|
||||||
@ -91,7 +71,7 @@ export class UnhandledExceptionFilter implements ExceptionFilter {
|
|||||||
message: this.translate(key, lang),
|
message: this.translate(key, lang),
|
||||||
reference,
|
reference,
|
||||||
timestamp: new Date().toISOString(),
|
timestamp: new Date().toISOString(),
|
||||||
path: safeRequestRoute(request),
|
path: request.url,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -101,16 +81,8 @@ export class UnhandledExceptionFilter implements ExceptionFilter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
const describe = (exception: unknown): string =>
|
||||||
* L'erreur est-elle le refus du declencheur `trg_users_keep_active_admin` ?
|
exception instanceof Error ? `${exception.name}: ${exception.message}` : String(exception);
|
||||||
* TypeORM recopie le code du pilote sur QueryFailedError ; `driverError` est
|
|
||||||
* verifie aussi, au cas ou cette recopie changerait.
|
|
||||||
*/
|
|
||||||
export function isLastActiveAdminViolation(exception: unknown): boolean {
|
|
||||||
if (!(exception instanceof Error)) return false;
|
|
||||||
const { code, driverError } = exception as { code?: string; driverError?: { code?: string } };
|
|
||||||
return code === LAST_ACTIVE_ADMIN_SQLSTATE || driverError?.code === LAST_ACTIVE_ADMIN_SQLSTATE;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* L'erreur vient-elle d'une dependance injoignable, plutot que d'une requete
|
* L'erreur vient-elle d'une dependance injoignable, plutot que d'une requete
|
||||||
|
|||||||
@ -1,70 +0,0 @@
|
|||||||
import { ConfigService } from '@nestjs/config';
|
|
||||||
import { JwtService } from '@nestjs/jwt';
|
|
||||||
import { Socket } from 'socket.io';
|
|
||||||
import { NotificationsGateway } from './notifications.gateway';
|
|
||||||
import { JwtStrategy } from '../auth/jwt.strategy';
|
|
||||||
import { AuthService } from '../auth/auth.service';
|
|
||||||
import { NotificationService } from '../services/notification.service';
|
|
||||||
|
|
||||||
describe('notification socket sessions', () => {
|
|
||||||
const jwt = new JwtService({ secret: 'test-only-socket-secret' });
|
|
||||||
const validateUser = jest.fn();
|
|
||||||
const notifications = {
|
|
||||||
getUnreadCount: jest.fn(async () => 0),
|
|
||||||
getRecentNotifications: jest.fn(async () => []),
|
|
||||||
markAllAsRead: jest.fn(),
|
|
||||||
};
|
|
||||||
let gateway: NotificationsGateway;
|
|
||||||
const socket = (token: string) =>
|
|
||||||
({
|
|
||||||
id: 'socket-1',
|
|
||||||
data: {},
|
|
||||||
handshake: { headers: {}, query: {}, auth: { token } },
|
|
||||||
join: jest.fn(),
|
|
||||||
emit: jest.fn(),
|
|
||||||
disconnect: jest.fn(),
|
|
||||||
}) as unknown as Socket;
|
|
||||||
const token = (type = 'access', expiresIn = 300) =>
|
|
||||||
jwt.sign({ sub: 'user-1', type }, { expiresIn });
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
jest.clearAllMocks();
|
|
||||||
validateUser.mockResolvedValue({ id: 'user-1', organizationId: 'org-1' });
|
|
||||||
const strategy = new JwtStrategy(new ConfigService({ JWT_SECRET: 'test-only-socket-secret' }), {
|
|
||||||
validateUser,
|
|
||||||
} as unknown as AuthService);
|
|
||||||
gateway = new NotificationsGateway(
|
|
||||||
jwt,
|
|
||||||
notifications as unknown as NotificationService,
|
|
||||||
strategy
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it.each(['refresh', 'unknown'])('rejects %s tokens before any data is sent', async type => {
|
|
||||||
const client = socket(token(type));
|
|
||||||
await gateway.handleConnection(client);
|
|
||||||
expect(client.disconnect).toHaveBeenCalled();
|
|
||||||
expect(client.emit).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('rejects expired and disabled sessions', async () => {
|
|
||||||
const expired = socket(token('access', -1));
|
|
||||||
await gateway.handleConnection(expired);
|
|
||||||
expect(expired.emit).not.toHaveBeenCalled();
|
|
||||||
validateUser.mockResolvedValue(null);
|
|
||||||
const disabled = socket(token());
|
|
||||||
await gateway.handleConnection(disabled);
|
|
||||||
expect(disabled.emit).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('rechecks the account on messages after a valid connection', async () => {
|
|
||||||
const client = socket(token());
|
|
||||||
await gateway.handleConnection(client);
|
|
||||||
expect(client.emit).toHaveBeenCalledWith('unread_count', { count: 0 });
|
|
||||||
validateUser.mockResolvedValue(null);
|
|
||||||
const result = await gateway.handleMarkAllAsRead(client);
|
|
||||||
expect(result.success).toBe(false);
|
|
||||||
expect(notifications.markAllAsRead).not.toHaveBeenCalled();
|
|
||||||
expect(client.disconnect).toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@ -14,9 +14,8 @@ import {
|
|||||||
MessageBody,
|
MessageBody,
|
||||||
} from '@nestjs/websockets';
|
} from '@nestjs/websockets';
|
||||||
import { Server, Socket } from 'socket.io';
|
import { Server, Socket } from 'socket.io';
|
||||||
import { Logger, UseGuards, UnauthorizedException } from '@nestjs/common';
|
import { Logger, UseGuards } from '@nestjs/common';
|
||||||
import { JwtService } from '@nestjs/jwt';
|
import { JwtService } from '@nestjs/jwt';
|
||||||
import { JwtStrategy, JwtPayload } from '../auth/jwt.strategy';
|
|
||||||
import { NotificationService } from '../services/notification.service';
|
import { NotificationService } from '../services/notification.service';
|
||||||
import { Notification } from '@domain/entities/notification.entity';
|
import { Notification } from '@domain/entities/notification.entity';
|
||||||
import { notificationTarget } from '@domain/services/notification-target';
|
import { notificationTarget } from '@domain/services/notification-target';
|
||||||
@ -37,13 +36,11 @@ export class NotificationsGateway implements OnGatewayConnection, OnGatewayDisco
|
|||||||
server: Server;
|
server: Server;
|
||||||
|
|
||||||
private readonly logger = new Logger(NotificationsGateway.name);
|
private readonly logger = new Logger(NotificationsGateway.name);
|
||||||
private readonly connections = new Map<string, Socket>();
|
|
||||||
private userSockets: Map<string, Set<string>> = new Map(); // userId -> Set of socket IDs
|
private userSockets: Map<string, Set<string>> = new Map(); // userId -> Set of socket IDs
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly jwtService: JwtService,
|
private readonly jwtService: JwtService,
|
||||||
private readonly notificationService: NotificationService,
|
private readonly notificationService: NotificationService
|
||||||
private readonly jwtStrategy: JwtStrategy
|
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -60,9 +57,8 @@ export class NotificationsGateway implements OnGatewayConnection, OnGatewayDisco
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Verify JWT token
|
// Verify JWT token
|
||||||
const user = await this.authenticate(client);
|
const payload = await this.jwtService.verifyAsync(token);
|
||||||
const userId = user.id;
|
const userId = payload.sub;
|
||||||
this.connections.set(client.id, client);
|
|
||||||
|
|
||||||
// Store socket connection for user
|
// Store socket connection for user
|
||||||
if (!this.userSockets.has(userId)) {
|
if (!this.userSockets.has(userId)) {
|
||||||
@ -72,7 +68,7 @@ export class NotificationsGateway implements OnGatewayConnection, OnGatewayDisco
|
|||||||
|
|
||||||
// Store user ID in socket data for later use
|
// Store user ID in socket data for later use
|
||||||
client.data.userId = userId;
|
client.data.userId = userId;
|
||||||
client.data.organizationId = user.organizationId;
|
client.data.organizationId = payload.organizationId;
|
||||||
|
|
||||||
// Join user-specific room
|
// Join user-specific room
|
||||||
client.join(`user:${userId}`);
|
client.join(`user:${userId}`);
|
||||||
@ -101,7 +97,6 @@ export class NotificationsGateway implements OnGatewayConnection, OnGatewayDisco
|
|||||||
* Handle client disconnection
|
* Handle client disconnection
|
||||||
*/
|
*/
|
||||||
handleDisconnect(client: Socket) {
|
handleDisconnect(client: Socket) {
|
||||||
this.connections.delete(client.id);
|
|
||||||
const userId = client.data.userId;
|
const userId = client.data.userId;
|
||||||
if (userId && this.userSockets.has(userId)) {
|
if (userId && this.userSockets.has(userId)) {
|
||||||
this.userSockets.get(userId)!.delete(client.id);
|
this.userSockets.get(userId)!.delete(client.id);
|
||||||
@ -121,12 +116,12 @@ export class NotificationsGateway implements OnGatewayConnection, OnGatewayDisco
|
|||||||
@MessageBody() data: { notificationId: string }
|
@MessageBody() data: { notificationId: string }
|
||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
const userId = (await this.authenticate(client)).id;
|
const userId = client.data.userId;
|
||||||
await this.notificationService.markAsRead(data.notificationId, userId);
|
await this.notificationService.markAsRead(data.notificationId);
|
||||||
|
|
||||||
// Send updated unread count
|
// Send updated unread count
|
||||||
const unreadCount = await this.notificationService.getUnreadCount(userId);
|
const unreadCount = await this.notificationService.getUnreadCount(userId);
|
||||||
await this.emitToUser(userId, 'unread_count', { count: unreadCount });
|
this.emitToUser(userId, 'unread_count', { count: unreadCount });
|
||||||
|
|
||||||
return { success: true };
|
return { success: true };
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
@ -141,11 +136,11 @@ export class NotificationsGateway implements OnGatewayConnection, OnGatewayDisco
|
|||||||
@SubscribeMessage('mark_all_as_read')
|
@SubscribeMessage('mark_all_as_read')
|
||||||
async handleMarkAllAsRead(@ConnectedSocket() client: Socket) {
|
async handleMarkAllAsRead(@ConnectedSocket() client: Socket) {
|
||||||
try {
|
try {
|
||||||
const userId = (await this.authenticate(client)).id;
|
const userId = client.data.userId;
|
||||||
await this.notificationService.markAllAsRead(userId);
|
await this.notificationService.markAllAsRead(userId);
|
||||||
|
|
||||||
// Send updated unread count (should be 0)
|
// Send updated unread count (should be 0)
|
||||||
await this.emitToUser(userId, 'unread_count', { count: 0 });
|
this.emitToUser(userId, 'unread_count', { count: 0 });
|
||||||
|
|
||||||
return { success: true };
|
return { success: true };
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
@ -160,7 +155,7 @@ export class NotificationsGateway implements OnGatewayConnection, OnGatewayDisco
|
|||||||
@SubscribeMessage('get_unread_count')
|
@SubscribeMessage('get_unread_count')
|
||||||
async handleGetUnreadCount(@ConnectedSocket() client: Socket) {
|
async handleGetUnreadCount(@ConnectedSocket() client: Socket) {
|
||||||
try {
|
try {
|
||||||
const userId = (await this.authenticate(client)).id;
|
const userId = client.data.userId;
|
||||||
const unreadCount = await this.notificationService.getUnreadCount(userId);
|
const unreadCount = await this.notificationService.getUnreadCount(userId);
|
||||||
return { count: unreadCount };
|
return { count: unreadCount };
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
@ -176,11 +171,11 @@ export class NotificationsGateway implements OnGatewayConnection, OnGatewayDisco
|
|||||||
const notificationDto = this.mapNotificationToDto(notification);
|
const notificationDto = this.mapNotificationToDto(notification);
|
||||||
|
|
||||||
// Emit to all connected sockets for this user
|
// Emit to all connected sockets for this user
|
||||||
await this.emitToUser(userId, 'new_notification', { notification: notificationDto });
|
this.emitToUser(userId, 'new_notification', { notification: notificationDto });
|
||||||
|
|
||||||
// Update unread count
|
// Update unread count
|
||||||
const unreadCount = await this.notificationService.getUnreadCount(userId);
|
const unreadCount = await this.notificationService.getUnreadCount(userId);
|
||||||
await this.emitToUser(userId, 'unread_count', { count: unreadCount });
|
this.emitToUser(userId, 'unread_count', { count: unreadCount });
|
||||||
|
|
||||||
this.logger.log(`Notification sent to user ${userId}: ${notification.title}`);
|
this.logger.log(`Notification sent to user ${userId}: ${notification.title}`);
|
||||||
}
|
}
|
||||||
@ -190,16 +185,9 @@ export class NotificationsGateway implements OnGatewayConnection, OnGatewayDisco
|
|||||||
*/
|
*/
|
||||||
async broadcastToOrganization(organizationId: string, notification: Notification) {
|
async broadcastToOrganization(organizationId: string, notification: Notification) {
|
||||||
const notificationDto = this.mapNotificationToDto(notification);
|
const notificationDto = this.mapNotificationToDto(notification);
|
||||||
for (const client of this.connections.values()) {
|
this.server.to(`org:${organizationId}`).emit('new_notification', {
|
||||||
try {
|
notification: notificationDto,
|
||||||
const user = await this.authenticate(client);
|
});
|
||||||
if (user.organizationId === organizationId) {
|
|
||||||
client.emit('new_notification', { notification: notificationDto });
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
client.disconnect();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
this.logger.log(`Notification broadcasted to organization ${organizationId}`);
|
this.logger.log(`Notification broadcasted to organization ${organizationId}`);
|
||||||
}
|
}
|
||||||
@ -207,36 +195,8 @@ export class NotificationsGateway implements OnGatewayConnection, OnGatewayDisco
|
|||||||
/**
|
/**
|
||||||
* Helper: Emit event to all sockets of a user
|
* Helper: Emit event to all sockets of a user
|
||||||
*/
|
*/
|
||||||
private async emitToUser(userId: string, event: string, data: unknown) {
|
private emitToUser(userId: string, event: string, data: any) {
|
||||||
for (const socketId of this.userSockets.get(userId) ?? []) {
|
this.server.to(`user:${userId}`).emit(event, data);
|
||||||
const client = this.connections.get(socketId);
|
|
||||||
if (!client) continue;
|
|
||||||
try {
|
|
||||||
const user = await this.authenticate(client);
|
|
||||||
if (user.id === userId) client.emit(event, data);
|
|
||||||
} catch {
|
|
||||||
client.disconnect();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async authenticate(client: Socket) {
|
|
||||||
try {
|
|
||||||
const token = this.extractToken(client);
|
|
||||||
if (!token) throw new UnauthorizedException();
|
|
||||||
const payload = await this.jwtService.verifyAsync<JwtPayload>(token);
|
|
||||||
if (
|
|
||||||
typeof payload.sub !== 'string' ||
|
|
||||||
!Number.isFinite(payload.exp) ||
|
|
||||||
payload.exp! * 1000 <= Date.now()
|
|
||||||
) {
|
|
||||||
throw new UnauthorizedException();
|
|
||||||
}
|
|
||||||
return await this.jwtStrategy.validate(payload);
|
|
||||||
} catch {
|
|
||||||
client.disconnect();
|
|
||||||
throw new UnauthorizedException('Invalid or expired session');
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@ -10,13 +10,8 @@ import { AuditModule } from '../audit/audit.module';
|
|||||||
import { GDPRController } from '../controllers/gdpr.controller';
|
import { GDPRController } from '../controllers/gdpr.controller';
|
||||||
import { GDPRService } from '../services/gdpr.service';
|
import { GDPRService } from '../services/gdpr.service';
|
||||||
import { RetentionService } from '../services/retention.service';
|
import { RetentionService } from '../services/retention.service';
|
||||||
import { UserDeletionService } from '../services/user-deletion.service';
|
|
||||||
import { AdminContinuityService } from '../services/admin-continuity.service';
|
|
||||||
import { SubscriptionsModule } from '../subscriptions/subscriptions.module';
|
|
||||||
import { UserOrmEntity } from '../../infrastructure/persistence/typeorm/entities/user.orm-entity';
|
import { UserOrmEntity } from '../../infrastructure/persistence/typeorm/entities/user.orm-entity';
|
||||||
import { CookieConsentOrmEntity } from '../../infrastructure/persistence/typeorm/entities/cookie-consent.orm-entity';
|
import { CookieConsentOrmEntity } from '../../infrastructure/persistence/typeorm/entities/cookie-consent.orm-entity';
|
||||||
import { USER_REPOSITORY } from '@domain/ports/out/user.repository';
|
|
||||||
import { TypeOrmUserRepository } from '../../infrastructure/persistence/typeorm/repositories/typeorm-user.repository';
|
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
@ -28,19 +23,9 @@ import { TypeOrmUserRepository } from '../../infrastructure/persistence/typeorm/
|
|||||||
// Les demandes de droits sont journalisees : l'article 5.2 impose de
|
// Les demandes de droits sont journalisees : l'article 5.2 impose de
|
||||||
// pouvoir demontrer qu'elles ont ete traitees.
|
// pouvoir demontrer qu'elles ont ete traitees.
|
||||||
AuditModule,
|
AuditModule,
|
||||||
// Suppression par un administrateur : la licence est revoquee apres
|
|
||||||
// l'effacement.
|
|
||||||
SubscriptionsModule,
|
|
||||||
],
|
],
|
||||||
controllers: [GDPRController],
|
controllers: [GDPRController],
|
||||||
providers: [
|
providers: [GDPRService, RetentionService],
|
||||||
GDPRService,
|
exports: [GDPRService, RetentionService],
|
||||||
RetentionService,
|
|
||||||
UserDeletionService,
|
|
||||||
// Au moins un administrateur actif : partage avec Admin et Users.
|
|
||||||
AdminContinuityService,
|
|
||||||
{ provide: USER_REPOSITORY, useClass: TypeOrmUserRepository },
|
|
||||||
],
|
|
||||||
exports: [GDPRService, RetentionService, UserDeletionService, AdminContinuityService],
|
|
||||||
})
|
})
|
||||||
export class GDPRModule {}
|
export class GDPRModule {}
|
||||||
|
|||||||
@ -18,7 +18,7 @@ import { REQUIRED_FEATURES_KEY } from '../decorators/requires-feature.decorator'
|
|||||||
* Feature Flag Guard
|
* Feature Flag Guard
|
||||||
*
|
*
|
||||||
* Checks if the user's subscription plan includes the required features.
|
* Checks if the user's subscription plan includes the required features.
|
||||||
* Uses current subscription data so stale token claims cannot preserve revoked rights.
|
* First tries to read plan from JWT payload (fast path), falls back to DB lookup.
|
||||||
*
|
*
|
||||||
* Usage:
|
* Usage:
|
||||||
* @UseGuards(JwtAuthGuard, RolesGuard, FeatureFlagGuard)
|
* @UseGuards(JwtAuthGuard, RolesGuard, FeatureFlagGuard)
|
||||||
@ -58,7 +58,19 @@ export class FeatureFlagGuard implements CanActivate {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Always resolve current rights, including after suspension or downgrade.
|
// Fast path: check plan features from JWT payload
|
||||||
|
if (user.planFeatures && Array.isArray(user.planFeatures)) {
|
||||||
|
const hasAllFeatures = requiredFeatures.every(feature => user.planFeatures.includes(feature));
|
||||||
|
|
||||||
|
if (hasAllFeatures) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// JWT says no — but JWT might be stale after an upgrade.
|
||||||
|
// Fall through to DB check.
|
||||||
|
}
|
||||||
|
|
||||||
|
// Slow path: DB lookup for fresh subscription data
|
||||||
try {
|
try {
|
||||||
const subscription = await this.subscriptionRepository.findByOrganizationId(
|
const subscription = await this.subscriptionRepository.findByOrganizationId(
|
||||||
user.organizationId
|
user.organizationId
|
||||||
@ -69,9 +81,8 @@ export class FeatureFlagGuard implements CanActivate {
|
|||||||
this.throwFeatureRequired(requiredFeatures);
|
this.throwFeatureRequired(requiredFeatures);
|
||||||
}
|
}
|
||||||
|
|
||||||
const missingFeatures = requiredFeatures.filter(
|
const plan = subscription!.plan;
|
||||||
feature => !subscription!.hasFeature(feature)
|
const missingFeatures = requiredFeatures.filter(feature => !plan.hasFeature(feature));
|
||||||
);
|
|
||||||
|
|
||||||
if (missingFeatures.length > 0) {
|
if (missingFeatures.length > 0) {
|
||||||
this.throwFeatureRequired(requiredFeatures);
|
this.throwFeatureRequired(requiredFeatures);
|
||||||
|
|||||||
@ -1,90 +0,0 @@
|
|||||||
import { ExecutionContext, ForbiddenException } from '@nestjs/common';
|
|
||||||
import { Reflector } from '@nestjs/core';
|
|
||||||
import { Subscription } from '@domain/entities/subscription.entity';
|
|
||||||
import { SubscriptionPlan } from '@domain/value-objects/subscription-plan.vo';
|
|
||||||
import {
|
|
||||||
SubscriptionStatus,
|
|
||||||
SubscriptionStatusType,
|
|
||||||
} from '@domain/value-objects/subscription-status.vo';
|
|
||||||
import { SubscriptionRepository } from '@domain/ports/out/subscription.repository';
|
|
||||||
import { FeatureFlagGuard } from './feature-flag.guard';
|
|
||||||
|
|
||||||
const subscriptionFor = (status: SubscriptionStatusType) =>
|
|
||||||
Subscription.create({
|
|
||||||
id: 'sub',
|
|
||||||
organizationId: 'org',
|
|
||||||
plan: SubscriptionPlan.gold(),
|
|
||||||
}).updateStatus(SubscriptionStatus.create(status));
|
|
||||||
|
|
||||||
const denied: SubscriptionStatusType[] = [
|
|
||||||
'UNPAID',
|
|
||||||
'PAUSED',
|
|
||||||
'INCOMPLETE',
|
|
||||||
'INCOMPLETE_EXPIRED',
|
|
||||||
'CANCELED',
|
|
||||||
];
|
|
||||||
const allowed: SubscriptionStatusType[] = ['ACTIVE', 'TRIALING', 'PAST_DUE'];
|
|
||||||
|
|
||||||
describe('Current subscription entitlement', () => {
|
|
||||||
it.each(denied)('%s removes paid benefits without erasing billing plan', status => {
|
|
||||||
const subscription = subscriptionFor(status);
|
|
||||||
expect(subscription.hasFeature('api_access')).toBe(false);
|
|
||||||
expect(subscription.maxShipmentsPerYear).toBe(SubscriptionPlan.bronze().maxShipmentsPerYear);
|
|
||||||
expect(subscription.bookingFeeEur).toBe(SubscriptionPlan.bronze().bookingFeeEur);
|
|
||||||
expect(subscription.plan.value).toBe('GOLD');
|
|
||||||
});
|
|
||||||
|
|
||||||
it.each(allowed)('%s retains paid benefits', status => {
|
|
||||||
const subscription = subscriptionFor(status);
|
|
||||||
expect(subscription.hasFeature('api_access')).toBe(true);
|
|
||||||
expect(subscription.maxShipmentsPerYear).toBe(SubscriptionPlan.gold().maxShipmentsPerYear);
|
|
||||||
});
|
|
||||||
|
|
||||||
const setup = (
|
|
||||||
subscription: Subscription | null,
|
|
||||||
role = 'MANAGER',
|
|
||||||
planFeatures = ['user_management']
|
|
||||||
) => {
|
|
||||||
const findByOrganizationId = jest.fn().mockResolvedValue(subscription);
|
|
||||||
const reflector = { getAllAndOverride: jest.fn().mockReturnValue(['user_management']) };
|
|
||||||
const guard = new FeatureFlagGuard(
|
|
||||||
reflector as unknown as Reflector,
|
|
||||||
{ findByOrganizationId } as unknown as SubscriptionRepository
|
|
||||||
);
|
|
||||||
const context = {
|
|
||||||
getHandler: () => undefined,
|
|
||||||
getClass: () => undefined,
|
|
||||||
switchToHttp: () => ({
|
|
||||||
getRequest: () => ({ user: { organizationId: 'org', role, planFeatures } }),
|
|
||||||
}),
|
|
||||||
} as unknown as ExecutionContext;
|
|
||||||
return { guard, context, findByOrganizationId };
|
|
||||||
};
|
|
||||||
|
|
||||||
it.each(denied)('%s cannot be bypassed by stale token features', async status => {
|
|
||||||
const { guard, context } = setup(subscriptionFor(status));
|
|
||||||
await expect(guard.canActivate(context)).rejects.toBeInstanceOf(ForbiddenException);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('denies a deleted subscription even with paid token features', async () => {
|
|
||||||
const { guard, context } = setup(null);
|
|
||||||
await expect(guard.canActivate(context)).rejects.toBeInstanceOf(ForbiddenException);
|
|
||||||
});
|
|
||||||
|
|
||||||
it.each(allowed)('%s allows current rights despite an old Bronze token', async status => {
|
|
||||||
const { guard, context } = setup(subscriptionFor(status), 'MANAGER', []);
|
|
||||||
await expect(guard.canActivate(context)).resolves.toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('preserves the platform ADMIN override', async () => {
|
|
||||||
const { guard, context, findByOrganizationId } = setup(null, 'ADMIN');
|
|
||||||
await expect(guard.canActivate(context)).resolves.toBe(true);
|
|
||||||
expect(findByOrganizationId).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('fails closed when current rights cannot be loaded', async () => {
|
|
||||||
const { guard, context, findByOrganizationId } = setup(subscriptionFor('ACTIVE'));
|
|
||||||
findByOrganizationId.mockRejectedValue(new Error('unavailable'));
|
|
||||||
await expect(guard.canActivate(context)).rejects.toBeInstanceOf(ForbiddenException);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@ -1,4 +1,3 @@
|
|||||||
import { safeRequestRoute } from '../logging/safe-http-log';
|
|
||||||
/**
|
/**
|
||||||
* Performance Monitoring Interceptor
|
* Performance Monitoring Interceptor
|
||||||
*
|
*
|
||||||
@ -16,8 +15,7 @@ export class PerformanceMonitoringInterceptor implements NestInterceptor {
|
|||||||
|
|
||||||
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
|
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
|
||||||
const request = context.switchToHttp().getRequest();
|
const request = context.switchToHttp().getRequest();
|
||||||
const { method, user } = request;
|
const { method, url, user } = request;
|
||||||
const url = safeRequestRoute(request);
|
|
||||||
const startTime = Date.now();
|
const startTime = Date.now();
|
||||||
|
|
||||||
return next.handle().pipe(
|
return next.handle().pipe(
|
||||||
@ -41,7 +39,10 @@ export class PerformanceMonitoringInterceptor implements NestInterceptor {
|
|||||||
const duration = Date.now() - startTime;
|
const duration = Date.now() - startTime;
|
||||||
|
|
||||||
// Log error
|
// Log error
|
||||||
this.logger.error(`Request error: ${method} ${url} (${duration}ms)`);
|
this.logger.error(
|
||||||
|
`Request error: ${method} ${url} (${duration}ms) - ${error.message}`,
|
||||||
|
error.stack
|
||||||
|
);
|
||||||
|
|
||||||
// Capture exception in Sentry
|
// Capture exception in Sentry
|
||||||
Sentry.withScope(scope => {
|
Sentry.withScope(scope => {
|
||||||
@ -51,7 +52,7 @@ export class PerformanceMonitoringInterceptor implements NestInterceptor {
|
|||||||
userId: user?.sub,
|
userId: user?.sub,
|
||||||
duration,
|
duration,
|
||||||
});
|
});
|
||||||
Sentry.captureException(new Error('Request failed; sensitive error details omitted'));
|
Sentry.captureException(error);
|
||||||
});
|
});
|
||||||
|
|
||||||
throw error;
|
throw error;
|
||||||
|
|||||||
@ -1,103 +0,0 @@
|
|||||||
import pino from 'pino';
|
|
||||||
import { Logger, ArgumentsHost, NotFoundException } from '@nestjs/common';
|
|
||||||
import { safeHttpSerializers, safeRequestRoute } from './safe-http-log';
|
|
||||||
import { UnhandledExceptionFilter } from '../filters/unhandled-exception.filter';
|
|
||||||
import { CsvBookingService } from '../services/csv-booking.service';
|
|
||||||
import { InvitationsController } from '../controllers/invitations.controller';
|
|
||||||
import { TypeOrmCsvBookingRepository } from '@infrastructure/persistence/typeorm/repositories/csv-booking.repository';
|
|
||||||
|
|
||||||
const secret = 'test-secret-not-for-logs';
|
|
||||||
|
|
||||||
describe('Capability-safe logs', () => {
|
|
||||||
afterEach(() => jest.restoreAllMocks());
|
|
||||||
|
|
||||||
it('serializes real Pino events without request, response or driver secrets', () => {
|
|
||||||
let output = '';
|
|
||||||
const logger = pino(
|
|
||||||
{ serializers: safeHttpSerializers },
|
|
||||||
{
|
|
||||||
write: (line: string) => {
|
|
||||||
output += line;
|
|
||||||
},
|
|
||||||
}
|
|
||||||
);
|
|
||||||
logger.error(
|
|
||||||
{
|
|
||||||
req: {
|
|
||||||
method: 'GET',
|
|
||||||
url: `/api/v1/invitations/verify/${secret}?password=${secret}`,
|
|
||||||
headers: { cookie: secret, referer: secret },
|
|
||||||
params: { token: secret },
|
|
||||||
body: { password: secret },
|
|
||||||
raw: { route: { path: '/api/v1/invitations/verify/:token' } },
|
|
||||||
},
|
|
||||||
res: { statusCode: 500, headers: { 'set-cookie': secret } },
|
|
||||||
err: Object.assign(new Error(secret), {
|
|
||||||
query: secret,
|
|
||||||
parameters: [secret],
|
|
||||||
cause: new Error(secret),
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
'request failed'
|
|
||||||
);
|
|
||||||
expect(output).not.toContain(secret);
|
|
||||||
expect(JSON.parse(output)).toMatchObject({
|
|
||||||
req: { method: 'GET', route: '/api/v1/invitations/verify/:token' },
|
|
||||||
res: { statusCode: 500 },
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('does not fall back to a raw or encoded path on an unmatched request', () => {
|
|
||||||
expect(safeRequestRoute({ url: `/api/v1/%69nvitations/verify/${secret}` })).toBe(
|
|
||||||
'[unmatched route]'
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('keeps correlation without raw exception details or URL in the global filter', () => {
|
|
||||||
const errorLog = jest.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined);
|
|
||||||
const json = jest.fn();
|
|
||||||
const status = jest.fn().mockReturnValue({ json });
|
|
||||||
const host = {
|
|
||||||
switchToHttp: () => ({
|
|
||||||
getRequest: () => ({ method: 'GET', url: `/${secret}`, headers: {} }),
|
|
||||||
getResponse: () => ({ status }),
|
|
||||||
}),
|
|
||||||
} as unknown as ArgumentsHost;
|
|
||||||
new UnhandledExceptionFilter({ translate: () => 'Please retry' } as never).catch(
|
|
||||||
new Error(secret),
|
|
||||||
host
|
|
||||||
);
|
|
||||||
expect(JSON.stringify(errorLog.mock.calls)).not.toContain(secret);
|
|
||||||
expect(JSON.stringify(json.mock.calls)).not.toContain(secret);
|
|
||||||
expect(json.mock.calls[0][0].reference).toBeTruthy();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('does not log tokens across controller, service and repository lookup paths', async () => {
|
|
||||||
const logs = jest.spyOn(Logger.prototype, 'log').mockImplementation(() => undefined);
|
|
||||||
const orm = { findOne: jest.fn().mockResolvedValue(null) };
|
|
||||||
const repository = new TypeOrmCsvBookingRepository(orm as never);
|
|
||||||
const service = new CsvBookingService(
|
|
||||||
repository,
|
|
||||||
{} as never,
|
|
||||||
{} as never,
|
|
||||||
{} as never,
|
|
||||||
{} as never,
|
|
||||||
{} as never,
|
|
||||||
{} as never
|
|
||||||
);
|
|
||||||
for (const call of [
|
|
||||||
() => service.getBookingByToken(secret),
|
|
||||||
() => service.acceptBooking(secret),
|
|
||||||
() => service.rejectBooking(secret),
|
|
||||||
]) {
|
|
||||||
await expect(call()).rejects.toBeInstanceOf(NotFoundException);
|
|
||||||
}
|
|
||||||
await expect(service.getBookingByToken(secret)).rejects.not.toThrow(secret);
|
|
||||||
const controller = new InvitationsController({
|
|
||||||
verifyInvitation: jest.fn().mockRejectedValue(new NotFoundException('not found')),
|
|
||||||
} as never);
|
|
||||||
await expect(controller.verifyInvitation(secret)).rejects.toBeInstanceOf(NotFoundException);
|
|
||||||
expect(JSON.stringify(logs.mock.calls)).not.toContain(secret);
|
|
||||||
expect(orm.findOne).toHaveBeenCalledWith({ where: { confirmationToken: secret } });
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@ -1,24 +0,0 @@
|
|||||||
/** Log server-owned routing metadata, never credentials carried by URLs or headers. */
|
|
||||||
export function safeRequestRoute(request: unknown): string {
|
|
||||||
if (!request || typeof request !== 'object') return '[unmatched route]';
|
|
||||||
const req = request as { route?: { path?: unknown }; raw?: { route?: { path?: unknown } } };
|
|
||||||
const path = req.route?.path ?? req.raw?.route?.path;
|
|
||||||
return typeof path === 'string' ? path : '[unmatched route]';
|
|
||||||
}
|
|
||||||
|
|
||||||
export const safeHttpSerializers = {
|
|
||||||
req(request: {
|
|
||||||
method?: string;
|
|
||||||
route?: { path?: unknown };
|
|
||||||
raw?: { route?: { path?: unknown } };
|
|
||||||
}) {
|
|
||||||
return { method: request.method, route: safeRequestRoute(request) };
|
|
||||||
},
|
|
||||||
res(response: { statusCode?: number }) {
|
|
||||||
return { statusCode: response.statusCode };
|
|
||||||
},
|
|
||||||
err(_error: unknown) {
|
|
||||||
// Driver/SMTP errors can contain SQL parameters, tokens, headers or message bodies.
|
|
||||||
return { type: 'Error', message: 'Request failed; sensitive error details omitted' };
|
|
||||||
},
|
|
||||||
};
|
|
||||||
@ -1,148 +0,0 @@
|
|||||||
import { TradePassage, TradeRetrievalPort } from '@domain/ports/out/trade-assistant.port';
|
|
||||||
import {
|
|
||||||
WikiContribution,
|
|
||||||
WikiContributionStatus,
|
|
||||||
} from '@domain/entities/wiki-contribution.entity';
|
|
||||||
import { WikiContributionRepository } from '@domain/ports/out/wiki-contribution.repository';
|
|
||||||
import { CapabilityActor } from '@domain/services/capability-access';
|
|
||||||
import { Capability, CapabilityInputError, parseInput } from '../capability';
|
|
||||||
import { knowledgeCapabilities } from './knowledge.capabilities';
|
|
||||||
|
|
||||||
const actor: CapabilityActor = { id: 'user', organizationId: 'org', role: 'MANAGER' };
|
|
||||||
|
|
||||||
const BODY = `La règle du 24 heures impose de transmettre le manifeste de cargaison aux douanes du pays de destination avant le chargement du navire au port d'embarquement. Elle s'applique au transport maritime international et conditionne l'autorisation de charger. Un dépôt tardif expose l'expéditeur à un refus d'embarquement et à une immobilisation du conteneur au terminal.`;
|
|
||||||
|
|
||||||
const page = {
|
|
||||||
topic: 'douanes',
|
|
||||||
title: 'La règle des 24 heures',
|
|
||||||
section: 'Dépôt du manifeste',
|
|
||||||
body: BODY,
|
|
||||||
};
|
|
||||||
|
|
||||||
/** Passe l'entree par le meme schema que le registre, comme en production. */
|
|
||||||
const invoke = (capability: Capability, input: Record<string, unknown>) =>
|
|
||||||
capability.handler(parseInput(capability.inputSchema, input), actor);
|
|
||||||
|
|
||||||
describe('knowledgeCapabilities', () => {
|
|
||||||
let retrieval: jest.Mocked<TradeRetrievalPort>;
|
|
||||||
let contributions: jest.Mocked<WikiContributionRepository>;
|
|
||||||
|
|
||||||
const contribute = () => {
|
|
||||||
const capability = knowledgeCapabilities(retrieval, contributions).find(
|
|
||||||
c => c.policy.name === 'contribute_wiki_page'
|
|
||||||
);
|
|
||||||
if (!capability) throw new Error('contribute_wiki_page is not published');
|
|
||||||
return capability;
|
|
||||||
};
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
retrieval = { search: jest.fn().mockResolvedValue([]) };
|
|
||||||
contributions = {
|
|
||||||
findPublished: jest.fn().mockResolvedValue([]),
|
|
||||||
findForReview: jest.fn().mockResolvedValue([]),
|
|
||||||
findById: jest.fn().mockResolvedValue(null),
|
|
||||||
findByTitle: jest.fn().mockResolvedValue(null),
|
|
||||||
save: jest.fn().mockImplementation((c: WikiContribution) => Promise.resolve(c)),
|
|
||||||
revision: jest.fn().mockResolvedValue('0:none'),
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
it('keeps the wiki read-only when no repository is wired', () => {
|
|
||||||
expect(knowledgeCapabilities(retrieval).map(c => c.policy.name)).toEqual([
|
|
||||||
'search_documentation',
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('declares the contribution as a write', () => {
|
|
||||||
expect(contribute().policy).toEqual({ name: 'contribute_wiki_page', scope: 'write' });
|
|
||||||
});
|
|
||||||
|
|
||||||
it('proposes a page the wiki does not cover, without publishing it', async () => {
|
|
||||||
const result = await invoke(contribute(), page);
|
|
||||||
|
|
||||||
expect(contributions.save).toHaveBeenCalledTimes(1);
|
|
||||||
const saved: WikiContribution = contributions.save.mock.calls[0][0];
|
|
||||||
expect(saved.title).toBe(page.title);
|
|
||||||
expect(saved.locale).toBe('fr');
|
|
||||||
expect(saved.authorUserId).toBe('user');
|
|
||||||
|
|
||||||
// Rien n'entre dans le wiki sans relecture : ni le statut, ni le resultat
|
|
||||||
// rendu au modele ne doivent laisser croire le contraire.
|
|
||||||
expect(saved.status).toBe(WikiContributionStatus.PENDING);
|
|
||||||
expect(result).toMatchObject({ status: 'pending_review' });
|
|
||||||
expect(result).not.toHaveProperty('url');
|
|
||||||
expect((result as { message: string }).message).toMatch(/validation par un administrateur/);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('refuses a page the wiki already covers', async () => {
|
|
||||||
const covered: TradePassage = {
|
|
||||||
id: 'fr:douanes:2',
|
|
||||||
title: 'Procédures Douanières',
|
|
||||||
section: 'Manifeste',
|
|
||||||
href: '/dashboard/wiki/douanes',
|
|
||||||
text: 'La règle des 24 heures…',
|
|
||||||
score: 0.71,
|
|
||||||
};
|
|
||||||
retrieval.search.mockResolvedValue([covered]);
|
|
||||||
|
|
||||||
await expect(invoke(contribute(), page)).rejects.toThrow(CapabilityInputError);
|
|
||||||
expect(contributions.save).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('updates the existing page instead of duplicating the subject', async () => {
|
|
||||||
const existing = WikiContribution.create({
|
|
||||||
id: 'w1',
|
|
||||||
locale: 'fr',
|
|
||||||
...page,
|
|
||||||
authorUserId: 'user',
|
|
||||||
authorOrganizationId: 'org',
|
|
||||||
});
|
|
||||||
contributions.findByTitle.mockResolvedValue(existing);
|
|
||||||
|
|
||||||
const result = await invoke(contribute(), {
|
|
||||||
...page,
|
|
||||||
body: `${BODY} Le manifeste est déposé par le transitaire.`,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Une revision ne repasse pas par le test de couverture : la page qu'elle
|
|
||||||
// remplace est justement celle que la recherche remonterait.
|
|
||||||
expect(retrieval.search).not.toHaveBeenCalled();
|
|
||||||
expect(contributions.save.mock.calls[0][0].id).toBe('w1');
|
|
||||||
expect(result).toMatchObject({ status: 'pending_review' });
|
|
||||||
});
|
|
||||||
|
|
||||||
it('does not withdraw a published page even for its original author', async () => {
|
|
||||||
const published = WikiContribution.create({
|
|
||||||
id: 'w1',
|
|
||||||
locale: 'fr',
|
|
||||||
...page,
|
|
||||||
authorUserId: actor.id,
|
|
||||||
authorOrganizationId: actor.organizationId,
|
|
||||||
}).publish('admin');
|
|
||||||
contributions.findByTitle.mockResolvedValue(published);
|
|
||||||
await expect(invoke(contribute(), page)).rejects.toThrow(CapabilityInputError);
|
|
||||||
expect(contributions.save).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('refuses content that recommends FCL, with a message the assistant can relay', async () => {
|
|
||||||
const body = `${BODY} Au-delà de 15 m³, nous recommandons le FCL.`;
|
|
||||||
|
|
||||||
await expect(invoke(contribute(), { ...page, body })).rejects.toThrow(
|
|
||||||
/ne publie pas de contenu qui recommande le FCL/
|
|
||||||
);
|
|
||||||
expect(contributions.save).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('refuses account-specific content', async () => {
|
|
||||||
const body = `${BODY} Pour votre dossier, le manifeste est parti le 3 mars.`;
|
|
||||||
|
|
||||||
await expect(invoke(contribute(), { ...page, body })).rejects.toThrow(/wiki est global/);
|
|
||||||
expect(contributions.save).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('rejects an unknown topic at the schema, before reaching the domain', () => {
|
|
||||||
expect(() => parseInput(contribute().inputSchema, { ...page, topic: 'divers' })).toThrow(
|
|
||||||
CapabilityInputError
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@ -1,46 +1,14 @@
|
|||||||
import { randomUUID } from 'crypto';
|
|
||||||
import { TradeRetrievalPort } from '@domain/ports/out/trade-assistant.port';
|
import { TradeRetrievalPort } from '@domain/ports/out/trade-assistant.port';
|
||||||
import {
|
import { Capability } from '../capability';
|
||||||
WikiContributionConflict,
|
|
||||||
WikiContributionRepository,
|
|
||||||
} from '@domain/ports/out/wiki-contribution.repository';
|
|
||||||
import {
|
|
||||||
WikiContribution,
|
|
||||||
WikiContributionRejected,
|
|
||||||
WikiContributionStatus,
|
|
||||||
} from '@domain/entities/wiki-contribution.entity';
|
|
||||||
import {
|
|
||||||
WIKI_REFUSAL_MESSAGES,
|
|
||||||
WIKI_TOPICS,
|
|
||||||
WikiRefusal,
|
|
||||||
} from '@domain/services/wiki-contribution-policy';
|
|
||||||
import { Capability, CapabilityInputError } from '../capability';
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Le wiki Xpeditis, en lecture et en ecriture.
|
* Documentation du site, exposee comme capacite.
|
||||||
*
|
*
|
||||||
* **Lecture.** Le meme index que l'assistant integre : un agent externe repond
|
* Le meme index que l'assistant integre : un agent externe repond donc a partir
|
||||||
* a partir de la documentation interne, avec les liens vers les pages, plutot
|
* du wiki Xpeditis, avec les liens vers les pages, plutot que de ses propres
|
||||||
* que de ses propres souvenirs sur le fret maritime.
|
* souvenirs sur le fret maritime.
|
||||||
*
|
|
||||||
* **Ecriture.** Le wiki a des trous, et ils se voient a l'usage : une question
|
|
||||||
* revient, la recherche ne remonte rien, l'assistant repond de memoire et la
|
|
||||||
* reponse n'est citable nulle part. `contribute_wiki_page` ferme ce trou au
|
|
||||||
* moment ou il apparait — mais seulement pour du savoir general sur le
|
|
||||||
* transport international, jamais pour un cas client. Les regles sont dans le
|
|
||||||
* domaine (`wiki-contribution-policy`), pas dans la description ci-dessous :
|
|
||||||
* le modele lit la description, il ne franchit que la politique.
|
|
||||||
*
|
|
||||||
* L'ecriture **propose**, elle ne publie pas. Une heuristique ecarte la faute
|
|
||||||
* franche, elle ne juge pas la justesse : la page part en relecture, et c'est
|
|
||||||
* un administrateur qui la fait entrer dans le wiki. Le nom de la capacite dit
|
|
||||||
* « contribuer », son resultat dit « en attente » — le modele doit annoncer une
|
|
||||||
* proposition, pas une publication.
|
|
||||||
*/
|
*/
|
||||||
export function knowledgeCapabilities(
|
export function knowledgeCapabilities(retrieval: TradeRetrievalPort): Capability[] {
|
||||||
retrieval: TradeRetrievalPort,
|
|
||||||
contributions?: WikiContributionRepository
|
|
||||||
): Capability[] {
|
|
||||||
return [
|
return [
|
||||||
{
|
{
|
||||||
policy: { name: 'search_documentation', scope: 'read' },
|
policy: { name: 'search_documentation', scope: 'read' },
|
||||||
@ -89,159 +57,5 @@ export function knowledgeCapabilities(
|
|||||||
};
|
};
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
...(contributions ? [contributeWikiPage(retrieval, contributions)] : []),
|
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Au-dessus de ce score, la recherche a trouve une page qui traite deja le
|
|
||||||
* sujet : contribuer reviendrait a ecrire une seconde version de ce que le
|
|
||||||
* wiki dit deja. Le seuil est au-dessus de celui de la recherche (0,45, voir
|
|
||||||
* `wiki-retriever`) : « en rapport avec » n'est pas « deja couvert ».
|
|
||||||
*/
|
|
||||||
const ALREADY_COVERED_SCORE = 0.62;
|
|
||||||
|
|
||||||
function contributeWikiPage(
|
|
||||||
retrieval: TradeRetrievalPort,
|
|
||||||
contributions: WikiContributionRepository
|
|
||||||
): Capability {
|
|
||||||
return {
|
|
||||||
policy: { name: 'contribute_wiki_page', scope: 'write' },
|
|
||||||
description:
|
|
||||||
"Propose au wiki Xpeditis une page d'information générale sur le transport international, quand la documentation ne couvre pas le sujet. La page part en relecture : elle n'est publiée qu'après validation par un administrateur. Réservé au savoir durable et valable pour tous les clients : jamais un cas client, un dossier, un tarif, un contenu recommandant le FCL, ni un sujet de transport national. Met à jour uniquement votre propre proposition non publiée si le titre est déjà pris.",
|
|
||||||
inputSchema: {
|
|
||||||
type: 'object',
|
|
||||||
properties: {
|
|
||||||
topic: {
|
|
||||||
type: 'string',
|
|
||||||
description: 'Sujet du wiki auquel rattacher la page.',
|
|
||||||
enum: WIKI_TOPICS,
|
|
||||||
},
|
|
||||||
title: {
|
|
||||||
type: 'string',
|
|
||||||
description: 'Titre de la page, court et descriptif.',
|
|
||||||
minLength: 5,
|
|
||||||
maxLength: 120,
|
|
||||||
},
|
|
||||||
section: {
|
|
||||||
type: 'string',
|
|
||||||
description: 'Intitulé de la section documentée.',
|
|
||||||
minLength: 3,
|
|
||||||
maxLength: 120,
|
|
||||||
},
|
|
||||||
body: {
|
|
||||||
type: 'string',
|
|
||||||
description:
|
|
||||||
'Le contenu, rédigé comme une page de documentation : autonome, factuel, sans cas client ni tarif.',
|
|
||||||
minLength: 200,
|
|
||||||
maxLength: 6000,
|
|
||||||
},
|
|
||||||
language: {
|
|
||||||
type: 'string',
|
|
||||||
description: 'Langue de rédaction.',
|
|
||||||
enum: ['fr', 'en'],
|
|
||||||
default: 'fr',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
required: ['topic', 'title', 'section', 'body'],
|
|
||||||
additionalProperties: false,
|
|
||||||
},
|
|
||||||
handler: async (input, actor) => {
|
|
||||||
const locale = (input.language as string) ?? 'fr';
|
|
||||||
const topic = input.topic as string;
|
|
||||||
const title = input.title as string;
|
|
||||||
const section = input.section as string;
|
|
||||||
const body = input.body as string;
|
|
||||||
|
|
||||||
const existing = await contributions.findByTitle(locale, topic, title);
|
|
||||||
|
|
||||||
if (
|
|
||||||
existing &&
|
|
||||||
(existing.authorUserId !== actor.id ||
|
|
||||||
existing.authorOrganizationId !== actor.organizationId ||
|
|
||||||
existing.status === WikiContributionStatus.PUBLISHED)
|
|
||||||
) {
|
|
||||||
throw new CapabilityInputError(
|
|
||||||
'Cette page ne peut pas être modifiée par cette contribution.'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Le doublon n'est teste que pour une page nouvelle : reviser un
|
|
||||||
// complement existant se heurterait sinon a ce complement lui-meme.
|
|
||||||
if (!existing) {
|
|
||||||
const covered = await alreadyCovered(retrieval, `${title} ${section}`, locale);
|
|
||||||
if (covered) {
|
|
||||||
throw new CapabilityInputError(
|
|
||||||
`Le wiki traite déjà ce sujet : « ${covered} ». Citez cette page au lieu d'en créer une autre.`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const page = reject(() =>
|
|
||||||
existing
|
|
||||||
? existing.revise(section, body)
|
|
||||||
: WikiContribution.create({
|
|
||||||
id: randomUUID(),
|
|
||||||
locale,
|
|
||||||
topic,
|
|
||||||
title,
|
|
||||||
section,
|
|
||||||
body,
|
|
||||||
authorUserId: actor.id,
|
|
||||||
authorOrganizationId: actor.organizationId,
|
|
||||||
})
|
|
||||||
);
|
|
||||||
|
|
||||||
let saved: WikiContribution;
|
|
||||||
try {
|
|
||||||
saved = await contributions.save(page, actor);
|
|
||||||
} catch (error) {
|
|
||||||
if (error instanceof WikiContributionConflict) {
|
|
||||||
throw new CapabilityInputError(
|
|
||||||
'La proposition a changé ou ce titre est déjà utilisé. Relisez la page avant de réessayer.'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
// Le resultat dit l'etat reel, pas l'intention : le modele annonce une
|
|
||||||
// proposition en attente, jamais une page publiee.
|
|
||||||
status: 'pending_review' as const,
|
|
||||||
title: saved.title,
|
|
||||||
section: saved.section,
|
|
||||||
message: existing
|
|
||||||
? 'Proposition mise à jour. Elle sera publiée après validation par un administrateur Xpeditis.'
|
|
||||||
: 'Proposition enregistrée. Elle sera publiée après validation par un administrateur Xpeditis.',
|
|
||||||
};
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Titre de la page qui couvre deja le sujet, s'il y en a une. */
|
|
||||||
async function alreadyCovered(
|
|
||||||
retrieval: TradeRetrievalPort,
|
|
||||||
query: string,
|
|
||||||
locale: string
|
|
||||||
): Promise<string | null> {
|
|
||||||
const [best] = await retrieval.search(query, locale, 1);
|
|
||||||
return best && best.score >= ALREADY_COVERED_SCORE ? `${best.title} — ${best.section}` : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Traduit un refus du domaine en erreur d'entree.
|
|
||||||
*
|
|
||||||
* `CapabilityInputError` revient au modele avec son message : il peut
|
|
||||||
* l'expliquer a l'utilisateur, ce qu'une exception technique ne permettrait
|
|
||||||
* pas.
|
|
||||||
*/
|
|
||||||
function reject(build: () => WikiContribution): WikiContribution {
|
|
||||||
try {
|
|
||||||
return build();
|
|
||||||
} catch (error) {
|
|
||||||
if (error instanceof WikiContributionRejected) {
|
|
||||||
throw new CapabilityInputError(WIKI_REFUSAL_MESSAGES[error.message as WikiRefusal]);
|
|
||||||
}
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@ -1,10 +1,4 @@
|
|||||||
import {
|
import { ForbiddenException, Inject, Injectable, NotFoundException } from '@nestjs/common';
|
||||||
ForbiddenException,
|
|
||||||
Inject,
|
|
||||||
Injectable,
|
|
||||||
NotFoundException,
|
|
||||||
Optional,
|
|
||||||
} from '@nestjs/common';
|
|
||||||
import { TRADE_RETRIEVAL, TradeRetrievalPort } from '@domain/ports/out/trade-assistant.port';
|
import { TRADE_RETRIEVAL, TradeRetrievalPort } from '@domain/ports/out/trade-assistant.port';
|
||||||
import { CsvRateSearchService } from '@domain/services/csv-rate-search.service';
|
import { CsvRateSearchService } from '@domain/services/csv-rate-search.service';
|
||||||
import {
|
import {
|
||||||
@ -18,10 +12,6 @@ import {
|
|||||||
ORGANIZATION_REPOSITORY,
|
ORGANIZATION_REPOSITORY,
|
||||||
OrganizationRepository,
|
OrganizationRepository,
|
||||||
} from '@domain/ports/out/organization.repository';
|
} from '@domain/ports/out/organization.repository';
|
||||||
import {
|
|
||||||
WIKI_CONTRIBUTION_REPOSITORY,
|
|
||||||
WikiContributionRepository,
|
|
||||||
} from '@domain/ports/out/wiki-contribution.repository';
|
|
||||||
import { AuditService } from '../services/audit.service';
|
import { AuditService } from '../services/audit.service';
|
||||||
import { CsvBookingService } from '../services/csv-booking.service';
|
import { CsvBookingService } from '../services/csv-booking.service';
|
||||||
import { SubscriptionService } from '../services/subscription.service';
|
import { SubscriptionService } from '../services/subscription.service';
|
||||||
@ -56,15 +46,11 @@ export class CapabilityRegistry {
|
|||||||
subscriptions: SubscriptionService,
|
subscriptions: SubscriptionService,
|
||||||
@Inject(USER_REPOSITORY) users: UserRepository,
|
@Inject(USER_REPOSITORY) users: UserRepository,
|
||||||
@Inject(ORGANIZATION_REPOSITORY) organizations: OrganizationRepository,
|
@Inject(ORGANIZATION_REPOSITORY) organizations: OrganizationRepository,
|
||||||
private readonly audit: AuditService,
|
private readonly audit: AuditService
|
||||||
// Optionnel : sans depot, le wiki reste en lecture seule pour les agents.
|
|
||||||
@Optional()
|
|
||||||
@Inject(WIKI_CONTRIBUTION_REPOSITORY)
|
|
||||||
wikiContributions?: WikiContributionRepository
|
|
||||||
) {
|
) {
|
||||||
this.capabilities = [
|
this.capabilities = [
|
||||||
...accountCapabilities(subscriptions),
|
...accountCapabilities(subscriptions),
|
||||||
...knowledgeCapabilities(retrieval, wikiContributions),
|
...knowledgeCapabilities(retrieval),
|
||||||
...ratesCapabilities(rateSearch),
|
...ratesCapabilities(rateSearch),
|
||||||
...bookingsCapabilities(bookings),
|
...bookingsCapabilities(bookings),
|
||||||
...adminCapabilities(users, organizations, rateSearch),
|
...adminCapabilities(users, organizations, rateSearch),
|
||||||
|
|||||||
@ -1,69 +0,0 @@
|
|||||||
import { Subscription } from '@domain/entities/subscription.entity';
|
|
||||||
import { SubscriptionPlan } from '@domain/value-objects/subscription-plan.vo';
|
|
||||||
import {
|
|
||||||
SubscriptionStatus,
|
|
||||||
SubscriptionStatusType,
|
|
||||||
} from '@domain/value-objects/subscription-status.vo';
|
|
||||||
import { McpController } from './mcp.controller';
|
|
||||||
import { CapabilityRegistry } from './capability.registry';
|
|
||||||
import { SubscriptionService } from '../services/subscription.service';
|
|
||||||
|
|
||||||
// Real registry and account capability: stale client claims must not be echoed as rights.
|
|
||||||
describe('MCP current entitlement', () => {
|
|
||||||
it.each<[SubscriptionStatusType, string, string]>([
|
|
||||||
['UNPAID', 'MANAGER', 'BRONZE'],
|
|
||||||
['PAUSED', 'MANAGER', 'BRONZE'],
|
|
||||||
['ACTIVE', 'MANAGER', 'GOLD'],
|
|
||||||
['TRIALING', 'MANAGER', 'GOLD'],
|
|
||||||
['PAST_DUE', 'MANAGER', 'GOLD'],
|
|
||||||
['UNPAID', 'ADMIN', 'PLATINIUM'],
|
|
||||||
])('%s resolves live rights for %s', async (status, role, expected) => {
|
|
||||||
const subscription = Subscription.create({
|
|
||||||
id: 'sub',
|
|
||||||
organizationId: 'org',
|
|
||||||
plan: SubscriptionPlan.gold(),
|
|
||||||
}).updateStatus(SubscriptionStatus.create(status));
|
|
||||||
const subscriptions = { getOrCreateSubscription: jest.fn().mockResolvedValue(subscription) };
|
|
||||||
const registry = new CapabilityRegistry(
|
|
||||||
{} as never,
|
|
||||||
{} as never,
|
|
||||||
{} as never,
|
|
||||||
subscriptions as unknown as SubscriptionService,
|
|
||||||
{} as never,
|
|
||||||
{} as never,
|
|
||||||
{ log: jest.fn().mockResolvedValue(undefined) } as never
|
|
||||||
);
|
|
||||||
const controller = new McpController(registry, subscriptions as unknown as SubscriptionService);
|
|
||||||
const user = {
|
|
||||||
id: 'user',
|
|
||||||
organizationId: 'org',
|
|
||||||
email: 'test@example.test',
|
|
||||||
firstName: 'Test',
|
|
||||||
lastName: 'User',
|
|
||||||
role,
|
|
||||||
plan: 'GOLD',
|
|
||||||
};
|
|
||||||
const result = await controller.rpc(user, {
|
|
||||||
jsonrpc: '2.0',
|
|
||||||
id: 1,
|
|
||||||
method: 'tools/call',
|
|
||||||
params: { name: 'whoami' },
|
|
||||||
});
|
|
||||||
expect(result).toMatchObject({
|
|
||||||
result: {
|
|
||||||
isError: false,
|
|
||||||
content: [
|
|
||||||
{
|
|
||||||
type: 'text',
|
|
||||||
text: JSON.stringify(
|
|
||||||
{ userId: 'user', organizationId: 'org', role, plan: expected },
|
|
||||||
null,
|
|
||||||
2
|
|
||||||
),
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
});
|
|
||||||
expect(subscriptions.getOrCreateSubscription).toHaveBeenCalledWith('org');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@ -155,17 +155,28 @@ export class McpController {
|
|||||||
/**
|
/**
|
||||||
* Identite de l'appelant, completee de son offre.
|
* Identite de l'appelant, completee de son offre.
|
||||||
*
|
*
|
||||||
* L'offre est relue a chaque appel pour appliquer les suspensions et les
|
* Une cle API porte deja l'offre ; un jeton JWT ne la porte pas, elle est
|
||||||
* changements de droits, meme si un jeton porte encore une ancienne offre.
|
* alors lue sur l'abonnement. Sans cette resolution, un utilisateur connecte
|
||||||
|
* a l'application serait traite comme un compte Bronze.
|
||||||
*/
|
*/
|
||||||
private async actorOf(user: UserPayload & { plan?: string }): Promise<CapabilityActor> {
|
private async actorOf(user: UserPayload & { plan?: string }): Promise<CapabilityActor> {
|
||||||
|
if (user.plan) {
|
||||||
|
return {
|
||||||
|
id: user.id,
|
||||||
|
organizationId: user.organizationId,
|
||||||
|
role: user.role,
|
||||||
|
email: user.email,
|
||||||
|
plan: user.plan,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
const subscription = await this.subscriptions.getOrCreateSubscription(user.organizationId);
|
const subscription = await this.subscriptions.getOrCreateSubscription(user.organizationId);
|
||||||
return {
|
return {
|
||||||
id: user.id,
|
id: user.id,
|
||||||
organizationId: user.organizationId,
|
organizationId: user.organizationId,
|
||||||
role: user.role,
|
role: user.role,
|
||||||
email: user.email,
|
email: user.email,
|
||||||
plan: subscription.accessPlan.value,
|
plan: subscription.plan.value,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,9 +1,7 @@
|
|||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
import { TRADE_RETRIEVAL, TRADE_EMBEDDINGS } from '@domain/ports/out/trade-assistant.port';
|
import { TRADE_RETRIEVAL, TRADE_EMBEDDINGS } from '@domain/ports/out/trade-assistant.port';
|
||||||
import { OpenAiEmbeddingAdapter } from '@infrastructure/ai/openai-embedding.adapter';
|
import { OpenAiEmbeddingAdapter } from '@infrastructure/ai/openai-embedding.adapter';
|
||||||
import { WIKI_CONTRIBUTION_REPOSITORY } from '@domain/ports/out/wiki-contribution.repository';
|
|
||||||
import { WikiRetriever } from '@infrastructure/ai/wiki-retriever';
|
import { WikiRetriever } from '@infrastructure/ai/wiki-retriever';
|
||||||
import { TypeOrmWikiContributionRepository } from '@infrastructure/persistence/typeorm/repositories/typeorm-wiki-contribution.repository';
|
|
||||||
import { CsvRateModule } from '@infrastructure/carriers/csv-loader/csv-rate.module';
|
import { CsvRateModule } from '@infrastructure/carriers/csv-loader/csv-rate.module';
|
||||||
import { AuditModule } from '../audit/audit.module';
|
import { AuditModule } from '../audit/audit.module';
|
||||||
import { CsvBookingsModule } from '../csv-bookings/csv-bookings.module';
|
import { CsvBookingsModule } from '../csv-bookings/csv-bookings.module';
|
||||||
@ -34,7 +32,6 @@ import { McpController } from './mcp.controller';
|
|||||||
CapabilityRegistry,
|
CapabilityRegistry,
|
||||||
{ provide: TRADE_EMBEDDINGS, useClass: OpenAiEmbeddingAdapter },
|
{ provide: TRADE_EMBEDDINGS, useClass: OpenAiEmbeddingAdapter },
|
||||||
{ provide: TRADE_RETRIEVAL, useClass: WikiRetriever },
|
{ provide: TRADE_RETRIEVAL, useClass: WikiRetriever },
|
||||||
{ provide: WIKI_CONTRIBUTION_REPOSITORY, useClass: TypeOrmWikiContributionRepository },
|
|
||||||
],
|
],
|
||||||
exports: [CapabilityRegistry],
|
exports: [CapabilityRegistry],
|
||||||
})
|
})
|
||||||
|
|||||||
@ -5,9 +5,8 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
import { AuthModule } from '../auth/auth.module';
|
|
||||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
import { JwtModule, JwtSignOptions } from '@nestjs/jwt';
|
import { JwtModule } from '@nestjs/jwt';
|
||||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||||
import { NotificationsController } from '../controllers/notifications.controller';
|
import { NotificationsController } from '../controllers/notifications.controller';
|
||||||
import { NotificationsGateway } from '../gateways/notifications.gateway';
|
import { NotificationsGateway } from '../gateways/notifications.gateway';
|
||||||
@ -18,14 +17,13 @@ import { NOTIFICATION_REPOSITORY } from '@domain/ports/out/notification.reposito
|
|||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
AuthModule,
|
|
||||||
TypeOrmModule.forFeature([NotificationOrmEntity]),
|
TypeOrmModule.forFeature([NotificationOrmEntity]),
|
||||||
JwtModule.registerAsync({
|
JwtModule.registerAsync({
|
||||||
imports: [ConfigModule],
|
imports: [ConfigModule],
|
||||||
useFactory: (configService: ConfigService) => ({
|
useFactory: (configService: ConfigService) => ({
|
||||||
secret: configService.get<string>('JWT_SECRET'),
|
secret: configService.get<string>('JWT_SECRET'),
|
||||||
signOptions: {
|
signOptions: {
|
||||||
expiresIn: configService.get<JwtSignOptions['expiresIn']>('JWT_ACCESS_EXPIRATION', '15m'),
|
expiresIn: configService.get<string>('JWT_ACCESS_EXPIRATION', '15m'),
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
inject: [ConfigService],
|
inject: [ConfigService],
|
||||||
|
|||||||
@ -1,56 +0,0 @@
|
|||||||
import { ConflictException } from '@nestjs/common';
|
|
||||||
import { UserRepository } from '@domain/ports/out/user.repository';
|
|
||||||
import { User, UserRole } from '@domain/entities/user.entity';
|
|
||||||
import { AdminContinuityService } from './admin-continuity.service';
|
|
||||||
|
|
||||||
const user = (id: string, role: UserRole, isActive = true) =>
|
|
||||||
({ id, role, isActive, email: `${id}@xpeditis.com` }) as unknown as User;
|
|
||||||
|
|
||||||
function serviceWith(users: User[]) {
|
|
||||||
const userRepository = {
|
|
||||||
findAllActive: jest.fn(async () => users.filter(u => u.isActive)),
|
|
||||||
findById: jest.fn(async (id: string) => users.find(u => u.id === id) ?? null),
|
|
||||||
} as unknown as UserRepository;
|
|
||||||
return new AdminContinuityService(userRepository);
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('AdminContinuityService', () => {
|
|
||||||
it('refuse de retirer le dernier admin actif, quelle que soit la maniere', async () => {
|
|
||||||
const onlyAdmin = user('a1', UserRole.ADMIN);
|
|
||||||
const service = serviceWith([onlyAdmin, user('u1', UserRole.USER)]);
|
|
||||||
|
|
||||||
await expect(service.assertKeepsAnActiveAdmin(onlyAdmin, null)).rejects.toBeInstanceOf(
|
|
||||||
ConflictException
|
|
||||||
);
|
|
||||||
await expect(
|
|
||||||
service.assertKeepsAnActiveAdmin(onlyAdmin, { role: UserRole.MANAGER, isActive: true })
|
|
||||||
).rejects.toBeInstanceOf(ConflictException);
|
|
||||||
await expect(
|
|
||||||
service.assertKeepsAnActiveAdmin(onlyAdmin, { role: UserRole.ADMIN, isActive: false })
|
|
||||||
).rejects.toBeInstanceOf(ConflictException);
|
|
||||||
await expect(service.assertCanErase('a1')).rejects.toBeInstanceOf(ConflictException);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("autorise l'operation tant qu'un autre admin actif subsiste", async () => {
|
|
||||||
const first = user('a1', UserRole.ADMIN);
|
|
||||||
const service = serviceWith([first, user('a2', UserRole.ADMIN)]);
|
|
||||||
|
|
||||||
await expect(service.assertKeepsAnActiveAdmin(first, null)).resolves.toBeUndefined();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('ne compte pas un admin desactive comme remplacant', async () => {
|
|
||||||
const first = user('a1', UserRole.ADMIN);
|
|
||||||
const service = serviceWith([first, user('a2', UserRole.ADMIN, false)]);
|
|
||||||
|
|
||||||
await expect(service.assertKeepsAnActiveAdmin(first, null)).rejects.toBeInstanceOf(
|
|
||||||
ConflictException
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("ne controle rien pour un compte qui n'est pas admin actif", async () => {
|
|
||||||
const service = serviceWith([user('u1', UserRole.USER)]);
|
|
||||||
|
|
||||||
await expect(service.assertCanErase('u1')).resolves.toBeUndefined();
|
|
||||||
await expect(service.assertCanErase('inconnu')).resolves.toBeUndefined();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@ -1,61 +0,0 @@
|
|||||||
/**
|
|
||||||
* Refuse, avant toute écriture, une opération qui laisserait la plateforme sans
|
|
||||||
* administrateur actif (suppression, rétrogradation, désactivation,
|
|
||||||
* auto-effacement RGPD).
|
|
||||||
*
|
|
||||||
* Ce contrôle donne un message clair ; il ne suffit pas seul : deux requêtes
|
|
||||||
* simultanées peuvent chacune voir l'autre administrateur encore actif. Le
|
|
||||||
* déclencheur PostgreSQL `trg_users_keep_active_admin` ferme ce cas — voir
|
|
||||||
* domain/services/admin-continuity.ts.
|
|
||||||
*/
|
|
||||||
|
|
||||||
import { ConflictException, Inject, Injectable } from '@nestjs/common';
|
|
||||||
import { UserRepository, USER_REPOSITORY } from '@domain/ports/out/user.repository';
|
|
||||||
import { User, UserRole } from '@domain/entities/user.entity';
|
|
||||||
import {
|
|
||||||
AdminState,
|
|
||||||
LAST_ACTIVE_ADMIN_CODE,
|
|
||||||
removesActiveAdmin,
|
|
||||||
} from '@domain/services/admin-continuity';
|
|
||||||
|
|
||||||
export function lastActiveAdminException(): ConflictException {
|
|
||||||
return new ConflictException({
|
|
||||||
statusCode: 409,
|
|
||||||
error: 'Conflict',
|
|
||||||
code: LAST_ACTIVE_ADMIN_CODE,
|
|
||||||
message:
|
|
||||||
'Impossible : la plateforme doit garder au moins un administrateur actif. ' +
|
|
||||||
'Promouvez ou réactivez d’abord un autre administrateur.',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class AdminContinuityService {
|
|
||||||
constructor(@Inject(USER_REPOSITORY) private readonly userRepository: UserRepository) {}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param target compte modifié, dans son état actuel
|
|
||||||
* @param after état visé, ou `null` si le compte est effacé
|
|
||||||
*/
|
|
||||||
async assertKeepsAnActiveAdmin(target: User, after: AdminState | null): Promise<void> {
|
|
||||||
if (!removesActiveAdmin({ role: target.role, isActive: target.isActive }, after)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const otherActiveAdmins = (await this.userRepository.findAllActive()).filter(
|
|
||||||
u => u.role === UserRole.ADMIN && u.id !== target.id
|
|
||||||
);
|
|
||||||
|
|
||||||
if (otherActiveAdmins.length === 0) {
|
|
||||||
throw lastActiveAdminException();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Variante pour un effacement dont on ne connaît que l'identifiant. */
|
|
||||||
async assertCanErase(userId: string): Promise<void> {
|
|
||||||
const target = await this.userRepository.findById(userId);
|
|
||||||
if (target) {
|
|
||||||
await this.assertKeepsAnActiveAdmin(target, null);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -233,7 +233,7 @@ export class AnalyticsService {
|
|||||||
const waitedMs = now - booking.requestedAt.getTime();
|
const waitedMs = now - booking.requestedAt.getTime();
|
||||||
const waitedDays = Math.floor(waitedMs / oneDay);
|
const waitedDays = Math.floor(waitedMs / oneDay);
|
||||||
|
|
||||||
// En attente du transporteur au-dela de 48 h : la demande decroche.
|
// Sans reponse du transporteur au-dela de 48 h, la demande decroche.
|
||||||
if (booking.status === CsvBookingStatus.PENDING && waitedMs > 2 * oneDay) {
|
if (booking.status === CsvBookingStatus.PENDING && waitedMs > 2 * oneDay) {
|
||||||
alerts.push({
|
alerts.push({
|
||||||
id: `pending-${booking.id}`,
|
id: `pending-${booking.id}`,
|
||||||
@ -250,8 +250,26 @@ export class AnalyticsService {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Les devis non regles ne remontent plus ici : ils vivent dans
|
// Reservation bloquee avant paiement : rien ne part tant qu'elle y reste.
|
||||||
// « Historique des devis » et ne bloquent aucun envoi en cours.
|
if (
|
||||||
|
(booking.status === CsvBookingStatus.PENDING_PAYMENT ||
|
||||||
|
booking.status === CsvBookingStatus.PENDING_BANK_TRANSFER) &&
|
||||||
|
waitedMs > oneDay
|
||||||
|
) {
|
||||||
|
alerts.push({
|
||||||
|
id: `payment-${booking.id}`,
|
||||||
|
type: 'payment',
|
||||||
|
severity: 'critical',
|
||||||
|
titleKey: 'awaitingPayment',
|
||||||
|
messageKey: 'awaitingPaymentSince',
|
||||||
|
messageParams: { days: waitedDays },
|
||||||
|
bookingId: booking.id,
|
||||||
|
bookingNumber: booking.bookingNumber,
|
||||||
|
createdAt: booking.requestedAt,
|
||||||
|
isRead: false,
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
// Refus recent : il faut replacer la marchandise.
|
// Refus recent : il faut replacer la marchandise.
|
||||||
if (
|
if (
|
||||||
|
|||||||
@ -17,9 +17,9 @@ import {
|
|||||||
export interface LogAuditInput {
|
export interface LogAuditInput {
|
||||||
action: AuditAction;
|
action: AuditAction;
|
||||||
status: AuditStatus;
|
status: AuditStatus;
|
||||||
userId: string | null;
|
userId: string;
|
||||||
userEmail: string;
|
userEmail: string;
|
||||||
organizationId: string | null;
|
organizationId: string;
|
||||||
resourceType?: string;
|
resourceType?: string;
|
||||||
resourceId?: string;
|
resourceId?: string;
|
||||||
resourceName?: string;
|
resourceName?: string;
|
||||||
@ -89,15 +89,12 @@ export class AuditService {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Log failed action
|
* Log failed action
|
||||||
*
|
|
||||||
* userId / organizationId are null when no user could be identified
|
|
||||||
* (e.g. a failed login) — never a placeholder string, the columns are uuid.
|
|
||||||
*/
|
*/
|
||||||
async logFailure(
|
async logFailure(
|
||||||
action: AuditAction,
|
action: AuditAction,
|
||||||
userId: string | null,
|
userId: string,
|
||||||
userEmail: string,
|
userEmail: string,
|
||||||
organizationId: string | null,
|
organizationId: string,
|
||||||
errorMessage: string,
|
errorMessage: string,
|
||||||
options?: {
|
options?: {
|
||||||
resourceType?: string;
|
resourceType?: string;
|
||||||
|
|||||||
@ -1,133 +0,0 @@
|
|||||||
import { ServiceUnavailableException } from '@nestjs/common';
|
|
||||||
import { CsvBookingService } from './csv-booking.service';
|
|
||||||
import { CreateCsvBookingDto } from '../dto/csv-booking.dto';
|
|
||||||
|
|
||||||
describe('Booking fee failure boundary', () => {
|
|
||||||
const setup = () => {
|
|
||||||
const subscriptionService = { getOrCreateSubscription: jest.fn() };
|
|
||||||
const booking = {
|
|
||||||
id: 'booking',
|
|
||||||
organizationId: 'org',
|
|
||||||
accept: jest.fn(),
|
|
||||||
applyBookingFee: jest.fn(),
|
|
||||||
};
|
|
||||||
const repo = {
|
|
||||||
findByToken: jest.fn().mockResolvedValue(booking),
|
|
||||||
repository: { findOne: jest.fn().mockResolvedValue(null) },
|
|
||||||
create: jest.fn(),
|
|
||||||
update: jest.fn(),
|
|
||||||
};
|
|
||||||
const service = new CsvBookingService(
|
|
||||||
repo as never,
|
|
||||||
{} as never,
|
|
||||||
{} as never,
|
|
||||||
{} as never,
|
|
||||||
{} as never,
|
|
||||||
subscriptionService as never,
|
|
||||||
{} as never
|
|
||||||
);
|
|
||||||
const upload = jest
|
|
||||||
.spyOn(service as unknown as { uploadDocuments: () => Promise<unknown[]> }, 'uploadDocuments')
|
|
||||||
.mockResolvedValue([]);
|
|
||||||
return { service, subscriptionService, repo, booking, upload };
|
|
||||||
};
|
|
||||||
|
|
||||||
it('refuses creation before uploading or saving when the fee is unknown', async () => {
|
|
||||||
const { service, subscriptionService, repo, upload } = setup();
|
|
||||||
subscriptionService.getOrCreateSubscription.mockRejectedValue(
|
|
||||||
new Error('dependency unavailable')
|
|
||||||
);
|
|
||||||
await expect(
|
|
||||||
service.createBooking({} as CreateCsvBookingDto, [{} as Express.Multer.File], 'user', 'org')
|
|
||||||
).rejects.toBeInstanceOf(ServiceUnavailableException);
|
|
||||||
expect(upload).not.toHaveBeenCalled();
|
|
||||||
expect(repo.create).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('does not accept or save a booking when the fee lookup fails', async () => {
|
|
||||||
const { service, subscriptionService, repo, booking } = setup();
|
|
||||||
subscriptionService.getOrCreateSubscription.mockRejectedValue(
|
|
||||||
new Error('dependency unavailable')
|
|
||||||
);
|
|
||||||
await expect(service.acceptBooking('test-token')).rejects.toBeInstanceOf(
|
|
||||||
ServiceUnavailableException
|
|
||||||
);
|
|
||||||
expect(booking.accept).not.toHaveBeenCalled();
|
|
||||||
expect(repo.update).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it.each([
|
|
||||||
[15, 'QUOTE'],
|
|
||||||
[-1, 'PENDING'],
|
|
||||||
])('preserves creation for a known fee %s', async (fee, expectedStatus) => {
|
|
||||||
const { service, subscriptionService, repo, upload } = setup();
|
|
||||||
subscriptionService.getOrCreateSubscription.mockResolvedValue({ bookingFeeEur: fee });
|
|
||||||
upload.mockResolvedValue([
|
|
||||||
{
|
|
||||||
id: 'doc',
|
|
||||||
type: 'OTHER',
|
|
||||||
fileName: 'test.pdf',
|
|
||||||
filePath: 'test',
|
|
||||||
mimeType: 'application/pdf',
|
|
||||||
size: 1,
|
|
||||||
uploadedAt: new Date(),
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
repo.create.mockImplementation(async value => value);
|
|
||||||
const mail = jest
|
|
||||||
.spyOn(
|
|
||||||
service as unknown as { sendCarrierBookingRequest: () => Promise<void> },
|
|
||||||
'sendCarrierBookingRequest'
|
|
||||||
)
|
|
||||||
.mockResolvedValue(undefined);
|
|
||||||
jest
|
|
||||||
.spyOn(
|
|
||||||
service as unknown as { notifyBookingRequestSent: () => Promise<void> },
|
|
||||||
'notifyBookingRequestSent'
|
|
||||||
)
|
|
||||||
.mockResolvedValue(undefined);
|
|
||||||
const result = await service.createBooking(
|
|
||||||
{
|
|
||||||
carrierName: 'Carrier',
|
|
||||||
carrierEmail: 'carrier@example.test',
|
|
||||||
origin: 'FRLEH',
|
|
||||||
destination: 'CNSHA',
|
|
||||||
volumeCBM: 1,
|
|
||||||
weightKG: 100,
|
|
||||||
palletCount: 1,
|
|
||||||
priceUSD: 100,
|
|
||||||
priceEUR: 90,
|
|
||||||
primaryCurrency: 'EUR',
|
|
||||||
transitDays: 10,
|
|
||||||
containerType: 'LCL',
|
|
||||||
} as CreateCsvBookingDto,
|
|
||||||
[{} as Express.Multer.File],
|
|
||||||
'user',
|
|
||||||
'org'
|
|
||||||
);
|
|
||||||
expect(result.status).toBe(expectedStatus);
|
|
||||||
expect(result.commissionAmountEur).toBe(fee === -1 ? 0 : fee);
|
|
||||||
expect(repo.create).toHaveBeenCalledTimes(1);
|
|
||||||
expect(mail).toHaveBeenCalledTimes(fee === -1 ? 1 : 0);
|
|
||||||
});
|
|
||||||
|
|
||||||
it.each([
|
|
||||||
[15, 15],
|
|
||||||
[10, 10],
|
|
||||||
[5, 5],
|
|
||||||
[-1, 0],
|
|
||||||
[0, 0],
|
|
||||||
])('preserves fee %s as %s', async (fee, expected) => {
|
|
||||||
const { service, subscriptionService } = setup();
|
|
||||||
subscriptionService.getOrCreateSubscription.mockResolvedValue({ bookingFeeEur: fee });
|
|
||||||
await expect(service['resolveBookingFeeEur']('org')).resolves.toBe(expected);
|
|
||||||
});
|
|
||||||
|
|
||||||
it.each([undefined, NaN, Infinity, -2])('rejects an invalid fee %s', async fee => {
|
|
||||||
const { service, subscriptionService } = setup();
|
|
||||||
subscriptionService.getOrCreateSubscription.mockResolvedValue({ bookingFeeEur: fee });
|
|
||||||
await expect(service['resolveBookingFeeEur']('org')).rejects.toBeInstanceOf(
|
|
||||||
ServiceUnavailableException
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@ -1,24 +0,0 @@
|
|||||||
import { CsvBookingService } from './csv-booking.service';
|
|
||||||
import { CsvBooking } from '@domain/entities/csv-booking.entity';
|
|
||||||
|
|
||||||
describe('customer booking response', () => {
|
|
||||||
it('omits carrier capabilities while preserving booking information', () => {
|
|
||||||
const booking = {
|
|
||||||
id: 'booking-1',
|
|
||||||
primaryCurrency: 'EUR',
|
|
||||||
confirmationToken: 'carrier-secret',
|
|
||||||
origin: { getValue: () => 'FRLEH' },
|
|
||||||
destination: { getValue: () => 'CNSHA' },
|
|
||||||
documents: [],
|
|
||||||
getRouteDescription: () => 'FRLEH → CNSHA',
|
|
||||||
isExpired: () => false,
|
|
||||||
getPriceInCurrency: () => 100,
|
|
||||||
} as unknown as CsvBooking;
|
|
||||||
const service = Object.create(CsvBookingService.prototype) as CsvBookingService;
|
|
||||||
const response = service['toResponseDto'](booking);
|
|
||||||
expect(response.id).toBe('booking-1');
|
|
||||||
expect(response.price).toBe(100);
|
|
||||||
expect(response).not.toHaveProperty('confirmationToken');
|
|
||||||
expect(JSON.stringify(response)).not.toContain('carrier-secret');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@ -1,104 +0,0 @@
|
|||||||
import { Logger } from '@nestjs/common';
|
|
||||||
import { CsvBookingService } from './csv-booking.service';
|
|
||||||
import { CsvBookingStatus } from '@domain/entities/csv-booking.entity';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Validation d'un virement par un administrateur : le booking passe en PENDING
|
|
||||||
* et la demande part chez le transporteur. Un echec de cet email etait avale
|
|
||||||
* sans que l'administrateur le sache.
|
|
||||||
*/
|
|
||||||
|
|
||||||
function pendingTransferBooking() {
|
|
||||||
const booking = {
|
|
||||||
id: 'b-1',
|
|
||||||
bookingNumber: 'XPD-2026-AAAAAA',
|
|
||||||
userId: 'u-1',
|
|
||||||
organizationId: 'org-1',
|
|
||||||
carrierName: 'SSC Consolidation',
|
|
||||||
carrierEmail: 'booking@ssc.test',
|
|
||||||
origin: { getValue: () => 'FRLEH' },
|
|
||||||
destination: { getValue: () => 'EGEDK' },
|
|
||||||
volumeCBM: 2.4,
|
|
||||||
weightKG: 850,
|
|
||||||
palletCount: 2,
|
|
||||||
priceUSD: 200,
|
|
||||||
priceEUR: 180,
|
|
||||||
primaryCurrency: 'EUR',
|
|
||||||
transitDays: 11,
|
|
||||||
containerType: 'LCL',
|
|
||||||
status: CsvBookingStatus.PENDING_BANK_TRANSFER as CsvBookingStatus,
|
|
||||||
documents: [],
|
|
||||||
confirmationToken: 'token',
|
|
||||||
requestedAt: new Date('2026-09-01T10:00:00Z'),
|
|
||||||
notes: undefined,
|
|
||||||
getRouteDescription: () => 'FRLEH → EGEDK',
|
|
||||||
isExpired: () => false,
|
|
||||||
getPriceInCurrency: () => 180,
|
|
||||||
options: {},
|
|
||||||
markBankTransferValidated() {
|
|
||||||
booking.status = CsvBookingStatus.PENDING;
|
|
||||||
},
|
|
||||||
};
|
|
||||||
return booking;
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildService(options: { emailFails: boolean }) {
|
|
||||||
const booking = pendingTransferBooking();
|
|
||||||
const csvBookingRepository = {
|
|
||||||
findById: jest.fn(async () => booking),
|
|
||||||
update: jest.fn(async (b: unknown) => b),
|
|
||||||
repository: {
|
|
||||||
findOne: jest.fn(async () => ({ bookingNumber: booking.bookingNumber, passwordHash: null })),
|
|
||||||
save: jest.fn(async (b: unknown) => b),
|
|
||||||
},
|
|
||||||
};
|
|
||||||
const emailAdapter = {
|
|
||||||
sendCsvBookingRequest: jest.fn(async () => {
|
|
||||||
if (options.emailFails) throw new Error('550 sender not valid');
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
const notificationRepository = { save: jest.fn(async () => undefined) };
|
|
||||||
const unused = {} as never;
|
|
||||||
|
|
||||||
const service = new CsvBookingService(
|
|
||||||
csvBookingRepository as never,
|
|
||||||
notificationRepository as never,
|
|
||||||
emailAdapter as never,
|
|
||||||
unused,
|
|
||||||
unused,
|
|
||||||
unused,
|
|
||||||
unused
|
|
||||||
);
|
|
||||||
return { service, booking, emailAdapter };
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('CsvBookingService.validateBankTransfer', () => {
|
|
||||||
beforeEach(() => {
|
|
||||||
jest.spyOn(Logger.prototype, 'log').mockImplementation(() => undefined);
|
|
||||||
jest.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined);
|
|
||||||
});
|
|
||||||
|
|
||||||
afterEach(() => jest.restoreAllMocks());
|
|
||||||
|
|
||||||
it('active le booking et envoie la demande au transporteur', async () => {
|
|
||||||
const { service, booking, emailAdapter } = buildService({ emailFails: false });
|
|
||||||
|
|
||||||
const result = await service.validateBankTransfer('b-1');
|
|
||||||
|
|
||||||
expect(booking.status).toBe(CsvBookingStatus.PENDING);
|
|
||||||
expect(emailAdapter.sendCsvBookingRequest).toHaveBeenCalledWith(
|
|
||||||
'booking@ssc.test',
|
|
||||||
expect.objectContaining({ bookingNumber: 'XPD-2026-AAAAAA', confirmationToken: 'token' })
|
|
||||||
);
|
|
||||||
expect(result.carrierEmailSent).toBe(true);
|
|
||||||
}, 20000);
|
|
||||||
|
|
||||||
it("signale l'echec de l'email au lieu de l'avaler, sans annuler la validation", async () => {
|
|
||||||
const { service, booking } = buildService({ emailFails: true });
|
|
||||||
|
|
||||||
const result = await service.validateBankTransfer('b-1');
|
|
||||||
|
|
||||||
expect(booking.status).toBe(CsvBookingStatus.PENDING);
|
|
||||||
expect(result.carrierEmailSent).toBe(false);
|
|
||||||
}, 20000);
|
|
||||||
});
|
|
||||||
@ -1,118 +0,0 @@
|
|||||||
import { NotFoundException } from '@nestjs/common';
|
|
||||||
import { CsvBookingService } from './csv-booking.service';
|
|
||||||
import { anonymisedEmail } from '@domain/services/data-retention';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Reservations et devis partages au sein d'une entreprise : chaque membre voit
|
|
||||||
* les lignes de ses collegues, avec le nom de leur auteur.
|
|
||||||
*/
|
|
||||||
|
|
||||||
const ORG = 'org-1';
|
|
||||||
|
|
||||||
const booking = (id: string, userId: string, organizationId = ORG) => ({
|
|
||||||
id,
|
|
||||||
bookingNumber: `XPD-2026-${id.toUpperCase()}`,
|
|
||||||
userId,
|
|
||||||
organizationId,
|
|
||||||
carrierName: 'SSC Consolidation',
|
|
||||||
carrierEmail: 'booking@ssc.test',
|
|
||||||
origin: { getValue: () => 'FRLEH' },
|
|
||||||
destination: { getValue: () => 'EGEDK' },
|
|
||||||
volumeCBM: 2.4,
|
|
||||||
weightKG: 850,
|
|
||||||
palletCount: 2,
|
|
||||||
priceUSD: 200,
|
|
||||||
priceEUR: 180,
|
|
||||||
primaryCurrency: 'EUR',
|
|
||||||
transitDays: 11,
|
|
||||||
containerType: 'LCL',
|
|
||||||
status: 'QUOTE',
|
|
||||||
documents: [],
|
|
||||||
confirmationToken: 'token',
|
|
||||||
requestedAt: new Date('2026-09-01T10:00:00Z'),
|
|
||||||
getRouteDescription: () => 'FRLEH → EGEDK',
|
|
||||||
isExpired: () => false,
|
|
||||||
getPriceInCurrency: () => 180,
|
|
||||||
options: {},
|
|
||||||
});
|
|
||||||
|
|
||||||
const member = (id: string, firstName: string, lastName: string, email = `${id}@acme.test`) => ({
|
|
||||||
id,
|
|
||||||
email,
|
|
||||||
firstName,
|
|
||||||
lastName,
|
|
||||||
});
|
|
||||||
|
|
||||||
function buildService(
|
|
||||||
bookings: ReturnType<typeof booking>[],
|
|
||||||
members: ReturnType<typeof member>[]
|
|
||||||
) {
|
|
||||||
const csvBookingRepository = {
|
|
||||||
findByOrganizationId: jest.fn(async (orgId: string) =>
|
|
||||||
bookings.filter(b => b.organizationId === orgId)
|
|
||||||
),
|
|
||||||
findById: jest.fn(async (id: string) => bookings.find(b => b.id === id) ?? null),
|
|
||||||
repository: { findOne: jest.fn(async () => null) },
|
|
||||||
};
|
|
||||||
const userRepository = {
|
|
||||||
findByOrganization: jest.fn(async () => members),
|
|
||||||
findById: jest.fn(async (id: string) => members.find(m => m.id === id) ?? null),
|
|
||||||
};
|
|
||||||
const unused = {} as never;
|
|
||||||
|
|
||||||
const service = new CsvBookingService(
|
|
||||||
csvBookingRepository as never,
|
|
||||||
unused,
|
|
||||||
unused,
|
|
||||||
unused,
|
|
||||||
unused,
|
|
||||||
unused,
|
|
||||||
userRepository as never
|
|
||||||
);
|
|
||||||
return { service, userRepository };
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('CsvBookingService — reservations de l’entreprise', () => {
|
|
||||||
it('liste les reservations de tous les membres, avec le nom de leur auteur', async () => {
|
|
||||||
const { service, userRepository } = buildService(
|
|
||||||
[booking('a', 'marie'), booking('b', 'paul'), booking('c', 'erased'), booking('d', 'gone')],
|
|
||||||
[
|
|
||||||
member('marie', 'Marie', 'Dupont'),
|
|
||||||
member('paul', '', '', 'paul@acme.test'),
|
|
||||||
member('erased', 'anonymised', 'anonymised', anonymisedEmail('erased')),
|
|
||||||
]
|
|
||||||
);
|
|
||||||
|
|
||||||
const result = await service.getOrganizationBookings(ORG, 1, 100);
|
|
||||||
|
|
||||||
expect(result.total).toBe(4);
|
|
||||||
expect(result.bookings.map(b => [b.userId, b.createdByName])).toEqual([
|
|
||||||
['marie', 'Marie Dupont'],
|
|
||||||
// Sans nom renseigne, l'adresse sert de libelle.
|
|
||||||
['paul', 'paul@acme.test'],
|
|
||||||
// Compte efface : aucune identite ne ressort.
|
|
||||||
['erased', null],
|
|
||||||
['gone', null],
|
|
||||||
]);
|
|
||||||
// Une seule requete pour les membres, pas une par reservation.
|
|
||||||
expect(userRepository.findByOrganization).toHaveBeenCalledTimes(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('laisse un collegue de la meme entreprise consulter une reservation', async () => {
|
|
||||||
const { service } = buildService([booking('a', 'marie')], [member('marie', 'Marie', 'Dupont')]);
|
|
||||||
|
|
||||||
const dto = await service.getBookingById('a', 'paul', undefined, ORG);
|
|
||||||
|
|
||||||
expect(dto.id).toBe('a');
|
|
||||||
expect(dto.createdByName).toBe('Marie Dupont');
|
|
||||||
});
|
|
||||||
|
|
||||||
it("refuse la consultation a un utilisateur d'une autre entreprise", async () => {
|
|
||||||
const { service } = buildService([booking('a', 'marie')], [member('marie', 'Marie', 'Dupont')]);
|
|
||||||
|
|
||||||
await expect(service.getBookingById('a', 'intrus', undefined, 'org-2')).rejects.toBeInstanceOf(
|
|
||||||
NotFoundException
|
|
||||||
);
|
|
||||||
await expect(service.getBookingById('a', 'intrus')).rejects.toBeInstanceOf(NotFoundException);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@ -5,7 +5,6 @@ import {
|
|||||||
BadRequestException,
|
BadRequestException,
|
||||||
Inject,
|
Inject,
|
||||||
UnauthorizedException,
|
UnauthorizedException,
|
||||||
ServiceUnavailableException,
|
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { v4 as uuidv4 } from 'uuid';
|
import { v4 as uuidv4 } from 'uuid';
|
||||||
import * as argon2 from 'argon2';
|
import * as argon2 from 'argon2';
|
||||||
@ -19,7 +18,6 @@ import {
|
|||||||
} from '@domain/ports/out/notification.repository';
|
} from '@domain/ports/out/notification.repository';
|
||||||
import { EmailPort, EMAIL_PORT } from '@domain/ports/out/email.port';
|
import { EmailPort, EMAIL_PORT } from '@domain/ports/out/email.port';
|
||||||
import { UserRepository, USER_REPOSITORY } from '@domain/ports/out/user.repository';
|
import { UserRepository, USER_REPOSITORY } from '@domain/ports/out/user.repository';
|
||||||
import { isAnonymisedEmail } from '@domain/services/data-retention';
|
|
||||||
import { StoragePort, STORAGE_PORT } from '@domain/ports/out/storage.port';
|
import { StoragePort, STORAGE_PORT } from '@domain/ports/out/storage.port';
|
||||||
import { StripePort, STRIPE_PORT } from '@domain/ports/out/stripe.port';
|
import { StripePort, STRIPE_PORT } from '@domain/ports/out/stripe.port';
|
||||||
import {
|
import {
|
||||||
@ -152,9 +150,6 @@ export class CsvBookingService {
|
|||||||
throw new BadRequestException('At least one document is required');
|
throw new BadRequestException('At least one document is required');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Resolve pricing before uploads or any persistent side effect.
|
|
||||||
const bookingFeeEur = await this.resolveBookingFeeEur(organizationId);
|
|
||||||
|
|
||||||
// Generate unique confirmation token and booking number
|
// Generate unique confirmation token and booking number
|
||||||
const confirmationToken = uuidv4();
|
const confirmationToken = uuidv4();
|
||||||
const bookingId = uuidv4();
|
const bookingId = uuidv4();
|
||||||
@ -170,8 +165,11 @@ export class CsvBookingService {
|
|||||||
// Flat per-booking service fee (forfait par booking) based on the org's plan.
|
// Flat per-booking service fee (forfait par booking) based on the org's plan.
|
||||||
// A fee <= 0 (e.g. Platinium "sur mesure") means no automatic charge: the
|
// A fee <= 0 (e.g. Platinium "sur mesure") means no automatic charge: the
|
||||||
// booking skips the payment gate and the carrier is notified immediately.
|
// booking skips the payment gate and the carrier is notified immediately.
|
||||||
|
const bookingFeeEur = await this.resolveBookingFeeEur(organizationId);
|
||||||
const requiresPayment = bookingFeeEur > 0;
|
const requiresPayment = bookingFeeEur > 0;
|
||||||
const initialStatus = requiresPayment ? CsvBookingStatus.QUOTE : CsvBookingStatus.PENDING;
|
const initialStatus = requiresPayment
|
||||||
|
? CsvBookingStatus.PENDING_PAYMENT
|
||||||
|
: CsvBookingStatus.PENDING;
|
||||||
|
|
||||||
// Create domain entity (no email sent yet when a payment is required)
|
// Create domain entity (no email sent yet when a payment is required)
|
||||||
let parsedOptions: Record<string, boolean> = {};
|
let parsedOptions: Record<string, boolean> = {};
|
||||||
@ -249,20 +247,17 @@ export class CsvBookingService {
|
|||||||
/**
|
/**
|
||||||
* Resolve the flat per-booking fee (forfait par booking) for an organization
|
* Resolve the flat per-booking fee (forfait par booking) for an organization
|
||||||
* from its subscription plan. Returns the plan's bookingFeeEur, or 0 when the
|
* from its subscription plan. Returns the plan's bookingFeeEur, or 0 when the
|
||||||
* plan has a custom fee (-1, e.g. Platinium "sur mesure").
|
* plan has a custom fee (-1, e.g. Platinium "sur mesure") or on error — such
|
||||||
* An unknown fee must never be interpreted as a free booking.
|
* bookings are not auto-charged.
|
||||||
*/
|
*/
|
||||||
private async resolveBookingFeeEur(organizationId: string): Promise<number> {
|
private async resolveBookingFeeEur(organizationId: string): Promise<number> {
|
||||||
try {
|
try {
|
||||||
const subscription = await this.subscriptionService.getOrCreateSubscription(organizationId);
|
const subscription = await this.subscriptionService.getOrCreateSubscription(organizationId);
|
||||||
const fee = subscription.bookingFeeEur;
|
const fee = subscription.plan.bookingFeeEur;
|
||||||
if (!Number.isFinite(fee) || (fee < 0 && fee !== -1)) {
|
|
||||||
throw new Error('Invalid booking fee');
|
|
||||||
}
|
|
||||||
return fee > 0 ? fee : 0;
|
return fee > 0 ? fee : 0;
|
||||||
} catch {
|
} catch (error: any) {
|
||||||
this.logger.error('Failed to resolve booking fee');
|
this.logger.error(`Failed to resolve booking fee: ${error?.message}`);
|
||||||
throw new ServiceUnavailableException('Booking fee unavailable. Please retry later.');
|
return 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -285,9 +280,9 @@ export class CsvBookingService {
|
|||||||
throw new NotFoundException(`Booking with ID ${bookingId} not found`);
|
throw new NotFoundException(`Booking with ID ${bookingId} not found`);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (booking.status !== CsvBookingStatus.QUOTE) {
|
if (booking.status !== CsvBookingStatus.PENDING_PAYMENT) {
|
||||||
throw new BadRequestException(
|
throw new BadRequestException(
|
||||||
`Booking is not a quote awaiting payment. Current status: ${booking.status}`
|
`Booking is not awaiting payment. Current status: ${booking.status}`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -339,13 +334,13 @@ export class CsvBookingService {
|
|||||||
throw new NotFoundException(`Booking with ID ${bookingId} not found`);
|
throw new NotFoundException(`Booking with ID ${bookingId} not found`);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (booking.status !== CsvBookingStatus.QUOTE) {
|
if (booking.status !== CsvBookingStatus.PENDING_PAYMENT) {
|
||||||
// Already confirmed - return current state
|
// Already confirmed - return current state
|
||||||
if (booking.status === CsvBookingStatus.PENDING) {
|
if (booking.status === CsvBookingStatus.PENDING) {
|
||||||
return this.toResponseDto(booking);
|
return this.toResponseDto(booking);
|
||||||
}
|
}
|
||||||
throw new BadRequestException(
|
throw new BadRequestException(
|
||||||
`Booking is not a quote awaiting payment. Current status: ${booking.status}`
|
`Booking is not awaiting payment. Current status: ${booking.status}`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -415,7 +410,7 @@ export class CsvBookingService {
|
|||||||
});
|
});
|
||||||
this.logger.log(`Email sent to carrier: ${booking.carrierEmail}`);
|
this.logger.log(`Email sent to carrier: ${booking.carrierEmail}`);
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
this.logger.error('Failed to send email to carrier');
|
this.logger.error(`Failed to send email to carrier: ${error?.message}`, error?.stack);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -442,7 +437,7 @@ export class CsvBookingService {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Declare bank transfer — user confirms they have sent the wire transfer
|
* Declare bank transfer — user confirms they have sent the wire transfer
|
||||||
* Transitions booking from QUOTE → PENDING_BANK_TRANSFER
|
* Transitions booking from PENDING_PAYMENT → PENDING_BANK_TRANSFER
|
||||||
* Sends an email notification to all ADMIN users
|
* Sends an email notification to all ADMIN users
|
||||||
*/
|
*/
|
||||||
async declareBankTransfer(bookingId: string, userId: string): Promise<CsvBookingResponseDto> {
|
async declareBankTransfer(bookingId: string, userId: string): Promise<CsvBookingResponseDto> {
|
||||||
@ -456,9 +451,9 @@ export class CsvBookingService {
|
|||||||
throw new NotFoundException(`Booking with ID ${bookingId} not found`);
|
throw new NotFoundException(`Booking with ID ${bookingId} not found`);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (booking.status !== CsvBookingStatus.QUOTE) {
|
if (booking.status !== CsvBookingStatus.PENDING_PAYMENT) {
|
||||||
throw new BadRequestException(
|
throw new BadRequestException(
|
||||||
`Booking is not a quote awaiting payment. Current status: ${booking.status}`
|
`Booking is not awaiting payment. Current status: ${booking.status}`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -486,18 +481,43 @@ export class CsvBookingService {
|
|||||||
)
|
)
|
||||||
: 'N/A';
|
: 'N/A';
|
||||||
|
|
||||||
// Gabarit commun ; le lien pointe vers /admin/bookings (l'ancien
|
await this.emailAdapter.send({
|
||||||
// /dashboard/admin/bookings n'existe pas).
|
to: adminEmails,
|
||||||
await this.emailAdapter.sendBankTransferToValidate(adminEmails, {
|
subject: `[XPEDITIS] Virement à valider — ${bookingNumber}`,
|
||||||
bookingNumber,
|
html: `
|
||||||
carrierName: booking.carrierName,
|
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
|
||||||
routeDescription: booking.getRouteDescription(),
|
<h2 style="color: #10183A;">Nouveau virement à valider</h2>
|
||||||
commissionAmount,
|
<p>Un client a déclaré avoir effectué un virement bancaire pour le booking suivant :</p>
|
||||||
|
<table style="width: 100%; border-collapse: collapse; margin: 16px 0;">
|
||||||
|
<tr style="background: #f5f5f5;">
|
||||||
|
<td style="padding: 8px 12px; font-weight: bold;">Numéro de booking</td>
|
||||||
|
<td style="padding: 8px 12px;">${bookingNumber}</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td style="padding: 8px 12px; font-weight: bold;">Transporteur</td>
|
||||||
|
<td style="padding: 8px 12px;">${booking.carrierName}</td>
|
||||||
|
</tr>
|
||||||
|
<tr style="background: #f5f5f5;">
|
||||||
|
<td style="padding: 8px 12px; font-weight: bold;">Trajet</td>
|
||||||
|
<td style="padding: 8px 12px;">${booking.getRouteDescription()}</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td style="padding: 8px 12px; font-weight: bold;">Montant commission</td>
|
||||||
|
<td style="padding: 8px 12px; color: #10183A; font-weight: bold;">${commissionAmount}</td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
<p>Rendez-vous dans la <strong>console d'administration</strong> pour valider ce virement et activer le booking.</p>
|
||||||
|
<a href="${process.env.APP_URL || 'http://localhost:3000'}/dashboard/admin/bookings"
|
||||||
|
style="display: inline-block; background: #10183A; color: white; padding: 12px 24px; border-radius: 6px; text-decoration: none; margin-top: 8px;">
|
||||||
|
Voir les bookings en attente
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
`,
|
||||||
});
|
});
|
||||||
this.logger.log(`Admin notification email sent to: ${adminEmails.join(', ')}`);
|
this.logger.log(`Admin notification email sent to: ${adminEmails.join(', ')}`);
|
||||||
}
|
}
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
this.logger.error('Failed to send admin notification email');
|
this.logger.error(`Failed to send admin notification email: ${error?.message}`, error?.stack);
|
||||||
}
|
}
|
||||||
|
|
||||||
// In-app notification for the user
|
// In-app notification for the user
|
||||||
@ -590,13 +610,10 @@ export class CsvBookingService {
|
|||||||
where: { id: bookingId },
|
where: { id: bookingId },
|
||||||
});
|
});
|
||||||
const bookingNumber = ormBooking?.bookingNumber;
|
const bookingNumber = ormBooking?.bookingNumber;
|
||||||
|
const documentPassword = await this.syncDocumentPassword(booking.id);
|
||||||
|
|
||||||
// Send email to carrier. The transfer stays validated even if the email
|
// Send email to carrier
|
||||||
// fails, but the admin is told (carrierEmailSent) so they can resend it —
|
|
||||||
// the failure used to be silent.
|
|
||||||
let carrierEmailSent = false;
|
|
||||||
try {
|
try {
|
||||||
const documentPassword = await this.syncDocumentPassword(booking.id);
|
|
||||||
await this.emailAdapter.sendCsvBookingRequest(booking.carrierEmail, {
|
await this.emailAdapter.sendCsvBookingRequest(booking.carrierEmail, {
|
||||||
bookingId: booking.id,
|
bookingId: booking.id,
|
||||||
bookingNumber: bookingNumber || '',
|
bookingNumber: bookingNumber || '',
|
||||||
@ -618,12 +635,11 @@ export class CsvBookingService {
|
|||||||
confirmationToken: booking.confirmationToken,
|
confirmationToken: booking.confirmationToken,
|
||||||
notes: booking.notes,
|
notes: booking.notes,
|
||||||
});
|
});
|
||||||
carrierEmailSent = true;
|
|
||||||
this.logger.log(
|
this.logger.log(
|
||||||
`Email sent to carrier after bank transfer validation: ${booking.carrierEmail}`
|
`Email sent to carrier after bank transfer validation: ${booking.carrierEmail}`
|
||||||
);
|
);
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
this.logger.error('Failed to send email to carrier');
|
this.logger.error(`Failed to send email to carrier: ${error?.message}`, error?.stack);
|
||||||
}
|
}
|
||||||
|
|
||||||
// In-app notification for the user
|
// In-app notification for the user
|
||||||
@ -643,19 +659,17 @@ export class CsvBookingService {
|
|||||||
this.logger.error(`Failed to create user notification: ${error?.message}`, error?.stack);
|
this.logger.error(`Failed to create user notification: ${error?.message}`, error?.stack);
|
||||||
}
|
}
|
||||||
|
|
||||||
return { ...this.toResponseDto(updatedBooking), carrierEmailSent };
|
return this.toResponseDto(updatedBooking);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get booking by ID
|
* Get booking by ID
|
||||||
* Readable by: booking owner, any member of the booking's organization, or
|
* Accessible by: booking owner OR assigned carrier
|
||||||
* the assigned carrier. Changes (pay, edit, cancel, documents) stay owner-only.
|
|
||||||
*/
|
*/
|
||||||
async getBookingById(
|
async getBookingById(
|
||||||
id: string,
|
id: string,
|
||||||
userId: string,
|
userId: string,
|
||||||
carrierId?: string,
|
carrierId?: string
|
||||||
organizationId?: string
|
|
||||||
): Promise<CsvBookingResponseDto> {
|
): Promise<CsvBookingResponseDto> {
|
||||||
const booking = await this.csvBookingRepository.findById(id);
|
const booking = await this.csvBookingRepository.findById(id);
|
||||||
|
|
||||||
@ -668,33 +682,15 @@ export class CsvBookingService {
|
|||||||
where: { id },
|
where: { id },
|
||||||
});
|
});
|
||||||
|
|
||||||
// Verify user owns this booking, belongs to its organization, OR is the assigned carrier
|
// Verify user owns this booking OR is the assigned carrier
|
||||||
const isOwner = booking.userId === userId;
|
const isOwner = booking.userId === userId;
|
||||||
const isSameOrganization = !!organizationId && booking.organizationId === organizationId;
|
|
||||||
const isAssignedCarrier = carrierId && ormBooking?.carrierId === carrierId;
|
const isAssignedCarrier = carrierId && ormBooking?.carrierId === carrierId;
|
||||||
|
|
||||||
if (!isOwner && !isSameOrganization && !isAssignedCarrier) {
|
if (!isOwner && !isAssignedCarrier) {
|
||||||
throw new NotFoundException(`Booking with ID ${id} not found`);
|
throw new NotFoundException(`Booking with ID ${id} not found`);
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return this.toResponseDto(booking);
|
||||||
...this.toResponseDto(booking),
|
|
||||||
createdByName: this.creatorName(await this.userRepository.findById(booking.userId)),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Display name of a booking's creator, or null when the account no longer
|
|
||||||
* exists or has been erased (its identity is anonymised).
|
|
||||||
*/
|
|
||||||
private creatorName(
|
|
||||||
user: { email: string; firstName?: string; lastName?: string } | null | undefined
|
|
||||||
): string | null {
|
|
||||||
if (!user || isAnonymisedEmail(user.email)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
const fullName = `${user.firstName ?? ''} ${user.lastName ?? ''}`.trim();
|
|
||||||
return fullName || user.email;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -704,7 +700,7 @@ export class CsvBookingService {
|
|||||||
const booking = await this.csvBookingRepository.findByToken(token);
|
const booking = await this.csvBookingRepository.findByToken(token);
|
||||||
|
|
||||||
if (!booking) {
|
if (!booking) {
|
||||||
throw new NotFoundException('Booking not found');
|
throw new NotFoundException(`Booking with token ${token} not found`);
|
||||||
}
|
}
|
||||||
|
|
||||||
return this.toResponseDto(booking);
|
return this.toResponseDto(booking);
|
||||||
@ -718,7 +714,7 @@ export class CsvBookingService {
|
|||||||
token: string,
|
token: string,
|
||||||
password?: string
|
password?: string
|
||||||
): Promise<CarrierDocumentsResponseDto> {
|
): Promise<CarrierDocumentsResponseDto> {
|
||||||
this.logger.log('Getting documents for carrier');
|
this.logger.log(`Getting documents for carrier with token: ${token}`);
|
||||||
|
|
||||||
// Get ORM entity to access passwordHash
|
// Get ORM entity to access passwordHash
|
||||||
const ormBooking = await this.csvBookingRepository['repository'].findOne({
|
const ormBooking = await this.csvBookingRepository['repository'].findOne({
|
||||||
@ -888,7 +884,7 @@ export class CsvBookingService {
|
|||||||
* Accept a booking request
|
* Accept a booking request
|
||||||
*/
|
*/
|
||||||
async acceptBooking(token: string): Promise<CsvBookingResponseDto> {
|
async acceptBooking(token: string): Promise<CsvBookingResponseDto> {
|
||||||
this.logger.log('Accepting booking');
|
this.logger.log(`Accepting booking with token: ${token}`);
|
||||||
|
|
||||||
const booking = await this.csvBookingRepository.findByToken(token);
|
const booking = await this.csvBookingRepository.findByToken(token);
|
||||||
|
|
||||||
@ -901,9 +897,11 @@ export class CsvBookingService {
|
|||||||
where: { confirmationToken: token },
|
where: { confirmationToken: token },
|
||||||
});
|
});
|
||||||
|
|
||||||
// Resolve pricing before mutating the booking.
|
// Accept the booking (domain logic validates status)
|
||||||
const bookingFeeEur = await this.resolveBookingFeeEur(booking.organizationId);
|
|
||||||
booking.accept();
|
booking.accept();
|
||||||
|
|
||||||
|
// Apply the flat per-booking service fee (forfait par booking) from the org's plan
|
||||||
|
const bookingFeeEur = await this.resolveBookingFeeEur(booking.organizationId);
|
||||||
booking.applyBookingFee(bookingFeeEur);
|
booking.applyBookingFee(bookingFeeEur);
|
||||||
this.logger.log(
|
this.logger.log(
|
||||||
`Booking fee applied: ${bookingFeeEur > 0 ? `${bookingFeeEur}€ (flat)` : 'none (custom)'} on booking ${booking.id}`
|
`Booking fee applied: ${bookingFeeEur > 0 ? `${bookingFeeEur}€ (flat)` : 'none (custom)'} on booking ${booking.id}`
|
||||||
@ -933,7 +931,7 @@ export class CsvBookingService {
|
|||||||
});
|
});
|
||||||
this.logger.log(`Document access email sent to carrier: ${booking.carrierEmail}`);
|
this.logger.log(`Document access email sent to carrier: ${booking.carrierEmail}`);
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
this.logger.error('Failed to send document access email');
|
this.logger.error(`Failed to send document access email: ${error?.message}`, error?.stack);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create notification for user
|
// Create notification for user
|
||||||
@ -960,7 +958,7 @@ export class CsvBookingService {
|
|||||||
* Reject a booking request
|
* Reject a booking request
|
||||||
*/
|
*/
|
||||||
async rejectBooking(token: string, reason?: string): Promise<CsvBookingResponseDto> {
|
async rejectBooking(token: string, reason?: string): Promise<CsvBookingResponseDto> {
|
||||||
this.logger.log('Rejecting booking');
|
this.logger.log(`Rejecting booking with token: ${token}`);
|
||||||
|
|
||||||
const booking = await this.csvBookingRepository.findByToken(token);
|
const booking = await this.csvBookingRepository.findByToken(token);
|
||||||
|
|
||||||
@ -1067,7 +1065,7 @@ export class CsvBookingService {
|
|||||||
/**
|
/**
|
||||||
* Update the cargo details of a booking before payment (user action).
|
* Update the cargo details of a booking before payment (user action).
|
||||||
*
|
*
|
||||||
* Only the owner can edit, and only while the booking is QUOTE.
|
* Only the owner can edit, and only while the booking is PENDING_PAYMENT.
|
||||||
*/
|
*/
|
||||||
async updateBookingDetails(
|
async updateBookingDetails(
|
||||||
id: string,
|
id: string,
|
||||||
@ -1131,7 +1129,7 @@ export class CsvBookingService {
|
|||||||
*
|
*
|
||||||
* Used when the user re-runs the search and picks a (possibly different) rate:
|
* Used when the user re-runs the search and picks a (possibly different) rate:
|
||||||
* carrier, route, container, transit, cargo and price are all replaced. Only
|
* carrier, route, container, transit, cargo and price are all replaced. Only
|
||||||
* the owner can edit, and only while the booking is QUOTE.
|
* the owner can edit, and only while the booking is PENDING_PAYMENT.
|
||||||
*/
|
*/
|
||||||
async updateBookingRate(
|
async updateBookingRate(
|
||||||
id: string,
|
id: string,
|
||||||
@ -1206,20 +1204,14 @@ export class CsvBookingService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get bookings for an organization (paginated), whoever created them, each
|
* Get bookings for an organization (paginated)
|
||||||
* with the name of its creator so the list can show and filter by author.
|
|
||||||
*/
|
*/
|
||||||
async getOrganizationBookings(
|
async getOrganizationBookings(
|
||||||
organizationId: string,
|
organizationId: string,
|
||||||
page: number = 1,
|
page: number = 1,
|
||||||
limit: number = 10
|
limit: number = 10
|
||||||
): Promise<CsvBookingListResponseDto> {
|
): Promise<CsvBookingListResponseDto> {
|
||||||
// One query for the members instead of one lookup per booking.
|
const bookings = await this.csvBookingRepository.findByOrganizationId(organizationId);
|
||||||
const [bookings, members] = await Promise.all([
|
|
||||||
this.csvBookingRepository.findByOrganizationId(organizationId),
|
|
||||||
this.userRepository.findByOrganization(organizationId),
|
|
||||||
]);
|
|
||||||
const creatorNames = new Map(members.map(member => [member.id, this.creatorName(member)]));
|
|
||||||
|
|
||||||
// Simple pagination (in-memory)
|
// Simple pagination (in-memory)
|
||||||
const start = (page - 1) * limit;
|
const start = (page - 1) * limit;
|
||||||
@ -1227,10 +1219,7 @@ export class CsvBookingService {
|
|||||||
const paginatedBookings = bookings.slice(start, end);
|
const paginatedBookings = bookings.slice(start, end);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
bookings: paginatedBookings.map(b => ({
|
bookings: paginatedBookings.map(b => this.toResponseDto(b)),
|
||||||
...this.toResponseDto(b),
|
|
||||||
createdByName: creatorNames.get(b.userId) ?? null,
|
|
||||||
})),
|
|
||||||
total: bookings.length,
|
total: bookings.length,
|
||||||
page,
|
page,
|
||||||
limit,
|
limit,
|
||||||
@ -1245,7 +1234,7 @@ export class CsvBookingService {
|
|||||||
const stats = await this.csvBookingRepository.countByStatusForUser(userId);
|
const stats = await this.csvBookingRepository.countByStatusForUser(userId);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
quote: stats[CsvBookingStatus.QUOTE] || 0,
|
pendingPayment: stats[CsvBookingStatus.PENDING_PAYMENT] || 0,
|
||||||
pending: stats[CsvBookingStatus.PENDING] || 0,
|
pending: stats[CsvBookingStatus.PENDING] || 0,
|
||||||
accepted: stats[CsvBookingStatus.ACCEPTED] || 0,
|
accepted: stats[CsvBookingStatus.ACCEPTED] || 0,
|
||||||
rejected: stats[CsvBookingStatus.REJECTED] || 0,
|
rejected: stats[CsvBookingStatus.REJECTED] || 0,
|
||||||
@ -1261,7 +1250,7 @@ export class CsvBookingService {
|
|||||||
const stats = await this.csvBookingRepository.countByStatusForOrganization(organizationId);
|
const stats = await this.csvBookingRepository.countByStatusForOrganization(organizationId);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
quote: stats[CsvBookingStatus.QUOTE] || 0,
|
pendingPayment: stats[CsvBookingStatus.PENDING_PAYMENT] || 0,
|
||||||
pending: stats[CsvBookingStatus.PENDING] || 0,
|
pending: stats[CsvBookingStatus.PENDING] || 0,
|
||||||
accepted: stats[CsvBookingStatus.ACCEPTED] || 0,
|
accepted: stats[CsvBookingStatus.ACCEPTED] || 0,
|
||||||
rejected: stats[CsvBookingStatus.REJECTED] || 0,
|
rejected: stats[CsvBookingStatus.REJECTED] || 0,
|
||||||
@ -1359,9 +1348,9 @@ export class CsvBookingService {
|
|||||||
throw new NotFoundException(`Booking with ID ${bookingId} not found`);
|
throw new NotFoundException(`Booking with ID ${bookingId} not found`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Allow adding documents to QUOTE, PENDING_BANK_TRANSFER, PENDING, or ACCEPTED bookings
|
// Allow adding documents to PENDING_PAYMENT, PENDING_BANK_TRANSFER, PENDING, or ACCEPTED bookings
|
||||||
if (
|
if (
|
||||||
booking.status !== CsvBookingStatus.QUOTE &&
|
booking.status !== CsvBookingStatus.PENDING_PAYMENT &&
|
||||||
booking.status !== CsvBookingStatus.PENDING_BANK_TRANSFER &&
|
booking.status !== CsvBookingStatus.PENDING_BANK_TRANSFER &&
|
||||||
booking.status !== CsvBookingStatus.PENDING &&
|
booking.status !== CsvBookingStatus.PENDING &&
|
||||||
booking.status !== CsvBookingStatus.ACCEPTED
|
booking.status !== CsvBookingStatus.ACCEPTED
|
||||||
@ -1411,7 +1400,10 @@ export class CsvBookingService {
|
|||||||
});
|
});
|
||||||
this.logger.log(`New documents notification sent to carrier: ${booking.carrierEmail}`);
|
this.logger.log(`New documents notification sent to carrier: ${booking.carrierEmail}`);
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
this.logger.error('Failed to send new documents notification');
|
this.logger.error(
|
||||||
|
`Failed to send new documents notification: ${error?.message}`,
|
||||||
|
error?.stack
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1615,6 +1607,7 @@ export class CsvBookingService {
|
|||||||
containerType: booking.containerType,
|
containerType: booking.containerType,
|
||||||
status: booking.status,
|
status: booking.status,
|
||||||
documents: booking.documents.map(this.toDocumentDto),
|
documents: booking.documents.map(this.toDocumentDto),
|
||||||
|
confirmationToken: booking.confirmationToken,
|
||||||
requestedAt: booking.requestedAt,
|
requestedAt: booking.requestedAt,
|
||||||
respondedAt: booking.respondedAt || null,
|
respondedAt: booking.respondedAt || null,
|
||||||
notes: booking.notes,
|
notes: booking.notes,
|
||||||
|
|||||||
@ -54,9 +54,7 @@ function buildService(options: { user?: UserOrmEntity | null } = {}) {
|
|||||||
} as unknown as EntityManager;
|
} as unknown as EntityManager;
|
||||||
|
|
||||||
const dataSource = {
|
const dataSource = {
|
||||||
transaction: jest.fn(async (callback: (m: EntityManager) => Promise<void>) =>
|
transaction: jest.fn(async (callback: (m: EntityManager) => Promise<void>) => callback(manager)),
|
||||||
callback(manager)
|
|
||||||
),
|
|
||||||
query: jest.fn(async (sql: string, parameters: unknown[]) => {
|
query: jest.fn(async (sql: string, parameters: unknown[]) => {
|
||||||
executed.push({ sql, parameters });
|
executed.push({ sql, parameters });
|
||||||
return [];
|
return [];
|
||||||
|
|||||||
@ -208,9 +208,7 @@ export class GDPRService {
|
|||||||
const user = await this.userRepository.findOne({ where: { id: userId } });
|
const user = await this.userRepository.findOne({ where: { id: userId } });
|
||||||
if (!user) throw new NotFoundException('User not found');
|
if (!user) throw new NotFoundException('User not found');
|
||||||
|
|
||||||
this.logger.warn(
|
this.logger.warn(`GDPR erasure starting for user ${userId} — reason: ${reason ?? 'unspecified'}`);
|
||||||
`GDPR erasure starting for user ${userId} — reason: ${reason ?? 'unspecified'}`
|
|
||||||
);
|
|
||||||
|
|
||||||
const deleted: Record<string, number> = {};
|
const deleted: Record<string, number> = {};
|
||||||
const anonymised: Record<string, number> = {};
|
const anonymised: Record<string, number> = {};
|
||||||
@ -230,9 +228,7 @@ export class GDPRService {
|
|||||||
userId,
|
userId,
|
||||||
]);
|
]);
|
||||||
deleted.apiKeys = await rows('DELETE FROM api_keys WHERE user_id = $1', [userId]);
|
deleted.apiKeys = await rows('DELETE FROM api_keys WHERE user_id = $1', [userId]);
|
||||||
deleted.cookieConsent = await rows('DELETE FROM cookie_consents WHERE user_id = $1', [
|
deleted.cookieConsent = await rows('DELETE FROM cookie_consents WHERE user_id = $1', [userId]);
|
||||||
userId,
|
|
||||||
]);
|
|
||||||
deleted.passwordResetTokens = await rows(
|
deleted.passwordResetTokens = await rows(
|
||||||
'DELETE FROM password_reset_tokens WHERE user_id = $1',
|
'DELETE FROM password_reset_tokens WHERE user_id = $1',
|
||||||
[userId]
|
[userId]
|
||||||
@ -365,9 +361,7 @@ export class GDPRService {
|
|||||||
|
|
||||||
const next: UpdateConsentDto = {
|
const next: UpdateConsentDto = {
|
||||||
essential: true,
|
essential: true,
|
||||||
functional: consentType
|
functional: consentType ? consentType !== 'functional' && (current?.functional ?? false) : false,
|
||||||
? consentType !== 'functional' && (current?.functional ?? false)
|
|
||||||
: false,
|
|
||||||
analytics: consentType ? consentType !== 'analytics' && (current?.analytics ?? false) : false,
|
analytics: consentType ? consentType !== 'analytics' && (current?.analytics ?? false) : false,
|
||||||
marketing: consentType ? consentType !== 'marketing' && (current?.marketing ?? false) : false,
|
marketing: consentType ? consentType !== 'marketing' && (current?.marketing ?? false) : false,
|
||||||
};
|
};
|
||||||
|
|||||||
@ -1,57 +0,0 @@
|
|||||||
import { Logger } from '@nestjs/common';
|
|
||||||
import { ConfigService } from '@nestjs/config';
|
|
||||||
import { InvitationService } from './invitation.service';
|
|
||||||
import { SubscriptionService } from './subscription.service';
|
|
||||||
import { InvitationToken } from '@domain/entities/invitation-token.entity';
|
|
||||||
import { UserRole } from '@domain/entities/user.entity';
|
|
||||||
import { InvitationTokenRepository } from '@domain/ports/out/invitation-token.repository';
|
|
||||||
import { UserRepository } from '@domain/ports/out/user.repository';
|
|
||||||
import { OrganizationRepository } from '@domain/ports/out/organization.repository';
|
|
||||||
import { EmailPort } from '@domain/ports/out/email.port';
|
|
||||||
|
|
||||||
describe('invitation secret handling', () => {
|
|
||||||
it('keeps the token in the email but out of success and failure logs', async () => {
|
|
||||||
const log = jest.spyOn(Logger.prototype, 'log').mockImplementation(() => undefined);
|
|
||||||
const error = jest.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined);
|
|
||||||
try {
|
|
||||||
const invitation = InvitationToken.create({
|
|
||||||
id: 'invite-id',
|
|
||||||
token: 'test-only-invitation-secret',
|
|
||||||
email: 'user@example.org',
|
|
||||||
firstName: 'Test',
|
|
||||||
lastName: 'User',
|
|
||||||
role: UserRole.USER,
|
|
||||||
organizationId: 'org',
|
|
||||||
invitedById: 'admin',
|
|
||||||
expiresAt: new Date(Date.now() + 60_000),
|
|
||||||
});
|
|
||||||
const send = jest.fn().mockResolvedValue(undefined);
|
|
||||||
const service = new InvitationService(
|
|
||||||
{
|
|
||||||
findByToken: async () => invitation,
|
|
||||||
update: async () => invitation,
|
|
||||||
} as unknown as InvitationTokenRepository,
|
|
||||||
{
|
|
||||||
findById: async () => ({ firstName: 'Test', lastName: 'Admin' }),
|
|
||||||
} as unknown as UserRepository,
|
|
||||||
{ findById: async () => ({ name: 'Company' }) } as unknown as OrganizationRepository,
|
|
||||||
{ sendInvitationWithToken: send } as unknown as EmailPort,
|
|
||||||
new ConfigService({ FRONTEND_URL: 'https://example.org' }),
|
|
||||||
{} as SubscriptionService
|
|
||||||
);
|
|
||||||
await service['sendInvitationEmail'](invitation);
|
|
||||||
expect(send.mock.calls[0][5]).toBe(
|
|
||||||
'https://example.org/register?token=test-only-invitation-secret'
|
|
||||||
);
|
|
||||||
send.mockRejectedValue(new Error('test-only-invitation-secret'));
|
|
||||||
await expect(service['sendInvitationEmail'](invitation)).rejects.toThrow();
|
|
||||||
await service.markInvitationAsUsed(invitation.token);
|
|
||||||
expect(JSON.stringify([...log.mock.calls, ...error.mock.calls])).not.toContain(
|
|
||||||
invitation.token
|
|
||||||
);
|
|
||||||
} finally {
|
|
||||||
log.mockRestore();
|
|
||||||
error.mockRestore();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@ -109,8 +109,10 @@ export class InvitationService {
|
|||||||
|
|
||||||
// Send invitation email (async - don't block on email sending)
|
// Send invitation email (async - don't block on email sending)
|
||||||
this.logger.log(`[INVITATION] About to send email to ${email}...`);
|
this.logger.log(`[INVITATION] About to send email to ${email}...`);
|
||||||
this.sendInvitationEmail(savedInvitation).catch(() => {
|
this.sendInvitationEmail(savedInvitation).catch(err => {
|
||||||
this.logger.error(`Invitation email delivery failed: ${savedInvitation.id}`);
|
this.logger.error(`[INVITATION] ❌ Failed to send invitation email to ${email}`, err);
|
||||||
|
this.logger.error(`[INVITATION] Error message: ${err?.message}`);
|
||||||
|
this.logger.error(`[INVITATION] Error stack: ${err?.stack?.substring(0, 500)}`);
|
||||||
});
|
});
|
||||||
|
|
||||||
this.logger.log(`Invitation created successfully for ${email}`);
|
this.logger.log(`Invitation created successfully for ${email}`);
|
||||||
@ -149,7 +151,7 @@ export class InvitationService {
|
|||||||
|
|
||||||
await this.invitationRepository.update(invitation);
|
await this.invitationRepository.update(invitation);
|
||||||
|
|
||||||
this.logger.log(`Invitation ${invitation.id} marked as used`);
|
this.logger.log(`Invitation ${token} marked as used`);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -176,6 +178,7 @@ export class InvitationService {
|
|||||||
const invitationLink = `${frontendUrl}/register?token=${invitation.token}`;
|
const invitationLink = `${frontendUrl}/register?token=${invitation.token}`;
|
||||||
|
|
||||||
this.logger.log(`[INVITATION] Frontend URL: ${frontendUrl}`);
|
this.logger.log(`[INVITATION] Frontend URL: ${frontendUrl}`);
|
||||||
|
this.logger.log(`[INVITATION] Invitation link: ${invitationLink}`);
|
||||||
|
|
||||||
// Get organization details
|
// Get organization details
|
||||||
this.logger.log(`[INVITATION] Fetching organization ${invitation.organizationId}...`);
|
this.logger.log(`[INVITATION] Fetching organization ${invitation.organizationId}...`);
|
||||||
@ -211,7 +214,11 @@ export class InvitationService {
|
|||||||
|
|
||||||
this.logger.log(`[INVITATION] ✅ Email sent successfully to ${invitation.email}`);
|
this.logger.log(`[INVITATION] ✅ Email sent successfully to ${invitation.email}`);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.logger.error(`Invitation email delivery failed: ${invitation.id}`);
|
this.logger.error(
|
||||||
|
`[INVITATION] ❌ Failed to send invitation email to ${invitation.email}`,
|
||||||
|
error
|
||||||
|
);
|
||||||
|
this.logger.error(`[INVITATION] Error details: ${JSON.stringify(error, null, 2)}`);
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,38 +0,0 @@
|
|||||||
import { NotificationService } from './notification.service';
|
|
||||||
import { NotificationRepository } from '@domain/ports/out/notification.repository';
|
|
||||||
import { TypeOrmNotificationRepository } from '@infrastructure/persistence/typeorm/repositories/typeorm-notification.repository';
|
|
||||||
import { NotificationOrmEntity } from '@infrastructure/persistence/typeorm/entities/notification.orm-entity';
|
|
||||||
import { Repository } from 'typeorm';
|
|
||||||
|
|
||||||
describe('notification mutation boundary', () => {
|
|
||||||
const owner = 'bd223f0d-89be-4f98-aaf4-0ab1353594e1';
|
|
||||||
const other = 'bd223f0d-89be-4f98-aaf4-0ab1353594e2';
|
|
||||||
const id = 'bd223f0d-89be-4f98-aaf4-0ab1353594e3';
|
|
||||||
it.each([{ read: false }, [], null, '', 'invalid'])(
|
|
||||||
'rejects malformed notification criteria %j',
|
|
||||||
async value => {
|
|
||||||
const markAsRead = jest.fn();
|
|
||||||
const service = new NotificationService({ markAsRead } as unknown as NotificationRepository);
|
|
||||||
await expect(service.markAsRead(value as unknown as string, owner)).rejects.toThrow();
|
|
||||||
expect(markAsRead).not.toHaveBeenCalled();
|
|
||||||
}
|
|
||||||
);
|
|
||||||
it('restricts an update to the authenticated recipient', async () => {
|
|
||||||
const row = { id, user_id: owner, read: false };
|
|
||||||
const update = jest.fn(async (criteria: { id: string; user_id: string }) => {
|
|
||||||
if (row.id === criteria.id && row.user_id === criteria.user_id) row.read = true;
|
|
||||||
});
|
|
||||||
const repository = new TypeOrmNotificationRepository({
|
|
||||||
update,
|
|
||||||
} as unknown as Repository<NotificationOrmEntity>);
|
|
||||||
const service = new NotificationService(repository);
|
|
||||||
await service.markAsRead(id, other);
|
|
||||||
expect(row.read).toBe(false);
|
|
||||||
expect(update).toHaveBeenLastCalledWith(
|
|
||||||
{ id, user_id: other },
|
|
||||||
expect.objectContaining({ read: true })
|
|
||||||
);
|
|
||||||
await service.markAsRead(id, owner);
|
|
||||||
expect(row.read).toBe(true);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@ -4,8 +4,8 @@
|
|||||||
* Handles creating and sending notifications to users
|
* Handles creating and sending notifications to users
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { Injectable, Logger, Inject, BadRequestException } from '@nestjs/common';
|
import { Injectable, Logger, Inject } from '@nestjs/common';
|
||||||
import { v4 as uuidv4, validate as isUuid } from 'uuid';
|
import { v4 as uuidv4 } from 'uuid';
|
||||||
import {
|
import {
|
||||||
Notification,
|
Notification,
|
||||||
NotificationType,
|
NotificationType,
|
||||||
@ -109,11 +109,8 @@ export class NotificationService {
|
|||||||
/**
|
/**
|
||||||
* Mark notification as read
|
* Mark notification as read
|
||||||
*/
|
*/
|
||||||
async markAsRead(id: string, userId: string): Promise<void> {
|
async markAsRead(id: string): Promise<void> {
|
||||||
if (typeof id !== 'string' || !isUuid(id) || typeof userId !== 'string' || !isUuid(userId)) {
|
await this.notificationRepository.markAsRead(id);
|
||||||
throw new BadRequestException('Invalid notification or user ID');
|
|
||||||
}
|
|
||||||
await this.notificationRepository.markAsRead(id, userId);
|
|
||||||
this.logger.log(`Notification marked as read: ${id}`);
|
this.logger.log(`Notification marked as read: ${id}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -49,7 +49,7 @@ describe('RetentionService', () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
it('épargne les traces de traitement des demandes de droits', async () => {
|
it("épargne les traces de traitement des demandes de droits", async () => {
|
||||||
const { service, executed } = buildService();
|
const { service, executed } = buildService();
|
||||||
|
|
||||||
await service.purge();
|
await service.purge();
|
||||||
|
|||||||
@ -1,56 +0,0 @@
|
|||||||
import { ConfigService } from '@nestjs/config';
|
|
||||||
import { RawBodyRequest } from '@nestjs/common';
|
|
||||||
import { Request } from 'express';
|
|
||||||
import { SubscriptionService } from './subscription.service';
|
|
||||||
import { SubscriptionsController } from '../controllers/subscriptions.controller';
|
|
||||||
import { Subscription } from '@domain/entities/subscription.entity';
|
|
||||||
import { SubscriptionPlan } from '@domain/value-objects/subscription-plan.vo';
|
|
||||||
import { SubscriptionRepository } from '@domain/ports/out/subscription.repository';
|
|
||||||
import { LicenseRepository } from '@domain/ports/out/license.repository';
|
|
||||||
import { OrganizationRepository } from '@domain/ports/out/organization.repository';
|
|
||||||
import { UserRepository } from '@domain/ports/out/user.repository';
|
|
||||||
import { StripePort } from '@domain/ports/out/stripe.port';
|
|
||||||
|
|
||||||
describe('Stripe subscription deletion', () => {
|
|
||||||
it('persists cancellation with excess seats and accepts a duplicate event', async () => {
|
|
||||||
let saved = Subscription.create({
|
|
||||||
id: 'sub',
|
|
||||||
organizationId: 'org',
|
|
||||||
plan: SubscriptionPlan.gold(),
|
|
||||||
});
|
|
||||||
const save = jest.fn(async (value: Subscription) => {
|
|
||||||
saved = value;
|
|
||||||
});
|
|
||||||
const count = jest.fn(async () => 10);
|
|
||||||
const service = new SubscriptionService(
|
|
||||||
{ findByStripeSubscriptionId: async () => saved, save } as unknown as SubscriptionRepository,
|
|
||||||
{ countActiveBySubscriptionIdExcludingAdmins: count } as unknown as LicenseRepository,
|
|
||||||
{ findById: async () => null } as unknown as OrganizationRepository,
|
|
||||||
{} as UserRepository,
|
|
||||||
{
|
|
||||||
constructWebhookEvent: async () => ({
|
|
||||||
type: 'customer.subscription.deleted',
|
|
||||||
data: { object: { id: 'stripe-sub' } },
|
|
||||||
}),
|
|
||||||
} as unknown as StripePort,
|
|
||||||
new ConfigService()
|
|
||||||
);
|
|
||||||
await service.handleStripeWebhook(Buffer.from('signed fixture'), 'signature');
|
|
||||||
await service.handleStripeWebhook(Buffer.from('signed fixture'), 'signature');
|
|
||||||
expect(saved.plan.value).toBe('BRONZE');
|
|
||||||
expect(saved.status.value).toBe('CANCELED');
|
|
||||||
expect(save).toHaveBeenCalledTimes(2);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('does not acknowledge processing failures as successful delivery', async () => {
|
|
||||||
const handleStripeWebhook = jest.fn().mockRejectedValue(new Error('storage unavailable'));
|
|
||||||
const controller = new SubscriptionsController(
|
|
||||||
{ handleStripeWebhook } as unknown as SubscriptionService,
|
|
||||||
{} as OrganizationRepository
|
|
||||||
);
|
|
||||||
const req = { rawBody: Buffer.from('fixture') } as RawBodyRequest<Request>;
|
|
||||||
await expect(controller.handleWebhook('signature', req)).rejects.toMatchObject({ status: 500 });
|
|
||||||
handleStripeWebhook.mockResolvedValue(undefined);
|
|
||||||
await expect(controller.handleWebhook('signature', req)).resolves.toEqual({ received: true });
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@ -1,115 +0,0 @@
|
|||||||
import { ConfigService } from '@nestjs/config';
|
|
||||||
import { SubscriptionService } from './subscription.service';
|
|
||||||
import { Subscription } from '@domain/entities/subscription.entity';
|
|
||||||
import { SubscriptionRepository } from '@domain/ports/out/subscription.repository';
|
|
||||||
import { LicenseRepository } from '@domain/ports/out/license.repository';
|
|
||||||
import { OrganizationRepository } from '@domain/ports/out/organization.repository';
|
|
||||||
import { UserRepository } from '@domain/ports/out/user.repository';
|
|
||||||
import {
|
|
||||||
StripePort,
|
|
||||||
StripeCheckoutSessionData,
|
|
||||||
StripeSubscriptionData,
|
|
||||||
} from '@domain/ports/out/stripe.port';
|
|
||||||
import { SubscriptionOverviewResponseDto } from '../dto/subscription.dto';
|
|
||||||
|
|
||||||
describe('Stripe checkout organization binding', () => {
|
|
||||||
let subscription: Subscription;
|
|
||||||
let session: StripeCheckoutSessionData;
|
|
||||||
let stripeData: StripeSubscriptionData;
|
|
||||||
let save: jest.Mock;
|
|
||||||
let getSubscription: jest.Mock;
|
|
||||||
let service: SubscriptionService;
|
|
||||||
beforeEach(() => {
|
|
||||||
subscription = Subscription.create({ id: 'local-sub', organizationId: 'org-caller' });
|
|
||||||
session = {
|
|
||||||
sessionId: 'cs_fixture',
|
|
||||||
customerId: 'cus_fixture',
|
|
||||||
subscriptionId: 'sub_fixture',
|
|
||||||
status: 'complete',
|
|
||||||
metadata: { organizationId: 'org-caller' },
|
|
||||||
};
|
|
||||||
stripeData = {
|
|
||||||
subscriptionId: 'sub_fixture',
|
|
||||||
customerId: 'cus_fixture',
|
|
||||||
status: 'active',
|
|
||||||
planId: 'price_fixture',
|
|
||||||
currentPeriodStart: new Date(),
|
|
||||||
currentPeriodEnd: new Date(),
|
|
||||||
cancelAtPeriodEnd: false,
|
|
||||||
};
|
|
||||||
// No local row owns the Stripe subscription yet: models checkout before webhook delivery.
|
|
||||||
save = jest.fn(async (value: Subscription) => {
|
|
||||||
subscription = value;
|
|
||||||
return value;
|
|
||||||
});
|
|
||||||
getSubscription = jest.fn(async () => stripeData);
|
|
||||||
service = new SubscriptionService(
|
|
||||||
{ findByOrganizationId: async () => subscription, save } as unknown as SubscriptionRepository,
|
|
||||||
{ countActiveBySubscriptionIdExcludingAdmins: async () => 0 } as unknown as LicenseRepository,
|
|
||||||
{} as OrganizationRepository,
|
|
||||||
{} as UserRepository,
|
|
||||||
{
|
|
||||||
getCheckoutSession: async () => session,
|
|
||||||
getSubscription,
|
|
||||||
mapPriceIdToPlan: () => 'GOLD',
|
|
||||||
} as unknown as StripePort,
|
|
||||||
new ConfigService()
|
|
||||||
);
|
|
||||||
jest
|
|
||||||
.spyOn(service, 'getSubscriptionOverview')
|
|
||||||
.mockResolvedValue({} as SubscriptionOverviewResponseDto);
|
|
||||||
});
|
|
||||||
|
|
||||||
it.each(['org-victim', undefined])(
|
|
||||||
'rejects a checkout whose organization is %j before fetching or saving its subscription',
|
|
||||||
async owner => {
|
|
||||||
session.metadata = owner ? { organizationId: owner } : {};
|
|
||||||
await expect(service.syncFromStripe('org-caller', session.sessionId)).rejects.toMatchObject({
|
|
||||||
status: 403,
|
|
||||||
});
|
|
||||||
expect(getSubscription).not.toHaveBeenCalled();
|
|
||||||
expect(save).not.toHaveBeenCalled();
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
it('preserves checkout synchronization for its authenticated organization', async () => {
|
|
||||||
await service.syncFromStripe('org-caller', session.sessionId);
|
|
||||||
expect(save).toHaveBeenCalledTimes(1);
|
|
||||||
expect(subscription.stripeSubscriptionId).toBe('sub_fixture');
|
|
||||||
expect(subscription.stripeCustomerId).toBe('cus_fixture');
|
|
||||||
expect(subscription.plan.value).toBe('GOLD');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('does not accept a foreign checkout merely because the customer matches', async () => {
|
|
||||||
subscription = subscription.updateStripeCustomerId('cus_fixture');
|
|
||||||
session.metadata = { organizationId: 'org-victim' };
|
|
||||||
await expect(service.syncFromStripe('org-caller', session.sessionId)).rejects.toMatchObject({
|
|
||||||
status: 403,
|
|
||||||
});
|
|
||||||
expect(save).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('permits an owned upgrade to replace the existing Stripe subscription ID', async () => {
|
|
||||||
subscription = subscription.updateStripeCustomerId('cus_fixture').updateStripeSubscription({
|
|
||||||
stripeSubscriptionId: 'sub_old',
|
|
||||||
currentPeriodStart: new Date(),
|
|
||||||
currentPeriodEnd: new Date(),
|
|
||||||
cancelAtPeriodEnd: false,
|
|
||||||
});
|
|
||||||
await service.syncFromStripe('org-caller', session.sessionId);
|
|
||||||
expect(subscription.stripeSubscriptionId).toBe('sub_fixture');
|
|
||||||
expect(save).toHaveBeenCalledTimes(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('preserves sessionless refresh of an already linked subscription', async () => {
|
|
||||||
subscription = subscription.updateStripeCustomerId('cus_fixture').updateStripeSubscription({
|
|
||||||
stripeSubscriptionId: 'sub_fixture',
|
|
||||||
currentPeriodStart: new Date(),
|
|
||||||
currentPeriodEnd: new Date(),
|
|
||||||
cancelAtPeriodEnd: false,
|
|
||||||
});
|
|
||||||
await service.syncFromStripe('org-caller');
|
|
||||||
expect(getSubscription).toHaveBeenCalledWith('sub_fixture');
|
|
||||||
expect(save).toHaveBeenCalledTimes(1);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@ -4,14 +4,7 @@
|
|||||||
* Business logic for subscription and license management.
|
* Business logic for subscription and license management.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import {
|
import { Injectable, Inject, Logger, NotFoundException, BadRequestException } from '@nestjs/common';
|
||||||
Injectable,
|
|
||||||
Inject,
|
|
||||||
Logger,
|
|
||||||
NotFoundException,
|
|
||||||
BadRequestException,
|
|
||||||
ForbiddenException,
|
|
||||||
} from '@nestjs/common';
|
|
||||||
import { ConfigService } from '@nestjs/config';
|
import { ConfigService } from '@nestjs/config';
|
||||||
import { v4 as uuidv4 } from 'uuid';
|
import { v4 as uuidv4 } from 'uuid';
|
||||||
import {
|
import {
|
||||||
@ -97,7 +90,7 @@ export class SubscriptionService {
|
|||||||
// ADMIN users always have PLATINIUM plan with no expiration.
|
// ADMIN users always have PLATINIUM plan with no expiration.
|
||||||
// La regle vit dans le domaine : l'assistant la lit au meme endroit.
|
// La regle vit dans le domaine : l'assistant la lit au meme endroit.
|
||||||
const isAdmin = userRole === PLATFORM_ADMIN_ROLE;
|
const isAdmin = userRole === PLATFORM_ADMIN_ROLE;
|
||||||
const effectivePlan = resolveEffectivePlan(userRole, subscription.accessPlan);
|
const effectivePlan = resolveEffectivePlan(userRole, subscription.plan);
|
||||||
const maxLicenses = effectivePlan.maxLicenses;
|
const maxLicenses = effectivePlan.maxLicenses;
|
||||||
const availableLicenses = effectivePlan.isUnlimited()
|
const availableLicenses = effectivePlan.isUnlimited()
|
||||||
? -1
|
? -1
|
||||||
@ -287,9 +280,6 @@ export class SubscriptionService {
|
|||||||
const checkoutSession = await this.stripeAdapter.getCheckoutSession(sessionId);
|
const checkoutSession = await this.stripeAdapter.getCheckoutSession(sessionId);
|
||||||
|
|
||||||
if (checkoutSession) {
|
if (checkoutSession) {
|
||||||
if (checkoutSession.metadata?.organizationId !== organizationId) {
|
|
||||||
throw new ForbiddenException('Checkout session does not belong to this organization');
|
|
||||||
}
|
|
||||||
this.logger.log(
|
this.logger.log(
|
||||||
`Checkout session found: subscriptionId=${checkoutSession.subscriptionId}, customerId=${checkoutSession.customerId}, status=${checkoutSession.status}`
|
`Checkout session found: subscriptionId=${checkoutSession.subscriptionId}, customerId=${checkoutSession.customerId}, status=${checkoutSession.status}`
|
||||||
);
|
);
|
||||||
@ -618,7 +608,12 @@ export class SubscriptionService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Downgrade to FREE plan - count only non-ADMIN licenses
|
// Downgrade to FREE plan - count only non-ADMIN licenses
|
||||||
const canceledSubscription = subscription.cancel();
|
const canceledSubscription = subscription
|
||||||
|
.updatePlan(
|
||||||
|
SubscriptionPlan.bronze(),
|
||||||
|
await this.licenseRepository.countActiveBySubscriptionIdExcludingAdmins(subscription.id)
|
||||||
|
)
|
||||||
|
.updateStatus(SubscriptionStatus.canceled());
|
||||||
|
|
||||||
await this.subscriptionRepository.save(canceledSubscription);
|
await this.subscriptionRepository.save(canceledSubscription);
|
||||||
|
|
||||||
|
|||||||
@ -1,107 +0,0 @@
|
|||||||
import { BadRequestException, ConflictException, NotFoundException } from '@nestjs/common';
|
|
||||||
import { UserRepository } from '@domain/ports/out/user.repository';
|
|
||||||
import { User, UserRole } from '@domain/entities/user.entity';
|
|
||||||
import { anonymisedEmail } from '@domain/services/data-retention';
|
|
||||||
import { UserDeletionService } from './user-deletion.service';
|
|
||||||
import { GDPRService } from './gdpr.service';
|
|
||||||
import { SubscriptionService } from './subscription.service';
|
|
||||||
import { AdminContinuityService } from './admin-continuity.service';
|
|
||||||
|
|
||||||
const ACTOR = { id: 'admin-actor', email: 'actor@xpeditis.com' };
|
|
||||||
|
|
||||||
const buildUser = (
|
|
||||||
overrides: Partial<{ id: string; email: string; role: UserRole; isActive: boolean }>
|
|
||||||
) =>
|
|
||||||
({
|
|
||||||
id: 'target',
|
|
||||||
email: 'target@xpeditis.com',
|
|
||||||
role: UserRole.USER,
|
|
||||||
isActive: true,
|
|
||||||
...overrides,
|
|
||||||
}) as unknown as User;
|
|
||||||
|
|
||||||
function buildService(users: User[]) {
|
|
||||||
const userRepository = {
|
|
||||||
findById: jest.fn(async (id: string) => users.find(u => u.id === id) ?? null),
|
|
||||||
findAllActive: jest.fn(async () => users.filter(u => u.isActive)),
|
|
||||||
} as unknown as UserRepository;
|
|
||||||
|
|
||||||
const report = { userId: 'target', erasedAt: 'now', deleted: {}, anonymised: {} };
|
|
||||||
const gdprService = {
|
|
||||||
deleteUserData: jest.fn(async () => report),
|
|
||||||
} as unknown as GDPRService;
|
|
||||||
|
|
||||||
const subscriptionService = {
|
|
||||||
revokeLicense: jest.fn(async () => undefined),
|
|
||||||
} as unknown as SubscriptionService;
|
|
||||||
|
|
||||||
// Vrai service : c'est la regle reelle qui est exercee.
|
|
||||||
const adminContinuity = new AdminContinuityService(userRepository);
|
|
||||||
|
|
||||||
const service = new UserDeletionService(
|
|
||||||
userRepository,
|
|
||||||
gdprService,
|
|
||||||
subscriptionService,
|
|
||||||
adminContinuity
|
|
||||||
);
|
|
||||||
return { service, gdprService, subscriptionService, report };
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('UserDeletionService', () => {
|
|
||||||
it('permet a un admin de supprimer un autre admin, sans DELETE destructif', async () => {
|
|
||||||
const users = [
|
|
||||||
buildUser({ id: ACTOR.id, email: ACTOR.email, role: UserRole.ADMIN }),
|
|
||||||
buildUser({ id: 'target', role: UserRole.ADMIN }),
|
|
||||||
];
|
|
||||||
const { service, gdprService, subscriptionService, report } = buildService(users);
|
|
||||||
|
|
||||||
await expect(service.deleteByAdmin('target', ACTOR)).resolves.toBe(report);
|
|
||||||
|
|
||||||
expect(gdprService.deleteUserData).toHaveBeenCalledWith(
|
|
||||||
'target',
|
|
||||||
expect.stringContaining(ACTOR.id)
|
|
||||||
);
|
|
||||||
expect(subscriptionService.revokeLicense).toHaveBeenCalledWith('target');
|
|
||||||
});
|
|
||||||
|
|
||||||
it("refuse qu'un admin supprime son propre compte", async () => {
|
|
||||||
const users = [buildUser({ id: ACTOR.id, role: UserRole.ADMIN })];
|
|
||||||
const { service, gdprService } = buildService(users);
|
|
||||||
|
|
||||||
await expect(service.deleteByAdmin(ACTOR.id, ACTOR)).rejects.toBeInstanceOf(
|
|
||||||
BadRequestException
|
|
||||||
);
|
|
||||||
expect(gdprService.deleteUserData).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('refuse de supprimer le dernier administrateur actif', async () => {
|
|
||||||
// L'acteur n'est plus actif en base (jeton encore valide) : la cible est le
|
|
||||||
// seul ADMIN actif restant.
|
|
||||||
const users = [
|
|
||||||
buildUser({ id: ACTOR.id, role: UserRole.ADMIN, isActive: false }),
|
|
||||||
buildUser({ id: 'target', role: UserRole.ADMIN }),
|
|
||||||
];
|
|
||||||
const { service, gdprService } = buildService(users);
|
|
||||||
|
|
||||||
await expect(service.deleteByAdmin('target', ACTOR)).rejects.toBeInstanceOf(ConflictException);
|
|
||||||
expect(gdprService.deleteUserData).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('renvoie 404 pour un compte inconnu ou deja efface', async () => {
|
|
||||||
const users = [buildUser({ id: 'erased', email: anonymisedEmail('erased') })];
|
|
||||||
const { service, gdprService } = buildService(users);
|
|
||||||
|
|
||||||
await expect(service.deleteByAdmin('missing', ACTOR)).rejects.toBeInstanceOf(NotFoundException);
|
|
||||||
await expect(service.deleteByAdmin('erased', ACTOR)).rejects.toBeInstanceOf(NotFoundException);
|
|
||||||
expect(gdprService.deleteUserData).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('ne fait pas echouer la suppression si la revocation de licence echoue', async () => {
|
|
||||||
const users = [buildUser({ id: 'target' })];
|
|
||||||
const { service, subscriptionService, report } = buildService(users);
|
|
||||||
(subscriptionService.revokeLicense as jest.Mock).mockRejectedValueOnce(new Error('db down'));
|
|
||||||
jest.spyOn(console, 'error').mockImplementation(() => undefined);
|
|
||||||
|
|
||||||
await expect(service.deleteByAdmin('target', ACTOR)).resolves.toBe(report);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@ -1,81 +0,0 @@
|
|||||||
/**
|
|
||||||
* Suppression d'un utilisateur par un administrateur.
|
|
||||||
*
|
|
||||||
* Les deux endpoints (`DELETE /admin/users/:id`, `DELETE /users/:id`)
|
|
||||||
* exécutaient un `DELETE FROM users`. Deux conséquences :
|
|
||||||
* - `csv_rate_configs.uploaded_by` référence `users` sans `ON DELETE` : dès
|
|
||||||
* que la personne avait importé une grille, PostgreSQL refusait et l'API
|
|
||||||
* répondait 500 ;
|
|
||||||
* - sinon, les clés `ON DELETE CASCADE` (`csv_bookings`, `licenses`,
|
|
||||||
* `api_keys`…) emportaient ses réservations, donc des pièces comptables.
|
|
||||||
*
|
|
||||||
* On applique donc l'effacement RGPD (`GDPRService.deleteUserData`) : données
|
|
||||||
* personnelles supprimées ou anonymisées, compte désactivé, réservations
|
|
||||||
* conservées — le tout en transaction et journalisé.
|
|
||||||
*
|
|
||||||
* Garde-fous :
|
|
||||||
* - un administrateur ne supprime pas son propre compte ici (il passe par
|
|
||||||
* « Supprimer mon compte », qui exige une confirmation) ;
|
|
||||||
* - le dernier administrateur actif ne peut pas être supprimé : la
|
|
||||||
* plateforme n'aurait plus personne pour la gérer (AdminContinuityService,
|
|
||||||
* doublé d'un déclencheur PostgreSQL pour les suppressions simultanées).
|
|
||||||
*/
|
|
||||||
|
|
||||||
import { BadRequestException, Inject, Injectable, Logger, NotFoundException } from '@nestjs/common';
|
|
||||||
import { UserRepository, USER_REPOSITORY } from '@domain/ports/out/user.repository';
|
|
||||||
import { isAnonymisedEmail } from '@domain/services/data-retention';
|
|
||||||
import { GDPRService, GDPRErasureReport } from './gdpr.service';
|
|
||||||
import { SubscriptionService } from './subscription.service';
|
|
||||||
import { AdminContinuityService } from './admin-continuity.service';
|
|
||||||
|
|
||||||
/** Administrateur à l'origine de la suppression. */
|
|
||||||
export interface DeletionActor {
|
|
||||||
id: string;
|
|
||||||
email: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class UserDeletionService {
|
|
||||||
private readonly logger = new Logger(UserDeletionService.name);
|
|
||||||
|
|
||||||
constructor(
|
|
||||||
@Inject(USER_REPOSITORY) private readonly userRepository: UserRepository,
|
|
||||||
private readonly gdprService: GDPRService,
|
|
||||||
private readonly subscriptionService: SubscriptionService,
|
|
||||||
private readonly adminContinuity: AdminContinuityService
|
|
||||||
) {}
|
|
||||||
|
|
||||||
async deleteByAdmin(targetId: string, actor: DeletionActor): Promise<GDPRErasureReport> {
|
|
||||||
if (targetId === actor.id) {
|
|
||||||
throw new BadRequestException(
|
|
||||||
'Vous ne pouvez pas supprimer votre propre compte depuis l’administration. ' +
|
|
||||||
'Utilisez « Supprimer mon compte » dans vos paramètres.'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const target = await this.userRepository.findById(targetId);
|
|
||||||
// Un compte déjà effacé n'est plus un utilisateur.
|
|
||||||
if (!target || isAnonymisedEmail(target.email)) {
|
|
||||||
throw new NotFoundException(`User ${targetId} not found`);
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.adminContinuity.assertKeepsAnActiveAdmin(target, null);
|
|
||||||
|
|
||||||
const report = await this.gdprService.deleteUserData(
|
|
||||||
targetId,
|
|
||||||
`Suppression par un administrateur (${actor.id})`
|
|
||||||
);
|
|
||||||
|
|
||||||
// Après l'effacement : si la révocation échoue, le compte est bel et bien
|
|
||||||
// effacé, et répondre 500 ferait croire le contraire.
|
|
||||||
try {
|
|
||||||
await this.subscriptionService.revokeLicense(targetId);
|
|
||||||
} catch (error: unknown) {
|
|
||||||
const message = error instanceof Error ? error.message : String(error);
|
|
||||||
this.logger.error(`User ${targetId} erased but license revocation failed: ${message}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
this.logger.warn(`User ${targetId} (${target.role}) erased by admin ${actor.email}`);
|
|
||||||
return report;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -8,7 +8,6 @@ import {
|
|||||||
ParseUUIDPipe,
|
ParseUUIDPipe,
|
||||||
Patch,
|
Patch,
|
||||||
Post,
|
Post,
|
||||||
Query,
|
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { Transform } from 'class-transformer';
|
import { Transform } from 'class-transformer';
|
||||||
import { IsIn, IsOptional, IsString, IsUUID, Length } from 'class-validator';
|
import { IsIn, IsOptional, IsString, IsUUID, Length } from 'class-validator';
|
||||||
@ -53,18 +52,6 @@ export class TradeAssistantController {
|
|||||||
return this.service.status(actorOf(user));
|
return this.service.status(actorOf(user));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Pages ajoutees au wiki par l'assistant.
|
|
||||||
*
|
|
||||||
* Le wiki publie vit dans le frontend ; celles-ci vivent en base. La page de
|
|
||||||
* complements les lit ici pour que le lecteur voie le wiki entier, pas la
|
|
||||||
* seule moitie figee au build.
|
|
||||||
*/
|
|
||||||
@Get('wiki')
|
|
||||||
wiki(@Query('language') language?: string) {
|
|
||||||
return this.service.wiki(language === 'en' ? 'en' : 'fr');
|
|
||||||
}
|
|
||||||
|
|
||||||
@Get('conversations')
|
@Get('conversations')
|
||||||
list(@CurrentUser() user: UserPayload) {
|
list(@CurrentUser() user: UserPayload) {
|
||||||
return this.service.list(user.id);
|
return this.service.list(user.id);
|
||||||
|
|||||||
@ -7,37 +7,28 @@ import {
|
|||||||
TRADE_QUOTA,
|
TRADE_QUOTA,
|
||||||
TRADE_RETRIEVAL,
|
TRADE_RETRIEVAL,
|
||||||
} from '@domain/ports/out/trade-assistant.port';
|
} from '@domain/ports/out/trade-assistant.port';
|
||||||
import { WIKI_CONTRIBUTION_REPOSITORY } from '@domain/ports/out/wiki-contribution.repository';
|
|
||||||
import { OpenAiEmbeddingAdapter } from '@infrastructure/ai/openai-embedding.adapter';
|
import { OpenAiEmbeddingAdapter } from '@infrastructure/ai/openai-embedding.adapter';
|
||||||
import { OpenAiTradeAdapter } from '@infrastructure/ai/openai-trade.adapter';
|
import { OpenAiTradeAdapter } from '@infrastructure/ai/openai-trade.adapter';
|
||||||
import { WikiRetriever } from '@infrastructure/ai/wiki-retriever';
|
import { WikiRetriever } from '@infrastructure/ai/wiki-retriever';
|
||||||
import { TypeOrmTradeConversationRepository } from '@infrastructure/persistence/typeorm/repositories/typeorm-trade-conversation.repository';
|
import { TypeOrmTradeConversationRepository } from '@infrastructure/persistence/typeorm/repositories/typeorm-trade-conversation.repository';
|
||||||
import { TypeOrmTradeQuotaRepository } from '@infrastructure/persistence/typeorm/repositories/typeorm-trade-quota.repository';
|
import { TypeOrmTradeQuotaRepository } from '@infrastructure/persistence/typeorm/repositories/typeorm-trade-quota.repository';
|
||||||
import { TypeOrmWikiContributionRepository } from '@infrastructure/persistence/typeorm/repositories/typeorm-wiki-contribution.repository';
|
|
||||||
import { AuditModule } from '../audit/audit.module';
|
|
||||||
import { McpModule } from '../mcp/mcp.module';
|
import { McpModule } from '../mcp/mcp.module';
|
||||||
import { SubscriptionsModule } from '../subscriptions/subscriptions.module';
|
import { SubscriptionsModule } from '../subscriptions/subscriptions.module';
|
||||||
import { UsersModule } from '../users/users.module';
|
|
||||||
import { TradeAssistantController } from './trade-assistant.controller';
|
import { TradeAssistantController } from './trade-assistant.controller';
|
||||||
import { TradeAssistantService } from './trade-assistant.service';
|
import { TradeAssistantService } from './trade-assistant.service';
|
||||||
import { WikiReviewController } from './wiki-review.controller';
|
|
||||||
import { WikiReviewService } from './wiki-review.service';
|
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
// `McpModule` fournit le registre de capacites : sans lui, l'assistant
|
// `McpModule` fournit le registre de capacites : sans lui, l'assistant
|
||||||
// repond mais n'agit jamais. `UsersModule` et `AuditModule` servent la
|
// repond mais n'agit jamais.
|
||||||
// relecture : nommer le relecteur, et garder la trace de sa decision.
|
imports: [ConfigModule, SubscriptionsModule, McpModule],
|
||||||
imports: [ConfigModule, SubscriptionsModule, McpModule, UsersModule, AuditModule],
|
controllers: [TradeAssistantController],
|
||||||
controllers: [TradeAssistantController, WikiReviewController],
|
|
||||||
providers: [
|
providers: [
|
||||||
TradeAssistantService,
|
TradeAssistantService,
|
||||||
WikiReviewService,
|
|
||||||
{ provide: TRADE_AI, useClass: OpenAiTradeAdapter },
|
{ provide: TRADE_AI, useClass: OpenAiTradeAdapter },
|
||||||
{ provide: TRADE_EMBEDDINGS, useClass: OpenAiEmbeddingAdapter },
|
{ provide: TRADE_EMBEDDINGS, useClass: OpenAiEmbeddingAdapter },
|
||||||
{ provide: TRADE_RETRIEVAL, useClass: WikiRetriever },
|
{ provide: TRADE_RETRIEVAL, useClass: WikiRetriever },
|
||||||
{ provide: TRADE_QUOTA, useClass: TypeOrmTradeQuotaRepository },
|
{ provide: TRADE_QUOTA, useClass: TypeOrmTradeQuotaRepository },
|
||||||
{ provide: TRADE_CONVERSATIONS, useClass: TypeOrmTradeConversationRepository },
|
{ provide: TRADE_CONVERSATIONS, useClass: TypeOrmTradeConversationRepository },
|
||||||
{ provide: WIKI_CONTRIBUTION_REPOSITORY, useClass: TypeOrmWikiContributionRepository },
|
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
export class TradeAssistantModule {}
|
export class TradeAssistantModule {}
|
||||||
|
|||||||
@ -9,7 +9,6 @@ import {
|
|||||||
TradeQuotaPort,
|
TradeQuotaPort,
|
||||||
TradeRetrievalPort,
|
TradeRetrievalPort,
|
||||||
} from '@domain/ports/out/trade-assistant.port';
|
} from '@domain/ports/out/trade-assistant.port';
|
||||||
import { WikiContributionRepository } from '@domain/ports/out/wiki-contribution.repository';
|
|
||||||
import { Subscription } from '@domain/entities/subscription.entity';
|
import { Subscription } from '@domain/entities/subscription.entity';
|
||||||
import { SubscriptionPlan, SubscriptionPlanType } from '@domain/value-objects/subscription-plan.vo';
|
import { SubscriptionPlan, SubscriptionPlanType } from '@domain/value-objects/subscription-plan.vo';
|
||||||
import { AskTradeAssistantDto } from './trade-assistant.controller';
|
import { AskTradeAssistantDto } from './trade-assistant.controller';
|
||||||
@ -55,7 +54,6 @@ describe('TradeAssistantService', () => {
|
|||||||
let ai: jest.Mocked<TradeAiPort>;
|
let ai: jest.Mocked<TradeAiPort>;
|
||||||
let retrieval: jest.Mocked<TradeRetrievalPort>;
|
let retrieval: jest.Mocked<TradeRetrievalPort>;
|
||||||
let conversations: jest.Mocked<TradeConversationRepository>;
|
let conversations: jest.Mocked<TradeConversationRepository>;
|
||||||
let wikiContributions: jest.Mocked<WikiContributionRepository>;
|
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
subscriptions = {
|
subscriptions = {
|
||||||
@ -93,22 +91,7 @@ describe('TradeAssistantService', () => {
|
|||||||
rename: jest.fn().mockResolvedValue(undefined),
|
rename: jest.fn().mockResolvedValue(undefined),
|
||||||
remove: jest.fn().mockResolvedValue(undefined),
|
remove: jest.fn().mockResolvedValue(undefined),
|
||||||
};
|
};
|
||||||
wikiContributions = {
|
service = new TradeAssistantService(subscriptions, quota, ai, retrieval, conversations);
|
||||||
findPublished: jest.fn().mockResolvedValue([]),
|
|
||||||
findForReview: jest.fn().mockResolvedValue([]),
|
|
||||||
findById: jest.fn().mockResolvedValue(null),
|
|
||||||
findByTitle: jest.fn().mockResolvedValue(null),
|
|
||||||
save: jest.fn(),
|
|
||||||
revision: jest.fn().mockResolvedValue('0:none'),
|
|
||||||
};
|
|
||||||
service = new TradeAssistantService(
|
|
||||||
subscriptions,
|
|
||||||
quota,
|
|
||||||
ai,
|
|
||||||
retrieval,
|
|
||||||
conversations,
|
|
||||||
wikiContributions
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
/* ---------------------------------------------------------------------- */
|
/* ---------------------------------------------------------------------- */
|
||||||
|
|||||||
@ -26,10 +26,6 @@ import {
|
|||||||
TradeToolDefinition,
|
TradeToolDefinition,
|
||||||
TradeToolInvoker,
|
TradeToolInvoker,
|
||||||
} from '@domain/ports/out/trade-assistant.port';
|
} from '@domain/ports/out/trade-assistant.port';
|
||||||
import {
|
|
||||||
WIKI_CONTRIBUTION_REPOSITORY,
|
|
||||||
WikiContributionRepository,
|
|
||||||
} from '@domain/ports/out/wiki-contribution.repository';
|
|
||||||
import {
|
import {
|
||||||
TRADE_SUPPORT_EMAIL,
|
TRADE_SUPPORT_EMAIL,
|
||||||
isUnlimitedTradeQuota,
|
isUnlimitedTradeQuota,
|
||||||
@ -68,33 +64,10 @@ export class TradeAssistantService {
|
|||||||
@Inject(TRADE_AI) private readonly ai: TradeAiPort,
|
@Inject(TRADE_AI) private readonly ai: TradeAiPort,
|
||||||
@Inject(TRADE_RETRIEVAL) private readonly retrieval: TradeRetrievalPort,
|
@Inject(TRADE_RETRIEVAL) private readonly retrieval: TradeRetrievalPort,
|
||||||
@Inject(TRADE_CONVERSATIONS) private readonly conversations: TradeConversationRepository,
|
@Inject(TRADE_CONVERSATIONS) private readonly conversations: TradeConversationRepository,
|
||||||
@Inject(WIKI_CONTRIBUTION_REPOSITORY)
|
|
||||||
private readonly wikiContributions: WikiContributionRepository,
|
|
||||||
// Optionnel : sans registre, l'assistant repond sans jamais agir.
|
// Optionnel : sans registre, l'assistant repond sans jamais agir.
|
||||||
@Optional() private readonly capabilities?: CapabilityRegistry
|
@Optional() private readonly capabilities?: CapabilityRegistry
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
/**
|
|
||||||
* Complements **valides** du wiki, pour la page qui les affiche.
|
|
||||||
*
|
|
||||||
* Ils sont publics au sein du produit, comme le reste du wiki : la page est
|
|
||||||
* derriere l'authentification, mais son contenu ne depend ni du compte ni de
|
|
||||||
* l'organisation — c'est ce qui en fait un wiki global. Une proposition en
|
|
||||||
* attente de relecture n'y figure pas.
|
|
||||||
*/
|
|
||||||
async wiki(locale: string) {
|
|
||||||
const pages = await this.wikiContributions.findPublished(locale === 'en' ? 'en' : 'fr');
|
|
||||||
return pages.map(page => ({
|
|
||||||
id: page.id,
|
|
||||||
topic: page.topic,
|
|
||||||
title: page.title,
|
|
||||||
section: page.section,
|
|
||||||
body: page.body,
|
|
||||||
href: page.href,
|
|
||||||
updatedAt: page.updatedAt.toISOString(),
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
async status(actor: TradeActor) {
|
async status(actor: TradeActor) {
|
||||||
const subscription = await this.subscriptions.findByOrganizationId(actor.organizationId);
|
const subscription = await this.subscriptions.findByOrganizationId(actor.organizationId);
|
||||||
// Un abonnement inactif ne porte plus son offre ; le role, lui, peut la
|
// Un abonnement inactif ne porte plus son offre ; le role, lui, peut la
|
||||||
|
|||||||
@ -1,104 +0,0 @@
|
|||||||
import {
|
|
||||||
Body,
|
|
||||||
Controller,
|
|
||||||
Get,
|
|
||||||
HttpCode,
|
|
||||||
Param,
|
|
||||||
ParseUUIDPipe,
|
|
||||||
Post,
|
|
||||||
Query,
|
|
||||||
UseGuards,
|
|
||||||
} from '@nestjs/common';
|
|
||||||
import { Transform } from 'class-transformer';
|
|
||||||
import { IsInt, Min, IsOptional, IsString, Length } from 'class-validator';
|
|
||||||
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
|
||||||
import { CurrentUser, UserPayload } from '../decorators/current-user.decorator';
|
|
||||||
import { Roles } from '../decorators/roles.decorator';
|
|
||||||
import { JwtAuthGuard } from '../guards/jwt-auth.guard';
|
|
||||||
import { RolesGuard } from '../guards/roles.guard';
|
|
||||||
import { WikiReviewService, WikiReviewer } from './wiki-review.service';
|
|
||||||
|
|
||||||
const trim = ({ value }: { value: unknown }) => (typeof value === 'string' ? value.trim() : value);
|
|
||||||
|
|
||||||
export class PublishWikiContributionDto {
|
|
||||||
@IsInt()
|
|
||||||
@Min(1)
|
|
||||||
expectedVersion: number;
|
|
||||||
|
|
||||||
/** Correction de l'intitulé de section. Absent : celui proposé est conservé. */
|
|
||||||
@IsOptional()
|
|
||||||
@Transform(trim)
|
|
||||||
@IsString()
|
|
||||||
@Length(3, 120)
|
|
||||||
section?: string;
|
|
||||||
|
|
||||||
/** Correction du corps. Absent : celui proposé est conservé. */
|
|
||||||
@IsOptional()
|
|
||||||
@Transform(trim)
|
|
||||||
@IsString()
|
|
||||||
@Length(200, 6000)
|
|
||||||
body?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class RejectWikiContributionDto {
|
|
||||||
@IsInt()
|
|
||||||
@Min(1)
|
|
||||||
expectedVersion: number;
|
|
||||||
|
|
||||||
/** Motif, conservé avec la page pour relire les refus. */
|
|
||||||
@IsOptional()
|
|
||||||
@Transform(trim)
|
|
||||||
@IsString()
|
|
||||||
@Length(1, 500)
|
|
||||||
note?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Relecture des pages que l'assistant propose au wiki.
|
|
||||||
*
|
|
||||||
* Reserve a l'administration : le wiki est global, donc valider une page la
|
|
||||||
* rend visible a tous les clients et citable par l'assistant dans toutes ses
|
|
||||||
* reponses suivantes. Les deux gardes sont poses explicitement, comme sur les
|
|
||||||
* autres controleurs d'administration : le role est verifie dans le processus,
|
|
||||||
* jamais dans un prompt.
|
|
||||||
*/
|
|
||||||
@ApiTags('Trade assistant')
|
|
||||||
@ApiBearerAuth()
|
|
||||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
|
||||||
@Roles('admin')
|
|
||||||
@Controller('admin/wiki-contributions')
|
|
||||||
export class WikiReviewController {
|
|
||||||
constructor(private readonly service: WikiReviewService) {}
|
|
||||||
|
|
||||||
/** `status` absent : toute la file, refus compris. */
|
|
||||||
@Get()
|
|
||||||
list(@Query('status') status?: string) {
|
|
||||||
return this.service.list(status);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Post(':id/publish')
|
|
||||||
@HttpCode(200)
|
|
||||||
publish(
|
|
||||||
@CurrentUser() user: UserPayload,
|
|
||||||
@Param('id', ParseUUIDPipe) id: string,
|
|
||||||
@Body() dto: PublishWikiContributionDto
|
|
||||||
) {
|
|
||||||
return this.service.publish(reviewerOf(user), id, dto);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Post(':id/reject')
|
|
||||||
@HttpCode(200)
|
|
||||||
reject(
|
|
||||||
@CurrentUser() user: UserPayload,
|
|
||||||
@Param('id', ParseUUIDPipe) id: string,
|
|
||||||
@Body() dto: RejectWikiContributionDto
|
|
||||||
) {
|
|
||||||
return this.service.reject(reviewerOf(user), id, dto.expectedVersion, dto.note);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const reviewerOf = (user: UserPayload): WikiReviewer => ({
|
|
||||||
id: user.id,
|
|
||||||
email: user.email,
|
|
||||||
organizationId: user.organizationId,
|
|
||||||
});
|
|
||||||
@ -1,52 +0,0 @@
|
|||||||
import { ConflictException } from '@nestjs/common';
|
|
||||||
import { WikiContribution, WikiContributionProps } from '@domain/entities/wiki-contribution.entity';
|
|
||||||
import { knowledgeCapabilities } from '../mcp/capabilities/knowledge.capabilities';
|
|
||||||
import { WikiReviewService } from './wiki-review.service';
|
|
||||||
|
|
||||||
const body =
|
|
||||||
'Le manifeste de cargaison décrit les marchandises transportées par voie maritime internationale. Le transitaire le transmet aux autorités douanières avant le chargement au port de départ. Les informations doivent être vérifiées pour éviter une immobilisation des marchandises au terminal.';
|
|
||||||
const draft = () =>
|
|
||||||
WikiContribution.create({
|
|
||||||
id: 'page',
|
|
||||||
locale: 'fr',
|
|
||||||
topic: 'douanes',
|
|
||||||
title: 'Le manifeste maritime',
|
|
||||||
section: 'Transmission du manifeste',
|
|
||||||
body,
|
|
||||||
authorUserId: 'author',
|
|
||||||
authorOrganizationId: 'org',
|
|
||||||
});
|
|
||||||
const actor = { id: 'intruder', organizationId: 'other-org', role: 'USER' };
|
|
||||||
const reviewer = { id: 'admin', organizationId: 'admin-org', email: 'admin@example.test' };
|
|
||||||
|
|
||||||
it.each(['pending', 'published'])(
|
|
||||||
'refuses a foreign %s contribution without saving',
|
|
||||||
async status => {
|
|
||||||
const page = status === 'published' ? draft().publish('admin') : draft();
|
|
||||||
const save = jest.fn(async value => value);
|
|
||||||
const repo = { findByTitle: jest.fn(async () => page), save };
|
|
||||||
const cap = knowledgeCapabilities({ search: jest.fn(async () => []) }, repo as never).find(
|
|
||||||
c => c.policy.name === 'contribute_wiki_page'
|
|
||||||
)!;
|
|
||||||
await expect(cap.handler({ ...page.toObject(), language: 'fr' }, actor)).rejects.toThrow();
|
|
||||||
expect(save).not.toHaveBeenCalled();
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
it('refuses publication when the content changed after the review list was loaded', async () => {
|
|
||||||
const changed = WikiContribution.fromPersistence({
|
|
||||||
...draft().toObject(),
|
|
||||||
body: body + ' Le texte a changé.',
|
|
||||||
version: 2,
|
|
||||||
} as WikiContributionProps);
|
|
||||||
const save = jest.fn(async value => value);
|
|
||||||
const service = new WikiReviewService(
|
|
||||||
{ findById: jest.fn(async () => changed), save } as never,
|
|
||||||
{} as never,
|
|
||||||
{ log: jest.fn() } as never
|
|
||||||
);
|
|
||||||
await expect(
|
|
||||||
service.publish(reviewer, 'page', { expectedVersion: 1 } as never)
|
|
||||||
).rejects.toBeInstanceOf(ConflictException);
|
|
||||||
expect(save).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
@ -1,148 +0,0 @@
|
|||||||
import { NotFoundException } from '@nestjs/common';
|
|
||||||
import {
|
|
||||||
WikiContribution,
|
|
||||||
WikiContributionRejected,
|
|
||||||
WikiContributionStatus,
|
|
||||||
} from '@domain/entities/wiki-contribution.entity';
|
|
||||||
import { WikiContributionRepository } from '@domain/ports/out/wiki-contribution.repository';
|
|
||||||
import { UserRepository } from '@domain/ports/out/user.repository';
|
|
||||||
import { AuditAction } from '@domain/entities/audit-log.entity';
|
|
||||||
import { AuditService } from '../services/audit.service';
|
|
||||||
import { WikiReviewService } from './wiki-review.service';
|
|
||||||
|
|
||||||
const reviewer = { id: 'admin-1', email: 'admin@xpeditis.com', organizationId: 'org' };
|
|
||||||
|
|
||||||
const BODY = `La règle du 24 heures impose de transmettre le manifeste de cargaison aux douanes du pays de destination avant le chargement du navire au port d'embarquement. Elle s'applique au transport maritime international et conditionne l'autorisation de charger. Un dépôt tardif expose l'expéditeur à un refus d'embarquement et à une immobilisation du conteneur au terminal.`;
|
|
||||||
|
|
||||||
const proposal = () =>
|
|
||||||
WikiContribution.fromPersistence({
|
|
||||||
...WikiContribution.create({
|
|
||||||
id: 'w1',
|
|
||||||
locale: 'fr',
|
|
||||||
topic: 'douanes',
|
|
||||||
title: 'La règle des 24 heures',
|
|
||||||
section: 'Dépôt du manifeste',
|
|
||||||
body: BODY,
|
|
||||||
authorUserId: 'user',
|
|
||||||
authorOrganizationId: 'org',
|
|
||||||
}).toObject(),
|
|
||||||
version: 1,
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('WikiReviewService', () => {
|
|
||||||
let contributions: jest.Mocked<WikiContributionRepository>;
|
|
||||||
let users: jest.Mocked<Pick<UserRepository, 'findById'>>;
|
|
||||||
let audit: jest.Mocked<Pick<AuditService, 'log'>>;
|
|
||||||
let service: WikiReviewService;
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
contributions = {
|
|
||||||
findPublished: jest.fn().mockResolvedValue([]),
|
|
||||||
findForReview: jest.fn().mockResolvedValue([]),
|
|
||||||
findById: jest.fn().mockResolvedValue(proposal()),
|
|
||||||
findByTitle: jest.fn().mockResolvedValue(null),
|
|
||||||
save: jest.fn().mockImplementation((c: WikiContribution) => Promise.resolve(c)),
|
|
||||||
revision: jest.fn().mockResolvedValue('0:none'),
|
|
||||||
};
|
|
||||||
users = { findById: jest.fn().mockResolvedValue(null) };
|
|
||||||
audit = { log: jest.fn().mockResolvedValue(undefined) };
|
|
||||||
|
|
||||||
service = new WikiReviewService(
|
|
||||||
contributions,
|
|
||||||
users as unknown as UserRepository,
|
|
||||||
audit as unknown as AuditService
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
/* ---------------------------------------------------------------------- */
|
|
||||||
/* File de relecture */
|
|
||||||
/* ---------------------------------------------------------------------- */
|
|
||||||
|
|
||||||
it('counts what is waiting, and passes an explicit filter through', async () => {
|
|
||||||
const pending = proposal();
|
|
||||||
const published = proposal().publish(reviewer.id);
|
|
||||||
contributions.findForReview.mockResolvedValue([pending, published]);
|
|
||||||
|
|
||||||
const result = await service.list();
|
|
||||||
|
|
||||||
expect(contributions.findForReview).toHaveBeenCalledWith(undefined);
|
|
||||||
expect(result.pending).toBe(1);
|
|
||||||
expect(result.contributions).toHaveLength(2);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('ignores a filter it does not know, rather than returning an empty list', async () => {
|
|
||||||
await service.list('whatever');
|
|
||||||
expect(contributions.findForReview).toHaveBeenCalledWith(undefined);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('names the reviewer, and survives an account deleted since', async () => {
|
|
||||||
contributions.findForReview.mockResolvedValue([proposal().publish(reviewer.id)]);
|
|
||||||
users.findById.mockRejectedValue(new Error('db down'));
|
|
||||||
|
|
||||||
const [view] = (await service.list()).contributions;
|
|
||||||
|
|
||||||
expect(view.reviewedBy).toBeNull();
|
|
||||||
expect(view.status).toBe(WikiContributionStatus.PUBLISHED);
|
|
||||||
});
|
|
||||||
|
|
||||||
/* ---------------------------------------------------------------------- */
|
|
||||||
/* Decisions */
|
|
||||||
/* ---------------------------------------------------------------------- */
|
|
||||||
|
|
||||||
it('publishes the page and links to it', async () => {
|
|
||||||
const view = await service.publish(reviewer, 'w1', { expectedVersion: 1 });
|
|
||||||
|
|
||||||
const saved: WikiContribution = contributions.save.mock.calls[0][0];
|
|
||||||
expect(saved.status).toBe(WikiContributionStatus.PUBLISHED);
|
|
||||||
expect(saved.reviewedByUserId).toBe(reviewer.id);
|
|
||||||
expect(view.href).toBe('/dashboard/wiki/complements#w1');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('keeps the reviewer edits instead of the proposed text', async () => {
|
|
||||||
const corrected = `${BODY} Le dépôt incombe au transitaire, jamais au destinataire.`;
|
|
||||||
|
|
||||||
await service.publish(reviewer, 'w1', { expectedVersion: 1, body: corrected });
|
|
||||||
|
|
||||||
expect(contributions.save.mock.calls[0][0].body).toBe(corrected);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('refuses an edit that breaks the content policy', async () => {
|
|
||||||
const advocacy = `${BODY} Au-delà de 15 m³, nous recommandons le FCL.`;
|
|
||||||
|
|
||||||
await expect(
|
|
||||||
service.publish(reviewer, 'w1', { expectedVersion: 1, body: advocacy })
|
|
||||||
).rejects.toThrow(WikiContributionRejected);
|
|
||||||
expect(contributions.save).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('keeps a rejected page, with its reason', async () => {
|
|
||||||
const view = await service.reject(reviewer, 'w1', 1, ' Source non vérifiée ');
|
|
||||||
|
|
||||||
const saved: WikiContribution = contributions.save.mock.calls[0][0];
|
|
||||||
expect(saved.status).toBe(WikiContributionStatus.REJECTED);
|
|
||||||
expect(saved.reviewNote).toBe('Source non vérifiée');
|
|
||||||
// Une page non publiee n'a pas de lien : il pointerait vers du vide.
|
|
||||||
expect(view.href).toBeNull();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('records who decided what', async () => {
|
|
||||||
await service.publish(reviewer, 'w1', { expectedVersion: 1 });
|
|
||||||
|
|
||||||
expect(audit.log).toHaveBeenCalledWith(
|
|
||||||
expect.objectContaining({
|
|
||||||
action: AuditAction.WIKI_CONTRIBUTION_REVIEWED,
|
|
||||||
userEmail: reviewer.email,
|
|
||||||
resourceType: 'wiki_contribution',
|
|
||||||
resourceId: 'w1',
|
|
||||||
metadata: expect.objectContaining({ decision: 'published' }),
|
|
||||||
})
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('reports an unknown page rather than failing silently', async () => {
|
|
||||||
contributions.findById.mockResolvedValue(null);
|
|
||||||
await expect(service.publish(reviewer, 'w1', { expectedVersion: 1 })).rejects.toThrow(
|
|
||||||
NotFoundException
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@ -1,186 +0,0 @@
|
|||||||
import { ConflictException, Inject, Injectable, Logger, NotFoundException } from '@nestjs/common';
|
|
||||||
import {
|
|
||||||
WikiContribution,
|
|
||||||
WikiContributionStatus,
|
|
||||||
} from '@domain/entities/wiki-contribution.entity';
|
|
||||||
import {
|
|
||||||
WIKI_CONTRIBUTION_REPOSITORY,
|
|
||||||
WikiContributionRepository,
|
|
||||||
WikiContributionConflict,
|
|
||||||
} from '@domain/ports/out/wiki-contribution.repository';
|
|
||||||
import { AuditAction, AuditStatus } from '@domain/entities/audit-log.entity';
|
|
||||||
import { USER_REPOSITORY, UserRepository } from '@domain/ports/out/user.repository';
|
|
||||||
import { AuditService } from '../services/audit.service';
|
|
||||||
|
|
||||||
/** Qui relit. Vient de la session validee, jamais du corps de requete. */
|
|
||||||
export interface WikiReviewer {
|
|
||||||
id: string;
|
|
||||||
email: string;
|
|
||||||
organizationId: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Relecture des pages proposees par l'assistant.
|
|
||||||
*
|
|
||||||
* Le contrat est court : rien n'entre dans le wiki sans qu'un administrateur
|
|
||||||
* l'ait lu. Le service ne re-verifie pas les droits — le controleur porte
|
|
||||||
* `@Roles('admin')` et le garde global valide la session — mais il journalise
|
|
||||||
* chaque decision, parce qu'une page publiee engage la marque aupres de tous
|
|
||||||
* les clients et qu'on doit pouvoir dire qui l'a laissee passer.
|
|
||||||
*/
|
|
||||||
@Injectable()
|
|
||||||
export class WikiReviewService {
|
|
||||||
private readonly logger = new Logger(WikiReviewService.name);
|
|
||||||
|
|
||||||
constructor(
|
|
||||||
@Inject(WIKI_CONTRIBUTION_REPOSITORY)
|
|
||||||
private readonly contributions: WikiContributionRepository,
|
|
||||||
@Inject(USER_REPOSITORY) private readonly users: UserRepository,
|
|
||||||
private readonly audit: AuditService
|
|
||||||
) {}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* File de relecture.
|
|
||||||
*
|
|
||||||
* Sans filtre, elle montre tout — y compris les refus, qui sont ce qui
|
|
||||||
* revele ou l'assistant se trompe systematiquement.
|
|
||||||
*/
|
|
||||||
async list(status?: string) {
|
|
||||||
const filter = asStatus(status);
|
|
||||||
const pages = await this.contributions.findForReview(filter);
|
|
||||||
const reviewers = await this.reviewerNames(pages);
|
|
||||||
|
|
||||||
return {
|
|
||||||
pending: pages.filter(page => page.status === WikiContributionStatus.PENDING).length,
|
|
||||||
contributions: pages.map(page => this.toView(page, reviewers)),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
async publish(
|
|
||||||
reviewer: WikiReviewer,
|
|
||||||
id: string,
|
|
||||||
edits: { expectedVersion: number; section?: string; body?: string }
|
|
||||||
) {
|
|
||||||
const page = await this.find(id);
|
|
||||||
this.assertVersion(page, edits.expectedVersion);
|
|
||||||
const published = await this.saveReview(page.publish(reviewer.id, edits));
|
|
||||||
|
|
||||||
await this.record(reviewer, published, AuditStatus.SUCCESS, 'published');
|
|
||||||
this.logger.log(`Wiki contribution "${published.title}" published by ${reviewer.email}`);
|
|
||||||
|
|
||||||
return this.toView(published, { [reviewer.id]: reviewer.email });
|
|
||||||
}
|
|
||||||
|
|
||||||
async reject(reviewer: WikiReviewer, id: string, expectedVersion: number, note?: string) {
|
|
||||||
const page = await this.find(id);
|
|
||||||
this.assertVersion(page, expectedVersion);
|
|
||||||
const rejected = await this.saveReview(page.reject(reviewer.id, note));
|
|
||||||
|
|
||||||
await this.record(reviewer, rejected, AuditStatus.SUCCESS, 'rejected');
|
|
||||||
|
|
||||||
return this.toView(rejected, { [reviewer.id]: reviewer.email });
|
|
||||||
}
|
|
||||||
|
|
||||||
private assertVersion(page: WikiContribution, expectedVersion: number): void {
|
|
||||||
if (
|
|
||||||
!Number.isSafeInteger(expectedVersion) ||
|
|
||||||
expectedVersion < 1 ||
|
|
||||||
page.version !== expectedVersion
|
|
||||||
) {
|
|
||||||
throw new ConflictException(
|
|
||||||
'La proposition a changé. Rechargez-la et relisez-la avant de décider.'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async saveReview(page: WikiContribution): Promise<WikiContribution> {
|
|
||||||
try {
|
|
||||||
return await this.contributions.save(page);
|
|
||||||
} catch (error) {
|
|
||||||
if (error instanceof WikiContributionConflict) {
|
|
||||||
throw new ConflictException(
|
|
||||||
'La proposition a changé. Rechargez-la et relisez-la avant de décider.'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async find(id: string): Promise<WikiContribution> {
|
|
||||||
const page = await this.contributions.findById(id);
|
|
||||||
if (!page) throw new NotFoundException('Contribution introuvable.');
|
|
||||||
return page;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* La decision est journalisee au meme titre qu'une action de capacite : c'est
|
|
||||||
* la seule trace qui relie une page du wiki a la personne qui l'a validee.
|
|
||||||
*/
|
|
||||||
private async record(
|
|
||||||
reviewer: WikiReviewer,
|
|
||||||
page: WikiContribution,
|
|
||||||
status: AuditStatus,
|
|
||||||
decision: string
|
|
||||||
): Promise<void> {
|
|
||||||
await this.audit.log({
|
|
||||||
action: AuditAction.WIKI_CONTRIBUTION_REVIEWED,
|
|
||||||
status,
|
|
||||||
userId: reviewer.id,
|
|
||||||
userEmail: reviewer.email,
|
|
||||||
organizationId: reviewer.organizationId,
|
|
||||||
resourceType: 'wiki_contribution',
|
|
||||||
resourceId: page.id,
|
|
||||||
resourceName: page.title,
|
|
||||||
metadata: { decision, topic: page.topic, locale: page.locale },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Adresses des relecteurs, en une requete.
|
|
||||||
*
|
|
||||||
* La liste affiche « validee par », et un identifiant ne dit rien a la
|
|
||||||
* personne qui relit. Un compte supprime depuis laisse la case vide plutot
|
|
||||||
* que de faire echouer la liste.
|
|
||||||
*/
|
|
||||||
private async reviewerNames(pages: WikiContribution[]): Promise<Record<string, string>> {
|
|
||||||
const ids = [...new Set(pages.map(page => page.reviewedByUserId).filter(Boolean))] as string[];
|
|
||||||
if (!ids.length) return {};
|
|
||||||
|
|
||||||
try {
|
|
||||||
const found = await Promise.all(ids.map(id => this.users.findById(id)));
|
|
||||||
return Object.fromEntries(
|
|
||||||
found.filter(Boolean).map(user => [user!.id, user!.email.toString()])
|
|
||||||
);
|
|
||||||
} catch (error) {
|
|
||||||
this.logger.warn(
|
|
||||||
`Could not resolve wiki reviewers: ${error instanceof Error ? error.message : String(error)}`
|
|
||||||
);
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private toView(page: WikiContribution, reviewers: Record<string, string>) {
|
|
||||||
return {
|
|
||||||
id: page.id,
|
|
||||||
version: page.version,
|
|
||||||
locale: page.locale,
|
|
||||||
topic: page.topic,
|
|
||||||
title: page.title,
|
|
||||||
section: page.section,
|
|
||||||
body: page.body,
|
|
||||||
status: page.status,
|
|
||||||
// Le lien n'a de sens qu'une fois la page publiee.
|
|
||||||
href: page.isPublished ? page.href : null,
|
|
||||||
reviewedBy: page.reviewedByUserId ? (reviewers[page.reviewedByUserId] ?? null) : null,
|
|
||||||
reviewedAt: page.reviewedAt?.toISOString() ?? null,
|
|
||||||
reviewNote: page.reviewNote ?? null,
|
|
||||||
createdAt: page.createdAt.toISOString(),
|
|
||||||
updatedAt: page.updatedAt.toISOString(),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Un filtre inconnu vaut « pas de filtre », plutot qu'une liste vide muette. */
|
|
||||||
function asStatus(value?: string): WikiContributionStatus | undefined {
|
|
||||||
return Object.values(WikiContributionStatus).find(status => status === value);
|
|
||||||
}
|
|
||||||
@ -8,20 +8,9 @@ import { TypeOrmUserRepository } from '../../infrastructure/persistence/typeorm/
|
|||||||
import { UserOrmEntity } from '../../infrastructure/persistence/typeorm/entities/user.orm-entity';
|
import { UserOrmEntity } from '../../infrastructure/persistence/typeorm/entities/user.orm-entity';
|
||||||
import { SubscriptionsModule } from '../subscriptions/subscriptions.module';
|
import { SubscriptionsModule } from '../subscriptions/subscriptions.module';
|
||||||
import { FeatureFlagGuard } from '../guards/feature-flag.guard';
|
import { FeatureFlagGuard } from '../guards/feature-flag.guard';
|
||||||
import { GDPRModule } from '../gdpr/gdpr.module';
|
|
||||||
import { EmailModule } from '../../infrastructure/email/email.module';
|
|
||||||
import { ORGANIZATION_REPOSITORY } from '@domain/ports/out/organization.repository';
|
|
||||||
import { OrganizationOrmEntity } from '../../infrastructure/persistence/typeorm/entities/organization.orm-entity';
|
|
||||||
import { TypeOrmOrganizationRepository } from '../../infrastructure/persistence/typeorm/repositories/typeorm-organization.repository';
|
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [TypeOrmModule.forFeature([UserOrmEntity]), SubscriptionsModule],
|
||||||
TypeOrmModule.forFeature([UserOrmEntity, OrganizationOrmEntity]),
|
|
||||||
SubscriptionsModule,
|
|
||||||
GDPRModule,
|
|
||||||
// Email d'accès envoyé au compte créé par un administrateur
|
|
||||||
EmailModule,
|
|
||||||
],
|
|
||||||
controllers: [UsersController],
|
controllers: [UsersController],
|
||||||
providers: [
|
providers: [
|
||||||
FeatureFlagGuard,
|
FeatureFlagGuard,
|
||||||
@ -29,10 +18,6 @@ import { TypeOrmOrganizationRepository } from '../../infrastructure/persistence/
|
|||||||
provide: USER_REPOSITORY,
|
provide: USER_REPOSITORY,
|
||||||
useClass: TypeOrmUserRepository,
|
useClass: TypeOrmUserRepository,
|
||||||
},
|
},
|
||||||
{
|
|
||||||
provide: ORGANIZATION_REPOSITORY,
|
|
||||||
useClass: TypeOrmOrganizationRepository,
|
|
||||||
},
|
|
||||||
],
|
],
|
||||||
exports: [
|
exports: [
|
||||||
USER_REPOSITORY, // optional, export if other modules need it
|
USER_REPOSITORY, // optional, export if other modules need it
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user