# Multi-Tenant Configurable LMS — Architecture & Diagrams
*UML Class, Sequence, and Bounded Context Specifications*

---

## 1. System Architecture

This system leverages a metadata-driven configuration gateway. Transactions (Amortization, Payments, Bucket Classification) dynamically load active rules from a Redis cache, falling back to a temporal database.

```mermaid
graph TD
    React[React Frontend App] -->|REST API Requests| FastAPI[FastAPI Web Gateway]
    
    subgraph ConfigurationService [Configuration & Cache Layer]
        FastAPI -->|1. Resolve Config| Cache[Redis Cache Store]
        Cache -->|Cache Miss| DB[(PostgreSQL Database)]
        DB -->|Cache Fill| Cache
    end

    subgraph DynamicEngines [Core Calculation Engines]
        FastAPI -->|2. Execute Actions| Engines[Modular Strategy Engines]
        Engines -->|Amortization| Interest[Interest Calculation Engine]
        Engines -->|Collections Split| Allocation[Payment Allocation Engine]
        Engines -->|Fees & Taxes| Charge[Charge Calculation Engine]
        Engines -->|Default Tracking| NPA[NPA Classification Engine]
        Engines -->|Account Closing| Settlement[Settlement & Foreclosure Engine]
    end

    subgraph Persistence [Transaction Repositories]
        Engines -->|Write Results| Repos[Repository Pattern Layer]
        Repos -->|Persist Transactions| DB
    end

    style ConfigurationService fill:#1e1b4b,stroke:#4f46e5,stroke-width:2px,color:#fff
    style DynamicEngines fill:#0f172a,stroke:#3b82f6,stroke-width:2px,color:#fff
    style Persistence fill:#022c22,stroke:#10b981,stroke-width:2px,color:#fff
```

---

## 2. Sequence Diagram: Loan Activation & Amortization

```mermaid
sequenceDiagram
    autonumber
    actor Ops as Operations / React UI
    participant Router as Loan Router
    participant Service as Loan Service
    participant Config as Configuration Service
    participant Engine as Interest Engine
    participant Repo as Loan Repository
    participant DB as PostgreSQL Database

    Ops->>Router: POST /loans (principal, rate, tenure, product_id)
    Router->>Service: create_loan_and_schedule()
    Service->>Config: get_config(InterestConfiguration, product_id)
    Config-->>Service: Active Config (Basis: ACTUAL_365, Type: REDUCING)
    
    Service->>Engine: generate_amortization_schedule(P, R, T, Basis, Type)
    Note over Engine: Calculates equal monthly PMT;<br/>Interest dynamically computed using Actual/365 daily basis.
    Engine-->>Service: List of Repayment Installments (Principal + Interest)
    
    Service->>Repo: create(Loan) & save(RepaymentSchedule)
    Repo->>DB: INSERT loans & repayment_schedules
    DB-->>Repo: Saved Entities
    Repo-->>Service: Persisted Loan Object
    Service-->>Router: Loan + Installments payload
    Router-->>Ops: JSON Response (Status: ACTIVE)
```

---

## 3. Sequence Diagram: Payment Allocation (e.g. IPC vs PIC)

```mermaid
sequenceDiagram
    autonumber
    actor Gateway as Payment Gateway / React Hook
    participant Router as Loan Router
    participant Service as Loan Service
    participant Config as Configuration Service
    participant Engine as Allocation Engine
    participant Repo as Loan Repository
    participant DB as PostgreSQL Database

    Gateway->>Router: POST /loans/{id}/payments (amount, reference_no)
    Router->>Service: record_payment_and_allocate()
    Service->>Repo: get_loan_with_relations(loan_id)
    Repo-->>Service: Loan + Unpaid Repayment Schedules
    
    Service->>Config: get_config(AllocationConfiguration & CollectionConfiguration)
    Config-->>Service: Priority Sequence (e.g. ["interest", "principal", "charges"])
    
    Service->>Engine: allocate_payment(amount, installments, sequence, strategy)
    Note over Engine: Loops unpaid installments;<br/>Splits funds according to configured sequence.
    Engine-->>Service: Excess amount + List of allocations
    
    Service->>Repo: save(Payment) & save(PaymentAllocation)
    Repo->>DB: INSERT payments & payment_allocations
    DB-->>Repo: Saved Entities
    Service-->>Router: Payment Receipt + Allocation Breakdown
    Router-->>Gateway: Reconciled JSON Payload
```

---

## 4. UML Class Diagram

```mermaid
classDiagram
    class Base {
        +metadata
    }

    class TemporalConfigMixin {
        +int version
        +bool is_active
        +datetime effective_from
        +datetime effective_to
        +datetime created_at
        +datetime updated_at
        +str created_by
        +str updated_by
    }

    class Lender {
        +int id
        +str name
        +str code
        +bool is_active
    }

    class Product {
        +int id
        +int lender_id
        +str name
        +str code
        +bool is_active
    }

    class InterestConfiguration {
        +int id
        +int product_id
        +str calculation_basis
        +str emi_type
        +str repayment_frequency
        +int grace_period_days
    }

    class AllocationConfiguration {
        +int id
        +int product_id
        +str sequence_type
        +list priority_sequence
    }

    class Loan {
        +int id
        +int lender_id
        +int product_id
        +float loan_amount
        +float approved_amount
        +float interest_rate
        +int tenure_months
        +str state
        +datetime disbursed_at
    }

    class RepaymentSchedule {
        +int id
        +int loan_id
        +int installment_no
        +date due_date
        +float principal_due
        +float interest_due
        +float charges_due
        +float principal_paid
        +float interest_paid
        +float charges_paid
        +str state
    }

    Base <|-- Lender
    Base <|-- Product
    Base <|-- Loan
    Base <|-- RepaymentSchedule
    Base <|-- InterestConfiguration
    Base <|-- AllocationConfiguration
    TemporalConfigMixin <|-- InterestConfiguration
    TemporalConfigMixin <|-- AllocationConfiguration

    Lender "1" *-- "many" Product : products
    Product "1" *-- "many" Loan : loans
    Product "1" *-- "many" InterestConfiguration : interest_configs
    Product "1" *-- "many" AllocationConfiguration : allocation_configs
    Loan "1" *-- "many" RepaymentSchedule : installments
```
