FlexDelivery24 API
A comprehensive delivery management platform built with NestJS, providing job creation, delivery matching, bidding, rewards, reviews, and comprehensive admin functionality.
Table of Contents
Features
π Authentication & Authorization
- Unified Login System: Single login endpoint supporting role-based access
- Multi-Role Support: Users can have multiple roles (user, delivery, vendor, admin)
- Role Switching: Dynamic role switching for multi-role users
- OTP Verification: Phone number verification via OTP (SMS via Twilio)
- JWT Tokens: Access and refresh token authentication
- Password Management: Forgot password, update password
- Two-Factor Authentication: Google Authenticator support for admins
- Permission-Based Access: Fine-grained permission system
π¦ Jobs & Deliveries
- Job Creation: Create delivery jobs with package details, locations, pricing
- Dynamic Pricing: Calculate delivery fees using configurable formulas
- Job Matching: Match jobs with delivery offers based on cities, budget, capacity
- Bidding System: FDA users can bid on jobs
- Status Management: Track job status (pending, approved, in_transit, completed, etc.)
- Cancellation & Refunds: Cancel jobs with automatic refund calculation
- Package Returns: Handle package returns with refund processing
- Job Dashboards: Sender and FDA dashboards with statistics
- Admin Approval: Admin approval/rejection workflow for jobs
π Delivery Offers
- Offer Creation: FDA users create delivery offers
- Offer Management: Update, activate/deactivate offers
- City-Based Matching: Match offers with jobs by pickup/delivery cities
- Availability Management: Set availability days and times
π° Rewards & Points
- Reward Programs: Configurable reward programs with levels
- Points System: Earn points from job completions
- Level Achievements: Automatic level progression
- Redemptions: Cash withdrawals and subscription upgrades
- OTP Verification: Secure redemption with OTP
- Admin Management: Create and manage reward programs
β Reviews & Ratings
- Job Reviews: Review jobs after completion
- Multi-Dimensional Ratings: Communication, promptness, handling, cooperation, compliance
- Rating Summaries: Aggregate user rating statistics
- Review Management: Edit, delete reviews
- Admin Moderation: Hide/unhide reviews, delete inappropriate content
π KYC & Document Verification
- KYC Uploads: Upload front, back, and holding proof documents
- CAC Documents: Upload CAC documents for business verification
- Admin Verification: Approve/reject documents
- Document History: Track document submission history
- Status Tracking: Pending, approved, rejected statuses
π₯ User Management
- User Profiles: Comprehensive user profiles with optional fields
- Bank Accounts: Manage bank accounts for withdrawals
- User Roles: Assign and manage user roles
- Role Invitations: Invite users to specific roles
- User Status: Active, suspended, deleted states
π° Wallet Management
- Wallet Entity: Separate wallet entity with relationship to users
- Auto-Creation: Wallet automatically created on user registration
- Balance Operations: Credit, debit, and balance checking operations
- Atomic Updates: Database-level atomic balance updates
- Multi-Currency Support: Support for multiple currencies (default: NGN)
- Wallet Transactions: Complete transaction history for wallet operations
π³ Payments & Transactions
- Wallet Deposits: Deposit funds to wallet via Paystack
- Initialize payment with Paystack
- Verify payment and credit wallet
- Automatic fee calculation (tax fees, Paystack charges)
- Webhook support for automatic processing
- Direct Payments: Pay directly without wallet (bypass wallet)
- Initiate direct payment for orders
- Payment status polling
- Webhook handling for payment updates
- Bank Account Verification: Verify bank accounts for withdrawals
- Paystack bank resolution API
- OTP verification for account confirmation
- Bank list retrieval
- Transfer recipient creation
- Withdrawals: Secure withdrawal system
- Initiate withdrawal with OTP verification
- Wallet balance validation
- Paystack transfer integration
- Admin approval workflow
- Automatic transfer processing
- Transaction Management:
- Complete transaction history
- Transaction types (FD, WF, Direct, DirectReceiver, Credit, Debit, etc.)
- Transaction notes and audit logs
- Analytics and reporting
- Balance verification
- Export capabilities
- Enhanced fields: recipientCode, withdrawalTransferId, creditAmount
π¦ Withdrawal Management
- Withdrawal Settings: Configure withdrawal limits (min, max, OTP threshold)
- Withdrawal Requests: Process withdrawal requests
- OTP Verification: Secure withdrawals with OTP
- Mobile Settings: Separate settings for mobile withdrawals
- Admin Processing: Admin approval/rejection of withdrawals
πΈ Tax & Fee Management
- Tax Charges: Configure tax charges (percentage and amount)
- Service Charges: Manage service charges
- Paystack Fees: Configure Paystack fee structures
πΊοΈ Serviceable Areas
- Area Management: Define serviceable areas by zipcode
- CRUD Operations: Create, read, update, delete serviceable areas
π Admin Dashboard
- Analytics: Comprehensive dashboard with statistics
- User Statistics: Total users, active users, new registrations
- Job Statistics: Total jobs, pending, completed, cancelled
- Transaction Statistics: Total transactions, revenue, fees
- Date Filtering: Filter analytics by date range
π§ Contact Management
- Email Settings: Configure contact email settings
- Message Submission: Submit contact messages
- Message Retrieval: Retrieve and manage contact messages
π’ Formula Management
- Delivery Formulas: Configure delivery fee calculation formulas
- Main Formulas: Manage main calculation formulas
- Shuffle Data: Configure shuffle data for calculations
π Admin Activity Logs
- Action Logging: Log all admin actions
- Audit Trail: Complete audit trail with IP, user agent, timestamps
- Filtering: Filter logs by admin, action, status, date
π Notifications
- Real-Time Notifications: Pusher integration for real-time updates
- Notification Settings: Configurable notification triggers
- Job Notifications: Notifications for job events (creation, bids, status updates)
- Review Notifications: Notifications for new reviews
Architecture
This application follows Clean Architecture principles with clear separation of concerns:
βββββββββββββββββββββββββββββββββββββββ
β Presentation Layer β
β (Controllers, Guards, Interceptors)β
ββββββββββββββββ¬βββββββββββββββββββββββ
β
ββββββββββββββββΌβββββββββββββββββββββββ
β Application Layer β
β (Use Cases, DTOs, Mappers) β
ββββββββββββββββ¬βββββββββββββββββββββββ
β
ββββββββββββββββΌβββββββββββββββββββββββ
β Domain Layer β
β (Entities, Interfaces, Services) β
ββββββββββββββββ¬βββββββββββββββββββββββ
β
ββββββββββββββββΌβββββββββββββββββββββββ
β Infrastructure Layer β
β (Repositories, External Services) β
ββββββββββββββββββββββββββββββββββββββββ
Module Structure
- Shared Module: Core business logic, use cases, repositories, services
- Web Module: Web-specific controllers (includes admin endpoints)
- Mobile Module: Mobile-specific controllers (user endpoints only)
Project Structure
src/
βββ config/ # Application configuration
βββ database/ # Database migrations
β βββ migrations/
βββ modules/
β βββ shared/ # Shared business logic
β β βββ application/ # Use cases, DTOs, mappers
β β βββ domain/ # Domain entities, interfaces
β β βββ infrastructure/ # Repositories, services, external APIs
β β βββ common/ # Utilities, constants, decorators
β β βββ errors/ # Error handling
β β βββ presentation/ # Guards, interceptors, filters
β βββ web/ # Web controllers (includes admin)
β β βββ controllers/
β βββ mobile/ # Mobile controllers (user-only)
β βββ controllers/
βββ main.ts # Application entry point
For detailed structure documentation, see:
Getting Started
Prerequisites
- Node.js (v18 or higher)
- MySQL database
- npm or yarn
Installation
# Install dependencies
npm install
# Copy environment file
cp .env.example .env
# Configure environment variables
# Edit .env with your database credentials, API keys, etc.
Environment Variables
Required environment variables (see .env.example):
DATABASE_HOST - Database host
DATABASE_PORT - Database port
DATABASE_USER - Database user
DATABASE_PASSWORD - Database password
DATABASE_NAME - Database name
JWT_SECRET - JWT secret key
JWT_REFRESH_SECRET - JWT refresh secret
TWILIO_ACCOUNT_SID - Twilio account SID
TWILIO_AUTH_TOKEN - Twilio auth token
PUSHER_APP_ID - Pusher app ID
PUSHER_KEY - Pusher key
PUSHER_SECRET - Pusher secret
PAYSTACK_SECRET_KEY - Paystack secret key
PAYSTACK_PUBLIC_KEY - Paystack public key (optional)
PAYSTACK_BASE_URL - Paystack API base URL (default: https://api.paystack.co)
CALLBACK_URL - Payment callback URL for Paystack webhooks
SMILE_ID_PARTNER_ID - SmileID partner ID (optional, for KYC verification)
SMILE_ID_API_KEY - SmileID API key (optional, for KYC verification)
SMILE_ID_BASE_URL - SmileID API base URL (optional, default: https://testapi.smileidentity.com/v1)
OPENAI_API_KEY - OpenAI API key (required for AI dispute resolution)
OPENAI_MODEL - OpenAI model to use (optional, default: 'gpt-4-turbo')
OPENAI_MAX_TOKENS - Maximum tokens for AI responses (optional, default: 2000)
OPENAI_TEMPERATURE - Temperature setting for AI (optional, default: 0.7)
OPENAI_TIMEOUT - Request timeout in milliseconds (optional, default: 30000)
Database Setup
# Run migrations
npm run migration:run:batch
# Seed initial data (roles, permissions)
npm run seed
Running the Application
# Development
npm run start:dev
# Production
npm run build
npm run start:prod
The API will be available at http://localhost:32901
API Documentation
API documentation is available via Swagger UI when the application is running:
- Swagger UI:
http://localhost:32901/api-docs
- Web API: All endpoints prefixed with
/api/v1/web/
- Mobile API: All endpoints prefixed with
/api/v1/mobile/
API Response Format
All API responses follow a standard format:
{
success: boolean;
message: string;
data?: any; // Present if data exists
errors?: any; // Present if errors exist
statusCode: number;
timestamp: string;
}
Paginated Responses
Paginated responses include metadata:
{
success: boolean;
message: string;
data: {
docs: any[]; // Array of results
meta: {
total: number;
page: number;
limit: number;
totalPages: number;
hasNextPage: boolean;
hasPrevPage: boolean;
}
};
statusCode: number;
timestamp: string;
}
Authentication
Login Flow
POST /api/v1/web/auth/login or /api/v1/mobile/auth/login
- Body:
{ phoneNumber, password, role? }
- Returns: Access token, refresh token, user details
OTP Verification (if phone not verified)
- POST
/api/v1/web/auth/verify-otp or /api/v1/mobile/auth/verify-otp
- Body:
{ phoneNumber, otpCode }
Token Usage
Include the access token in the Authorization header:
Authorization: Bearer <access_token>
Role-Based Access
- Default role:
user (if no role specified)
- Multi-role users can switch roles
- Admin endpoints require
admin or superAdmin role
- Admin endpoints are web-only
Modules
Shared Module
Core business logic shared between web and mobile:
- Use cases (business logic)
- Repositories (data access)
- Services (infrastructure services)
- Domain entities and interfaces
- Payment processing (wallet, direct payments, withdrawals)
- Transaction management
Web Module
Web-specific controllers:
- User endpoints
- Admin endpoints (web-only)
- Enhanced permissions
- Payment endpoints (wallet, direct payments, bank verification, withdrawals)
- Admin withdrawal processing
Mobile Module
Mobile-specific controllers:
- User endpoints only
- No admin endpoints
- Payment endpoints (wallet, direct payments, bank verification, withdrawals)
Database
Migrations
Database schema is managed through TypeORM migrations:
- Location:
src/database/migrations/
- Run:
npm run migration:run
- Revert:
npm run migration:revert
Key Tables
users - User accounts
jobs - Delivery jobs
job_participants - Job participants (sender, receiver, FDA)
job_locations - Pickup and delivery locations
job_packages - Package details
job_bids - Bids on jobs
delivery_offers - FDA delivery offers
wallets - User wallet balances
transactions - Financial transactions
user_bank_accounts - Bank accounts for withdrawals
user_points - User reward points
job_reviews - Job reviews
kyc_documents - KYC documents
admin_activity_logs - Admin action logs
csvdata - CSV file tracking for exports
mobile_otp - Mobile OTP entries
- And many more...
See Database README for details.
Development
Code Style
- Follow TypeScript best practices
- Use ESLint and Prettier
- Follow NestJS conventions
- Use dependency injection
Adding New Features
- Create DTOs in
src/modules/shared/application/dto/
- Create Use Case in
src/modules/shared/application/use-cases/[feature]/
- Create/Update Repository if needed
- Create Controller in
src/modules/web/controllers/ and/or src/modules/mobile/controllers/
- Register in appropriate module
Testing
# Unit tests
npm run test
# E2E tests
npm run test:e2e
# Test coverage
npm run test:cov
Scripts
# Development
npm run start:dev
# Build
npm run build
# Production
npm run start:prod
# Migrations
npm run migration:run
npm run migration:revert
npm run migration:generate -- -n MigrationName
# Format code
npm run format
# Lint
npm run lint
Key Conventions
Naming Conventions
- Use Cases:
[action]-[entity].use-case.ts
- DTOs:
[Action][Entity]Dto
- Repositories:
[Entity]Repository
- Entities:
[Entity]Entity
- Controllers:
Web[Feature]Controller / Mobile[Feature]Controller
Response Format
- Always use
StandardResponse or PaginatedResponse
- Use
createSuccessResponse() helper
- Use
createErrorResponse() for errors (handled by filter)
Error Handling
- Throw HTTP exceptions (
NotFoundException, BadRequestException, etc.)
- Use generic messages for 403 Forbidden errors
- Let
HttpExceptionFilter format errors
Admin Endpoints
- Web-only: Admin endpoints only in
WebModule
- Role Guard: Use
@Roles('admin', 'superAdmin')
- Activity Logging: Log all admin actions
Technology Stack
- Framework: NestJS (Node.js)
- Database: MySQL with TypeORM
- Authentication: JWT (access + refresh tokens)
- Real-Time: Pusher
- SMS/OTP: Twilio
- Payments: Paystack (wallet deposits, direct payments, bank verification, transfers)
- File Storage: Local (development), S3 (production)
- Documentation: Swagger/OpenAPI
- Validation: class-validator, class-transformer
License
[Your License Here]
Support
For issues and questions, please contact the development team.