Skip to main content

DemozPay System Documentation

⚠️ Partially outdated — 2026-05-23. Folder references in this document predate the May 2026 restructure. App names (business, client, bnpl-partner, fi, admin, docs) are now <audience>-web (employer-web, employee-web, merchant-web, fi-web, admin-web, docs-web) per ADR-004. Carved-out Go services moved from apps/ to services/. Library locations moved from libs/ to packages/.

⚠️ Positioning superseded. The "employee benefits management" / HR-suite framing below predates the current product identity. DemozPay is payroll-powered financial infrastructure — payroll is the trust layer that enables financial products, not an HR/benefits platform — and an orchestrator, not a custodian of funds (ADR-014). Treat docs/architecture/SYSTEM_OVERVIEW.md and the README as authoritative for positioning.

Authoritative current layout: PROJECT_STRUCTURE.md. Decisions: docs/adr/.

📋 Table of Contents

  1. System Overview
  2. Architecture
  3. Applications
  4. Database Schema
  5. API Endpoints
  6. Authentication & Authorization
  7. Deployment

🎯 System Overview

DemozPay is salary-linked financial infrastructure for the Ethiopian market: payroll is the trust layer that powers financial products (EWA, lending, BNPL, Equb, savings) delivered through licensed partner banks. DemozPay orchestrates the rails and never holds customer funds (ADR-014). (Historic note: an earlier draft framed this as "employee benefits management" — that HR-suite framing is superseded; see the banner above.) The system serves multiple stakeholders through dedicated portals:

  • Businesses: Manage payroll, employees, and financial services
  • Employees: Access wages, loans, BNPL, and savings (Equb)
  • Financial Institutions: Manage loan products and repayments
  • BNPL Partners: Track transactions and settlements
  • Platform Administrators: Oversee the entire ecosystem

Key Features

  • 💰 Payroll Management: Multi-level approval workflow, tax calculations, pension deductions
  • 🏦 Early Wage Access (EWA): Employees can access earned wages before payday
  • 🛍️ Buy Now Pay Later (BNPL): Salary-backed installment purchases
  • 💳 Employee Loans: Personal and emergency loans with payroll deduction
  • 🤝 Equb System: Traditional Ethiopian savings circles (Rotating Savings and Credit Associations)
  • 📊 Financial Analytics: Comprehensive reporting and insights
  • 🔐 Bank-Grade Security: KYC verification, 2FA, audit logging

🏗️ Architecture

Technology Stack

Frontend:

  • Framework: Next.js 16 (App Router)
  • UI Library: React 19
  • Styling: Tailwind CSS + Radix UI
  • State Management: React Context API
  • Form Handling: React Hook Form + Zod validation

Backend:

  • Framework: NestJS 11
  • ORM: Prisma 5
  • Database: PostgreSQL
  • Authentication: JWT + Passport
  • API Style: RESTful

Infrastructure:

  • Monorepo: Nx 22.1.1
  • Package Manager: pnpm
  • Testing: Jest (unit) + Playwright (E2E)
  • CI/CD: GitHub Actions
  • Containerization: Docker + Docker Compose

System Architecture Diagram

┌─────────────────────────────────────────────────────────────────┐
│ Client Layer │
├──────────┬──────────┬──────────┬──────────┬──────────────────────┤
│ Admin │ Business │ Client │ FI │ BNPL Partner │
│ Portal │ Portal │ Portal │ Portal │ Portal │
│ (4200) │ (4201) │ (4202) │ (4203) │ (4204) │
└──────────┴──────────┴──────────┴──────────┴──────────────────────┘


┌─────────────────────────────────────────────────────────────────┐
│ API Gateway Layer │
│ NestJS Server (3000) │
├─────────────────────────────────────────────────────────────────┤
│ Auth │ Business │ Employee │ Payroll │ Loans │ BNPL │ Equb │
└─────────────────────────────────────────────────────────────────┘


┌─────────────────────────────────────────────────────────────────┐
│ Data Layer │
│ PostgreSQL Database │
│ (Prisma ORM) │
└─────────────────────────────────────────────────────────────────┘

📱 Applications

🔧 Admin Portal

Purpose: Platform administration and oversight of all system operations

Port: 4200

Target Users: Super Admins, Platform Administrators, Support Staff

Features

1. Dashboard
  • Overview: System-wide metrics and KPIs
  • Metrics:
    • Total businesses onboarded
    • Active employees across platform
    • Total transaction volume
    • Active loans and BNPL purchases
    • Equb participation rates
  • Expected Endpoints:
    • GET /api/admin/dashboard/metrics
    • GET /api/admin/dashboard/recent-activities
2. Business Management
  • List View: All registered businesses with filters
  • Detail View: Complete business profile and operations
  • Actions: Approve/suspend/activate businesses
  • KYC Verification: Review and approve business documents
  • Expected Endpoints:
    • GET /api/admin/businesses - List all businesses
    • GET /api/admin/businesses/:id - Get business details
    • POST /api/admin/businesses - Create new business
    • PATCH /api/admin/businesses/:id - Update business
    • PATCH /api/admin/businesses/:id/status - Change status
    • POST /api/admin/businesses/:id/verify-kyc - Verify KYC
3. User Management
  • User Types: Super Admin, Admin, Support, Viewer, Company Admin, BNPL Partner Admin, FI Partner Admin
  • Features:
    • Create/edit/deactivate users
    • Role-based access control (RBAC)
    • Password reset
    • Activity monitoring
  • Expected Endpoints:
    • GET /api/admin/users - List all users
    • GET /api/admin/users/:id - Get user details
    • POST /api/admin/users - Create user
    • PATCH /api/admin/users/:id - Update user
    • DELETE /api/admin/users/:id - Deactivate user
    • POST /api/admin/users/:id/reset-password - Reset password
4. Payroll Monitoring
  • Overview: Monitor all payroll processing across businesses
  • Features:
    • View payroll status (Draft, Pending Approval, Approved, Paid)
    • Track approval workflows
    • Monitor deductions (EWA, BNPL, Loans, Equb)
    • Generate platform-wide payroll reports
  • Expected Endpoints:
    • GET /api/admin/payrolls - List all payrolls
    • GET /api/admin/payrolls/:id - Get payroll details
    • GET /api/admin/payrolls/statistics - Payroll statistics
5. Loan Management
  • Business Loans: Working capital, salary advance, expansion, equipment
  • Employee Loans: Personal, emergency, education, medical, salary top-up
  • Features:
    • Review loan applications
    • Approve/reject loans
    • Monitor repayment schedules
    • Track defaults
  • Expected Endpoints:
    • GET /api/admin/loans/business - List business loans
    • GET /api/admin/loans/employee - List employee loans
    • GET /api/admin/loans/:id - Get loan details
    • PATCH /api/admin/loans/:id/approve - Approve loan
    • PATCH /api/admin/loans/:id/reject - Reject loan
6. Early Wage Access (EWA) Oversight
  • Features:
    • Monitor EWA requests across platform
    • Track disbursement and repayment
    • Set platform-wide EWA limits
    • Analyze EWA usage patterns
  • Expected Endpoints:
    • GET /api/admin/ewa/requests - List all EWA requests
    • GET /api/admin/ewa/statistics - EWA statistics
    • PATCH /api/admin/ewa/limits - Update platform limits
7. BNPL Management
  • Features:
    • Monitor BNPL transactions
    • Manage BNPL partners
    • Track merchant relationships
    • Settlement management
  • Expected Endpoints:
    • GET /api/admin/bnpl/transactions - List transactions
    • GET /api/admin/bnpl/partners - List BNPL partners
    • POST /api/admin/bnpl/partners - Add partner
    • GET /api/admin/bnpl/settlements - Settlement batches
8. Equb Management
  • Types: Corporate Equb, Private Equb
  • Features:
    • Monitor all equb circles
    • Track contributions and payouts
    • Resolve disputes
    • Audit equb transactions
  • Expected Endpoints:
    • GET /api/admin/equbs - List all equbs
    • GET /api/admin/equbs/:id - Get equb details
    • GET /api/admin/equbs/:id/rounds - Get equb rounds
    • GET /api/admin/equbs/:id/participants - Get participants
    • GET /api/admin/equbs/:id/audit-logs - Get audit logs
9. Financial Institution Management
  • Features:
    • Onboard MFIs and banks
    • Manage loan products
    • Track settlements
    • Monitor repayments
  • Expected Endpoints:
    • GET /api/admin/financial-institutions - List FIs
    • POST /api/admin/financial-institutions - Add FI
    • PATCH /api/admin/financial-institutions/:id - Update FI
    • GET /api/admin/financial-institutions/:id/loans - FI loans
10. Compliance & Reporting
  • Features:
    • KYC verification tracking
    • Regulatory compliance reports
    • Transaction monitoring
    • Audit trail
  • Expected Endpoints:
    • GET /api/admin/compliance/kyc-pending - Pending KYC
    • GET /api/admin/compliance/reports - Generate reports
    • GET /api/admin/audit-logs - System audit logs
11. Remittance Oversight
  • Features:
    • Monitor cross-border remittances
    • Track settlement batches
    • Reconciliation management
  • Expected Endpoints:
    • GET /api/admin/remittances - List remittances
    • GET /api/admin/remittances/:id - Remittance details
12. Demo Requests
  • Features:
    • Manage demo requests from potential clients
    • Schedule demos
    • Track conversion pipeline
  • Expected Endpoints:
    • GET /api/admin/demo-requests - List demo requests
    • PATCH /api/admin/demo-requests/:id - Update status

🏢 Business Portal

Purpose: Business/employer management of payroll, employees, and financial services

Port: 4201

Target Users: Business Owners, HR Managers, Finance Managers, Department Heads

Features

1. Dashboard
  • Overview: Business-specific metrics
  • Metrics:
    • Total employees
    • Current month payroll status
    • Pending approvals
    • Active loans and EWA requests
    • Equb participation
  • Expected Endpoints:
    • GET /api/business/dashboard/metrics
    • GET /api/business/dashboard/recent-activities
2. Employee Management
  • List View: All employees with filters (department, status)
  • Detail View: Complete employee profile
  • Features:
    • Add/edit/terminate employees
    • Department management
    • Document management (ID, contracts)
    • Absence tracking
    • KYC verification
  • Expected Endpoints:
    • GET /api/business/employees - List employees
    • GET /api/business/employees/:id - Employee details
    • POST /api/business/employees - Add employee
    • PATCH /api/business/employees/:id - Update employee
    • DELETE /api/business/employees/:id - Terminate employee
    • GET /api/business/departments - List departments
    • POST /api/business/departments - Create department
    • POST /api/business/employees/:id/documents - Upload document
    • POST /api/business/employees/:id/absences - Log absence
3. Payroll Management
  • Payroll Cycle: Monthly processing with multi-level approval
  • Features:
    • Create payroll (clean draft or clone previous)
    • Import variable components (overtime, bonuses)
    • Calculate deductions (tax, pension, loans, EWA, BNPL, equb)
    • Multi-level approval workflow (HR → Finance → CEO)
    • Generate payslips
    • Submit to Ministry of Revenue (MoR)
    • Payroll history and reports
  • Expected Endpoints:
    • GET /api/business/payrolls - List payrolls
    • GET /api/business/payrolls/:id - Payroll details
    • POST /api/business/payrolls - Create payroll
    • POST /api/business/payrolls/:id/clone - Clone previous
    • POST /api/business/payrolls/:id/import-variables - Import data
    • PATCH /api/business/payrolls/:id/calculate - Calculate
    • POST /api/business/payrolls/:id/approve - Approve
    • POST /api/business/payrolls/:id/submit-mor - Submit to MoR
    • GET /api/business/payrolls/:id/payslips - Generate payslips
4. Financial Services Management

4.1 Early Wage Access (EWA)

  • Features:
    • Review EWA requests
    • Approve/reject requests
    • Track disbursements
    • Monitor repayment through payroll
  • Expected Endpoints:
    • GET /api/business/ewa/requests - List EWA requests
    • GET /api/business/ewa/requests/:id - Request details
    • PATCH /api/business/ewa/requests/:id/approve - Approve
    • PATCH /api/business/ewa/requests/:id/reject - Reject

4.2 Employee Loans

  • Features:
    • Review loan applications
    • HR approval workflow
    • Track loan repayments
    • Monitor defaults
  • Expected Endpoints:
    • GET /api/business/loans/employee - List employee loans
    • GET /api/business/loans/employee/:id - Loan details
    • PATCH /api/business/loans/employee/:id/hr-approve - HR approval

4.3 Payroll Loans

  • Features:
    • Apply for business loans
    • Track loan status
    • Monitor repayments
  • Expected Endpoints:
    • GET /api/business/loans/payroll - List payroll loans
    • POST /api/business/loans/payroll - Apply for loan
    • GET /api/business/loans/payroll/:id - Loan details

4.4 Buy Now Pay Later (BNPL)

  • Features:
    • Monitor employee BNPL purchases
    • Track installment deductions
    • View merchant transactions
  • Expected Endpoints:
    • GET /api/business/bnpl/purchases - List BNPL purchases
    • GET /api/business/bnpl/purchases/:id - Purchase details
5. Corporate Equb Management
  • Features:
    • Create corporate equb circles
    • Manage participants
    • Track contributions
    • Monitor payout schedules
    • View equb history
  • Expected Endpoints:
    • GET /api/business/equbs - List corporate equbs
    • POST /api/business/equbs - Create equb
    • GET /api/business/equbs/:id - Equb details
    • POST /api/business/equbs/:id/members - Add member
    • GET /api/business/equbs/:id/rounds - View rounds
6. Reports & Analytics
  • Features:
    • Payroll reports
    • Employee demographics
    • Financial services utilization
    • Tax and pension reports
    • Custom report generation
  • Expected Endpoints:
    • GET /api/business/reports/payroll - Payroll reports
    • GET /api/business/reports/employees - Employee reports
    • GET /api/business/reports/financial-services - Financial reports
    • GET /api/business/reports/tax - Tax reports
7. PAYE Tax Reporting
  • Features:
    • Generate PAYE tax reports
    • Submit to tax authority
    • Track tax payments
  • Expected Endpoints:
    • GET /api/business/tax/paye - PAYE reports
    • POST /api/business/tax/paye/submit - Submit report
8. Utility Bill Payments
  • Features:
    • Pay utility bills (water, electricity, internet)
    • Track payment history
    • Manage multiple accounts
  • Expected Endpoints:
    • GET /api/business/bills - List bills
    • POST /api/business/bills/pay - Pay bill
    • GET /api/business/bills/history - Payment history
9. User Management
  • Features:
    • Manage business users (HR, Finance, Managers)
    • Role-based permissions
    • Activity tracking
  • Expected Endpoints:
    • GET /api/business/users - List business users
    • POST /api/business/users - Add user
    • PATCH /api/business/users/:id - Update user
10. Settings
  • Features:
    • Business profile management
    • Payroll configuration
    • Telebirr integration settings
    • Financial limits configuration
    • Notification preferences
  • Expected Endpoints:
    • GET /api/business/settings - Get settings
    • PATCH /api/business/settings - Update settings
    • PATCH /api/business/settings/payroll-config - Payroll config
    • PATCH /api/business/settings/telebirr - Telebirr config

👤 Client Portal (Employee App)

Purpose: Employee self-service for financial management and benefits

Port: 4202

Target Users: Employees

Features

1. Home Dashboard
  • Overview: Personal financial snapshot
  • Widgets:
    • Upcoming pay amount and date
    • Quick actions (EWA, BNPL, Loans, Equb)
    • Budget planner
    • Recent activities
  • Expected Endpoints:
    • GET /api/employee/dashboard - Dashboard data
    • GET /api/employee/upcoming-pay - Next paycheck info
2. Finance Hub
  • Tabs: EWA, BNPL, Loans

2.1 Early Wage Access (EWA)

  • Features:
    • Check available EWA amount
    • Request early wage access
    • View EWA history
    • Track repayment status
  • Expected Endpoints:
    • GET /api/employee/ewa/available - Available amount
    • POST /api/employee/ewa/request - Request EWA
    • GET /api/employee/ewa/history - EWA history

2.2 Buy Now Pay Later (BNPL)

  • Features:
    • Browse BNPL-enabled merchants
    • Make BNPL purchases
    • View active installments
    • Track payment schedule
  • Expected Endpoints:
    • GET /api/employee/bnpl/merchants - List merchants
    • POST /api/employee/bnpl/purchase - Make purchase
    • GET /api/employee/bnpl/purchases - My purchases
    • GET /api/employee/bnpl/purchases/:id - Purchase details

2.3 Loans

  • Features:
    • Apply for personal loans
    • View loan eligibility
    • Track loan status
    • View repayment schedule
  • Expected Endpoints:
    • GET /api/employee/loans/eligibility - Check eligibility
    • POST /api/employee/loans/apply - Apply for loan
    • GET /api/employee/loans - My loans
    • GET /api/employee/loans/:id - Loan details
    • GET /api/employee/loans/:id/schedule - Repayment schedule
3. Equb (Savings Circles)
  • Types: Corporate Equb, Private Equb
  • Features:
    • Browse available equbs
    • Join equb circles
    • Create private equbs
    • Track contributions
    • View payout schedule
    • Monitor equb rounds
  • Expected Endpoints:
    • GET /api/employee/equbs - List available equbs
    • GET /api/employee/equbs/my - My equbs
    • POST /api/employee/equbs/join - Join equb
    • POST /api/employee/equbs/create - Create private equb
    • GET /api/employee/equbs/:id - Equb details
    • GET /api/employee/equbs/:id/rounds - View rounds
    • POST /api/employee/equbs/:id/invite - Invite members
4. Payslip
  • Features:
    • View current and historical payslips
    • Download payslips (PDF)
    • Salary breakdown (earnings, deductions)
    • Year-to-date summary
  • Expected Endpoints:
    • GET /api/employee/payslips - List payslips
    • GET /api/employee/payslips/:id - Payslip details
    • GET /api/employee/payslips/:id/download - Download PDF
    • GET /api/employee/payslips/ytd - Year-to-date summary
5. Profile
  • Features:
    • View personal information
    • Employment details
    • Contact information
    • Bank account details
    • Document uploads
  • Expected Endpoints:
    • GET /api/employee/profile - Get profile
    • PATCH /api/employee/profile - Update profile
    • POST /api/employee/profile/documents - Upload document
    • PATCH /api/employee/profile/bank-account - Update bank info
6. Budget Planner
  • Features:
    • Track income and expenses
    • Set savings goals
    • Expense categorization
    • Budget insights
  • Expected Endpoints:
    • GET /api/employee/budget/summary - Budget summary
    • POST /api/employee/budget/expenses - Add expense
    • GET /api/employee/budget/expenses - List expenses
    • POST /api/employee/budget/goals - Create savings goal
    • GET /api/employee/budget/goals - List goals
7. Settings
  • Features:
    • Language selection (Amharic, English)
    • Theme selection (Light, Dark, Midnight)
    • Notification preferences
    • Security settings (2FA, password change)
  • Expected Endpoints:
    • GET /api/employee/settings - Get settings
    • PATCH /api/employee/settings - Update settings
    • POST /api/employee/settings/2fa/enable - Enable 2FA
    • POST /api/employee/settings/password - Change password
8. Onboarding
  • Features:
    • Welcome flow for new employees
    • Profile setup
    • Bank account linking
    • Feature introduction
  • Expected Endpoints:
    • GET /api/employee/onboarding/status - Onboarding status
    • POST /api/employee/onboarding/complete - Complete step
9. Help & Support
  • Features:
    • FAQ section
    • Contact support
    • Feature tutorials
  • Expected Endpoints:
    • GET /api/employee/help/faq - Get FAQs
    • POST /api/employee/help/contact - Contact support

🏦 Financial Institution Portal

Purpose: Loan management for banks and microfinance institutions

Port: 4203

Target Users: MFI Administrators, Loan Officers

Features

1. Dashboard
  • Overview: Loan portfolio metrics
  • Metrics:
    • Total active loans
    • Loan disbursement volume
    • Repayment rate
    • Default rate
    • Pending applications
  • Expected Endpoints:
    • GET /api/fi/dashboard/metrics - Dashboard metrics
    • GET /api/fi/dashboard/recent-activities - Recent activities
2. Loan Requests
  • Types: Business Loans, Employee Loans
  • Features:
    • Review loan applications
    • Credit assessment
    • Approve/reject loans
    • Set loan terms (amount, interest rate, tenure)
    • Document verification
  • Expected Endpoints:
    • GET /api/fi/loan-requests - List loan requests
    • GET /api/fi/loan-requests/:id - Request details
    • PATCH /api/fi/loan-requests/:id/approve - Approve loan
    • PATCH /api/fi/loan-requests/:id/reject - Reject loan
    • POST /api/fi/loan-requests/:id/disburse - Disburse loan
3. Active Loans
  • Features:
    • View all active loans
    • Monitor repayment status
    • Track overdue payments
    • Loan performance analytics
  • Expected Endpoints:
    • GET /api/fi/loans/active - List active loans
    • GET /api/fi/loans/:id - Loan details
    • GET /api/fi/loans/:id/payments - Payment history
    • GET /api/fi/loans/overdue - Overdue loans
4. Repayments & Remittance
  • Features:
    • Track loan repayments
    • Settlement reconciliation
    • Generate remittance reports
    • Payment collection tracking
  • Expected Endpoints:
    • GET /api/fi/repayments - List repayments
    • GET /api/fi/repayments/:id - Repayment details
    • GET /api/fi/settlements - Settlement batches
    • POST /api/fi/settlements/:id/reconcile - Reconcile settlement
5. Settings
  • Features:
    • FI profile management
    • Loan product configuration
    • Interest rate settings
    • Settlement account details
  • Expected Endpoints:
    • GET /api/fi/settings - Get settings
    • PATCH /api/fi/settings - Update settings
    • GET /api/fi/settings/loan-products - Loan products
    • POST /api/fi/settings/loan-products - Add loan product

🛍️ BNPL Partner Portal

Purpose: Transaction management for Buy Now Pay Later partners

Port: 4204

Target Users: BNPL Partner Administrators, Merchant Managers

Features

1. Dashboard
  • Overview: BNPL transaction metrics
  • Metrics:
    • Total transactions
    • Transaction volume
    • Active installment plans
    • Settlement pending
    • Default rate
  • Expected Endpoints:
    • GET /api/bnpl/dashboard/metrics - Dashboard metrics
    • GET /api/bnpl/dashboard/recent-transactions - Recent transactions
2. BNPL Transactions
  • Features:
    • View all BNPL purchases
    • Transaction details
    • Customer information
    • Installment tracking
    • Transaction status monitoring
  • Expected Endpoints:
    • GET /api/bnpl/transactions - List transactions
    • GET /api/bnpl/transactions/:id - Transaction details
    • GET /api/bnpl/transactions/:id/installments - Installment schedule
3. Exposure & Risk Management
  • Features:
    • Credit exposure analysis
    • Default risk assessment
    • Customer credit limits
    • Risk alerts
  • Expected Endpoints:
    • GET /api/bnpl/risk/exposure - Exposure analysis
    • GET /api/bnpl/risk/defaults - Default tracking
    • GET /api/bnpl/risk/alerts - Risk alerts
4. Repayments & Remittance
  • Features:
    • Track installment payments
    • Settlement reconciliation
    • Payment collection status
    • Generate settlement reports
  • Expected Endpoints:
    • GET /api/bnpl/repayments - List repayments
    • GET /api/bnpl/settlements - Settlement batches
    • GET /api/bnpl/settlements/:id - Settlement details
    • POST /api/bnpl/settlements/:id/reconcile - Reconcile
5. Settings
  • Features:
    • Partner profile management
    • Merchant management
    • Product catalog
    • Settlement account configuration
  • Expected Endpoints:
    • GET /api/bnpl/settings - Get settings
    • PATCH /api/bnpl/settings - Update settings
    • GET /api/bnpl/merchants - List merchants
    • POST /api/bnpl/merchants - Add merchant

🔌 Server API

Purpose: Backend API serving all portals

Port: 3000

Framework: NestJS 11

Current Modules

1. Authentication Module (/auth)
  • Features:
    • User registration
    • Login (JWT-based)
    • Password reset
    • Token refresh
    • 2FA support
  • Endpoints:
    • POST /auth/register - Register new user
    • POST /auth/login - Login
    • POST /auth/logout - Logout
    • POST /auth/refresh - Refresh token
    • POST /auth/forgot-password - Request password reset
    • POST /auth/reset-password - Reset password
    • POST /auth/2fa/enable - Enable 2FA
    • POST /auth/2fa/verify - Verify 2FA code
2. Business Module (/business)
  • Features:
    • Business CRUD operations
    • Business profile management
    • KYC verification
  • Endpoints:
    • GET /business - List businesses
    • GET /business/:id - Get business
    • POST /business - Create business
    • PATCH /business/:id - Update business
    • DELETE /business/:id - Delete business
3. Employee Module (/employee)
  • Features:
    • Employee CRUD operations
    • Employee profile management
    • Document management
  • Endpoints:
    • GET /employee - List employees
    • GET /employee/:id - Get employee
    • POST /employee - Create employee
    • PATCH /employee/:id - Update employee
    • DELETE /employee/:id - Delete employee

Expected Additional Modules

4. Payroll Module (/payroll)
  • Payroll processing
  • Approval workflows
  • Payslip generation
  • Tax calculations
5. Loan Module (/loans)
  • Loan application processing
  • Loan approval workflows
  • Repayment tracking
6. EWA Module (/ewa)
  • EWA request processing
  • Disbursement management
  • Repayment tracking
7. BNPL Module (/bnpl)
  • BNPL transaction processing
  • Installment management
  • Merchant management
8. Equb Module (/equb)
  • Equb creation and management
  • Contribution tracking
  • Payout processing
9. Wallet Module (/wallet)
  • Wallet management
  • Transaction processing
  • Withdrawal requests
10. Settlement Module (/settlement)
  • Settlement batch processing
  • Reconciliation
  • Payment distribution

🗄️ Database Schema

Core Entities

1. User & Authentication

  • User: Core user entity with authentication
  • Role: Granular role-based access control
  • AdminProfile: Admin-specific profile data

2. Business & Organization

  • Business: Company/organization entity
  • Department: Organizational departments
  • Employee: Employee records with KYC

3. Payroll System

  • Payroll: Payroll batch processing
  • PayrollEntry: Individual employee payroll entries

4. Financial Services

Loans:

  • BusinessLoan: Loans for businesses
  • EmployeeLoan: Loans for employees
  • LoanPayment: Loan repayment tracking

Early Wage Access:

  • EarlyWageAccess: EWA requests and disbursements

BNPL:

  • BNPLPurchase: BNPL transactions
  • BNPLPayment: Installment payments
  • BNPLPartner: BNPL partner entities
  • Merchant: Merchant entities

5. Equb System

  • Equb: Equb circle entity
  • EqubMember: Equb membership
  • EqubPayout: Payout tracking

6. Financial Infrastructure

  • FinancialInstitution: Banks and MFIs
  • LedgerAccount: Chart of accounts
  • Transaction: Financial transactions
  • JournalEntry: Double-entry bookkeeping

7. Wallet System

  • Wallet: Employee wallet
  • WalletTransaction: Wallet transactions
  • WithdrawalRequest: Withdrawal requests

8. Settlement & Reconciliation

  • SettlementBatch: Settlement batches
  • SettlementRecord: Individual settlement records

9. Utilities

  • BillPayment: Utility bill payments
  • Expense: Personal expense tracking
  • SavingGoal: Savings goals

10. Audit & Compliance

  • AuditLog: System audit trail
  • EmployeeAbsence: Absence tracking

Key Relationships

Business
├── Employees (1:N)
├── Payrolls (1:N)
├── Departments (1:N)
├── BusinessLoans (1:N)
├── Equbs (1:N)
└── LedgerAccounts (1:N)

Employee
├── User (1:1)
├── Wallet (1:1)
├── PayrollEntries (1:N)
├── EmployeeLoans (1:N)
├── EarlyWageAccess (1:N)
├── BNPLPurchases (1:N)
├── EqubMemberships (1:N)
└── Expenses (1:N)

Payroll
├── Business (N:1)
└── PayrollEntries (1:N)

Equb
├── Business (N:1) [optional]
├── EqubMembers (1:N)
└── EqubPayouts (1:N)

🔐 Authentication & Authorization

Authentication Flow

  1. User Registration

    • User provides email, password, name
    • Password hashed with bcrypt
    • User record created
    • Verification email sent (optional)
  2. Login

    • User provides email and password
    • Credentials validated
    • JWT access token generated (15min expiry)
    • JWT refresh token generated (7 days expiry)
    • Tokens returned to client
  3. Token Refresh

    • Client sends refresh token
    • New access token generated
    • New refresh token generated (optional)
  4. 2FA (Optional)

    • User enables 2FA in settings
    • TOTP secret generated
    • QR code provided for authenticator app
    • Backup codes generated
    • 2FA required on subsequent logins

Authorization (RBAC)

Role Hierarchy

Platform Roles:

  • Super Admin: Full system access
  • Admin: Platform administration
  • Support: Customer support access
  • Viewer: Read-only access

Business Roles:

  • Business Owner: Full business access
  • HR Manager: Employee and payroll management
  • Finance Manager: Financial operations
  • Department Head: Department-specific access
  • Employee: Self-service access

Partner Roles:

  • FI Admin: Financial institution operations
  • BNPL Partner Admin: BNPL operations

Permission Model

Permissions are defined per module and action:

{
module: "Payroll",
actions: ["view", "create", "edit", "approve", "delete"]
}

Example Role Configuration:

{
"name": "HR Manager",
"scope": "BUSINESS",
"permissions": [
{ "module": "Employee", "actions": ["view", "create", "edit"] },
{ "module": "Payroll", "actions": ["view", "create", "edit"] },
{ "module": "EWA", "actions": ["view", "approve", "reject"] }
]
}

Security Features

  1. Password Security

    • Minimum 8 characters
    • Bcrypt hashing (10 rounds)
    • Password history (prevent reuse)
  2. JWT Security

    • Short-lived access tokens (15min)
    • Refresh token rotation
    • Token blacklisting on logout
  3. 2FA Support

    • TOTP-based (Google Authenticator, Authy)
    • Backup codes for recovery
    • Optional per user
  4. KYC Verification

    • ID document upload (front/back)
    • Selfie verification
    • Manual review workflow
    • Bank-grade verification
  5. Audit Logging

    • All sensitive operations logged
    • User actions tracked
    • IP address and user agent captured
    • Immutable audit trail

🚀 Deployment

Development Environment

# Install dependencies
pnpm install

# Start database
pnpm docker:up

# Run migrations
pnpm prisma:migrate
pnpm prisma:generate

# Start all applications
pnpm dev

# Or start individually
pnpm dev:api # Backend API (port 3000)
pnpm dev:admin # Admin portal (port 4200)
pnpm dev:business # Business portal (port 4201)
pnpm dev:client # Client portal (port 4202)
pnpm dev:fi # FI portal (port 4203)
pnpm dev:bnpl-partner # BNPL portal (port 4204)

I'll analyze each application in the system thoroughly and create a comprehensive README. Let me start by examining the structure and features of each app.

Production Build

# Build all applications
pnpm build

# Or build individually
pnpm build:api
pnpm build:admin
pnpm build:business
pnpm build:client
pnpm build:fi
pnpm build:bnpl-partner

Docker Deployment

API:

# Build Docker image
docker build -f apps/api/Dockerfile -t demozpay-api .

# Run container
docker run -p 3000:3000 \
-e DATABASE_URL="postgresql://..." \
-e JWT_SECRET="..." \
demozpay-api

Frontend Apps: Each Next.js app can be deployed to:

  • Vercel (recommended)
  • Netlify
  • AWS Amplify
  • Self-hosted Node.js server

Environment Variables

Server (.env):

DATABASE_URL="postgresql://user:password@localhost:5432/demozpay"
JWT_SECRET="your-secret-key"
JWT_EXPIRES_IN="15m"
REFRESH_TOKEN_SECRET="your-refresh-secret"
REFRESH_TOKEN_EXPIRES_IN="7d"
PORT=3000

Frontend (.env.local):

NEXT_PUBLIC_API_URL="http://localhost:3000"
NEXT_PUBLIC_APP_NAME="DemozPay"

📊 API Endpoint Summary

Admin Portal Endpoints

ModuleMethodEndpointDescription
DashboardGET/api/admin/dashboard/metricsDashboard metrics
BusinessesGET/api/admin/businessesList businesses
BusinessesGET/api/admin/businesses/:idGet business details
BusinessesPOST/api/admin/businessesCreate business
BusinessesPATCH/api/admin/businesses/:idUpdate business
BusinessesPATCH/api/admin/businesses/:id/statusChange status
UsersGET/api/admin/usersList users
UsersPOST/api/admin/usersCreate user
UsersPATCH/api/admin/users/:idUpdate user
PayrollGET/api/admin/payrollsList all payrolls
LoansGET/api/admin/loans/businessBusiness loans
LoansGET/api/admin/loans/employeeEmployee loans
EWAGET/api/admin/ewa/requestsEWA requests
BNPLGET/api/admin/bnpl/transactionsBNPL transactions
EqubGET/api/admin/equbsList equbs
FIGET/api/admin/financial-institutionsList FIs

Business Portal Endpoints

ModuleMethodEndpointDescription
DashboardGET/api/business/dashboard/metricsDashboard metrics
EmployeesGET/api/business/employeesList employees
EmployeesPOST/api/business/employeesAdd employee
EmployeesPATCH/api/business/employees/:idUpdate employee
DepartmentsGET/api/business/departmentsList departments
PayrollGET/api/business/payrollsList payrolls
PayrollPOST/api/business/payrollsCreate payroll
PayrollPOST/api/business/payrolls/:id/approveApprove payroll
EWAGET/api/business/ewa/requestsEWA requests
EWAPATCH/api/business/ewa/requests/:id/approveApprove EWA
LoansGET/api/business/loans/employeeEmployee loans
BNPLGET/api/business/bnpl/purchasesBNPL purchases
EqubGET/api/business/equbsCorporate equbs
EqubPOST/api/business/equbsCreate equb

Client Portal Endpoints

ModuleMethodEndpointDescription
DashboardGET/api/employee/dashboardDashboard data
EWAGET/api/employee/ewa/availableAvailable EWA
EWAPOST/api/employee/ewa/requestRequest EWA
BNPLGET/api/employee/bnpl/merchantsList merchants
BNPLPOST/api/employee/bnpl/purchaseMake purchase
LoansGET/api/employee/loans/eligibilityCheck eligibility
LoansPOST/api/employee/loans/applyApply for loan
EqubGET/api/employee/equbsAvailable equbs
EqubPOST/api/employee/equbs/joinJoin equb
EqubPOST/api/employee/equbs/createCreate private equb
PayslipGET/api/employee/payslipsList payslips
ProfileGET/api/employee/profileGet profile
BudgetGET/api/employee/budget/summaryBudget summary

FI Portal Endpoints

ModuleMethodEndpointDescription
DashboardGET/api/fi/dashboard/metricsDashboard metrics
LoansGET/api/fi/loan-requestsLoan requests
LoansPATCH/api/fi/loan-requests/:id/approveApprove loan
LoansGET/api/fi/loans/activeActive loans
RepaymentsGET/api/fi/repaymentsList repayments
SettlementsGET/api/fi/settlementsSettlement batches

BNPL Portal Endpoints

ModuleMethodEndpointDescription
DashboardGET/api/bnpl/dashboard/metricsDashboard metrics
TransactionsGET/api/bnpl/transactionsList transactions
RiskGET/api/bnpl/risk/exposureExposure analysis
RepaymentsGET/api/bnpl/repaymentsList repayments
SettlementsGET/api/bnpl/settlementsSettlement batches

🔄 Key Business Flows

1. Payroll Processing Flow

1. HR creates payroll (clean draft or clone previous)
2. HR imports variable components (overtime, bonuses)
3. System calculates:
- Gross pay (base salary + allowances + overtime + bonus)
- Deductions (tax, pension, loans, EWA, BNPL, equb)
- Net pay
4. HR reviews and submits for approval
5. Finance Manager approves
6. CEO approves (if required)
7. Payroll status: APPROVED
8. System generates payslips
9. Business initiates payment
10. System marks payroll as PAID
11. Optional: Submit to Ministry of Revenue

2. Early Wage Access (EWA) Flow

1. Employee checks available EWA amount
2. Employee requests EWA (amount, purpose)
3. System validates:
- Employee eligibility
- Available earned wages
- Maximum EWA limit
4. HR/Manager reviews request
5. HR approves/rejects
6. If approved, system disburses to employee
7. Amount deducted from next payroll
8. EWA marked as DEDUCTED

3. BNPL Purchase Flow

1. Employee browses BNPL merchants
2. Employee selects product and installment plan
3. System checks:
- Employee eligibility
- Credit limit
- Salary sufficiency
4. Employee confirms purchase
5. System creates BNPL record
6. Merchant receives payment
7. Installments deducted from monthly payroll
8. System tracks payment status
9. Upon completion, BNPL marked as COMPLETED

4. Loan Application Flow

1. Employee applies for loan (amount, purpose, term)
2. HR reviews and approves (employee loans)
3. Application sent to Financial Institution
4. FI reviews credit assessment
5. FI approves/rejects with terms
6. If approved, loan disbursed
7. Monthly repayments deducted from payroll
8. System tracks repayment schedule
9. Upon full repayment, loan marked as PAID_OFF

5. Equb Creation & Management Flow

1. Organizer creates equb (name, contribution, frequency, members)
2. System validates equb parameters
3. Organizer invites members (corporate) or members join (private)
4. Admin approves equb (if required)
5. Equb starts on specified date
6. Each round:
- Members contribute (auto-deducted from payroll)
- Winner selected (random/sequential/bidding)
- Payout executed
- Round marked as completed
7. After all rounds, equb marked as COMPLETED

💡 Key Features Explained

Equb System (Ethiopian Savings Circles)

What is Equb? Equb is a traditional Ethiopian rotating savings and credit association (ROSCA). Members contribute a fixed amount regularly, and each round, one member receives the total pool.

Types:

  • Corporate Equb: Organized by businesses for employees
  • Private Equb: Created by individuals for friends/family

How it works:

  1. 10 members contribute ETB 1,000 monthly
  2. Total pool: ETB 10,000
  3. Month 1: Member A receives ETB 10,000
  4. Month 2: Member B receives ETB 10,000
  5. Continues until all members receive payout

Selection Methods:

  • Random: Winner selected randomly
  • Sequential: Pre-determined order
  • Bidding: Members bid for early payout

Early Wage Access (EWA)

What is EWA? Employees can access a portion of their earned wages before the regular payday.

How it works:

  1. Employee has earned ETB 15,000 (15 days worked)
  2. Employee can request up to 50% (ETB 7,500)
  3. Amount disbursed immediately
  4. Deducted from next paycheck

Benefits:

  • Financial flexibility for emergencies
  • No interest charges
  • Instant disbursement
  • Automatic payroll deduction

Buy Now Pay Later (BNPL)

What is BNPL? Salary-backed installment purchases from partner merchants.

How it works:

  1. Employee purchases ETB 10,000 laptop
  2. Chooses 5-month installment plan
  3. Pays ETB 2,000 monthly from salary
  4. No interest (or low interest)
  5. Merchant receives full payment upfront

Benefits:

  • Access to goods without upfront payment
  • Automatic salary deduction
  • Credit building
  • No traditional credit check

Multi-Level Payroll Approval

Approval Workflow:

  1. HR Approval: Verify employee data, attendance
  2. Finance Approval: Verify calculations, budget
  3. CEO Approval: Final authorization (optional)

Status Progression:

DRAFT → PENDING_HR_APPROVAL → PENDING_FINANCE_APPROVAL
→ PENDING_CEO_APPROVAL → APPROVED → PAID

Double-Entry Bookkeeping

Ledger System: Every financial transaction creates balanced journal entries.

Example - Payroll Payment:

Debit: Payroll Expense ETB 100,000
Credit: Cash ETB 100,000

Example - Loan Disbursement:

Debit: Loans Receivable ETB 50,000
Credit: Cash ETB 50,000

🧪 Testing

Unit Tests

# Run all unit tests
pnpm test

# Run tests for specific project
npx nx test api
npx nx test admin

# Run with coverage
pnpm test:coverage

# Watch mode
pnpm test:watch

E2E Tests

# Run all E2E tests
pnpm e2e

# Run E2E for specific app
pnpm e2e:admin
pnpm e2e:business
pnpm e2e:client

Test Structure

apps/
├── api/ NestJS modular monolith
│ └── src/ app/ · _infra/ · identity/ · workforce/ · products/ · compliance/ · money/ · payroll/
├── admin-web/ (+ admin-web-e2e/)
├── employer-web/ (+ employer-web-e2e/)
├── employee-web/ (+ employee-web-e2e/)
├── fi-web/ (+ fi-web-e2e/)
├── merchant-web/ (+ merchant-web-e2e/)
└── docs-web/

📚 Additional Resources

Documentation

Project-Specific Docs

  • README.md - Quick start guide
  • NX_WORKSPACE_EXPLAINED.md - Nx workspace explanation
  • FIGMA_DESIGN_SPECS.md - Design specifications
  • apps/docs/ - Docusaurus documentation site

Development Commands

# Dependency graph
pnpm graph

# Affected commands (only changed projects)
pnpm affected:build
pnpm affected:test
pnpm affected:lint

# Database management
pnpm prisma:studio # Open Prisma Studio
pnpm prisma:migrate # Run migrations
pnpm prisma:generate # Generate Prisma Client
pnpm prisma:seed # Seed database

# Code quality
pnpm lint # Lint all projects
pnpm lint:fix # Fix linting issues
pnpm format # Format with Prettier

🎨 UI/UX Features

Theme System

Available Themes:

  • Light: Default theme with blue accents
  • Dark: Dark mode with blue accents
  • Midnight: Dark mode with midnight blue accents

Theme Variables:

--bg-primary: Background color
--text-primary: Primary text color
--button-primary: Primary button color
--border-primary: Border color

Implementation:

  • CSS custom properties
  • Theme context provider
  • Persistent theme selection
  • Smooth transitions

Multi-Language Support

Supported Languages:

  • English
  • Amharic (አማርኛ)

Implementation:

  • Language selector in settings
  • Persistent language preference
  • RTL support (if needed)

Responsive Design

Breakpoints:

  • Mobile: < 768px
  • Tablet: 768px - 1024px
  • Desktop: > 1024px

Mobile-First Approach:

  • Touch-friendly interfaces
  • Optimized for small screens
  • Progressive enhancement

🔒 Security Best Practices

Data Protection

  1. Encryption at Rest

    • Database encryption
    • File encryption for documents
  2. Encryption in Transit

    • HTTPS/TLS for all communications
    • Secure WebSocket connections
  3. Sensitive Data Handling

    • PII encryption
    • Secure password storage (bcrypt)
    • Token encryption

Access Control

  1. Principle of Least Privilege

    • Users have minimum required permissions
    • Role-based access control
  2. Session Management

    • Short-lived access tokens
    • Secure refresh token rotation
    • Session timeout
  3. API Security

    • Rate limiting
    • Request validation
    • CORS configuration

Compliance

  1. Data Privacy

    • GDPR-compliant (if applicable)
    • Data retention policies
    • Right to deletion
  2. Audit Trail

    • All sensitive operations logged
    • Immutable audit logs
    • Regular audit reviews
  3. KYC/AML

    • Identity verification
    • Document verification
    • Risk assessment

📈 Scalability Considerations

Database Optimization

  1. Indexing Strategy

    • Primary keys on all tables
    • Foreign key indexes
    • Composite indexes for common queries
    • Full-text search indexes
  2. Query Optimization

    • Efficient joins
    • Pagination for large datasets
    • Caching frequently accessed data
  3. Connection Pooling

    • Prisma connection pooling
    • Optimal pool size configuration

Caching Strategy

  1. Application-Level Caching

    • Redis for session storage
    • Cache frequently accessed data
    • Cache invalidation strategy
  2. CDN for Static Assets

    • Images, CSS, JavaScript
    • Global distribution

Horizontal Scaling

  1. Stateless API Design

    • No server-side session storage
    • JWT-based authentication
    • Load balancer ready
  2. Database Replication

    • Read replicas for queries
    • Write to primary database
    • Automatic failover
  3. Microservices (Future)

    • Service decomposition
    • Independent scaling
    • Service mesh

🚨 Monitoring & Observability

Application Monitoring

  1. Logging

    • Structured logging (JSON)
    • Log levels (ERROR, WARN, INFO, DEBUG)
    • Centralized log aggregation
  2. Metrics

    • Request rate
    • Response time
    • Error rate
    • Database query performance
  3. Alerting

    • Error rate thresholds
    • Performance degradation
    • System health checks

Business Metrics

  1. Transaction Monitoring

    • Payroll processing time
    • EWA disbursement rate
    • Loan approval rate
    • BNPL transaction volume
  2. User Analytics

    • Active users
    • Feature adoption
    • User engagement

🔮 Future Enhancements

Planned Features

  1. Mobile Applications

    • Native iOS app
    • Native Android app
    • React Native implementation
  2. Advanced Analytics

    • Predictive analytics
    • Financial insights
    • Spending patterns
  3. Integration Ecosystem

    • Accounting software (QuickBooks, Xero)
    • Payment gateways (Stripe, PayPal)
    • Banking APIs
    • Government systems (tax, pension)
  4. AI/ML Features

    • Credit scoring
    • Fraud detection
    • Spending recommendations
    • Chatbot support
  5. Additional Financial Products

    • Insurance products
    • Investment options
    • Pension management
    • Remittance services
  6. Enhanced Equb Features

    • Equb marketplace
    • Equb insurance
    • Flexible contribution schedules
    • Equb analytics

👥 Team & Roles

Development Team Structure

Backend Team:

  • NestJS developers
  • Database administrators
  • DevOps engineers

Frontend Team:

  • Next.js/React developers
  • UI/UX designers
  • Mobile developers (future)

Product Team:

  • Product managers
  • Business analysts
  • QA engineers

Operations Team:

  • System administrators
  • Support engineers
  • Compliance officers

📞 Support & Contact

Technical Support

Business Inquiries


📝 License

This project is licensed under the MIT License - see the LICENSE file for details.


🙏 Acknowledgments

  • Ethiopian fintech ecosystem
  • Open source community
  • Nx team for the amazing monorepo tool
  • All contributors and supporters

Last Updated: February 2026

Version: 1.0.0

Maintained by: DemozPay Development Team