Skip to main content

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 endpoints
    • AuthController.cs: Authentication (login, register, password management)
    • UsersController.cs: User CRUD operations
    • CommunitiesController.cs: Community management
    • ResidentsController.cs: Resident operations
    • VehiclesController.cs: Vehicle registry
    • PetsController.cs: Pet registry
    • TicketsController.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
Security Configuration (Program.cs:74-119):
// JWT Bearer Authentication
builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,
        ValidIssuer = jwtIssuer,
        ValidAudience = jwtAudience,
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey))
    };
});
Authorization Policies (Program.cs:113-119):
  • AdminCompanyOrSystemAdmin: Requires ADMIN_COMPANY or SYSTEM_ADMIN role
  • SystemAdminOnly: Requires SYSTEM_ADMIN role 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:
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
public DbSet<Resident> Residents { get; set; }
public DbSet<Community> Communities { get; set; }
public DbSet<Vehicle> Vehicles { get; set; }
public DbSet<Pet> Pets { get; set; }
public DbSet<ResidentVisit> ResidentVisits { get; set; }
public DbSet<Amenity> Amenities { get; set; }
public DbSet<Ticket> Tickets { get; set; }
public DbSet<CargoResidente> CargosResidente { get; set; }
public DbSet<PagoResidente> PagosResidente { get; set; }
// ... and 35+ more
Service Implementations (Services/):
  • PasswordHasherService: BCrypt password hashing
  • JwtService: JWT token generation and validation
  • UserService: User management operations
  • AuthService: Authentication logic
  • VehicleService, PetService, ResidentVisitService: Domain services
  • And 20+ more service implementations
Data Seeders (Seeders/):
  • InitialSeeder.cs:20-155: Seeds roles, vehicle types, admin user, ticket categories
  • DummySeeder.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 (Entities/User.cs:1-27):
public class User : AuditBase
{
    public Guid Id { get; set; }
    public Guid? RoleId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Username { get; set; }
    public string Email { get; set; }
    public string Password { get; set; } // BCrypt hashed
    public bool IsActive { get; set; }
    
    // Navigation properties
    public Role? Role { get; set; }
    public ICollection<UserRole> UserRoles { get; set; }
    public Resident? Resident { get; set; }
    public ICollection<UserCommunity> UserCommunities { get; set; }
}
Role (Entities/Role.cs:1-14):
public class Role
{
    public Guid Id { get; set; }
    public string Code { get; set; }
    public string Description { get; set; }
    
    public ICollection<UserRole> UserRoles { get; set; }
}
AuditBase (Entities/AuditBase.cs): Many entities inherit from AuditBase for automatic timestamp tracking:
public abstract class AuditBase
{
    public DateTime CreatedAt { get; set; }
    public DateTime? UpdatedAt { get; set; }
}

Application Layer (HappyHabitat.Application)

Defines service contracts and DTOs for business operations. Service Interfaces (Interfaces/):
public interface IAuthService
public interface IUserService
public interface IVehicleService
public interface IPetService
public interface IResidentVisitService
public interface IBannerService
public interface IAmenityService
public interface ITicketService
// ... 20+ more interfaces
Registration (Program.cs:122-149): All services are registered with dependency injection:
builder.Services.AddScoped<IPasswordHasherService, PasswordHasherService>();
builder.Services.AddScoped<IJwtService, JwtService>();
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddScoped<IAuthService, AuthService>();
builder.Services.AddScoped<IVehicleService, VehicleService>();
// ... 25+ more service registrations

Frontend Architecture

The frontend is built with Angular 19 using a component-based architecture.

Project Structure

src/app/
├── auth/              # Authentication module
├── components/        # Reusable UI components (24+ components)
├── constants/         # Application constants
├── enums/             # TypeScript enums
├── guards/            # Route guards (auth, role)
├── interceptors/      # HTTP interceptors (auth, error)
├── interfaces/        # TypeScript interfaces
├── layouts/           # Layout components (8+ layouts)
├── pages/             # Page components (6+ pages)
├── services/          # Angular services
├── shared/            # Shared utilities (20+ utilities)
└── utils/             # Helper functions

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):
export const environment = {
  production: false,
  apiUrl: 'http://localhost:5080/api',
  apiVersion: 'v1',
  appName: 'Happy Habitat',
  logging: {
    level: LogLevel.DEBUG,
    enableConsole: true,
    enableRemote: false,
    enableStackTraces: true
  },
  auth: {
    useMockAuth: false
  }
};

Authentication Flow

1

User Login

User submits credentials via login form
POST /api/auth/login
{
  "username": "elgrandeahc",
  "password": "abc123"
}
2

JWT Token Generation

Backend validates credentials and generates JWT tokenThe JwtService creates a token containing:
  • User ID
  • Username
  • Email
  • Roles
  • Expiration time
3

Token Storage

Frontend stores the JWT token in localStorage or sessionStorage
4

Authenticated Requests

All subsequent API requests include the token in the Authorization header:
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
5

Token Validation

Backend middleware validates the token on each request (Program.cs:94-111)
6

Authorization Check

Role-based authorization policies determine endpoint access

Database Architecture

Schema Overview

Happy Habitat uses SQL Server with Entity Framework Core migrations for schema management. Connection Configuration (appsettings.json:2-4):
{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(local);Database=HappyHabitat;Trusted_Connection=True;TrustServerCertificate=True;"
  }
}

Entity Relationships

Key Tables

  • Users: User accounts with authentication
  • Roles: System roles (6 predefined roles)
  • UserRoles: Many-to-many relationship
  • UserCommunities: User-community associations
  • Communities: Residential complexes
  • Residents: Resident profiles linked to users
  • CommunityConfigurations: Custom community settings
  • CommunityPrices: Pricing structures
  • ResidentConfigurations: Resident-specific settings
  • Vehicles: Resident vehicle registry
  • VehicleTypes: Vehicle classifications
  • Pets: Pet registry
  • ResidentVisits: Visitor log
  • Amenities: Community facilities
  • Currently implementing booking system
  • Tickets: Support tickets
  • CategoriaTicket: Ticket categories
  • StatusTicket: Ticket statuses
  • Comentarios: Comments/replies
  • Banners: Homepage banners
  • Comunicados: Announcements
  • Documents: Shared documents
  • Contratos: Community contracts
  • CargosComunidad: Community charges
  • PagoComunidad: Community payments
  • CargoResidente: Resident charges
  • PagoResidente: Resident payments
  • PaymentHistory: Payment tracking
  • SaldoCuentaBancaria: Bank account balances
  • Encuestas: Surveys
  • PreguntasEncuesta: Survey questions
  • OpcionesRespuesta: Answer options
  • RespuestasResidente: Resident responses
  • CommunityProviders: Approved service providers

Database Migrations

Schema changes are managed through EF Core migrations:
# Create a new migration
dotnet ef migrations add MigrationName -p HappyHabitat.Infrastructure -s HappyHabitat.API

# Apply migrations
dotnet ef database update -p HappyHabitat.Infrastructure -s HappyHabitat.API

# Remove last migration (if not applied)
dotnet ef migrations remove -p HappyHabitat.Infrastructure -s HappyHabitat.API

Data Seeding

Automatic Seeding (Program.cs:240-276): On startup, the application:
  1. Applies pending migrations
  2. Runs InitialSeeder (creates roles, admin user, vehicle types, ticket data)
  3. In development mode: Runs DummySeeder for test data
Seed-only mode is available for CI/CD pipelines:
dotnet run --seed-only
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:
{
  "code": "VALIDATION_ERROR",
  "message": "One or more validation errors occurred.",
  "errors": {
    "Email": ["Email is required"],
    "Password": ["Password must be at least 6 characters"]
  },
  "traceId": "00-abc123..."
}
Error Codes:
  • VALIDATION_ERROR (400): Invalid input data
  • UNAUTHORIZED (401): Authentication required
  • NOT_FOUND (404): Resource not found
  • BAD_REQUEST (400): Invalid operation
  • INTERNAL_ERROR (500): Server error
  • DATABASE_ERROR (500): Database operation failed
Global Exception Middleware (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):
builder.WebHost.ConfigureKestrel(options =>
{
    options.Limits.MaxRequestBodySize = 10 * 1024 * 1024; // 10 MB
});
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/
└── {communityId}/
    └── {category}/
        └── {residentId}/
            └── {filename}.{ext}
Static file serving is configured to expose the uploads directory at /uploads path.

Security Architecture

Authentication

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
Example:
[Authorize(Policy = "AdminCompanyOrSystemAdmin")]
public class CommunitiesController : ControllerBase
{
    // Only ADMIN_COMPANY and SYSTEM_ADMIN can access
}

CORS Protection

Development (Program.cs:46-67):
  • Allows localhost origins by default
  • Credentials enabled for cookie/auth header support
Production:
  • 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)
Scaling Recommendations:
  1. Move file storage to Azure Blob Storage or AWS S3
  2. Implement distributed caching with Redis
  3. Use load balancer for multiple API instances
  4. Configure connection pooling for database
  5. Consider read replicas for reporting queries

Deployment Architecture

Development

Developer Machine
├── Frontend (ng serve) - localhost:4200
├── Backend (dotnet run) - localhost:5080
└── SQL Server - (local)

Production

Cloud/On-Premise
├── Web Server (IIS/Nginx)
│   └── Angular SPA (static files)
├── Application Server
│   └── .NET API (Kestrel behind reverse proxy)
├── Database Server
│   └── SQL Server (with backups)
└── File Storage
    └── Blob storage or network share
Production Checklist:
  • Set secure JWT key
  • Configure CORS origins
  • Disable database recreation
  • Enable HTTPS/SSL
  • Configure proper connection strings
  • Set up database backups
  • Configure logging and monitoring
  • Review and set request size limits
  • Implement rate limiting (recommended)
  • Set up health checks

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

Build docs developers (and LLMs) love