# SaaS Spring Boot 3 Multi-Tenant API

## Overview
This project is a production-ready Spring Boot 3 REST API for multi-tenant SaaS applications, designed for scalability, security, and rich features. It offers database-per-tenant isolation, JWT authentication with role-based access control, a DTO layer, global exception handling, audit logging, and OpenAPI documentation. A key focus is a comprehensive VoIP system with multi-provider support (Twilio, Telnyx, Ziwo), flexible AI integration for voicebots (OpenAI, ElevenLabs), and robust cost tracking, enabling advanced features like medical voice assistants and automated SMS confirmations. The business vision is to provide a scalable, secure, and feature-rich backend for SaaS platforms, particularly those requiring advanced communication and AI capabilities.

## User Preferences
I want iterative development.
Ask before making major changes.
I prefer detailed explanations.
Do not make changes to the folder `Z`.
Do not make changes to the file `Y`.

## System Architecture
The system employs a clean architecture with `admin`, `tenant`, and `shared` modules.

- **UI/UX Decisions**: API-driven design supporting frontend integration via clear endpoints and DTOs. OpenAPI/Swagger UI provides interactive documentation.
- **Technical Implementations**:
    - **Authentication & Authorization**: Triple-layer security using legacy `role`, `userType`, and dynamic RBAC permissions. JWTs include `userId`, `tenantId`, `schemaName`, `userType`, and `email`. Spring Security authorities are generated from all three layers for granular control.
    - **Multi-Tenancy**: Database-per-tenant model using MySQL with physical data isolation. Hibernate's `SchemaMultiTenantConnectionProvider` routes connections based on the JWT's `schemaName`. Tenant entities do not contain `tenantId` columns.
    - **Database Migrations Strategy**: **Hibernate auto-DDL (`ddl-auto: update`) for ALL databases** - both admin schema (`saas_db`) and tenant schemas. No Flyway migrations, no manual SQL. Hibernate automatically creates/updates all tables on app startup.
    - **Data Transfer Objects (DTOs)**: Comprehensive DTO layer with MapStruct for entity-DTO mapping.
    - **Global Exception Handling**: Standardized error codes and custom exceptions caught by `@RestControllerAdvice`.
    - **Audit Logging**: AOP-based `@Auditable` annotation for asynchronous CRUD operation logging to a central `audit_logs` table in `saas_db`.
    - **Phone Number Management**: Unified `PhoneNumber` entity supporting multiple VoIP providers with multi-tenant assignment, managed via `AdminPhoneNumberController`.
    - **Per-Tenant VoIP Configuration**: Clean architecture with separated concerns for tenant-specific VoIP settings. `TenantVoipConfigRuntimeService` provides cached runtime resolution, while `TenantVoipConfigAdminService` handles CRUD operations and cache eviction.
    - **VoIP Integration**: Supports Twilio, Telnyx, and Ziwo, with a flexible AI provider abstraction (OpenAI, ElevenLabs) for voicebots, real-time media streaming, and patient data extraction via AI function calling.
    - **SMS Notifications**: Automated, multi-tenant SMS confirmations with delivery tracking via Twilio.
    - **Tenant APIs**: Self-service endpoints for tenants to access their own data, including Cost Analytics, Call Records, and VoIP Configuration.
    - **RBAC System**: Comprehensive permission management with `resource:action` format, roles, and user-role assignments stored in `saas_db`. Integrated with Spring Security via `CustomUserDetailsService` and `CustomPermissionEvaluator` for dynamic permission checks.
    - **Cost Tracking**: Multi-provider call cost tracking system with `CallCostRecord` entity, `CallCostTrackingService`, and provider-specific webhook endpoints.
- **Feature Specifications**:
    - **Triple-Layer Authentication & Routing**: `SYSTEM_ADMIN` users access `saas_db` for cross-tenant administration; `TENANT_USER` users route to their assigned tenant database.
    - **API Documentation**: Comprehensive documentation includes `API_DOCUMENTATION.md`, an importable `API_DOCUMENTATION_INSOMNIA.json` collection, `DEMO_DATA.md`, and auto-generated OpenAPI with Swagger UI.
    - **VoIP Voicebots**: French medical assistant voicebot with configurable AI backend (OpenAI, ElevenLabs).
    - **Patient Data Capture & Conversation Storage**: Dual-database persistence for call data. Conversation transcripts stored as JSON in both admin and tenant databases. Patient/appointment data extracted and persisted in the tenant database only. Call cost records saved to the admin database.
- **System Design Choices**:
    - **Database Architecture**: Dual-database persistence model (`saas_db` for system-wide data and `tenant_X` for isolated tenant data) with automatic routing.
    - **Directory Structure**: Organized into `admin`, `tenant`, and `shared` modules.
    - **Security**: JWT authentication (HS512), BCrypt password hashing, triple-layer authorization, database-per-tenant physical isolation, and dynamic permission loading.
    - **AI Provider Abstraction**: `AiSessionHandler` interface and `VoiceAiSessionFactory` for flexible AI backend selection.

## External Dependencies
- **Spring Boot**: 3.5.6
- **Java**: 19
- **Maven**: 3.x
- **MySQL**: 8.0+
- **Spring Security**: 6.x
- **JJWT**: 0.12.6
- **BCrypt**: Password hashing
- **Hibernate**: 6.x
- **Spring Data JPA**: 3.x
- **MapStruct**: 1.6.3
- **Lombok**: 1.18.30
- **SpringDoc OpenAPI**: 2.3.0
- **Spring Boot Actuator**: Health checks and monitoring
- **Logback**: Logging framework
- **Logstash Encoder**: 7.4
- **spring-dotenv**: 4.0.0
- **Twilio SDK**: 10.6.3
- **OpenAI API**
- **ElevenLabs API**
- **Telnyx API**
- **Ziwo API**