Compare commits

..

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

1097 changed files with 16969 additions and 197155 deletions

View File

@ -1,43 +0,0 @@
---
name: "source-command-explore-and-plan"
description: "Explore codebase, create implementation plan, code, and test following EPCT workflow"
---
# source-command-explore-and-plan
Use this skill when the user asks to run the migrated source command `explore-and-plan`.
## Command Template
# Explore, Plan, Code, Test Workflow
At the end of this message, I will ask you to do something.
Please follow the "Explore, Plan, Code, Test" workflow when you start.
## Explore
First, use parallel subagents to find and read all files that may be useful for implementing the ticket, either as examples or as edit targets. The subagents should return relevant file paths, and any other info that may be useful.
## Plan
Next, think hard and write up a detailed implementation plan. Don't forget to include tests, lookbook components, and documentation. Use your judgement as to what is necessary, given the standards of this repo.
If there are things you are not sure about, use parallel subagents to do some web research. They should only return useful information, no noise.
If there are things you still do not understand or questions you have for the user, pause here to ask them before continuing.
## Code
When you have a thorough implementation plan, you are ready to start writing code. Follow the style of the existing codebase (e.g. we prefer clearly named variables and methods to extensive comments). Make sure to run our autoformatting script when you're done, and fix linter warnings that seem reasonable to you.
## Test
Use parallel subagents to run tests, and make sure they all pass.
If your changes touch the UX in a major way, use the browser to make sure that everything works correctly. Make a list of what to test for, and use a subagent for this step.
If your testing shows problems, go back to the planning stage and think ultrahard.
## Write up your work
When you are happy with your work, write up a short report that could be used as the PR description. Include what you set out to do, the choices you made with their brief justification, and any commands you ran in the process that may be useful for future developers to know about.

View File

@ -1,17 +0,0 @@
---
name: "source-command-fix-pr-comments"
description: "Fetch all comments for the current pull request and fix them."
---
# source-command-fix-pr-comments
Use this skill when the user asks to run the migrated source command `fix-pr-comments`.
## Command Template
Workflow:
1. Use `gh cli` to fetch the comments that are NOT resolved from the pull request.
2. Define all the modifications you should actually make.
3. Act and update the files.
4. Create a commit and push.

View File

@ -1,43 +0,0 @@
---
name: "source-command-quick-commit"
description: "Quickly commit all changes with an auto-generated message"
---
# source-command-quick-commit
Use this skill when the user asks to run the migrated source command `quick-commit`.
## Command Template
Workflow for quick Git commits:
1. Check git status to see what changes are present
2. Analyze changes to generate a short, clear commit message
3. Stage all changes (tracked and untracked files)
4. Create the commit with DH7789-dev signature
5. Optionally push to remote if tracking branch exists
The commit message will be automatically generated by analyzing:
- Modified files and their purposes (components, configs, tests, docs, etc.)
- New files added and their function
- Deleted files and cleanup operations
- Overall scope of changes to determine action verb (add, update, fix, refactor, remove, etc.)
Commit message format: `[action] [what was changed]`
Examples:
- `add user authentication system`
- `fix navigation menu responsive issues`
- `update API endpoints configuration`
- `refactor database connection logic`
- `remove deprecated utility functions`
This command is ideal for:
- Quick iteration cycles
- Work-in-progress commits
- Feature development checkpoints
- Bug fix commits
The commit will include your custom signature:
```
Signed-off-by: DH7789-dev
```

View File

@ -14,55 +14,55 @@
const SECURITY_RULES = { const SECURITY_RULES = {
// Critical system destruction commands // Critical system destruction commands
CRITICAL_COMMANDS: [ CRITICAL_COMMANDS: [
'del', "del",
'format', "format",
'mkfs', "mkfs",
'shred', "shred",
'dd', "dd",
'fdisk', "fdisk",
'parted', "parted",
'gparted', "gparted",
'cfdisk', "cfdisk",
], ],
// Privilege escalation and system access // Privilege escalation and system access
PRIVILEGE_COMMANDS: [ PRIVILEGE_COMMANDS: [
'sudo', "sudo",
'su', "su",
'passwd', "passwd",
'chpasswd', "chpasswd",
'usermod', "usermod",
'chmod', "chmod",
'chown', "chown",
'chgrp', "chgrp",
'setuid', "setuid",
'setgid', "setgid",
], ],
// Network and remote access tools // Network and remote access tools
NETWORK_COMMANDS: [ NETWORK_COMMANDS: [
'nc', "nc",
'netcat', "netcat",
'nmap', "nmap",
'telnet', "telnet",
'ssh-keygen', "ssh-keygen",
'iptables', "iptables",
'ufw', "ufw",
'firewall-cmd', "firewall-cmd",
'ipfw', "ipfw",
], ],
// System service and process manipulation // System service and process manipulation
SYSTEM_COMMANDS: [ SYSTEM_COMMANDS: [
'systemctl', "systemctl",
'service', "service",
'kill', "kill",
'killall', "killall",
'pkill', "pkill",
'mount', "mount",
'umount', "umount",
'swapon', "swapon",
'swapoff', "swapoff",
], ],
// Dangerous regex patterns // Dangerous regex patterns
@ -147,73 +147,74 @@ const SECURITY_RULES = {
/printenv.*PASSWORD/i, /printenv.*PASSWORD/i,
], ],
// Paths that should never be written to // Paths that should never be written to
PROTECTED_PATHS: [ PROTECTED_PATHS: [
'/etc/', "/etc/",
'/usr/', "/usr/",
'/bin/', "/bin/",
'/sbin/', "/sbin/",
'/boot/', "/boot/",
'/sys/', "/sys/",
'/proc/', "/proc/",
'/dev/', "/dev/",
'/root/', "/root/",
], ],
}; };
// Allowlist of safe commands (when used appropriately) // Allowlist of safe commands (when used appropriately)
const SAFE_COMMANDS = [ const SAFE_COMMANDS = [
'ls', "ls",
'dir', "dir",
'pwd', "pwd",
'whoami', "whoami",
'date', "date",
'echo', "echo",
'cat', "cat",
'head', "head",
'tail', "tail",
'grep', "grep",
'find', "find",
'wc', "wc",
'sort', "sort",
'uniq', "uniq",
'cut', "cut",
'awk', "awk",
'sed', "sed",
'git', "git",
'npm', "npm",
'pnpm', "pnpm",
'node', "node",
'bun', "bun",
'python', "python",
'pip', "pip",
'cd', "cd",
'cp', "cp",
'mv', "mv",
'mkdir', "mkdir",
'touch', "touch",
'ln', "ln",
]; ];
class CommandValidator { class CommandValidator {
constructor() { constructor() {
this.logFile = '/Users/david/.claude/security.log'; this.logFile = "/Users/david/.claude/security.log";
} }
/** /**
* Main validation function * Main validation function
*/ */
validate(command, toolName = 'Unknown') { validate(command, toolName = "Unknown") {
const result = { const result = {
isValid: true, isValid: true,
severity: 'LOW', severity: "LOW",
violations: [], violations: [],
sanitizedCommand: command, sanitizedCommand: command,
}; };
if (!command || typeof command !== 'string') { if (!command || typeof command !== "string") {
result.isValid = false; result.isValid = false;
result.violations.push('Invalid command format'); result.violations.push("Invalid command format");
return result; return result;
} }
@ -225,28 +226,28 @@ class CommandValidator {
// Check against critical commands // Check against critical commands
if (SECURITY_RULES.CRITICAL_COMMANDS.includes(mainCommand)) { if (SECURITY_RULES.CRITICAL_COMMANDS.includes(mainCommand)) {
result.isValid = false; result.isValid = false;
result.severity = 'CRITICAL'; result.severity = "CRITICAL";
result.violations.push(`Critical dangerous command: ${mainCommand}`); result.violations.push(`Critical dangerous command: ${mainCommand}`);
} }
// Check privilege escalation commands // Check privilege escalation commands
if (SECURITY_RULES.PRIVILEGE_COMMANDS.includes(mainCommand)) { if (SECURITY_RULES.PRIVILEGE_COMMANDS.includes(mainCommand)) {
result.isValid = false; result.isValid = false;
result.severity = 'HIGH'; result.severity = "HIGH";
result.violations.push(`Privilege escalation command: ${mainCommand}`); result.violations.push(`Privilege escalation command: ${mainCommand}`);
} }
// Check network commands // Check network commands
if (SECURITY_RULES.NETWORK_COMMANDS.includes(mainCommand)) { if (SECURITY_RULES.NETWORK_COMMANDS.includes(mainCommand)) {
result.isValid = false; result.isValid = false;
result.severity = 'HIGH'; result.severity = "HIGH";
result.violations.push(`Network/remote access command: ${mainCommand}`); result.violations.push(`Network/remote access command: ${mainCommand}`);
} }
// Check system commands // Check system commands
if (SECURITY_RULES.SYSTEM_COMMANDS.includes(mainCommand)) { if (SECURITY_RULES.SYSTEM_COMMANDS.includes(mainCommand)) {
result.isValid = false; result.isValid = false;
result.severity = 'HIGH'; result.severity = "HIGH";
result.violations.push(`System manipulation command: ${mainCommand}`); result.violations.push(`System manipulation command: ${mainCommand}`);
} }
@ -254,25 +255,21 @@ class CommandValidator {
for (const pattern of SECURITY_RULES.DANGEROUS_PATTERNS) { for (const pattern of SECURITY_RULES.DANGEROUS_PATTERNS) {
if (pattern.test(command)) { if (pattern.test(command)) {
result.isValid = false; result.isValid = false;
result.severity = 'CRITICAL'; result.severity = "CRITICAL";
result.violations.push(`Dangerous pattern detected: ${pattern.source}`); result.violations.push(`Dangerous pattern detected: ${pattern.source}`);
} }
} }
// Check for protected path access (but allow common redirections like /dev/null) // Check for protected path access (but allow common redirections like /dev/null)
for (const path of SECURITY_RULES.PROTECTED_PATHS) { for (const path of SECURITY_RULES.PROTECTED_PATHS) {
if (command.includes(path)) { if (command.includes(path)) {
// Allow common safe redirections // Allow common safe redirections
if ( if (path === "/dev/" && (command.includes("/dev/null") || command.includes("/dev/stderr") || command.includes("/dev/stdout"))) {
path === '/dev/' &&
(command.includes('/dev/null') ||
command.includes('/dev/stderr') ||
command.includes('/dev/stdout'))
) {
continue; continue;
} }
result.isValid = false; result.isValid = false;
result.severity = 'HIGH'; result.severity = "HIGH";
result.violations.push(`Access to protected path: ${path}`); result.violations.push(`Access to protected path: ${path}`);
} }
} }
@ -280,20 +277,21 @@ class CommandValidator {
// Additional safety checks // Additional safety checks
if (command.length > 2000) { if (command.length > 2000) {
result.isValid = false; result.isValid = false;
result.severity = 'MEDIUM'; result.severity = "MEDIUM";
result.violations.push('Command too long (potential buffer overflow)'); result.violations.push("Command too long (potential buffer overflow)");
} }
// Check for binary/encoded content // Check for binary/encoded content
if (/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\xFF]/.test(command)) { if (/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\xFF]/.test(command)) {
result.isValid = false; result.isValid = false;
result.severity = 'HIGH'; result.severity = "HIGH";
result.violations.push('Binary or encoded content detected'); result.violations.push("Binary or encoded content detected");
} }
return result; return result;
} }
/** /**
* Log security events * Log security events
*/ */
@ -307,20 +305,22 @@ class CommandValidator {
blocked: !result.isValid, blocked: !result.isValid,
severity: result.severity, severity: result.severity,
violations: result.violations, violations: result.violations,
source: 'claude-code-hook', source: "claude-code-hook",
}; };
try { try {
// Write to log file // Write to log file
const logLine = JSON.stringify(logEntry) + '\n'; const logLine = JSON.stringify(logEntry) + "\n";
await Bun.write(this.logFile, logLine, { createPath: true, flag: 'a' }); await Bun.write(this.logFile, logLine, { createPath: true, flag: "a" });
// Also output to stderr for immediate visibility // Also output to stderr for immediate visibility
console.error( console.error(
`[SECURITY] ${result.isValid ? 'ALLOWED' : 'BLOCKED'}: ${command.substring(0, 100)}` `[SECURITY] ${
result.isValid ? "ALLOWED" : "BLOCKED"
}: ${command.substring(0, 100)}`
); );
} catch (error) { } catch (error) {
console.error('Failed to write security log:', error); console.error("Failed to write security log:", error);
} }
} }
@ -331,9 +331,12 @@ class CommandValidator {
for (const pattern of allowedPatterns) { for (const pattern of allowedPatterns) {
// Convert Claude Code permission pattern to regex // Convert Claude Code permission pattern to regex
// e.g., "Bash(git *)" becomes /^git\s+.*$/ // e.g., "Bash(git *)" becomes /^git\s+.*$/
if (pattern.startsWith('Bash(') && pattern.endsWith(')')) { if (pattern.startsWith("Bash(") && pattern.endsWith(")")) {
const cmdPattern = pattern.slice(5, -1); // Remove "Bash(" and ")" const cmdPattern = pattern.slice(5, -1); // Remove "Bash(" and ")"
const regex = new RegExp('^' + cmdPattern.replace(/\*/g, '.*') + '$', 'i'); const regex = new RegExp(
"^" + cmdPattern.replace(/\*/g, ".*") + "$",
"i"
);
if (regex.test(command)) { if (regex.test(command)) {
return true; return true;
} }
@ -361,7 +364,7 @@ async function main() {
const input = Buffer.concat(chunks).toString(); const input = Buffer.concat(chunks).toString();
if (!input.trim()) { if (!input.trim()) {
console.error('No input received from stdin'); console.error("No input received from stdin");
process.exit(1); process.exit(1);
} }
@ -370,23 +373,23 @@ async function main() {
try { try {
hookData = JSON.parse(input); hookData = JSON.parse(input);
} catch (error) { } catch (error) {
console.error('Invalid JSON input:', error.message); console.error("Invalid JSON input:", error.message);
process.exit(1); process.exit(1);
} }
const toolName = hookData.tool_name || 'Unknown'; const toolName = hookData.tool_name || "Unknown";
const toolInput = hookData.tool_input || {}; const toolInput = hookData.tool_input || {};
const sessionId = hookData.session_id || null; const sessionId = hookData.session_id || null;
// Only validate Bash commands for now // Only validate Bash commands for now
if (toolName !== 'Bash') { if (toolName !== "Bash") {
console.log(`Skipping validation for tool: ${toolName}`); console.log(`Skipping validation for tool: ${toolName}`);
process.exit(0); process.exit(0);
} }
const command = toolInput.command; const command = toolInput.command;
if (!command) { if (!command) {
console.error('No command found in tool input'); console.error("No command found in tool input");
process.exit(1); process.exit(1);
} }
@ -398,22 +401,24 @@ async function main() {
// Output result and exit with appropriate code // Output result and exit with appropriate code
if (result.isValid) { if (result.isValid) {
console.log('Command validation passed'); console.log("Command validation passed");
process.exit(0); // Allow execution process.exit(0); // Allow execution
} else { } else {
console.error(`Command validation failed: ${result.violations.join(', ')}`); console.error(
`Command validation failed: ${result.violations.join(", ")}`
);
console.error(`Severity: ${result.severity}`); console.error(`Severity: ${result.severity}`);
process.exit(2); // Block execution (Claude Code requires exit code 2) process.exit(2); // Block execution (Claude Code requires exit code 2)
} }
} catch (error) { } catch (error) {
console.error('Validation script error:', error); console.error("Validation script error:", error);
// Fail safe - block execution on any script error // Fail safe - block execution on any script error
process.exit(2); process.exit(2);
} }
} }
// Execute main function // Execute main function
main().catch(error => { main().catch((error) => {
console.error('Fatal error:', error); console.error("Fatal error:", error);
process.exit(2); process.exit(2);
}); });

View File

@ -1,46 +0,0 @@
{
"permissions": {
"allow": [
"Bash(docker-compose:*)",
"Bash(npm run lint)",
"Bash(npm run lint:*)",
"Bash(npm run backend:lint)",
"Bash(npm run backend:build:*)",
"Bash(npm run frontend:build:*)",
"Bash(rm:*)",
"Bash(git rm:*)",
"Bash(git add:*)",
"Bash(git commit:*)",
"Bash(git push:*)",
"Bash(npx tsc:*)",
"Bash(npx nest:*)",
"Read(//Users/david/Documents/xpeditis/**)",
"Bash(find:*)",
"Bash(npm test)",
"Bash(git checkout:*)",
"Bash(git reset:*)",
"Bash(curl:*)",
"Read(//private/tmp/**)",
"Bash(lsof:*)",
"Bash(awk:*)",
"Bash(xargs kill:*)",
"Read(//dev/**)",
"Bash(psql:*)",
"Bash(npx ts-node:*)",
"Bash(python3:*)",
"Read(//Users/david/.docker/**)",
"Bash(env)",
"Bash(ssh david@xpeditis-cloud \"docker ps --filter name=xpeditis-backend --format ''{{.ID}} {{.Status}}''\")",
"Bash(git revert:*)",
"Bash(git log:*)",
"Bash(xargs -r docker rm:*)",
"Bash(npm run migration:run:*)",
"Bash(npm run dev:*)",
"Bash(npm run backend:dev:*)",
"Bash(env -i PATH=\"$PATH\" HOME=\"$HOME\" node:*)",
"Bash(PGPASSWORD=xpeditis_dev_password psql -h localhost -U xpeditis -d xpeditis_dev -c:*)"
],
"deny": [],
"ask": []
}
}

View File

@ -1,25 +0,0 @@
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "bun /Users/david/.claude/scripts/validate-command.js"
}
]
}
],
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "afplay /Users/david/.claude/song/finish.mp3"
}
]
}
]
}
}

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,269 +0,0 @@
name: Rollback
# Emergency rollback — production (Hetzner k3s) and preprod (Portainer).
#
# Production strategies:
# previous — kubectl rollout undo (fastest, reverts to previous ReplicaSet)
# specific-version — kubectl set image to a specific prod-SHA tag
#
# Preprod strategy:
# Re-tags a preprod-SHA image back to :preprod, triggers Portainer webhook.
#
# Secrets required:
# REGISTRY_TOKEN — Scaleway registry
# HETZNER_KUBECONFIG — base64 kubeconfig (production only)
# PORTAINER_WEBHOOK_BACKEND — Portainer webhook preprod backend
# PORTAINER_WEBHOOK_FRONTEND — Portainer webhook preprod frontend
# PROD_BACKEND_URL — https://api.xpeditis.com
# PROD_FRONTEND_URL — https://app.xpeditis.com
# PREPROD_BACKEND_URL — https://api.preprod.xpeditis.com
# PREPROD_FRONTEND_URL — https://preprod.xpeditis.com
# DISCORD_WEBHOOK_URL
on:
workflow_dispatch:
inputs:
environment:
description: 'Target environment'
required: true
type: choice
options: [production, preprod]
strategy:
description: 'Strategy (production only — "previous" = instant kubectl undo)'
required: true
type: choice
options: [previous, specific-version]
version_tag:
description: 'Tag for specific-version (e.g. prod-a1b2c3d or preprod-a1b2c3d)'
required: false
type: string
reason:
description: 'Reason (audit trail)'
required: true
type: string
env:
REGISTRY: rg.fr-par.scw.cloud/weworkstudio
K8S_NAMESPACE: xpeditis-prod
jobs:
validate:
name: Validate Inputs
runs-on: ubuntu-latest
steps:
- name: Check inputs
run: |
ENV="${{ github.event.inputs.environment }}"
STRATEGY="${{ github.event.inputs.strategy }}"
TAG="${{ github.event.inputs.version_tag }}"
if [ "$STRATEGY" = "specific-version" ] && [ -z "$TAG" ]; then
echo "ERROR: version_tag is required for specific-version strategy."
exit 1
fi
if [ "$ENV" = "production" ] && [ "$STRATEGY" = "specific-version" ]; then
if [[ ! "$TAG" =~ ^prod- ]]; then
echo "ERROR: Production tag must start with 'prod-' (got: $TAG)"
exit 1
fi
fi
if [ "$ENV" = "preprod" ]; then
if [[ ! "$TAG" =~ ^preprod- ]]; then
echo "ERROR: Preprod tag must start with 'preprod-' (got: $TAG)"
exit 1
fi
fi
echo "Validated — env: $ENV | strategy: $STRATEGY | tag: ${TAG:-N/A} | reason: ${{ github.event.inputs.reason }}"
# ── Production rollback via kubectl ──────────────────────────────────
rollback-production:
name: Rollback Production
runs-on: ubuntu-latest
needs: validate
if: github.event.inputs.environment == 'production'
environment:
name: production
url: https://app.xpeditis.com
steps:
- name: Configure kubectl
run: |
mkdir -p ~/.kube
echo "${{ secrets.HETZNER_KUBECONFIG }}" | base64 -d > ~/.kube/config
chmod 600 ~/.kube/config
kubectl cluster-info
- name: Rollback — previous version
if: github.event.inputs.strategy == 'previous'
run: |
kubectl rollout undo deployment/xpeditis-backend -n ${{ env.K8S_NAMESPACE }}
kubectl rollout status deployment/xpeditis-backend -n ${{ env.K8S_NAMESPACE }} --timeout=180s
kubectl rollout undo deployment/xpeditis-frontend -n ${{ env.K8S_NAMESPACE }}
kubectl rollout status deployment/xpeditis-frontend -n ${{ env.K8S_NAMESPACE }} --timeout=180s
kubectl get pods -n ${{ env.K8S_NAMESPACE }}
- name: Login to Scaleway (for image verification)
if: github.event.inputs.strategy == 'specific-version'
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: nologin
password: ${{ secrets.REGISTRY_TOKEN }}
- uses: docker/setup-buildx-action@v3
if: github.event.inputs.strategy == 'specific-version'
- name: Rollback — specific version
if: github.event.inputs.strategy == 'specific-version'
run: |
TAG="${{ github.event.inputs.version_tag }}"
BACKEND="${{ env.REGISTRY }}/xpeditis-backend:${TAG}"
FRONTEND="${{ env.REGISTRY }}/xpeditis-frontend:${TAG}"
echo "Verifying images exist..."
docker buildx imagetools inspect "$BACKEND" || { echo "ERROR: $BACKEND 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 rollout status deployment/xpeditis-backend -n ${{ env.K8S_NAMESPACE }} --timeout=180s
kubectl set image deployment/xpeditis-frontend frontend="$FRONTEND" -n ${{ env.K8S_NAMESPACE }}
kubectl rollout status deployment/xpeditis-frontend -n ${{ env.K8S_NAMESPACE }} --timeout=180s
kubectl get pods -n ${{ env.K8S_NAMESPACE }}
- name: Rollout history
if: always()
run: |
kubectl rollout history deployment/xpeditis-backend -n ${{ env.K8S_NAMESPACE }} || true
kubectl rollout history deployment/xpeditis-frontend -n ${{ env.K8S_NAMESPACE }} || true
# ── Preprod rollback via Portainer ───────────────────────────────────
rollback-preprod:
name: Rollback Preprod
runs-on: ubuntu-latest
needs: validate
if: github.event.inputs.environment == 'preprod'
steps:
- uses: docker/setup-buildx-action@v3
- uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: nologin
password: ${{ secrets.REGISTRY_TOKEN }}
- name: Verify target image exists
run: |
TAG="${{ github.event.inputs.version_tag }}"
docker buildx imagetools inspect "${{ env.REGISTRY }}/xpeditis-backend:${TAG}" || \
{ echo "ERROR: backend image not found: $TAG"; exit 1; }
docker buildx imagetools inspect "${{ env.REGISTRY }}/xpeditis-frontend:${TAG}" || \
{ echo "ERROR: frontend image not found: $TAG"; exit 1; }
- name: Re-tag as preprod
run: |
TAG="${{ github.event.inputs.version_tag }}"
docker buildx imagetools create \
--tag ${{ env.REGISTRY }}/xpeditis-backend:preprod \
${{ env.REGISTRY }}/xpeditis-backend:${TAG}
docker buildx imagetools create \
--tag ${{ env.REGISTRY }}/xpeditis-frontend:preprod \
${{ env.REGISTRY }}/xpeditis-frontend:${TAG}
- name: Deploy backend (Portainer)
run: curl -sf -X POST "${{ secrets.PORTAINER_WEBHOOK_BACKEND }}"
- run: sleep 20
- name: Deploy frontend (Portainer)
run: curl -sf -X POST "${{ secrets.PORTAINER_WEBHOOK_FRONTEND }}"
# ── Smoke Tests ───────────────────────────────────────────────────────
smoke-tests:
name: Smoke Tests Post-Rollback
runs-on: ubuntu-latest
needs: [rollback-production, rollback-preprod]
if: always() && (needs.rollback-production.result == 'success' || needs.rollback-preprod.result == 'success')
steps:
- name: Set URLs
id: urls
run: |
if [ "${{ github.event.inputs.environment }}" = "production" ]; then
echo "backend=${{ secrets.PROD_BACKEND_URL }}/api/v1/health" >> $GITHUB_OUTPUT
echo "frontend=${{ secrets.PROD_FRONTEND_URL }}" >> $GITHUB_OUTPUT
echo "wait=30" >> $GITHUB_OUTPUT
else
echo "backend=${{ secrets.PREPROD_BACKEND_URL }}/api/v1/health" >> $GITHUB_OUTPUT
echo "frontend=${{ secrets.PREPROD_FRONTEND_URL }}" >> $GITHUB_OUTPUT
echo "wait=60" >> $GITHUB_OUTPUT
fi
- run: sleep ${{ steps.urls.outputs.wait }}
- name: Health — Backend
run: |
for i in {1..12}; do
STATUS=$(curl -s -o /dev/null -w "%{http_code}" --max-time 10 \
"${{ steps.urls.outputs.backend }}" 2>/dev/null || echo "000")
echo " Attempt $i: HTTP $STATUS"
if [ "$STATUS" = "200" ]; then echo "Backend OK."; exit 0; fi
sleep 15
done
echo "Backend unhealthy after rollback."
exit 1
- name: Health — Frontend
run: |
for i in {1..12}; do
STATUS=$(curl -s -o /dev/null -w "%{http_code}" --max-time 10 \
"${{ steps.urls.outputs.frontend }}" 2>/dev/null || echo "000")
echo " Attempt $i: HTTP $STATUS"
if [ "$STATUS" = "200" ]; then echo "Frontend OK."; exit 0; fi
sleep 15
done
echo "Frontend unhealthy after rollback."
exit 1
# ── Notifications ─────────────────────────────────────────────────────
notify:
name: Notify
runs-on: ubuntu-latest
needs: [rollback-production, rollback-preprod, smoke-tests]
if: always()
steps:
- name: Success
if: needs.smoke-tests.result == 'success'
run: |
curl -s -H "Content-Type: application/json" -d '{
"embeds": [{
"title": "↩️ Rollback Successful",
"color": 16776960,
"fields": [
{"name": "Environment", "value": "`${{ github.event.inputs.environment }}`", "inline": true},
{"name": "Strategy", "value": "`${{ github.event.inputs.strategy }}`", "inline": true},
{"name": "Version", "value": "`${{ github.event.inputs.version_tag || 'previous' }}`", "inline": true},
{"name": "By", "value": "${{ github.actor }}", "inline": true},
{"name": "Reason", "value": "${{ github.event.inputs.reason }}", "inline": false}
],
"footer": {"text": "Xpeditis CI/CD • Rollback"}
}]
}' ${{ secrets.DISCORD_WEBHOOK_URL }}
- name: Failure
if: needs.smoke-tests.result != 'success'
run: |
curl -s -H "Content-Type: application/json" -d '{
"content": "@here ROLLBACK FAILED — MANUAL INTERVENTION REQUIRED",
"embeds": [{
"title": "🔴 Rollback Failed",
"color": 15158332,
"fields": [
{"name": "Environment", "value": "`${{ github.event.inputs.environment }}`", "inline": true},
{"name": "Attempted", "value": "`${{ github.event.inputs.version_tag || 'previous' }}`", "inline": true},
{"name": "By", "value": "${{ github.actor }}", "inline": true},
{"name": "Reason", "value": "${{ github.event.inputs.reason }}", "inline": false}
],
"footer": {"text": "Xpeditis CI/CD • Rollback"}
}]
}' ${{ secrets.DISCORD_WEBHOOK_URL }}

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

54
.github/pull_request_template.md vendored Normal file
View File

@ -0,0 +1,54 @@
# Description
<!-- Provide a brief description of the changes in this PR -->
## Type of Change
- [ ] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
- [ ] Documentation update
- [ ] Code refactoring
- [ ] Performance improvement
- [ ] Test addition/update
## Related Issue
<!-- Link to the related issue (if applicable) -->
Closes #
## Changes Made
<!-- List the main changes made in this PR -->
-
-
-
## Testing
<!-- Describe the testing you've done -->
- [ ] Unit tests pass locally
- [ ] E2E tests pass locally
- [ ] Manual testing completed
- [ ] No new warnings
## Checklist
- [ ] My code follows the hexagonal architecture principles
- [ ] I have performed a self-review of my code
- [ ] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [ ] My changes generate no new warnings
- [ ] I have added tests that prove my fix is effective or that my feature works
- [ ] New and existing unit tests pass locally with my changes
- [ ] Any dependent changes have been merged and published
## Screenshots (if applicable)
<!-- Add screenshots to help explain your changes -->
## Additional Notes
<!-- Any additional information that reviewers should know -->

199
.github/workflows/ci.yml vendored Normal file
View File

@ -0,0 +1,199 @@
name: CI
on:
push:
branches: [main, dev]
pull_request:
branches: [main, dev]
jobs:
lint-and-format:
name: Lint & Format Check
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Run Prettier check
run: npm run format:check
- name: Lint backend
run: npm run backend:lint --workspace=apps/backend
- name: Lint frontend
run: npm run frontend:lint --workspace=apps/frontend
test-backend:
name: Test Backend
runs-on: ubuntu-latest
services:
postgres:
image: postgres:15-alpine
env:
POSTGRES_USER: xpeditis_test
POSTGRES_PASSWORD: xpeditis_test
POSTGRES_DB: xpeditis_test
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
ports:
- 5432:5432
redis:
image: redis:7-alpine
options: >-
--health-cmd "redis-cli ping"
--health-interval 10s
--health-timeout 5s
--health-retries 5
ports:
- 6379:6379
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Run backend unit tests
working-directory: apps/backend
env:
NODE_ENV: test
DATABASE_HOST: localhost
DATABASE_PORT: 5432
DATABASE_USER: xpeditis_test
DATABASE_PASSWORD: xpeditis_test
DATABASE_NAME: xpeditis_test
REDIS_HOST: localhost
REDIS_PORT: 6379
REDIS_PASSWORD: ''
JWT_SECRET: test-jwt-secret
run: npm run test
- name: Run backend E2E tests
working-directory: apps/backend
env:
NODE_ENV: test
DATABASE_HOST: localhost
DATABASE_PORT: 5432
DATABASE_USER: xpeditis_test
DATABASE_PASSWORD: xpeditis_test
DATABASE_NAME: xpeditis_test
REDIS_HOST: localhost
REDIS_PORT: 6379
REDIS_PASSWORD: ''
JWT_SECRET: test-jwt-secret
run: npm run test:e2e
- name: Upload backend coverage
uses: codecov/codecov-action@v3
with:
files: ./apps/backend/coverage/lcov.info
flags: backend
name: backend-coverage
test-frontend:
name: Test Frontend
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Run frontend tests
working-directory: apps/frontend
run: npm run test
- name: Upload frontend coverage
uses: codecov/codecov-action@v3
with:
files: ./apps/frontend/coverage/lcov.info
flags: frontend
name: frontend-coverage
build-backend:
name: Build Backend
runs-on: ubuntu-latest
needs: [lint-and-format, test-backend]
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Build backend
working-directory: apps/backend
run: npm run build
- name: Upload build artifacts
uses: actions/upload-artifact@v4
with:
name: backend-dist
path: apps/backend/dist
build-frontend:
name: Build Frontend
runs-on: ubuntu-latest
needs: [lint-and-format, test-frontend]
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Build frontend
working-directory: apps/frontend
env:
NEXT_PUBLIC_API_URL: ${{ secrets.NEXT_PUBLIC_API_URL || 'http://localhost:4000' }}
run: npm run build
- name: Upload build artifacts
uses: actions/upload-artifact@v4
with:
name: frontend-build
path: apps/frontend/.next

40
.github/workflows/security.yml vendored Normal file
View File

@ -0,0 +1,40 @@
name: Security Audit
on:
schedule:
- cron: '0 0 * * 1' # Run every Monday at midnight
push:
branches: [main]
pull_request:
branches: [main]
jobs:
audit:
name: npm audit
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Run npm audit
run: npm audit --audit-level=moderate
dependency-review:
name: Dependency Review
runs-on: ubuntu-latest
if: github.event_name == 'pull_request'
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Dependency Review
uses: actions/dependency-review-action@v4
with:
fail-on-severity: moderate

7
.gitignore vendored
View File

@ -12,9 +12,7 @@ coverage/
dist/ dist/
build/ build/
.next/ .next/
# Only ignore Next.js output directory, not all 'out' folders out/
/.next/out/
/apps/frontend/out/
# Environment variables # Environment variables
.env .env
@ -44,9 +42,6 @@ lerna-debug.log*
# Docker # Docker
docker-compose.override.yml docker-compose.override.yml
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.

277
AGENTS.md
View File

@ -1,277 +0,0 @@
# AGENTS.md
This file provides guidance to Codex (Codex.ai/code) when working with code in this repository.
## Project Overview
**Xpeditis** is a B2B SaaS maritime freight booking platform. Freight forwarders search and compare real-time shipping rates, book containers, and manage shipments. Monorepo with NestJS 10 backend (Hexagonal Architecture) and Next.js 14 frontend.
## Development Commands
All commands run from repo root unless noted otherwise.
```bash
# Infrastructure (PostgreSQL 15 + Redis 7 + MinIO)
docker-compose up -d
# Install all dependencies
npm run install:all
# Environment setup (required on first run)
cp apps/backend/.env.example apps/backend/.env
cp apps/frontend/.env.example apps/frontend/.env
# Database migrations (from apps/backend/)
cd apps/backend && npm run migration:run
# Development servers
npm run backend:dev # http://localhost:4000, Swagger: /api/docs
npm run frontend:dev # http://localhost:3000
```
### Testing
```bash
# Backend (from apps/backend/)
npm test # Unit tests (Jest)
npm test -- booking.entity.spec.ts # Single file
npm test -- --testNamePattern="should create" # Filter by test name
npm run test:cov # With coverage
npm run test:integration # Integration tests (needs DB/Redis, 30s timeout)
npm run test:e2e # E2E tests
# Frontend (from apps/frontend/)
npm test
npm run test:e2e # Playwright (chromium, firefox, webkit + mobile)
# From root
npm run backend:test
npm run frontend:test
```
Backend test config is in `apps/backend/package.json` (Jest). Integration test config: `apps/backend/jest-integration.json` (covers infrastructure layer, setup in `test/setup-integration.ts`). Frontend E2E config: `apps/frontend/playwright.config.ts`.
### Linting, Formatting & Type Checking
```bash
npm run backend:lint # ESLint backend
npm run frontend:lint # ESLint frontend
npm run format # Prettier (all files)
npm run format:check # Check formatting
# From apps/frontend/
npm run type-check # TypeScript checking (frontend only)
```
### Database Migrations
```bash
cd apps/backend
npm run migration:generate -- src/infrastructure/persistence/typeorm/migrations/MigrationName
npm run migration:run
npm run migration:revert
```
### Build
```bash
npm run backend:build # NestJS build with tsc-alias for path resolution
npm run frontend:build # Next.js production build (standalone output)
npm run clean # Remove all node_modules, dist, .next directories
```
## Local Infrastructure
Docker-compose defaults (no `.env` changes needed for local dev):
- **PostgreSQL**: `xpeditis:xpeditis_dev_password@localhost:5432/xpeditis_dev`
- **Redis**: password `xpeditis_redis_password`, port 6379
- **MinIO** (S3-compatible storage): `minioadmin:minioadmin`, API port 9000, console port 9001
Frontend env var: `NEXT_PUBLIC_API_URL` (defaults to `http://localhost:4000`) — configured in `next.config.js`.
## Architecture
### Hexagonal Architecture (Backend)
```
apps/backend/src/
├── domain/ # CORE - Pure TypeScript, NO framework imports
│ ├── entities/ # Booking, RateQuote, Carrier, Port, Container, Notification, Webhook,
│ │ # AuditLog, User, Organization, Subscription, License, CsvBooking,
│ │ # CsvRate, InvitationToken
│ ├── value-objects/ # Money, Email, BookingNumber, BookingStatus, PortCode, ContainerType,
│ │ # Volume, DateRange, Surcharge
│ ├── services/ # Pure domain services (csv-rate-price-calculator)
│ ├── ports/
│ │ ├── in/ # Use case interfaces with execute() method
│ │ └── out/ # Repository/SPI interfaces (token constants like BOOKING_REPOSITORY = 'BookingRepository')
│ └── exceptions/ # Domain-specific exceptions
├── application/ # Controllers, DTOs (class-validator), Guards, Decorators, Mappers
│ ├── [feature]/ # Feature modules: auth/, bookings/, csv-bookings, rates/, ports/,
│ │ # organizations/, users/, dashboard/, audit/, notifications/, webhooks/,
│ │ # gdpr/, admin/, subscriptions/
│ ├── controllers/ # REST controllers (also nested under feature folders)
│ ├── services/ # Application services: audit, notification, webhook,
│ │ # booking-automation, export, fuzzy-search, brute-force-protection
│ ├── gateways/ # WebSocket gateways (notifications.gateway.ts via Socket.IO)
│ ├── guards/ # JwtAuthGuard, RolesGuard, CustomThrottlerGuard
│ ├── decorators/ # @Public(), @Roles(), @CurrentUser()
│ ├── dto/ # Request/response DTOs with class-validator
│ ├── mappers/ # Domain ↔ DTO mappers
│ └── interceptors/ # PerformanceMonitoringInterceptor
└── infrastructure/ # TypeORM entities/repos/mappers, Redis cache, carrier APIs,
# MinIO/S3, email (MJML+Nodemailer), Stripe, Sentry,
# Pappers (French SIRET registry), PDF generation
```
**Critical dependency rules**:
- Domain layer: zero imports from NestJS, TypeORM, Redis, or any framework
- Dependencies flow inward only: Infrastructure → Application → Domain
- Path aliases: `@domain/*`, `@application/*`, `@infrastructure/*` (defined in `apps/backend/tsconfig.json`)
- Domain tests run without NestJS TestingModule
- Backend has strict TypeScript: `strict: true`, `strictNullChecks: true` (but `strictPropertyInitialization: false`)
- Env vars validated at startup via Joi schema in `app.module.ts` — required vars include DATABASE_*, REDIS_*, JWT_SECRET, SMTP_*
### NestJS Modules (app.module.ts)
Global guards: JwtAuthGuard (all routes protected by default), CustomThrottlerGuard.
Feature modules: Auth, Rates, Ports, Bookings, CsvBookings, Organizations, Users, Dashboard, Audit, Notifications, Webhooks, GDPR, Admin, Subscriptions.
Infrastructure modules: CacheModule, CarrierModule, SecurityModule, CsvRateModule, StripeModule, PdfModule, StorageModule, EmailModule.
Swagger plugin enabled in `nest-cli.json` — DTOs auto-documented. Logging via `nestjs-pino` (pino-pretty in dev).
### Frontend (Next.js 14 App Router)
```
apps/frontend/
├── app/ # App Router pages (root-level)
│ ├── dashboard/ # Protected routes (bookings, admin, settings, wiki, search)
│ ├── carrier/ # Carrier portal (magic link auth — accept/reject/documents)
│ ├── booking/ # Booking confirmation/rejection flows
│ └── [auth pages] # login, register, forgot-password, verify-email
└── src/
├── app/ # Additional app pages (e.g. rates/csv-search)
├── components/ # React components (ui/, layout/, bookings/, admin/, rate-search/, organization/)
├── hooks/ # useBookings, useNotifications, useCsvRateSearch, useCompanies, useFilterOptions
├── lib/
│ ├── api/ # Fetch-based API client with auto token refresh (client.ts + per-module files)
│ ├── context/ # Auth context, cookie context
│ ├── providers/ # QueryProvider (TanStack Query / React Query)
│ └── fonts.ts # Manrope (headings) + Montserrat (body)
├── types/ # TypeScript type definitions
├── utils/ # Export utilities (Excel, PDF)
└── legacy-pages/ # Archived page components (BookingsManagement, CarrierManagement, CarrierMonitoring)
```
Path aliases: `@/*` → `./src/*`, `@/components/*`, `@/lib/*`, `@/app/*` → `./app/*`, `@/types/*`, `@/hooks/*`, `@/utils/*`
**Note**: Frontend tsconfig has `strict: false`, `noImplicitAny: false`, `strictNullChecks: false` (unlike backend which is strict). Uses TanStack Query (React Query) for server state — wrap new data fetching in hooks, not bare `fetch` calls.
### Brand Design
Colors: Navy `#10183A` (primary), Turquoise `#34CCCD` (accent), Green `#067224` (success), Gray `#F2F2F2`.
Fonts: Manrope (headings), Montserrat (body).
Landing page is in French.
## Key Patterns
### Entity Pattern (Domain)
Private constructor + static `create()` factory. Immutable — mutation methods return new instances. Some entities also have `fromPersistence()` for reconstitution and `toObject()` for serialization.
```typescript
export class Booking {
private readonly props: BookingProps;
static create(props: Omit<BookingProps, 'bookingNumber' | 'status'>): Booking { ... }
updateStatus(newStatus: BookingStatus): Booking { // Returns new instance
return new Booking({ ...this.props, status: newStatus });
}
}
```
### Value Object Pattern
Immutable, self-validating via static `create()`. E.g. `Money` supports USD, EUR, GBP, CNY, JPY with arithmetic and formatting methods.
### Repository Pattern
- Interface in `domain/ports/out/` with token constant (e.g. `BOOKING_REPOSITORY = 'BookingRepository'`)
- Implementation in `infrastructure/persistence/typeorm/repositories/`
- ORM entities: `infrastructure/persistence/typeorm/entities/*.orm-entity.ts`
- Separate mapper classes (`infrastructure/persistence/typeorm/mappers/`) with static `toOrm()`, `toDomain()`, `toDomainMany()` methods
### Frontend API Client
Custom Fetch wrapper in `src/lib/api/client.ts` — exports `get()`, `post()`, `patch()`, `del()`, `upload()`, `download()`. Auto-refreshes JWT on 401. Tokens stored in localStorage **and synced to cookies** (`accessToken` cookie) so Next.js middleware can read them server-side. Per-module files (auth.ts, bookings.ts, rates.ts, etc.) import from client.
### Route Protection (Middleware)
`apps/frontend/middleware.ts` checks the `accessToken` cookie to protect routes. Public paths are defined in two lists:
- `exactPublicPaths`: exact matches (e.g. `/`)
- `prefixPublicPaths`: prefix matches including sub-paths (e.g. `/login`, `/carrier`, `/about`, etc.)
All other routes redirect to `/login?redirect=<pathname>` when the cookie is absent.
### Application Decorators
- `@Public()` — skip JWT auth
- `@Roles()` — role-based access control
- `@CurrentUser()` — inject authenticated user
### API Key Authentication
A second auth mechanism alongside JWT. `ApiKey` domain entity (`domain/entities/api-key.entity.ts`) — keys are hashed with Argon2. `ApiKeyGuard` in `application/guards/` checks the `x-api-key` header. Routes can accept either JWT or API key; see `admin.controller.ts` for examples.
### WebSocket (Real-time Notifications)
Socket.IO gateway at `application/gateways/notifications.gateway.ts`. Clients connect to `/` namespace with a JWT bearer token in the handshake auth. Server emits `notification` events. The frontend `useNotifications` hook handles subscriptions.
### Carrier Connectors
Five carrier connectors (Maersk, MSC, CMA CGM, Hapag-Lloyd, ONE) extending `base-carrier.connector.ts`, each with request/response mappers. Circuit breaker via `opossum` (5s timeout).
### Caching
Redis with 15-min TTL for rate quotes. Key format: `rate:{origin}:{destination}:{containerType}`.
## Business Rules
- Booking number format: `WCM-YYYY-XXXXXX`
- Booking status flow: draft → confirmed → shipped → delivered
- Rate quotes expire after 15 minutes
- Multi-currency: USD, EUR, GBP, CNY, JPY
- RBAC Roles: ADMIN, MANAGER, USER, VIEWER, CARRIER
- JWT: access token 15min, refresh token 7d
- Password hashing: Argon2
- OAuth providers: Google, Microsoft (configured via passport strategies)
- Organizations can be validated via Pappers API (French SIRET/company registry) at `infrastructure/external/pappers-siret.adapter.ts`
### Carrier Portal Workflow
1. Admin creates CSV booking → assigns carrier
2. Email with magic link sent (1-hour expiry)
3. Carrier auto-login → accept/reject booking
4. Activity logged in `carrier_activities` table (via `CarrierProfile` + `CarrierActivity` ORM entities)
## Common Pitfalls
- Never import NestJS/TypeORM in domain layer
- Never use `any` type in backend (strict mode enabled)
- Never modify applied migrations — create new ones
- Always validate DTOs with `class-validator` decorators
- Always create separate mappers for Domain ↔ ORM conversions
- ORM entity files must match pattern `*.orm-entity.{ts,js}` (auto-discovered by data-source)
- Migration files must be in `infrastructure/persistence/typeorm/migrations/`
- Database synchronize is hard-coded to `false` — always use migrations
## Adding a New Feature
1. **Domain Entity** → `domain/entities/*.entity.ts` (pure TS, unit tests)
2. **Value Objects** → `domain/value-objects/*.vo.ts` (immutable)
3. **In Port (Use Case)** → `domain/ports/in/*.use-case.ts` (interface with `execute()`)
4. **Out Port (Repository)** → `domain/ports/out/*.repository.ts` (with token constant)
5. **ORM Entity** → `infrastructure/persistence/typeorm/entities/*.orm-entity.ts`
6. **Migration** → `npm run migration:generate -- src/infrastructure/persistence/typeorm/migrations/MigrationName`
7. **Repository Impl** → `infrastructure/persistence/typeorm/repositories/`
8. **Mapper** → `infrastructure/persistence/typeorm/mappers/` (static toOrm/toDomain/toDomainMany)
9. **DTOs** → `application/dto/` (with class-validator decorators)
10. **Controller** → `application/controllers/` (with Swagger decorators)
11. **Module** → Register repository + use-case providers, import in `app.module.ts`
## Documentation
- API Docs: http://localhost:4000/api/docs (Swagger, when running)
- Setup guide: `docs/installation/START-HERE.md`
- Carrier Portal API: `apps/backend/docs/CARRIER_PORTAL_API.md`
- Full docs index: `docs/README.md`
- Development roadmap: `TODO.md`
- Infrastructure configs (CI/CD, Docker): `infra/`

853
CLAUDE.md
View File

@ -4,274 +4,641 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
## Project Overview ## Project Overview
**Xpeditis** is a B2B SaaS maritime freight booking platform. Freight forwarders search and compare real-time shipping rates, book containers, and manage shipments. Monorepo with NestJS 10 backend (Hexagonal Architecture) and Next.js 14 frontend. **Xpeditis** is a B2B SaaS maritime freight booking and management platform (maritime equivalent of WebCargo). The platform allows freight forwarders to search and compare real-time shipping rates, book containers online, and manage shipments from a centralized dashboard.
## Development Commands **MVP Goal**: Deliver a minimal but professional product capable of handling 50-100 bookings/month for 10-20 early adopter freight forwarders within 4-6 months.
All commands run from repo root unless noted otherwise.
```bash
# Infrastructure (PostgreSQL 15 + Redis 7 + MinIO)
docker-compose up -d
# Install all dependencies
npm run install:all
# Environment setup (required on first run)
cp apps/backend/.env.example apps/backend/.env
cp apps/frontend/.env.example apps/frontend/.env
# Database migrations (from apps/backend/)
cd apps/backend && npm run migration:run
# Development servers
npm run backend:dev # http://localhost:4000, Swagger: /api/docs
npm run frontend:dev # http://localhost:3000
```
### Testing
```bash
# Backend (from apps/backend/)
npm test # Unit tests (Jest)
npm test -- booking.entity.spec.ts # Single file
npm test -- --testNamePattern="should create" # Filter by test name
npm run test:cov # With coverage
npm run test:integration # Integration tests (needs DB/Redis, 30s timeout)
npm run test:e2e # E2E tests
# Frontend (from apps/frontend/)
npm test
npm run test:e2e # Playwright (chromium, firefox, webkit + mobile)
# From root
npm run backend:test
npm run frontend:test
```
Backend test config is in `apps/backend/package.json` (Jest). Integration test config: `apps/backend/jest-integration.json` (covers infrastructure layer, setup in `test/setup-integration.ts`). Frontend E2E config: `apps/frontend/playwright.config.ts`.
### Linting, Formatting & Type Checking
```bash
npm run backend:lint # ESLint backend
npm run frontend:lint # ESLint frontend
npm run format # Prettier (all files)
npm run format:check # Check formatting
# From apps/frontend/
npm run type-check # TypeScript checking (frontend only)
```
### Database Migrations
```bash
cd apps/backend
npm run migration:generate -- src/infrastructure/persistence/typeorm/migrations/MigrationName
npm run migration:run
npm run migration:revert
```
### Build
```bash
npm run backend:build # NestJS build with tsc-alias for path resolution
npm run frontend:build # Next.js production build (standalone output)
npm run clean # Remove all node_modules, dist, .next directories
```
## Local Infrastructure
Docker-compose defaults (no `.env` changes needed for local dev):
- **PostgreSQL**: `xpeditis:xpeditis_dev_password@localhost:5432/xpeditis_dev`
- **Redis**: password `xpeditis_redis_password`, port 6379
- **MinIO** (S3-compatible storage): `minioadmin:minioadmin`, API port 9000, console port 9001
Frontend env var: `NEXT_PUBLIC_API_URL` (defaults to `http://localhost:4000`) — configured in `next.config.js`.
## Architecture ## Architecture
### Hexagonal Architecture (Backend) ### Hexagonal Architecture (Ports & Adapters)
The codebase follows hexagonal architecture principles with clear separation of concerns:
- **API Layer (External Adapters)**: Controllers, validation, auth middleware
- **Application Layer (Ports)**: Use cases (searchRates, createBooking, confirmBooking)
- **Domain Layer (Core)**: Entities (Booking, RateQuote, Carrier, Organization, User)
- **Infrastructure Adapters**: DB repositories, carrier connectors, email services, storage, Redis cache
### Tech Stack
- **Frontend**: Next.js (TypeScript) with SSR/ISR
- **Backend**: Node.js API-first (OpenAPI spec)
- **Database**: PostgreSQL (TypeORM or Prisma)
- **Cache**: Redis (15 min TTL for spot rates)
- **Storage**: S3-compatible (AWS S3 or MinIO)
- **Auth**: OAuth2 + JWT (access 15min, refresh 7 days)
### Project Structure (Planned Monorepo)
``` ```
apps/backend/src/ apps/
├── domain/ # CORE - Pure TypeScript, NO framework imports frontend/ # Next.js application
│ ├── entities/ # Booking, RateQuote, Carrier, Port, Container, Notification, Webhook, backend/ # Node.js API
│ │ # AuditLog, User, Organization, Subscription, License, CsvBooking, libs/
│ │ # CsvRate, InvitationToken domain/ # Core domain entities and business logic
│ ├── value-objects/ # Money, Email, BookingNumber, BookingStatus, PortCode, ContainerType, infra/ # Infrastructure configuration
│ │ # Volume, DateRange, Surcharge
│ ├── services/ # Pure domain services (csv-rate-price-calculator)
│ ├── ports/
│ │ ├── in/ # Use case interfaces with execute() method
│ │ └── out/ # Repository/SPI interfaces (token constants like BOOKING_REPOSITORY = 'BookingRepository')
│ └── exceptions/ # Domain-specific exceptions
├── application/ # Controllers, DTOs (class-validator), Guards, Decorators, Mappers
│ ├── [feature]/ # Feature modules: auth/, bookings/, csv-bookings, rates/, ports/,
│ │ # organizations/, users/, dashboard/, audit/, notifications/, webhooks/,
│ │ # gdpr/, admin/, subscriptions/
│ ├── controllers/ # REST controllers (also nested under feature folders)
│ ├── services/ # Application services: audit, notification, webhook,
│ │ # booking-automation, export, fuzzy-search, brute-force-protection
│ ├── gateways/ # WebSocket gateways (notifications.gateway.ts via Socket.IO)
│ ├── guards/ # JwtAuthGuard, RolesGuard, CustomThrottlerGuard
│ ├── decorators/ # @Public(), @Roles(), @CurrentUser()
│ ├── dto/ # Request/response DTOs with class-validator
│ ├── mappers/ # Domain ↔ DTO mappers
│ └── interceptors/ # PerformanceMonitoringInterceptor
└── infrastructure/ # TypeORM entities/repos/mappers, Redis cache, carrier APIs,
# MinIO/S3, email (MJML+Nodemailer), Stripe, Sentry,
# Pappers (French SIRET registry), PDF generation
``` ```
**Critical dependency rules**: ## Core Domain Entities
- Domain layer: zero imports from NestJS, TypeORM, Redis, or any framework
- Dependencies flow inward only: Infrastructure → Application → Domain
- Path aliases: `@domain/*`, `@application/*`, `@infrastructure/*` (defined in `apps/backend/tsconfig.json`)
- Domain tests run without NestJS TestingModule
- Backend has strict TypeScript: `strict: true`, `strictNullChecks: true` (but `strictPropertyInitialization: false`)
- Env vars validated at startup via Joi schema in `app.module.ts` — required vars include DATABASE_*, REDIS_*, JWT_SECRET, SMTP_*
### NestJS Modules (app.module.ts) - **Organization**: `{ id, name, type, scac, address, logo_url, documents[] }`
- **User**: `{ id, org_id, role, email, pwd_hash, totp_secret }`
- **RateQuote**: `{ id, origin, destination, carrier_id, price_currency, price_value, surcharges[], etd, eta, transit_days, route, availability }`
- **Booking**: `{ id, booking_number, user_id, org_id, rate_quote_id, shipper, consignee, containers[], status, created_at, updated_at }`
- **Container**: `{ id, booking_id, type, container_number, vgm, temp, seal_number }`
Global guards: JwtAuthGuard (all routes protected by default), CustomThrottlerGuard. ## Key API Endpoints
Feature modules: Auth, Rates, Ports, Bookings, CsvBookings, Organizations, Users, Dashboard, Audit, Notifications, Webhooks, GDPR, Admin, Subscriptions. ### Rate Search
- `POST /api/v1/rates/search`: Search shipping rates with origin/destination/container specs
- Response includes carrier, pricing, surcharges, ETD/ETA, transit time, route, CO2 emissions
- Cache TTL: 15 minutes (Redis)
- Timeout: 5 seconds per carrier API
Infrastructure modules: CacheModule, CarrierModule, SecurityModule, CsvRateModule, StripeModule, PdfModule, StorageModule, EmailModule. ### Booking Management
- `POST /api/v1/bookings`: Create booking (multi-step workflow)
- `GET /api/v1/bookings/:id`: Get booking details
- Booking number format: `WCM-YYYY-XXXXXX` (6 alphanumeric chars)
Swagger plugin enabled in `nest-cli.json` — DTOs auto-documented. Logging via `nestjs-pino` (pino-pretty in dev). ### Authentication
- `/auth/register`: Email + password (≥12 chars)
- `/auth/login`: JWT-based login + OAuth2 (Google Workspace, Microsoft 365)
- `/auth/logout`: Session termination
- `/auth/refresh`: Token refresh
### Frontend (Next.js 14 App Router) ## Critical Integration Points
### Carrier Connectors (MVP Priority)
Implement connectors for 3-5 carriers using Strategy pattern:
- Maersk (required)
- MSC
- CMA CGM
- Hapag-Lloyd
- ONE
Each connector must:
- Normalize data to internal schema
- Implement retry logic and circuit breakers
- Respect rate limiting
- Log detailed metrics
- Respond within 5s or fallback gracefully
### Cache Strategy
- Preload top 100 trade lanes on startup
- 15-minute TTL for spot rates
- Cache hit target: >90% for common routes
## Security Requirements
- TLS 1.2+ for all traffic
- Password hashing: Argon2id or bcrypt (≥12 rounds)
- OWASP Top 10 protection (rate limiting, input validation, CSP headers)
- Audit logs for sensitive actions
- S3 ACLs for compliance documents
- Optional TOTP 2FA
## RBAC Roles
- **Admin**: Full system access
- **Manager**: Manage bookings and users within organization
- **User**: Create and view bookings
- **Viewer**: Read-only access
## Performance Targets
- Rate search: <2s for 90% of requests (with cache)
- Dashboard load: <1s for up to 5k bookings
- Carrier API timeout: 5s
- Email confirmation: Send within 3s of booking
- Session auto-logout: 2h inactivity
## Development Workflow
### Testing Requirements
- Unit tests: Domain logic and use cases
- Integration tests: Carrier connectors and DB repositories
- E2E tests: Complete booking workflow (happy path + 3 common error scenarios)
### Email & Notifications
- Templates: MJML format
- Booking confirmation email on successful booking
- Push notifications (if mobile app)
### Document Generation
- PDF booking confirmations
- Excel/PDF export for rate search results
## Data Requirements
- Port autocomplete: 10k+ ports (IATA/UN LOCODE)
- Multi-currency support: USD, EUR
- Hazmat support: IMO class validation
- Container types: 20', 40', 40'HC, etc.
## MVP Roadmap (4-6 months)
**Sprint 0 (2 weeks)**: Repo setup, infrastructure, OpenAPI skeleton, ports/adapters scaffolding
**Phase 1 (6-8 weeks)**: Rate search API + UI, Redis cache, 1-2 carrier connectors, basic auth
**Phase 2 (6-8 weeks)**: Booking workflow, email templates, dashboard, RBAC, organizations
**Phase 3 (4-6 weeks)**: Additional carrier integrations, exports, E2E tests, monitoring, security hardening
**Go-to-market (2 weeks)**: Early adopter onboarding, support, KPI tracking
## Important Constraints
- Pre-fetch top 100 trade lanes on application startup
- All carrier API calls must have circuit breakers
- Booking workflow: ≤4 steps maximum
- Session timeout: 2 hours of inactivity
- Rate search pagination: >20 results
- SLA: 95% of rate searches <1s (including cache)
## Business KPIs to Track
- Active users (DAU/MAU)
- Bookings per month
- Search-to-booking conversion rate (target ≥3%)
- Average time to create booking
- Carrier API error rates
- Cache hit ratio
- Customer retention at 3 months
---
# Backend Hexagonal Architecture Guidelines (Node.js/TypeScript)
## Phase 1: Business Domain Analysis
### Domain Identification
- **Primary business domain**: Maritime freight booking platform
- **Core entities**: Organization, User, RateQuote, Booking, Container, Carrier
- **Business rules**:
- Rate quotes expire after 15 minutes (Redis cache)
- Bookings must validate container availability in real-time
- Multi-step booking workflow (≤4 steps)
- RBAC enforcement for all operations
- Carrier API timeout: 5 seconds with fallback
- **Use cases**: searchRates, createBooking, confirmBooking, manageOrganizations, authenticateUser
### Integration Requirements
- **External actors**: Freight forwarders (users), carriers (API integrations)
- **External services**: PostgreSQL, Redis, S3, Email (MJML templates), Carrier APIs (Maersk, MSC, CMA CGM, etc.)
- **Input interfaces**: REST API (OpenAPI), OAuth2 callbacks
- **Output interfaces**: Database persistence, email notifications, carrier API calls, S3 document storage
## Phase 2: Architectural Design
### Module Structure
``` ```
apps/frontend/ backend/
├── app/ # App Router pages (root-level) ├── src/
│ ├── dashboard/ # Protected routes (bookings, admin, settings, wiki, search) │ ├── domain/ # Pure business logic (NO external dependencies)
│ ├── carrier/ # Carrier portal (magic link auth — accept/reject/documents) │ │ ├── entities/
│ ├── booking/ # Booking confirmation/rejection flows │ │ │ ├── organization.entity.ts
│ └── [auth pages] # login, register, forgot-password, verify-email │ │ │ ├── user.entity.ts
└── src/ │ │ │ ├── rate-quote.entity.ts
├── app/ # Additional app pages (e.g. rates/csv-search) │ │ │ ├── booking.entity.ts
├── components/ # React components (ui/, layout/, bookings/, admin/, rate-search/, organization/) │ │ │ ├── container.entity.ts
├── hooks/ # useBookings, useNotifications, useCsvRateSearch, useCompanies, useFilterOptions │ │ │ ├── carrier.entity.ts
├── lib/ │ │ │ └── index.ts
│ ├── api/ # Fetch-based API client with auto token refresh (client.ts + per-module files) │ │ ├── value-objects/
│ ├── context/ # Auth context, cookie context │ │ │ ├── email.vo.ts
│ ├── providers/ # QueryProvider (TanStack Query / React Query) │ │ │ ├── booking-number.vo.ts
│ └── fonts.ts # Manrope (headings) + Montserrat (body) │ │ │ ├── port-code.vo.ts
├── types/ # TypeScript type definitions │ │ │ └── index.ts
├── utils/ # Export utilities (Excel, PDF) │ │ ├── services/
└── legacy-pages/ # Archived page components (BookingsManagement, CarrierManagement, CarrierMonitoring) │ │ │ ├── rate-search.service.ts
│ │ │ ├── booking.service.ts
│ │ │ ├── user.service.ts
│ │ │ └── index.ts
│ │ ├── ports/
│ │ │ ├── in/ # API Ports (use cases)
│ │ │ │ ├── search-rates.port.ts
│ │ │ │ ├── create-booking.port.ts
│ │ │ │ ├── manage-user.port.ts
│ │ │ │ └── index.ts
│ │ │ └── out/ # SPI Ports (infrastructure interfaces)
│ │ │ ├── rate-quote.repository.ts
│ │ │ ├── booking.repository.ts
│ │ │ ├── user.repository.ts
│ │ │ ├── carrier-connector.port.ts
│ │ │ ├── cache.port.ts
│ │ │ ├── email.port.ts
│ │ │ └── index.ts
│ │ └── exceptions/
│ │ ├── booking-not-found.exception.ts
│ │ ├── invalid-rate-quote.exception.ts
│ │ ├── carrier-timeout.exception.ts
│ │ └── index.ts
│ │
│ ├── application/ # Controllers and DTOs (depends ONLY on domain)
│ │ ├── controllers/
│ │ │ ├── rates.controller.ts
│ │ │ ├── bookings.controller.ts
│ │ │ ├── auth.controller.ts
│ │ │ └── index.ts
│ │ ├── dto/
│ │ │ ├── rate-search.dto.ts
│ │ │ ├── create-booking.dto.ts
│ │ │ ├── booking-response.dto.ts
│ │ │ └── index.ts
│ │ ├── mappers/
│ │ │ ├── rate-quote.mapper.ts
│ │ │ ├── booking.mapper.ts
│ │ │ └── index.ts
│ │ └── config/
│ │ ├── validation.config.ts
│ │ └── swagger.config.ts
│ │
│ ├── infrastructure/ # All external integrations (depends ONLY on domain)
│ │ ├── persistence/
│ │ │ ├── typeorm/
│ │ │ │ ├── entities/
│ │ │ │ │ ├── organization.orm-entity.ts
│ │ │ │ │ ├── user.orm-entity.ts
│ │ │ │ │ ├── booking.orm-entity.ts
│ │ │ │ │ └── index.ts
│ │ │ │ ├── repositories/
│ │ │ │ │ ├── typeorm-booking.repository.ts
│ │ │ │ │ ├── typeorm-user.repository.ts
│ │ │ │ │ └── index.ts
│ │ │ │ └── mappers/
│ │ │ │ ├── booking-orm.mapper.ts
│ │ │ │ └── index.ts
│ │ │ └── database.module.ts
│ │ ├── cache/
│ │ │ ├── redis-cache.adapter.ts
│ │ │ └── cache.module.ts
│ │ ├── carriers/
│ │ │ ├── maersk/
│ │ │ │ ├── maersk.connector.ts
│ │ │ │ ├── maersk.mapper.ts
│ │ │ │ └── maersk.types.ts
│ │ │ ├── msc/
│ │ │ ├── cma-cgm/
│ │ │ └── carrier.module.ts
│ │ ├── email/
│ │ │ ├── mjml-email.adapter.ts
│ │ │ └── email.module.ts
│ │ ├── storage/
│ │ │ ├── s3-storage.adapter.ts
│ │ │ └── storage.module.ts
│ │ └── config/
│ │ ├── database.config.ts
│ │ ├── redis.config.ts
│ │ └── jwt.config.ts
│ │
│ ├── main.ts # Application entry point
│ └── app.module.ts # Root module (NestJS)
│
├── test/
│ ├── unit/
│ ├── integration/
│ └── e2e/
│
├── package.json
├── tsconfig.json
├── jest.config.js
└── .env.example
``` ```
Path aliases: `@/*` → `./src/*`, `@/components/*`, `@/lib/*`, `@/app/*` → `./app/*`, `@/types/*`, `@/hooks/*`, `@/utils/*` ### Port Definitions
**Note**: Frontend tsconfig has `strict: false`, `noImplicitAny: false`, `strictNullChecks: false` (unlike backend which is strict). Uses TanStack Query (React Query) for server state — wrap new data fetching in hooks, not bare `fetch` calls. **API Ports (domain/ports/in/)** - Exposed by domain:
- `SearchRatesPort`: Interface for searching shipping rates
- `CreateBookingPort`: Interface for creating bookings
- `ManageUserPort`: Interface for user management
- `AuthenticatePort`: Interface for authentication flows
### Brand Design **SPI Ports (domain/ports/out/)** - Required by domain:
- `RateQuoteRepository`: Persistence interface for rate quotes
- `BookingRepository`: Persistence interface for bookings
- `UserRepository`: Persistence interface for users
- `CarrierConnectorPort`: Interface for carrier API integrations
- `CachePort`: Interface for caching (Redis)
- `EmailPort`: Interface for sending emails
- `StoragePort`: Interface for S3 document storage
Colors: Navy `#10183A` (primary), Turquoise `#34CCCD` (accent), Green `#067224` (success), Gray `#F2F2F2`. ### Adapter Design
Fonts: Manrope (headings), Montserrat (body).
Landing page is in French.
## Key Patterns **Driving Adapters (Input)**:
- REST controllers (NestJS @Controller)
- GraphQL resolvers (future)
- CLI commands (future)
### Entity Pattern (Domain) **Driven Adapters (Output)**:
Private constructor + static `create()` factory. Immutable — mutation methods return new instances. Some entities also have `fromPersistence()` for reconstitution and `toObject()` for serialization. - TypeORM repositories implementing repository ports
- Carrier connectors (Maersk, MSC, etc.) implementing CarrierConnectorPort
- Redis adapter implementing CachePort
- MJML email adapter implementing EmailPort
- S3 adapter implementing StoragePort
## Phase 3: Layer Architecture
### Domain Layer Rules
- **Zero external dependencies**: No NestJS, TypeORM, Redis, etc.
- **Pure TypeScript**: Only type definitions and business logic
- **Self-contained**: Must compile independently
- **Test without framework**: Jest only, no NestJS testing utilities
### Application Layer Rules
- **Depends only on domain**: Import from `@domain/*` only
- **Exposes REST API**: Controllers validate input and delegate to domain services
- **DTO mapping**: Transform external DTOs to domain entities
- **No business logic**: Controllers are thin, logic stays in domain
### Infrastructure Layer Rules
- **Implements SPI ports**: All repository and service interfaces
- **Framework dependencies**: TypeORM, Redis, AWS SDK, etc.
- **Maps external data**: ORM entities ↔ Domain entities
- **Circuit breakers**: Carrier connectors must implement retry/fallback logic
## Phase 4: Technical Validation
### Dependency Management
**domain/package.json** (if separate):
```json
{
"dependencies": {}, // NO runtime dependencies
"devDependencies": {
"typescript": "^5.3.0",
"@types/node": "^20.0.0"
}
}
```
**Root package.json**:
```json
{
"dependencies": {
"@nestjs/common": "^10.0.0",
"@nestjs/core": "^10.0.0",
"@nestjs/swagger": "^7.0.0",
"typeorm": "^0.3.17",
"pg": "^8.11.0",
"redis": "^4.6.0",
"class-validator": "^0.14.0",
"class-transformer": "^0.5.1"
}
}
```
### tsconfig.json Path Aliases
```json
{
"compilerOptions": {
"strict": true,
"baseUrl": "./src",
"paths": {
"@domain/*": ["domain/*"],
"@application/*": ["application/*"],
"@infrastructure/*": ["infrastructure/*"]
}
}
}
```
### Design Patterns
- **Domain-Driven Design**: Entities, Value Objects, Aggregates
- **SOLID Principles**: Especially DIP (Dependency Inversion)
- **Repository Pattern**: Abstraction over data persistence
- **Strategy Pattern**: Carrier connectors (Maersk, MSC, etc.)
- **Circuit Breaker**: For carrier API calls (5s timeout)
### NestJS Configuration
- Use `@Injectable()` in application and infrastructure layers ONLY
- Domain services registered manually via `@Module` providers
- Avoid `@Component` or decorators in domain layer
- Use interceptors for transactions (`@Transactional`)
## Phase 5: Testing Strategy
### Unit Tests (Domain)
```typescript ```typescript
export class Booking { // domain/services/booking.service.spec.ts
private readonly props: BookingProps; describe('BookingService', () => {
static create(props: Omit<BookingProps, 'bookingNumber' | 'status'>): Booking { ... } it('should create booking with valid rate quote', () => {
updateStatus(newStatus: BookingStatus): Booking { // Returns new instance // Test without any framework dependencies
return new Booking({ ...this.props, status: newStatus }); const service = new BookingService(mockRepository);
const result = service.createBooking(validInput);
expect(result.bookingNumber).toMatch(/^WCM-\d{4}-[A-Z0-9]{6}$/);
});
});
```
### Integration Tests (Infrastructure)
```typescript
// infrastructure/persistence/typeorm/repositories/booking.repository.spec.ts
describe('TypeOrmBookingRepository', () => {
let repository: TypeOrmBookingRepository;
beforeAll(async () => {
// Use testcontainers for real PostgreSQL
await setupTestDatabase();
});
it('should persist booking to database', async () => {
const booking = createTestBooking();
await repository.save(booking);
const found = await repository.findById(booking.id);
expect(found).toBeDefined();
});
});
```
### E2E Tests (Full API)
```typescript
// test/e2e/booking-workflow.e2e-spec.ts
describe('Booking Workflow (E2E)', () => {
it('should complete full booking flow', async () => {
// 1. Search rates
const ratesResponse = await request(app.getHttpServer())
.post('/api/v1/rates/search')
.send(searchPayload);
// 2. Create booking
const bookingResponse = await request(app.getHttpServer())
.post('/api/v1/bookings')
.send(bookingPayload);
// 3. Verify booking confirmation email sent
expect(bookingResponse.status).toBe(201);
expect(emailSpy).toHaveBeenCalled();
});
});
```
### Test Coverage Targets
- **Domain**: 90%+ coverage
- **Application**: 80%+ coverage
- **Infrastructure**: 70%+ coverage (focus on critical paths)
## Phase 6: Naming Conventions
### TypeScript Conventions
- **Interfaces**: `UserRepository` (no "I" prefix)
- **Ports**: `SearchRatesPort`, `CarrierConnectorPort`
- **Adapters**: `TypeOrmBookingRepository`, `MaerskConnectorAdapter`
- **Services**: `BookingService`, `RateSearchService`
- **Entities**: `Booking`, `RateQuote`, `Organization`
- **Value Objects**: `BookingNumber`, `Email`, `PortCode`
- **DTOs**: `CreateBookingDto`, `RateSearchRequestDto`
### File Naming
- **Entities**: `booking.entity.ts`
- **Interfaces**: `booking.repository.ts` (for ports)
- **Implementations**: `typeorm-booking.repository.ts`
- **Tests**: `booking.service.spec.ts`
- **Barrel exports**: `index.ts`
### Import Order
```typescript
// 1. External dependencies
import { Injectable } from '@nestjs/common';
// 2. Domain imports
import { Booking } from '@domain/entities';
import { BookingRepository } from '@domain/ports/out';
// 3. Relative imports
import { BookingOrmEntity } from './entities/booking.orm-entity';
```
## Phase 7: Validation Checklist
### Critical Questions
- ✅ **Domain isolation**: No `import` of NestJS/TypeORM in domain layer?
- ✅ **Dependency direction**: All dependencies point inward toward domain?
- ✅ **Framework-free testing**: Can domain be tested without NestJS TestingModule?
- ✅ **Database agnostic**: Could we switch from TypeORM to Prisma without touching domain?
- ✅ **Interface flexibility**: Could we add GraphQL without changing domain?
- ✅ **Compilation independence**: Does domain compile without other layers?
### Data Flow Validation
- **Inbound**: HTTP Request → Controller → DTO → Mapper → Domain Entity → Use Case
- **Outbound**: Use Case → Repository Port → Adapter → ORM Entity → Database
- **Carrier Integration**: Use Case → CarrierConnectorPort → MaerskAdapter → Maersk API
## Phase 8: Pre-Coding Checklist
### Setup Tasks
- ✅ Node.js v20+ installed
- ✅ TypeScript with `strict: true`
- ✅ NestJS CLI installed globally
- ✅ ESLint + Prettier configured
- ✅ Husky pre-commit hooks
- ✅ `.env.example` with all required variables
### Architecture Validation
- ✅ PRD reviewed and understood
- ✅ Domain entities mapped to database schema
- ✅ All ports (in/out) identified
- ✅ Carrier connector strategy defined
- ✅ Cache strategy documented (Redis, 15min TTL)
- ✅ Test strategy approved
### Development Order
1. **Domain layer**: Entities → Value Objects → Services → Ports
2. **Infrastructure layer**: TypeORM entities → Repositories → Carrier connectors → Cache/Email adapters
3. **Application layer**: DTOs → Mappers → Controllers → Validation pipes
4. **Bootstrap**: main.ts → app.module.ts → DI configuration
5. **Tests**: Unit (domain) → Integration (repos) → E2E (API)
## Common Pitfalls to Avoid
⚠️ **Critical Mistakes**:
- Circular imports (use barrel exports `index.ts`)
- Framework decorators in domain (`@Column`, `@Injectable`)
- Business logic in controllers or adapters
- Using `any` type (always explicit types)
- Promises not awaited (use `async/await` properly)
- Carrier APIs without circuit breakers
- Missing Redis cache for rate queries
- Not validating DTOs with `class-validator`
## Recommended Tools
- **Validation**: `class-validator` + `class-transformer`
- **Mapping**: Manual mappers (avoid heavy libraries)
- **API Docs**: `@nestjs/swagger` (OpenAPI)
- **Logging**: Winston or Pino
- **Config**: `@nestjs/config` with Joi validation
- **Testing**: Jest + Supertest + @faker-js/faker
- **Circuit Breaker**: `opossum` library
- **Redis**: `ioredis`
- **Email**: `mjml` + `nodemailer`
## Example: Complete Feature Flow
### Scenario: Search Rates for Rotterdam → Shanghai
```typescript
// 1. Controller (application layer)
@Controller('api/v1/rates')
export class RatesController {
constructor(private readonly searchRatesUseCase: SearchRatesPort) {}
@Post('search')
async searchRates(@Body() dto: RateSearchDto) {
const domainInput = RateSearchMapper.toDomain(dto);
const quotes = await this.searchRatesUseCase.execute(domainInput);
return RateSearchMapper.toDto(quotes);
}
}
// 2. Use Case (domain port in)
export interface SearchRatesPort {
execute(input: RateSearchInput): Promise<RateQuote[]>;
}
// 3. Domain Service (domain layer)
export class RateSearchService implements SearchRatesPort {
constructor(
private readonly cache: CachePort,
private readonly carriers: CarrierConnectorPort[]
) {}
async execute(input: RateSearchInput): Promise<RateQuote[]> {
// Check cache first
const cached = await this.cache.get(input.cacheKey);
if (cached) return cached;
// Query carriers in parallel with timeout
const results = await Promise.allSettled(
this.carriers.map(c => c.searchRates(input))
);
// Filter successful results
const quotes = results
.filter(r => r.status === 'fulfilled')
.flatMap(r => r.value);
// Cache results (15 min TTL)
await this.cache.set(input.cacheKey, quotes, 900);
return quotes;
}
}
// 4. Infrastructure Adapter (infrastructure layer)
export class MaerskConnectorAdapter implements CarrierConnectorPort {
async searchRates(input: RateSearchInput): Promise<RateQuote[]> {
// HTTP call to Maersk API with 5s timeout
const response = await this.httpClient.post(
'https://api.maersk.com/rates',
this.mapToMaerskFormat(input),
{ timeout: 5000 }
);
// Map Maersk response to domain entities
return this.mapToDomainQuotes(response.data);
} }
} }
``` ```
### Value Object Pattern This architecture ensures clean separation, testability, and flexibility for the Xpeditis maritime freight platform.
Immutable, self-validating via static `create()`. E.g. `Money` supports USD, EUR, GBP, CNY, JPY with arithmetic and formatting methods.
### Repository Pattern
- Interface in `domain/ports/out/` with token constant (e.g. `BOOKING_REPOSITORY = 'BookingRepository'`)
- Implementation in `infrastructure/persistence/typeorm/repositories/`
- ORM entities: `infrastructure/persistence/typeorm/entities/*.orm-entity.ts`
- Separate mapper classes (`infrastructure/persistence/typeorm/mappers/`) with static `toOrm()`, `toDomain()`, `toDomainMany()` methods
### Frontend API Client
Custom Fetch wrapper in `src/lib/api/client.ts` — exports `get()`, `post()`, `patch()`, `del()`, `upload()`, `download()`. Auto-refreshes JWT on 401. Tokens stored in localStorage **and synced to cookies** (`accessToken` cookie) so Next.js middleware can read them server-side. Per-module files (auth.ts, bookings.ts, rates.ts, etc.) import from client.
### Route Protection (Middleware)
`apps/frontend/middleware.ts` checks the `accessToken` cookie to protect routes. Public paths are defined in two lists:
- `exactPublicPaths`: exact matches (e.g. `/`)
- `prefixPublicPaths`: prefix matches including sub-paths (e.g. `/login`, `/carrier`, `/about`, etc.)
All other routes redirect to `/login?redirect=<pathname>` when the cookie is absent.
### Application Decorators
- `@Public()` — skip JWT auth
- `@Roles()` — role-based access control
- `@CurrentUser()` — inject authenticated user
### API Key Authentication
A second auth mechanism alongside JWT. `ApiKey` domain entity (`domain/entities/api-key.entity.ts`) — keys are hashed with Argon2. `ApiKeyGuard` in `application/guards/` checks the `x-api-key` header. Routes can accept either JWT or API key; see `admin.controller.ts` for examples.
### WebSocket (Real-time Notifications)
Socket.IO gateway at `application/gateways/notifications.gateway.ts`. Clients connect to `/` namespace with a JWT bearer token in the handshake auth. Server emits `notification` events. The frontend `useNotifications` hook handles subscriptions.
### Carrier Connectors
Five carrier connectors (Maersk, MSC, CMA CGM, Hapag-Lloyd, ONE) extending `base-carrier.connector.ts`, each with request/response mappers. Circuit breaker via `opossum` (5s timeout).
### Caching
Redis with 15-min TTL for rate quotes. Key format: `rate:{origin}:{destination}:{containerType}`.
## Business Rules
- Booking number format: `WCM-YYYY-XXXXXX`
- Booking status flow: draft → confirmed → shipped → delivered
- Rate quotes expire after 15 minutes
- Multi-currency: USD, EUR, GBP, CNY, JPY
- RBAC Roles: ADMIN, MANAGER, USER, VIEWER, CARRIER
- JWT: access token 15min, refresh token 7d
- Password hashing: Argon2
- OAuth providers: Google, Microsoft (configured via passport strategies)
- Organizations can be validated via Pappers API (French SIRET/company registry) at `infrastructure/external/pappers-siret.adapter.ts`
### Carrier Portal Workflow
1. Admin creates CSV booking → assigns carrier
2. Email with magic link sent (1-hour expiry)
3. Carrier auto-login → accept/reject booking
4. Activity logged in `carrier_activities` table (via `CarrierProfile` + `CarrierActivity` ORM entities)
## Common Pitfalls
- Never import NestJS/TypeORM in domain layer
- Never use `any` type in backend (strict mode enabled)
- Never modify applied migrations — create new ones
- Always validate DTOs with `class-validator` decorators
- Always create separate mappers for Domain ↔ ORM conversions
- ORM entity files must match pattern `*.orm-entity.{ts,js}` (auto-discovered by data-source)
- Migration files must be in `infrastructure/persistence/typeorm/migrations/`
- Database synchronize is hard-coded to `false` — always use migrations
## Adding a New Feature
1. **Domain Entity** → `domain/entities/*.entity.ts` (pure TS, unit tests)
2. **Value Objects** → `domain/value-objects/*.vo.ts` (immutable)
3. **In Port (Use Case)** → `domain/ports/in/*.use-case.ts` (interface with `execute()`)
4. **Out Port (Repository)** → `domain/ports/out/*.repository.ts` (with token constant)
5. **ORM Entity** → `infrastructure/persistence/typeorm/entities/*.orm-entity.ts`
6. **Migration** → `npm run migration:generate -- src/infrastructure/persistence/typeorm/migrations/MigrationName`
7. **Repository Impl** → `infrastructure/persistence/typeorm/repositories/`
8. **Mapper** → `infrastructure/persistence/typeorm/mappers/` (static toOrm/toDomain/toDomainMany)
9. **DTOs** → `application/dto/` (with class-validator decorators)
10. **Controller** → `application/controllers/` (with Swagger decorators)
11. **Module** → Register repository + use-case providers, import in `app.module.ts`
## Documentation
- API Docs: http://localhost:4000/api/docs (Swagger, when running)
- Setup guide: `docs/installation/START-HERE.md`
- Carrier Portal API: `apps/backend/docs/CARRIER_PORTAL_API.md`
- Full docs index: `docs/README.md`
- Development roadmap: `TODO.md`
- Infrastructure configs (CI/CD, Docker): `infra/`

393
INDEX.md
View File

@ -1,81 +1,348 @@
# Index de documentation — Xpeditis # 📑 Xpeditis Documentation Index
Complete guide to all documentation files in the Xpeditis project.
--- ---
## Démarrage ## 🚀 Getting Started (Read First)
| Fichier | Description | Start here if you're new to the project:
|---------|-------------|
| [README.md](README.md) | Vue d'ensemble du projet | 1. **[README.md](README.md)** - Project overview and quick start
| [QUICK-START.md](QUICK-START.md) | Démarrage en 5 minutes | 2. **[QUICK-START.md](QUICK-START.md)** ⚡ - Get running in 5 minutes
| [CLAUDE.md](CLAUDE.md) | Architecture hexagonale, conventions, règles | 3. **[INSTALLATION-STEPS.md](INSTALLATION-STEPS.md)** - Detailed installation guide
| [docs/README.md](docs/README.md) | Index complet de la documentation | 4. **[NEXT-STEPS.md](NEXT-STEPS.md)** - What to do after setup
--- ---
## Documentation complète ## 📊 Project Status & Planning
Toute la documentation est organisée dans [docs/](docs/) : ### Sprint 0 (Complete ✅)
``` - **[SPRINT-0-FINAL.md](SPRINT-0-FINAL.md)** - Complete Sprint 0 report
docs/ - All deliverables
├── README.md # Index principal - Architecture details
├── getting-started/ # Installation et démarrage - How to use
│ ├── quick-start.md # Guide rapide mis à jour - Success criteria
│ ├── installation.md # Installation détaillée
│ └── windows.md # Spécifique Windows - **[SPRINT-0-SUMMARY.md](SPRINT-0-SUMMARY.md)** - Executive summary
│ - Objectives achieved
├── architecture/ # Documentation technique - Metrics
│ ├── overview.md # Vue d'ensemble système - Key features
│ ├── database.md # Schéma BDD complet (21 tables) - Next steps
│ ├── backend.md # NestJS hexagonal, patterns
│ └── frontend.md # Next.js 14, App Router, i18n - **[SPRINT-0-COMPLETE.md](SPRINT-0-COMPLETE.md)** - Technical completion checklist
│ - Week-by-week breakdown
├── features/ # Documentation par fonctionnalité - Files created
│ ├── auth.md # Auth JWT/OAuth/API Keys + RBAC - Remaining tasks
│ ├── bookings.md # Réservations standard
│ ├── csv-bookings.md # CSV bookings + portail carrier ### Project Roadmap
│ ├── rate-search.md # Recherche tarifs FCL + CSV
│ ├── subscriptions.md # Stripe + abonnements - **[TODO.md](TODO.md)** 📅 - 30-week MVP development roadmap
│ ├── notifications.md # WebSocket + webhooks - Sprint-by-sprint breakdown
│ └── api-access.md # Clés API - Detailed tasks with checkboxes
│ - Phase 1-4 planning
├── deployment/ # Déploiement - Go-to-market strategy
│ ├── portainer.md # Portainer / Docker Swarm (consolidé)
│ ├── hetzner/ # Kubernetes Hetzner (15 fichiers numérotés) - **[PRD.md](PRD.md)** 📋 - Product Requirements Document
│ └── STRIPE_SETUP.md # Configuration Stripe - Business context
│ - Functional specifications
├── testing/ # Tests - Technical requirements
├── csv-system/ # Système CSV (format, calcul prix) - Success metrics
├── carrier-portal/ # Portail carrier (recherche API)
├── api-access/ # Documentation accès API
├── backend/ # Notes backend (cleanup, MinIO)
└── archive/ # Rapports de sprint archivés
├── phases/ # Historique phases 1-4
└── debug/ # Notes de debug résolues
```
--- ---
## Commandes essentielles ## 🏗️ Architecture & Development Guidelines
```bash ### Core Architecture
# Démarrer
docker-compose up -d
npm run install:all
cd apps/backend && npm run migration:run && cd ../..
npm run backend:dev # http://localhost:4000
npm run frontend:dev # http://localhost:3000
# Tests - **[CLAUDE.md](CLAUDE.md)** 🏗️ - **START HERE FOR ARCHITECTURE**
npm run backend:test - Complete hexagonal architecture guide
npm run frontend:test - Domain/Application/Infrastructure layers
- Ports & Adapters pattern
- Naming conventions
- Testing strategy
- Common pitfalls
- Complete examples (476 lines)
# Qualité ### Component-Specific Documentation
npm run format
npm run backend:lint && npm run frontend:lint - **[apps/backend/README.md](apps/backend/README.md)** - Backend (NestJS + Hexagonal)
``` - Architecture details
- Available scripts
- API endpoints
- Testing guide
- Hexagonal architecture DOs and DON'Ts
- **[apps/frontend/README.md](apps/frontend/README.md)** - Frontend (Next.js 14)
- Tech stack
- Project structure
- API integration
- Forms & validation
- Testing guide
--- ---
*Dernière mise à jour : Mai 2026* ## 🛠️ Technical Documentation
### Configuration Files
**Root Level**:
- `package.json` - Workspace configuration
- `.gitignore` - Git ignore rules
- `.prettierrc` - Code formatting
- `docker-compose.yml` - PostgreSQL + Redis
- `tsconfig.json` - TypeScript configuration (per app)
**Backend** (`apps/backend/`):
- `package.json` - Backend dependencies
- `tsconfig.json` - TypeScript strict mode + path aliases
- `nest-cli.json` - NestJS CLI configuration
- `.eslintrc.js` - ESLint rules
- `.env.example` - Environment variables template
**Frontend** (`apps/frontend/`):
- `package.json` - Frontend dependencies
- `tsconfig.json` - TypeScript configuration
- `next.config.js` - Next.js configuration
- `tailwind.config.ts` - Tailwind CSS theme
- `postcss.config.js` - PostCSS configuration
- `.env.example` - Environment variables template
### CI/CD
**GitHub Actions** (`.github/workflows/`):
- `ci.yml` - Continuous Integration
- Lint & format check
- Unit tests (backend + frontend)
- E2E tests
- Build verification
- `security.yml` - Security Audit
- npm audit
- Dependency review
**Templates**:
- `.github/pull_request_template.md` - PR template with hexagonal architecture checklist
---
## 📚 Documentation by Use Case
### I want to...
**...get started quickly**
1. [QUICK-START.md](QUICK-START.md) - 5-minute setup
2. [INSTALLATION-STEPS.md](INSTALLATION-STEPS.md) - Detailed steps
3. [NEXT-STEPS.md](NEXT-STEPS.md) - Begin development
**...understand the architecture**
1. [CLAUDE.md](CLAUDE.md) - Complete hexagonal architecture guide
2. [apps/backend/README.md](apps/backend/README.md) - Backend specifics
3. [SPRINT-0-FINAL.md](SPRINT-0-FINAL.md) - See what's implemented
**...know what to build next**
1. [TODO.md](TODO.md) - Full roadmap
2. [NEXT-STEPS.md](NEXT-STEPS.md) - Immediate next tasks
3. [PRD.md](PRD.md) - Business requirements
**...understand the business context**
1. [PRD.md](PRD.md) - Product requirements
2. [README.md](README.md) - Project overview
3. [SPRINT-0-SUMMARY.md](SPRINT-0-SUMMARY.md) - Executive summary
**...fix an installation issue**
1. [INSTALLATION-STEPS.md](INSTALLATION-STEPS.md) - Troubleshooting section
2. [QUICK-START.md](QUICK-START.md) - Common issues
3. [README.md](README.md) - Basic setup
**...write code following best practices**
1. [CLAUDE.md](CLAUDE.md) - Architecture guidelines (READ THIS FIRST)
2. [apps/backend/README.md](apps/backend/README.md) - Backend DOs and DON'Ts
3. [TODO.md](TODO.md) - Task specifications and acceptance criteria
**...run tests**
1. [apps/backend/README.md](apps/backend/README.md) - Testing section
2. [apps/frontend/README.md](apps/frontend/README.md) - Testing section
3. [CLAUDE.md](CLAUDE.md) - Testing strategy
**...deploy to production**
1. [SPRINT-0-FINAL.md](SPRINT-0-FINAL.md) - Security checklist
2. [apps/backend/.env.example](apps/backend/.env.example) - All required variables
3. `.github/workflows/ci.yml` - CI/CD pipeline
---
## 📖 Documentation by Role
### For Developers
**Must Read**:
1. [CLAUDE.md](CLAUDE.md) - Architecture principles
2. [apps/backend/README.md](apps/backend/README.md) OR [apps/frontend/README.md](apps/frontend/README.md)
3. [TODO.md](TODO.md) - Current sprint tasks
**Reference**:
- [INSTALLATION-STEPS.md](INSTALLATION-STEPS.md) - Setup issues
- [PRD.md](PRD.md) - Business context
### For Architects
**Must Read**:
1. [CLAUDE.md](CLAUDE.md) - Complete architecture
2. [SPRINT-0-FINAL.md](SPRINT-0-FINAL.md) - Implementation details
3. [PRD.md](PRD.md) - Technical requirements
**Reference**:
- [TODO.md](TODO.md) - Technical roadmap
- [apps/backend/README.md](apps/backend/README.md) - Backend architecture
### For Project Managers
**Must Read**:
1. [SPRINT-0-SUMMARY.md](SPRINT-0-SUMMARY.md) - Status overview
2. [TODO.md](TODO.md) - Complete roadmap
3. [PRD.md](PRD.md) - Requirements & KPIs
**Reference**:
- [SPRINT-0-FINAL.md](SPRINT-0-FINAL.md) - Detailed completion report
- [README.md](README.md) - Project overview
### For DevOps
**Must Read**:
1. [INSTALLATION-STEPS.md](INSTALLATION-STEPS.md) - Setup guide
2. [docker-compose.yml](docker-compose.yml) - Infrastructure
3. `.github/workflows/` - CI/CD pipelines
**Reference**:
- [apps/backend/.env.example](apps/backend/.env.example) - Environment variables
- [SPRINT-0-FINAL.md](SPRINT-0-FINAL.md) - Security checklist
---
## 🗂️ Complete File List
### Documentation (11 files)
| File | Purpose | Length |
|------|---------|--------|
| [README.md](README.md) | Project overview | Medium |
| [CLAUDE.md](CLAUDE.md) | Architecture guide | Long (476 lines) |
| [PRD.md](PRD.md) | Product requirements | Long (352 lines) |
| [TODO.md](TODO.md) | 30-week roadmap | Very Long (1000+ lines) |
| [QUICK-START.md](QUICK-START.md) | 5-minute setup | Short |
| [INSTALLATION-STEPS.md](INSTALLATION-STEPS.md) | Detailed setup | Medium |
| [NEXT-STEPS.md](NEXT-STEPS.md) | What's next | Medium |
| [SPRINT-0-FINAL.md](SPRINT-0-FINAL.md) | Sprint 0 report | Long |
| [SPRINT-0-SUMMARY.md](SPRINT-0-SUMMARY.md) | Executive summary | Medium |
| [SPRINT-0-COMPLETE.md](SPRINT-0-COMPLETE.md) | Technical checklist | Short |
| [INDEX.md](INDEX.md) | This file | Medium |
### App-Specific (2 files)
| File | Purpose |
|------|---------|
| [apps/backend/README.md](apps/backend/README.md) | Backend guide |
| [apps/frontend/README.md](apps/frontend/README.md) | Frontend guide |
### Configuration (10+ files)
Root, backend, and frontend configuration files (package.json, tsconfig.json, etc.)
---
## 📊 Documentation Statistics
- **Total Documentation Files**: 13
- **Total Lines**: ~4,000+
- **Coverage**: Setup, Architecture, Development, Testing, Deployment
- **Last Updated**: October 7, 2025
---
## 🎯 Recommended Reading Path
### For New Team Members (Day 1)
**Morning** (2 hours):
1. [README.md](README.md) - 10 min
2. [QUICK-START.md](QUICK-START.md) - 30 min (includes setup)
3. [CLAUDE.md](CLAUDE.md) - 60 min (comprehensive architecture)
4. [PRD.md](PRD.md) - 20 min (business context)
**Afternoon** (2 hours):
5. [apps/backend/README.md](apps/backend/README.md) OR [apps/frontend/README.md](apps/frontend/README.md) - 30 min
6. [TODO.md](TODO.md) - Current sprint section - 30 min
7. [NEXT-STEPS.md](NEXT-STEPS.md) - 30 min
8. Start coding! 🚀
### For Code Review (30 minutes)
1. [CLAUDE.md](CLAUDE.md) - Hexagonal architecture section
2. [apps/backend/README.md](apps/backend/README.md) - DOs and DON'Ts
3. [TODO.md](TODO.md) - Acceptance criteria for the feature
### For Sprint Planning (1 hour)
1. [TODO.md](TODO.md) - Next sprint tasks
2. [PRD.md](PRD.md) - Requirements for the module
3. [SPRINT-0-SUMMARY.md](SPRINT-0-SUMMARY.md) - Current status
---
## 🔍 Quick Reference
### Common Questions
**Q: How do I get started?**
A: [QUICK-START.md](QUICK-START.md)
**Q: What is hexagonal architecture?**
A: [CLAUDE.md](CLAUDE.md) - Complete guide with examples
**Q: What should I build next?**
A: [NEXT-STEPS.md](NEXT-STEPS.md) then [TODO.md](TODO.md)
**Q: How do I run tests?**
A: [apps/backend/README.md](apps/backend/README.md) or [apps/frontend/README.md](apps/frontend/README.md)
**Q: Where are the business requirements?**
A: [PRD.md](PRD.md)
**Q: What's the project status?**
A: [SPRINT-0-SUMMARY.md](SPRINT-0-SUMMARY.md)
**Q: Installation failed, what do I do?**
A: [INSTALLATION-STEPS.md](INSTALLATION-STEPS.md) - Troubleshooting section
**Q: Can I change the database/framework?**
A: Yes! That's the point of hexagonal architecture. See [CLAUDE.md](CLAUDE.md)
---
## 📞 Getting Help
If you can't find what you need:
1. **Check this index** - Use Ctrl+F to search
2. **Read CLAUDE.md** - Covers 90% of architecture questions
3. **Check TODO.md** - Has detailed task specifications
4. **Open an issue** - If documentation is unclear or missing
---
## 🎉 Happy Reading!
All documentation is up-to-date as of Sprint 0 completion.
**Quick Links**:
- 🚀 [Get Started](QUICK-START.md)
- 🏗️ [Architecture](CLAUDE.md)
- 📅 [Roadmap](TODO.md)
- 📋 [Requirements](PRD.md)
---
*Xpeditis MVP - Maritime Freight Booking Platform*
*Documentation Index - October 7, 2025*

285
README.md
View File

@ -1,151 +1,206 @@
# Xpeditis — Maritime Freight Booking Platform # Xpeditis - Maritime Freight Booking Platform
Plateforme B2B SaaS permettant aux transitaires de rechercher, comparer et réserver du fret maritime en temps réel. **Xpeditis** is a B2B SaaS platform for freight forwarders to search, compare, and book maritime freight in real-time.
--- ---
## Démarrage rapide ## ⭐ **[START HERE](START-HERE.md)** ⭐
**New to the project?** Read **[START-HERE.md](START-HERE.md)** - Get running in 10 minutes!
---
## 🚀 Quick Start
### Prerequisites
- Node.js >= 20.0.0
- npm >= 10.0.0
- Docker & Docker Compose
- PostgreSQL 15+
- Redis 7+
### Installation
```bash ```bash
# 1. Installer les dépendances # Install dependencies
npm run install:all npm install
# 2. Démarrer l'infrastructure (PostgreSQL + Redis + MinIO) # Start infrastructure (PostgreSQL + Redis)
docker-compose up -d docker-compose up -d
# 3. Configurer l'environnement # Setup environment variables
cp apps/backend/.env.example apps/backend/.env cp apps/backend/.env.example apps/backend/.env
cp apps/frontend/.env.example apps/frontend/.env.local cp apps/frontend/.env.example apps/frontend/.env
# 4. Exécuter les migrations # Run database migrations
cd apps/backend && npm run migration:run && cd ../.. npm run backend:migrate
# 5. Démarrer les serveurs # Start backend (development)
npm run backend:dev # http://localhost:4000 · Swagger: /api/docs npm run backend:dev
npm run frontend:dev # http://localhost:3000
# Start frontend (development)
npm run frontend:dev
``` ```
--- ### Access Points
## Structure du projet - **Frontend**: http://localhost:3000
- **Backend API**: http://localhost:4000
- **API Documentation**: http://localhost:4000/api/docs
## 📁 Project Structure
``` ```
xpeditis/ xpeditis/
├── apps/ ├── apps/
│ ├── backend/ # NestJS 10 — Architecture hexagonale │ ├── backend/ # NestJS API (Hexagonal Architecture)
│ │ └── src/ │ │ └── src/
│ │ ├── domain/ # Logique métier pure (TypeScript) │ │ ├── domain/ # Pure business logic
│ │ ├── application/ # Controllers, DTOs, Guards │ │ ├── application/ # Controllers & DTOs
│ │ └── infrastructure/ # TypeORM, Redis, S3, Email, Stripe │ │ └── infrastructure/ # External adapters
│ └── frontend/ # Next.js 14 App Router │ └── frontend/ # Next.js 14 App Router
│ ├── app/[locale]/ # Routing i18n (fr, en) ├── packages/
│ └── src/ # Components, hooks, lib/api │ ├── shared-types/ # Shared TypeScript types
├── docker-compose.yml # PostgreSQL 15 + Redis 7 + MinIO │ └── domain/ # Shared domain logic
└── docs/ # Documentation complète └── infra/ # Infrastructure configs
``` ```
--- ## 🏗️ Architecture
## Documentation This project follows **Hexagonal Architecture** (Ports & Adapters) principles:
| Sujet | Fichier | - **Domain Layer**: Pure business logic, no external dependencies
|-------|---------| - **Application Layer**: Use cases, controllers, DTOs
| Index complet | [docs/README.md](docs/README.md) | - **Infrastructure Layer**: Database, external APIs, cache, email, storage
| Architecture hexagonale + conventions | [CLAUDE.md](CLAUDE.md) |
| Vue d'ensemble système | [docs/architecture/overview.md](docs/architecture/overview.md) |
| Schéma BDD (21 tables) | [docs/architecture/database.md](docs/architecture/database.md) |
| Démarrage rapide | [docs/getting-started/quick-start.md](docs/getting-started/quick-start.md) |
--- See [CLAUDE.md](CLAUDE.md) for detailed architecture guidelines.
## Commandes de développement ## 🛠️ Development
```bash
# Backend
npm run backend:dev # Serveur avec hot-reload
npm run backend:test # Tests unitaires Jest
npm run backend:lint # ESLint
npm run backend:build # Build production
# Frontend
npm run frontend:dev # Serveur avec hot-reload
npm run frontend:test # Tests unitaires Jest
npm run frontend:lint # ESLint
cd apps/frontend && npm run test:e2e # Playwright E2E
# Qualité
npm run format # Prettier (tous les fichiers)
# Base de données
cd apps/backend
npm run migration:generate -- src/infrastructure/persistence/typeorm/migrations/NomMigration
npm run migration:run
npm run migration:revert
```
---
## Stack technique
### Backend ### Backend
| Composant | Technologie | ```bash
|-----------|-------------| npm run backend:dev # Start dev server
| Framework | NestJS 10 + TypeScript 5 (strict) | npm run backend:test # Run tests
| Base de données | PostgreSQL 15 + TypeORM | npm run backend:test:watch # Run tests in watch mode
| Cache | Redis 7 (ioredis) | npm run backend:test:cov # Generate coverage report
| Auth | JWT (15min) + Refresh + OAuth2 + API Keys (Argon2) | npm run backend:lint # Lint code
| Temps réel | Socket.IO | npm run backend:build # Build for production
| Email | Nodemailer + MJML | ```
| Paiements | Stripe |
| Stockage | S3/MinIO |
| Logging | nestjs-pino |
| Monitoring | Sentry |
### Frontend ### Frontend
| Composant | Technologie | ```bash
|-----------|-------------| npm run frontend:dev # Start dev server
| Framework | Next.js 14 App Router + TypeScript | npm run frontend:build # Build for production
| Styling | Tailwind CSS + shadcn/ui (Radix UI) | npm run frontend:test # Run tests
| State serveur | TanStack Query v5 | npm run frontend:lint # Lint code
| Tables | TanStack Table v8 + Virtual | ```
| Formulaires | react-hook-form + zod |
| Temps réel | Socket.IO client | ## 📚 Documentation
| i18n | next-intl (fr, en) |
| Graphiques | recharts | ### Getting Started
- **[QUICK-START.md](QUICK-START.md)** ⚡ - Get running in 5 minutes
- **[INSTALLATION-STEPS.md](INSTALLATION-STEPS.md)** 📦 - Detailed installation guide
- **[NEXT-STEPS.md](NEXT-STEPS.md)** 🚀 - What to do after setup
### Architecture & Guidelines
- **[CLAUDE.md](CLAUDE.md)** 🏗️ - Hexagonal architecture guidelines (complete)
- **[apps/backend/README.md](apps/backend/README.md)** - Backend documentation
- **[apps/frontend/README.md](apps/frontend/README.md)** - Frontend documentation
### Project Planning
- **[PRD.md](PRD.md)** 📋 - Product Requirements Document
- **[TODO.md](TODO.md)** 📅 - 30-week development roadmap
- **[SPRINT-0-FINAL.md](SPRINT-0-FINAL.md)** ✅ - Sprint 0 completion report
- **[SPRINT-0-SUMMARY.md](SPRINT-0-SUMMARY.md)** 📊 - Executive summary
### API Documentation
- **[API Docs](http://localhost:4000/api/docs)** 📖 - OpenAPI/Swagger (when running)
## 🧪 Testing
```bash
# Run all tests
npm run test:all
# Run backend tests
npm run backend:test
# Run frontend tests
npm run frontend:test
# E2E tests (after implementation)
npm run test:e2e
```
## 🔒 Security
- All passwords hashed with bcrypt (12 rounds minimum)
- JWT tokens (access: 15min, refresh: 7 days)
- HTTPS/TLS 1.2+ enforced
- OWASP Top 10 protection
- Rate limiting on all endpoints
- CSRF protection
## 📊 Tech Stack
### Backend
- **Framework**: NestJS 10+
- **Language**: TypeScript 5+
- **Database**: PostgreSQL 15+
- **Cache**: Redis 7+
- **ORM**: TypeORM
- **Testing**: Jest, Supertest
- **API Docs**: Swagger/OpenAPI
### Frontend
- **Framework**: Next.js 14+ (App Router)
- **Language**: TypeScript 5+
- **Styling**: Tailwind CSS
- **UI Components**: shadcn/ui
- **State**: React Query (TanStack Query)
- **Forms**: React Hook Form + Zod
- **Testing**: Jest, React Testing Library, Playwright
## 🚢 Carrier Integrations
MVP supports the following maritime carriers:
- ✅ Maersk
- ✅ MSC
- ✅ CMA CGM
- ✅ Hapag-Lloyd
- ✅ ONE (Ocean Network Express)
## 📈 Monitoring & Logging
- **Logging**: Winston / Pino
- **Error Tracking**: Sentry
- **APM**: Application Performance Monitoring
- **Metrics**: Prometheus (planned)
## 🔧 Environment Variables
See `.env.example` files in each app for required environment variables.
## 🤝 Contributing
1. Create a feature branch
2. Make your changes
3. Write tests
4. Run linting and formatting
5. Submit a pull request
## 📝 License
Proprietary - All rights reserved
## 👥 Team
Built with ❤️ by the Xpeditis team
--- ---
## Carriers intégrés For detailed implementation guidelines, see [CLAUDE.md](CLAUDE.md).
| Carrier | Code | Statut |
|---------|------|--------|
| Maersk | MAEU | Connecteur API |
| MSC | MSCU | Connecteur API |
| CMA CGM | CMDU | Connecteur API |
| Hapag-Lloyd | HLCU | Connecteur API |
| ONE | ONEY | Connecteur API |
| SSC Consolidation | — | CSV |
| ECU Worldwide | — | CSV + API |
| TCC Logistics | — | CSV |
| NVO Consolidation | — | CSV |
---
## Fonctionnalités principales
- **Recherche tarifs** : FCL (carriers API + cache Redis 15min) + LCL CSV
- **Réservation standard** : workflow 4 étapes, numéro WCM-YYYY-XXXXXX
- **Réservation CSV + Portail Carrier** : magic link, accept/reject
- **Dashboard** : KPI, graphiques, table interactive virtuelle
- **Auth** : JWT, OAuth2 (Google/Microsoft), API Keys, RBAC (5 rôles)
- **Abonnements** : Stripe (FREE/BRONZE/SILVER/GOLD/PLATINIUM)
- **Notifications** : WebSocket temps réel + webhooks tiers
- **GDPR** : export/suppression des données utilisateur
- **Blog** : gestion de contenu bilingue (fr/en)
- **Audit** : journal d'audit de toutes les actions
---
*Architecture hexagonale — NestJS 10 + Next.js 14 — PostgreSQL 15 + Redis 7*

View File

@ -1,85 +0,0 @@
# Dependencies
node_modules
npm-debug.log
yarn-error.log
yarn.lock
pnpm-lock.yaml
# Build output
dist
build
.next
out
# Tests
coverage
.nyc_output
*.spec.ts
*.test.ts
**/__tests__
**/__mocks__
test
tests
e2e
# Environment files
.env
.env.*
.env.local
.env.development
.env.test
.env.production
.env.*.local
# IDE
.vscode
.idea
*.swp
*.swo
*.swn
.DS_Store
# Git
.git
.gitignore
.gitattributes
.github
# Documentation
*.md
docs
documentation
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Temporary files
tmp
temp
*.tmp
*.bak
*.cache
# Docker
Dockerfile
.dockerignore
docker-compose.yaml
# CI/CD
.gitlab-ci.yml
.travis.yml
Jenkinsfile
azure-pipelines.yml
# Other
.prettierrc
.prettierignore
.eslintrc.js
.eslintignore
tsconfig.build.tsbuildinfo

View File

@ -18,19 +18,11 @@ REDIS_PORT=6379
REDIS_PASSWORD=xpeditis_redis_password REDIS_PASSWORD=xpeditis_redis_password
REDIS_DB=0 REDIS_DB=0
# JWT (JWT_SECRET must be at least 32 characters) # JWT
JWT_SECRET=your-super-secret-jwt-key-change-this-in-production JWT_SECRET=your-super-secret-jwt-key-change-this-in-production
JWT_ACCESS_EXPIRATION=15m JWT_ACCESS_EXPIRATION=15m
JWT_REFRESH_EXPIRATION=7d JWT_REFRESH_EXPIRATION=7d
# Auth cookies — domain shared between frontend and API in production
# (e.g. .xpeditis.com). Leave unset for localhost development.
# COOKIE_DOMAIN=.xpeditis.com
# Secret used to derive carrier document passwords (min 16 chars).
# Falls back to JWT_SECRET when unset.
# DOCUMENT_PASSWORD_SECRET=your-document-password-secret
# OAuth2 - Google # OAuth2 - Google
GOOGLE_CLIENT_ID=your-google-client-id GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret GOOGLE_CLIENT_SECRET=your-google-client-secret
@ -43,27 +35,29 @@ MICROSOFT_CALLBACK_URL=http://localhost:4000/api/v1/auth/microsoft/callback
# Application URL # Application URL
APP_URL=http://localhost:3000 APP_URL=http://localhost:3000
FRONTEND_URL=http://localhost:3000
# Email (SMTP) # Email (SMTP)
SMTP_HOST=smtp-relay.brevo.com SMTP_HOST=smtp.sendgrid.net
SMTP_PORT=587 SMTP_PORT=587
SMTP_USER=
SMTP_PASS=
SMTP_SECURE=false SMTP_SECURE=false
SMTP_USER=apikey
SMTP_PASS=your-sendgrid-api-key
SMTP_FROM=noreply@xpeditis.com SMTP_FROM=noreply@xpeditis.com
# AWS S3 / Storage (or MinIO for development) # AWS S3 / Storage (or MinIO for development)
AWS_ACCESS_KEY_ID=minioadmin AWS_ACCESS_KEY_ID=your-aws-access-key
AWS_SECRET_ACCESS_KEY=minioadmin AWS_SECRET_ACCESS_KEY=your-aws-secret-key
AWS_REGION=us-east-1 AWS_REGION=us-east-1
AWS_S3_ENDPOINT=http://localhost:9000 AWS_S3_ENDPOINT=http://localhost:9000
# AWS_S3_ENDPOINT= # Leave empty for AWS S3 # AWS_S3_ENDPOINT= # Leave empty for AWS S3
# Carrier APIs
# Swagger Documentation Access (HTTP Basic Auth — only you can access /api/docs) MAERSK_API_KEY=your-maersk-api-key
SWAGGER_USERNAME= MAERSK_API_URL=https://api.maersk.com
SWAGGER_PASSWORD= MSC_API_KEY=your-msc-api-key
MSC_API_URL=https://api.msc.com
CMA_CGM_API_KEY=your-cma-cgm-api-key
CMA_CGM_API_URL=https://api.cma-cgm.com
# Security # Security
BCRYPT_ROUNDS=12 BCRYPT_ROUNDS=12
@ -75,43 +69,3 @@ RATE_LIMIT_MAX=100
# Monitoring # Monitoring
SENTRY_DSN=your-sentry-dsn SENTRY_DSN=your-sentry-dsn
# Frontend URL (for redirects)
FRONTEND_URL=http://localhost:3000
# Stripe (Subscriptions & Payments)
STRIPE_SECRET_KEY=
STRIPE_WEBHOOK_SECRET=
# Stripe Price IDs (from Stripe Dashboard)
STRIPE_SILVER_MONTHLY_PRICE_ID=
STRIPE_SILVER_YEARLY_PRICE_ID=
STRIPE_GOLD_MONTHLY_PRICE_ID=
STRIPE_GOLD_YEARLY_PRICE_ID=
STRIPE_PLATINIUM_MONTHLY_PRICE_ID=
STRIPE_PLATINIUM_YEARLY_PRICE_ID=
# Premier administrateur (amorcage) - migration BootstrapAdminFromEnv
# En developpement, laissez vide : SeedTestUsers cree deja admin@xpeditis.com.
# En production, renseignez une adresse RELEVABLE : le compte est cree sans
# mot de passe utilisable et vous definissez le votre via "mot de passe oublie".
# BOOTSTRAP_ADMIN_EMAIL=
# BOOTSTRAP_ADMIN_FIRST_NAME=Admin
# BOOTSTRAP_ADMIN_LAST_NAME=Xpeditis
# BOOTSTRAP_ADMIN_ORG_NAME=Xpeditis
# BOOTSTRAP_ADMIN_ORG_STREET=A completer
# BOOTSTRAP_ADMIN_ORG_CITY=A completer
# BOOTSTRAP_ADMIN_ORG_POSTAL_CODE=00000
# BOOTSTRAP_ADMIN_ORG_COUNTRY=FR
# Facultatif : hash Argon2id, si SMTP n'est pas encore operationnel.
# Generer avec : node scripts/setup/generate-admin-hash.js
# Jamais un mot de passe en clair - la migration le refuse.
# BOOTSTRAP_ADMIN_PASSWORD_HASH=
# Force la neutralisation des comptes de demonstration hors production.
# FORCE_NEUTRALIZE_SEED_ACCOUNTS=true
# Trade assistant — server only. Empty key enables guided help only.
OPENAI_API_KEY=
OPENAI_MODEL=gpt-4.1-mini

View File

@ -1,33 +1,25 @@
module.exports = { module.exports = {
parser: '@typescript-eslint/parser', parser: '@typescript-eslint/parser',
parserOptions: { parserOptions: {
project: ['tsconfig.json', 'tsconfig.test.json'], project: 'tsconfig.json',
tsconfigRootDir: __dirname, tsconfigRootDir: __dirname,
sourceType: 'module', sourceType: 'module',
}, },
plugins: ['@typescript-eslint/eslint-plugin', 'unused-imports'], plugins: ['@typescript-eslint/eslint-plugin'],
extends: ['plugin:@typescript-eslint/recommended', 'plugin:prettier/recommended'], extends: [
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
],
root: true, root: true,
env: { env: {
node: true, node: true,
jest: true, jest: true,
}, },
ignorePatterns: ['.eslintrc.js', 'dist/**', 'node_modules/**', 'apps/**'], ignorePatterns: ['.eslintrc.js'],
rules: { rules: {
'@typescript-eslint/interface-name-prefix': 'off', '@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off', '@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off', '@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-explicit-any': 'off', // Désactivé pour projet existant en production '@typescript-eslint/no-explicit-any': 'warn',
'@typescript-eslint/no-unused-vars': 'off', // Désactivé car remplacé par unused-imports
'unused-imports/no-unused-imports': 'error',
'unused-imports/no-unused-vars': [
'warn',
{
argsIgnorePattern: '^_',
varsIgnorePattern: '^_',
caughtErrorsIgnorePattern: '^_',
ignoreRestSiblings: true,
},
],
}, },
}; };

View File

@ -1,95 +0,0 @@
# ===============================================
# Stage 1: Dependencies Installation
# ===============================================
FROM node:22-alpine AS dependencies
# Install build dependencies
RUN apk add --no-cache python3 make g++ libc6-compat
# Set working directory
WORKDIR /app
# Copy package files
COPY package*.json ./
COPY tsconfig*.json ./
# Install all dependencies (including dev for build)
RUN npm ci --legacy-peer-deps
# ===============================================
# Stage 2: Build Application
# ===============================================
FROM node:22-alpine AS builder
WORKDIR /app
# Copy dependencies from previous stage
COPY --from=dependencies /app/node_modules ./node_modules
# Copy source code
COPY . .
# Build the application
RUN npm run build
# Remove dev dependencies to reduce size
RUN npm prune --production --legacy-peer-deps
# ===============================================
# Stage 3: Production Image
# ===============================================
FROM node:22-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
RUN apk add --no-cache dumb-init
# Create non-root user
RUN addgroup -g 1001 -S nodejs && \
adduser -S nestjs -u 1001
# Set working directory
WORKDIR /app
# Copy built application from builder
COPY --from=builder --chown=nestjs:nodejs /app/dist ./dist
COPY --from=builder --chown=nestjs:nodejs /app/node_modules ./node_modules
COPY --from=builder --chown=nestjs:nodejs /app/package*.json ./
# Copy source code needed at runtime (for CSV storage path resolution)
COPY --from=builder --chown=nestjs:nodejs /app/src ./src
# Copy startup script (includes migrations)
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
RUN mkdir -p /app/logs && \
mkdir -p /app/src/infrastructure/storage/csv-storage/rates && \
chown -R nestjs:nodejs /app/logs /app/src
# Switch to non-root user
USER nestjs
# Expose port
EXPOSE 4000
# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \
CMD node -e "require('http').get('http://localhost:4000/api/v1/health', (r) => process.exit(r.statusCode === 200 ? 0 : 1))"
# Set environment variables
ENV NODE_ENV=production \
PORT=4000
# Use dumb-init to handle signals properly
ENTRYPOINT ["dumb-init", "--"]
# Start the application with migrations
CMD ["node", "startup.js"]

View File

@ -1,26 +0,0 @@
#!/bin/sh
echo "Starting Xpeditis Backend..."
echo "Waiting for PostgreSQL..."
max_attempts=30
attempt=0
while [ $attempt -lt $max_attempts ]; do
if node -e "const { Client } = require('pg'); const { databaseTlsOptions } = require('/app/dist/infrastructure/persistence/typeorm/database-tls'); const client = new Client({ host: process.env.DATABASE_HOST, port: process.env.DATABASE_PORT, user: process.env.DATABASE_USER, password: process.env.DATABASE_PASSWORD, database: process.env.DATABASE_NAME, ssl: databaseTlsOptions(process.env.DATABASE_SSL, process.env.DATABASE_SSL_CA, process.env.DATABASE_HOST) }); client.connect().then(() => { client.end(); process.exit(0); }).catch(() => process.exit(1));" 2>/dev/null; then
echo "PostgreSQL is ready"
break
fi
attempt=$((attempt + 1))
echo "Attempt $attempt/$max_attempts - Retrying..."
sleep 2
done
if [ $attempt -eq $max_attempts ]; then
echo "Failed to connect to PostgreSQL"
exit 1
fi
echo "Running database migrations..."
node /app/run-migrations.js
if [ $? -ne 0 ]; then
echo "Migrations failed"
exit 1
fi
echo "Starting NestJS application..."
exec "$@"

View File

@ -1,727 +0,0 @@
# Carrier Portal API Documentation
**Version**: 1.0
**Base URL**: `http://localhost:4000/api/v1`
**Last Updated**: 2025-12-04
## Table of Contents
1. [Overview](#overview)
2. [Authentication](#authentication)
3. [API Endpoints](#api-endpoints)
- [Carrier Authentication](#carrier-authentication)
- [Carrier Dashboard](#carrier-dashboard)
- [Booking Management](#booking-management)
- [Document Management](#document-management)
4. [Data Models](#data-models)
5. [Error Handling](#error-handling)
6. [Examples](#examples)
---
## Overview
The Carrier Portal API provides endpoints for transportation carriers (transporteurs) to:
- Authenticate and manage their accounts
- View dashboard statistics
- Manage booking requests from clients
- Accept or reject booking requests
- Download shipment documents
- Track their performance metrics
All endpoints require JWT authentication except for the public authentication endpoints.
---
## Authentication
### Authentication Header
All protected endpoints require a Bearer token in the Authorization header:
```
Authorization: Bearer <access_token>
```
### Token Management
- **Access Token**: Valid for 15 minutes
- **Refresh Token**: Valid for 7 days
- **Auto-Login Token**: Valid for 1 hour (for magic link authentication)
---
## API Endpoints
### Carrier Authentication
#### 1. Login
**Endpoint**: `POST /carrier-auth/login`
**Description**: Authenticate a carrier with email and password.
**Request Body**:
```json
{
"email": "carrier@example.com",
"password": "SecurePassword123!"
}
```
**Response** (200 OK):
```json
{
"accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"carrier": {
"id": "carrier-uuid",
"companyName": "Transport Express",
"email": "carrier@example.com"
}
}
```
**Errors**:
- `401 Unauthorized`: Invalid credentials
- `401 Unauthorized`: Account is inactive
- `400 Bad Request`: Validation error
---
#### 2. Get Current Carrier Profile
**Endpoint**: `GET /carrier-auth/me`
**Description**: Retrieve the authenticated carrier's profile information.
**Headers**:
```
Authorization: Bearer <access_token>
```
**Response** (200 OK):
```json
{
"id": "carrier-uuid",
"userId": "user-uuid",
"companyName": "Transport Express",
"email": "carrier@example.com",
"role": "CARRIER",
"organizationId": "org-uuid",
"phone": "+33612345678",
"website": "https://transport-express.com",
"city": "Paris",
"country": "France",
"isVerified": true,
"isActive": true,
"totalBookingsAccepted": 45,
"totalBookingsRejected": 5,
"acceptanceRate": 90.0,
"totalRevenueUsd": 125000,
"totalRevenueEur": 112500,
"preferredCurrency": "EUR",
"lastLoginAt": "2025-12-04T10:30:00Z"
}
```
**Errors**:
- `401 Unauthorized`: Invalid or expired token
---
#### 3. Change Password
**Endpoint**: `PATCH /carrier-auth/change-password`
**Description**: Change the carrier's password.
**Headers**:
```
Authorization: Bearer <access_token>
```
**Request Body**:
```json
{
"oldPassword": "OldPassword123!",
"newPassword": "NewPassword123!"
}
```
**Response** (200 OK):
```json
{
"message": "Password changed successfully"
}
```
**Errors**:
- `401 Unauthorized`: Invalid old password
- `400 Bad Request`: Password validation failed
---
#### 4. Request Password Reset
**Endpoint**: `POST /carrier-auth/request-password-reset`
**Description**: Request a password reset (generates temporary password).
**Request Body**:
```json
{
"email": "carrier@example.com"
}
```
**Response** (200 OK):
```json
{
"message": "If this email exists, a password reset will be sent"
}
```
**Note**: For security, the response is the same whether the email exists or not.
---
#### 5. Verify Auto-Login Token
**Endpoint**: `POST /carrier-auth/verify-auto-login`
**Description**: Verify an auto-login token from email magic link.
**Request Body**:
```json
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
```
**Response** (200 OK):
```json
{
"userId": "user-uuid",
"carrierId": "carrier-uuid"
}
```
**Errors**:
- `401 Unauthorized`: Invalid or expired token
---
### Carrier Dashboard
#### 6. Get Dashboard Statistics
**Endpoint**: `GET /carrier-dashboard/stats`
**Description**: Retrieve carrier dashboard statistics including bookings count, revenue, and recent activities.
**Headers**:
```
Authorization: Bearer <access_token>
```
**Response** (200 OK):
```json
{
"totalBookings": 50,
"pendingBookings": 5,
"acceptedBookings": 42,
"rejectedBookings": 3,
"acceptanceRate": 93.3,
"totalRevenue": {
"usd": 125000,
"eur": 112500
},
"recentActivities": [
{
"id": "activity-uuid",
"type": "BOOKING_ACCEPTED",
"description": "Booking #12345 accepted",
"createdAt": "2025-12-04T09:15:00Z",
"bookingId": "booking-uuid"
},
{
"id": "activity-uuid-2",
"type": "DOCUMENT_DOWNLOADED",
"description": "Downloaded invoice.pdf",
"createdAt": "2025-12-04T08:30:00Z",
"bookingId": "booking-uuid-2"
}
]
}
```
**Errors**:
- `401 Unauthorized`: Invalid or expired token
- `404 Not Found`: Carrier not found
---
#### 7. Get Carrier Bookings (Paginated)
**Endpoint**: `GET /carrier-dashboard/bookings`
**Description**: Retrieve a paginated list of bookings for the carrier.
**Headers**:
```
Authorization: Bearer <access_token>
```
**Query Parameters**:
- `page` (number, optional): Page number (default: 1)
- `limit` (number, optional): Items per page (default: 10)
- `status` (string, optional): Filter by status (PENDING, ACCEPTED, REJECTED)
**Example Request**:
```
GET /carrier-dashboard/bookings?page=1&limit=10&status=PENDING
```
**Response** (200 OK):
```json
{
"data": [
{
"id": "booking-uuid",
"origin": "Rotterdam",
"destination": "New York",
"status": "PENDING",
"priceUsd": 1500,
"priceEur": 1350,
"primaryCurrency": "USD",
"requestedAt": "2025-12-04T08:00:00Z",
"carrierViewedAt": null,
"documentsCount": 3,
"volumeCBM": 25.5,
"weightKG": 12000,
"palletCount": 10,
"transitDays": 15,
"containerType": "40HC"
}
],
"total": 50,
"page": 1,
"limit": 10
}
```
**Errors**:
- `401 Unauthorized`: Invalid or expired token
- `404 Not Found`: Carrier not found
---
#### 8. Get Booking Details
**Endpoint**: `GET /carrier-dashboard/bookings/:id`
**Description**: Retrieve detailed information about a specific booking.
**Headers**:
```
Authorization: Bearer <access_token>
```
**Path Parameters**:
- `id` (string, required): Booking ID
**Response** (200 OK):
```json
{
"id": "booking-uuid",
"carrierName": "Transport Express",
"carrierEmail": "carrier@example.com",
"origin": "Rotterdam",
"destination": "New York",
"volumeCBM": 25.5,
"weightKG": 12000,
"palletCount": 10,
"priceUSD": 1500,
"priceEUR": 1350,
"primaryCurrency": "USD",
"transitDays": 15,
"containerType": "40HC",
"status": "PENDING",
"documents": [
{
"id": "doc-uuid",
"fileName": "invoice.pdf",
"type": "INVOICE",
"url": "https://storage.example.com/doc.pdf",
"uploadedAt": "2025-12-03T10:00:00Z"
}
],
"confirmationToken": "token-123",
"requestedAt": "2025-12-04T08:00:00Z",
"respondedAt": null,
"notes": "Urgent shipment",
"rejectionReason": null,
"carrierViewedAt": "2025-12-04T10:15:00Z",
"carrierAcceptedAt": null,
"carrierRejectedAt": null,
"carrierRejectionReason": null,
"carrierNotes": null,
"createdAt": "2025-12-04T08:00:00Z",
"updatedAt": "2025-12-04T10:15:00Z"
}
```
**Errors**:
- `401 Unauthorized`: Invalid or expired token
- `403 Forbidden`: Access denied to this booking
- `404 Not Found`: Booking not found
---
### Booking Management
#### 9. Accept Booking
**Endpoint**: `POST /carrier-dashboard/bookings/:id/accept`
**Description**: Accept a booking request.
**Headers**:
```
Authorization: Bearer <access_token>
```
**Path Parameters**:
- `id` (string, required): Booking ID
**Request Body**:
```json
{
"notes": "Ready to proceed. Pickup scheduled for Dec 5th."
}
```
**Response** (200 OK):
```json
{
"message": "Booking accepted successfully"
}
```
**Errors**:
- `401 Unauthorized`: Invalid or expired token
- `403 Forbidden`: Access denied to this booking
- `404 Not Found`: Booking not found
- `400 Bad Request`: Booking cannot be accepted (wrong status)
---
#### 10. Reject Booking
**Endpoint**: `POST /carrier-dashboard/bookings/:id/reject`
**Description**: Reject a booking request with a reason.
**Headers**:
```
Authorization: Bearer <access_token>
```
**Path Parameters**:
- `id` (string, required): Booking ID
**Request Body**:
```json
{
"reason": "CAPACITY_NOT_AVAILABLE",
"notes": "Sorry, we don't have capacity for this shipment at the moment."
}
```
**Response** (200 OK):
```json
{
"message": "Booking rejected successfully"
}
```
**Errors**:
- `401 Unauthorized`: Invalid or expired token
- `403 Forbidden`: Access denied to this booking
- `404 Not Found`: Booking not found
- `400 Bad Request`: Rejection reason required
- `400 Bad Request`: Booking cannot be rejected (wrong status)
---
### Document Management
#### 11. Download Document
**Endpoint**: `GET /carrier-dashboard/bookings/:bookingId/documents/:documentId/download`
**Description**: Download a document associated with a booking.
**Headers**:
```
Authorization: Bearer <access_token>
```
**Path Parameters**:
- `bookingId` (string, required): Booking ID
- `documentId` (string, required): Document ID
**Response** (200 OK):
```json
{
"document": {
"id": "doc-uuid",
"fileName": "invoice.pdf",
"type": "INVOICE",
"url": "https://storage.example.com/doc.pdf",
"size": 245678,
"mimeType": "application/pdf",
"uploadedAt": "2025-12-03T10:00:00Z"
}
}
```
**Errors**:
- `401 Unauthorized`: Invalid or expired token
- `403 Forbidden`: Access denied to this document
- `404 Not Found`: Document or booking not found
---
## Data Models
### Carrier Profile
```typescript
interface CarrierProfile {
id: string;
userId: string;
organizationId: string;
companyName: string;
email: string;
phone?: string;
website?: string;
city?: string;
country?: string;
isVerified: boolean;
isActive: boolean;
totalBookingsAccepted: number;
totalBookingsRejected: number;
acceptanceRate: number;
totalRevenueUsd: number;
totalRevenueEur: number;
preferredCurrency: 'USD' | 'EUR';
lastLoginAt?: Date;
}
```
### Booking
```typescript
interface Booking {
id: string;
carrierId: string;
carrierName: string;
carrierEmail: string;
origin: string;
destination: string;
volumeCBM: number;
weightKG: number;
palletCount: number;
priceUSD: number;
priceEUR: number;
primaryCurrency: 'USD' | 'EUR';
transitDays: number;
containerType: string;
status: 'PENDING' | 'ACCEPTED' | 'REJECTED' | 'CANCELLED';
documents: Document[];
confirmationToken: string;
requestedAt: Date;
respondedAt?: Date;
notes?: string;
rejectionReason?: string;
carrierViewedAt?: Date;
carrierAcceptedAt?: Date;
carrierRejectedAt?: Date;
carrierRejectionReason?: string;
carrierNotes?: string;
createdAt: Date;
updatedAt: Date;
}
```
### Document
```typescript
interface Document {
id: string;
fileName: string;
type: 'INVOICE' | 'PACKING_LIST' | 'CERTIFICATE' | 'OTHER';
url: string;
size?: number;
mimeType?: string;
uploadedAt: Date;
}
```
### Activity
```typescript
interface CarrierActivity {
id: string;
carrierId: string;
bookingId?: string;
activityType: 'BOOKING_ACCEPTED' | 'BOOKING_REJECTED' | 'DOCUMENT_DOWNLOADED' | 'PROFILE_UPDATED';
description: string;
metadata?: Record<string, any>;
createdAt: Date;
}
```
---
## Error Handling
### Error Response Format
All error responses follow this structure:
```json
{
"statusCode": 400,
"message": "Validation failed",
"error": "Bad Request",
"timestamp": "2025-12-04T10:30:00Z",
"path": "/api/v1/carrier-auth/login"
}
```
### Common HTTP Status Codes
- `200 OK`: Request successful
- `201 Created`: Resource created successfully
- `400 Bad Request`: Validation error or invalid request
- `401 Unauthorized`: Authentication required or invalid credentials
- `403 Forbidden`: Insufficient permissions
- `404 Not Found`: Resource not found
- `500 Internal Server Error`: Server error
---
## Examples
### Complete Authentication Flow
```bash
# 1. Login
curl -X POST http://localhost:4000/api/v1/carrier-auth/login \
-H "Content-Type: application/json" \
-d '{
"email": "carrier@example.com",
"password": "SecurePassword123!"
}'
# Response:
# {
# "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
# "refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
# "carrier": { "id": "carrier-uuid", ... }
# }
# 2. Get Dashboard Stats
curl -X GET http://localhost:4000/api/v1/carrier-dashboard/stats \
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
# 3. Get Pending Bookings
curl -X GET "http://localhost:4000/api/v1/carrier-dashboard/bookings?status=PENDING&page=1&limit=10" \
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
# 4. Accept a Booking
curl -X POST http://localhost:4000/api/v1/carrier-dashboard/bookings/booking-uuid/accept \
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \
-H "Content-Type: application/json" \
-d '{
"notes": "Ready to proceed with shipment"
}'
```
### Using Auto-Login Token
```bash
# Verify auto-login token from email magic link
curl -X POST http://localhost:4000/api/v1/carrier-auth/verify-auto-login \
-H "Content-Type: application/json" \
-d '{
"token": "auto-login-token-from-email"
}'
```
---
## Rate Limiting
All API endpoints are rate-limited to prevent abuse:
- **Authentication endpoints**: 5 requests per minute per IP
- **Dashboard/Booking endpoints**: 30 requests per minute per user
- **Global limit**: 100 requests per minute per user
Rate limit headers are included in all responses:
```
X-RateLimit-Limit: 30
X-RateLimit-Remaining: 29
X-RateLimit-Reset: 60
```
---
## Security
### Best Practices
1. **Always use HTTPS** in production
2. **Store tokens securely** (e.g., httpOnly cookies, secure storage)
3. **Implement token refresh** before access token expires
4. **Validate all input** on client side before sending to API
5. **Handle errors gracefully** without exposing sensitive information
6. **Log out properly** by clearing all stored tokens
### CORS Configuration
The API allows requests from:
- `http://localhost:3000` (development)
- `https://your-production-domain.com` (production)
---
## Changelog
### Version 1.0 (2025-12-04)
- Initial release
- Authentication endpoints
- Dashboard endpoints
- Booking management
- Document management
- Complete carrier portal workflow
---
## Support
For API support or questions:
- **Email**: support@xpeditis.com
- **Documentation**: https://docs.xpeditis.com
- **Status Page**: https://status.xpeditis.com
---
**Document created**: 2025-12-04
**Author**: Xpeditis Development Team
**Version**: 1.0

View File

@ -1,152 +0,0 @@
/**
* K6 Load Test - Rate Search Endpoint
*
* Target: 100 requests/second
* Duration: 5 minutes
*
* Run: k6 run rate-search.test.js
*/
import http from 'k6/http';
import { check, sleep } from 'k6';
import { Rate, Trend } from 'k6/metrics';
// Custom metrics
const errorRate = new Rate('errors');
const searchDuration = new Trend('search_duration');
// Test configuration
export const options = {
stages: [
{ duration: '1m', target: 20 }, // Ramp up to 20 users
{ duration: '2m', target: 50 }, // Ramp up to 50 users
{ duration: '1m', target: 100 }, // Ramp up to 100 users
{ duration: '3m', target: 100 }, // Stay at 100 users
{ duration: '1m', target: 0 }, // Ramp down
],
thresholds: {
http_req_duration: ['p(95)<2000'], // 95% of requests must complete below 2s
http_req_failed: ['rate<0.01'], // Error rate must be less than 1%
errors: ['rate<0.05'], // Business error rate must be less than 5%
},
};
// Base URL
const BASE_URL = __ENV.API_URL || 'http://localhost:4000/api/v1';
// Auth token (should be set via environment variable)
const AUTH_TOKEN = __ENV.AUTH_TOKEN || '';
// Test data - common trade lanes
const tradeLanes = [
{
origin: 'NLRTM', // Rotterdam
destination: 'CNSHA', // Shanghai
containerType: '40HC',
},
{
origin: 'USNYC', // New York
destination: 'GBLON', // London
containerType: '20ST',
},
{
origin: 'SGSIN', // Singapore
destination: 'USOAK', // Oakland
containerType: '40ST',
},
{
origin: 'DEHAM', // Hamburg
destination: 'BRRIO', // Rio de Janeiro
containerType: '40HC',
},
{
origin: 'AEDXB', // Dubai
destination: 'INMUN', // Mumbai
containerType: '20ST',
},
];
export default function () {
// Select random trade lane
const tradeLane = tradeLanes[Math.floor(Math.random() * tradeLanes.length)];
// Prepare request payload
const payload = JSON.stringify({
origin: tradeLane.origin,
destination: tradeLane.destination,
departureDate: new Date(Date.now() + 14 * 24 * 60 * 60 * 1000).toISOString().split('T')[0], // 2 weeks from now
containers: [
{
type: tradeLane.containerType,
quantity: 1,
},
],
});
const params = {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${AUTH_TOKEN}`,
},
tags: { name: 'RateSearch' },
};
// Make request
const startTime = Date.now();
const response = http.post(`${BASE_URL}/rates/search`, payload, params);
const duration = Date.now() - startTime;
// Record metrics
searchDuration.add(duration);
// Check response
const success = check(response, {
'status is 200': r => r.status === 200,
'response has quotes': r => {
try {
const body = JSON.parse(r.body);
return body.quotes && body.quotes.length > 0;
} catch (e) {
return false;
}
},
'response time < 2s': r => duration < 2000,
});
errorRate.add(!success);
// Small delay between requests
sleep(1);
}
export function handleSummary(data) {
return {
stdout: textSummary(data, { indent: ' ', enableColors: true }),
'load-test-results/rate-search-summary.json': JSON.stringify(data),
};
}
function textSummary(data, options) {
const indent = options.indent || '';
const enableColors = options.enableColors || false;
return `
${indent}Test Summary - Rate Search Load Test
${indent}=====================================
${indent}
${indent}Total Requests: ${data.metrics.http_reqs.values.count}
${indent}Failed Requests: ${data.metrics.http_req_failed.values.rate * 100}%
${indent}
${indent}Response Times:
${indent} Average: ${data.metrics.http_req_duration.values.avg.toFixed(2)}ms
${indent} Median: ${data.metrics.http_req_duration.values.med.toFixed(2)}ms
${indent} 95th: ${data.metrics.http_req_duration.values['p(95)'].toFixed(2)}ms
${indent} 99th: ${data.metrics.http_req_duration.values['p(99)'].toFixed(2)}ms
${indent}
${indent}Requests/sec: ${data.metrics.http_reqs.values.rate.toFixed(2)}
${indent}
${indent}Business Metrics:
${indent} Error Rate: ${(data.metrics.errors.values.rate * 100).toFixed(2)}%
${indent} Avg Search Duration: ${data.metrics.search_duration.values.avg.toFixed(2)}ms
`;
}

View File

@ -4,13 +4,6 @@
"sourceRoot": "src", "sourceRoot": "src",
"compilerOptions": { "compilerOptions": {
"deleteOutDir": true, "deleteOutDir": true,
"builder": "tsc", "webpack": false
"tsConfigPath": "tsconfig.build.json",
"plugins": ["@nestjs/swagger"],
"assets": [
{ "include": "i18n/**/*.json", "outDir": "dist" },
{ "include": "infrastructure/ai/knowledge/*.json", "outDir": "dist" }
],
"watchAssets": true
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -4,9 +4,8 @@
"description": "Xpeditis Backend API - Maritime Freight Booking Platform", "description": "Xpeditis Backend API - Maritime Freight Booking Platform",
"private": true, "private": true,
"scripts": { "scripts": {
"build": "nest build && tsc-alias -p tsconfig.build.json", "build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"knowledge:build": "node scripts/setup/build-knowledge-corpus.js",
"start": "nest start", "start": "nest start",
"dev": "nest start --watch", "dev": "nest start --watch",
"start:debug": "nest start --debug --watch", "start:debug": "nest start --debug --watch",
@ -28,42 +27,30 @@
"@aws-sdk/client-s3": "^3.906.0", "@aws-sdk/client-s3": "^3.906.0",
"@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/common": "^10.2.10",
"@nestjs/common": "^11.2.6", "@nestjs/config": "^3.1.1",
"@nestjs/config": "^4.0.4", "@nestjs/core": "^10.2.10",
"@nestjs/core": "^11.2.6", "@nestjs/jwt": "^10.2.0",
"@nestjs/jwt": "^11.0.2", "@nestjs/passport": "^10.0.3",
"@nestjs/passport": "^11.0.5", "@nestjs/platform-express": "^10.2.10",
"@nestjs/platform-express": "^11.2.6", "@nestjs/swagger": "^7.1.16",
"@nestjs/platform-socket.io": "^11.2.6", "@nestjs/typeorm": "^10.0.1",
"@nestjs/schedule": "^6.1.3", "@types/mjml": "^4.7.4",
"@nestjs/swagger": "^11.4.7",
"@nestjs/throttler": "^6.4.0",
"@nestjs/typeorm": "^11.0.3",
"@nestjs/websockets": "^11.2.6",
"@sentry/node": "^10.19.0",
"@sentry/profiling-node": "^10.19.0",
"@types/leaflet": "^1.9.21",
"@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",
"argon2": "^0.44.0", "argon2": "^0.44.0",
"axios": "^1.12.2", "axios": "^1.12.2",
"bcrypt": "^5.1.1",
"class-transformer": "^0.5.1", "class-transformer": "^0.5.1",
"class-validator": "^0.14.2", "class-validator": "^0.14.2",
"compression": "^1.8.1",
"cookie-parser": "^1.4.7",
"csv-parse": "^6.1.0",
"exceljs": "^4.4.0",
"handlebars": "^4.7.8", "handlebars": "^4.7.8",
"helmet": "^7.2.0", "helmet": "^7.1.0",
"ioredis": "^5.8.1", "ioredis": "^5.8.1",
"joi": "^17.11.0", "joi": "^17.11.0",
"leaflet": "^1.9.4", "mjml": "^4.16.1",
"mjml": "^5.4.1",
"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",
@ -74,38 +61,28 @@
"pino": "^8.17.1", "pino": "^8.17.1",
"pino-http": "^8.6.0", "pino-http": "^8.6.0",
"pino-pretty": "^10.3.0", "pino-pretty": "^10.3.0",
"react-leaflet": "^5.0.0",
"reflect-metadata": "^0.1.14", "reflect-metadata": "^0.1.14",
"rxjs": "^7.8.1", "rxjs": "^7.8.1",
"sharp": "^0.35.3", "typeorm": "^0.3.17"
"socket.io": "^4.8.1",
"stripe": "^14.14.0",
"typeorm": "^0.3.17",
"uuid": "^9.0.1"
}, },
"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/express": "^4.17.21",
"@types/cookie-parser": "^1.4.10",
"@types/express": "^5.0.6",
"@types/jest": "^29.5.11", "@types/jest": "^29.5.11",
"@types/mjml": "^5.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",
"@types/passport-jwt": "^3.0.13", "@types/passport-jwt": "^3.0.13",
"@types/supertest": "^6.0.2", "@types/supertest": "^6.0.2",
"@types/uuid": "^10.0.0", "@types/uuid": "^10.0.0",
"@typescript-eslint/eslint-plugin": "^7.18.0", "@typescript-eslint/eslint-plugin": "^6.15.0",
"@typescript-eslint/parser": "^7.18.0", "@typescript-eslint/parser": "^6.15.0",
"eslint": "^8.56.0", "eslint": "^8.56.0",
"eslint-config-prettier": "^9.1.0", "eslint-config-prettier": "^9.1.0",
"eslint-plugin-prettier": "^5.0.1", "eslint-plugin-prettier": "^5.0.1",
"eslint-plugin-unused-imports": "^4.3.0",
"ioredis-mock": "^8.13.0", "ioredis-mock": "^8.13.0",
"jest": "^29.7.0", "jest": "^29.7.0",
"prettier": "^3.1.1", "prettier": "^3.1.1",
@ -114,7 +91,6 @@
"ts-jest": "^29.1.1", "ts-jest": "^29.1.1",
"ts-loader": "^9.5.1", "ts-loader": "^9.5.1",
"ts-node": "^10.9.2", "ts-node": "^10.9.2",
"tsc-alias": "^1.8.16",
"tsconfig-paths": "^4.2.0", "tsconfig-paths": "^4.2.0",
"typescript": "^5.3.3" "typescript": "^5.3.3"
}, },
@ -127,12 +103,7 @@
"rootDir": "src", "rootDir": "src",
"testRegex": ".*\\.spec\\.ts$", "testRegex": ".*\\.spec\\.ts$",
"transform": { "transform": {
"^.+\\.(t|j)s$": [ "^.+\\.(t|j)s$": "ts-jest"
"ts-jest",
{
"tsconfig": "tsconfig.test.json"
}
]
}, },
"collectCoverageFrom": [ "collectCoverageFrom": [
"**/*.(t|j)s" "**/*.(t|j)s"

View File

@ -1,372 +0,0 @@
{
"info": {
"name": "Xpeditis API",
"description": "Complete API collection for Xpeditis maritime freight booking platform",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
"_postman_id": "xpeditis-api-v1",
"version": "1.0.0"
},
"auth": {
"type": "bearer",
"bearer": [
{
"key": "token",
"value": "{{access_token}}",
"type": "string"
}
]
},
"variable": [
{
"key": "base_url",
"value": "http://localhost:4000/api/v1",
"type": "string"
},
{
"key": "access_token",
"value": "",
"type": "string"
},
{
"key": "refresh_token",
"value": "",
"type": "string"
},
{
"key": "user_id",
"value": "",
"type": "string"
},
{
"key": "booking_id",
"value": "",
"type": "string"
}
],
"item": [
{
"name": "Authentication",
"item": [
{
"name": "Register User",
"event": [
{
"listen": "test",
"script": {
"exec": [
"pm.test(\"Status code is 201\", function () {",
" pm.response.to.have.status(201);",
"});",
"",
"pm.test(\"Response has user data\", function () {",
" const jsonData = pm.response.json();",
" pm.expect(jsonData).to.have.property('user');",
" pm.expect(jsonData).to.have.property('accessToken');",
" pm.environment.set('access_token', jsonData.accessToken);",
" pm.environment.set('user_id', jsonData.user.id);",
"});"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json"
}
],
"body": {
"mode": "raw",
"raw": "{\n \"email\": \"test@example.com\",\n \"password\": \"TestPassword123!\",\n \"firstName\": \"Test\",\n \"lastName\": \"User\",\n \"organizationName\": \"Test Organization\"\n}"
},
"url": {
"raw": "{{base_url}}/auth/register",
"host": ["{{base_url}}"],
"path": ["auth", "register"]
}
}
},
{
"name": "Login",
"event": [
{
"listen": "test",
"script": {
"exec": [
"pm.test(\"Status code is 200\", function () {",
" pm.response.to.have.status(200);",
"});",
"",
"pm.test(\"Response has tokens\", function () {",
" const jsonData = pm.response.json();",
" pm.expect(jsonData).to.have.property('accessToken');",
" pm.expect(jsonData).to.have.property('refreshToken');",
" pm.environment.set('access_token', jsonData.accessToken);",
" pm.environment.set('refresh_token', jsonData.refreshToken);",
"});"
],
"type": "text/javascript"
}
}
],
"request": {
"auth": {
"type": "noauth"
},
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json"
}
],
"body": {
"mode": "raw",
"raw": "{\n \"email\": \"test@example.com\",\n \"password\": \"TestPassword123!\"\n}"
},
"url": {
"raw": "{{base_url}}/auth/login",
"host": ["{{base_url}}"],
"path": ["auth", "login"]
}
}
},
{
"name": "Refresh Token",
"event": [
{
"listen": "test",
"script": {
"exec": [
"pm.test(\"Status code is 200\", function () {",
" pm.response.to.have.status(200);",
"});",
"",
"const jsonData = pm.response.json();",
"pm.environment.set('access_token', jsonData.accessToken);"
],
"type": "text/javascript"
}
}
],
"request": {
"auth": {
"type": "noauth"
},
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json"
}
],
"body": {
"mode": "raw",
"raw": "{\n \"refreshToken\": \"{{refresh_token}}\"\n}"
},
"url": {
"raw": "{{base_url}}/auth/refresh",
"host": ["{{base_url}}"],
"path": ["auth", "refresh"]
}
}
}
]
},
{
"name": "Rates",
"item": [
{
"name": "Search Rates",
"event": [
{
"listen": "test",
"script": {
"exec": [
"pm.test(\"Status code is 200\", function () {",
" pm.response.to.have.status(200);",
"});",
"",
"pm.test(\"Response has quotes\", function () {",
" const jsonData = pm.response.json();",
" pm.expect(jsonData).to.have.property('quotes');",
" pm.expect(jsonData.quotes).to.be.an('array');",
"});",
"",
"pm.test(\"Response time < 2000ms\", function () {",
" pm.expect(pm.response.responseTime).to.be.below(2000);",
"});"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json"
}
],
"body": {
"mode": "raw",
"raw": "{\n \"origin\": \"NLRTM\",\n \"destination\": \"CNSHA\",\n \"departureDate\": \"2025-11-01\",\n \"containers\": [\n {\n \"type\": \"40HC\",\n \"quantity\": 1\n }\n ]\n}"
},
"url": {
"raw": "{{base_url}}/rates/search",
"host": ["{{base_url}}"],
"path": ["rates", "search"]
}
}
}
]
},
{
"name": "Bookings",
"item": [
{
"name": "Create Booking",
"event": [
{
"listen": "test",
"script": {
"exec": [
"pm.test(\"Status code is 201\", function () {",
" pm.response.to.have.status(201);",
"});",
"",
"pm.test(\"Response has booking data\", function () {",
" const jsonData = pm.response.json();",
" pm.expect(jsonData).to.have.property('id');",
" pm.expect(jsonData).to.have.property('bookingNumber');",
" pm.environment.set('booking_id', jsonData.id);",
"});",
"",
"pm.test(\"Booking number format is correct\", function () {",
" const jsonData = pm.response.json();",
" pm.expect(jsonData.bookingNumber).to.match(/^WCM-\\d{4}-[A-Z0-9]{6}$/);",
"});"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json"
}
],
"body": {
"mode": "raw",
"raw": "{\n \"rateQuoteId\": \"rate-quote-id\",\n \"shipper\": {\n \"name\": \"Test Shipper Inc.\",\n \"address\": \"123 Test St\",\n \"city\": \"Rotterdam\",\n \"country\": \"Netherlands\",\n \"email\": \"shipper@test.com\",\n \"phone\": \"+31612345678\"\n },\n \"consignee\": {\n \"name\": \"Test Consignee Ltd.\",\n \"address\": \"456 Dest Ave\",\n \"city\": \"Shanghai\",\n \"country\": \"China\",\n \"email\": \"consignee@test.com\",\n \"phone\": \"+8613812345678\"\n },\n \"containers\": [\n {\n \"type\": \"40HC\",\n \"description\": \"Electronics\",\n \"weight\": 15000\n }\n ]\n}"
},
"url": {
"raw": "{{base_url}}/bookings",
"host": ["{{base_url}}"],
"path": ["bookings"]
}
}
},
{
"name": "Get Booking by ID",
"event": [
{
"listen": "test",
"script": {
"exec": [
"pm.test(\"Status code is 200\", function () {",
" pm.response.to.have.status(200);",
"});",
"",
"pm.test(\"Response has booking details\", function () {",
" const jsonData = pm.response.json();",
" pm.expect(jsonData).to.have.property('id');",
" pm.expect(jsonData).to.have.property('status');",
"});"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "GET",
"url": {
"raw": "{{base_url}}/bookings/{{booking_id}}",
"host": ["{{base_url}}"],
"path": ["bookings", "{{booking_id}}"]
}
}
},
{
"name": "List Bookings",
"event": [
{
"listen": "test",
"script": {
"exec": [
"pm.test(\"Status code is 200\", function () {",
" pm.response.to.have.status(200);",
"});",
"",
"pm.test(\"Response is paginated\", function () {",
" const jsonData = pm.response.json();",
" pm.expect(jsonData).to.have.property('data');",
" pm.expect(jsonData).to.have.property('total');",
" pm.expect(jsonData).to.have.property('page');",
"});"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "GET",
"url": {
"raw": "{{base_url}}/bookings?page=1&pageSize=20",
"host": ["{{base_url}}"],
"path": ["bookings"],
"query": [
{
"key": "page",
"value": "1"
},
{
"key": "pageSize",
"value": "20"
}
]
}
}
},
{
"name": "Export Bookings (CSV)",
"request": {
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json"
}
],
"body": {
"mode": "raw",
"raw": "{\n \"format\": \"csv\",\n \"bookingIds\": []\n}"
},
"url": {
"raw": "{{base_url}}/bookings/export",
"host": ["{{base_url}}"],
"path": ["bookings", "export"]
}
}
}
]
}
]
}

View File

@ -1,106 +0,0 @@
/**
* Script to delete test documents from MinIO
*
* Deletes only small test files (< 1000 bytes) created by upload-test-documents.js
* Preserves real uploaded documents (larger files)
*/
const { S3Client, ListObjectsV2Command, DeleteObjectCommand } = require('@aws-sdk/client-s3');
require('dotenv').config();
const MINIO_ENDPOINT = process.env.AWS_S3_ENDPOINT || 'http://localhost:9000';
const BUCKET_NAME = 'xpeditis-documents';
const TEST_FILE_SIZE_THRESHOLD = 1000; // Files smaller than 1KB are likely test files
// Initialize MinIO client
const s3Client = new S3Client({
region: 'us-east-1',
endpoint: MINIO_ENDPOINT,
credentials: {
accessKeyId: process.env.AWS_ACCESS_KEY_ID || 'minioadmin',
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY || 'minioadmin',
},
forcePathStyle: true,
});
async function deleteTestDocuments() {
try {
console.log('📋 Listing all files in bucket:', BUCKET_NAME);
// List all files
let allFiles = [];
let continuationToken = null;
do {
const command = new ListObjectsV2Command({
Bucket: BUCKET_NAME,
ContinuationToken: continuationToken,
});
const response = await s3Client.send(command);
if (response.Contents) {
allFiles = allFiles.concat(response.Contents);
}
continuationToken = response.NextContinuationToken;
} while (continuationToken);
console.log(`\n📊 Found ${allFiles.length} total files\n`);
// Filter test files (small files < 1000 bytes)
const testFiles = allFiles.filter(file => file.Size < TEST_FILE_SIZE_THRESHOLD);
const realFiles = allFiles.filter(file => file.Size >= TEST_FILE_SIZE_THRESHOLD);
console.log(`🔍 Analysis:`);
console.log(` Test files (< ${TEST_FILE_SIZE_THRESHOLD} bytes): ${testFiles.length}`);
console.log(` Real files (>= ${TEST_FILE_SIZE_THRESHOLD} bytes): ${realFiles.length}\n`);
if (testFiles.length === 0) {
console.log('✅ No test files to delete');
return;
}
console.log(`🗑️ Deleting ${testFiles.length} test files:\n`);
let deletedCount = 0;
for (const file of testFiles) {
console.log(` Deleting: ${file.Key} (${file.Size} bytes)`);
try {
await s3Client.send(
new DeleteObjectCommand({
Bucket: BUCKET_NAME,
Key: file.Key,
})
);
deletedCount++;
} catch (error) {
console.error(` ❌ Failed to delete ${file.Key}:`, error.message);
}
}
console.log(`\n✅ Deleted ${deletedCount} test files`);
console.log(`✅ Preserved ${realFiles.length} real documents\n`);
console.log('📂 Remaining real documents:');
realFiles.forEach(file => {
const filename = file.Key.split('/').pop();
const sizeMB = (file.Size / 1024 / 1024).toFixed(2);
console.log(` - ${filename} (${sizeMB} MB)`);
});
} catch (error) {
console.error('❌ Error:', error);
throw error;
}
}
deleteTestDocuments()
.then(() => {
console.log('\n✅ Script completed successfully');
process.exit(0);
})
.catch(error => {
console.error('\n❌ Script failed:', error);
process.exit(1);
});

View File

@ -1,42 +0,0 @@
#!/usr/bin/env node
/**
* Script to fix TypeScript imports in domain/services
* Replace relative paths with path aliases
*/
const fs = require('fs');
const path = require('path');
function fixImportsInFile(filePath) {
const content = fs.readFileSync(filePath, 'utf8');
let modified = content;
// Replace relative imports to ../ports/ with @domain/ports/
modified = modified.replace(/from ['"]\.\.\/ports\//g, "from '@domain/ports/");
modified = modified.replace(/import\s+(['"])\.\.\/ports\//g, 'import $1@domain/ports/');
if (modified !== content) {
fs.writeFileSync(filePath, modified, 'utf8');
return true;
}
return false;
}
const servicesDir = path.join(__dirname, 'src/domain/services');
console.log('🔧 Fixing domain/services imports...\n');
const files = fs.readdirSync(servicesDir);
let count = 0;
for (const file of files) {
if (file.endsWith('.ts')) {
const filePath = path.join(servicesDir, file);
if (fixImportsInFile(filePath)) {
console.log(`✅ Fixed: ${filePath}`);
count++;
}
}
}
console.log(`\n✅ Fixed ${count} files in domain/services`);

View File

@ -1,90 +0,0 @@
/**
* Script to fix dummy storage URLs in the database
*
* This script updates all document URLs from "dummy-storage.com" to proper MinIO URLs
*/
const { Client } = require('pg');
require('dotenv').config();
const MINIO_ENDPOINT = process.env.AWS_S3_ENDPOINT || 'http://localhost:9000';
const BUCKET_NAME = 'xpeditis-documents';
async function fixDummyUrls() {
const client = new Client({
host: process.env.DATABASE_HOST || 'localhost',
port: process.env.DATABASE_PORT || 5432,
user: process.env.DATABASE_USER || 'xpeditis',
password: process.env.DATABASE_PASSWORD || 'xpeditis_dev_password',
database: process.env.DATABASE_NAME || 'xpeditis_dev',
});
try {
await client.connect();
console.log('✅ Connected to database');
// Get all CSV bookings with documents
const result = await client.query(
`SELECT id, documents FROM csv_bookings WHERE documents IS NOT NULL AND documents::text LIKE '%dummy-storage%'`
);
console.log(`\n📄 Found ${result.rows.length} bookings with dummy URLs\n`);
let updatedCount = 0;
for (const row of result.rows) {
const bookingId = row.id;
const documents = row.documents;
// Update each document URL
const updatedDocuments = documents.map(doc => {
if (doc.filePath && doc.filePath.includes('dummy-storage')) {
// Extract filename from dummy URL
const fileName = doc.fileName || doc.filePath.split('/').pop();
const documentId = doc.id;
// Build proper MinIO URL
const newUrl = `${MINIO_ENDPOINT}/${BUCKET_NAME}/csv-bookings/${bookingId}/${documentId}-${fileName}`;
console.log(` Old: ${doc.filePath}`);
console.log(` New: ${newUrl}`);
return {
...doc,
filePath: newUrl,
};
}
return doc;
});
// Update the database
await client.query(`UPDATE csv_bookings SET documents = $1 WHERE id = $2`, [
JSON.stringify(updatedDocuments),
bookingId,
]);
updatedCount++;
console.log(`✅ Updated booking ${bookingId}\n`);
}
console.log(`\n🎉 Successfully updated ${updatedCount} bookings`);
console.log(`\n⚠️ Note: The actual files need to be uploaded to MinIO at the correct paths.`);
console.log(` You can upload test files or re-create the bookings with real file uploads.`);
} catch (error) {
console.error('❌ Error:', error);
throw error;
} finally {
await client.end();
console.log('\n👋 Disconnected from database');
}
}
fixDummyUrls()
.then(() => {
console.log('\n✅ Script completed successfully');
process.exit(0);
})
.catch(error => {
console.error('\n❌ Script failed:', error);
process.exit(1);
});

View File

@ -1,68 +0,0 @@
#!/usr/bin/env node
/**
* Script to fix TypeScript imports from relative paths to path aliases
*
* Replaces:
* - from '../../domain/...' → from '@domain/...'
* - from '../../../domain/...' → from '@domain/...'
* - from '../domain/...' → from '@domain/...'
* - from '../../../../domain/...' → from '@domain/...'
*/
const fs = require('fs');
const path = require('path');
function fixImportsInFile(filePath) {
const content = fs.readFileSync(filePath, 'utf8');
let modified = content;
// Replace all variations of relative domain imports with @domain alias
modified = modified.replace(/from ['"]\.\.\/\.\.\/\.\.\/\.\.\/domain\//g, "from '@domain/");
modified = modified.replace(/from ['"]\.\.\/\.\.\/\.\.\/domain\//g, "from '@domain/");
modified = modified.replace(/from ['"]\.\.\/\.\.\/domain\//g, "from '@domain/");
modified = modified.replace(/from ['"]\.\.\/domain\//g, "from '@domain/");
// Also fix import statements (not just from)
modified = modified.replace(
/import\s+(['"])\.\.\/\.\.\/\.\.\/\.\.\/domain\//g,
'import $1@domain/'
);
modified = modified.replace(/import\s+(['"])\.\.\/\.\.\/\.\.\/domain\//g, 'import $1@domain/');
modified = modified.replace(/import\s+(['"])\.\.\/\.\.\/domain\//g, 'import $1@domain/');
modified = modified.replace(/import\s+(['"])\.\.\/domain\//g, 'import $1@domain/');
if (modified !== content) {
fs.writeFileSync(filePath, modified, 'utf8');
return true;
}
return false;
}
function walkDir(dir) {
const files = fs.readdirSync(dir);
let count = 0;
for (const file of files) {
const filePath = path.join(dir, file);
const stat = fs.statSync(filePath);
if (stat.isDirectory()) {
count += walkDir(filePath);
} else if (file.endsWith('.ts')) {
if (fixImportsInFile(filePath)) {
console.log(`✅ Fixed: ${filePath}`);
count++;
}
}
}
return count;
}
const srcDir = path.join(__dirname, 'src');
console.log('🔧 Fixing TypeScript imports...\n');
const count = walkDir(srcDir);
console.log(`\n✅ Fixed ${count} files`);

View File

@ -1,81 +0,0 @@
/**
* Script to fix minio hostname in document URLs
*
* Changes http://minio:9000 to http://localhost:9000
*/
const { Client } = require('pg');
require('dotenv').config();
async function fixMinioHostname() {
const client = new Client({
host: process.env.DATABASE_HOST || 'localhost',
port: process.env.DATABASE_PORT || 5432,
user: process.env.DATABASE_USER || 'xpeditis',
password: process.env.DATABASE_PASSWORD || 'xpeditis_dev_password',
database: process.env.DATABASE_NAME || 'xpeditis_dev',
});
try {
await client.connect();
console.log('✅ Connected to database');
// Find bookings with minio:9000 in URLs
const result = await client.query(
`SELECT id, documents FROM csv_bookings WHERE documents::text LIKE '%http://minio:9000%'`
);
console.log(`\n📄 Found ${result.rows.length} bookings with minio hostname\n`);
let updatedCount = 0;
for (const row of result.rows) {
const bookingId = row.id;
const documents = row.documents;
// Update each document URL
const updatedDocuments = documents.map(doc => {
if (doc.filePath && doc.filePath.includes('http://minio:9000')) {
const newUrl = doc.filePath.replace('http://minio:9000', 'http://localhost:9000');
console.log(` Booking: ${bookingId}`);
console.log(` Old: ${doc.filePath}`);
console.log(` New: ${newUrl}\n`);
return {
...doc,
filePath: newUrl,
};
}
return doc;
});
// Update the database
await client.query(`UPDATE csv_bookings SET documents = $1 WHERE id = $2`, [
JSON.stringify(updatedDocuments),
bookingId,
]);
updatedCount++;
console.log(`✅ Updated booking ${bookingId}\n`);
}
console.log(`\n🎉 Successfully updated ${updatedCount} bookings`);
} catch (error) {
console.error('❌ Error:', error);
throw error;
} finally {
await client.end();
console.log('\n👋 Disconnected from database');
}
}
fixMinioHostname()
.then(() => {
console.log('\n✅ Script completed successfully');
process.exit(0);
})
.catch(error => {
console.error('\n❌ Script failed:', error);
process.exit(1);
});

View File

@ -1,182 +0,0 @@
/**
* Script to restore document references in database from MinIO files
*
* Scans MinIO for existing files and creates/updates database references
*/
const { S3Client, ListObjectsV2Command, HeadObjectCommand } = require('@aws-sdk/client-s3');
const { Client } = require('pg');
const { v4: uuidv4 } = require('uuid');
require('dotenv').config();
const MINIO_ENDPOINT = process.env.AWS_S3_ENDPOINT || 'http://localhost:9000';
const BUCKET_NAME = 'xpeditis-documents';
// Initialize MinIO client
const s3Client = new S3Client({
region: 'us-east-1',
endpoint: MINIO_ENDPOINT,
credentials: {
accessKeyId: process.env.AWS_ACCESS_KEY_ID || 'minioadmin',
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY || 'minioadmin',
},
forcePathStyle: true,
});
async function restoreDocumentReferences() {
const pgClient = new Client({
host: process.env.DATABASE_HOST || 'localhost',
port: process.env.DATABASE_PORT || 5432,
user: process.env.DATABASE_USER || 'xpeditis',
password: process.env.DATABASE_PASSWORD || 'xpeditis_dev_password',
database: process.env.DATABASE_NAME || 'xpeditis_dev',
});
try {
await pgClient.connect();
console.log('✅ Connected to database\n');
// Get all MinIO files
console.log('📋 Listing files in MinIO...');
let allFiles = [];
let continuationToken = null;
do {
const command = new ListObjectsV2Command({
Bucket: BUCKET_NAME,
ContinuationToken: continuationToken,
});
const response = await s3Client.send(command);
if (response.Contents) {
allFiles = allFiles.concat(response.Contents);
}
continuationToken = response.NextContinuationToken;
} while (continuationToken);
console.log(` Found ${allFiles.length} files in MinIO\n`);
// Group files by booking ID
const filesByBooking = {};
allFiles.forEach(file => {
const parts = file.Key.split('/');
if (parts.length >= 3 && parts[0] === 'csv-bookings') {
const bookingId = parts[1];
const documentId = parts[2].split('-')[0]; // Extract UUID from filename
const fileName = parts[2].substring(37); // Remove UUID prefix (36 chars + dash)
if (!filesByBooking[bookingId]) {
filesByBooking[bookingId] = [];
}
filesByBooking[bookingId].push({
key: file.Key,
documentId: documentId,
fileName: fileName,
size: file.Size,
lastModified: file.LastModified,
});
}
});
console.log(`📦 Found files for ${Object.keys(filesByBooking).length} bookings\n`);
let updatedCount = 0;
let createdDocsCount = 0;
for (const [bookingId, files] of Object.entries(filesByBooking)) {
// Check if booking exists
const bookingResult = await pgClient.query(
'SELECT id, documents FROM csv_bookings WHERE id = $1',
[bookingId]
);
if (bookingResult.rows.length === 0) {
console.log(`⚠️ Booking not found: ${bookingId.substring(0, 8)}... (skipping)`);
continue;
}
const booking = bookingResult.rows[0];
const existingDocs = booking.documents || [];
console.log(`\n📦 Booking: ${bookingId.substring(0, 8)}...`);
console.log(` Existing documents in DB: ${existingDocs.length}`);
console.log(` Files in MinIO: ${files.length}`);
// Create document references for files
const newDocuments = files.map(file => {
// Determine MIME type from file extension
const ext = file.fileName.split('.').pop().toLowerCase();
const mimeTypeMap = {
pdf: 'application/pdf',
png: 'image/png',
jpg: 'image/jpeg',
jpeg: 'image/jpeg',
txt: 'text/plain',
};
const mimeType = mimeTypeMap[ext] || 'application/octet-stream';
// Determine document type
let docType = 'OTHER';
if (
file.fileName.toLowerCase().includes('bill-of-lading') ||
file.fileName.toLowerCase().includes('bol')
) {
docType = 'BILL_OF_LADING';
} else if (file.fileName.toLowerCase().includes('packing-list')) {
docType = 'PACKING_LIST';
} else if (
file.fileName.toLowerCase().includes('commercial-invoice') ||
file.fileName.toLowerCase().includes('invoice')
) {
docType = 'COMMERCIAL_INVOICE';
}
const doc = {
id: file.documentId,
type: docType,
fileName: file.fileName,
filePath: `${MINIO_ENDPOINT}/${BUCKET_NAME}/${file.key}`,
mimeType: mimeType,
size: file.size,
uploadedAt: file.lastModified.toISOString(),
};
console.log(` ✅ ${file.fileName} (${(file.size / 1024).toFixed(2)} KB)`);
return doc;
});
// Update the booking with new document references
await pgClient.query('UPDATE csv_bookings SET documents = $1 WHERE id = $2', [
JSON.stringify(newDocuments),
bookingId,
]);
updatedCount++;
createdDocsCount += newDocuments.length;
}
console.log(`\n📊 Summary:`);
console.log(` Bookings updated: ${updatedCount}`);
console.log(` Document references created: ${createdDocsCount}`);
console.log(`\n✅ Document references restored`);
} catch (error) {
console.error('❌ Error:', error);
throw error;
} finally {
await pgClient.end();
console.log('\n👋 Disconnected from database');
}
}
restoreDocumentReferences()
.then(() => {
console.log('\n✅ Script completed successfully');
process.exit(0);
})
.catch(error => {
console.error('\n❌ Script failed:', error);
process.exit(1);
});

View File

@ -1,154 +0,0 @@
/**
* Script to sync database with MinIO
*
* Removes document references from database for files that no longer exist in MinIO
*/
const { S3Client, ListObjectsV2Command, HeadObjectCommand } = require('@aws-sdk/client-s3');
const { Client } = require('pg');
require('dotenv').config();
const MINIO_ENDPOINT = process.env.AWS_S3_ENDPOINT || 'http://localhost:9000';
const BUCKET_NAME = 'xpeditis-documents';
// Initialize MinIO client
const s3Client = new S3Client({
region: 'us-east-1',
endpoint: MINIO_ENDPOINT,
credentials: {
accessKeyId: process.env.AWS_ACCESS_KEY_ID || 'minioadmin',
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY || 'minioadmin',
},
forcePathStyle: true,
});
async function syncDatabase() {
const pgClient = new Client({
host: process.env.DATABASE_HOST || 'localhost',
port: process.env.DATABASE_PORT || 5432,
user: process.env.DATABASE_USER || 'xpeditis',
password: process.env.DATABASE_PASSWORD || 'xpeditis_dev_password',
database: process.env.DATABASE_NAME || 'xpeditis_dev',
});
try {
await pgClient.connect();
console.log('✅ Connected to database\n');
// Get all MinIO files
console.log('📋 Listing files in MinIO...');
let allMinioFiles = [];
let continuationToken = null;
do {
const command = new ListObjectsV2Command({
Bucket: BUCKET_NAME,
ContinuationToken: continuationToken,
});
const response = await s3Client.send(command);
if (response.Contents) {
allMinioFiles = allMinioFiles.concat(response.Contents.map(f => f.Key));
}
continuationToken = response.NextContinuationToken;
} while (continuationToken);
console.log(` Found ${allMinioFiles.length} files in MinIO\n`);
// Create a set for faster lookup
const minioFilesSet = new Set(allMinioFiles);
// Get all bookings with documents
const result = await pgClient.query(
`SELECT id, documents FROM csv_bookings WHERE documents IS NOT NULL AND jsonb_array_length(documents::jsonb) > 0`
);
console.log(`📄 Found ${result.rows.length} bookings with documents in database\n`);
let updatedCount = 0;
let removedDocsCount = 0;
let emptyBookingsCount = 0;
for (const row of result.rows) {
const bookingId = row.id;
const documents = row.documents;
// Filter documents to keep only those that exist in MinIO
const validDocuments = [];
const missingDocuments = [];
for (const doc of documents) {
if (!doc.filePath) {
missingDocuments.push(doc);
continue;
}
// Extract the S3 key from the URL
try {
const url = new URL(doc.filePath);
const pathname = url.pathname;
// Remove leading slash and bucket name
const key = pathname.substring(1).replace(`${BUCKET_NAME}/`, '');
if (minioFilesSet.has(key)) {
validDocuments.push(doc);
} else {
missingDocuments.push(doc);
}
} catch (error) {
console.error(` ⚠️ Invalid URL for booking ${bookingId}: ${doc.filePath}`);
missingDocuments.push(doc);
}
}
if (missingDocuments.length > 0) {
console.log(`\n📦 Booking: ${bookingId.substring(0, 8)}...`);
console.log(` Total documents: ${documents.length}`);
console.log(` Valid documents: ${validDocuments.length}`);
console.log(` Missing documents: ${missingDocuments.length}`);
missingDocuments.forEach(doc => {
console.log(` ❌ ${doc.fileName || 'Unknown'}`);
});
// Update the database
await pgClient.query(`UPDATE csv_bookings SET documents = $1 WHERE id = $2`, [
JSON.stringify(validDocuments),
bookingId,
]);
updatedCount++;
removedDocsCount += missingDocuments.length;
if (validDocuments.length === 0) {
emptyBookingsCount++;
console.log(` ⚠️ This booking now has NO documents`);
}
}
}
console.log(`\n📊 Summary:`);
console.log(` Bookings updated: ${updatedCount}`);
console.log(` Documents removed from DB: ${removedDocsCount}`);
console.log(` Bookings with no documents: ${emptyBookingsCount}`);
console.log(`\n✅ Database synchronized with MinIO`);
} catch (error) {
console.error('❌ Error:', error);
throw error;
} finally {
await pgClient.end();
console.log('\n👋 Disconnected from database');
}
}
syncDatabase()
.then(() => {
console.log('\n✅ Script completed successfully');
process.exit(0);
})
.catch(error => {
console.error('\n❌ Script failed:', error);
process.exit(1);
});

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

@ -1,127 +0,0 @@
#!/usr/bin/env node
/**
* Construit le corpus de connaissances de l'assistant a partir du wiki du site.
*
* Le wiki n'est pas ecrit en dur dans des pages : son contenu vit dans les
* fichiers de traduction du frontend, sous `dashboard.wikiPages`. C'est donc la
* source de verite, et la meme que celle que lit l'utilisateur — une reponse de
* l'assistant et la page wiki citee ne peuvent pas diverger.
*
* Le corpus est ecrit dans le backend et versionne : l'image backend ne doit
* pas dependre des fichiers du frontend a l'execution.
*
* Usage : npm run knowledge:build
*/
const fs = require('fs');
const path = require('path');
const ROOT = path.resolve(__dirname, '../../../..');
const MESSAGES = path.join(ROOT, 'apps/frontend/messages');
const OUT = path.resolve(__dirname, '../../src/infrastructure/ai/knowledge/wiki-corpus.json');
const LOCALES = ['fr', 'en'];
/** Les cles de mise en page ne portent aucune connaissance. */
const LAYOUT_KEYS = /^(col[A-Z]|.*Title$|.*Label$|backToWiki)/;
/** `documentsTransport` -> `documents-transport`, l'URL de la page wiki. */
const toSlug = key => key.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
const humanize = key =>
key
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
.replace(/^./, c => c.toUpperCase())
.trim();
/**
* Nomme un champ d'objet dans la langue du wiki.
*
* Les cles de traduction sont en anglais (`code`, `name`, `description`) mais
* chaque sujet publie deja ses en-tetes de colonnes (`colCode`, `colName`...) :
* les reutiliser evite d'ecrire « Name: » au milieu d'un fragment francais.
*/
const labelFor = (topic, key) => topic[`col${key[0].toUpperCase()}${key.slice(1)}`] ?? humanize(key);
/** Aplatit une valeur de traduction en lignes lisibles par un modele. */
function toLines(value, topic) {
if (typeof value === 'string') return [value];
if (typeof value === 'number' || typeof value === 'boolean') return [String(value)];
if (Array.isArray(value)) return value.flatMap(item => toLines(item, topic));
if (value && typeof value === 'object') {
// Un objet de table se lit mieux sur une ligne qu'eclate en champs :
// « Code: 40 00 — Nom: Mise en Libre Pratique — Description: ... ».
const entries = Object.entries(value).filter(([, v]) => v !== null && v !== undefined);
const scalars = entries.filter(([, v]) => typeof v === 'string' || typeof v === 'number');
const rest = entries.filter(([, v]) => typeof v === 'object');
const head = scalars.map(([k, v]) => `${labelFor(topic, k)}: ${v}`).join(' — ');
return [
head,
...rest.flatMap(([k, v]) => toLines(v, topic).map(line => `${labelFor(topic, k)}: ${line}`)),
].filter(Boolean);
}
return [];
}
/**
* Un fragment par section du sujet. Une section = un champ de premier niveau,
* intitule par son `*Title` voisin quand il existe. Decouper plus finement
* casserait les tableaux (un Incoterm isole de sa colonne « risque ») ;
* decouper moins finement noierait la reponse sous 4 000 caracteres.
*/
function chunksForTopic(locale, topicKey, topic) {
const title = topic.title ?? humanize(topicKey);
const href = `/dashboard/wiki/${toSlug(topicKey)}`;
const chunks = [];
const header = [topic.title, topic.description].filter(Boolean).join('\n');
if (header) {
chunks.push({ section: title, text: header });
}
for (const [key, value] of Object.entries(topic)) {
if (key === 'title' || key === 'description') continue;
if (LAYOUT_KEYS.test(key)) continue;
const lines = toLines(value, topic).filter(Boolean);
if (!lines.length) continue;
const section = topic[`${key}Title`] ?? humanize(key);
chunks.push({ section, text: `${section}\n${lines.map(line => `- ${line}`).join('\n')}` });
}
return chunks.map((chunk, index) => ({
id: `${locale}:${topicKey}:${index}`,
locale,
topic: topicKey,
title,
section: chunk.section,
href,
text: chunk.text,
}));
}
const documents = [];
for (const locale of LOCALES) {
const file = path.join(MESSAGES, `${locale}.json`);
const wiki = JSON.parse(fs.readFileSync(file, 'utf8')).dashboard?.wikiPages;
if (!wiki) throw new Error(`dashboard.wikiPages introuvable dans ${file}`);
for (const [topicKey, topic] of Object.entries(wiki)) {
// Les libelles partages (`responsibleLabel`...) sont des chaines, pas des sujets.
if (!topic || typeof topic !== 'object' || Array.isArray(topic)) continue;
documents.push(...chunksForTopic(locale, topicKey, topic));
}
}
fs.mkdirSync(path.dirname(OUT), { recursive: true });
fs.writeFileSync(OUT, JSON.stringify({ documents }, null, 2) + '\n');
const byLocale = LOCALES.map(l => `${l}: ${documents.filter(d => d.locale === l).length}`).join(', ');
const chars = documents.reduce((sum, d) => sum + d.text.length, 0);
console.log(`${documents.length} fragments (${byLocale}) — ${chars} caracteres`);
console.log(`écrit dans ${path.relative(ROOT, OUT)}`);

View File

@ -1,132 +0,0 @@
#!/usr/bin/env node
/**
* Génère un hash Argon2id pour BOOTSTRAP_ADMIN_PASSWORD_HASH.
*
* cd apps/backend && node scripts/setup/generate-admin-hash.js
*
* Le mot de passe est saisi sans écho et ne quitte jamais votre poste : ni
* argument de ligne de commande (visible dans `ps` et dans l'historique du
* shell), ni variable d'environnement, ni fichier temporaire.
*
* Le hash est appliqué à CHAQUE lancement du backend (AdminBootstrapService) :
* - au compte BOOTSTRAP_ADMIN_EMAIL s'il ne s'est encore jamais connecté ;
* - à tout compte si BOOTSTRAP_ADMIN_RESET_PASSWORD=true (retirez ensuite
* les deux variables, sinon un mot de passe changé depuis l'interface
* serait remplacé au lancement suivant).
*
* 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';
const argon2 = require('argon2');
const readline = require('readline');
// Mêmes paramètres que auth.service.ts : un hash produit ici est vérifiable
// par l'application sans aucune adaptation.
const ARGON2_OPTIONS = {
type: argon2.argon2id,
memoryCost: 65536, // 64 Mo
timeCost: 3,
parallelism: 4,
};
const MIN_LENGTH = 16;
/** 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 = () => {
// Réécrit la ligne sans révéler la longueur de la saisie.
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 checkStrength(password) {
const problems = [];
if (password.length < MIN_LENGTH) {
problems.push(`au moins ${MIN_LENGTH} caractères (${password.length} fournis)`);
}
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');
if (!/[^A-Za-z0-9]/.test(password)) problems.push('un caractère spécial');
return problems;
}
async function main() {
console.log('');
console.log('Génération du hash Argon2id pour le premier administrateur.');
console.log('La saisie n’est pas affichée.');
console.log('');
const password = await readSecret('Mot de passe : ');
if (!password) {
console.error('Aucun mot de passe saisi.');
process.exit(1);
}
if (process.stdin.isTTY) {
const confirmation = await readSecret('Confirmation : ');
if (confirmation !== password) {
console.error('Les deux saisies diffèrent.');
process.exit(1);
}
}
const problems = checkStrength(password);
if (problems.length > 0) {
console.error('');
console.error('Mot de passe refusé. Il manque : ' + problems.join(', ') + '.');
console.error('Ce compte a tous les droits sur la plateforme : générez plutôt une');
console.error('phrase longue et aléatoire depuis votre gestionnaire de mots de passe.');
process.exit(1);
}
const hash = await argon2.hash(password, ARGON2_OPTIONS);
console.log('');
console.log('Hash à placer dans le Secret Kubernetes (jamais dans le ConfigMap) :');
console.log('');
console.log(' BOOTSTRAP_ADMIN_PASSWORD_HASH: ' + JSON.stringify(hash));
console.log('');
console.log(' cd infra/prod && sops k8s/base/03-secrets.sops.yaml');
console.log('');
console.log('Après votre première connexion :');
console.log(' 1. changez le mot de passe depuis l’interface ;');
console.log(' 2. retirez BOOTSTRAP_ADMIN_PASSWORD_HASH du Secret et réappliquez.');
console.log('');
console.log('Un hash reste attaquable hors ligne : il n’a plus aucune raison');
console.log('de rester stocké une fois le compte opérationnel.');
console.log('');
}
main().catch(error => {
console.error('Échec :', error.message);
process.exit(1);
});

View File

@ -1,14 +0,0 @@
const argon2 = require('argon2');
async function generateHash() {
const hash = await argon2.hash('Password123!', {
type: argon2.argon2id,
memoryCost: 65536, // 64 MB
timeCost: 3,
parallelism: 4,
});
console.log('Argon2id hash for "Password123!":');
console.log(hash);
}
generateHash().catch(console.error);

View File

@ -1,367 +0,0 @@
/**
* Script to generate ports seed migration from sea-ports JSON data
*
* Data source: https://github.com/marchah/sea-ports
* License: MIT
*
* This script:
* 1. Reads sea-ports.json from /tmp
* 2. Parses and validates port data
* 3. Generates SQL INSERT statements
* 4. Creates a TypeORM migration file
*/
import * as fs from 'fs';
import * as path from 'path';
interface SeaPort {
name: string;
city: string;
country: string;
coordinates: [number, number]; // [longitude, latitude]
province?: string;
timezone?: string;
unlocs: string[];
code?: string;
alias?: string[];
regions?: string[];
}
interface SeaPortsData {
[locode: string]: SeaPort;
}
interface ParsedPort {
code: string;
name: string;
city: string;
country: string;
countryName: string;
countryCode: string;
latitude: number;
longitude: number;
timezone: string | null;
isActive: boolean;
}
// Country code to name mapping (ISO 3166-1 alpha-2)
const countryNames: { [key: string]: string } = {
AE: 'United Arab Emirates',
AG: 'Antigua and Barbuda',
AL: 'Albania',
AM: 'Armenia',
AO: 'Angola',
AR: 'Argentina',
AT: 'Austria',
AU: 'Australia',
AZ: 'Azerbaijan',
BA: 'Bosnia and Herzegovina',
BB: 'Barbados',
BD: 'Bangladesh',
BE: 'Belgium',
BG: 'Bulgaria',
BH: 'Bahrain',
BN: 'Brunei',
BR: 'Brazil',
BS: 'Bahamas',
BZ: 'Belize',
CA: 'Canada',
CH: 'Switzerland',
CI: 'Ivory Coast',
CL: 'Chile',
CM: 'Cameroon',
CN: 'China',
CO: 'Colombia',
CR: 'Costa Rica',
CU: 'Cuba',
CY: 'Cyprus',
CZ: 'Czech Republic',
DE: 'Germany',
DJ: 'Djibouti',
DK: 'Denmark',
DO: 'Dominican Republic',
DZ: 'Algeria',
EC: 'Ecuador',
EE: 'Estonia',
EG: 'Egypt',
ES: 'Spain',
FI: 'Finland',
FJ: 'Fiji',
FR: 'France',
GA: 'Gabon',
GB: 'United Kingdom',
GE: 'Georgia',
GH: 'Ghana',
GI: 'Gibraltar',
GR: 'Greece',
GT: 'Guatemala',
GY: 'Guyana',
HK: 'Hong Kong',
HN: 'Honduras',
HR: 'Croatia',
HT: 'Haiti',
HU: 'Hungary',
ID: 'Indonesia',
IE: 'Ireland',
IL: 'Israel',
IN: 'India',
IQ: 'Iraq',
IR: 'Iran',
IS: 'Iceland',
IT: 'Italy',
JM: 'Jamaica',
JO: 'Jordan',
JP: 'Japan',
KE: 'Kenya',
KH: 'Cambodia',
KR: 'South Korea',
KW: 'Kuwait',
KZ: 'Kazakhstan',
LB: 'Lebanon',
LK: 'Sri Lanka',
LR: 'Liberia',
LT: 'Lithuania',
LV: 'Latvia',
LY: 'Libya',
MA: 'Morocco',
MC: 'Monaco',
MD: 'Moldova',
ME: 'Montenegro',
MG: 'Madagascar',
MK: 'North Macedonia',
MM: 'Myanmar',
MN: 'Mongolia',
MO: 'Macau',
MR: 'Mauritania',
MT: 'Malta',
MU: 'Mauritius',
MV: 'Maldives',
MX: 'Mexico',
MY: 'Malaysia',
MZ: 'Mozambique',
NA: 'Namibia',
NG: 'Nigeria',
NI: 'Nicaragua',
NL: 'Netherlands',
NO: 'Norway',
NZ: 'New Zealand',
OM: 'Oman',
PA: 'Panama',
PE: 'Peru',
PG: 'Papua New Guinea',
PH: 'Philippines',
PK: 'Pakistan',
PL: 'Poland',
PR: 'Puerto Rico',
PT: 'Portugal',
PY: 'Paraguay',
QA: 'Qatar',
RO: 'Romania',
RS: 'Serbia',
RU: 'Russia',
SA: 'Saudi Arabia',
SD: 'Sudan',
SE: 'Sweden',
SG: 'Singapore',
SI: 'Slovenia',
SK: 'Slovakia',
SN: 'Senegal',
SO: 'Somalia',
SR: 'Suriname',
SY: 'Syria',
TH: 'Thailand',
TN: 'Tunisia',
TR: 'Turkey',
TT: 'Trinidad and Tobago',
TW: 'Taiwan',
TZ: 'Tanzania',
UA: 'Ukraine',
UG: 'Uganda',
US: 'United States',
UY: 'Uruguay',
VE: 'Venezuela',
VN: 'Vietnam',
YE: 'Yemen',
ZA: 'South Africa',
};
function parseSeaPorts(filePath: string): ParsedPort[] {
const jsonData = fs.readFileSync(filePath, 'utf-8');
const seaPorts: SeaPortsData = JSON.parse(jsonData);
const parsedPorts: ParsedPort[] = [];
let skipped = 0;
for (const [locode, port] of Object.entries(seaPorts)) {
// Validate required fields
if (!port.name || !port.coordinates || port.coordinates.length !== 2) {
skipped++;
continue;
}
// Extract country code from UN/LOCODE (first 2 characters)
const countryCode = locode.substring(0, 2).toUpperCase();
// Skip if invalid country code
if (!countryNames[countryCode]) {
skipped++;
continue;
}
// Validate coordinates
const [longitude, latitude] = port.coordinates;
if (latitude < -90 || latitude > 90 || longitude < -180 || longitude > 180) {
skipped++;
continue;
}
parsedPorts.push({
code: locode.toUpperCase(),
name: port.name.trim(),
city: port.city?.trim() || port.name.trim(),
country: countryCode,
countryName: countryNames[countryCode] || port.country,
countryCode: countryCode,
latitude: Number(latitude.toFixed(6)),
longitude: Number(longitude.toFixed(6)),
timezone: port.timezone || null,
isActive: true,
});
}
console.log(`✅ Parsed ${parsedPorts.length} ports`);
console.log(`⚠️ Skipped ${skipped} invalid entries`);
return parsedPorts;
}
function generateSQLInserts(ports: ParsedPort[]): string {
const batchSize = 100;
const batches: string[] = [];
for (let i = 0; i < ports.length; i += batchSize) {
const batch = ports.slice(i, i + batchSize);
const values = batch
.map(port => {
const name = port.name.replace(/'/g, "''");
const city = port.city.replace(/'/g, "''");
const countryName = port.countryName.replace(/'/g, "''");
const timezone = port.timezone ? `'${port.timezone}'` : 'NULL';
return `(
'${port.code}',
'${name}',
'${city}',
'${port.country}',
'${countryName}',
${port.latitude},
${port.longitude},
${timezone},
${port.isActive}
)`;
})
.join(',\n ');
batches.push(`
// Batch ${Math.floor(i / batchSize) + 1}/${Math.ceil(ports.length / batchSize)} (${batch.length} ports)
await queryRunner.query(\`
INSERT INTO ports (code, name, city, country, country_name, latitude, longitude, timezone, is_active)
VALUES ${values}
\`);
`);
}
return batches.join('\n');
}
function generateMigration(ports: ParsedPort[]): string {
const timestamp = Date.now();
const className = `SeedPorts${timestamp}`;
const sqlInserts = generateSQLInserts(ports);
const migrationContent = `/**
* Migration: Seed Ports Table
*
* Source: sea-ports (https://github.com/marchah/sea-ports)
* License: MIT
* Generated: ${new Date().toISOString()}
* Total ports: ${ports.length}
*/
import { MigrationInterface, QueryRunner } from 'typeorm';
export class ${className} implements MigrationInterface {
name = '${className}';
public async up(queryRunner: QueryRunner): Promise<void> {
console.log('Seeding ${ports.length} maritime ports...');
${sqlInserts}
console.log('✅ Successfully seeded ${ports.length} ports');
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(\`TRUNCATE TABLE ports RESTART IDENTITY CASCADE\`);
console.log('🗑️ Cleared all ports');
}
}
`;
return migrationContent;
}
async function main() {
const seaPortsPath = '/tmp/sea-ports.json';
console.log('🚢 Generating Ports Seed Migration\n');
// Check if sea-ports.json exists
if (!fs.existsSync(seaPortsPath)) {
console.error('❌ Error: /tmp/sea-ports.json not found!');
console.log('Please download it first:');
console.log(
'curl -o /tmp/sea-ports.json https://raw.githubusercontent.com/marchah/sea-ports/master/lib/ports.json'
);
process.exit(1);
}
// Parse ports
console.log('📖 Parsing sea-ports.json...');
const ports = parseSeaPorts(seaPortsPath);
// Sort by country, then by name
ports.sort((a, b) => {
if (a.country !== b.country) {
return a.country.localeCompare(b.country);
}
return a.name.localeCompare(b.name);
});
// Generate migration
console.log('\n📝 Generating migration file...');
const migrationContent = generateMigration(ports);
// Write migration file
const migrationsDir = path.join(
__dirname,
'../src/infrastructure/persistence/typeorm/migrations'
);
const timestamp = Date.now();
const fileName = `${timestamp}-SeedPorts.ts`;
const filePath = path.join(migrationsDir, fileName);
fs.writeFileSync(filePath, migrationContent, 'utf-8');
console.log(`\n✅ Migration created: ${fileName}`);
console.log(`📍 Location: ${filePath}`);
console.log(`\n📊 Summary:`);
console.log(` - Total ports: ${ports.length}`);
console.log(` - Countries: ${new Set(ports.map(p => p.country)).size}`);
console.log(` - Ports with timezone: ${ports.filter(p => p.timezone).length}`);
console.log(`\n🚀 Run the migration:`);
console.log(` cd apps/backend`);
console.log(` npm run migration:run`);
}
main().catch(console.error);

View File

@ -1,92 +0,0 @@
/**
* Script to list all files in MinIO xpeditis-documents bucket
*/
const { S3Client, ListObjectsV2Command } = require('@aws-sdk/client-s3');
require('dotenv').config();
const MINIO_ENDPOINT = process.env.AWS_S3_ENDPOINT || 'http://localhost:9000';
const BUCKET_NAME = 'xpeditis-documents';
// Initialize MinIO client
const s3Client = new S3Client({
region: 'us-east-1',
endpoint: MINIO_ENDPOINT,
credentials: {
accessKeyId: process.env.AWS_ACCESS_KEY_ID || 'minioadmin',
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY || 'minioadmin',
},
forcePathStyle: true,
});
async function listFiles() {
try {
console.log(`📋 Listing all files in bucket: ${BUCKET_NAME}\n`);
let allFiles = [];
let continuationToken = null;
do {
const command = new ListObjectsV2Command({
Bucket: BUCKET_NAME,
ContinuationToken: continuationToken,
});
const response = await s3Client.send(command);
if (response.Contents) {
allFiles = allFiles.concat(response.Contents);
}
continuationToken = response.NextContinuationToken;
} while (continuationToken);
console.log(`Found ${allFiles.length} files total:\n`);
// Group by booking ID
const byBooking = {};
allFiles.forEach(file => {
const parts = file.Key.split('/');
if (parts.length >= 3 && parts[0] === 'csv-bookings') {
const bookingId = parts[1];
if (!byBooking[bookingId]) {
byBooking[bookingId] = [];
}
byBooking[bookingId].push({
key: file.Key,
size: file.Size,
lastModified: file.LastModified,
});
} else {
console.log(` Other: ${file.Key} (${file.Size} bytes)`);
}
});
console.log(`\nFiles grouped by booking:\n`);
Object.entries(byBooking).forEach(([bookingId, files]) => {
console.log(`📦 Booking: ${bookingId.substring(0, 8)}...`);
files.forEach(file => {
const filename = file.key.split('/').pop();
console.log(` - ${filename} (${file.size} bytes) - ${file.lastModified}`);
});
console.log('');
});
console.log(`\n📊 Summary:`);
console.log(` Total files: ${allFiles.length}`);
console.log(` Bookings with files: ${Object.keys(byBooking).length}`);
} catch (error) {
console.error('❌ Error:', error);
throw error;
}
}
listFiles()
.then(() => {
console.log('\n✅ Script completed successfully');
process.exit(0);
})
.catch(error => {
console.error('\n❌ Script failed:', error);
process.exit(1);
});

View File

@ -1,57 +0,0 @@
/**
* Script to list all Stripe prices
* Run with: node scripts/list-stripe-prices.js
*/
const Stripe = require('stripe');
if (!process.env.STRIPE_SECRET_KEY) {
throw new Error('STRIPE_SECRET_KEY is required');
}
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
async function listPrices() {
console.log('Fetching Stripe prices...\n');
try {
const prices = await stripe.prices.list({ limit: 50, expand: ['data.product'] });
if (prices.data.length === 0) {
console.log('No prices found. You need to create prices in Stripe Dashboard.');
console.log('\nSteps:');
console.log('1. Go to https://dashboard.stripe.com/products');
console.log('2. Click on each product (Starter, Pro, Enterprise)');
console.log('3. Add a recurring price (monthly and yearly)');
console.log('4. Copy the Price IDs (format: price_xxxxx)');
return;
}
console.log('Available Prices:\n');
console.log('='.repeat(100));
for (const price of prices.data) {
const product = typeof price.product === 'object' ? price.product : { name: price.product };
const interval = price.recurring ? `${price.recurring.interval}ly` : 'one-time';
const amount = (price.unit_amount / 100).toFixed(2);
console.log(`Price ID: ${price.id}`);
console.log(`Product: ${product.name || product.id}`);
console.log(`Amount: ${amount} ${price.currency.toUpperCase()}`);
console.log(`Interval: ${interval}`);
console.log(`Active: ${price.active}`);
console.log('-'.repeat(100));
}
console.log('\n\nCopy the relevant Price IDs to your .env file:');
console.log('STRIPE_STARTER_MONTHLY_PRICE_ID=price_xxxxx');
console.log('STRIPE_STARTER_YEARLY_PRICE_ID=price_xxxxx');
console.log('STRIPE_PRO_MONTHLY_PRICE_ID=price_xxxxx');
console.log('STRIPE_PRO_YEARLY_PRICE_ID=price_xxxxx');
console.log('STRIPE_ENTERPRISE_MONTHLY_PRICE_ID=price_xxxxx');
console.log('STRIPE_ENTERPRISE_YEARLY_PRICE_ID=price_xxxxx');
} catch (error) {
console.error('Error fetching prices:', error.message);
}
}
listPrices();

View File

@ -1,63 +0,0 @@
const { DataSource } = require('typeorm');
const path = require('path');
const { existsSync } = require('fs');
const applicationRoot = existsSync(path.join(__dirname, 'dist'))
? __dirname
: path.resolve(__dirname, '../..');
const { databaseTlsOptions } = require(
path.join(applicationRoot, 'dist/infrastructure/persistence/typeorm/database-tls')
);
const { SafeDatabaseLogger } = require(
path.join(applicationRoot, 'dist/infrastructure/persistence/typeorm/safe-database-logger')
);
const AppDataSource = new DataSource({
type: 'postgres',
host: process.env.DATABASE_HOST,
port: parseInt(process.env.DATABASE_PORT, 10),
username: process.env.DATABASE_USER,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE_NAME,
ssl: databaseTlsOptions(
process.env.DATABASE_SSL,
process.env.DATABASE_SSL_CA,
process.env.DATABASE_HOST
),
entities: [path.join(applicationRoot, 'dist/**/*.orm-entity.js')],
migrations: [
path.join(applicationRoot, 'dist/infrastructure/persistence/typeorm/migrations/*.js'),
],
synchronize: false,
logging: true,
logger: new SafeDatabaseLogger(true),
migrationsTransactionMode: 'all',
});
console.log('🚀 Starting Xpeditis Backend Migration Script...');
console.log('📦 Initializing DataSource...');
AppDataSource.initialize()
.then(async () => {
console.log('✅ DataSource initialized successfully');
console.log('🔄 Running pending migrations...');
const migrations = await AppDataSource.runMigrations();
if (migrations.length === 0) {
console.log('✅ No pending migrations');
} else {
console.log(`✅ Successfully ran ${migrations.length} migration(s):`);
migrations.forEach(migration => {
console.log(` - ${migration.name}`);
});
}
await AppDataSource.destroy();
console.log('✅ Database migrations completed successfully');
process.exit(0);
})
.catch(error => {
console.error('❌ Error during migration:');
console.error('Check migration prerequisites and database availability.');
process.exit(1);
});

View File

@ -1,79 +0,0 @@
/**
* Script to set MinIO bucket policy for public read access
*
* This allows documents to be downloaded directly via URL without authentication
*/
const { S3Client, PutBucketPolicyCommand, GetBucketPolicyCommand } = require('@aws-sdk/client-s3');
require('dotenv').config();
const MINIO_ENDPOINT = process.env.AWS_S3_ENDPOINT || 'http://localhost:9000';
const BUCKET_NAME = 'xpeditis-documents';
// Initialize MinIO client
const s3Client = new S3Client({
region: 'us-east-1',
endpoint: MINIO_ENDPOINT,
credentials: {
accessKeyId: process.env.AWS_ACCESS_KEY_ID || 'minioadmin',
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY || 'minioadmin',
},
forcePathStyle: true,
});
async function setBucketPolicy() {
try {
// Policy to allow public read access to all objects in the bucket
const policy = {
Version: '2012-10-17',
Statement: [
{
Effect: 'Allow',
Principal: '*',
Action: ['s3:GetObject'],
Resource: [`arn:aws:s3:::${BUCKET_NAME}/*`],
},
],
};
console.log('📋 Setting bucket policy for:', BUCKET_NAME);
console.log('Policy:', JSON.stringify(policy, null, 2));
// Set the bucket policy
await s3Client.send(
new PutBucketPolicyCommand({
Bucket: BUCKET_NAME,
Policy: JSON.stringify(policy),
})
);
console.log('\n✅ Bucket policy set successfully!');
console.log(` All objects in ${BUCKET_NAME} are now publicly readable`);
// Verify the policy was set
console.log('\n🔍 Verifying bucket policy...');
const getPolicy = await s3Client.send(
new GetBucketPolicyCommand({
Bucket: BUCKET_NAME,
})
);
console.log('✅ Current policy:', getPolicy.Policy);
console.log('\n📝 Note: This allows public read access to all documents.');
console.log(' For production, consider using signed URLs instead.');
} catch (error) {
console.error('❌ Error:', error);
throw error;
}
}
setBucketPolicy()
.then(() => {
console.log('\n✅ Script completed successfully');
process.exit(0);
})
.catch(error => {
console.error('\n❌ Script failed:', error);
process.exit(1);
});

View File

@ -1,91 +0,0 @@
#!/usr/bin/env node
/**
* Setup MinIO Bucket
*
* Creates the required bucket for document storage if it doesn't exist
*/
const { S3Client, CreateBucketCommand, HeadBucketCommand } = require('@aws-sdk/client-s3');
require('dotenv').config();
const BUCKET_NAME = 'xpeditis-documents';
// Configure S3 client for MinIO
const s3Client = new S3Client({
region: process.env.AWS_REGION || 'us-east-1',
endpoint: process.env.AWS_S3_ENDPOINT || 'http://localhost:9000',
credentials: {
accessKeyId: process.env.AWS_ACCESS_KEY_ID || 'minioadmin',
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY || 'minioadmin',
},
forcePathStyle: true, // Required for MinIO
});
async function setupBucket() {
console.log('\n🪣 MinIO Bucket Setup');
console.log('==========================================');
console.log(`Bucket name: ${BUCKET_NAME}`);
console.log(`Endpoint: ${process.env.AWS_S3_ENDPOINT || 'http://localhost:9000'}`);
console.log('');
try {
// Check if bucket exists
console.log('📋 Step 1: Checking if bucket exists...');
try {
await s3Client.send(new HeadBucketCommand({ Bucket: BUCKET_NAME }));
console.log(`✅ Bucket '${BUCKET_NAME}' already exists`);
console.log('');
console.log('✅ Setup complete! The bucket is ready to use.');
process.exit(0);
} catch (error) {
if (error.name === 'NotFound' || error.$metadata?.httpStatusCode === 404) {
console.log(`ℹ️ Bucket '${BUCKET_NAME}' does not exist`);
} else {
throw error;
}
}
// Create bucket
console.log('');
console.log('📋 Step 2: Creating bucket...');
await s3Client.send(new CreateBucketCommand({ Bucket: BUCKET_NAME }));
console.log(`✅ Bucket '${BUCKET_NAME}' created successfully!`);
// Verify creation
console.log('');
console.log('📋 Step 3: Verifying bucket...');
await s3Client.send(new HeadBucketCommand({ Bucket: BUCKET_NAME }));
console.log(`✅ Bucket '${BUCKET_NAME}' verified!`);
console.log('');
console.log('==========================================');
console.log('✅ Setup complete! The bucket is ready to use.');
console.log('');
console.log('You can now:');
console.log(' 1. Create CSV bookings via the frontend');
console.log(' 2. Upload documents to this bucket');
console.log(' 3. View files at: http://localhost:9001 (MinIO Console)');
console.log('');
process.exit(0);
} catch (error) {
console.error('');
console.error('❌ ERROR: Failed to setup bucket');
console.error('');
console.error('Error details:');
console.error(` Name: ${error.name}`);
console.error(` Message: ${error.message}`);
if (error.$metadata) {
console.error(` HTTP Status: ${error.$metadata.httpStatusCode}`);
}
console.error('');
console.error('Common solutions:');
console.error(' 1. Check if MinIO is running: docker ps | grep minio');
console.error(' 2. Verify credentials in .env file');
console.error(' 3. Ensure AWS_S3_ENDPOINT is set correctly');
console.error('');
process.exit(1);
}
}
setupBucket();

View File

@ -1,132 +0,0 @@
#!/usr/bin/env node
const { Client } = require('pg');
const { DataSource } = require('typeorm');
const path = require('path');
const { spawn } = require('child_process');
const { existsSync } = require('fs');
// Docker copies this script to /app/startup.js; local copies stay in scripts/setup.
const applicationRoot = existsSync(path.join(__dirname, 'dist'))
? __dirname
: path.resolve(__dirname, '../..');
const { databaseTlsOptions } = require(
path.join(applicationRoot, 'dist/infrastructure/persistence/typeorm/database-tls')
);
const { SafeDatabaseLogger } = require(
path.join(applicationRoot, 'dist/infrastructure/persistence/typeorm/safe-database-logger')
);
async function waitForPostgres(maxAttempts = 30) {
console.log('⏳ Waiting for PostgreSQL to be ready...');
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
const client = new Client({
host: process.env.DATABASE_HOST,
port: parseInt(process.env.DATABASE_PORT, 10),
user: process.env.DATABASE_USER,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE_NAME,
ssl: databaseTlsOptions(
process.env.DATABASE_SSL,
process.env.DATABASE_SSL_CA,
process.env.DATABASE_HOST
),
});
await client.connect();
await client.end();
console.log('✅ PostgreSQL is ready');
return true;
} catch (error) {
console.log(`⏳ Attempt ${attempt}/${maxAttempts} - PostgreSQL not ready, retrying...`);
await new Promise(resolve => setTimeout(resolve, 2000));
}
}
console.error('❌ Failed to connect to PostgreSQL after', maxAttempts, 'attempts');
process.exit(1);
}
async function runMigrations() {
console.log('🔄 Running database migrations...');
const AppDataSource = new DataSource({
type: 'postgres',
host: process.env.DATABASE_HOST,
port: parseInt(process.env.DATABASE_PORT, 10),
username: process.env.DATABASE_USER,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE_NAME,
ssl: databaseTlsOptions(
process.env.DATABASE_SSL,
process.env.DATABASE_SSL_CA,
process.env.DATABASE_HOST
),
entities: [path.join(applicationRoot, 'dist/**/*.orm-entity.js')],
migrations: [
path.join(applicationRoot, 'dist/infrastructure/persistence/typeorm/migrations/*.js'),
],
synchronize: false,
logging: true,
logger: new SafeDatabaseLogger(true),
migrationsTransactionMode: 'all',
});
try {
await AppDataSource.initialize();
console.log('✅ DataSource initialized');
const migrations = await AppDataSource.runMigrations();
if (migrations.length === 0) {
console.log('✅ No pending migrations');
} else {
console.log(`✅ Successfully ran ${migrations.length} migration(s):`);
migrations.forEach(migration => {
console.log(` - ${migration.name}`);
});
}
await AppDataSource.destroy();
console.log('✅ Database migrations completed');
return true;
} catch (error) {
console.error('❌ Migration failed. Check migration prerequisites and database availability.');
process.exit(1);
}
}
function startApplication() {
console.log('🚀 Starting NestJS application...');
const app = spawn('node', ['dist/main'], {
stdio: 'inherit',
env: process.env,
cwd: applicationRoot,
});
app.on('exit', code => {
process.exit(code);
});
process.on('SIGTERM', () => app.kill('SIGTERM'));
process.on('SIGINT', () => app.kill('SIGINT'));
}
async function main() {
console.log('🚀 Starting Xpeditis Backend...');
await waitForPostgres();
await runMigrations();
startApplication();
}
if (require.main === module) {
main().catch(error => {
console.error('❌ Startup failed. Check migration prerequisites and database availability.');
process.exit(1);
});
}
module.exports = { waitForPostgres, runMigrations };

View File

@ -1,185 +0,0 @@
/**
* Script to upload test documents to MinIO
*/
const { S3Client, PutObjectCommand, CreateBucketCommand } = require('@aws-sdk/client-s3');
const { Client: PgClient } = require('pg');
const fs = require('fs');
const path = require('path');
require('dotenv').config();
const MINIO_ENDPOINT = process.env.AWS_S3_ENDPOINT || 'http://localhost:9000';
const BUCKET_NAME = 'xpeditis-documents';
// Initialize MinIO client
const s3Client = new S3Client({
region: 'us-east-1',
endpoint: MINIO_ENDPOINT,
credentials: {
accessKeyId: process.env.AWS_ACCESS_KEY_ID || 'minioadmin',
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY || 'minioadmin',
},
forcePathStyle: true,
});
// Create a simple PDF buffer (minimal valid PDF)
function createTestPDF(title) {
return Buffer.from(
`%PDF-1.4
1 0 obj
<<
/Type /Catalog
/Pages 2 0 R
>>
endobj
2 0 obj
<<
/Type /Pages
/Kids [3 0 R]
/Count 1
>>
endobj
3 0 obj
<<
/Type /Page
/Parent 2 0 R
/MediaBox [0 0 612 792]
/Contents 4 0 R
/Resources <<
/Font <<
/F1 <<
/Type /Font
/Subtype /Type1
/BaseFont /Helvetica
>>
>>
>>
>>
endobj
4 0 obj
<<
/Length 100
>>
stream
BT
/F1 24 Tf
100 700 Td
(${title}) Tj
ET
endstream
endobj
xref
0 5
0000000000 65535 f
0000000009 00000 n
0000000058 00000 n
0000000115 00000 n
0000000300 00000 n
trailer
<<
/Size 5
/Root 1 0 R
>>
startxref
450
%%EOF`,
'utf-8'
);
}
async function uploadTestDocuments() {
const pgClient = new PgClient({
host: process.env.DATABASE_HOST || 'localhost',
port: process.env.DATABASE_PORT || 5432,
user: process.env.DATABASE_USER || 'xpeditis',
password: process.env.DATABASE_PASSWORD || 'xpeditis_dev_password',
database: process.env.DATABASE_NAME || 'xpeditis_dev',
});
try {
// Connect to database
await pgClient.connect();
console.log('✅ Connected to database');
// Create bucket if it doesn't exist
try {
await s3Client.send(new CreateBucketCommand({ Bucket: BUCKET_NAME }));
console.log(`✅ Created bucket: ${BUCKET_NAME}`);
} catch (error) {
if (error.name === 'BucketAlreadyOwnedByYou' || error.Code === 'BucketAlreadyOwnedByYou') {
console.log(`✅ Bucket already exists: ${BUCKET_NAME}`);
} else {
console.log(`⚠️ Could not create bucket (might already exist): ${error.message}`);
}
}
// Get all CSV bookings with documents
const result = await pgClient.query(
`SELECT id, documents FROM csv_bookings WHERE documents IS NOT NULL`
);
console.log(`\n📄 Found ${result.rows.length} bookings with documents\n`);
let uploadedCount = 0;
for (const row of result.rows) {
const bookingId = row.id;
const documents = row.documents;
console.log(`\n📦 Processing booking: ${bookingId}`);
for (const doc of documents) {
if (!doc.filePath || !doc.filePath.includes(MINIO_ENDPOINT)) {
console.log(` ⏭️ Skipping document (not a MinIO URL): ${doc.fileName}`);
continue;
}
// Extract the S3 key from the URL
const url = new URL(doc.filePath);
const key = url.pathname.substring(1).replace(`${BUCKET_NAME}/`, '');
// Create test PDF content
const pdfContent = createTestPDF(doc.fileName || 'Test Document');
try {
// Upload to MinIO
await s3Client.send(
new PutObjectCommand({
Bucket: BUCKET_NAME,
Key: key,
Body: pdfContent,
ContentType: doc.mimeType || 'application/pdf',
})
);
console.log(` ✅ Uploaded: ${doc.fileName}`);
console.log(` Path: ${key}`);
uploadedCount++;
} catch (error) {
console.error(` ❌ Failed to upload ${doc.fileName}:`, error.message);
}
}
}
console.log(`\n🎉 Successfully uploaded ${uploadedCount} test documents to MinIO`);
console.log(`\n📍 MinIO Console: http://localhost:9001`);
console.log(` Username: minioadmin`);
console.log(` Password: minioadmin`);
} catch (error) {
console.error('❌ Error:', error);
throw error;
} finally {
await pgClient.end();
console.log('\n👋 Disconnected from database');
}
}
uploadTestDocuments()
.then(() => {
console.log('\n✅ Script completed successfully');
process.exit(0);
})
.catch(error => {
console.error('\n❌ Script failed:', error);
process.exit(1);
});

View File

@ -1,113 +0,0 @@
/**
* Script pour créer un booking de test avec statut PENDING
* Usage: node create-test-booking.js
*/
const { Client } = require('pg');
const { v4: uuidv4 } = require('uuid');
async function createTestBooking() {
const client = new Client({
host: process.env.DATABASE_HOST || 'localhost',
port: parseInt(process.env.DATABASE_PORT || '5432'),
database: process.env.DATABASE_NAME || 'xpeditis_dev',
user: process.env.DATABASE_USER || 'xpeditis',
password: process.env.DATABASE_PASSWORD || 'xpeditis_dev_password',
});
try {
await client.connect();
console.log('✅ Connecté à la base de données');
const bookingId = uuidv4();
const confirmationToken = uuidv4();
const userId = '8cf7d5b3-d94f-44aa-bb5a-080002919dd1'; // User demo@xpeditis.com
const organizationId = '199fafa9-d26f-4cf9-9206-73432baa8f63';
// Create dummy documents in JSONB format
const dummyDocuments = JSON.stringify([
{
id: uuidv4(),
type: 'BILL_OF_LADING',
fileName: 'bill-of-lading.pdf',
filePath: 'https://dummy-storage.com/documents/bill-of-lading.pdf',
mimeType: 'application/pdf',
size: 102400, // 100KB
uploadedAt: new Date().toISOString(),
},
{
id: uuidv4(),
type: 'PACKING_LIST',
fileName: 'packing-list.pdf',
filePath: 'https://dummy-storage.com/documents/packing-list.pdf',
mimeType: 'application/pdf',
size: 51200, // 50KB
uploadedAt: new Date().toISOString(),
},
{
id: uuidv4(),
type: 'COMMERCIAL_INVOICE',
fileName: 'commercial-invoice.pdf',
filePath: 'https://dummy-storage.com/documents/commercial-invoice.pdf',
mimeType: 'application/pdf',
size: 76800, // 75KB
uploadedAt: new Date().toISOString(),
},
]);
const query = `
INSERT INTO csv_bookings (
id, user_id, organization_id, carrier_name, carrier_email,
origin, destination, volume_cbm, weight_kg, pallet_count,
price_usd, price_eur, primary_currency, transit_days, container_type,
status, confirmation_token, requested_at, notes, documents
) VALUES (
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10,
$11, $12, $13, $14, $15, $16, $17, NOW(), $18, $19
) RETURNING id, confirmation_token;
`;
const values = [
bookingId,
userId,
organizationId,
'Test Carrier',
'test@carrier.com',
'NLRTM', // Rotterdam
'USNYC', // New York
25.5, // volume_cbm
3500, // weight_kg
10, // pallet_count
1850.5, // price_usd
1665.45, // price_eur
'USD', // primary_currency
28, // transit_days
'LCL', // container_type
'PENDING', // status - IMPORTANT!
confirmationToken,
'Test booking created by script',
dummyDocuments, // documents JSONB
];
const result = await client.query(query, values);
console.log('\n🎉 Booking de test créé avec succès!');
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
console.log(`📦 Booking ID: ${bookingId}`);
console.log(`🔑 Token: ${confirmationToken}`);
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
console.log('🔗 URLs de test:');
console.log(` Accept: http://localhost:3000/carrier/accept/${confirmationToken}`);
console.log(` Reject: http://localhost:3000/carrier/reject/${confirmationToken}`);
console.log('\n📧 URL API (pour curl):');
console.log(` curl http://localhost:4000/api/v1/csv-bookings/accept/${confirmationToken}`);
console.log('\n✅ Ce booking est en statut PENDING et peut être accepté/refusé.\n');
} catch (error) {
console.error('❌ Erreur:', error.message);
console.error(error);
} finally {
await client.end();
}
}
createTestBooking();

View File

@ -1,192 +0,0 @@
#!/bin/bash
# Script de diagnostic complet pour l'envoi d'email aux transporteurs
# Ce script fait TOUT automatiquement
set -e # Arrêter en cas d'erreur
# Couleurs
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
echo ""
echo "╔════════════════════════════════════════════════════════════╗"
echo "║ 🔍 DIAGNOSTIC COMPLET - Email Transporteur ║"
echo "╚════════════════════════════════════════════════════════════╝"
echo ""
# Fonction pour afficher les étapes
step_header() {
echo ""
echo -e "${BLUE}╔════════════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║ $1${NC}"
echo -e "${BLUE}╚════════════════════════════════════════════════════════════╝${NC}"
echo ""
}
# Fonction pour les succès
success() {
echo -e "${GREEN}✅ $1${NC}"
}
# Fonction pour les erreurs
error() {
echo -e "${RED}❌ $1${NC}"
}
# Fonction pour les warnings
warning() {
echo -e "${YELLOW}⚠️ $1${NC}"
}
# Fonction pour les infos
info() {
echo -e "${BLUE}ℹ️ $1${NC}"
}
# Aller dans le répertoire backend
cd "$(dirname "$0")"
# ============================================================
# ÉTAPE 1: Arrêter le backend
# ============================================================
step_header "ÉTAPE 1/5: Arrêt du backend actuel"
BACKEND_PIDS=$(lsof -ti:4000 2>/dev/null || true)
if [ -n "$BACKEND_PIDS" ]; then
info "Processus backend trouvés: $BACKEND_PIDS"
kill -9 $BACKEND_PIDS 2>/dev/null || true
sleep 2
success "Backend arrêté"
else
info "Aucun backend en cours d'exécution"
fi
# ============================================================
# ÉTAPE 2: Vérifier les modifications
# ============================================================
step_header "ÉTAPE 2/5: Vérification des modifications"
if grep -q "Using direct IP" src/infrastructure/email/email.adapter.ts; then
success "Modifications DNS présentes dans email.adapter.ts"
else
error "Modifications DNS ABSENTES dans email.adapter.ts"
error "Le fix n'a pas été appliqué correctement!"
exit 1
fi
# ============================================================
# ÉTAPE 3: Test de connexion SMTP (sans backend)
# ============================================================
step_header "ÉTAPE 3/5: Test de connexion SMTP directe"
info "Exécution de debug-email-flow.js..."
echo ""
if node debug-email-flow.js > /tmp/email-test.log 2>&1; then
success "Test SMTP réussi!"
echo ""
echo "Résultats du test:"
echo "─────────────────"
tail -15 /tmp/email-test.log
else
error "Test SMTP échoué!"
echo ""
echo "Logs d'erreur:"
echo "──────────────"
cat /tmp/email-test.log
echo ""
error "ARRÊT: La connexion SMTP ne fonctionne pas"
error "Vérifiez vos credentials SMTP dans .env"
exit 1
fi
# ============================================================
# ÉTAPE 4: Redémarrer le backend
# ============================================================
step_header "ÉTAPE 4/5: Redémarrage du backend"
info "Démarrage du backend en arrière-plan..."
# Démarrer le backend
npm run dev > /tmp/backend.log 2>&1 &
BACKEND_PID=$!
info "Backend démarré (PID: $BACKEND_PID)"
info "Attente de l'initialisation (15 secondes)..."
# Attendre que le backend démarre
sleep 15
# Vérifier que le backend tourne
if kill -0 $BACKEND_PID 2>/dev/null; then
success "Backend en cours d'exécution"
# Afficher les logs de démarrage
echo ""
echo "Logs de démarrage du backend:"
echo "─────────────────────────────"
tail -20 /tmp/backend.log
echo ""
# Vérifier le log DNS fix
if grep -q "Using direct IP" /tmp/backend.log; then
success "✨ DNS FIX DÉTECTÉ: Le backend utilise bien l'IP directe!"
else
warning "DNS fix non détecté dans les logs"
warning "Cela peut être normal si le message est tronqué"
fi
else
error "Le backend n'a pas démarré correctement"
echo ""
echo "Logs d'erreur:"
echo "──────────────"
cat /tmp/backend.log
exit 1
fi
# ============================================================
# ÉTAPE 5: Test de création de booking (optionnel)
# ============================================================
step_header "ÉTAPE 5/5: Instructions pour tester"
echo ""
echo "Le backend est maintenant en cours d'exécution avec les corrections."
echo ""
echo "Pour tester l'envoi d'email:"
echo "──────────────────────────────────────────────────────────────"
echo ""
echo "1. ${GREEN}Via le frontend${NC}:"
echo " - Ouvrez http://localhost:3000"
echo " - Créez un CSV booking"
echo " - Vérifiez les logs backend pour:"
echo " ${GREEN}✅ Email sent to carrier: <email>${NC}"
echo ""
echo "2. ${GREEN}Via l'API directement${NC}:"
echo " - Utilisez Postman ou curl"
echo " - POST http://localhost:4000/api/v1/csv-bookings"
echo " - Avec un fichier et les données du booking"
echo ""
echo "3. ${GREEN}Vérifier Mailtrap${NC}:"
echo " - https://mailtrap.io/inboxes"
echo " - Cherchez: 'Nouvelle demande de réservation'"
echo ""
echo "──────────────────────────────────────────────────────────────"
echo ""
info "Pour voir les logs backend en temps réel:"
echo " ${YELLOW}tail -f /tmp/backend.log${NC}"
echo ""
info "Pour arrêter le backend:"
echo " ${YELLOW}kill $BACKEND_PID${NC}"
echo ""
success "Diagnostic terminé!"
echo ""
echo "╔════════════════════════════════════════════════════════════╗"
echo "║ ✅ BACKEND PRÊT - Créez un booking pour tester ║"
echo "╚════════════════════════════════════════════════════════════╝"
echo ""

View File

@ -1,67 +0,0 @@
const axios = require('axios');
const FormData = require('form-data');
const API_URL = 'http://localhost:4000/api/v1';
async function loginAndTestEmail() {
try {
// 1. Login
console.log('🔐 Connexion...');
const loginResponse = await axios.post(`${API_URL}/auth/login`, {
email: 'admin@xpeditis.com',
password: 'Admin123!@#',
});
const token = loginResponse.data.accessToken;
console.log('✅ Connecté avec succès\n');
// 2. Créer un CSV booking pour tester l'envoi d'email
console.log("📧 Création d'une CSV booking pour tester l'envoi d'email...");
const form = new FormData();
const testFile = Buffer.from('Test document PDF content');
form.append('documents', testFile, {
filename: 'test-doc.pdf',
contentType: 'application/pdf',
});
form.append('carrierName', 'Test Carrier');
form.append('carrierEmail', 'testcarrier@example.com');
form.append('origin', 'NLRTM');
form.append('destination', 'USNYC');
form.append('volumeCBM', '25.5');
form.append('weightKG', '3500');
form.append('palletCount', '10');
form.append('priceUSD', '1850.50');
form.append('priceEUR', '1665.45');
form.append('primaryCurrency', 'USD');
form.append('transitDays', '28');
form.append('containerType', 'LCL');
form.append('notes', 'Test email');
const bookingResponse = await axios.post(`${API_URL}/csv-bookings`, form, {
headers: {
...form.getHeaders(),
Authorization: `Bearer ${token}`,
},
});
console.log('✅ CSV Booking créé:', bookingResponse.data.id);
console.log('\n📋 VÉRIFICATIONS À FAIRE:');
console.log('1. Vérifier les logs du backend ci-dessus');
console.log(' Chercher: "Email sent to carrier: testcarrier@example.com"');
console.log('2. Vérifier Mailtrap inbox: https://mailtrap.io/inboxes');
console.log('3. Email devrait être envoyé à: testcarrier@example.com');
console.log('\n⏳ Attendez quelques secondes puis vérifiez les logs du backend...');
} catch (error) {
console.error('❌ ERREUR:');
if (error.response) {
console.error('Status:', error.response.status);
console.error('Data:', JSON.stringify(error.response.data, null, 2));
} else {
console.error(error.message);
}
}
}
loginAndTestEmail();

View File

@ -1,53 +0,0 @@
#!/bin/bash
echo "🚀 Starting backend with SMTP fix..."
echo ""
# Kill any existing backend
lsof -ti:4000 | xargs -r kill -9 2>/dev/null || true
sleep 2
# Start backend
npm run dev > /tmp/backend-startup.log 2>&1 &
BACKEND_PID=$!
echo "Backend started (PID: $BACKEND_PID)"
echo "Waiting 15 seconds for initialization..."
sleep 15
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "📋 Backend Startup Logs:"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
tail -30 /tmp/backend-startup.log
echo ""
# Check for SMTP initialization
if grep -q "Email adapter initialized" /tmp/backend-startup.log; then
echo "✅ Email adapter initialized successfully!"
echo ""
grep "Email adapter initialized" /tmp/backend-startup.log
echo ""
else
echo "❌ Email adapter NOT initialized - check logs above"
echo ""
fi
# Check for errors
if grep -qi "error" /tmp/backend-startup.log | head -5; then
echo "⚠️ Errors found in logs:"
grep -i "error" /tmp/backend-startup.log | head -5
echo ""
fi
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "Backend is running. To test email:"
echo " node test-smtp-simple.js"
echo ""
echo "To see live logs:"
echo " tail -f /tmp/backend-startup.log"
echo ""
echo "To stop backend:"
echo " kill $BACKEND_PID"
echo ""

View File

@ -1,200 +0,0 @@
#!/bin/bash
# Test script to create a CSV booking and identify errors
set -e
echo "=========================================="
echo "🧪 Test de création de CSV Booking"
echo "=========================================="
echo ""
# Configuration
API_URL="http://localhost:4000/api/v1"
BACKEND_LOG="/tmp/backend-startup.log"
# Couleurs
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Étape 1: Login pour obtenir le JWT token
echo -e "${BLUE}📋 Étape 1: Connexion (obtention du token JWT)${NC}"
echo "----------------------------------------------"
# Utiliser des credentials admin ou de test
LOGIN_RESPONSE=$(curl -s -X POST "${API_URL}/auth/login" \
-H "Content-Type: application/json" \
-d '{
"email": "admin@xpeditis.com",
"password": "Admin123!"
}' 2>&1)
echo "Response: ${LOGIN_RESPONSE:0:200}..."
# Extraire le token
TOKEN=$(echo "$LOGIN_RESPONSE" | grep -o '"accessToken":"[^"]*"' | cut -d'"' -f4)
if [ -z "$TOKEN" ]; then
echo -e "${RED}❌ Échec de connexion${NC}"
echo "Essayez avec d'autres credentials ou créez un utilisateur de test."
echo "Full response: $LOGIN_RESPONSE"
exit 1
fi
echo -e "${GREEN}✅ Token obtenu: ${TOKEN:0:30}...${NC}"
echo ""
# Étape 2: Créer un fichier de test
echo -e "${BLUE}📋 Étape 2: Création d'un fichier de test${NC}"
echo "----------------------------------------------"
TEST_FILE="/tmp/test-booking-doc.txt"
cat > "$TEST_FILE" << EOF
BILL OF LADING - TEST DOCUMENT
================================
Booking ID: TEST-$(date +%s)
Origin: NLRTM (Rotterdam)
Destination: USNYC (New York)
Date: $(date)
This is a test document for CSV booking creation.
Weight: 1500 kg
Volume: 2.88 CBM
Pallets: 3
Test completed successfully.
EOF
echo -e "${GREEN}✅ Fichier créé: $TEST_FILE${NC}"
echo ""
# Étape 3: Vérifier le bucket S3/MinIO
echo -e "${BLUE}📋 Étape 3: Vérification du bucket MinIO${NC}"
echo "----------------------------------------------"
# Check if MinIO is running
if docker ps | grep -q "xpeditis-minio"; then
echo -e "${GREEN}✅ MinIO container is running${NC}"
else
echo -e "${RED}❌ MinIO container is NOT running${NC}"
echo "Start it with: docker-compose up -d"
exit 1
fi
# Check if bucket exists (via MinIO API)
echo "Checking if bucket 'xpeditis-documents' exists..."
BUCKET_CHECK=$(curl -s -I "http://localhost:9000/xpeditis-documents/" \
-H "Authorization: AWS4-HMAC-SHA256 Credential=minioadmin/20231201/us-east-1/s3/aws4_request" 2>&1 | head -1)
if echo "$BUCKET_CHECK" | grep -q "200 OK"; then
echo -e "${GREEN}✅ Bucket 'xpeditis-documents' exists${NC}"
elif echo "$BUCKET_CHECK" | grep -q "404"; then
echo -e "${YELLOW}⚠️ Bucket 'xpeditis-documents' does NOT exist${NC}"
echo "The backend will try to create it automatically, or it may fail."
else
echo -e "${YELLOW}⚠️ Cannot verify bucket (MinIO might require auth)${NC}"
fi
echo ""
# Étape 4: Envoyer la requête de création de booking
echo -e "${BLUE}📋 Étape 4: Création du CSV booking${NC}"
echo "----------------------------------------------"
# Clear previous backend logs
echo "" > "$BACKEND_LOG.tail"
# Start tailing logs in background
tail -f "$BACKEND_LOG" > "$BACKEND_LOG.tail" &
TAIL_PID=$!
# Wait a second
sleep 1
echo "Sending POST request to /api/v1/csv-bookings..."
echo ""
# Send the booking request
BOOKING_RESPONSE=$(curl -s -w "\nHTTP_STATUS:%{http_code}" -X POST "${API_URL}/csv-bookings" \
-H "Authorization: Bearer ${TOKEN}" \
-F "carrierName=Test Maritime Express" \
-F "carrierEmail=carrier@test.com" \
-F "origin=NLRTM" \
-F "destination=USNYC" \
-F "volumeCBM=2.88" \
-F "weightKG=1500" \
-F "palletCount=3" \
-F "priceUSD=4834.44" \
-F "priceEUR=4834.44" \
-F "primaryCurrency=USD" \
-F "transitDays=22" \
-F "containerType=LCL" \
-F "notes=Test booking via script" \
-F "documents=@${TEST_FILE}" 2>&1)
# Extract HTTP status
HTTP_STATUS=$(echo "$BOOKING_RESPONSE" | grep "HTTP_STATUS" | cut -d':' -f2)
RESPONSE_BODY=$(echo "$BOOKING_RESPONSE" | sed '/HTTP_STATUS/d')
echo "HTTP Status: $HTTP_STATUS"
echo ""
echo "Response Body:"
echo "$RESPONSE_BODY" | head -50
echo ""
# Stop tailing
kill $TAIL_PID 2>/dev/null || true
# Wait a bit for logs to flush
sleep 2
# Étape 5: Analyser les logs backend
echo -e "${BLUE}📋 Étape 5: Analyse des logs backend${NC}"
echo "----------------------------------------------"
echo "Recent backend logs (CSV/Booking/Error related):"
tail -100 "$BACKEND_LOG" | grep -i "csv\|booking\|error\|email\|upload\|s3" | tail -30
echo ""
# Étape 6: Vérifier le résultat
echo "=========================================="
if [ "$HTTP_STATUS" = "201" ] || [ "$HTTP_STATUS" = "200" ]; then
echo -e "${GREEN}✅ SUCCESS: Booking created successfully!${NC}"
# Extract booking ID
BOOKING_ID=$(echo "$RESPONSE_BODY" | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
echo "Booking ID: $BOOKING_ID"
echo ""
echo "Check:"
echo "1. Mailtrap inbox: https://mailtrap.io/inboxes"
echo "2. Frontend bookings page: http://localhost:3000/dashboard/bookings"
elif [ "$HTTP_STATUS" = "400" ]; then
echo -e "${RED}❌ FAILED: Bad Request (400)${NC}"
echo "Possible issues:"
echo " - Missing required fields"
echo " - Invalid data format"
echo " - Document validation failed"
elif [ "$HTTP_STATUS" = "401" ]; then
echo -e "${RED}❌ FAILED: Unauthorized (401)${NC}"
echo "Possible issues:"
echo " - JWT token expired"
echo " - Invalid credentials"
elif [ "$HTTP_STATUS" = "500" ]; then
echo -e "${RED}❌ FAILED: Internal Server Error (500)${NC}"
echo "Possible issues:"
echo " - S3/MinIO connection failed"
echo " - Database error"
echo " - Email sending failed (check backend logs)"
else
echo -e "${RED}❌ FAILED: Unknown error (HTTP $HTTP_STATUS)${NC}"
fi
echo "=========================================="
echo ""
echo "📄 Full backend logs available at: $BACKEND_LOG"
echo ""

View File

@ -1,72 +0,0 @@
#!/bin/bash
echo "Testing CSV Booking Creation"
echo "=============================="
API_URL="http://localhost:4000/api/v1"
# Step 1: Login
echo "Step 1: Login..."
LOGIN_RESPONSE=$(curl -s -X POST "${API_URL}/auth/login" \
-H "Content-Type: application/json" \
-d '{"email":"admin@xpeditis.com","password":"Admin123!"}')
TOKEN=$(echo "$LOGIN_RESPONSE" | grep -o '"accessToken":"[^"]*"' | cut -d'"' -f4)
if [ -z "$TOKEN" ]; then
echo "ERROR: Login failed"
echo "$LOGIN_RESPONSE"
exit 1
fi
echo "SUCCESS: Token obtained"
echo ""
# Step 2: Create test file
echo "Step 2: Creating test document..."
TEST_FILE="/tmp/test-bol.txt"
echo "Bill of Lading - Test Document" > "$TEST_FILE"
echo "Date: $(date)" >> "$TEST_FILE"
echo "Origin: NLRTM" >> "$TEST_FILE"
echo "Destination: USNYC" >> "$TEST_FILE"
echo "SUCCESS: Test file created at $TEST_FILE"
echo ""
# Step 3: Create booking
echo "Step 3: Creating CSV booking..."
RESPONSE=$(curl -s -w "\nSTATUS:%{http_code}" -X POST "${API_URL}/csv-bookings" \
-H "Authorization: Bearer ${TOKEN}" \
-F "carrierName=Test Carrier" \
-F "carrierEmail=carrier@test.com" \
-F "origin=NLRTM" \
-F "destination=USNYC" \
-F "volumeCBM=2.88" \
-F "weightKG=1500" \
-F "palletCount=3" \
-F "priceUSD=4834.44" \
-F "priceEUR=4834.44" \
-F "primaryCurrency=USD" \
-F "transitDays=22" \
-F "containerType=LCL" \
-F "notes=Test" \
-F "documents=@${TEST_FILE}")
STATUS=$(echo "$RESPONSE" | grep "STATUS" | cut -d':' -f2)
BODY=$(echo "$RESPONSE" | sed '/STATUS/d')
echo "HTTP Status: $STATUS"
echo ""
echo "Response:"
echo "$BODY"
echo ""
if [ "$STATUS" = "201" ] || [ "$STATUS" = "200" ]; then
echo "SUCCESS: Booking created!"
else
echo "FAILED: Booking creation failed with status $STATUS"
fi
echo ""
echo "Check backend logs:"
tail -50 /tmp/backend-startup.log | grep -i "csv\|booking\|error" | tail -20

View File

@ -1,95 +0,0 @@
/**
* Test the complete CSV booking workflow
* This tests if email sending is triggered when creating a booking
*/
const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
const API_BASE = 'http://localhost:4000/api/v1';
// Test credentials - you need to use real credentials from your database
const TEST_USER = {
email: 'admin@xpeditis.com', // Change this to a real user email
password: 'Admin123!', // Change this to the real password
};
async function testWorkflow() {
console.log('🧪 Testing CSV Booking Workflow\n');
try {
// Step 1: Login to get JWT token
console.log('1️⃣ Logging in...');
const loginResponse = await axios.post(`${API_BASE}/auth/login`, {
email: TEST_USER.email,
password: TEST_USER.password,
});
const token = loginResponse.data.accessToken;
console.log('✅ Login successful\n');
// Step 2: Create a test CSV booking
console.log('2️⃣ Creating CSV booking...');
const form = new FormData();
// Booking data
form.append('carrierName', 'Test Carrier');
form.append('carrierEmail', 'test-carrier@example.com'); // Email to receive booking
form.append('origin', 'FRPAR');
form.append('destination', 'USNYC');
form.append('volumeCBM', '10');
form.append('weightKG', '500');
form.append('palletCount', '2');
form.append('priceUSD', '1500');
form.append('priceEUR', '1300');
form.append('primaryCurrency', 'USD');
form.append('transitDays', '15');
form.append('containerType', '20FT');
form.append('notes', 'Test booking for email workflow verification');
// Create a test document file
const testDocument = Buffer.from('Test document content for booking');
form.append('documents', testDocument, {
filename: 'test-invoice.pdf',
contentType: 'application/pdf',
});
const bookingResponse = await axios.post(`${API_BASE}/csv-bookings`, form, {
headers: {
...form.getHeaders(),
Authorization: `Bearer ${token}`,
},
});
console.log('✅ Booking created successfully!');
console.log('📦 Booking ID:', bookingResponse.data.id);
console.log('📧 Email should be sent to:', bookingResponse.data.carrierEmail);
console.log('🔗 Confirmation token:', bookingResponse.data.confirmationToken);
console.log('\n💡 Check backend logs for:');
console.log(' - "Email sent to carrier: test-carrier@example.com"');
console.log(' - "CSV booking request sent to test-carrier@example.com"');
console.log(' - OR any error messages about email sending');
console.log('\n📬 Check Mailtrap inbox: https://mailtrap.io/inboxes');
} catch (error) {
console.error('❌ Error:', error.response?.data || error.message);
if (error.response?.status === 401) {
console.error(
'\n⚠️ Authentication failed. Please update TEST_USER credentials in the script.'
);
}
if (error.response?.status === 400) {
console.error('\n⚠️ Bad request. Check the booking data format.');
console.error('Details:', error.response.data);
}
if (error.code === 'ECONNREFUSED') {
console.error('\n⚠️ Backend server is not running. Start it with: npm run backend:dev');
}
}
}
testWorkflow();

View File

@ -1,230 +0,0 @@
/**
* Script de test pour vérifier l'envoi d'email aux transporteurs
*
* Usage: node test-carrier-email-fix.js
*/
const nodemailer = require('nodemailer');
async function testEmailConfig() {
console.log('🔍 Test de configuration email Mailtrap...\n');
const config = {
host: process.env.SMTP_HOST || 'sandbox.smtp.mailtrap.io',
port: parseInt(process.env.SMTP_PORT || '2525'),
user: process.env.SMTP_USER || '2597bd31d265eb',
pass: process.env.SMTP_PASS || 'cd126234193c89',
};
console.log('📧 Configuration SMTP:');
console.log(` Host: ${config.host}`);
console.log(` Port: ${config.port}`);
console.log(` User: ${config.user}`);
console.log(` Pass: ${config.pass.substring(0, 4)}***\n`);
// Test 1: Configuration standard (peut échouer avec timeout DNS)
console.log('Test 1: Configuration standard...');
try {
const transporter1 = nodemailer.createTransport({
host: config.host,
port: config.port,
secure: false,
auth: {
user: config.user,
pass: config.pass,
},
connectionTimeout: 10000,
greetingTimeout: 10000,
socketTimeout: 30000,
});
await transporter1.sendMail({
from: 'noreply@xpeditis.com',
to: 'test@xpeditis.com',
subject: 'Test Email - Configuration Standard',
html: '<h1>Test réussi!</h1><p>Configuration standard fonctionne.</p>',
});
console.log('✅ Test 1 RÉUSSI - Configuration standard OK\n');
} catch (error) {
console.error('❌ Test 1 ÉCHOUÉ:', error.message);
console.error(' Code:', error.code);
console.error(' Timeout?', error.message.includes('ETIMEOUT'));
console.log('');
}
// Test 2: Configuration avec IP directe (devrait toujours fonctionner)
console.log('Test 2: Configuration avec IP directe...');
try {
const useDirectIP = config.host.includes('mailtrap.io');
const actualHost = useDirectIP ? '3.209.246.195' : config.host;
const serverName = useDirectIP ? 'smtp.mailtrap.io' : config.host;
console.log(` Utilisation IP directe: ${useDirectIP}`);
console.log(` Host réel: ${actualHost}`);
console.log(` Server name (TLS): ${serverName}`);
const transporter2 = nodemailer.createTransport({
host: actualHost,
port: config.port,
secure: false,
auth: {
user: config.user,
pass: config.pass,
},
tls: {
rejectUnauthorized: false,
servername: serverName,
},
connectionTimeout: 10000,
greetingTimeout: 10000,
socketTimeout: 30000,
dnsTimeout: 10000,
});
const result = await transporter2.sendMail({
from: 'noreply@xpeditis.com',
to: 'test@xpeditis.com',
subject: 'Test Email - Configuration IP Directe',
html: '<h1>Test réussi!</h1><p>Configuration avec IP directe fonctionne.</p>',
});
console.log('✅ Test 2 RÉUSSI - Configuration IP directe OK');
console.log(` Message ID: ${result.messageId}`);
console.log(` Response: ${result.response}\n`);
} catch (error) {
console.error('❌ Test 2 ÉCHOUÉ:', error.message);
console.error(' Code:', error.code);
console.log('');
}
// Test 3: Template HTML de booking transporteur
console.log('Test 3: Envoi avec template HTML complet...');
try {
const useDirectIP = config.host.includes('mailtrap.io');
const actualHost = useDirectIP ? '3.209.246.195' : config.host;
const serverName = useDirectIP ? 'smtp.mailtrap.io' : config.host;
const transporter3 = nodemailer.createTransport({
host: actualHost,
port: config.port,
secure: false,
auth: {
user: config.user,
pass: config.pass,
},
tls: {
rejectUnauthorized: false,
servername: serverName,
},
connectionTimeout: 10000,
greetingTimeout: 10000,
socketTimeout: 30000,
dnsTimeout: 10000,
});
const bookingData = {
bookingId: 'TEST-' + Date.now(),
origin: 'FRPAR',
destination: 'USNYC',
volumeCBM: 10.5,
weightKG: 850,
palletCount: 4,
priceUSD: 1500,
priceEUR: 1350,
primaryCurrency: 'USD',
transitDays: 15,
containerType: '20FT',
documents: [
{ type: 'Bill of Lading', fileName: 'bol.pdf' },
{ type: 'Packing List', fileName: 'packing_list.pdf' },
],
acceptUrl: 'http://localhost:3000/carrier/booking/accept',
rejectUrl: 'http://localhost:3000/carrier/booking/reject',
};
const htmlTemplate = `
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"></head>
<body style="font-family: Arial, sans-serif; background-color: #f4f6f8; padding: 20px;">
<div style="max-width: 600px; margin: 0 auto; background: white; border-radius: 8px; overflow: hidden;">
<div style="background: linear-gradient(135deg, #045a8d, #00bcd4); color: white; padding: 30px; text-align: center;">
<h1 style="margin: 0;">🚢 Nouvelle demande de réservation</h1>
<p style="margin: 5px 0 0;">Xpeditis</p>
</div>
<div style="padding: 30px;">
<p style="font-size: 16px;">Bonjour,</p>
<p>Vous avez reçu une nouvelle demande de réservation via Xpeditis.</p>
<h2 style="color: #045a8d; border-bottom: 2px solid #00bcd4; padding-bottom: 8px;">📋 Détails du transport</h2>
<table style="width: 100%; border-collapse: collapse;">
<tr style="border-bottom: 1px solid #e0e0e0;">
<td style="padding: 12px; font-weight: bold; color: #045a8d;">Route</td>
<td style="padding: 12px;">${bookingData.origin} → ${bookingData.destination}</td>
</tr>
<tr style="border-bottom: 1px solid #e0e0e0;">
<td style="padding: 12px; font-weight: bold; color: #045a8d;">Volume</td>
<td style="padding: 12px;">${bookingData.volumeCBM} CBM</td>
</tr>
<tr style="border-bottom: 1px solid #e0e0e0;">
<td style="padding: 12px; font-weight: bold; color: #045a8d;">Prix</td>
<td style="padding: 12px; font-size: 24px; font-weight: bold; color: #00aa00;">
${bookingData.priceUSD} USD
</td>
</tr>
</table>
<div style="text-align: center; margin: 30px 0;">
<p style="font-weight: bold;">Veuillez confirmer votre décision :</p>
<a href="${bookingData.acceptUrl}" style="display: inline-block; padding: 15px 30px; background: #00aa00; color: white; text-decoration: none; border-radius: 6px; margin: 0 5px;">✓ Accepter</a>
<a href="${bookingData.rejectUrl}" style="display: inline-block; padding: 15px 30px; background: #cc0000; color: white; text-decoration: none; border-radius: 6px; margin: 0 5px;">✗ Refuser</a>
</div>
<div style="background: #fff8e1; border-left: 4px solid #f57c00; padding: 15px; margin: 20px 0;">
<p style="margin: 0; font-size: 14px; color: #666;">
<strong style="color: #f57c00;">⚠️ Important</strong><br>
Cette demande expire automatiquement dans 7 jours si aucune action n'est prise.
</p>
</div>
</div>
<div style="background: #f4f6f8; padding: 20px; text-align: center; font-size: 12px; color: #666;">
<p style="margin: 5px 0; font-weight: bold; color: #045a8d;">Référence : ${bookingData.bookingId}</p>
<p style="margin: 5px 0;">© 2025 Xpeditis. Tous droits réservés.</p>
</div>
</div>
</body>
</html>
`;
const result = await transporter3.sendMail({
from: 'noreply@xpeditis.com',
to: 'carrier@test.com',
subject: `Nouvelle demande de réservation - ${bookingData.origin} → ${bookingData.destination}`,
html: htmlTemplate,
});
console.log('✅ Test 3 RÉUSSI - Email complet avec template envoyé');
console.log(` Message ID: ${result.messageId}`);
console.log(` Response: ${result.response}\n`);
} catch (error) {
console.error('❌ Test 3 ÉCHOUÉ:', error.message);
console.error(' Code:', error.code);
console.log('');
}
console.log('📊 Résumé des tests:');
console.log(' ✓ Vérifiez Mailtrap inbox: https://mailtrap.io/inboxes');
console.log(' ✓ Recherchez les emails de test ci-dessus');
console.log(
' ✓ Si Test 2 et 3 réussissent, le backend doit être corrigé avec la configuration IP directe\n'
);
}
// Run test
testEmailConfig()
.then(() => {
console.log('✅ Tests terminés avec succès');
process.exit(0);
})
.catch(error => {
console.error('❌ Erreur lors des tests:', error);
process.exit(1);
});

View File

@ -1,32 +0,0 @@
const nodemailer = require('nodemailer');
const transporter = nodemailer.createTransport({
host: 'sandbox.smtp.mailtrap.io',
port: 2525,
auth: {
user: '2597bd31d265eb',
pass: 'cd126234193c89',
},
});
console.log("🔄 Tentative d'envoi d'email...");
transporter
.sendMail({
from: 'noreply@xpeditis.com',
to: 'test@example.com',
subject: 'Test Email depuis Portail Transporteur',
text: 'Email de test pour vérifier la configuration',
})
.then(info => {
console.log('✅ Email envoyé:', info.messageId);
console.log('📧 Response:', info.response);
process.exit(0);
})
.catch(err => {
console.error('❌ Erreur:', err.message);
console.error('Code:', err.code);
console.error('Command:', err.command);
console.error('Stack:', err.stack);
process.exit(1);
});

View File

@ -1,382 +0,0 @@
/**
* CSV Rate API Test Script (Node.js)
*
* Usage: node test-csv-api.js
*
* Tests all CSV rate endpoints and verifies comparator functionality
*/
const API_URL = 'http://localhost:4000';
// Color codes for terminal output
const colors = {
reset: '\x1b[0m',
red: '\x1b[31m',
green: '\x1b[32m',
yellow: '\x1b[33m',
blue: '\x1b[34m',
};
function printTest(number, description) {
console.log(`${colors.yellow}[TEST ${number}] ${description}${colors.reset}`);
}
function printSuccess(message) {
console.log(`${colors.green}✓ ${message}${colors.reset}`);
}
function printError(message) {
console.log(`${colors.red}✗ ${message}${colors.reset}`);
}
function printInfo(message) {
console.log(`${colors.blue}→ ${message}${colors.reset}`);
}
async function authenticateUser() {
printTest(1, 'Authenticating as regular user');
const response = await fetch(`${API_URL}/api/v1/auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: 'test4@xpeditis.com',
password: 'SecurePassword123',
}),
});
const data = await response.json();
if (data.accessToken) {
printSuccess('Regular user authenticated');
printInfo(`Token: ${data.accessToken.substring(0, 20)}...`);
return data.accessToken;
} else {
printError('Failed to authenticate regular user');
console.log('Response:', data);
throw new Error('Authentication failed');
}
}
async function testGetCompanies(token) {
printTest(2, 'GET /rates/companies - Get available companies');
const response = await fetch(`${API_URL}/api/v1/rates/companies`, {
headers: { Authorization: `Bearer ${token}` },
});
const data = await response.json();
console.log(JSON.stringify(data, null, 2));
if (data.total === 5) {
printSuccess('Got 5 companies (including Test Maritime Express)');
printInfo(`Companies: ${data.companies.join(', ')}`);
} else {
printError(`Expected 5 companies, got ${data.total}`);
}
console.log('');
return data;
}
async function testGetFilterOptions(token) {
printTest(3, 'GET /rates/filters/options - Get filter options');
const response = await fetch(`${API_URL}/api/v1/rates/filters/options`, {
headers: { Authorization: `Bearer ${token}` },
});
const data = await response.json();
console.log(JSON.stringify(data, null, 2));
printSuccess('Filter options retrieved');
console.log('');
return data;
}
async function testBasicSearch(token) {
printTest(4, 'POST /rates/search-csv - Basic rate search (NLRTM → USNYC)');
const response = await fetch(`${API_URL}/api/v1/rates/search-csv`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({
origin: 'NLRTM',
destination: 'USNYC',
volumeCBM: 25.5,
weightKG: 3500,
palletCount: 10,
containerType: 'LCL',
}),
});
const data = await response.json();
console.log(JSON.stringify(data, null, 2));
printInfo(`Total results: ${data.totalResults}`);
// Check if Test Maritime Express is in results
const hasTestMaritime = data.results.some(r => r.companyName === 'Test Maritime Express');
if (hasTestMaritime) {
printSuccess('Test Maritime Express found in results');
const testPrice = data.results.find(r => r.companyName === 'Test Maritime Express').totalPrice
.amount;
printInfo(`Test Maritime Express price: $${testPrice}`);
} else {
printError('Test Maritime Express NOT found in results');
}
// Count unique companies
const uniqueCompanies = [...new Set(data.results.map(r => r.companyName))];
printInfo(`Results from ${uniqueCompanies.length} different companies`);
if (uniqueCompanies.length >= 3) {
printSuccess('Multiple companies in comparator ✓');
} else {
printError(`Expected multiple companies, got ${uniqueCompanies.length}`);
}
console.log('');
return data;
}
async function testCompanyFilter(token) {
printTest(5, 'POST /rates/search-csv - Filter by Test Maritime Express only');
const response = await fetch(`${API_URL}/api/v1/rates/search-csv`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({
origin: 'NLRTM',
destination: 'USNYC',
volumeCBM: 25.5,
weightKG: 3500,
palletCount: 10,
containerType: 'LCL',
filters: {
companies: ['Test Maritime Express'],
},
}),
});
const data = await response.json();
console.log(JSON.stringify(data.results.slice(0, 3), null, 2));
const uniqueCompanies = [...new Set(data.results.map(r => r.companyName))];
if (uniqueCompanies.length === 1 && uniqueCompanies[0] === 'Test Maritime Express') {
printSuccess('Company filter working correctly');
} else {
printError(`Company filter not working - got: ${uniqueCompanies.join(', ')}`);
}
console.log('');
return data;
}
async function testPriceFilter(token) {
printTest(6, 'POST /rates/search-csv - Filter by price range ($900-$1200)');
const response = await fetch(`${API_URL}/api/v1/rates/search-csv`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({
origin: 'NLRTM',
destination: 'USNYC',
volumeCBM: 25.5,
weightKG: 3500,
palletCount: 10,
containerType: 'LCL',
filters: {
minPrice: 900,
maxPrice: 1200,
currency: 'USD',
},
}),
});
const data = await response.json();
printInfo(`Results in price range $900-$1200: ${data.totalResults}`);
const prices = data.results.map(r => r.totalPrice.amount);
const minPrice = Math.min(...prices);
const maxPrice = Math.max(...prices);
if (minPrice >= 900 && maxPrice <= 1200) {
printSuccess(`Price filter working correctly (range: $${minPrice} - $${maxPrice})`);
} else {
printError(`Price filter not working - got range: $${minPrice} - $${maxPrice}`);
}
console.log('');
return data;
}
async function testTransitFilter(token) {
printTest(7, 'POST /rates/search-csv - Filter by max transit days (≤23 days)');
const response = await fetch(`${API_URL}/api/v1/rates/search-csv`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({
origin: 'NLRTM',
destination: 'USNYC',
volumeCBM: 25.5,
weightKG: 3500,
containerType: 'LCL',
filters: {
maxTransitDays: 23,
},
}),
});
const data = await response.json();
printInfo(`Results with transit ≤23 days: ${data.totalResults}`);
const maxTransit = Math.max(...data.results.map(r => r.transitDays));
if (maxTransit <= 23) {
printSuccess(`Transit filter working correctly (max: ${maxTransit} days)`);
} else {
printError(`Transit filter not working - max transit: ${maxTransit} days`);
}
console.log('');
return data;
}
async function testSurchargeFilter(token) {
printTest(8, 'POST /rates/search-csv - Filter for rates without surcharges (all-in prices)');
const response = await fetch(`${API_URL}/api/v1/rates/search-csv`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({
origin: 'NLRTM',
destination: 'USNYC',
volumeCBM: 25.5,
weightKG: 3500,
containerType: 'LCL',
filters: {
withoutSurcharges: true,
},
}),
});
const data = await response.json();
printInfo(`Results without surcharges: ${data.totalResults}`);
const withSurcharges = data.results.filter(r => r.hasSurcharges).length;
if (withSurcharges === 0) {
printSuccess('Surcharge filter working correctly');
} else {
printError(`Surcharge filter not working - found ${withSurcharges} results with surcharges`);
}
console.log('');
return data;
}
async function testComparator(token) {
printTest(9, 'COMPARATOR TEST - Show all 5 companies for NLRTM → USNYC');
const response = await fetch(`${API_URL}/api/v1/rates/search-csv`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({
origin: 'NLRTM',
destination: 'USNYC',
volumeCBM: 25,
weightKG: 3500,
palletCount: 10,
containerType: 'LCL',
}),
});
const data = await response.json();
console.log('\nCompany Comparison Table:');
console.log('=========================');
data.results.slice(0, 10).forEach(result => {
console.log(
`${result.companyName}: $${result.totalPrice.amount} ${result.totalPrice.currency} - ${result.transitDays} days - Match: ${result.matchScore}%`
);
});
const uniqueCompanies = [...new Set(data.results.map(r => r.companyName))];
printInfo('Companies in results:');
uniqueCompanies.forEach(company => console.log(` - ${company}`));
// Check if Test Maritime Express has lowest price
const sortedByPrice = [...data.results].sort((a, b) => a.totalPrice.amount - b.totalPrice.amount);
const lowestPriceCompany = sortedByPrice[0].companyName;
const lowestPrice = sortedByPrice[0].totalPrice.amount;
if (lowestPriceCompany === 'Test Maritime Express') {
printSuccess('Test Maritime Express has the lowest price ✓');
printInfo(`Lowest price: $${lowestPrice} (Test Maritime Express)`);
} else {
printError(
`Expected Test Maritime Express to have lowest price, but got: ${lowestPriceCompany}`
);
}
console.log('');
return data;
}
async function runTests() {
console.log(`${colors.blue}========================================${colors.reset}`);
console.log(`${colors.blue}CSV Rate API Test Script${colors.reset}`);
console.log(`${colors.blue}========================================${colors.reset}`);
console.log('');
try {
// Authenticate
const token = await authenticateUser();
console.log('');
// Run all tests
await testGetCompanies(token);
await testGetFilterOptions(token);
await testBasicSearch(token);
await testCompanyFilter(token);
await testPriceFilter(token);
await testTransitFilter(token);
await testSurchargeFilter(token);
await testComparator(token);
console.log(`${colors.blue}========================================${colors.reset}`);
console.log(`${colors.green}✓ All public endpoint tests completed!${colors.reset}`);
console.log(`${colors.blue}========================================${colors.reset}`);
console.log('');
console.log('Next steps:');
console.log('1. Run admin tests with an admin account');
console.log('2. Test CSV upload functionality');
console.log('3. Test CSV validation endpoint');
} catch (error) {
printError(`Test failed: ${error.message}`);
console.error(error);
process.exit(1);
}
}
// Run tests
runTests();

View File

@ -1,299 +0,0 @@
#!/bin/bash
# CSV Rate API Test Script
# This script tests all CSV rate endpoints
set -e
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
API_URL="http://localhost:4000"
TOKEN=""
ADMIN_TOKEN=""
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}CSV Rate API Test Script${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""
# Function to print test header
print_test() {
echo -e "${YELLOW}[TEST $1] $2${NC}"
}
# Function to print success
print_success() {
echo -e "${GREEN}✓ $1${NC}"
}
# Function to print error
print_error() {
echo -e "${RED}✗ $1${NC}"
}
# Function to print info
print_info() {
echo -e "${BLUE}→ $1${NC}"
}
# Step 1: Get authentication token
print_test "1" "Authenticating as regular user"
LOGIN_RESPONSE=$(curl -s -X POST "$API_URL/api/v1/auth/login" \
-H "Content-Type: application/json" \
-d '{
"email": "test4@xpeditis.com",
"password": "SecurePassword123"
}')
TOKEN=$(echo $LOGIN_RESPONSE | jq -r '.accessToken')
if [ "$TOKEN" != "null" ] && [ -n "$TOKEN" ]; then
print_success "Regular user authenticated"
print_info "Token: ${TOKEN:0:20}..."
else
print_error "Failed to authenticate regular user"
echo "Response: $LOGIN_RESPONSE"
exit 1
fi
echo ""
# Step 2: Test GET /rates/companies
print_test "2" "GET /rates/companies - Get available companies"
COMPANIES_RESPONSE=$(curl -s -X GET "$API_URL/api/v1/rates/companies" \
-H "Authorization: Bearer $TOKEN")
echo "$COMPANIES_RESPONSE" | jq '.'
COMPANIES_COUNT=$(echo $COMPANIES_RESPONSE | jq '.total')
if [ "$COMPANIES_COUNT" -eq 5 ]; then
print_success "Got 5 companies (including Test Maritime Express)"
else
print_error "Expected 5 companies, got $COMPANIES_COUNT"
fi
echo ""
# Step 3: Test GET /rates/filters/options
print_test "3" "GET /rates/filters/options - Get filter options"
FILTERS_RESPONSE=$(curl -s -X GET "$API_URL/api/v1/rates/filters/options" \
-H "Authorization: Bearer $TOKEN")
echo "$FILTERS_RESPONSE" | jq '.'
print_success "Filter options retrieved"
echo ""
# Step 4: Test POST /rates/search-csv - Basic search
print_test "4" "POST /rates/search-csv - Basic rate search (NLRTM → USNYC)"
SEARCH_RESPONSE=$(curl -s -X POST "$API_URL/api/v1/rates/search-csv" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $TOKEN" \
-d '{
"origin": "NLRTM",
"destination": "USNYC",
"volumeCBM": 25.5,
"weightKG": 3500,
"palletCount": 10,
"containerType": "LCL"
}')
echo "$SEARCH_RESPONSE" | jq '.'
TOTAL_RESULTS=$(echo $SEARCH_RESPONSE | jq '.totalResults')
print_info "Total results: $TOTAL_RESULTS"
# Check if Test Maritime Express is in results
HAS_TEST_MARITIME=$(echo $SEARCH_RESPONSE | jq '.results[] | select(.companyName == "Test Maritime Express") | .companyName' | wc -l)
if [ "$HAS_TEST_MARITIME" -gt 0 ]; then
print_success "Test Maritime Express found in results"
# Get Test Maritime Express price
TEST_PRICE=$(echo $SEARCH_RESPONSE | jq '.results[] | select(.companyName == "Test Maritime Express") | .totalPrice.amount' | head -1)
print_info "Test Maritime Express price: \$$TEST_PRICE"
else
print_error "Test Maritime Express NOT found in results"
fi
# Count unique companies in results
UNIQUE_COMPANIES=$(echo $SEARCH_RESPONSE | jq -r '.results[].companyName' | sort -u | wc -l)
print_info "Results from $UNIQUE_COMPANIES different companies"
if [ "$UNIQUE_COMPANIES" -ge 3 ]; then
print_success "Multiple companies in comparator ✓"
else
print_error "Expected multiple companies, got $UNIQUE_COMPANIES"
fi
echo ""
# Step 5: Test POST /rates/search-csv - Filter by company
print_test "5" "POST /rates/search-csv - Filter by Test Maritime Express only"
FILTER_RESPONSE=$(curl -s -X POST "$API_URL/api/v1/rates/search-csv" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $TOKEN" \
-d '{
"origin": "NLRTM",
"destination": "USNYC",
"volumeCBM": 25.5,
"weightKG": 3500,
"palletCount": 10,
"containerType": "LCL",
"filters": {
"companies": ["Test Maritime Express"]
}
}')
echo "$FILTER_RESPONSE" | jq '.results[0:3]'
FILTER_COMPANIES=$(echo $FILTER_RESPONSE | jq -r '.results[].companyName' | sort -u)
if [ "$FILTER_COMPANIES" == "Test Maritime Express" ]; then
print_success "Company filter working correctly"
else
print_error "Company filter not working - got: $FILTER_COMPANIES"
fi
echo ""
# Step 6: Test POST /rates/search-csv - Filter by price range
print_test "6" "POST /rates/search-csv - Filter by price range (\$900-\$1200)"
PRICE_FILTER_RESPONSE=$(curl -s -X POST "$API_URL/api/v1/rates/search-csv" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $TOKEN" \
-d '{
"origin": "NLRTM",
"destination": "USNYC",
"volumeCBM": 25.5,
"weightKG": 3500,
"palletCount": 10,
"containerType": "LCL",
"filters": {
"minPrice": 900,
"maxPrice": 1200,
"currency": "USD"
}
}')
PRICE_RESULTS=$(echo $PRICE_FILTER_RESPONSE | jq '.totalResults')
print_info "Results in price range \$900-\$1200: $PRICE_RESULTS"
# Verify all results are in range
MIN_PRICE=$(echo $PRICE_FILTER_RESPONSE | jq '[.results[].totalPrice.amount] | min')
MAX_PRICE=$(echo $PRICE_FILTER_RESPONSE | jq '[.results[].totalPrice.amount] | max')
if (( $(echo "$MIN_PRICE >= 900" | bc -l) )) && (( $(echo "$MAX_PRICE <= 1200" | bc -l) )); then
print_success "Price filter working correctly (range: \$$MIN_PRICE - \$$MAX_PRICE)"
else
print_error "Price filter not working - got range: \$$MIN_PRICE - \$$MAX_PRICE"
fi
echo ""
# Step 7: Test POST /rates/search-csv - Filter by transit days
print_test "7" "POST /rates/search-csv - Filter by max transit days (≤23 days)"
TRANSIT_FILTER_RESPONSE=$(curl -s -X POST "$API_URL/api/v1/rates/search-csv" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $TOKEN" \
-d '{
"origin": "NLRTM",
"destination": "USNYC",
"volumeCBM": 25.5,
"weightKG": 3500,
"containerType": "LCL",
"filters": {
"maxTransitDays": 23
}
}')
TRANSIT_RESULTS=$(echo $TRANSIT_FILTER_RESPONSE | jq '.totalResults')
print_info "Results with transit ≤23 days: $TRANSIT_RESULTS"
MAX_TRANSIT=$(echo $TRANSIT_FILTER_RESPONSE | jq '[.results[].transitDays] | max')
if [ "$MAX_TRANSIT" -le 23 ]; then
print_success "Transit filter working correctly (max: $MAX_TRANSIT days)"
else
print_error "Transit filter not working - max transit: $MAX_TRANSIT days"
fi
echo ""
# Step 8: Test POST /rates/search-csv - Filter by surcharges
print_test "8" "POST /rates/search-csv - Filter for rates without surcharges (all-in prices)"
SURCHARGE_FILTER_RESPONSE=$(curl -s -X POST "$API_URL/api/v1/rates/search-csv" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $TOKEN" \
-d '{
"origin": "NLRTM",
"destination": "USNYC",
"volumeCBM": 25.5,
"weightKG": 3500,
"containerType": "LCL",
"filters": {
"withoutSurcharges": true
}
}')
SURCHARGE_RESULTS=$(echo $SURCHARGE_FILTER_RESPONSE | jq '.totalResults')
print_info "Results without surcharges: $SURCHARGE_RESULTS"
# Verify all results have hasSurcharges=false
HAS_SURCHARGES=$(echo $SURCHARGE_FILTER_RESPONSE | jq '.results[] | select(.hasSurcharges == true)' | wc -l)
if [ "$HAS_SURCHARGES" -eq 0 ]; then
print_success "Surcharge filter working correctly"
else
print_error "Surcharge filter not working - found $HAS_SURCHARGES results with surcharges"
fi
echo ""
# Step 9: Comparison test - Show all companies for same route
print_test "9" "COMPARATOR TEST - Show all 5 companies for NLRTM → USNYC"
COMPARISON_RESPONSE=$(curl -s -X POST "$API_URL/api/v1/rates/search-csv" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $TOKEN" \
-d '{
"origin": "NLRTM",
"destination": "USNYC",
"volumeCBM": 25,
"weightKG": 3500,
"palletCount": 10,
"containerType": "LCL"
}')
echo "Company Comparison Table:"
echo "========================="
echo "$COMPARISON_RESPONSE" | jq -r '.results[] | "\(.companyName): $\(.totalPrice.amount) \(.totalPrice.currency) - \(.transitDays) days - Match: \(.matchScore)%"' | head -10
COMPANY_LIST=$(echo $COMPARISON_RESPONSE | jq -r '.results[].companyName' | sort -u)
print_info "Companies in results:"
echo "$COMPANY_LIST"
# Check if Test Maritime Express has lowest price
LOWEST_PRICE_COMPANY=$(echo $COMPARISON_RESPONSE | jq -r '[.results[] | {company: .companyName, price: .totalPrice.amount}] | sort_by(.price) | .[0].company')
if [ "$LOWEST_PRICE_COMPANY" == "Test Maritime Express" ]; then
print_success "Test Maritime Express has the lowest price ✓"
LOWEST_PRICE=$(echo $COMPARISON_RESPONSE | jq -r '[.results[]] | sort_by(.totalPrice.amount) | .[0].totalPrice.amount')
print_info "Lowest price: \$$LOWEST_PRICE (Test Maritime Express)"
else
print_error "Expected Test Maritime Express to have lowest price, but got: $LOWEST_PRICE_COMPANY"
fi
echo ""
echo -e "${BLUE}========================================${NC}"
echo -e "${GREEN}✓ All public endpoint tests completed!${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""
echo "Next steps:"
echo "1. Run admin tests with an admin account"
echo "2. Test CSV upload functionality"
echo "3. Test CSV validation endpoint"
echo ""
echo "For admin tests, you need to:"
echo "1. Create an admin user or promote existing user to ADMIN role"
echo "2. Authenticate to get admin JWT token"
echo "3. Run admin endpoints (upload, validate, delete)"

View File

@ -1,125 +0,0 @@
#!/bin/bash
# Test script pour créer un CSV booking via API et vérifier l'envoi d'email
#
# Usage: ./test-csv-booking-api.sh
echo "🧪 Test de création de CSV Booking avec envoi d'email"
echo "======================================================"
echo ""
# Configuration
API_URL="http://localhost:4000/api/v1"
TEST_EMAIL="transporteur@test.com"
# Couleurs
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
echo -e "${YELLOW}📋 Étape 1: Connexion et obtention du token JWT${NC}"
echo "----------------------------------------------"
# Login (utilisez vos credentials de test)
LOGIN_RESPONSE=$(curl -s -X POST "${API_URL}/auth/login" \
-H "Content-Type: application/json" \
-d '{
"email": "admin@xpeditis.com",
"password": "admin123"
}')
echo "Response: $LOGIN_RESPONSE"
# Extraire le token
TOKEN=$(echo $LOGIN_RESPONSE | grep -o '"accessToken":"[^"]*"' | cut -d'"' -f4)
if [ -z "$TOKEN" ]; then
echo -e "${RED}❌ Échec de connexion. Vérifiez vos credentials.${NC}"
echo "Essayez avec d'autres credentials ou créez un utilisateur de test."
exit 1
fi
echo -e "${GREEN}✅ Token obtenu: ${TOKEN:0:20}...${NC}"
echo ""
echo -e "${YELLOW}📋 Étape 2: Création d'un fichier de test${NC}"
echo "----------------------------------------------"
# Créer un fichier PDF factice
cat > /tmp/test-bol.txt << EOF
BILL OF LADING - TEST
====================
Booking ID: TEST-$(date +%s)
Origin: FRPAR
Destination: USNYC
Date: $(date)
This is a test document.
EOF
echo -e "${GREEN}✅ Fichier de test créé: /tmp/test-bol.txt${NC}"
echo ""
echo -e "${YELLOW}📋 Étape 3: Création du CSV booking${NC}"
echo "----------------------------------------------"
echo "Email transporteur: $TEST_EMAIL"
echo ""
# Créer le booking avec curl multipart
BOOKING_RESPONSE=$(curl -s -X POST "${API_URL}/csv-bookings" \
-H "Authorization: Bearer ${TOKEN}" \
-F "carrierName=Test Carrier Ltd" \
-F "carrierEmail=${TEST_EMAIL}" \
-F "origin=FRPAR" \
-F "destination=USNYC" \
-F "volumeCBM=12.5" \
-F "weightKG=850" \
-F "palletCount=4" \
-F "priceUSD=1800" \
-F "priceEUR=1650" \
-F "primaryCurrency=USD" \
-F "transitDays=16" \
-F "containerType=20FT" \
-F "notes=Test booking créé via script automatique" \
-F "files=@/tmp/test-bol.txt")
echo "Response:"
echo "$BOOKING_RESPONSE" | jq '.' 2>/dev/null || echo "$BOOKING_RESPONSE"
echo ""
# Vérifier si le booking a été créé
BOOKING_ID=$(echo $BOOKING_RESPONSE | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
if [ -z "$BOOKING_ID" ]; then
echo -e "${RED}❌ Échec de création du booking${NC}"
echo "Vérifiez les logs du backend pour plus de détails."
exit 1
fi
echo -e "${GREEN}✅ Booking créé avec succès!${NC}"
echo " Booking ID: $BOOKING_ID"
echo ""
echo -e "${YELLOW}📋 Étape 4: Vérification des logs backend${NC}"
echo "----------------------------------------------"
echo "Recherchez dans les logs backend:"
echo " ✅ Email sent to carrier: ${TEST_EMAIL}"
echo " ✅ CSV booking request sent to ${TEST_EMAIL}"
echo ""
echo "Si vous NE voyez PAS ces logs, l'email n'a PAS été envoyé."
echo ""
echo -e "${YELLOW}📋 Étape 5: Vérifier Mailtrap${NC}"
echo "----------------------------------------------"
echo "1. Ouvrez: https://mailtrap.io/inboxes"
echo "2. Cherchez: 'Nouvelle demande de réservation - FRPAR → USNYC'"
echo "3. Vérifiez: Le template HTML avec boutons Accepter/Refuser"
echo ""
echo -e "${GREEN}✅ Test terminé${NC}"
echo "Si vous ne recevez pas l'email:"
echo " 1. Vérifiez les logs backend (voir ci-dessus)"
echo " 2. Exécutez: node debug-email-flow.js"
echo " 3. Vérifiez que le backend a bien redémarré avec la correction"
echo ""

View File

@ -1,282 +0,0 @@
#!/bin/bash
# Script de test pour l'API de génération d'offres CSV
# Usage: ./test-csv-offers-api.sh
set -e
echo "================================================"
echo "🧪 Test de l'API - Génération d'Offres CSV"
echo "================================================"
echo ""
# Configuration
API_URL="http://localhost:4000/api/v1"
JWT_TOKEN=""
# Couleurs pour l'output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Fonction pour afficher les résultats
print_step() {
echo -e "${BLUE}➜${NC} $1"
}
print_success() {
echo -e "${GREEN}✓${NC} $1"
}
print_error() {
echo -e "${RED}✗${NC} $1"
}
print_info() {
echo -e "${YELLOW}ℹ${NC} $1"
}
# Étape 1: Login
print_step "Étape 1: Authentification"
echo ""
LOGIN_RESPONSE=$(curl -s -X POST "${API_URL}/auth/login" \
-H "Content-Type: application/json" \
-d '{
"email": "admin@xpeditis.com",
"password": "Admin123!"
}')
JWT_TOKEN=$(echo $LOGIN_RESPONSE | jq -r '.accessToken')
if [ "$JWT_TOKEN" != "null" ] && [ ! -z "$JWT_TOKEN" ]; then
print_success "Authentification réussie"
print_info "Token: ${JWT_TOKEN:0:20}..."
else
print_error "Échec de l'authentification"
echo "Réponse: $LOGIN_RESPONSE"
exit 1
fi
echo ""
echo "================================================"
echo ""
# Étape 2: Recherche standard (sans offres)
print_step "Étape 2: Recherche CSV standard (sans offres)"
echo ""
STANDARD_RESPONSE=$(curl -s -X POST "${API_URL}/rates/search-csv" \
-H "Authorization: Bearer ${JWT_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"origin": "FRPAR",
"destination": "USNYC",
"volumeCBM": 5.0,
"weightKG": 1000,
"palletCount": 2
}')
STANDARD_RESULTS=$(echo $STANDARD_RESPONSE | jq -r '.totalResults // 0')
print_info "Résultats trouvés (standard): $STANDARD_RESULTS"
if [ "$STANDARD_RESULTS" -gt "0" ]; then
print_success "Recherche standard réussie"
# Afficher le premier résultat
echo ""
print_info "Premier résultat (standard):"
echo $STANDARD_RESPONSE | jq '.results[0] | {
companyName: .rate.companyName,
priceUSD: .calculatedPrice.usd,
transitDays: .rate.transitDays,
serviceLevel: .serviceLevel
}' | sed 's/^/ /'
else
print_error "Aucun résultat trouvé (vérifiez que des tarifs CSV sont chargés)"
fi
echo ""
echo "================================================"
echo ""
# Étape 3: Recherche avec génération d'offres
print_step "Étape 3: Recherche CSV avec génération d'offres (RAPID, STANDARD, ECONOMIC)"
echo ""
OFFERS_RESPONSE=$(curl -s -X POST "${API_URL}/rates/search-csv-offers" \
-H "Authorization: Bearer ${JWT_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"origin": "FRPAR",
"destination": "USNYC",
"volumeCBM": 5.0,
"weightKG": 1000,
"palletCount": 2
}')
OFFERS_RESULTS=$(echo $OFFERS_RESPONSE | jq -r '.totalResults // 0')
print_info "Résultats trouvés (avec offres): $OFFERS_RESULTS"
if [ "$OFFERS_RESULTS" -gt "0" ]; then
print_success "Recherche avec offres réussie"
# Vérifier qu'on a bien 3x plus d'offres qu'en standard
EXPECTED_OFFERS=$((STANDARD_RESULTS * 3))
if [ "$OFFERS_RESULTS" -eq "$EXPECTED_OFFERS" ]; then
print_success "Nombre d'offres correct: $OFFERS_RESULTS (= $STANDARD_RESULTS tarifs × 3 offres)"
else
print_info "Offres générées: $OFFERS_RESULTS (attendu: $EXPECTED_OFFERS)"
fi
echo ""
print_info "Première offre de chaque type:"
echo ""
# Afficher une offre ECONOMIC
print_info "📦 Offre ECONOMIC (moins chère + plus lente):"
echo $OFFERS_RESPONSE | jq '.results[] | select(.serviceLevel == "ECONOMIC") | {
companyName: .rate.companyName,
serviceLevel: .serviceLevel,
priceUSD: .calculatedPrice.usd,
originalPriceUSD: .originalPrice.usd,
transitDays: .rate.transitDays,
originalTransitDays: .originalTransitDays,
priceAdjustment: "-15%",
transitAdjustment: "+50%"
}' | head -n 12 | sed 's/^/ /'
echo ""
# Afficher une offre STANDARD
print_info "📦 Offre STANDARD (prix et transit de base):"
echo $OFFERS_RESPONSE | jq '.results[] | select(.serviceLevel == "STANDARD") | {
companyName: .rate.companyName,
serviceLevel: .serviceLevel,
priceUSD: .calculatedPrice.usd,
originalPriceUSD: .originalPrice.usd,
transitDays: .rate.transitDays,
originalTransitDays: .originalTransitDays,
priceAdjustment: "Aucun",
transitAdjustment: "Aucun"
}' | head -n 12 | sed 's/^/ /'
echo ""
# Afficher une offre RAPID
print_info "📦 Offre RAPID (plus chère + plus rapide):"
echo $OFFERS_RESPONSE | jq '.results[] | select(.serviceLevel == "RAPID") | {
companyName: .rate.companyName,
serviceLevel: .serviceLevel,
priceUSD: .calculatedPrice.usd,
originalPriceUSD: .originalPrice.usd,
transitDays: .rate.transitDays,
originalTransitDays: .originalTransitDays,
priceAdjustment: "+20%",
transitAdjustment: "-30%"
}' | head -n 12 | sed 's/^/ /'
echo ""
echo "================================================"
echo ""
# Validation de la logique métier
print_step "Validation de la logique métier"
echo ""
# Extraire les prix et transit pour validation
ECONOMIC_PRICE=$(echo $OFFERS_RESPONSE | jq -r '.results[] | select(.serviceLevel == "ECONOMIC") | .calculatedPrice.usd' | head -1)
STANDARD_PRICE=$(echo $OFFERS_RESPONSE | jq -r '.results[] | select(.serviceLevel == "STANDARD") | .calculatedPrice.usd' | head -1)
RAPID_PRICE=$(echo $OFFERS_RESPONSE | jq -r '.results[] | select(.serviceLevel == "RAPID") | .calculatedPrice.usd' | head -1)
ECONOMIC_TRANSIT=$(echo $OFFERS_RESPONSE | jq -r '.results[] | select(.serviceLevel == "ECONOMIC") | .rate.transitDays' | head -1)
STANDARD_TRANSIT=$(echo $OFFERS_RESPONSE | jq -r '.results[] | select(.serviceLevel == "STANDARD") | .rate.transitDays' | head -1)
RAPID_TRANSIT=$(echo $OFFERS_RESPONSE | jq -r '.results[] | select(.serviceLevel == "RAPID") | .rate.transitDays' | head -1)
# Validation: RAPID plus cher que STANDARD
if (( $(echo "$RAPID_PRICE > $STANDARD_PRICE" | bc -l) )); then
print_success "RAPID plus cher que STANDARD ($RAPID_PRICE > $STANDARD_PRICE) ✓"
else
print_error "RAPID devrait être plus cher que STANDARD"
fi
# Validation: ECONOMIC moins cher que STANDARD
if (( $(echo "$ECONOMIC_PRICE < $STANDARD_PRICE" | bc -l) )); then
print_success "ECONOMIC moins cher que STANDARD ($ECONOMIC_PRICE < $STANDARD_PRICE) ✓"
else
print_error "ECONOMIC devrait être moins cher que STANDARD"
fi
# Validation: RAPID plus rapide que STANDARD
if (( $(echo "$RAPID_TRANSIT < $STANDARD_TRANSIT" | bc -l) )); then
print_success "RAPID plus rapide que STANDARD ($RAPID_TRANSIT < $STANDARD_TRANSIT jours) ✓"
else
print_error "RAPID devrait être plus rapide que STANDARD"
fi
# Validation: ECONOMIC plus lent que STANDARD
if (( $(echo "$ECONOMIC_TRANSIT > $STANDARD_TRANSIT" | bc -l) )); then
print_success "ECONOMIC plus lent que STANDARD ($ECONOMIC_TRANSIT > $STANDARD_TRANSIT jours) ✓"
else
print_error "ECONOMIC devrait être plus lent que STANDARD"
fi
else
print_error "Aucune offre générée"
echo "Réponse: $OFFERS_RESPONSE" | jq '.'
fi
echo ""
echo "================================================"
echo ""
# Étape 4: Test avec filtre de niveau de service
print_step "Étape 4: Test avec filtre de niveau de service (RAPID uniquement)"
echo ""
FILTERED_RESPONSE=$(curl -s -X POST "${API_URL}/rates/search-csv-offers" \
-H "Authorization: Bearer ${JWT_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"origin": "FRPAR",
"destination": "USNYC",
"volumeCBM": 5.0,
"weightKG": 1000,
"palletCount": 2,
"filters": {
"serviceLevels": ["RAPID"]
}
}')
FILTERED_RESULTS=$(echo $FILTERED_RESPONSE | jq -r '.totalResults // 0')
print_info "Résultats filtrés (RAPID uniquement): $FILTERED_RESULTS"
if [ "$FILTERED_RESULTS" -gt "0" ]; then
print_success "Filtre de niveau de service fonctionne"
# Vérifier que toutes les offres sont RAPID
NON_RAPID=$(echo $FILTERED_RESPONSE | jq -r '.results[] | select(.serviceLevel != "RAPID") | .serviceLevel' | wc -l)
if [ "$NON_RAPID" -eq "0" ]; then
print_success "Toutes les offres sont de niveau RAPID ✓"
else
print_error "Certaines offres ne sont pas de niveau RAPID"
fi
else
print_error "Aucun résultat avec filtre RAPID"
fi
echo ""
echo "================================================"
echo ""
print_success "Tests terminés avec succès!"
echo ""
print_info "Pour tester dans Swagger UI:"
print_info " → http://localhost:4000/api/docs"
print_info " → Endpoint: POST /api/v1/rates/search-csv-offers"
echo ""
print_info "Documentation complète:"
print_info " → ALGO_BOOKING_CSV_IMPLEMENTATION.md"
echo ""
echo "================================================"

View File

@ -1,66 +0,0 @@
/**
* Test email with IP address directly (bypass DNS)
*/
const nodemailer = require('nodemailer');
const config = {
host: '3.209.246.195', // IP directe de smtp.mailtrap.io
port: 2525,
secure: false,
auth: {
user: '2597bd31d265eb',
pass: 'cd126234193c89',
},
connectionTimeout: 10000,
greetingTimeout: 10000,
socketTimeout: 30000,
tls: {
rejectUnauthorized: false,
servername: 'smtp.mailtrap.io', // Important pour TLS
},
};
console.log('🧪 Testing SMTP with IP address directly...');
console.log('Config:', {
...config,
auth: { user: config.auth.user, pass: '***' },
});
const transporter = nodemailer.createTransport(config);
console.log('\n1️⃣ Verifying SMTP connection...');
transporter
.verify()
.then(() => {
console.log('✅ SMTP connection verified!');
console.log('\n2️⃣ Sending test email...');
return transporter.sendMail({
from: 'noreply@xpeditis.com',
to: 'test@example.com',
subject: 'Test Xpeditis - Envoi Direct IP',
html: "<h1>✅ Email envoyé avec succès!</h1><p>Ce test utilise l'IP directe pour contourner le DNS.</p>",
});
})
.then(info => {
console.log('✅ Email sent successfully!');
console.log('📧 Message ID:', info.messageId);
console.log('📬 Response:', info.response);
console.log('\n🎉 SUCCESS! Email sending works with IP directly.');
process.exit(0);
})
.catch(error => {
console.error('\n❌ ERROR:', error.message);
console.error('Code:', error.code);
console.error('Command:', error.command);
if (error.code === 'EAUTH') {
console.error('\n⚠️ Authentication failed - credentials may be invalid');
} else if (error.code === 'ETIMEDOUT' || error.code === 'ECONNREFUSED') {
console.error('\n⚠️ Connection failed - firewall or network issue');
}
process.exit(1);
});

View File

@ -1,68 +0,0 @@
/**
* Test l'envoi d'email via le service backend
*/
const axios = require('axios');
const API_URL = 'http://localhost:4000/api/v1';
// Token d'authentification (admin@xpeditis.com)
const AUTH_TOKEN =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI5MTI3Y2M0Zi04Yzg4LTRjNGUtYmU1ZC1hNmY1ZTE2MWZlNDMiLCJlbWFpbCI6ImFkbWluQHhwZWRpdGlzLmNvbSIsInJvbGUiOiJBRE1JTiIsIm9yZ2FuaXphdGlvbklkIjoiMWZhOWE1NjUtZjNjOC00ZTExLTliMzAtMTIwZDEwNTJjZWYwIiwidHlwZSI6ImFjY2VzcyIsImlhdCI6MTc2NDg3NDQ2MSwiZXhwIjoxNzY0ODc1MzYxfQ.l_-97_rikGj-DP8aA14CK-Ab-0Usy722MRe1lqi0u9I';
async function testCsvBookingEmail() {
console.log('🧪 Test envoi email via CSV booking...\n');
try {
// Créer un FormData pour simuler l'upload de fichiers
const FormData = require('form-data');
const fs = require('fs');
const form = new FormData();
// Créer un fichier de test temporaire
const testFile = Buffer.from('Test document content');
form.append('documents', testFile, {
filename: 'test-document.pdf',
contentType: 'application/pdf',
});
// Ajouter les champs du formulaire
form.append('carrierName', 'Test Carrier Email');
form.append('carrierEmail', 'test-carrier@example.com');
form.append('origin', 'NLRTM');
form.append('destination', 'USNYC');
form.append('volumeCBM', '25.5');
form.append('weightKG', '3500');
form.append('palletCount', '10');
form.append('priceUSD', '1850.50');
form.append('priceEUR', '1665.45');
form.append('primaryCurrency', 'USD');
form.append('transitDays', '28');
form.append('containerType', 'LCL');
form.append('notes', 'Test email sending');
console.log('📤 Envoi de la requête de création de CSV booking...');
const response = await axios.post(`${API_URL}/csv-bookings`, form, {
headers: {
...form.getHeaders(),
Authorization: `Bearer ${AUTH_TOKEN}`,
},
});
console.log('✅ Réponse reçue:', response.status);
console.log('📋 Booking créé:', response.data.id);
console.log('\n⚠️ Vérifiez maintenant:');
console.log('1. Les logs du backend pour voir "Email sent to carrier:"');
console.log('2. Votre inbox Mailtrap: https://mailtrap.io/inboxes');
console.log('3. Email destinataire: test-carrier@example.com');
} catch (error) {
console.error('❌ Erreur:', error.response?.data || error.message);
if (error.response?.status === 401) {
console.error("\n⚠️ Token expiré. Connectez-vous d'abord avec:");
console.error('POST /api/v1/auth/login');
console.error('{ "email": "admin@xpeditis.com", "password": "..." }');
}
}
}
testCsvBookingEmail();

View File

@ -1,57 +0,0 @@
/**
* Simple email test script for Mailtrap
* Usage: node test-email.js
*/
const nodemailer = require('nodemailer');
const config = {
host: 'smtp.mailtrap.io',
port: 2525,
secure: false,
auth: {
user: '2597bd31d265eb',
pass: 'cd126234193c89',
},
connectionTimeout: 10000,
greetingTimeout: 10000,
socketTimeout: 30000,
tls: {
rejectUnauthorized: false,
},
dnsTimeout: 10000,
};
console.log('Creating transporter with config:', {
...config,
auth: { user: config.auth.user, pass: '***' },
});
const transporter = nodemailer.createTransport(config);
console.log('\nVerifying SMTP connection...');
transporter
.verify()
.then(() => {
console.log('✅ SMTP connection verified successfully!');
console.log('\nSending test email...');
return transporter.sendMail({
from: 'noreply@xpeditis.com',
to: 'test@example.com',
subject: 'Test Email from Xpeditis',
html: '<h1>Test Email</h1><p>If you see this, email sending works!</p>',
});
})
.then(info => {
console.log('✅ Email sent successfully!');
console.log('Message ID:', info.messageId);
console.log('Response:', info.response);
process.exit(0);
})
.catch(error => {
console.error('❌ Error:', error.message);
console.error('Full error:', error);
process.exit(1);
});

View File

@ -1,74 +0,0 @@
#!/usr/bin/env node
// Test SMTP ultra-simple pour identifier le problème
const nodemailer = require('nodemailer');
require('dotenv').config();
console.log('🔍 Test SMTP Simple\n');
console.log('Configuration:');
console.log(' SMTP_HOST:', process.env.SMTP_HOST || 'NON DÉFINI');
console.log(' SMTP_PORT:', process.env.SMTP_PORT || 'NON DÉFINI');
console.log(' SMTP_USER:', process.env.SMTP_USER || 'NON DÉFINI');
console.log(' SMTP_PASS:', process.env.SMTP_PASS ? '***' : 'NON DÉFINI');
console.log('');
const host = process.env.SMTP_HOST;
const port = parseInt(process.env.SMTP_PORT || '2525');
const user = process.env.SMTP_USER;
const pass = process.env.SMTP_PASS;
// Appliquer le même fix DNS que dans email.adapter.ts
const useDirectIP = host && host.includes('mailtrap.io');
const actualHost = useDirectIP ? '3.209.246.195' : host;
const serverName = useDirectIP ? 'smtp.mailtrap.io' : host;
console.log('Fix DNS:');
console.log(' Utilise IP directe:', useDirectIP);
console.log(' Host réel:', actualHost);
console.log(' Server name:', serverName);
console.log('');
const transporter = nodemailer.createTransport({
host: actualHost,
port,
secure: false,
auth: { user, pass },
tls: {
rejectUnauthorized: false,
servername: serverName,
},
connectionTimeout: 10000,
greetingTimeout: 10000,
socketTimeout: 30000,
dnsTimeout: 10000,
});
async function test() {
try {
console.log('Test 1: Vérification de la connexion...');
await transporter.verify();
console.log('✅ Connexion SMTP OK\n');
console.log("Test 2: Envoi d'un email...");
const info = await transporter.sendMail({
from: 'noreply@xpeditis.com',
to: 'test@example.com',
subject: 'Test - ' + new Date().toISOString(),
html: "<h1>Test réussi!</h1><p>Ce message confirme que l'envoi d'email fonctionne.</p>",
});
console.log('✅ Email envoyé avec succès!');
console.log(' Message ID:', info.messageId);
console.log(' Response:', info.response);
console.log('');
console.log('✅ TOUS LES TESTS RÉUSSIS - Le SMTP fonctionne!');
process.exit(0);
} catch (error) {
console.error('❌ ERREUR:', error.message);
console.error(' Code:', error.code);
console.error(' Command:', error.command);
process.exit(1);
}
}
test();

View File

@ -1,130 +1,52 @@
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 { McpModule } from './application/mcp/mcp.module';
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { ScheduleModule } from '@nestjs/schedule';
import { ConfigModule, ConfigService } from '@nestjs/config'; import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm'; import { TypeOrmModule } from '@nestjs/typeorm';
import { LoggerModule } from 'nestjs-pino'; import { LoggerModule } from 'nestjs-pino';
import { APP_GUARD } from '@nestjs/core'; import { APP_GUARD } from '@nestjs/core';
import {
AcceptLanguageResolver,
CookieResolver,
HeaderResolver,
I18nModule,
QueryResolver,
} from 'nestjs-i18n';
import * as path from 'path';
import * as Joi from 'joi'; import * as Joi from 'joi';
import { UserPreferenceResolver } from './infrastructure/i18n/user-preference.resolver';
import { databaseTlsOptions } from './infrastructure/persistence/typeorm/database-tls';
// Import feature modules // Import feature modules
import { AuthModule } from './application/auth/auth.module'; import { AuthModule } from './application/auth/auth.module';
import { RatesModule } from './application/rates/rates.module'; import { RatesModule } from './application/rates/rates.module';
import { PortsModule } from './application/ports/ports.module';
import { BookingsModule } from './application/bookings/bookings.module'; import { BookingsModule } from './application/bookings/bookings.module';
import { OrganizationsModule } from './application/organizations/organizations.module'; import { OrganizationsModule } from './application/organizations/organizations.module';
import { UsersModule } from './application/users/users.module'; import { UsersModule } from './application/users/users.module';
import { DashboardModule } from './application/dashboard/dashboard.module';
import { AuditModule } from './application/audit/audit.module';
import { NotificationsModule } from './application/notifications/notifications.module';
import { WebhooksModule } from './application/webhooks/webhooks.module';
import { GDPRModule } from './application/gdpr/gdpr.module';
import { CsvBookingsModule } from './application/csv-bookings/csv-bookings.module';
import { AdminModule } from './application/admin/admin.module';
import { BlogModule } from './application/blog/blog.module';
import { LogsModule } from './application/logs/logs.module';
import { SubscriptionsModule } from './application/subscriptions/subscriptions.module';
import { ApiKeysModule } from './application/api-keys/api-keys.module';
import { CacheModule } from './infrastructure/cache/cache.module'; 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 { 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 { JwtAuthGuard } from './application/guards/jwt-auth.guard';
import { HealthController } from './application/controllers/health.controller';
import { CustomThrottlerGuard } from './application/guards/throttle.guard';
@Module({ @Module({
imports: [ imports: [
ScheduleModule.forRoot(),
// Configuration // Configuration
ConfigModule.forRoot({ ConfigModule.forRoot({
isGlobal: true, isGlobal: true,
validationSchema: Joi.object({ validationSchema: Joi.object({
NODE_ENV: Joi.string().valid('development', 'production', 'test').default('development'), NODE_ENV: Joi.string()
.valid('development', 'production', 'test')
.default('development'),
PORT: Joi.number().default(4000), PORT: Joi.number().default(4000),
APP_URL: Joi.string().uri().default('http://localhost:3000'),
BACKEND_URL: Joi.string().uri().optional(),
DATABASE_HOST: Joi.string().required(), DATABASE_HOST: Joi.string().required(),
DATABASE_PORT: Joi.number().default(5432), DATABASE_PORT: Joi.number().default(5432),
DATABASE_USER: Joi.string().required(), DATABASE_USER: Joi.string().required(),
DATABASE_PASSWORD: Joi.string().required(), DATABASE_PASSWORD: Joi.string().required(),
DATABASE_NAME: Joi.string().required(), DATABASE_NAME: Joi.string().required(),
DATABASE_SSL: Joi.boolean().default(false),
DATABASE_SSL_CA: Joi.string().optional(),
REDIS_HOST: Joi.string().required(), REDIS_HOST: Joi.string().required(),
REDIS_PORT: Joi.number().default(6379), REDIS_PORT: Joi.number().default(6379),
REDIS_PASSWORD: Joi.string().required(), REDIS_PASSWORD: Joi.string().required(),
JWT_SECRET: Joi.string().min(32).required(), JWT_SECRET: Joi.string().required(),
JWT_ACCESS_EXPIRATION: Joi.string().default('15m'), JWT_ACCESS_EXPIRATION: Joi.string().default('15m'),
JWT_REFRESH_EXPIRATION: Joi.string().default('7d'), JWT_REFRESH_EXPIRATION: Joi.string().default('7d'),
// Cookie domain for auth cookies (e.g. ".xpeditis.com" so the frontend
// and API subdomains share them). Unset = host-only (fine for localhost).
COOKIE_DOMAIN: Joi.string().optional(),
// Secret used to derive carrier document passwords (falls back to JWT_SECRET)
DOCUMENT_PASSWORD_SECRET: Joi.string().min(16).optional(),
// SMTP Configuration
SMTP_HOST: Joi.string().required(),
SMTP_PORT: Joi.number().default(2525),
SMTP_USER: Joi.string().required(),
SMTP_PASS: Joi.string().required(),
SMTP_FROM: Joi.string().email().default('noreply@xpeditis.com'),
SMTP_SECURE: Joi.boolean().default(false),
// Stripe Configuration (optional for development)
// Purge des donnees arrivees au terme de leur duree de
// conservation. Desactivee par defaut : elle supprime
// definitivement des lignes, l'activer est une decision
// d'exploitation.
RETENTION_PURGE_ENABLED: Joi.string().valid('true', 'false').default('false'),
OPENAI_API_KEY: Joi.string().allow('').optional(),
OPENAI_MODEL: Joi.string().default('gpt-4.1-mini'),
OPENAI_EMBEDDING_MODEL: Joi.string().default('text-embedding-3-small'),
STRIPE_SECRET_KEY: Joi.string().optional(),
STRIPE_WEBHOOK_SECRET: Joi.string().optional(),
STRIPE_SILVER_MONTHLY_PRICE_ID: Joi.string().optional(),
STRIPE_SILVER_YEARLY_PRICE_ID: Joi.string().optional(),
STRIPE_GOLD_MONTHLY_PRICE_ID: Joi.string().optional(),
STRIPE_GOLD_YEARLY_PRICE_ID: Joi.string().optional(),
STRIPE_PLATINIUM_MONTHLY_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'),
// 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'),
}), }),
}), }),
// Logging // Logging
LoggerModule.forRootAsync({ LoggerModule.forRootAsync({
useFactory: (configService: ConfigService) => { useFactory: (configService: ConfigService) => ({
const isDev = configService.get('NODE_ENV') === 'development';
// LOG_FORMAT=json forces structured JSON output (e.g. inside Docker + Promtail)
const forceJson = configService.get('LOG_FORMAT') === 'json';
const usePretty = isDev && !forceJson;
return {
pinoHttp: { pinoHttp: {
serializers: safeHttpSerializers, transport:
transport: usePretty configService.get('NODE_ENV') === 'development'
? { ? {
target: 'pino-pretty', target: 'pino-pretty',
options: { options: {
@ -134,45 +56,10 @@ import { CustomThrottlerGuard } from './application/guards/throttle.guard';
}, },
} }
: undefined, : undefined,
level: isDev ? 'debug' : 'info', level: configService.get('NODE_ENV') === 'production' ? 'info' : 'debug',
// Redact sensitive fields from logs
redact: {
paths: [
'req.headers.authorization',
'req.headers["x-api-key"]',
'req.body.password',
'req.body.currentPassword',
'req.body.newPassword',
],
censor: '[REDACTED]',
}, },
},
};
},
inject: [ConfigService],
}), }),
inject: [ConfigService],
// Internationalization (FR / EN)
// Resolver chain (highest priority first):
// 1. UserPreferenceResolver — authenticated user's preferredLanguage
// 2. CookieResolver (NEXT_LOCALE) — set by frontend switcher
// 3. HeaderResolver (x-lang / x-locale)
// 4. QueryResolver (?lang=xx)
// 5. AcceptLanguageResolver
// 6. fallback → 'fr'
I18nModule.forRoot({
fallbackLanguage: 'fr',
loaderOptions: {
path: path.join(__dirname, '/i18n/'),
watch: true,
},
resolvers: [
UserPreferenceResolver,
new CookieResolver(['NEXT_LOCALE', 'lang']),
new HeaderResolver(['x-lang', 'x-locale']),
new QueryResolver(['lang', 'locale']),
AcceptLanguageResolver,
],
}), }),
// Database // Database
@ -184,61 +71,31 @@ import { CustomThrottlerGuard } from './application/guards/throttle.guard';
username: configService.get('DATABASE_USER'), username: configService.get('DATABASE_USER'),
password: configService.get('DATABASE_PASSWORD'), password: configService.get('DATABASE_PASSWORD'),
database: configService.get('DATABASE_NAME'), database: configService.get('DATABASE_NAME'),
ssl: databaseTlsOptions( entities: [],
configService.get<boolean>('DATABASE_SSL'), synchronize: configService.get('DATABASE_SYNC', false),
configService.get<string>('DATABASE_SSL_CA'),
configService.get<string>('DATABASE_HOST')
),
entities: [__dirname + '/**/*.orm-entity{.ts,.js}'],
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()
}), }),
inject: [ConfigService], inject: [ConfigService],
}), }),
// Infrastructure modules // Infrastructure modules
SecurityModule,
CacheModule, CacheModule,
CarrierModule, CarrierModule,
CsvRateModule,
// Un administrateur exploitable a chaque lancement (base neuve comprise)
AdminBootstrapModule,
// Feature modules // Feature modules
AuthModule, AuthModule,
RatesModule, RatesModule,
PortsModule,
BookingsModule, BookingsModule,
CsvBookingsModule,
OrganizationsModule, OrganizationsModule,
UsersModule, UsersModule,
DashboardModule,
AuditModule,
NotificationsModule,
WebhooksModule,
GDPRModule,
AdminModule,
BlogModule,
SubscriptionsModule,
TradeAssistantModule,
McpModule,
ApiKeysModule,
LogsModule,
], ],
controllers: [HealthController], controllers: [],
providers: [ providers: [
// Global authentication guard — supports both JWT (frontend) and API key (Gold/Platinium) // Global JWT authentication guard
// All routes are protected by default, use @Public() to bypass // All routes are protected by default, use @Public() to bypass
{ {
provide: APP_GUARD, provide: APP_GUARD,
useClass: ApiKeyOrJwtGuard, useClass: JwtAuthGuard,
},
// Global rate limiting guard
{
provide: APP_GUARD,
useClass: CustomThrottlerGuard,
}, },
], ],
}) })

View File

@ -1,68 +0,0 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule } from '@nestjs/config';
// Controller
import { AdminController } from '../controllers/admin.controller';
// ORM Entities
import { UserOrmEntity } from '@infrastructure/persistence/typeorm/entities/user.orm-entity';
import { OrganizationOrmEntity } from '@infrastructure/persistence/typeorm/entities/organization.orm-entity';
import { CsvBookingOrmEntity } from '@infrastructure/persistence/typeorm/entities/csv-booking.orm-entity';
// Repositories
import { TypeOrmUserRepository } from '@infrastructure/persistence/typeorm/repositories/typeorm-user.repository';
import { TypeOrmOrganizationRepository } from '@infrastructure/persistence/typeorm/repositories/typeorm-organization.repository';
import { TypeOrmCsvBookingRepository } from '@infrastructure/persistence/typeorm/repositories/csv-booking.repository';
// Repository tokens
import { USER_REPOSITORY } from '@domain/ports/out/user.repository';
import { ORGANIZATION_REPOSITORY } from '@domain/ports/out/organization.repository';
// SIRET verification
import { SIRET_VERIFICATION_PORT } from '@domain/ports/out/siret-verification.port';
import { PappersSiretAdapter } from '@infrastructure/external/pappers-siret.adapter';
// CSV Booking Service
import { CsvBookingsModule } from '../csv-bookings/csv-bookings.module';
// Email
import { EmailModule } from '@infrastructure/email/email.module';
// Blog
import { BlogModule } from '../blog/blog.module';
// Storage
import { StorageModule } from '@infrastructure/storage/storage.module';
// User deletion (GDPR erasure)
import { GDPRModule } from '../gdpr/gdpr.module';
@Module({
imports: [
TypeOrmModule.forFeature([UserOrmEntity, OrganizationOrmEntity, CsvBookingOrmEntity]),
ConfigModule,
CsvBookingsModule,
EmailModule,
BlogModule,
StorageModule,
GDPRModule,
],
controllers: [AdminController],
providers: [
{
provide: USER_REPOSITORY,
useClass: TypeOrmUserRepository,
},
{
provide: ORGANIZATION_REPOSITORY,
useClass: TypeOrmOrganizationRepository,
},
TypeOrmCsvBookingRepository,
{
provide: SIRET_VERIFICATION_PORT,
useClass: PappersSiretAdapter,
},
],
})
export class AdminModule {}

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

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