# System Architecture

## Overview

The Building Management System is built on Laravel 12 following Domain-Driven Design (DDD) principles with a layered architecture approach. This architecture enables scalability, maintainability, and clear separation of concerns.

## High-Level Architecture

```
┌────────────────────────────────────────────────────────────────────────────┐
│                              Client Applications                            │
│                    (Web App, Mobile App, Third-party Integrations)          │
└────────────────────────────────────────────────────────────────────────────┘
                                       │
                                       ▼
┌────────────────────────────────────────────────────────────────────────────┐
│                              API Gateway Layer                              │
│                         (Authentication, Rate Limiting)                      │
│                              Laravel Sanctum                                 │
└────────────────────────────────────────────────────────────────────────────┘
                                       │
                                       ▼
┌────────────────────────────────────────────────────────────────────────────┐
│                            Presentation Layer                               │
│  ┌─────────────┐    ┌─────────────┐    ┌─────────────┐    ┌─────────────┐ │
│  │ Controllers │    │  Requests   │    │  Resources  │    │ Middleware  │ │
│  └─────────────┘    └─────────────┘    └─────────────┘    └─────────────┘ │
└────────────────────────────────────────────────────────────────────────────┘
                                       │
                                       ▼
┌────────────────────────────────────────────────────────────────────────────┐
│                            Application Layer                                │
│  ┌─────────────┐    ┌─────────────┐    ┌─────────────┐    ┌─────────────┐ │
│  │  Services   │    │    DTOs     │    │   Events    │    │  Listeners  │ │
│  └─────────────┘    └─────────────┘    └─────────────┘    └─────────────┘ │
└────────────────────────────────────────────────────────────────────────────┘
                                       │
                                       ▼
┌────────────────────────────────────────────────────────────────────────────┐
│                              Domain Layer                                   │
│  ┌─────────────┐    ┌─────────────┐    ┌─────────────┐    ┌─────────────┐ │
│  │   Models    │    │  Policies   │    │  Observers  │    │   Scopes    │ │
│  └─────────────┘    └─────────────┘    └─────────────┘    └─────────────┘ │
└────────────────────────────────────────────────────────────────────────────┘
                                       │
                                       ▼
┌────────────────────────────────────────────────────────────────────────────┐
│                           Infrastructure Layer                              │
│  ┌─────────────┐    ┌─────────────┐    ┌─────────────┐    ┌─────────────┐ │
│  │ Repositories│    │  Database   │    │   Cache     │    │   Queue     │ │
│  └─────────────┘    └─────────────┘    └─────────────┘    └─────────────┘ │
└────────────────────────────────────────────────────────────────────────────┘
```

## Layer Responsibilities

### 1. Presentation Layer

**Location**: `app/Http/`

Handles HTTP requests and responses. This layer is responsible for:
- Receiving and validating incoming requests
- Transforming data for client consumption
- Managing HTTP-specific concerns (headers, status codes)

| Component | Location | Responsibility |
|-----------|----------|----------------|
| Controllers | `Http/Controllers/V1/` | Handle HTTP requests, delegate to services |
| Form Requests | `Http/Requests/` | Validate incoming data |
| Resources | `Http/Resources/V1/` | Transform models to JSON responses |
| Middleware | `Http/Middleware/` | Cross-cutting HTTP concerns |

### 2. Application Layer

**Location**: `app/Domains/*/Services/`, `app/Domains/*/DTOs/`

Orchestrates business operations and coordinates between layers:
- Implements use cases and business workflows
- Coordinates multiple domain operations
- Handles transaction management

| Component | Location | Responsibility |
|-----------|----------|----------------|
| Services | `Domains/*/Services/` | Business logic and orchestration |
| DTOs | `Domains/*/DTOs/` | Data transfer between layers |
| Events | `Domains/*/Events/` | Domain event definitions |
| Listeners | `Domains/*/Listeners/` | Event handlers |

### 3. Domain Layer

**Location**: `app/Domains/*/Models/`

Contains the core business logic and domain rules:
- Defines business entities and relationships
- Encapsulates business rules and validations
- Maintains domain integrity

| Component | Location | Responsibility |
|-----------|----------|----------------|
| Models | `Domains/*/Models/` | Business entities with Eloquent |
| Policies | `Domains/*/Policies/` | Authorization rules |
| Observers | `Domains/*/Observers/` | Model lifecycle hooks |
| Scopes | Within Models | Query scoping logic |

### 4. Infrastructure Layer

**Location**: `app/Core/`, `database/`, `config/`

Provides technical capabilities to other layers:
- Database access and persistence
- External service integrations
- Caching and queueing

| Component | Location | Responsibility |
|-----------|----------|----------------|
| Contracts | `Domains/*/Contracts/` | Repository interfaces |
| Migrations | `database/migrations/` | Database schema |
| Seeders | `database/seeders/` | Initial data |
| Config | `config/` | Application configuration |

## Directory Structure

```
app/
├── Core/                           # Shared infrastructure
│   ├── Enums/                      # Shared enumerations
│   ├── Facades/                    # Service facades
│   ├── Helpers/                    # Global helper functions
│   ├── Interfaces/                 # Shared contracts
│   ├── Rules/                      # Custom validation rules
│   ├── Services/                   # Core services
│   └── Traits/                     # Shared traits
│
├── Domains/                        # Business domains
│   ├── Accounting/                 # Financial operations
│   ├── Catalog/                    # Product catalog
│   ├── Construction/               # Project management
│   ├── Contracts/                  # Contract management
│   ├── Core/                       # Cross-cutting domain
│   ├── CRM/                        # Customer relations
│   ├── Maintenance/                # Maintenance operations
│   ├── Management/                 # HR and admin
│   ├── Procurement/                # Purchasing
│   └── Supply/                     # Supply chain
│
├── Http/                           # HTTP layer
│   ├── Controllers/V1/             # API controllers
│   ├── Middleware/                 # Request middleware
│   ├── Requests/                   # Form requests
│   └── Resources/V1/               # API resources
│
└── Providers/                      # Service providers
```

## Design Patterns

### Repository Pattern

Used for data access abstraction:

```php
// Contract
interface ProductRepositoryContract
{
    public function find(int $id): ?Product;
    public function create(array $data): Product;
}

// Implementation
class ProductRepository implements ProductRepositoryContract
{
    public function find(int $id): ?Product
    {
        return Product::find($id);
    }
}
```

### Service Layer Pattern

Business logic encapsulation:

```php
class UserService
{
    public function __construct(
        private UserRepositoryContract $repository
    ) {}

    public function createUser(UserDTO $dto): User
    {
        // Business logic here
        return $this->repository->create($dto->toArray());
    }
}
```

### DTO Pattern

Data transfer between layers:

```php
class UserDTO
{
    public function __construct(
        public readonly string $name,
        public readonly string $email,
        public readonly ?string $phone = null
    ) {}

    public static function fromRequest(Request $request): self
    {
        return new self(
            name: $request->input('name'),
            email: $request->input('email'),
            phone: $request->input('phone')
        );
    }
}
```

### Observer Pattern

Model lifecycle management:

```php
class UserObserver
{
    public function created(User $user): void
    {
        // Send welcome email
        // Log activity
    }

    public function deleted(User $user): void
    {
        // Cleanup related data
    }
}
```

## Cross-Cutting Concerns

### Authentication

- **Method**: Token-based (Laravel Sanctum)
- **Token Location**: `Authorization: Bearer {token}`
- **Middleware**: `auth:sanctum`

### Authorization

- **Library**: Spatie Laravel Permission
- **Method**: Role-based access control (RBAC)
- **Implementation**: Policies and middleware

### Logging

- **Activity Log**: Spatie Activity Log
- **Error Log**: Laravel Log (storage/logs)
- **Debugging**: Laravel Telescope

### Caching

- **Driver**: Redis
- **Strategies**: Query caching, response caching
- **Invalidation**: Event-based cache clearing

## Scalability Considerations

### Horizontal Scaling

- Stateless API design
- Session storage in Redis/Database
- Queue workers can scale independently

### Vertical Scaling

- Database query optimization
- Eager loading relationships
- Database indexing strategy

### Performance Optimization

- Response caching
- Database connection pooling
- Asset compilation and minification
