Software Architecture Document: CHS Lite ERP

Software Architecture Document: CHS Lite ERP

This document outlines the software architecture of CHS Lite ERP, a mobile-first Progressive Web App (PWA) designed for Cooperative Housing Societies (CHS). The architecture is structured in accordance with the industry-standard software architecture guidelines defined by roadmap.sh/software-architect.


1. Architectural Drivers

Architectural drivers define the core requirements, quality attributes, and constraints that shape the system’s design.

1.1 Functional Requirements

  • Multi-Tenant Partitioning: Logical isolation of cooperative housing societies under a unified application deployment using chs_id.
  • Role-Based Access Control (RBAC): Distinct permissions for System, Admin, Manager, Security, and User roles.
  • Financial & Billing Operations: Service charge groups, automated invoice generation, journal vouchers, and ledger-compatible records.
  • Resident & Gatekeeper Collaboration: Visitor registration, approval alerts, support requests, and parking allocations.
  • eVault Storage: Secure document uploading and management with granular read/write permissions.

1.2 Non-Functional Requirements (System Quality Attributes)

  • Accessibility & Simplicity: High-contrast, senior-friendly interfaces optimized for mobile viewports using a bottom navigation bar.
  • Offline Reliability: Capabilities to view recently fetched notices, directories, and member profiles without active internet connection.
  • Security & Integrity: Session hijacking protection, secure credential storage, single-session enforcement, and role-based data shielding.
  • Performance: Edge-optimized server-side rendering (SSR), minimized API latencies, and optimized asset delivery via service workers.

1.3 Technical Constraints

  • Database Engine: Microsoft SQL Server accessed through Prisma ORM using standard TCP connections.
  • Hosting Constraints: Deployment in cloud environments where private resources (SQL Server databases) reside in secure VPCs.
  • Interoperability: Strict browser support guidelines for PWAs, local database persistence, and integration with the Telegram Bot API.

2. Software Architecture Styles & Design Patterns

The system combines several design patterns to achieve high cohesion, separation of concerns, and ease of deployment.

graph TD
    classDef layerStyle fill:#f9f9f9,stroke:#333,stroke-width:2px;
    classDef componentStyle fill:#e1f5fe,stroke:#0288d1,stroke-width:1px;

    subgraph ClientLayer ["1. Presentation Layer (Mobile Client)"]
        Client[PWA Browser Client]:::componentStyle
        SW[Service Worker Caching]:::componentStyle
    end

    subgraph SecLayer ["2. Security & Session Layer"]
        SessionCheck[JWT cookie verify-otp & getSession]:::componentStyle
        RBAC[canPerform Permission Check]:::componentStyle
    end

    subgraph AppLayer ["3. Application Layer (Next.js App Router)"]
        Actions[Server Actions app/actions/]:::componentStyle
        APIs[API Routes app/api/]:::componentStyle
    end

    subgraph DbLayer ["4. Persistence & Database Layer"]
        Prisma[Prisma Client ORM]:::componentStyle
        DB[(MS SQL Server Database)]:::componentStyle
    end

    Client <-->|HTTPS / Server Actions| SessionCheck
    SessionCheck <--> RBAC
    RBAC <--> Actions & APIs
    Actions & APIs <--> Prisma
    Prisma <--> DB

    class ClientLayer,SecLayer,AppLayer,DbLayer layerStyle;

2.1 Component-Based Monolith (Next.js App Router)

CHS Lite utilizes a component-based architecture where both routing, business actions, and visual layouts are consolidated in a Next.js workspace. This eliminates unnecessary network boundaries and serialization latency between backend routes and user interfaces.

2.2 Layered (N-Tier) Architecture

The software logic is decoupled into distinct vertical layers:

  1. Presentation Layer: Client-side React components rendering a mobile-responsive interface styled with Tailwind CSS. Offline caching is controlled here via PWA Service Workers.
  2. Session & Security Layer: Server-side middleware and authentication helpers validating JWT cookies and verifying role permissions.
  3. Application Layer: Core business logic implemented via server-side Next.js Server Actions and JSON API routes.
  4. Data Persistence Layer: Object-Relational Mapping (ORM) abstracting physical database calls using Prisma.
  5. Database Store: SQL Server database housing all normalized application tables.

3. Technology Stack & Database Selection

3.1 Technology Stack Details

  • Frontend Framework: Next.js 16 (React 19, TypeScript strict mode).
  • Styling & Layout: Tailwind CSS v4, Radix UI Primitives, Lucide Icons, and Framer Motion.
  • PWA Service: @ducanh2912/next-pwa enabling offline capabilities and app-like installation.
  • Database Client: @prisma/client with @prisma/adapter-mssql and tedious driver.
  • External Integrations:
    • AWS S3: Document vault upload and retrieval using @aws-sdk/client-s3.
    • AWS SES: Transactional notice announcements and ticketing notifications.
    • Telegram Bot API: Verification code (OTP) dispatch and real-time gate notification delivery.

3.2 Data Model & Partitioning (Relational Database)

Multi-tenancy is enforced using logical rows: every core table contains a chs_id (representing the specific Cooperative Housing Society).

erDiagram
    SOCIETIES {
        nvarchar id PK
        nvarchar chs_id
        nvarchar chs_name
        datetime created_at
    }
    MEMBERS {
        nvarchar id PK
        nvarchar member_id
        nvarchar first_name
        nvarchar last_name
        nvarchar chs_id FK
        nvarchar role
        nvarchar mobile
        nvarchar email
        nvarchar telegram_id
        nvarchar current_session_id
        nvarchar otp_code
        datetime otp_expires_at
    }
    INVOICES {
        nvarchar id PK
        nvarchar chs_id FK
        nvarchar invoice_no
        nvarchar fylabel
        nvarchar memberid FK
        decimal total_amount
        nvarchar status
    }
    INVOICE_DETAILS {
        nvarchar id PK
        nvarchar chs_id FK
        nvarchar invoiceno
        nvarchar service_charges_code FK
        decimal amount
    }
    SERVICE_CHARGES {
        nvarchar id PK
        nvarchar service_code
        nvarchar service_name
        decimal amount
        nvarchar chs_id FK
        nvarchar mainac
        nvarchar subac
    }
    VISITORS {
        nvarchar id PK
        nvarchar visitor_name
        nvarchar contact_no
        nvarchar purpose
        nvarchar status
        nvarchar chs_id FK
        nvarchar host_member_id FK
    }
    PARKING_SLOTS {
        nvarchar id PK
        nvarchar chs_id FK
        nvarchar slot_name
        nvarchar parking_type
        nvarchar member_id FK
    }

    SOCIETIES ||--o{ MEMBERS : "has members"
    MEMBERS ||--o{ INVOICES : "receives"
    MEMBERS ||--o{ PARKING_SLOTS : "occupies"
    MEMBERS ||--o{ VISITORS : "hosts"
    INVOICES ||--o{ INVOICE_DETAILS : "contains"
    SERVICE_CHARGES ||--o{ INVOICE_DETAILS : "describes"

4. Security Architecture

4.1 Authentication & Single Session Enforcement

  1. One-Time Passcode (OTP): Logging in requires request dispatch to /api/auth/send-otp. A 6-digit code is sent to the user’s mobile number via Telegram (if linked) or SMS/Email.
  2. JWT Payload: Upon verification, the server generates a token containing memberId, chsId, role, and a unique sessionId.
  3. Cookie Settings: The signed JWT token is stored inside an httpOnly, secure (in production), and sameSite: lax cookie named chs_session.
  4. Single Session Enforcement: The server cross-references the token’s sessionId with the member’s current_session_id field in the database during every request. When a member logs in on a new device, a new sessionId is saved to the database, instantly invalidating the previous device’s session token.
sequenceDiagram
    autonumber
    actor User as Resident / Admin
    participant Client as PWA Client
    participant Server as Next.js Server
    participant Telegram as Telegram API
    participant DB as SQL Server DB

    User->>Client: Enters registered mobile number
    Client->>Server: Request OTP (send-otp)
    Server->>DB: Query member details by mobile number
    DB-->>Server: Return Member details & telegram_id
    Server->>Server: Generate 6-digit OTP & expiry
    Server->>DB: Update Member Record with OTP fields
    Server->>Telegram: Send OTP message (or via Email)
    Telegram-->>User: Delivers OTP Code
    User->>Client: Inputs OTP code
    Client->>Server: Verify OTP (verify-otp)
    Server->>DB: Fetch Member by OTP
    Server->>Server: Validate OTP code & check expiry
    Server->>Server: Generate unique sessionId & JWT token
    Server->>DB: Update Member current_session_id = sessionId
    Server->>Client: Write secure httpOnly cookie 'chs_session'
    Client-->>User: Redirect to Authorized Dashboard

4.2 Authorization & RBAC

Authorization is strictly evaluated in Next.js Server Actions using the canPerform(session, action, resource?) policy engine:

  • System: Global administrator. Can switch active societies and perform all read, write, and delete operations.
  • Admin: Society-level administrator. Holds full operational permission to create, edit, and delete records inside their own society.
  • Manager: Operational controller. Can view, edit, and create records but is strictly prohibited from deleting any records.
  • Security: Gatekeeper role. Can only register, view, and process visitor details, check parking slot statuses, and view basic member directories.
  • User: Resident role. Restricted to self-service items (viewing own profile, managing own visitor invitations, submitting service requests).

5. Infrastructure & Deployment Architecture

The application deployment topology ensures that public endpoints are decoupled from internal databases, maintaining high security and isolating the SQL Server database.

graph TB
    classDef clientStyle fill:#e8f5e9,stroke:#2e7d32,stroke-width:2px;
    classDef awsStyle fill:#fff3e0,stroke:#e65100,stroke-width:2px;
    classDef vpcStyle fill:#eceff1,stroke:#37474f,stroke-width:2px;

    Client[PWA Client Browser]:::clientStyle
    Telegram[Telegram Bot API]:::clientStyle

    subgraph AWSCloud ["AWS Cloud Deployment"]
        Amplify[AWS Amplify Hosting 
Next.js App Router Monolith]:::awsStyle S3[AWS S3 Bucket
eVault Storage]:::awsStyle SES[AWS SES
Email Dispatcher]:::awsStyle subgraph AWSVPC ["AWS VPC"] NAT[NAT Gateway]:::awsStyle subgraph PrivateSubnet ["Private Subnet"] Lambda[Amplify SQL Bridge
Lambda Function]:::awsStyle EC2[EC2 Windows VM
SQL Server Express]:::awsStyle end end end Client -->|HTTPS / WSS| Amplify Client -.->|Direct OAuth / Login Widget| Telegram Amplify -->|Amplify Data / AppSync| Lambda Lambda -->|Port 1433| EC2 Amplify -->|Presigned Upload/Download URLs| S3 Amplify -->|Nodemailer Client| SES Amplify -->|HTTPS POST| Telegram Amplify -->|Outgoing Traffic| NAT NAT --> PrivateSubnet class AWSCloud awsStyle; class AWSVPC vpcStyle;

5.1 Deployment Containers

  • Next.js Host (AWS Amplify): Server-Side Rendering (SSR) pages, static assets, and Server Actions are compiled and hosted on AWS Amplify.
  • Amplify SQL Bridge Lambda: A VPC-bound AWS Lambda function that mediates SQL queries between the server and database, bypassing public ports.
  • Database Host (AWS EC2): A Microsoft SQL Server Express instance hosted on a private EC2 instance inside a secure private subnet.
  • Vault File Storage (AWS S3): Private S3 bucket utilizing pre-signed URLs to stream, verify, upload, and delete resident documents securely.

5.2 Network Configuration

  • No Public Database Endpoints: The database server (EC2) resides inside a private subnet and only exposes port 1433 to the security group associated with the SQL Bridge Lambda.
  • IAM Authorization: Cognito user credentials and Amplify-defined policies authorize connection triggers to the database bridge Lambda.
  • Secrets Management: Database passwords and encryption credentials are stored as environment secrets inside the AWS Amplify Console.