System Architecture

စနစ် ဗိသုကာ

Cherry Land Taunggyi သည် Microservices Architecture ကို အသုံးပြုပြီး ခေတ်မီနည်းပညာများဖြင့် တည်ဆောက်ထားသော Delivery Platform ဖြစ်ပါတယ်

5+
Microservices
24/7
Real-time
99.99%
Uptime
Secure
Tunnel

Database Ownership

MariaDB vs MongoDB - Purpose and Usage

MariaDB (Relational Database)

Ownership

Python FastAPI parser processes and cleans data before storage

Purpose

Primary database for business workflow operations

Data Type

Structured, processed data with consistent schemas

Use Cases

  • • Operational users, sessions, realtime data
  • • FCM tokens
  • • Parsed orders (one row per assigned rider)
  • • Settlements, deposits, expenses
  • • Marketplace data

Access Pattern

FastAPI writes processed data; PHP, Go, and NestJS read for business operations

Note: One MongoDB order message can create multiple MariaDB rows (one per mentioned rider)

MongoDB (Document Database)

Ownership

NestJS OrdersService stores raw data directly

Purpose

Raw data storage for unstructured information across multiple chat types

Data Type

Complex, inconsistent formats without fixed schemas

Use Cases

  • • Multiple chat types stored as single documents
  • • All chat types include: attachments, reactions, mentions, raw text, riderStatus
  • • Chat types identified by chatType field value

Access Pattern

NestJS writes raw chat data for all types; reads for chat history and message context

Note: Each chat type uses the same Order schema but different chatType values

Data Flow Pattern

flowchart LR A[Raw Chat Data] --> B[MongoDB
Single Document] B --> C[FastAPI Parser] C --> D[MariaDB
Structured Rows
One per Rider] D --> E[Business Operations] style A fill:#3b82f6 style B fill:#10b981 style C fill:#8b5cf6 style D fill:#f59e0b style E fill:#ef4444
1. Raw chat data → MongoDB (single document with raw text and metadata)
2. FastAPI parses MongoDB data → MariaDB (structured rows - one per assigned rider)
3. Business operations use MariaDB for workflow execution

Admin Panel

Vue.js 3 + Tailwind CSS + Socket.IO

Vue.js 3

Composition API with reactive state management

Tailwind CSS

Utility-first CSS framework for styling

Socket.IO

Real-time bidirectional communication

IndexedDB

Client-side storage with Dexie.js

MapLibre GL

Interactive map visualization

Day.js

Lightweight date/time manipulation

Component Architecture

flowchart TD subgraph App["Vue Application"] Root[App.vue] subgraph Layout["Layout Components"] Header[Desktop Header] Sidebar[Desktop Sidebar] MobileHeader[Mobile Header] MobileNav[Mobile Bottom Nav] end subgraph Pages["Page Components"] Dashboard[Dashboard] Realtime[Real-time Tracking] Map[Map Visualization] Chat[Chat System] Settlement[Settlement] Users[User Management] Marketplace[Marketplace Module] end subgraph Shared["Shared Components"] Alert[Alert Modal] Toast[Toast Notifications] ChatComp[Chat Components] end subgraph Composables["Composables"] Auth[useAuth] Socket[useSocket] AlertComp[useAlert] Perms[usePermissions] end subgraph Storage["Storage"] IDB[IndexedDB] Local[localStorage] Cookie[Cookie] end subgraph External["External Services"] SocketIO[Socket.IO Client] API[REST API] ImageSvc[Image Service] end Root --> Layout Layout --> Pages Pages --> Shared Pages --> Composables Composables --> Storage Composables --> External Shared --> Composables end style App fill:#3b82f6 style Layout fill:#10b981 style Pages fill:#8b5cf6 style Shared fill:#f59e0b style Composables fill:#ef4444 style Storage fill:#06b6d4 style External fill:#84cc16

Data Flow with Composables

sequenceDiagram participant C as Component participant Auth as useAuth participant Socket as useSocket participant API as REST API participant IDB as IndexedDB participant S as Socket.IO C->>Auth: Check Auth Auth->>Cookie: Read Token Auth->>API: Validate Token API->>Auth: User Data Auth->>C: Auth State C->>Socket: Connect Socket->>S: WebSocket Connect S->>Socket: Connected Socket->>C: Socket State C->>API: Fetch Data API->>C: Response Data C->>IDB: Cache Data S->>Socket: Real-time Event Socket->>C: Emit Event C->>C: Update UI C->>IDB: Sync Offline C->>Auth: Check Permission Auth->>C: Permission Result

Socket.IO Integration

flowchart LR subgraph Client["Vue.js Client"] A[Component] B[useSocket Composable] C[Socket.IO Client] end subgraph Server["NestJS Server"] D[WebSocket Gateway] E[Event Handlers] F[Room Management] end subgraph Database["Data Sources"] G[MongoDB] H[MySQL] end subgraph External["External Services"] I[Firebase] end A --> B B --> C C <--> D D --> E E --> F E --> G E --> H E --> I style Client fill:#3b82f6 style Server fill:#10b981 style Database fill:#8b5cf6 style External fill:#f59e0b

IndexedDB Data Flow

flowchart TD subgraph Chat["chatDB"] A[messages store] B[images store] C[syncMetadata store] D[pinnedMessages store] end subgraph Users["usersDB"] E[users store] end subgraph Operations["Operations"] F[Add Message] G[Sync Messages] H[Cache User] I[Offline Queue] end subgraph Sync["Sync Process"] J[Fetch New Messages] K[Update Sync Metadata] L[Process Queue] end F --> A F --> B G --> A G --> C G --> J H --> E I --> L J --> A J --> K K --> C style Chat fill:#3b82f6 style Users fill:#10b981 style Operations fill:#8b5cf6 style Sync fill:#f59e0b

Key Composables

useAuth

Token management, user data storage, role hierarchy (office < admin < ceo < developer), permission checking, route-based access control

useAlert

Alert modal for confirmations, toast notifications (success, error, warning, info), auto-dismiss with configurable duration

usePermissions

Message permission checks: edit message, delete message, reaction, reply permissions

useSocket

Socket client management, automatic reconnection, message queuing when offline, cross-tab sync via BroadcastChannel

IndexedDB Schema

chatDB
  • • messages: Chat messages with indexes for chatType, tempId, serverId, senderId, timestamp, status
  • • images: Binary image data with messageId reference
  • • syncMetadata: Sync timestamps for incremental sync
  • • pinnedMessages: Pinned messages (max 5 per user)
usersDB
  • • users: User data with indexes for userId, username, name, avatar, role, status

Socket.IO Events

Connection
  • • connect, disconnect, connect_error
Chat
  • • new-message, message-edited, message-deleted, reaction-updated, message-read
Acknowledgments
  • • message-acknowledged, delete-acknowledged
Orders
  • • order-cancelled

Key Features

Real-time rider tracking
Order management system
Financial tracking
User management
Marketplace module
Chat system
Offline support
Mobile-first design

Page Components

Dashboard

Advanced filtering, statistics cards, billing calculation, CSV export

Realtime

Rider status filtering, location updates, battery monitoring, thermal box tracking

Map

Interactive rider map, search functionality, focused rider details

Chat

Multi-type chat (order, payment, settlement), IndexedDB storage, real-time sync

Settlement

Financial settlement tracking, Telegram message links, status toggling

Marketplace

Business, category, product management, overall posts, image uploads

Composables

useAuth

Token management, user data storage, role hierarchy (office < admin < ceo < developer), permission checking, route-based access control

useAlert

Alert modal for confirmations, toast notifications (success, error, warning, info), auto-dismiss with configurable duration

usePermissions

Message permission checks: edit message, delete message, reaction, reply permissions

useSocket

Socket client management, automatic reconnection, message queuing when offline, cross-tab sync via BroadcastChannel

IndexedDB Schema

chatDB
  • • messages: Chat messages with indexes for chatType, tempId, serverId, senderId, timestamp, status
  • • images: Binary image data with messageId reference
  • • syncMetadata: Sync timestamps for incremental sync
  • • pinnedMessages: Pinned messages (max 5 per user)
usersDB
  • • users: User data with indexes for userId, username, name, avatar, role, status

Cronjob Architecture

Automated Task Scheduling System

PHP

Duty checking & penalty enforcement

Python

Data analysis & reporting

Bash

Database backup operations

Telegram API

Notifications & alerts

Core Components

Morning Duty Checker

Monitors morning duty compliance, enforces penalties, rotates duty schedule, sends Telegram notifications

Non-Morning Duty Checker

Checks general rider compliance, handles leave exemptions, applies penalties for non-ready status

Morning Duty Reporter

Announces tomorrow's morning duty assignment via Telegram with @username mentions

Daily Summary Reporter

Generates analytical reports with matplotlib charts: 3-day revenue, delivery ways, top riders

Database Backup Script

Automated MySQL backups with mysqldump, gzip compression, and secure file permissions

Environment Loader

Centralized configuration management for database credentials, API tokens, and settings

Cronjob Execution Flow

flowchart TD subgraph Cron["Cron Scheduler"] A[Trigger Script] end subgraph PHP["PHP Scripts"] B[Morning Duty Checker] C[Non-Morning Duty Checker] end subgraph Python["Python Scripts"] D[Morning Duty Reporter] E[Daily Summary Reporter] end subgraph Bash["Bash Scripts"] F[Database Backup] end subgraph DB["MySQL Database"] G[Duty Schedule] H[Users Table] I[Realtime Status] J[Orders Table] K[Penalties Table] L[Leave Days] end subgraph Telegram["Telegram API"] M[Bot Notifications] end subgraph Backup["Backup Storage"] N[Compressed SQL] end A --> B A --> C A --> D A --> E A --> F B --> G B --> H B --> I B --> J B --> K B --> M B --> G C --> H C --> I C --> J C --> K C --> L C --> M D --> G D --> M E --> J E --> H E --> M F --> DB F --> N style Cron fill:#3b82f6 style PHP fill:#8b5cf6 style Python fill:#10b981 style Bash fill:#f59e0b style DB fill:#ef4444 style Telegram fill:#06b6d4 style Backup fill:#84cc16

Database Tables Accessed

Duty Schedule

Daily duty assignments with date and username list (JSON)

Users Table

Rider information: username, Telegram username, chat ID

Realtime Table

Rider status updates: username, status, timestamp

Orders Table

Order records: username, delivery fee, way count, timestamp

Penalties Table

Penalty records: username, date, reason, amount

Leave Days

Approved leave records: username, date

Cron Schedule

flowchart LR subgraph Daily["Daily Schedule"] A[Morning Duty Check] B[Non-Morning Duty Check] C[Morning Duty Report] D[Daily Summary Report] E[Database Backup] end A --> B B --> C C --> D D --> E style A fill:#3b82f6 style B fill:#8b5cf6 style C fill:#10b981 style D fill:#f59e0b style E fill:#ef4444

Security & Performance

Environment variable configuration
Prepared statements for SQL injection prevention
Transaction-based atomic operations
Restrictive backup file permissions (600)
Optimized database queries with indexes
Gzip compression for backup storage
Duplicate prevention before insertion
Automatic temporary file cleanup

Script Details

Morning Duty Checker (PHP)

Monitors morning duty compliance, enforces penalties, rotates duty schedule, sends Telegram notifications. Checks realtime status and order completion.

Non-Morning Duty Checker (PHP)

Checks general rider compliance, handles leave exemptions, applies penalties for non-ready status. Filters by active riders and leave days.

Morning Duty Reporter (Python)

Announces tomorrow's morning duty assignment via Telegram with @username mentions. Queries duty schedule and formats message.

Daily Summary Reporter (Python)

Generates analytical reports with matplotlib charts: 3-day revenue, delivery ways, top riders. Sends charts via Telegram API.

Database Backup (Bash)

Automated MySQL backups with mysqldump, gzip compression, and secure file permissions. Single transaction for consistency.

Environment Loader (PHP)

Centralized configuration management for database credentials, API tokens, and settings. Loads .env file and sets environment variables.

Database Tables Accessed

Duty Schedule

Daily duty assignments with date and username list (JSON)

Users Table

Rider information: username, Telegram username, chat ID

Realtime Table

Rider status updates: username, status, timestamp

Orders Table

Order records: username, delivery fee, way count, timestamp

Penalties Table

Penalty records: username, date, reason, amount

Leave Days

Approved leave records: username, date

Deployment Architecture

Docker Compose + Cloudflare Tunnel

Docker Compose

Container orchestration for all microservices with persistent volumes

Cloudflare Tunnel

Secure public exposure without public IP, DDoS protection, auto HTTPS

MySQL 8.0

Relational database with persistent volume storage

MongoDB 6.0

Document database for chat and order storage

Security Features

Localhost-only binding
Docker network isolation
Internal auth keys
SSL/TLS termination
No direct port exposure
Session validation

Service Details

MySQL 8.0

Relational database with persistent volume storage. Localhost-only binding, optimized for high connection limits, timezone Asia/Yangon.

MongoDB 6.0

Document database for chat and order storage. Localhost-only binding, built-in health check, persistent volume for data persistence.

Cloudflare Tunnel

Secure public exposure without public IP. DDoS protection, auto HTTPS, SSL/TLS termination at Cloudflare edge.

Docker Network

External bridge network for inter-service communication. Services communicate using container names as hostnames.

Volume Management

Persistent Data Volumes
  • • Relational database volume for MySQL data
  • • Document database volume for MongoDB data
  • • Node modules volume for dependency caching
  • • Image storage directory for persistent images
Application Data Mounts
  • • Frontend code mounted for live updates
  • • Laravel code mounted for live updates
  • • FastAPI code mounted for live updates
  • • NestJS code mounted for live updates

FastAPI Backend

Order Parsing Service with NLP

Python 3.x

Modern async web framework with automatic OpenAPI docs

Regex Parser

Natural language processing for Myanmar/English orders

PyMySQL

Relational database driver with DictCursor support

Pydantic

Data validation and serialization with type hints

Capabilities

Myanmar digit conversion
Phone number normalization
Multi-rider assignment
Complexity scoring
Type classification
Warning generation

Parser Modules

DeliveryParser (order.py)

Parses delivery orders with pickup/delivery extraction, fee calculation, way counting, complexity scoring, and warning generation.

SettleParser (settle.py)

Parses settlement messages with payer information, fee breakdowns, and order validation. Handles delivery and service fees.

DepositParser (deposit.py)

Parses deposit and stake transactions with multi-user support, expense tracking, and promotion card parsing.

Data Flow

flowchart LR subgraph Input["Input Data"] A[Order Text] B[Settlement Text] C[Deposit Text] end subgraph Parser["FastAPI Parsers"] D[DeliveryParser] E[SettleParser] F[DepositParser] end subgraph DB["Relational Database"] G[Orders Table] H[Settlements Table] I[Deposits Table] J[Expenses Table] end A --> D B --> E C --> F D --> G E --> H F --> I F --> J style Input fill:#3b82f6 style Parser fill:#10b981 style DB fill:#8b5cf6

Image Service

Go + Gin + WebP Conversion

Go (Golang)

High-performance HTTP server with Gin framework

WebP Conversion

Automatic conversion with 25-35% size reduction

MySQL

Session validation for admin and rider auth

Local Storage

Filesystem-based storage with volume mounting

Service Types

Profile avatars
Voucher attachments
Order attachments
Settlement brochures
Payment receipts
Marketplace images

NestJS Backend

Real-time Communication with WebSocket

NestJS

Progressive Node.js framework with TypeScript

WebSocket

Real-time bidirectional event-based communication

MongoDB

Document database for chat and order storage

Firebase

Push notifications for rider updates

Real-time Features

Live rider location updates
Order status changes
Chat messaging
Notification broadcasts

Gateway Details

ChatGateway

Handles real-time chat communication, message persistence, broadcasting, user presence, and multi-chat type support (order, payment, settlement).

RidersGateway

Manages rider location tracking, status updates, online/offline detection, and rider room management for real-time rider monitoring.

Chat Types

Order Chat

Delivery order discussions with rider assignment and tracking. Parsed by FastAPI DeliveryParser.

Payment Chat

Deposit and stake transaction discussions. Parsed by FastAPI DepositParser.

Settlement Chat

Financial settlement discussions with payer information. Parsed by FastAPI SettleParser.

Core Services

OrdersService

Message transformation, mention parsing, MongoDB operations, FastAPI integration based on chatType, and rider notification management.

RiderNotificationService

Socket.IO events to rider rooms, FCM push notifications, rider assignment/removal notifications, and action-based alerts.

FirebaseService

Push notification delivery for admin and rider notifications, token management, and message formatting.

RealtimeService

Rider realtime tracking table management, order ID assignment/removal, and status updates for rider availability.

Laravel Backend

PHP 8.2 + Marketplace API

Laravel

PHP framework for marketplace and admin operations

PHP 8.2

Modern PHP with Apache web server

MySQL

Relational database for business data

Apache

Web server with optimized configuration

Marketplace Features

Business management
Category management
Product catalog
Overall posts

Order Processing Workflow

End-to-End Order Flow

sequenceDiagram participant C as Customer participant O as Office participant F as FastAPI participant M as MySQL participant N as NestJS participant R as Rider participant A as Admin Panel C->>O: Submit Order (Phone/Chat) O->>F: Send Order Text F->>F: Parse Order (NLP) F->>F: Extract: Pickup, Delivery, Fee, Ways F->>F: Detect @mentions F->>M: Save Parsed Order M->>M: Create Order Rows per Rider M->>F: Confirm Save F->>O: Return Parsed Data O->>N: Broadcast Order Event N->>R: Push Notification R->>N: Accept/Reject Order N->>A: Update Order Status loop Real-time Tracking R->>N: Send GPS Location N->>A: Update Map Display end R->>O: Mark Delivered O->>M: Update Order Status O->>M: Calculate Settlement M->>A: Update Financial Records
1

Order Submission

Customer submits order via phone/chat → Order text received by system

2

Order Parsing

FastAPI parses order text → Extracts pickup, delivery, fee, ways, complexity → Multi-rider mention detection

3

Database Storage

Parsed order saved to MySQL → Order rows created per mentioned rider → Transaction committed

4

Rider Assignment

Socket.IO broadcasts order to mentioned riders → Riders receive notification → Rider accepts/rejects

5

Real-time Tracking

Rider location updates via WebSocket → Admin panel shows live map → Customer receives status updates

6

Delivery & Settlement

Order completed → Settlement calculated → Payment processed → Financial records updated

Image Upload Workflow

WebP Optimization Pipeline

flowchart TD A[User Upload Image] --> B[Multipart Form Data] B --> C{Go Service} C --> D[Middleware Auth Check] D --> E{Valid Token?} E -->|Yes| F[Validate File Type] E -->|No| G[Return 403 Forbidden] F --> H[Check Image Integrity] H --> I[Convert to WebP] I --> J[Generate UUID] J --> K[Save to Volume] K --> L[Return Public URL] L --> M[Set Cache Headers] M --> N[CDN Distribution] style A fill:#3b82f6 style C fill:#10b981 style I fill:#8b5cf6 style N fill:#f59e0b
1

Image Upload

User uploads image (JPEG/PNG/GIF/WebP) → Multipart form data sent to Go service

2

Authentication

Middleware validates X-Internal-Auth or X-Session-Token → Session checked in MySQL → Access granted/denied

3

Validation & Conversion

File type validated → Image integrity checked → Converted to WebP (75% quality) → 25-35% size reduction

4

Storage

UUID generated → WebP file saved to service-specific directory → Persistent volume mounted

5

Response & Caching

Public URL returned → 1-year cache headers set → CDN-ready for global distribution

Real-time Communication Workflow

WebSocket & Socket.IO Flow

sequenceDiagram participant RA as Rider App participant N as NestJS participant M as MongoDB participant F as Firebase participant AP as Admin Panel participant IDB as IndexedDB RA->>N: WebSocket Connect N->>N: Validate Auth N->>RA: Join Room (rider) loop Location Updates RA->>N: Send GPS Coordinates N->>AP: Broadcast to Admin Room AP->>AP: Update Map Display end RA->>N: Send Chat Message N->>M: Save to MongoDB N->>AP: Broadcast to Chat Room AP->>IDB: Sync for Offline N->>M: Order Status Update N->>AP: Emit Status Event N->>RA: Emit Status Event AP->>AP: Update UI Instantly RA->>RA: Update UI Instantly N->>F: Send Push Notification F->>RA: Order Assignment Alert F->>RA: Status Notification
1

Connection Establishment

Client connects to NestJS WebSocket → Authentication validated → Room joined (rider/admin)

2

Location Updates

Rider app sends GPS coordinates → NestJS receives → Broadcasts to admin room → Admin panel updates map

3

Chat Messaging

User sends message → Saved to MongoDB → Broadcasted to chat room → IndexedDB sync for offline

4

Order Status Changes

Status updated in MySQL → Event emitted → All connected clients notified → UI updates instantly

5

Push Notifications

Firebase integration → Rider app receives push → Order assignment alerts → Status notifications

Marketplace Data Flow

Business → Category → Product Pipeline

flowchart LR subgraph Admin["Admin Panel"] A[Create Business] B[Upload Logo/Cover] C[Create Category] D[Add Products] end subgraph Go["Go Image Service"] E[Store Images] F[Return URLs] end subgraph Laravel["Laravel API"] G[Save to MySQL] H[REST Endpoints] end subgraph Frontend["Vue.js Frontend"] I[Fetch Data] J[Render Components] K[Load Images] end A --> B B --> E E --> F F --> A A --> G C --> G D --> G G --> H H --> I I --> J J --> K K --> E style Admin fill:#3b82f6 style Go fill:#10b981 style Laravel fill:#8b5cf6 style Frontend fill:#f59e0b
1

Business Creation

Admin creates business → Logo/cover uploaded to Go service → Business saved to MySQL → API endpoint exposed

2

Category Management

Categories created → Image uploaded → Sort order set → Linked to businesses → Active status managed

3

Product Catalog

Products added → Images uploaded → Price/sale price set → Business/category linked → Availability toggled

4

API Exposure

Laravel REST API → JSON responses → Pagination support → Filtering by active status → Frontend consumption

5

Frontend Display

Vue.js fetches data → Components render → Images loaded from Go service → User browses marketplace

Code Execution Architecture

Detailed Function-to-Function Execution Flows

Admin Chat Message Flow

sequenceDiagram participant UI as Admin PWA participant N as NestJS
(ChatGateway + OrdersService) participant M as MongoDB participant P as FastAPI participant D as Relational DB participant R as Rider participant F as Firebase UI->>N: send-message event N->>N: Validate sender ID N->>N: Transform DTO & Parse mentions N->>M: Save chat document N->>P: Parse based on chatType P->>D: Save structured rows D-->>P: Success P-->>N: Success N->>N: Broadcast raw message to rider N-->>UI: message-acknowledged N->>N: Broadcast to room N->>F: Push notifications

Rider Order Assignment Flow

sequenceDiagram participant UI as Admin PWA participant N as NestJS
(OrdersService) participant M as MongoDB participant P as FastAPI participant D as Relational DB participant R as Rider participant S as RealtimeService participant Notif as RiderNotification UI->>N: Create order with mentions N->>N: Parse @mentions N->>M: Save with mentions array N->>P: Parse structured data P->>D: Save per-rider rows D-->>P: Success P-->>N: Success N->>N: Broadcast raw message to rider N->>S: Add to realtime tracking N->>Notif: Notify riders Notif->>Notif: Socket + FCM

Rider Delivery Action Flow

sequenceDiagram participant R as Rider PWA participant PHP as PHP API participant D as Relational DB participant RT as Realtime Table participant N as NestJS participant A as Admin Panel R->>PHP: Delivered action PHP->>RT: Remove order ID PHP->>D: Update order status PHP->>N: Trigger remove notification PHP->>RT: Update status N->>A: Broadcast

Key Execution Details

Message transformation: images → attachments
Mention parsing: @(\w+) regex pattern
Multi-rider: One message → multiple DB rows
FastAPI routing: chatType determines parser
Realtime tracking: Comma-separated order IDs
Transaction safety: Rollback on error