LogistiX - Software Design Document (SDD) - Draft
Version: 0.1 Date: April 30, 2025
Table of Contents
- Introduction 1.1 Purpose 1.2 Scope 1.3 Definitions, Acronyms, and Abbreviations 1.4 References 1.5 Overview
- System Architecture 2.1 Architectural Design 2.2 Architectural Views (Logical, Process, Deployment, Data) 2.3 Technology Stack Rationale
- Detailed Design
3.1 Backend Services Design
3.1.1 Order Service
3.1.2 Courier Service
3.1.3 Authentication Service
3.1.4 Pricing Service
3.1.5 Notification Service
3.1.6 API Gateway
3.2 Frontend Design
3.2.1 Merchant Dashboard (React)
3.2.2 Courier Mobile App (Flutter)
3.2.3 Admin Dashboard (React)
3.3 Database Design
3.3.1 Schema Design (Reference
database_schema.sql) 3.3.2 Data Model (ERD - Conceptual) 3.3.3 Indexing Strategy 3.4 API Design 3.4.1 Merchant API (Referenceapi_spec_draft.yaml) 3.4.2 Internal API Communication 3.5 Security Design Details 3.5.1 Authentication Flow (JWT) 3.5.2 Authorization Logic (RBAC) 3.5.3 Data Encryption Details 3.5.4 API Key Handling 3.6 Scalability and Caching Design 3.6.1 Load Balancing Strategy 3.6.2 Caching Strategy (Redis) 3.6.3 Asynchronous Processing (Message Queues) 3.7 Third-Party Integration Design 3.7.1 Mapping Service Integration (OpenStreetMap/OSRM) 3.7.2 Notification Service Integration (FCM/Twilio) 3.7.3 Payment Gateway Integration (M-Pesa Daraja) - Deployment Strategy (Initial) 4.1 Cloud Environment Setup (AWS/GCP Free Tier) 4.2 Containerization (Docker) 4.3 Continuous Integration/Continuous Deployment (CI/CD) Approach (Conceptual) 4.4 Monitoring and Logging Approach
- Design Decisions and Rationale
1. Introduction
1.1 Purpose
This Software Design Document (SDD) provides a detailed description of the design for the LogistiX platform. It elaborates on the architectural decisions made and specifies the design of individual components, interfaces, and data structures, serving as a blueprint for developers during the implementation phase.
1.2 Scope
This document covers the design of the LogistiX backend services, frontend applications (Merchant Dashboard, Courier App, Admin Dashboard), database, APIs, security mechanisms, and deployment strategy for the initial Minimum Viable Product (MVP), as defined in the SRS (srs_draft.md).
1.3 Definitions, Acronyms, and Abbreviations
- API: Application Programming Interface
- AWS: Amazon Web Services
- CDN: Content Delivery Network
- CI/CD: Continuous Integration / Continuous Deployment
- DB: Database
- DPA: Data Protection Act (Kenya, 2019)
- ERD: Entity-Relationship Diagram
- FCM: Firebase Cloud Messaging
- GCP: Google Cloud Platform
- GPS: Global Positioning System
- JWT: JSON Web Token
- MVP: Minimum Viable Product
- OSM: OpenStreetMap
- OSRM: Open Source Routing Machine
- PII: Personally Identifiable Information
- RBAC: Role-Based Access Control
- REST: Representational State Transfer
- SDD: Software Design Document
- SME: Small and Medium Enterprise
- SRS: Software Requirements Specification
- SSL: Secure Sockets Layer
- TLS: Transport Layer Security
- UI: User Interface
- UML: Unified Modeling Language
- VPC: Virtual Private Cloud
1.4 References
- LogistiX Software Requirements Specification (SRS) (
/home/ubuntu/logistix_project/docs/srs_draft.md) - LogistiX System Design and Architecture (
/home/ubuntu/logistix_project/docs/system_architecture_draft.md) - LogistiX UML Diagrams (
/home/ubuntu/logistix_project/docs/uml_diagrams_draft.md) - LogistiX API Specification (
/home/ubuntu/logistix_project/docs/api_spec_draft.yaml) - LogistiX Database Schema (
/home/ubuntu/logistix_project/docs/database_schema.sql)
1.5 Overview
This document details the system architecture (Section 2), followed by the detailed design of backend services, frontend components, database, APIs, security, scalability, and third-party integrations (Section 3). Section 4 outlines the initial deployment strategy, and Section 5 summarizes key design decisions.
2. System Architecture
2.1 Architectural Design
As outlined in the System Architecture document, LogistiX employs a modular, cloud-native architecture. The primary components are the Merchant API, Courier Mobile App, Merchant Dashboard, Admin Dashboard, Backend Services (Node.js), PostgreSQL Database, and Redis Cache. Communication primarily occurs via REST APIs over HTTPS. For the MVP, backend services might be implemented within a well-structured monolith using Node.js, but designed with clear separation of concerns to allow future migration to microservices if needed.
2.2 Architectural Views
- Logical View: Depicted by the Class Diagram and Component Diagram in
uml_diagrams_draft.md. Shows key classes/components and their relationships (User, Merchant, Courier, Order, Services, etc.). - Process View: Illustrated by Sequence Diagrams (e.g., Order Creation) and Activity Diagrams (e.g., Courier Delivery Process) in
uml_diagrams_draft.md. Shows interactions between components for key workflows. - Deployment View: Described in the Deployment Diagram in
uml_diagrams_draft.md. Shows how software components map to hardware/cloud infrastructure (AWS/GCP instances, DB services, Load Balancer, etc.). - Data View: Represented by the Database Schema (
database_schema.sql) and the conceptual ERD described in the System Architecture document.
2.3 Technology Stack Rationale
- Node.js (Backend): Chosen for its performance (non-blocking I/O), large ecosystem (npm), and consistency with JavaScript used in frontend frameworks, potentially allowing for easier full-stack development within a small team.
- PostgreSQL: A robust, open-source relational database with strong support for JSONB and geospatial data (via PostGIS, needed for location features).
- Redis: Industry-standard in-memory data store for caching and session management, improving performance.
- React (Web Frontends): Popular, component-based library for building interactive UIs.
create_react_apptemplate provides a good starting point with useful tools (Tailwind, shadcn/ui). - Flutter (Mobile App): Allows for cross-platform development (iOS/Android) from a single codebase, reducing development effort for the Courier App.
- AWS/GCP: Major cloud providers offering generous free tiers, managed services (DB, Cache, Load Balancer), and scalability.
- OpenStreetMap: Free and open data source for mapping, suitable for MVP to control costs. Routing engines like OSRM can be self-hosted or used via APIs.
- Docker: Ensures consistent development and deployment environments.
- OpenAPI: Standard for defining REST APIs, enabling documentation generation and client/server code generation.
(Section 3 onwards will detail the design based on architecture docs)
3. Detailed Design
This section elaborates on the design of individual components identified in the architecture.
3.1 Backend Services Design (Node.js)
Assuming a well-structured monolithic approach for MVP, services represent logical modules within the Node.js application.
-
Directory Structure (Conceptual):
/src /config # Environment variables, DB connection /controllers # Request handlers (Express route handlers) /services # Business logic (OrderService, CourierService, etc.) /repositories # Data access logic (interacting with DB) /routes # API route definitions (Express routers) /models # Data models (e.g., Sequelize/TypeORM models if using ORM) /middleware # Express middleware (auth, validation, logging) /utils # Helper functions /validators # Input validation schemas/logic /integrations # Clients for third-party APIs (Maps, SMS, Payment) app.js # Main application entry point server.js # HTTP server setup -
3.1.1 Order Service:
- Responsibilities: Handle order creation logic, status updates, retrieval, validation, interaction with Pricing Service, Database (Orders, OrderTracking tables), and triggering Dispatch/Notification services.
- Key Functions:
createOrder(),getOrderById(),getOrdersByMerchant(),updateOrderStatus(),addTrackingUpdate(). - Dependencies: Pricing Service, Dispatch Service (via queue), Notification Service (via queue), Order Repository.
- 3.1.2 Courier Service:
- Responsibilities: Manage courier profiles, availability status, location updates, matching logic (finding suitable couriers for orders), interaction with Database (Couriers table).
- Key Functions:
updateCourierLocation(),setAvailabilityStatus(),findAvailableCouriersNear(),getCourierById(),updateCourierProfile(). - Dependencies: Courier Repository, potentially Mapping Service (for proximity calculations).
- 3.1.3 Authentication Service:
- Responsibilities: Handle user registration (hashing passwords), login (verifying credentials, generating JWTs), API key validation, JWT verification (middleware).
- Key Functions:
registerUser(),loginUser(),generateJwt(),verifyJwt(),validateApiKey(). - Dependencies: User Repository.
- 3.1.4 Pricing Service:
- Responsibilities: Calculate delivery quotes based on distance, package size/weight, and configurable pricing rules.
- Key Functions:
calculateQuote(). - Dependencies: Mapping Service (for distance calculation), Admin-configurable pricing rules (from DB/config).
- 3.1.5 Notification Service:
- Responsibilities: Consume notification requests (from message queue) and send them via appropriate channels (FCM, Twilio).
- Key Functions:
sendPushNotification(),sendSms(). - Dependencies: FCM Integration, Twilio Integration.
- 3.1.6 API Gateway (Conceptual - Implemented via Express Middleware/Routing):
- Responsibilities: Route incoming API requests to appropriate controllers, handle authentication/authorization middleware, perform initial request validation.
- Implementation: Use Express.js routing and middleware.
3.2 Frontend Design
- 3.2.1 Merchant Dashboard (React):
- Architecture: Single Page Application (SPA) using React.
- State Management: Context API or Zustand (simpler alternatives to Redux for MVP).
- UI Components: Utilize
shadcn/uifor pre-built, accessible components, styled with Tailwind CSS. - Key Views: Login, Registration, Dashboard Overview, Order List, Order Details (with Tracking Map), Create Order Form, Profile Management, API Key Management.
- API Interaction: Use
fetchAPI or libraries likeaxiosto communicate with the LogistiX Merchant API.
- 3.2.2 Courier Mobile App (Flutter):
- Architecture: Cross-platform application using Flutter framework.
- State Management: Provider or Riverpod.
- Key Screens: Login, Registration, Availability Toggle, Available Orders List, Order Details (Pickup/Delivery Info, Map View), Navigation View (using map SDK), Status Update Confirmation, Earnings Summary, Profile.
- API Interaction: Use Dart's
httppackage ordioto communicate with backend APIs. - Integrations:
google_maps_flutterorflutter_map(for OSM),firebase_messaging,geolocator,camera(for proof of delivery).
- 3.2.3 Admin Dashboard (React):
- Architecture: Similar to Merchant Dashboard (SPA using React).
- UI Components:
shadcn/uiand Tailwind CSS. - Key Views: Login, User Management (Merchants, Couriers), Order Monitoring, System Configuration (Pricing, Areas), Reporting/Analytics Views.
- API Interaction: Communicate with dedicated Admin API endpoints.
3.3 Database Design
- 3.3.1 Schema Design: Detailed schema provided in
/home/ubuntu/logistix_project/docs/database_schema.sql. Uses PostgreSQL with specific data types, constraints, and indexes. - 3.3.2 Data Model (ERD - Conceptual): Key entities (Users, Merchants, Couriers, Orders, OrderTracking, Ratings, Payments) and their relationships are described conceptually in the System Architecture document and reflected in the SQL schema.
- 3.3.3 Indexing Strategy: Indexes are defined in the SQL schema (
database_schema.sql) on foreign keys (e.g.,merchant_id,assigned_courier_idin Orders), status fields, timestamps, and geospatial data (current_locationin Couriers,locationin OrderTracking using GIST) to optimize common query patterns.
3.4 API Design
- 3.4.1 Merchant API: Defined in OpenAPI 3.0 format in
/home/ubuntu/logistix_project/docs/api_spec_draft.yaml. Specifies endpoints, request/response schemas, and authentication (API Key). - 3.4.2 Internal API Communication: For MVP (structured monolith), communication between services/modules will primarily be through direct function calls within the Node.js application. If migrating to microservices later, communication would shift to REST APIs or asynchronous messaging (message queues).
- Courier App API: Requires separate API endpoints (likely under
/api/v1/courier/) for courier-specific actions (accept/reject order, update status, update location, get earnings). Authentication via JWT. - Admin API: Requires separate API endpoints (likely under
/api/v1/admin/) for administrative functions. Authentication via JWT with admin role checks.
3.5 Security Design Details
- 3.5.1 Authentication Flow (JWT):
- User (Courier/Admin/Merchant via Dashboard) logs in with credentials.
- Auth Service verifies credentials against
Userstable (password_hash). - If valid, Auth Service generates a JWT containing
userId,role, and expiry time, signed with a secret key. - JWT is returned to the client.
- Client includes JWT in the
Authorization: Bearer <token>header for subsequent requests. - API Gateway/Middleware verifies the JWT signature and expiry, extracts
userIdandrolefor authorization checks.
- 3.5.2 Authorization Logic (RBAC): Implemented using middleware in the backend (Express). Each protected route will specify the required role(s). The middleware checks the
roleextracted from the validated JWT against the required roles. - 3.5.3 Data Encryption Details:
- At Rest: Use PostgreSQL encryption features if available/needed, or application-level encryption for specific sensitive fields (e.g., API keys) using Node.js crypto libraries.
- In Transit: Enforce HTTPS for all API endpoints and web dashboards using TLS certificates (e.g., Let's Encrypt via cloud provider services).
- 3.5.4 API Key Handling: Generate cryptographically strong random strings for API keys. Store securely (e.g., hashed or encrypted) in the
Merchantstable. Only display the full key to the merchant once upon generation.
3.6 Scalability and Caching Design
- 3.6.1 Load Balancing Strategy: Use AWS ELB or GCP Cloud Load Balancer in front of multiple instances of the Node.js backend application (running in Docker containers, potentially managed by ECS/EKS/GKE or simple EC2/Compute Engine instances with auto-scaling groups in later phases).
- 3.6.2 Caching Strategy (Redis):
- Cache user session information (linked to JWT or session ID).
- Cache frequently accessed configuration data (e.g., pricing rules, service areas).
- Consider caching results of expensive queries (e.g., complex reports) with appropriate invalidation.
- 3.6.3 Asynchronous Processing (Message Queues): Use AWS SQS or RabbitMQ. Tasks like sending notifications (SMS/Push), generating complex reports, or potentially triggering background checks can be pushed onto a queue by the main application thread and processed by separate worker services/processes. This improves API responsiveness.
3.7 Third-Party Integration Design
- 3.7.1 Mapping Service Integration (OpenStreetMap/OSRM):
- Create an adapter module (
/src/integrations/mappingService.js). - Use libraries like
node-osrmor make HTTP requests to an OSRM API (self-hosted or public) for route distance/duration. - Use Nominatim API (or a library wrapper) for geocoding addresses to coordinates.
- Handle API rate limits and error responses.
- Create an adapter module (
- 3.7.2 Notification Service Integration (FCM/Twilio):
- Create adapter modules (
/src/integrations/fcmService.js,/src/integrations/twilioService.js). - Use official Node.js SDKs (
firebase-adminfor FCM,twiliofor SMS). - Manage API keys/credentials securely (environment variables).
- Implement logic to fetch recipient tokens/phone numbers and construct messages based on requests from the message queue.
- Create adapter modules (
- 3.7.3 Payment Gateway Integration (M-Pesa Daraja):
- Create an adapter module (
/src/integrations/mpesaService.js). - Use Safaricom Daraja API documentation to implement necessary flows (e.g., C2B for merchant payments, B2C for courier payouts).
- Handle authentication (OAuth), request/response formats, callbacks, and error handling specific to Daraja.
- Store transaction IDs and update payment status in the
Paymentstable.
- Create an adapter module (
4. Deployment Strategy (Initial)
- 4.1 Cloud Environment Setup (AWS/GCP Free Tier):
- Set up VPC, subnets, security groups.
- Provision free tier instances (EC2 t2.micro / GCP e2-micro) for backend application.
- Provision free tier managed database (RDS/Cloud SQL PostgreSQL).
- Provision free tier managed cache (ElastiCache/Memorystore Redis).
- Configure S3/Cloud Storage bucket for static frontend assets.
- Configure CloudFront/Cloud CDN for serving frontend assets.
- Set up DNS records.
- 4.2 Containerization (Docker):
- Create
Dockerfilefor the Node.js backend application. - Use Docker Compose for local development environment setup (backend, DB, cache).
- Deploy backend application as a Docker container on cloud instances.
- Create
- 4.3 CI/CD Approach (Conceptual):
- Use GitHub Actions or GitLab CI/CD.
- Pipeline triggers on push to main/develop branches.
- Steps: Install dependencies, Run linters/formatters, Run unit/integration tests, Build Docker image, Push image to registry (Docker Hub, ECR, GCR), Deploy image to cloud instances (e.g., using SSH, or cloud-specific deployment tools).
- 4.4 Monitoring and Logging Approach:
- Use cloud provider's basic monitoring (CloudWatch/Cloud Monitoring) for CPU, memory, network.
- Implement structured logging within the Node.js application (e.g., using Winston or Pino), outputting logs to stdout/stderr for container log collection.
- Set up basic health checks on the load balancer.
5. Design Decisions and Rationale
- Monolith vs. Microservices: Chose structured monolith for MVP due to small team size and faster initial development, but designed for future separation.
- Node.js Backend: Leverages JavaScript ecosystem consistency and performance benefits of non-blocking I/O.
- PostgreSQL: Robust RDBMS with needed features (JSONB, PostGIS) and good cloud support.
- React/Flutter: Popular, well-supported frameworks for web and cross-platform mobile development.
- OpenStreetMap: Cost-effective mapping solution for MVP.
- Cloud Free Tiers: Minimizes initial infrastructure costs.
- JWT Authentication: Standard, stateless authentication mechanism suitable for APIs.
- API Key for Merchants: Simple authentication method for B2B API integration.