System Architecture
Happy Habitat follows a modern, layered architecture pattern with a clear separation between the frontend presentation layer and the backend business logic layer.Backend Architecture
The backend follows Clean Architecture principles with clear separation of concerns across four main layers.Layer Structure
API Layer
HappyHabitat.API
- Controllers (REST endpoints)
- Middleware (exception handling)
- Program.cs (startup configuration)
- JWT & CORS configuration
Application Layer
HappyHabitat.Application
- Service interfaces
- DTOs (Data Transfer Objects)
- Business logic contracts
Infrastructure Layer
HappyHabitat.Infrastructure
- Service implementations
- ApplicationDbContext
- Data seeders
- External integrations
Domain Layer
HappyHabitat.Domain
- Entity models
- Business rules
- Value objects
- Domain events
API Layer (HappyHabitat.API)
The API layer is responsible for HTTP request handling, routing, and response formatting. Key Components:-
Controllers (
Controllers/): 28 RESTful controllers handling all API endpointsAuthController.cs: Authentication (login, register, password management)UsersController.cs: User CRUD operationsCommunitiesController.cs: Community managementResidentsController.cs: Resident operationsVehiclesController.cs: Vehicle registryPetsController.cs: Pet registryTicketsController.cs: Support ticket system- And more…
-
Middleware (
Middleware/ExceptionHandlingMiddleware.cs): Global exception handling with unified error responses -
Program.cs (
Program.cs:1-285): Application startup and configuration- Dependency injection setup
- JWT authentication configuration
- CORS policy
- Swagger/OpenAPI
- Database migrations and seeding
Program.cs:74-119):
Program.cs:113-119):
AdminCompanyOrSystemAdmin: RequiresADMIN_COMPANYorSYSTEM_ADMINroleSystemAdminOnly: RequiresSYSTEM_ADMINrole only
Infrastructure Layer (HappyHabitat.Infrastructure)
Implements data access, external services, and cross-cutting concerns. ApplicationDbContext (Data/ApplicationDbContext.cs:1-1012):
The central EF Core DbContext managing 46+ entity sets:
Services/):
PasswordHasherService: BCrypt password hashingJwtService: JWT token generation and validationUserService: User management operationsAuthService: Authentication logicVehicleService,PetService,ResidentVisitService: Domain services- And 20+ more service implementations
Seeders/):
InitialSeeder.cs:20-155: Seeds roles, vehicle types, admin user, ticket categoriesDummySeeder.cs: Development test data (only runs in development mode)
Domain Layer (HappyHabitat.Domain)
Contains business entities and rules, independent of infrastructure concerns. Core Entities:- User & Authentication
- Community & Residents
- Vehicles & Pets
- Financial Entities
User (Role (
Entities/User.cs:1-27):Entities/Role.cs:1-14):Entities/AuditBase.cs):
Many entities inherit from AuditBase for automatic timestamp tracking:
Application Layer (HappyHabitat.Application)
Defines service contracts and DTOs for business operations. Service Interfaces (Interfaces/):
Program.cs:122-149):
All services are registered with dependency injection:
Frontend Architecture
The frontend is built with Angular 19 using a component-based architecture.Project Structure
Key Technologies
Angular 19.2
Core framework with standalone components
Tailwind CSS 4
Utility-first styling
DaisyUI 5
Component library
RxJS 7.8
Reactive programming
Chart.js 4.5
Data visualization
TypeScript 5.7
Type safety
API Communication
The frontend communicates with the backend via RESTful HTTP calls: Environment Configuration (src/environments/environment.ts:3-21):
Authentication Flow
JWT Token Generation
Backend validates credentials and generates JWT tokenThe
JwtService creates a token containing:- User ID
- Username
- Roles
- Expiration time
Database Architecture
Schema Overview
Happy Habitat uses SQL Server with Entity Framework Core migrations for schema management. Connection Configuration (appsettings.json:2-4):
Entity Relationships
Key Tables
Users & Roles
Users & Roles
- Users: User accounts with authentication
- Roles: System roles (6 predefined roles)
- UserRoles: Many-to-many relationship
- UserCommunities: User-community associations
Communities & Residents
Communities & Residents
- Communities: Residential complexes
- Residents: Resident profiles linked to users
- CommunityConfigurations: Custom community settings
- CommunityPrices: Pricing structures
- ResidentConfigurations: Resident-specific settings
Assets & Visitors
Assets & Visitors
- Vehicles: Resident vehicle registry
- VehicleTypes: Vehicle classifications
- Pets: Pet registry
- ResidentVisits: Visitor log
Amenities & Bookings
Amenities & Bookings
- Amenities: Community facilities
- Currently implementing booking system
Support & Communication
Support & Communication
- Tickets: Support tickets
- CategoriaTicket: Ticket categories
- StatusTicket: Ticket statuses
- Comentarios: Comments/replies
- Banners: Homepage banners
- Comunicados: Announcements
- Documents: Shared documents
Financial
Financial
- Contratos: Community contracts
- CargosComunidad: Community charges
- PagoComunidad: Community payments
- CargoResidente: Resident charges
- PagoResidente: Resident payments
- PaymentHistory: Payment tracking
- SaldoCuentaBancaria: Bank account balances
Surveys
Surveys
- Encuestas: Surveys
- PreguntasEncuesta: Survey questions
- OpcionesRespuesta: Answer options
- RespuestasResidente: Resident responses
Service Providers
Service Providers
- CommunityProviders: Approved service providers
Database Migrations
Schema changes are managed through EF Core migrations:Data Seeding
Automatic Seeding (Program.cs:240-276):
On startup, the application:
- Applies pending migrations
- Runs
InitialSeeder(creates roles, admin user, vehicle types, ticket data) - In development mode: Runs
DummySeederfor test data
Seed-only mode is available for CI/CD pipelines:This applies migrations and seeds data without starting the web server.
API Architecture
RESTful Endpoints
All endpoints follow REST conventions with standardized responses. Base URL:http://localhost:5080/api
Endpoint Structure:
/api/auth/*- Authentication endpoints/api/users/*- User management/api/communities/*- Community operations/api/residents/*- Resident management/api/vehicles/*- Vehicle registry/api/pets/*- Pet registry/api/residentvisits/*- Visitor management/api/amenities/*- Amenity management/api/tickets/*- Support tickets/api/banners/*- Banner management/api/documents/*- Document storage- And 15+ more endpoint groups…
Error Handling
Unified Error Format (documentacion/API_ERROR_FORMAT.md:1-45):
All API errors follow a consistent structure:
VALIDATION_ERROR(400): Invalid input dataUNAUTHORIZED(401): Authentication requiredNOT_FOUND(404): Resource not foundBAD_REQUEST(400): Invalid operationINTERNAL_ERROR(500): Server errorDATABASE_ERROR(500): Database operation failed
Middleware/ExceptionHandlingMiddleware.cs):
Catches all unhandled exceptions and returns unified error responses with trace IDs for debugging.
Request Size Limits
Global Limit (Program.cs:17-21):
Individual controllers can override this with
[RequestSizeLimit] attributes for file uploads.File Upload System
Upload Directory (Program.cs:225-233):
Files are stored in the uploads/ directory with the structure:
/uploads path.
Security Architecture
Authentication
- JWT Token Structure
- Password Security
- Token Validation
Tokens contain:
- iss: Issuer (“HappyHabitat”)
- aud: Audience (“HappyHabitatUsers”)
- sub: User ID
- unique_name: Username
- email: User email
- role: User roles (array)
- exp: Expiration timestamp
- iat: Issued at timestamp
Authorization
Role-Based Access Control (RBAC):- Controllers use
[Authorize]attribute - Policies enforce role requirements
- Custom authorization policies defined in
Program.cs:113-119
CORS Protection
Development (Program.cs:46-67):
- Allows localhost origins by default
- Credentials enabled for cookie/auth header support
- Requires explicit origin configuration
- Application refuses to start without proper CORS setup
- Semicolon-separated origin list in configuration
Performance Considerations
Database Optimization
- Indexes: Entity Framework creates indexes on foreign keys automatically
- Unique Constraints: Defined on UserRoles, UserCommunities, etc. (
ApplicationDbContext.cs:122-124, 476-478) - Eager Loading: Use
.Include()for related entities to avoid N+1 queries - Async Operations: All database operations use async/await
Caching Strategy
Currently, Happy Habitat does not implement caching. Consider adding:
- Response caching for read-heavy endpoints
- Distributed caching (Redis) for multi-instance deployments
- Memory caching for frequently accessed lookup data (roles, vehicle types)
Scalability
Current Architecture:- Stateless API (JWT tokens, no server sessions)
- Database-backed (SQL Server supports vertical scaling)
- File storage on disk (consider blob storage for horizontal scaling)
- Move file storage to Azure Blob Storage or AWS S3
- Implement distributed caching with Redis
- Use load balancer for multiple API instances
- Configure connection pooling for database
- Consider read replicas for reporting queries
Deployment Architecture
Development
Production
Design Patterns
Happy Habitat implements several design patterns:- Repository Pattern: Implicit through EF Core DbContext
- Service Pattern: Business logic encapsulated in service classes
- Dependency Injection: All dependencies injected via constructor
- Middleware Pattern: Request pipeline customization
- DTO Pattern: Data transfer between layers
- Clean Architecture: Separation of concerns across layers
Next Steps
API Reference
Explore detailed API endpoint documentation
User Management
Learn about user roles and permissions
Community Setup
Configure communities and amenities
Financial Module
Understand billing and payment workflows