Aller au contenu principal

Backend Documentation

Overview

The backend is built with NestJS following Clean Architecture and Domain Driven Design principles.

Project Structure

backend/src/
├── __tests__/ # Unit tests
├── _generated/ # Generated types from OpenAPI
├── auth/ # Authentication module
├── common/ # Shared utilities
├── contacts/ # Contact management
├── contact-files/ # Contact file management
├── db/ # Database service
├── duplicates/ # Duplicate management
├── extraction/ # OCR and LLM extraction
├── notifications/ # Notification system
├── session-files/ # Session file management
├── sessions/ # Session management
├── storage/ # File storage (R2)
├── stripe/ # Stripe integration (subscriptions, payments)
├── tags/ # Tag system
├── users/ # User management
├── analytics/ # Analytics and reporting
├── audit/ # Audit logging
├── availability/ # Availability slots management
├── booking/ # Public booking system
├── cache/ # Redis cache
├── export/ # Data export (CSV, Excel, JSON)
├── gdpr/ # GDPR/RGPD compliance module
├── google-calendar/ # Google Calendar integration
├── pdf/ # PDF generation service
├── rate-limiting/ # API rate limiting
└── websocket/ # WebSocket gateway

Key Modules

Authentication (auth/)

  • JWT token generation and validation
  • Google OAuth integration
  • User guards (ActiveUserGuard)
  • Authentication helpers

See: backend/src/auth/README.md for detailed documentation

Database (db/)

  • Kysely query builder
  • Type-safe database access
  • Connection management

See: backend/src/db/README.md for detailed documentation

Storage (storage/)

  • Cloudflare R2 integration
  • File upload/download
  • File validation

See: backend/src/storage/README.md for detailed documentation

Users (users/)

  • User CRUD operations
  • Profile management
  • Company information
  • Password management
  • Email validation

Sessions (sessions/)

  • Session CRUD operations
  • Session contacts management
  • Session providers management
  • Session tags

Contacts (contacts/)

  • Contact CRUD operations
  • Location data management
  • Contact-session relationships

Tags (tags/)

  • Tag CRUD operations
  • Reusable tagging system

Duplicates (duplicates/)

  • Duplicate registration management
  • Duplicate status tracking

Extraction (extraction/)

  • OCR text extraction
  • LLM-based structured data extraction

See: backend/src/extraction/README.md for detailed documentation

WebSocket (websocket/)

  • Real-time communication
  • Event-based messaging
  • User-specific notifications

See: backend/src/websocket/README.md for detailed documentation

Quotes & Invoices (quotes-invoices/)

  • Quote and invoice management
  • PDF generation
  • Email sending via Gmail API
  • Scheduled emails
  • Variable replacement in email templates

See: backend/src/quotes-invoices/README.md for detailed documentation

Stripe (stripe/)

  • Subscription management (FREE, BASIC, PRO plans)
  • Payment method collection via SetupIntent
  • Payment method attachment and management
  • Invoice payment processing
  • Webhook event handling
  • Payment history tracking

See: backend/src/stripe/README.md for detailed documentation

Environment Variables:

  • STRIPE_SECRET_KEY - Stripe secret key (required)
  • STRIPE_WEBHOOK_SECRET - Webhook signing secret (required for webhooks)
  • STRIPE_PUBLISHABLE_KEY - Stripe publishable key (for backend, optional)
  • VITE_STRIPE_PUBLISHABLE_KEY - Stripe publishable key for frontend (required for payment forms)

Note: Stripe Price IDs are managed via the admin interface. Go to Admin Panel > Subscription Plans to configure Price IDs for each plan.

Scheduled Emails (scheduled-emails/)

  • Deferred email sending
  • Email scheduling and processing
  • Annual re-sending
  • Attachment handling

See: backend/src/scheduled-emails/README.md for detailed documentation

Analytics (analytics/)

  • Dashboard statistics (revenue, quotes, sessions, invoices)
  • Revenue analytics with breakdown by status and period
  • Conversion analytics (quote to invoice conversion rates)
  • Session analytics with status and period breakdown
  • PDF report generation and export

See: backend/src/analytics/README.md for detailed documentation

Audit (audit/)

  • Comprehensive audit logging of user actions
  • Data modification tracking
  • Entity history and traceability
  • Admin audit log interface

See: backend/src/audit/README.md for detailed documentation

Cache (cache/)

  • Redis-based caching for performance
  • Permission caching
  • Frequently accessed data caching
  • Cache invalidation strategies

See: backend/src/cache/README.md for detailed documentation

Export (export/)

  • Data export in multiple formats (CSV, Excel, JSON)
  • GDPR-compliant data export
  • Bulk export of sessions, contacts, quotes, invoices

See: backend/src/export/README.md for detailed documentation

GDPR (gdpr/)

  • GDPR/RGPD compliance module
  • User consent management (NECESSARY, FUNCTIONAL, ANALYTICS, MARKETING, THIRD_PARTY)
  • GDPR request handling (ACCESS, RECTIFICATION, ERASURE, PORTABILITY, OBJECTION, RESTRICTION)
  • Data export and portability
  • Secure data deletion with audit logs
  • Email verification for sensitive operations
  • Protection against race conditions and security vulnerabilities

See: backend/src/gdpr/README.md for detailed documentation

PDF (pdf/)

  • PDF generation from HTML content
  • Support for quotes, invoices, contracts, and analytics reports
  • Automatic upload to R2 storage
  • Signed URL generation for secure downloads

See: backend/src/pdf/README.md for detailed documentation

Rate Limiting (rate-limiting/)

  • API protection against abuse
  • Configurable rate limits per endpoint
  • Redis-based rate limiting
  • IP and user-based limiting

See: backend/src/rate-limiting/README.md for detailed documentation

Availability (availability/)

  • Availability slot management
  • Recurring slot support
  • Slot availability checking
  • Expansion of recurring slots into individual occurrences

Booking (booking/)

  • Public booking system : Permet aux clients de réserver des créneaux via une interface publique
  • BookingController : Gère les réservations publiques (création, annulation)
  • BookingsController : Gère les bookings pour les utilisateurs authentifiés (liste, statistiques, édition, suppression)
  • BookingCancelTokensService : Gère les tokens d'annulation sécurisés
  • Création d'événements Google Calendar avec préfixe [MEETING]
  • Filtrage des créneaux disponibles (exclut les créneaux déjà réservés)
  • Expansion des créneaux récurrents en occurrences individuelles
  • Cache temporaire pour gérer le délai de propagation de Google Calendar
  • Notifications email et in-app pour les réservations et annulations

Endpoints publics :

  • GET /api/public/booking/:userId/info - Informations publiques du User
  • GET /api/public/booking/:userId/availability - Créneaux disponibles
  • POST /api/public/booking/:userId/book - Créer une réservation
  • POST /api/public/booking/cancel/:token - Annuler une réservation

Endpoints protégés :

  • GET /api/bookings - Liste des bookings de l'utilisateur
  • GET /api/bookings/stats - Statistiques des bookings
  • PATCH /api/bookings/:eventId - Mettre à jour un booking
  • DELETE /api/bookings/:eventId - Supprimer un booking

See: docs/BOOKING_SYSTEM.md for detailed documentation

Google Calendar (google-calendar/)

  • Google Calendar API integration
  • Event creation, update, and deletion
  • Calendar synchronization
  • Google Meet link generation
  • Booking event filtering

Development Guidelines

Adding a New Module

  1. Create module directory: src/my-module/
  2. Create files:
    • my-module.module.ts - NestJS module
    • my-module.controller.ts - API endpoints
    • my-module.service.ts - Business logic
    • dto/ - Data transfer objects
  3. Add OpenAPI schemas in openapi/components/
  4. Add OpenAPI paths in openapi/paths/
  5. Run npm run openapi:generate to generate types
  6. Write unit tests in __tests__/

Database Migrations

  1. Create migration in infra/liquibase/changes/XXXX_description/
  2. Add up.sql and down.sql
  3. Update infra/liquibase/changelog-master.yaml
  4. Run migrations: infra/migrate-improved.sh

API Endpoints

All endpoints require:

  • JWT authentication (AuthGuard('jwt'))
  • Active user status (ActiveUserGuard) for most operations
  • Resource ownership verification for modifications

Validation

  • Use Zod schemas for DTO validation
  • Validate in controllers before service calls
  • Return clear error messages

Logging

  • Use structured logging with scopes and emojis
  • Log all important operations
  • Include user context in logs

Error Handling

  • Use NestJS exceptions (BadRequestException, ForbiddenException, etc.)
  • Return consistent error format
  • Log errors with context

Client access tokens

  • Use ClientAccessService.getOrCreateQuoteLink to generate time-limited /client links (currently used for quotes).
  • Tokens are stored in client_access_tokens with a TTL controlled by CLIENT_ACCESS_TOKEN_TTL_HOURS (default 72h).
  • Public resolver endpoints:
    • GET /client-access?token=... returns a sanitized payload (quote, session summary, owner profile).
    • GET /client-access/quotes/{quoteId}?token=... (ensures token matches the quote).
    • POST /client-access/quotes/{quoteId}/accept?token=... to mark a quote as ACCEPTED.
  • Never embed dashboard URLs in emails; always rely on the generated client link.

Testing

Run tests:

npm run test

Write tests for:

  • Service methods
  • Controller endpoints
  • Business logic
  • Edge cases

Use in-memory implementations for repositories in tests.

Environment Variables

See .env.example for required variables:

  • Database connection
  • JWT configuration
  • Google OAuth
  • Cloudflare R2
  • Timeout configuration - See ENV_VARIABLES_TIMEOUT.md for all timeout-related variables

Note: OpenAI API keys are no longer configured via environment variables. Each user configures their own API key in the application's connections settings. The keys are encrypted and stored in the database.

Timeout Management: All timeout configurations are optional and have sensible defaults. See TIMEOUT_MANAGEMENT.md for details.