๐Ÿฆ BOC Life Retirement Package Booking Platform

A comprehensive booking platform for BOC Life policy holders to redeem retirement packages using their accumulated points.

๐Ÿ“Š System Architecture

High-Level Architecture

graph TB
    subgraph "Client Layer"
        A[Flutter Web App]
        B[Flutter iOS App]
        C[Flutter Android App]
        D[Admin Dashboard]
    end

    subgraph "Application Layer"
        E[FastAPI Backend<br/>Python 3.12+]
        F[Directus CMS<br/>Node.js]
    end

    subgraph "Data Layer"
        G[(PostgreSQL 15<br/>Main Database)]
        H[(Redis Cache)]
    end

    subgraph "AWS Cloud Services"
        I[S3 Bucket<br/>File Storage]
        J[SNS<br/>SMS/OTP]
        K[SES<br/>Email Service]
        L[CloudFront<br/>CDN]
        M[EC2/ECS<br/>Hosting]
    end

    A --> E
    B --> E
    C --> E
    D --> F
    E --> F
    E --> G
    E --> H
    F --> G
    E --> I
    E --> J
    E --> K
    A --> L
    B --> L
    C --> L
    E --> M
    F --> M

    style E fill:#e3f2fd
    style F fill:#fff3e0
    style G fill:#f3e5f5
    style H fill:#fce4ec

API Architecture & Data Flow

sequenceDiagram
    participant User as User/Client
    participant API as FastAPI Backend
    participant Cache as Redis Cache
    participant DB as PostgreSQL
    participant CMS as Directus CMS
    participant AWS as AWS Services

    User->>API: Request Package List
    API->>Cache: Check Cache
    alt Cache Hit
        Cache-->>API: Return Cached Data
    else Cache Miss
        API->>CMS: Fetch Packages
        CMS->>DB: Query Data
        DB-->>CMS: Package Data
        CMS-->>API: Package List
        API->>Cache: Store in Cache
    end
    API-->>User: Return Packages

    User->>API: Create Booking
    API->>DB: Validate Points
    DB-->>API: Points Available
    API->>DB: Create Booking & Deduct Points
    API->>AWS: Send Confirmation Email (SES)
    API->>CMS: Log Booking Event
    API-->>User: Booking Confirmation

Authentication Flow

sequenceDiagram
    participant User as User
    participant App as Flutter App
    participant API as FastAPI
    participant SNS as AWS SNS
    participant DB as Database

    User->>App: Enter Invitation Code
    App->>API: POST /auth/verify-invitation
    API->>DB: Validate Invitation Code
    DB-->>API: Code Valid
    API-->>App: Code Verified

    User->>App: Enter Phone Number
    App->>API: POST /auth/request-otp
    API->>SNS: Send OTP SMS
    SNS-->>User: OTP SMS
    API-->>App: OTP Sent

    User->>App: Enter OTP
    App->>API: POST /auth/verify-otp
    API->>DB: Verify OTP
    DB-->>API: OTP Valid
    API->>DB: Create/Update User
    API-->>App: JWT Access Token
    App-->>User: Authenticated

Booking System Flow

flowchart TD
    A[User Browses Packages] --> B{Filter by Location?}
    B -->|Yes| C[Select City/Region]
    B -->|No| D[View All Packages]
    C --> E[Display Filtered Packages]
    D --> E

    E --> F[Select Package]
    F --> G[Check Availability]
    G --> H{Available?}
    H -->|No| I[Show Alternative Dates]
    H -->|Yes| J[Check Points Balance]

    J --> K{Sufficient Points?}
    K -->|No| L[Show Insufficient Points]
    K -->|Yes| M[Enter Guest Details]

    M --> N[Review Booking]
    N --> O{Confirm?}
    O -->|No| P[Cancel/Edit]
    O -->|Yes| Q[Process Booking]

    Q --> R[Deduct Points]
    R --> S[Create Booking Record]
    S --> T[Send Email Confirmation]
    T --> U[Update Availability]
    U --> V[Booking Complete]

    I --> F
    L --> E
    P --> M

    style Q fill:#4caf50,color:#fff
    style V fill:#2196f3,color:#fff
    style L fill:#f44336,color:#fff

Database Schema Overview

erDiagram
    USERS ||--o{ BOOKINGS : creates
    USERS ||--o{ POINTS_TRANSACTIONS : has
    CAMPAIGNS ||--o{ INVITATION_CODES : generates
    INVITATION_CODES ||--o| USERS : used_by
    PACKAGES ||--o{ BOOKINGS : booked_in
    HOTELS ||--o{ PACKAGES : contains
    CITIES ||--o{ HOTELS : located_in

    USERS {
        string id PK
        string phone_number UK
        string email
        string full_name
        string language
        int total_points
        datetime created_at
        datetime last_login
    }

    CAMPAIGNS {
        string id PK
        string name
        string description
        int points_allocation
        datetime start_date
        datetime end_date
        boolean is_active
    }

    INVITATION_CODES {
        string code PK
        string campaign_id FK
        string user_id FK
        boolean is_used
        datetime used_at
        datetime expires_at
    }

    PACKAGES {
        string id PK
        string hotel_id FK
        string name_en
        string name_zh_hk
        string name_zh_cn
        int points_required
        int max_guests
        boolean is_active
    }

    HOTELS {
        string id PK
        string city_id FK
        string name
        string address
        float rating
        string image_url
    }

    BOOKINGS {
        string id PK
        string booking_code UK
        string user_id FK
        string package_id FK
        date check_in_date
        date check_out_date
        int points_used
        string status
        datetime created_at
    }

    POINTS_TRANSACTIONS {
        string id PK
        string user_id FK
        int points_change
        string transaction_type
        string reference_id
        datetime created_at
    }

๐Ÿš€ Tech Stack

Backend

CMS

Frontend

Infrastructure

Development Tools

โœจ Key Features

๐Ÿ” User Authentication

๐Ÿ“ฆ Package Management

๐ŸŽซ Booking System

โš™๏ธ Admin Features (Directus CMS)

๐Ÿ“Š Points System

๐Ÿ“ฑ Platform Coverage

Platform Technology Status
๐Ÿ“ฑ Mobile Web Flutter Web โœ… Supported
๐ŸŽ iOS Flutter Native โœ… Supported
๐Ÿค– Android Flutter Native โœ… Supported
๐Ÿ’ผ Admin Panel Directus CMS โœ… Supported

๐Ÿ”ง Quick Start

Prerequisites

Ensure you have the following installed:

Option 1: Docker Compose (Recommended)

This is the fastest way to get the entire platform running locally.

# 1. Clone the repository
git clone <repository-url>
cd fast_boc_life_retirement_package_booking_platform

# 2. Copy environment configuration
cp .env.example .env
# Edit .env with your configuration

# 3. Start all services
docker-compose up -d

# 4. Wait for services to start (check logs)
docker-compose logs -f

# 5. Access the services
# - Backend API: http://localhost:8000
# - API Docs: http://localhost:8000/docs
# - Directus CMS: http://localhost:8055
# - PostgreSQL: localhost:5432
# - Redis: localhost:6379

Option 2: Manual Setup

Backend Setup (FastAPI)

# 1. Navigate to backend directory
cd backend

# 2. Create virtual environment (optional but recommended)
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# 3. Install dependencies
pip install -r requirements.txt

# 4. Configure environment
cp .env.example .env
# Edit .env with your database and AWS credentials

# 5. Run database migrations (if using Alembic)
alembic upgrade head

# 6. Start the development server
uvicorn main:app --reload --host 0.0.0.0 --port 8000

# Server will be available at http://localhost:8000

Python UV Setup (Alternative)

# Using UV package manager for faster dependency resolution
uv pip install -r requirements.txt
uv run uvicorn main:app --reload

Directus CMS Setup

# 1. Navigate to CMS directory
cd _directus

# 2. Install dependencies
npm install
# Or using Bun (faster)
bun install

# 3. Configure environment
cp .env.example .env
# Edit .env with database credentials

# 4. Bootstrap Directus
npx directus bootstrap

# 5. Start Directus
npx directus start
# Or with Bun
bun run directus start

# Directus will be available at http://localhost:8055

Frontend Setup (Flutter)

# 1. Navigate to Flutter app directory
cd flutter_app

# 2. Install dependencies
flutter pub get

# 3. Configure environment
cp lib/core/config/config.example.dart lib/core/config/config.dart
# Edit config.dart with your API endpoints

# 4. Run on different platforms

# Web
flutter run -d chrome

# iOS (requires macOS and Xcode)
flutter run -d ios

# Android
flutter run -d android

# Build for production
flutter build web --release
flutter build ios --release
flutter build apk --release

Database Setup

# Using Docker for PostgreSQL
docker run -d \
  --name boclife-postgres \
  -e POSTGRES_USER=boclife \
  -e POSTGRES_PASSWORD=boclife123 \
  -e POSTGRES_DB=boc_retirement \
  -p 5432:5432 \
  postgres:15-alpine

# Using Docker for Redis
docker run -d \
  --name boclife-redis \
  -p 6379:6379 \
  redis:7-alpine

๐Ÿ” Environment Variables

Backend (.env)

# Application
APP_NAME=BOC Life Retirement Package API
API_V1_STR=/api/v1
DEBUG=True

# Database
DATABASE_URL=postgresql://boclife:boclife123@localhost:5432/boc_retirement

# JWT Authentication
JWT_SECRET_KEY=your-super-secret-jwt-key-change-this-in-production
JWT_ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30

# Redis
REDIS_URL=redis://localhost:6379

# AWS Configuration
AWS_ACCESS_KEY_ID=your-aws-access-key
AWS_SECRET_ACCESS_KEY=your-aws-secret-key
AWS_REGION=ap-east-1
AWS_S3_BUCKET=boclife-retirement-uploads

# AWS SNS (for OTP)
AWS_SNS_SENDER_ID=BOCLife

# AWS SES (for Email)
[email protected]

# Directus
DIRECTUS_URL=http://localhost:8055
DIRECTUS_TOKEN=your-directus-static-token

# CORS
CORS_ORIGINS=["http://localhost:3000","http://localhost:8080"]

Directus CMS (.env)

# Server
PORT=8055
PUBLIC_URL=http://localhost:8055

# Database
DB_CLIENT=pg
DB_HOST=localhost
DB_PORT=5432
DB_DATABASE=directus
DB_USER=boclife
DB_PASSWORD=boclife123

# Security
KEY=your-directus-key-min-32-characters
SECRET=your-directus-secret-min-32-characters

# Admin Account
[email protected]
ADMIN_PASSWORD=change-this-secure-password

# Storage
STORAGE_LOCATIONS=local
STORAGE_LOCAL_DRIVER=local
STORAGE_LOCAL_ROOT=./uploads

# Email (Optional)
[email protected]
EMAIL_TRANSPORT=smtp
EMAIL_SMTP_HOST=smtp.gmail.com
EMAIL_SMTP_PORT=587
[email protected]
EMAIL_SMTP_PASSWORD=your-app-password

# Extensions
EXTENSIONS_PATH=./extensions

๐Ÿ“ Project Structure

fast_boc_life_retirement_package_booking_platform/
โ”‚
โ”œโ”€โ”€ backend/                    # FastAPI Backend Application
โ”‚   โ”œโ”€โ”€ api/                    # API Routes
โ”‚   โ”‚   โ”œโ”€โ”€ v1/                 # API Version 1
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ auth/           # Authentication endpoints
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ users/          # User management
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ packages/       # Package endpoints
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ hotels/         # Hotel endpoints
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ bookings/       # Booking endpoints
โ”‚   โ”‚   โ”œโ”€โ”€ admin/              # Admin endpoints
โ”‚   โ”‚   โ””โ”€โ”€ dependencies.py     # Shared dependencies
โ”‚   โ”œโ”€โ”€ config/                 # Configuration
โ”‚   โ”‚   โ””โ”€โ”€ settings.py         # App settings
โ”‚   โ”œโ”€โ”€ schemas/                # Pydantic schemas
โ”‚   โ”œโ”€โ”€ services/               # Business logic services
โ”‚   โ”œโ”€โ”€ main.py                 # Application entry point
โ”‚   โ”œโ”€โ”€ requirements.txt        # Python dependencies
โ”‚   โ””โ”€โ”€ Dockerfile              # Docker configuration
โ”‚
โ”œโ”€โ”€ _directus/                  # Directus CMS Integration
โ”‚   โ”œโ”€โ”€ index.ts                # Directus SDK client
โ”‚   โ”œโ”€โ”€ directus-setup.js       # Setup scripts
โ”‚   โ”œโ”€โ”€ package.json            # Node dependencies
โ”‚   โ””โ”€โ”€ README.md               # Directus documentation
โ”‚
โ”œโ”€โ”€ cms/                        # CMS Data & Schema
โ”‚   โ”œโ”€โ”€ directus_schema.json    # Complete schema export
โ”‚   โ”œโ”€โ”€ directus_collections.json # Collections configuration
โ”‚   โ”œโ”€โ”€ directus_complete_schema.json # Full schema backup
โ”‚   โ””โ”€โ”€ uploads/                # User uploads (gitignored)
โ”‚
โ”œโ”€โ”€ deployment/                 # Deployment Configuration
โ”‚   โ””โ”€โ”€ init-db.sh              # Database initialization script
โ”‚
โ”œโ”€โ”€ scripts/                    # Utility Scripts
โ”‚   โ””โ”€โ”€ ...                     # Various helper scripts
โ”‚
โ”œโ”€โ”€ docker-compose.yml          # Docker Compose configuration
โ”œโ”€โ”€ Dockerfile                  # Main application Dockerfile
โ”œโ”€โ”€ package.json                # Root Node.js configuration
โ”œโ”€โ”€ pyproject.toml              # Python project configuration (UV)
โ”œโ”€โ”€ tsconfig.json               # TypeScript configuration
โ”œโ”€โ”€ .env.example                # Environment variables template
โ””โ”€โ”€ README.md                   # This file

๐ŸŒ API Documentation

Once the backend is running, interactive API documentation is available at:

๐Ÿ”‘ Key API Endpoints

Authentication

Method Endpoint Description
POST /api/v1/auth/verify-invitation Verify invitation code
POST /api/v1/auth/request-otp Request OTP SMS
POST /api/v1/auth/verify-otp Verify OTP and get JWT token
POST /api/v1/auth/register Register new user
POST /api/v1/auth/login User login

Packages & Hotels

Method Endpoint Description
GET /api/v1/packages List all available packages
GET /api/v1/packages/{id} Get package details
GET /api/v1/packages/search Advanced package search
GET /api/v1/hotels List all hotels
GET /api/v1/hotels/cities Get available cities
GET /api/v1/hotels/news Get latest news updates

Bookings

Method Endpoint Description
POST /api/v1/bookings Create new booking
GET /api/v1/bookings Get user's bookings
GET /api/v1/bookings/{code} Get booking details
PUT /api/v1/bookings/{code} Update booking
POST /api/v1/bookings/{code}/cancel Cancel booking

User Profile

Method Endpoint Description
GET /api/v1/users/me Get current user profile
PUT /api/v1/users/me Update user profile
GET /api/v1/users/dashboard Get user dashboard data

Admin

Method Endpoint Description
POST /api/v1/admin/campaigns Create campaign
GET /api/v1/admin/campaigns List all campaigns
POST /api/v1/admin/campaigns/{id}/generate-invitations Generate invitation codes
GET /api/v1/admin/statistics Get admin statistics

๐Ÿš€ Deployment

Docker Deployment

# Build all images
docker-compose build

# Start services in production mode
docker-compose -f docker-compose.yml -f docker-compose.prod.yml up -d

# View logs
docker-compose logs -f backend

# Stop services
docker-compose down

AWS Deployment

Backend (ECS/EC2)

# 1. Build Docker image
docker build -t boclife-api:latest ./backend

# 2. Tag for ECR
docker tag boclife-api:latest <aws-account-id>.dkr.ecr.ap-east-1.amazonaws.com/boclife-api:latest

# 3. Login to ECR
aws ecr get-login-password --region ap-east-1 | \
  docker login --username AWS --password-stdin <aws-account-id>.dkr.ecr.ap-east-1.amazonaws.com

# 4. Push to ECR
docker push <aws-account-id>.dkr.ecr.ap-east-1.amazonaws.com/boclife-api:latest

# 5. Update ECS service
aws ecs update-service --cluster boclife-cluster --service boclife-api --force-new-deployment

Flutter Web (S3 + CloudFront)

# 1. Build Flutter web app
cd flutter_app
flutter build web --release

# 2. Sync to S3
aws s3 sync build/web/ s3://boclife-web-app/ --delete

# 3. Invalidate CloudFront cache
aws cloudfront create-invalidation \
  --distribution-id <DISTRIBUTION_ID> \
  --paths "/*"

๐Ÿงช Testing

Backend Testing

# Run all tests
cd backend
pytest

# Run with coverage
pytest --cov=app --cov-report=html

# Run specific test file
pytest tests/test_auth.py

# Run with verbose output
pytest -v

Frontend Testing

cd flutter_app

# Unit tests
flutter test

# Integration tests
flutter test integration_test/

# Widget tests
flutter test test/widgets/

# Generate coverage
flutter test --coverage
genhtml coverage/lcov.info -o coverage/html

๐ŸŒ Internationalization (i18n)

The platform supports three languages:

Language Code Coverage
English en โœ… Full
Traditional Chinese zh-HK โœ… Full
Simplified Chinese zh-CN โœ… Full

Managing Translations

Backend (FastAPI)

Translations are stored in Directus CMS and accessed via API.

Frontend (Flutter)

# Generate translations
flutter gen-l10n

# Translation files location
lib/l10n/
โ”œโ”€โ”€ app_en.arb
โ”œโ”€โ”€ app_zh_HK.arb
โ””โ”€โ”€ app_zh_CN.arb

Directus CMS

All content fields support multi-language input directly in the admin interface.

๐Ÿ“Š Monitoring & Observability

Health Checks

# Backend health check
curl http://localhost:8000/health

# Directus health check
curl http://localhost:8055/server/health

Logs

# Docker logs
docker-compose logs -f backend
docker-compose logs -f directus

# Application logs (if running locally)
tail -f logs/app.log

Metrics

๐Ÿ”ง Development Guidelines

Code Style

Git Workflow

# Branch naming
feature/your-feature-name
bugfix/issue-description
hotfix/critical-fix

# Commit messages (Conventional Commits)
feat: add points balance endpoint
fix: resolve OTP verification timeout
docs: update API documentation
refactor: optimize booking service

Pull Request Process

  1. Create feature branch from main or develop
  2. Implement changes with appropriate tests
  3. Update documentation if needed
  4. Ensure all tests pass
  5. Create PR with clear description
  6. Request code review
  7. Address review comments
  8. Merge after approval

๐Ÿ› ๏ธ Troubleshooting

Common Issues

Backend Won't Start

Symptom: Server fails to start

# Check logs
docker-compose logs backend

# Common fixes:
# 1. Check database connection
docker-compose ps postgres

# 2. Verify environment variables
cat .env

# 3. Check port availability
lsof -i :8000

OTP Not Sending

Symptom: OTP SMS not received

# Verify AWS SNS configuration
aws sns list-phone-numbers-opted-out

# Check AWS credentials
aws sts get-caller-identity

# Review IAM permissions for SNS

Database Connection Issues

# Test PostgreSQL connection
docker-compose exec postgres psql -U boclife -d boc_retirement -c "SELECT 1;"

# Reset database
docker-compose down -v
docker-compose up -d postgres

Flutter Build Fails

# Clean Flutter build
flutter clean
flutter pub get
flutter pub upgrade

# Clear Flutter cache
rm -rf ~/.pub-cache
flutter pub cache repair

Logs Location

Service Location
Backend logs/app.log
Directus cms/logs/directus.log
PostgreSQL docker logs boclife-postgres
Redis docker logs boclife-redis

๐Ÿ“ž Support & Contact

Technical Contact

Documentation

Getting Help

  1. Check this README for setup instructions
  2. Review API documentation at /docs
  3. Check the troubleshooting section
  4. Contact the development team

๐Ÿ“„ License

This project is proprietary software developed for BOC Life Insurance.

ยฉ 2024 BOC Life Insurance. All rights reserved.

๐Ÿค Contributing

This is a private project. For authorized contributors:

  1. Follow the development guidelines above
  2. Ensure all tests pass before submitting PR
  3. Update documentation for new features
  4. Coordinate with stakeholders for major changes
  5. Maintain code quality and security standards

๐Ÿ”’ Security

Security Best Practices

Reporting Security Issues

If you discover a security vulnerability, please email [email protected] immediately.

Do not create public issues for security vulnerabilities.


Built with โค๏ธ for BOC Life Insurance policy holders

Last Updated: November 2024