Compare commits

..

No commits in common. "main" and "check_secu" have entirely different histories.

248 changed files with 5983 additions and 18673 deletions

View File

@ -1,2 +0,0 @@
# All jobs use the existing ubuntu-latest runner label.
{}

View File

@ -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."

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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 }}

View File

@ -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 }}

View File

@ -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 }}

View File

@ -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
View 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
View 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
View 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
View 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

View File

@ -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
View File

@ -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/

View File

@ -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.

View File

@ -24,7 +24,6 @@ e2e
# Environment files # Environment files
.env .env
.env.*
.env.local .env.local
.env.development .env.development
.env.test .env.test

View File

@ -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 && \

File diff suppressed because it is too large Load Diff

View File

@ -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",

View File

@ -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);
});

View File

@ -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';

View File

@ -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');

View File

@ -7,9 +7,6 @@ const applicationRoot = existsSync(path.join(__dirname, 'dist'))
const { databaseTlsOptions } = require( const { databaseTlsOptions } = require(
path.join(applicationRoot, 'dist/infrastructure/persistence/typeorm/database-tls') 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',
@ -29,8 +26,6 @@ const AppDataSource = new DataSource({
], ],
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 +53,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);
}); });

View File

@ -12,9 +12,6 @@ const applicationRoot = existsSync(path.join(__dirname, 'dist'))
const { databaseTlsOptions } = require( const { databaseTlsOptions } = require(
path.join(applicationRoot, 'dist/infrastructure/persistence/typeorm/database-tls') 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...');
@ -69,8 +66,6 @@ async function runMigrations() {
], ],
synchronize: false, synchronize: false,
logging: true, logging: true,
logger: new SafeDatabaseLogger(true),
migrationsTransactionMode: 'all',
}); });
try { try {
@ -92,7 +87,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);
} }
} }
@ -124,7 +119,7 @@ async function main() {
if (require.main === module) { if (require.main === module) {
main().catch(error => { main().catch(error => {
console.error('❌ Startup failed. Check migration prerequisites and database availability.'); console.error('❌ Startup failed:', error);
process.exit(1); process.exit(1);
}); });
} }

View File

@ -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';
@ -42,7 +40,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';
@ -103,13 +100,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 +113,6 @@ import { CustomThrottlerGuard } from './application/guards/throttle.guard';
return { return {
pinoHttp: { pinoHttp: {
serializers: safeHttpSerializers,
transport: usePretty transport: usePretty
? { ? {
target: 'pino-pretty', target: 'pino-pretty',
@ -192,7 +181,6 @@ import { CustomThrottlerGuard } from './application/guards/throttle.guard';
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 +191,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,

View File

@ -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: [

View File

@ -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,
});
}
);
});

View File

@ -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],
}; };
} }

View File

@ -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'),
}, },
}), }),
}), }),

View File

@ -208,16 +208,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}`);
@ -457,8 +447,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}`);
} }

View File

@ -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}` };

View File

@ -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;

View File

@ -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, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}
/** /**
* 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}`);

View File

@ -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(

View File

@ -178,7 +178,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 +255,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(
@ -327,8 +327,7 @@ export class CsvBookingsController {
@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 })
@ -450,7 +449,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;
@ -538,7 +537,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 +564,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 +577,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
);
} }
/** /**
@ -659,7 +651,7 @@ export class CsvBookingsController {
@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({
@ -692,7 +684,7 @@ export class CsvBookingsController {
@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({

View File

@ -2,11 +2,6 @@ import { ExecutionContext, INestApplication } from '@nestjs/common';
import { Test } from '@nestjs/testing'; import { Test } from '@nestjs/testing';
import { ConfigService } from '@nestjs/config'; import { ConfigService } from '@nestjs/config';
import request from 'supertest'; 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 { CsvBookingsController } from './csv-bookings.controller';
import { JwtAuthGuard } from '../guards/jwt-auth.guard'; import { JwtAuthGuard } from '../guards/jwt-auth.guard';
import { CsvBookingService } from '../services/csv-booking.service'; import { CsvBookingService } from '../services/csv-booking.service';
@ -16,8 +11,6 @@ import { ORGANIZATION_REPOSITORY } from '@domain/ports/out/organization.reposito
describe('CSV booking HTTP security', () => { describe('CSV booking HTTP security', () => {
let app: INestApplication; let app: INestApplication;
let subscription: Subscription;
const countPaidShipmentsForOrganizationInYear = jest.fn().mockResolvedValue(0);
const createBooking = jest.fn(async () => ({ id: 'booking' })); const createBooking = jest.fn(async () => ({ id: 'booking' }));
const getUserBookings = jest.fn(async () => ({ bookings: [] })); const getUserBookings = jest.fn(async () => ({ bookings: [] }));
beforeAll(async () => { beforeAll(async () => {
@ -28,11 +21,11 @@ describe('CSV booking HTTP security', () => {
{ {
provide: SubscriptionService, provide: SubscriptionService,
useValue: { useValue: {
getOrCreateSubscription: async () => subscription, getOrCreateSubscription: async () => ({ plan: { maxShipmentsPerYear: -1 } }),
}, },
}, },
{ provide: ConfigService, useValue: {} }, { provide: ConfigService, useValue: {} },
{ provide: SHIPMENT_COUNTER_PORT, useValue: { countPaidShipmentsForOrganizationInYear } }, { provide: SHIPMENT_COUNTER_PORT, useValue: {} },
{ provide: ORGANIZATION_REPOSITORY, useValue: {} }, { provide: ORGANIZATION_REPOSITORY, useValue: {} },
], ],
}) })
@ -56,15 +49,7 @@ describe('CSV booking HTTP security', () => {
afterAll(async () => { afterAll(async () => {
await app?.close(); await app?.close();
}); });
beforeEach(() => { beforeEach(() => jest.clearAllMocks());
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 () => { it('rejects VIEWER mutations before invoking the booking service', async () => {
await request(app.getHttpServer()) await request(app.getHttpServer())
@ -91,24 +76,6 @@ describe('CSV booking HTTP security', () => {
.expect(413); .expect(413);
expect(createBooking).not.toHaveBeenCalled(); 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 () => { it('preserves permitted uploads', async () => {
await request(app.getHttpServer()) await request(app.getHttpServer())
.post('/csv-bookings') .post('/csv-bookings')

View File

@ -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);
} }

View File

@ -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);

View File

@ -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);
});

View File

@ -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,7 @@ 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 return UserMapper.toDto(savedUser);
// temporaire etait ecrit en clair dans les journaux. Il part desormais par
// email, et n'apparait plus nulle part ailleurs.
const invitationEmailSent = await this.sendAccountCreatedEmail(savedUser, tempPassword, user);
return { ...UserMapper.toDto(savedUser), invitationEmailSent };
}
/**
* 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;
}
} }
/** /**
@ -312,13 +262,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 +312,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 +335,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 +397,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') {

View File

@ -16,11 +16,7 @@ describe('administrator target protection', () => {
findByEmail: async () => null, findByEmail: async () => null,
save: async (user: User) => user, save: async (user: User) => user,
} as unknown as UserRepository, } as unknown as UserRepository,
{} as SubscriptionService, {} 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( await controller.createUser(
{ {
@ -69,11 +65,7 @@ describe('administrator target protection', () => {
const save = jest.fn(async () => user); const save = jest.fn(async () => user);
const controller = new UsersController( const controller = new UsersController(
{ findById: jest.fn(async () => user), save } as unknown as UserRepository, { findById: jest.fn(async () => user), save } as unknown as UserRepository,
{} as SubscriptionService, {} 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); const result = controller.updateUser(user.id, { firstName: 'Changed' }, actor);
if (role === UserRole.ADMIN) { if (role === UserRole.ADMIN) {

View File

@ -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 });
});
});

View File

@ -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;
@ -700,10 +683,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',

View File

@ -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;

View File

@ -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,
}); });
} }
} }

View File

@ -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();

View File

@ -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

View File

@ -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 {}

View File

@ -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);

View File

@ -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);
});
});

View File

@ -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;

View File

@ -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 } });
});
});

View File

@ -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' };
},
};

View File

@ -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
);
});
});

View File

@ -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;
}
}

View File

@ -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),

View File

@ -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');
});
});

View File

@ -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,
}; };
} }
} }

View File

@ -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],
}) })

View File

@ -7,7 +7,7 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { AuthModule } from '../auth/auth.module'; 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';
@ -25,7 +25,7 @@ import { NOTIFICATION_REPOSITORY } from '@domain/ports/out/notification.reposito
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],

View File

@ -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();
});
});

View File

@ -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);
}
}
}

View File

@ -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 (

View File

@ -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;

View File

@ -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
);
});
});

View File

@ -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);
});

View File

@ -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);
});
});

View File

@ -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
);
} }
} }

View File

@ -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 [];

View File

@ -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,
}; };

View File

@ -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();

View File

@ -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);
});
});

View File

@ -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}`
); );

View File

@ -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);
});
});

View File

@ -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;
}
}

View File

@ -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);

View File

@ -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 {}

View File

@ -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
);
}); });
/* ---------------------------------------------------------------------- */ /* ---------------------------------------------------------------------- */

View File

@ -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

View File

@ -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,
});

View File

@ -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();
});

View File

@ -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
);
});
});

View File

@ -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);
}

View File

@ -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

View File

@ -47,11 +47,6 @@ export enum AuditAction {
// l'assistant integre. Le nom de la capacite est dans `resourceName`. // l'assistant integre. Le nom de la capacite est dans `resourceName`.
AGENT_CAPABILITY_INVOKED = 'agent_capability_invoked', AGENT_CAPABILITY_INVOKED = 'agent_capability_invoked',
// Relecture d'une page proposee au wiki par l'assistant. Une page publiee
// engage la marque aupres de tous les clients : la trace dit qui l'a laissee
// passer, et `metadata.decision` ce qui a ete decide.
WIKI_CONTRIBUTION_REVIEWED = 'wiki_contribution_reviewed',
// Droits des personnes (RGPD). L'article 5.2 impose de pouvoir demontrer // Droits des personnes (RGPD). L'article 5.2 impose de pouvoir demontrer
// qu'une demande a ete traitee : sans trace, honorer un droit et l'ignorer // qu'une demande a ete traitee : sans trace, honorer un droit et l'ignorer
// se ressemblent. La trace d'un effacement porte l'identifiant technique et // se ressemblent. La trace d'un effacement porte l'identifiant technique et
@ -72,9 +67,9 @@ export interface AuditLogProps {
id: string; id: string;
action: AuditAction; action: AuditAction;
status: AuditStatus; status: AuditStatus;
userId: string | null; // null when no user could be identified (e.g. failed login) userId: string;
userEmail: string; userEmail: string;
organizationId: string | null; organizationId: string;
resourceType?: string; // e.g., 'booking', 'user', 'document' resourceType?: string; // e.g., 'booking', 'user', 'document'
resourceId?: string; resourceId?: string;
resourceName?: string; resourceName?: string;
@ -122,7 +117,7 @@ export class AuditLog {
return this.props.status; return this.props.status;
} }
get userId(): string | null { get userId(): string {
return this.props.userId; return this.props.userId;
} }
@ -130,7 +125,7 @@ export class AuditLog {
return this.props.userEmail; return this.props.userEmail;
} }
get organizationId(): string | null { get organizationId(): string {
return this.props.organizationId; return this.props.organizationId;
} }

View File

@ -318,7 +318,7 @@ describe('CsvBooking Entity', () => {
describe('isDeletable', () => { describe('isDeletable', () => {
it('allows deleting a booking whose commission is still unpaid', () => { it('allows deleting a booking whose commission is still unpaid', () => {
const booking = createValidBooking(); const booking = createValidBooking();
booking.status = CsvBookingStatus.QUOTE; booking.status = CsvBookingStatus.PENDING_PAYMENT;
expect(booking.isDeletable()).toBe(true); expect(booking.isDeletable()).toBe(true);
}); });
@ -340,7 +340,7 @@ describe('CsvBooking Entity', () => {
it('stops being deletable once the payment is completed', () => { it('stops being deletable once the payment is completed', () => {
const booking = createValidBooking(); const booking = createValidBooking();
booking.status = CsvBookingStatus.QUOTE; booking.status = CsvBookingStatus.PENDING_PAYMENT;
expect(booking.isDeletable()).toBe(true); expect(booking.isDeletable()).toBe(true);
booking.markPaymentCompleted(); booking.markPaymentCompleted();

View File

@ -6,7 +6,7 @@ import { PortCode } from '../value-objects/port-code.vo';
* Represents the lifecycle of a CSV-based booking request * Represents the lifecycle of a CSV-based booking request
*/ */
export enum CsvBookingStatus { export enum CsvBookingStatus {
QUOTE = 'QUOTE', // Devis : reservation creee, frais de booking non regles PENDING_PAYMENT = 'PENDING_PAYMENT', // Awaiting commission payment
PENDING_BANK_TRANSFER = 'PENDING_BANK_TRANSFER', // Bank transfer declared, awaiting admin validation PENDING_BANK_TRANSFER = 'PENDING_BANK_TRANSFER', // Bank transfer declared, awaiting admin validation
PENDING = 'PENDING', // Awaiting carrier response PENDING = 'PENDING', // Awaiting carrier response
ACCEPTED = 'ACCEPTED', // Carrier accepted the booking ACCEPTED = 'ACCEPTED', // Carrier accepted the booking
@ -18,7 +18,7 @@ export enum CsvBookingStatus {
* Statuts dans lesquels aucun paiement n'a ete encaisse : la reservation peut * Statuts dans lesquels aucun paiement n'a ete encaisse : la reservation peut
* alors etre supprimee. Voir `CsvBooking.isDeletable()`. * alors etre supprimee. Voir `CsvBooking.isDeletable()`.
*/ */
export const DELETABLE_STATUSES: readonly CsvBookingStatus[] = [CsvBookingStatus.QUOTE]; export const DELETABLE_STATUSES: readonly CsvBookingStatus[] = [CsvBookingStatus.PENDING_PAYMENT];
/** /**
* Document Interface * Document Interface
@ -194,12 +194,12 @@ export class CsvBooking {
/** /**
* Mark commission payment as completed → transition to PENDING * Mark commission payment as completed → transition to PENDING
* *
* @throws Error if booking is not in QUOTE status * @throws Error if booking is not in PENDING_PAYMENT status
*/ */
markPaymentCompleted(): void { markPaymentCompleted(): void {
if (this.status !== CsvBookingStatus.QUOTE) { if (this.status !== CsvBookingStatus.PENDING_PAYMENT) {
throw new Error( throw new Error(
`Cannot mark payment completed for booking with status ${this.status}. Only QUOTE bookings can transition.` `Cannot mark payment completed for booking with status ${this.status}. Only PENDING_PAYMENT bookings can transition.`
); );
} }
@ -210,12 +210,12 @@ export class CsvBooking {
* Declare bank transfer → transition to PENDING_BANK_TRANSFER * Declare bank transfer → transition to PENDING_BANK_TRANSFER
* Called when user confirms they have sent the bank transfer * Called when user confirms they have sent the bank transfer
* *
* @throws Error if booking is not in QUOTE status * @throws Error if booking is not in PENDING_PAYMENT status
*/ */
markBankTransferDeclared(): void { markBankTransferDeclared(): void {
if (this.status !== CsvBookingStatus.QUOTE) { if (this.status !== CsvBookingStatus.PENDING_PAYMENT) {
throw new Error( throw new Error(
`Cannot declare bank transfer for booking with status ${this.status}. Only QUOTE bookings can transition.` `Cannot declare bank transfer for booking with status ${this.status}. Only PENDING_PAYMENT bookings can transition.`
); );
} }
@ -325,11 +325,11 @@ export class CsvBooking {
/** /**
* Edit the cargo details of a booking before it is paid. * Edit the cargo details of a booking before it is paid.
* *
* Only allowed while the booking is awaiting payment (QUOTE), i.e. * Only allowed while the booking is awaiting payment (PENDING_PAYMENT), i.e.
* before it is sent to the carrier. Carrier, route and price derive from the * before it is sent to the carrier. Carrier, route and price derive from the
* selected rate and are not editable here. * selected rate and are not editable here.
* *
* @throws Error if the booking is not in QUOTE status or values are invalid * @throws Error if the booking is not in PENDING_PAYMENT status or values are invalid
*/ */
editDetails(details: { editDetails(details: {
volumeCBM?: number; volumeCBM?: number;
@ -346,9 +346,9 @@ export class CsvBooking {
fobCurrency?: string; fobCurrency?: string;
}; };
}): void { }): void {
if (this.status !== CsvBookingStatus.QUOTE) { if (this.status !== CsvBookingStatus.PENDING_PAYMENT) {
throw new Error( throw new Error(
`Cannot edit booking with status ${this.status}. Only QUOTE bookings can be edited.` `Cannot edit booking with status ${this.status}. Only PENDING_PAYMENT bookings can be edited.`
); );
} }
@ -399,9 +399,9 @@ export class CsvBooking {
/** /**
* Re-apply a full rate selection before payment: the user re-ran the search * Re-apply a full rate selection before payment: the user re-ran the search
* and picked a rate, so carrier, route, container, transit, cargo and price * and picked a rate, so carrier, route, container, transit, cargo and price
* are all replaced. Only allowed while the booking is QUOTE. * are all replaced. Only allowed while the booking is PENDING_PAYMENT.
* *
* @throws Error if the booking is not QUOTE or values are invalid * @throws Error if the booking is not PENDING_PAYMENT or values are invalid
*/ */
editFromRate(data: { editFromRate(data: {
carrierName: string; carrierName: string;
@ -423,9 +423,9 @@ export class CsvBooking {
notes?: string; notes?: string;
options?: Record<string, boolean>; options?: Record<string, boolean>;
}): void { }): void {
if (this.status !== CsvBookingStatus.QUOTE) { if (this.status !== CsvBookingStatus.PENDING_PAYMENT) {
throw new Error( throw new Error(
`Cannot edit booking with status ${this.status}. Only QUOTE bookings can be edited.` `Cannot edit booking with status ${this.status}. Only PENDING_PAYMENT bookings can be edited.`
); );
} }
if (!data.carrierName || data.carrierName.trim().length === 0) { if (!data.carrierName || data.carrierName.trim().length === 0) {
@ -462,11 +462,12 @@ export class CsvBooking {
} }
/** /**
* Un devis : la reservation est construite mais les frais de booking ne sont * Check if booking has expired (7 days without response)
* pas regles, donc rien n'est encore parti chez le transporteur. *
* @returns true if booking is older than 7 days and still pending
*/ */
isQuote(): boolean { isPendingPayment(): boolean {
return this.status === CsvBookingStatus.QUOTE; return this.status === CsvBookingStatus.PENDING_PAYMENT;
} }
isExpired(): boolean { isExpired(): boolean {

View File

@ -62,34 +62,35 @@ export class Subscription {
}); });
} }
/** Current entitlements; keep the persisted plan intact for billing and recovery. */ /**
get accessPlan(): SubscriptionPlan { * Reconstitute from persistence
return this.isActive() ? this.props.plan : SubscriptionPlan.bronze(); */
} /**
* Check if a specific plan feature is available
*/
hasFeature(feature: import('../value-objects/plan-feature.vo').PlanFeature): boolean { hasFeature(feature: import('../value-objects/plan-feature.vo').PlanFeature): boolean {
return this.accessPlan.hasFeature(feature); return this.props.plan.hasFeature(feature);
} }
/** /**
* Get the maximum shipments per year allowed * Get the maximum shipments per year allowed
*/ */
get maxShipmentsPerYear(): number { get maxShipmentsPerYear(): number {
return this.accessPlan.maxShipmentsPerYear; return this.props.plan.maxShipmentsPerYear;
} }
/** /**
* Get the per-booking fee for this subscription's plan * Get the per-booking fee for this subscription's plan
*/ */
get bookingFeeEur(): number { get bookingFeeEur(): number {
return this.accessPlan.bookingFeeEur; return this.props.plan.bookingFeeEur;
} }
/** /**
* Get the status badge for this subscription's plan * Get the status badge for this subscription's plan
*/ */
get statusBadge(): string { get statusBadge(): string {
return this.accessPlan.statusBadge; return this.props.plan.statusBadge;
} }
/** /**

View File

@ -1,257 +0,0 @@
import {
WikiContributionDraft,
refuseWikiContribution,
} from '../services/wiki-contribution-policy';
/**
* Page proposee au wiki global par l'assistant.
*
* Le wiki publie vit dans les fichiers de traduction du frontend : il est fige
* au build et ne peut pas grandir pendant qu'un client pose une question. Cette
* entite est l'autre moitie du wiki — celle qui s'ecrit a l'execution, quand
* l'assistant rencontre un sujet d'information generale que la documentation ne
* couvre pas encore.
*
* Elle nait **en attente**. `refuseWikiContribution` ecarte la faute franche a
* la construction, mais une heuristique ne juge pas la justesse d'un contenu :
* une page fausse mais bien ecrite la franchirait. Un administrateur tranche
* donc avant publication, et rien n'est lu par la recherche ni affiche aux
* clients tant qu'il n'a pas tranche.
*
* Elle porte son auteur : la page est globale, mais on sait toujours quelle
* question l'a fait naitre, et qui l'a validee.
*/
export enum WikiContributionStatus {
/** Ecrite par l'assistant, pas encore relue. Invisible partout ailleurs. */
PENDING = 'pending',
/** Validee par un administrateur : elle fait partie du wiki. */
PUBLISHED = 'published',
/** Ecartee a la relecture. Conservee pour la trace, jamais affichee. */
REJECTED = 'rejected',
}
export interface WikiContributionProps {
id: string;
version: number;
locale: string;
/** Sujet du wiki auquel la page se rattache, ex. `douanes`. */
topic: string;
title: string;
/** Intitule de la section, affiche sous le titre et indexe avec lui. */
section: string;
body: string;
status: WikiContributionStatus;
/** Compte dont la question a declenche la contribution. */
authorUserId: string;
authorOrganizationId: string;
/** Administrateur qui a tranche, une fois la relecture faite. */
reviewedByUserId?: string;
reviewedAt?: Date;
/** Motif du refus, rendu a l'administrateur dans la liste. */
reviewNote?: string;
createdAt: Date;
updatedAt: Date;
}
export class WikiContributionRejected extends Error {}
export class WikiContribution {
private constructor(private readonly props: WikiContributionProps) {}
/**
* Cree une page, ou refuse le brouillon.
*
* Le refus est une exception et non un `null` : l'appelant est une capacite
* invoquee par un modele, et le motif doit lui revenir en toutes lettres pour
* qu'il l'explique a l'utilisateur au lieu de reessayer.
*/
static create(
props: Omit<WikiContributionProps, 'id' | 'status' | 'createdAt' | 'updatedAt' | 'version'> & {
id: string;
}
): WikiContribution {
const draft: WikiContributionDraft = {
topic: props.topic,
title: props.title,
section: props.section,
body: props.body,
};
const refusal = refuseWikiContribution(draft);
if (refusal) throw new WikiContributionRejected(refusal);
const now = new Date();
return new WikiContribution({
...props,
// Le statut n'est pas un parametre : rien ne nait publie, pas meme une
// page ecrite par un administrateur.
version: 0,
status: WikiContributionStatus.PENDING,
createdAt: now,
updatedAt: now,
});
}
static fromPersistence(props: WikiContributionProps): WikiContribution {
return new WikiContribution(props);
}
/**
* Remplace le corps d'une page existante.
*
* Un sujet deja couvert ne donne pas une seconde page : le wiki grandirait en
* doublons, et la recherche citerait deux fois la meme chose. Le meme titre
* dans la meme langue est donc mis a jour, pas duplique.
*/
revise(section: string, body: string): WikiContribution {
const refusal = refuseWikiContribution({
topic: this.props.topic,
title: this.props.title,
section,
body,
});
if (refusal) throw new WikiContributionRejected(refusal);
// Reviser, c'est reproposer : une page deja validee qui change de contenu
// repasse par la relecture, sinon la validation porterait sur un texte que
// plus personne n'a lu.
return new WikiContribution({
...this.props,
section,
body,
status: WikiContributionStatus.PENDING,
reviewedByUserId: undefined,
reviewedAt: undefined,
reviewNote: undefined,
updatedAt: new Date(),
});
}
/**
* Valide la page : elle entre dans le wiki.
*
* L'administrateur peut corriger le texte au passage — c'est le cas courant,
* une page presque juste qu'il ne veut pas renvoyer a l'assistant. Sa version
* passe la meme politique de contenu que l'originale.
*/
publish(reviewerId: string, edits?: { section?: string; body?: string }): WikiContribution {
const section = edits?.section?.trim() || this.props.section;
const body = edits?.body?.trim() || this.props.body;
const refusal = refuseWikiContribution({
topic: this.props.topic,
title: this.props.title,
section,
body,
});
if (refusal) throw new WikiContributionRejected(refusal);
return new WikiContribution({
...this.props,
section,
body,
status: WikiContributionStatus.PUBLISHED,
reviewedByUserId: reviewerId,
reviewedAt: new Date(),
reviewNote: undefined,
updatedAt: new Date(),
});
}
/**
* Ecarte la page.
*
* Elle est conservee plutot que supprimee : la liste des refus est ce qui
* montre ou l'assistant se trompe, et elle evite de relire deux fois la meme
* proposition.
*/
reject(reviewerId: string, note?: string): WikiContribution {
return new WikiContribution({
...this.props,
status: WikiContributionStatus.REJECTED,
reviewedByUserId: reviewerId,
reviewedAt: new Date(),
reviewNote: note?.trim() || undefined,
updatedAt: new Date(),
});
}
get version(): number {
return this.props.version;
}
get status(): WikiContributionStatus {
return this.props.status;
}
get isPublished(): boolean {
return this.props.status === WikiContributionStatus.PUBLISHED;
}
get reviewedByUserId(): string | undefined {
return this.props.reviewedByUserId;
}
get reviewedAt(): Date | undefined {
return this.props.reviewedAt;
}
get reviewNote(): string | undefined {
return this.props.reviewNote;
}
get id(): string {
return this.props.id;
}
get locale(): string {
return this.props.locale;
}
get topic(): string {
return this.props.topic;
}
get title(): string {
return this.props.title;
}
get section(): string {
return this.props.section;
}
get body(): string {
return this.props.body;
}
get authorUserId(): string {
return this.props.authorUserId;
}
get authorOrganizationId(): string {
return this.props.authorOrganizationId;
}
get createdAt(): Date {
return this.props.createdAt;
}
get updatedAt(): Date {
return this.props.updatedAt;
}
/**
* Lien vers la page, dans le wiki.
*
* Les complements tiennent sur une seule page, groupee par sujet : l'ancre
* amene le lecteur au bon paragraphe, sans creer une route par contribution
* ni un sujet vide pour chaque page qui n'en a pas encore.
*/
get href(): string {
return `/dashboard/wiki/complements#${this.props.id}`;
}
toObject(): WikiContributionProps {
return { ...this.props };
}
}

View File

@ -25,43 +25,7 @@ export interface EmailOptions {
attachments?: EmailAttachment[]; attachments?: EmailAttachment[];
} }
/** Message du formulaire de contact, adressé à l'équipe. */
export interface ContactMessageEmail {
firstName: string;
lastName: string;
email: string;
company?: string;
phone?: string;
/** Libellé lisible du sujet choisi. */
subjectLabel: string;
message: string;
}
/** Virement déclaré par un client, à valider par un administrateur. */
export interface BankTransferToValidateEmail {
bookingNumber: string;
carrierName: string;
routeDescription: string;
/** Montant déjà formaté (ex. « 150,00 € »). */
commissionAmount: string;
}
export interface EmailPort { export interface EmailPort {
/**
* Send the contact form message to the team (reply-to = sender)
*/
sendContactMessage(to: string, data: ContactMessageEmail): Promise<void>;
/**
* Alert admins that a declared bank transfer awaits validation
*/
sendBankTransferToValidate(to: string[], data: BankTransferToValidateEmail): Promise<void>;
/**
* Send the SMTP diagnostic email from the admin panel
*/
sendSmtpTest(to: string, requestedBy: string): Promise<void>;
/** /**
* Send an email * Send an email
*/ */

View File

@ -15,8 +15,11 @@ export interface ShipmentCounterPort {
/** /**
* Count only PAID shipments (fee paid / payment declared / accepted) created by * Count only PAID shipments (fee paid / payment declared / accepted) created by
* an organization in a given year. Unpaid drafts (QUOTE), rejected and * an organization in a given year. Unpaid drafts (PENDING_PAYMENT), rejected and
* cancelled bookings are excluded. * cancelled bookings are excluded.
*/ */
countPaidShipmentsForOrganizationInYear(organizationId: string, year: number): Promise<number>; countPaidShipmentsForOrganizationInYear(
organizationId: string,
year: number
): Promise<number>;
} }

View File

@ -1,56 +0,0 @@
import { WikiContribution, WikiContributionStatus } from '../../entities/wiki-contribution.entity';
export class WikiContributionConflict extends Error {}
export interface WikiContributionWriter {
id: string;
organizationId: string;
}
export const WIKI_CONTRIBUTION_REPOSITORY = 'WikiContributionRepository';
export interface WikiContributionRepository {
/**
* Pages **publiees** pour cette langue, de la plus recente a la plus ancienne.
*
* C'est ce que lisent la recherche documentaire et la page de complements :
* une proposition en attente n'existe pour personne d'autre que le relecteur.
*/
findPublished(locale: string): Promise<WikiContribution[]>;
/**
* File de relecture, tous statuts confondus ou filtree.
*
* Reservee a l'administration : c'est le seul endroit d'ou une page en
* attente est visible.
*/
findForReview(status?: WikiContributionStatus): Promise<WikiContribution[]>;
findById(id: string): Promise<WikiContribution | null>;
/**
* Page portant deja ce titre, quel que soit son statut.
*
* Le couple (langue, sujet, titre) est l'identite editoriale d'une page :
* c'est ce qui permet de mettre a jour une proposition plutot que d'en
* empiler une seconde sur le meme sujet, y compris quand la premiere attend
* encore sa relecture.
*/
findByTitle(locale: string, topic: string, title: string): Promise<WikiContribution | null>;
/** Inserts version 0; otherwise atomically updates the exact version. Contributor writes also enforce ownership and unpublished state. */
save(
contribution: WikiContribution,
contributor?: WikiContributionWriter
): Promise<WikiContribution>;
/**
* Empreinte du jeu **publie**, qui change des qu'une page est validee,
* revisee ou retiree.
*
* L'index vectoriel des complements est garde en memoire ; cette valeur est
* ce qui dit a la recherche qu'il est perime, sans relire tout le contenu a
* chaque question.
*/
revision(locale: string): Promise<string>;
}

View File

@ -1,20 +0,0 @@
import { removesActiveAdmin } from './admin-continuity';
const activeAdmin = { role: 'ADMIN', isActive: true };
describe('removesActiveAdmin', () => {
it("detecte l'effacement, la retrogradation et la desactivation d'un admin actif", () => {
expect(removesActiveAdmin(activeAdmin, null)).toBe(true);
expect(removesActiveAdmin(activeAdmin, { role: 'MANAGER', isActive: true })).toBe(true);
expect(removesActiveAdmin(activeAdmin, { role: 'ADMIN', isActive: false })).toBe(true);
});
it("laisse passer ce qui conserve l'admin actif", () => {
expect(removesActiveAdmin(activeAdmin, { role: 'ADMIN', isActive: true })).toBe(false);
});
it('ignore les comptes qui ne sont pas des admins actifs', () => {
expect(removesActiveAdmin({ role: 'USER', isActive: true }, null)).toBe(false);
expect(removesActiveAdmin({ role: 'ADMIN', isActive: false }, null)).toBe(false);
});
});

View File

@ -1,43 +0,0 @@
/**
* Continuité de l'administration : la plateforme garde toujours au moins un
* administrateur actif.
*
* Sans administrateur, plus personne ne peut valider une organisation, gérer
* les comptes ou rétablir un accès : la seule issue est une intervention SQL
* sur la base de production.
*
* La règle est appliquée à deux niveaux :
* - dans l'application (AdminContinuityService), pour répondre un message
* clair avant toute écriture ;
* - dans PostgreSQL (déclencheur `trg_users_keep_active_admin`, migration
* 1790000000002), seul endroit capable de l'imposer à deux requêtes
* simultanées — deux administrateurs qui se suppriment l'un l'autre au même
* instant — et à toute écriture qui ne passerait pas par l'application.
*/
/** Code métier renvoyé au client quand l'opération retirerait le dernier admin. */
export const LAST_ACTIVE_ADMIN_CODE = 'last_active_admin';
/** SQLSTATE levé par le déclencheur PostgreSQL pour la même violation. */
export const LAST_ACTIVE_ADMIN_SQLSTATE = 'XP001';
const ADMIN_ROLE = 'ADMIN';
export interface AdminState {
role: string;
isActive: boolean;
}
/**
* L'opération fait-elle perdre à ce compte son statut d'administrateur actif ?
*
* @param before état actuel du compte
* @param after état visé, ou `null` si le compte est effacé
*/
export function removesActiveAdmin(before: AdminState, after: AdminState | null): boolean {
const wasActiveAdmin = before.role === ADMIN_ROLE && before.isActive;
if (!wasActiveAdmin) {
return false;
}
return after === null || after.role !== ADMIN_ROLE || !after.isActive;
}

View File

@ -80,7 +80,7 @@ export const RETENTION_RULES: readonly RetentionRule[] = [
timestampColumn: 'created_at', timestampColumn: 'created_at',
onErasure: 'delete', onErasure: 'delete',
months: 12, months: 12,
basis: 'Confort de service, sans valeur probante : rien ne justifie de les conserver.', basis: "Confort de service, sans valeur probante : rien ne justifie de les conserver.",
}, },
{ {
table: 'trade_conversations', table: 'trade_conversations',
@ -155,7 +155,3 @@ export const ANONYMISED = 'anonymised';
* permet aucun rattachement — l'identifiant technique existait déjà en base. * permet aucun rattachement — l'identifiant technique existait déjà en base.
*/ */
export const anonymisedEmail = (userId: string): string => `${ANONYMISED}+${userId}@invalid.local`; export const anonymisedEmail = (userId: string): string => `${ANONYMISED}+${userId}@invalid.local`;
/** Le compte portant cette adresse a-t-il été effacé ? */
export const isAnonymisedEmail = (email: string): boolean =>
email.startsWith(`${ANONYMISED}+`) && email.endsWith('@invalid.local');

View File

@ -1,98 +0,0 @@
import {
WIKI_TOPICS,
WikiContributionDraft,
refuseWikiContribution,
} from './wiki-contribution-policy';
/**
* Le corps d'une page valide : assez long, franchement international, sans
* conseil FCL ni donnee de compte. Chaque cas ne modifie que ce qu'il teste.
*/
const BODY = `Le connaissement maritime, ou bill of lading, est le document qui matérialise le contrat de transport international. Il vaut titre de propriété de la marchandise et preuve de la prise en charge par le transitaire. Il est émis en trois originaux négociables, dont la remise conditionne la livraison au destinataire au port de destination. Un connaissement propre ne porte aucune réserve sur l'état du cargo au chargement.`;
const draft = (overrides: Partial<WikiContributionDraft> = {}): WikiContributionDraft => ({
topic: 'documents-transport',
title: 'Le connaissement maritime',
section: 'Rôle et originaux',
body: BODY,
...overrides,
});
describe('refuseWikiContribution', () => {
it('accepts a page of general international-transport knowledge', () => {
expect(refuseWikiContribution(draft())).toBeNull();
});
it('accepts every published topic', () => {
for (const topic of WIKI_TOPICS) {
expect(refuseWikiContribution(draft({ topic }))).toBeNull();
}
});
it('refuses a topic outside the wiki', () => {
expect(refuseWikiContribution(draft({ topic: 'divers' }))).toBe('unknown-topic');
});
it('refuses a remark passed off as a page', () => {
expect(refuseWikiContribution(draft({ body: 'Le connaissement fait foi.' }))).toBe('too-thin');
});
/* ---------------------------------------------------------------------- */
/* Le FCL */
/* ---------------------------------------------------------------------- */
it.each([
'Nous recommandons le FCL au-delà de 15 m³.',
'Il est préférable de choisir un conteneur complet pour ce type de cargo.',
'Au-delà de ce volume, le FCL est plus économique sur la liaison maritime.',
'For larger cargo you should use FCL instead of consolidation.',
'Un conteneur dédié reste la meilleure option pour un export fragile.',
])('refuses FCL advocacy: %s', sentence => {
expect(refuseWikiContribution(draft({ body: `${BODY} ${sentence}` }))).toBe('fcl-advocacy');
});
it('allows FCL to be explained without being advised', () => {
const body = `${BODY} Le FCL désigne un conteneur complet chargé pour un seul expéditeur. Xpeditis opère en groupage LCL : les marchandises de plusieurs clients partagent le conteneur.`;
expect(refuseWikiContribution(draft({ body }))).toBeNull();
});
it('does not refuse an LCL recommendation that merely names FCL elsewhere', () => {
const body = `${BODY}\nLe FCL est un conteneur complet. Le groupage LCL est recommandé pour les envois de moins de 15 m³.`;
expect(refuseWikiContribution(draft({ body }))).toBeNull();
});
/* ---------------------------------------------------------------------- */
/* Le particulier */
/* ---------------------------------------------------------------------- */
it.each([
['a booking number', 'La réservation WCM-2026-004512 illustre ce cas.'],
['an e-mail address', 'Écrivez à jean.martin@acme-import.fr pour les originaux.'],
['a customer file', 'Pour votre dossier, le connaissement a été émis le 3 mars.'],
['a rate', 'Le fret maritime revient à 48 EUR par CBM sur cette liaison.'],
['a price in symbols', 'Comptez $3,400 de THC au départ.'],
])('refuses account-specific content — %s', (_label, sentence) => {
expect(refuseWikiContribution(draft({ body: `${BODY} ${sentence}` }))).toBe('account-specific');
});
/* ---------------------------------------------------------------------- */
/* Le perimetre */
/* ---------------------------------------------------------------------- */
it('refuses content that is not about international transport', () => {
const body =
"La tenue d'une comptabilité analytique suppose de distinguer les charges directes des charges indirectes, puis de les répartir par centre d'analyse selon des clés stables d'un exercice à l'autre. Cette méthode éclaire la marge dégagée par chaque activité de l'entreprise, sans rien changer aux comptes publiés.";
expect(refuseWikiContribution(draft({ body, title: 'Comptabilité analytique' }))).toBe(
'not-international'
);
});
it('checks the title and the section, not only the body', () => {
expect(refuseWikiContribution(draft({ title: 'Pourquoi préférer le FCL' }))).toBe(
'fcl-advocacy'
);
expect(refuseWikiContribution(draft({ section: 'Votre dossier en cours' }))).toBe(
'account-specific'
);
});
});

View File

@ -1,160 +0,0 @@
/**
* Ce qui a le droit d'entrer dans le wiki global.
*
* Le wiki est lu par tous les clients et sert de source a l'assistant : une
* page fausse ou hors sujet ne coute pas une reponse, elle contamine toutes les
* suivantes. La contribution automatique est donc bornee ici, dans le domaine,
* et non dans un prompt — un modele peut oublier une consigne, il ne peut pas
* contourner cette fonction.
*
* Trois interdits, dans l'ordre ou ils comptent :
*
* 1. **Le FCL.** Xpeditis ne vend que du groupage LCL. Une page qui conseille
* le conteneur complet envoie le client ailleurs, et l'assistant la citerait
* ensuite comme une recommandation maison.
* 2. **Le particulier.** Un dossier, un tarif, une adresse : c'est de la donnee
* de compte, elle n'a rien a faire dans une page vue par tout le monde.
* 3. **Le hors-perimetre.** Le wiki documente le transport international. Le
* reste n'y a pas sa place, meme juste.
*
* Les heuristiques ci-dessous sont un garde-fou, pas une preuve : elles
* attrapent la faute franche. Elles sont volontairement severes — refuser une
* bonne page coute une contribution, en accepter une mauvaise coute le wiki.
*/
/** Sujets ouverts a la contribution. Ce sont ceux du wiki publie. */
export const WIKI_TOPICS = [
'incoterms',
'documents-transport',
'douanes',
'assurance',
'calcul-fret',
'conteneurs',
'imdg',
'vgm',
'lettre-credit',
'ports-routes',
'transit-time',
'reglementation',
] as const;
export type WikiTopic = (typeof WIKI_TOPICS)[number];
export interface WikiContributionDraft {
topic: string;
title: string;
section: string;
body: string;
}
export type WikiRefusal =
| 'unknown-topic'
| 'too-thin'
| 'fcl-advocacy'
| 'account-specific'
| 'not-international';
/**
* Message rendu a l'agent quand la contribution est refusee.
*
* Il dit ce qui bloque, pas comment le contourner : l'assistant doit pouvoir
* l'expliquer a l'utilisateur, pas reecrire le texte jusqu'a passer.
*/
export const WIKI_REFUSAL_MESSAGES: Readonly<Record<WikiRefusal, string>> = {
'unknown-topic': `Sujet inconnu. Les sujets du wiki sont : ${WIKI_TOPICS.join(', ')}.`,
'too-thin':
"Contribution trop courte pour une page de wiki : il faut un texte d'information autonome, pas une phrase.",
'fcl-advocacy':
'Le wiki Xpeditis ne publie pas de contenu qui recommande le FCL. Xpeditis opère en groupage LCL uniquement.',
'account-specific':
"Le wiki est global : il n'accueille ni cas client, ni dossier, ni tarif, ni coordonnées. Ne publiez que du savoir valable pour tous.",
'not-international':
"Le wiki ne documente que le transport international de marchandises. Ce contenu n'y a pas sa place.",
};
/** En deca, ce n'est pas une page d'information mais une remarque. */
const MIN_BODY_LENGTH = 200;
/**
* Le FCL nomme, dans toutes ses formulations courantes.
*
* « conteneur complet » compte autant que le sigle : l'interdit porte sur la
* solution, pas sur les trois lettres.
*/
const FCL_MENTION =
/\b(fcl|full\s+container(\s+load)?|conteneurs?\s+(complets?|entiers?|d[ée]di[ée]s?|exclusifs?))(?![a-zà-ÿ0-9])/i;
/**
* Verbe ou tournure qui transforme une mention en conseil.
*
* Expliquer ce qu'est le FCL reste permis — c'est du vocabulaire metier. Le
* refus vise la phrase qui pousse a y aller.
*/
const ADVOCACY =
/\b(recommand\w*|conseill\w*|pr[ée]conis\w*|privil[ée]gi\w*|opt(ez|er|e|ons)|choisi\w*|choisir|pr[ée]f[ée]r\w*|mieux\s+vaut|passez?\s+(au|en)|bascul\w*|plus\s+([ée]conomique|avantageu\w*|rentable|int[ée]ressant\w*|adapt[ée]\w*)|meilleur\w*|id[ée]al\w*|recommend\w*|prefer\w*|should\s+(use|choose|go|book|switch)|better\s+(to|option|choice)|best\s+(option|choice)|cheaper|go\s+for)(?![a-zà-ÿ0-9])/i;
/**
* Ce qui trahit un contenu de dossier plutot qu'une page de wiki.
*
* Les montants comptent : un tarif vieillit, et une page de wiki ne vieillit
* pas — elle reste lue longtemps apres que le prix a change.
*/
const ACCOUNT_SPECIFIC: readonly RegExp[] = [
/\bWCM-\d{4}-\d{6}\b/i,
/[\w.+-]+@[\w-]+\.[a-z]{2,}/i,
/\b(votre|vos|ton|tes|mon|ma|mes|notre|nos)\s+(dossier|r[ée]servation|booking|compte|abonnement|organisation|exp[ée]dition|devis|facture|client)\b/i,
/\b(your|my|our)\s+(booking|account|shipment|quote|invoice|subscription)\b/i,
// « 1 250 EUR », « 45€/CBM », « $3,400 » : un chiffre colle a une monnaie.
/\d[\d\s.,]*\s*(€|\$|£|¥|eur\b|usd\b|gbp\b|cny\b|jpy\b)/i,
/(€|\$|£|¥)\s*\d/,
];
/**
* Vocabulaire du transport international.
*
* Deux termes distincts suffisent : une page legitime en emploie toujours
* plusieurs, un texte hors sujet n'en emploie aucun.
*/
const INTERNATIONAL_TERMS =
/\b(maritime|incoterms?|douan\w+|customs|d[ée]douan\w+|import\w*|export\w*|connaissement|bill\s+of\s+lading|b\/l|sea\s+waybill|conteneur\w*|container\w*|fret|freight|lcl|groupage|consolidation|transitaire|forwarder|exp[ée]diteur|destinataire|shipper|consignee|hs\s+code|code\s+sh|nomenclature|eur\.?1|transit|transbordement|navire|vessel|armateur|port|terminal|cfs|vgm|imdg|solas|cbm|thc|baf|caf|cr[ée]dit\s+documentaire|letter\s+of\s+credit|assurance|cargo|international\w*|manifeste|manifest|surestaries|demurrage|detention)\b/gi;
const MIN_INTERNATIONAL_TERMS = 2;
/**
* Examine un brouillon. `null` : il peut etre publie.
*
* L'ordre des controles est celui des messages rendus : le premier motif
* trouve est celui qui est explique, sans enumerer les autres.
*/
export function refuseWikiContribution(draft: WikiContributionDraft): WikiRefusal | null {
if (!(WIKI_TOPICS as readonly string[]).includes(draft.topic)) return 'unknown-topic';
const body = draft.body.trim();
if (body.length < MIN_BODY_LENGTH) return 'too-thin';
const full = `${draft.title}\n${draft.section}\n${body}`;
if (advocatesFcl(full)) return 'fcl-advocacy';
if (ACCOUNT_SPECIFIC.some(pattern => pattern.test(full))) return 'account-specific';
if (distinctInternationalTerms(full) < MIN_INTERNATIONAL_TERMS) return 'not-international';
return null;
}
/**
* Le FCL est-il conseille, et non seulement nomme ?
*
* La recherche se fait phrase par phrase : « Le FCL est un conteneur complet.
* Le groupage LCL est recommande sous 15 m³. » ne doit pas etre refusee parce
* que les deux tournures cohabitent dans le meme paragraphe.
*/
function advocatesFcl(text: string): boolean {
return text
.split(/(?<=[.!?;:])\s+|\n+/)
.some(sentence => FCL_MENTION.test(sentence) && ADVOCACY.test(sentence));
}
function distinctInternationalTerms(text: string): number {
const found = text.match(INTERNATIONAL_TERMS) ?? [];
return new Set(found.map(term => term.toLowerCase())).size;
}

View File

@ -20,7 +20,6 @@
"RATE_QUOTE_EXPIRED": "Rate quote has expired", "RATE_QUOTE_EXPIRED": "Rate quote has expired",
"CARRIER_NOT_FOUND": "Carrier not found", "CARRIER_NOT_FOUND": "Carrier not found",
"NO_LICENSES_AVAILABLE": "No licenses available for this organization", "NO_LICENSES_AVAILABLE": "No licenses available for this organization",
"LAST_ACTIVE_ADMIN": "Not possible: the platform must keep at least one active administrator. Promote or reactivate another administrator first.",
"SERVICE_UNAVAILABLE": "The service is temporarily unavailable. Try again in a moment; if the problem persists, contact support@xpeditis.com.", "SERVICE_UNAVAILABLE": "The service is temporarily unavailable. Try again in a moment; if the problem persists, contact support@xpeditis.com.",
"UNEXPECTED_ERROR": "Something went wrong on our side. Try again, and if it happens again, send the reference below to support@xpeditis.com." "UNEXPECTED_ERROR": "Something went wrong on our side. Try again, and if it happens again, send the reference below to support@xpeditis.com."
} }

View File

@ -20,7 +20,6 @@
"RATE_QUOTE_EXPIRED": "La cotation a expiré", "RATE_QUOTE_EXPIRED": "La cotation a expiré",
"CARRIER_NOT_FOUND": "Transporteur introuvable", "CARRIER_NOT_FOUND": "Transporteur introuvable",
"NO_LICENSES_AVAILABLE": "Aucune licence disponible pour cette organisation", "NO_LICENSES_AVAILABLE": "Aucune licence disponible pour cette organisation",
"LAST_ACTIVE_ADMIN": "Impossible : la plateforme doit garder au moins un administrateur actif. Promouvez ou réactivez d’abord un autre administrateur.",
"SERVICE_UNAVAILABLE": "Service momentanément indisponible. Réessayez dans quelques instants ; si le problème persiste, contactez support@xpeditis.com.", "SERVICE_UNAVAILABLE": "Service momentanément indisponible. Réessayez dans quelques instants ; si le problème persiste, contactez support@xpeditis.com.",
"UNEXPECTED_ERROR": "Une erreur inattendue s'est produite de notre côté. Réessayez, et si cela se reproduit, transmettez la référence ci-dessous à support@xpeditis.com." "UNEXPECTED_ERROR": "Une erreur inattendue s'est produite de notre côté. Réessayez, et si cela se reproduit, transmettez la référence ci-dessous à support@xpeditis.com."
} }

Some files were not shown because too many files have changed in this diff Show More