Skip to content

A modern, scalable package delivery platform that matches package senders with transporters, built with Node.js, NestJS, PostgreSQL, and Redis.

License

Notifications You must be signed in to change notification settings

hambaar-app/backend

Repository files navigation

HamBaar Logo

Hambaar - Package Delivery Platform

A modern, scalable package delivery platform that matches package senders with transporters, built with Node.js, NestJS, PostgreSQL, and Redis.

TypeScript Node.js NestJS

PostgreSQL Prisma Redis

AWS S3 Docker Jest Turf.js



πŸ—οΈ Architecture Overview

HamBaar Architecture

The system uses a modern containerized architecture with frontend/backend separation, leveraging relational and non-relational databases, cloud storage, and third-party API integrations.

πŸ”§ Architecture Components

  • Frontend Container: Vue.js with Nginx for serving static files and handling HTTP requests with JWT cookies
  • Backend Container: NestJS/Node.js handling core business logic, REST APIs, JWT authentication, and third-party API processing
  • PostgreSQL Database: Self-hosted in Docker container, storing relational data (packages, users, delivery records) via Prisma ORM
  • Redis: Self-hosted in Docker container with multiple databases:
    • Database 1: OTP data (one-time passwords)
    • Database 2: Session data
  • AWS S3: Cloud storage for package images and transporter documents using pre-signed URLs
  • External APIs:
    • Neshan Maps API: Map data and routing analysis
    • SMS API: OTP and notification delivery
    • Validation API: Transporter verification (personal info, vehicles)

πŸ› οΈ Technology Stack

Core Technologies

Category Technology Version Purpose
Runtime Node.js 22.14+ Server-side JavaScript execution
Framework NestJS Latest Enterprise-grade Node.js framework
Database PostgreSQL 15+ Primary relational database
ORM Prisma Latest Type-safe database access
Cache Redis 7+ Session management & caching
Storage AWS S3 - Cloud file storage
Maps Neshan API & Turf.js - Geospatial operations
Container Docker Latest Containerization & deployment

πŸ‘₯ User Management System

🎭 User Roles & Capabilities

πŸ“¦ Sender 🚚 Transporter πŸ› οΈ Support πŸ‘‘ Admin

β€’ Create & manage packages
β€’ Find matched trips
β€’ Send delivery requests
β€’ Track package status
β€’ Rate & review transporters
β€’ Manage payments

β€’ Create & manage trips
β€’ Handle delivery requests
β€’ Update trip status
β€’ Manage tracking info
β€’ Deliver packages
β€’ Vehicle management

β€’ Transporter verification
β€’ Monitor activities
β€’ Customer support

β€’ Full system access
β€’ System configuration


πŸ—„οΈ Database Design

πŸ“Š Entity Relationship Overview

Our PostgreSQL database is designed for scalability and data integrity:

Core Entities

Entity Purpose Key Features
πŸ‘€ User Authentication & basic profile JWT tokens, role-based access
🚚 Transporter Extended courier profiles Verification status, ratings
πŸ“¦ Package Delivery items Pricing, special handling, tracking
πŸ›£οΈ Trip Transport journeys Routes, capacity, scheduling
πŸ“ Address Location management Geocoding, province/city hierarchy
πŸš— Vehicle Transport assets Capacity, documentation

Business Logic Entities

Entity Purpose Key Features
🀝 TripRequest Delivery requests Status tracking, negotiation
βœ… MatchedRequest Confirmed matches Finalized agreements
πŸ“ TrackingUpdate Status updates Real-time location, timestamps
πŸ’° Wallet Financial management Balance, transaction history
🏦 Transaction Payment records Escrow, settlements, commissions

πŸ” Authentication & Authorization

🎫 Multi-Stage Authentication

Our security system implements a comprehensive authentication flow:

sequenceDiagram participant U as User participant S as System participant SMS as SMS Service U->>S: Phone Number S->>SMS: Send OTP SMS-->>U: OTP Code U->>S: Verify OTP S->>U: Temporary Token (20min) alt Sender Registration U->>S: Complete User Registration S->>U: Access Token (20 days) else Transporter Registration U->>S: User Registration (Stage One) S->>U: Progress Token (2 days) U->>S: Complete Authentication (Stage Two and Three) S->>U: Access Token (20 days) end 
Loading

πŸ›‘οΈ Token Management

Token Type Validity Purpose Scope
πŸ”‘ Temporary 20 minutes Initial registration Basic profile creation
⏳ Progress 2 days Multi-step registration Transporter verification
βœ… Access 20 days Full system access All authenticated operations

πŸ”’ Authorization Guards

  • Role-based Access Control (RBAC)
  • Resource ownership validation
  • Route-level protection
  • API rate limiting
  • Input sanitization

πŸš€ Core Platform Features

1. πŸ“¦ Package Management

Click to expand Package Features

Package Creation & Pricing

  • Detailed package specifications (weight, dimensions, type)
  • Automated pricing calculation with multiple factors
  • Photo upload with S3 pre-signed URLs
  • Special handling options (fragile, perishable)

Real-time Status Tracking

  • 20-digit unique tracking codes
  • Status history with timestamps
  • Public tracking (no authentication required)
  • Delivery confirmation with 5-digit codes

2. πŸ›£οΈ Trip Management

Click to expand Trip Features

Trip Planning

  • Multi-point route definition (origin, waypoints, destination)
  • Capacity management (weight and space limitations)
  • Route optimization using geospatial algorithms

Trip Lifecycle

  • Pre-trip preparation and validation

    • Intermediate city discovery
  • Real-time status updates during trip

  • Package pickup and delivery confirmations

  • Post-trip settlement and ratings

  • Get directions to pickup/delivery each

  • Get Trip Directions:

    • Retrieve directions from the transporter’s current location to the next pickup or delivery point for all packages, then to the trip’s final destination.

3. 🎯 Matching Process Flow

flowchart TD A[New Package Created] --> B{Basic Filters} B -->|Active Trips| C{Geographic Analysis} B -->|No Match| Z[No Matches Found] C -->|Route Compatible| D{Capacity Check} C -->|Out of Route| Z D -->|Sufficient Capacity| E[Calculate Score] D -->|Over Capacity| Z E --> F[Rank Matches] F --> G[Present to Sender] G --> H{Sender Selects} H -->|Request Sent| I[Transporter Review] H -->|No Selection| Z I -->|Accepted| J[Match Confirmed] I -->|Rejected| K[Try Next Match] K --> G J --> L[Payment Opened] 
Loading

4. πŸ’° Pricing Engine

Our dynamic pricing system considers multiple factors for fair and competitive rates:

Pricing Components

Component Default Rate Description
🏁 Base Price 50,000 IRR Starting price for all deliveries
πŸ“ Distance Pricing 1,200-600 IRR/km Tiered rates based on total distance
βš–οΈ Weight Pricing 8,000 IRR/100g Applied to packages over 500g
β›½ Fuel Rate 200 IRR/km Fuel compensation for transporters

Special Handling Multipliers

Package Type Multiplier Example
🟒 Standard 1.0x Electronics, clothing, books
πŸ”Έ Fragile 1.25x Glassware, ceramics, art
🧊 Perishable 1.35x Food, medicine, flowers
⚠️ Both 1.5x Fresh desserts, medical samples

Geographic Factors

Major city advantages and rural area adjustments ensure fair pricing across all regions:

City Type Multiplier Description
Major City Origin 0.9x 10% discount
Major City Destination 1.2x 20% premium
Small Cities 1.15x 15% premium

Route Deviation Costs

  • Distance Deviation: 2,000 IRR per extra kilometer
  • Time Deviation: 1,500 IRR per 10 minutes

5. πŸ—ΊοΈ Trip Lifecycle Management

Complete workflow from trip start to completion:

  1. Trip Start: Transporter declares trip beginning
  2. Package Pickup: Confirmation of package collection
  3. Status Updates: Real-time location and status updates
  4. Package Delivery: Delivery confirmation with codes
  5. Trip Completion: Final trip closure and settlements

6. πŸ“ Tracking System

  • Automatic Events: Trip start, pickup, delivery completion
  • Manual Updates: Transporter location and status updates
  • GPS Integration: Location-based city and route detection

7. ⬆️ File Upload System

Secure file management using AWS S3:

Upload Categories

  • Transporter Documents:

    • Profile pictures
    • National ID cards
    • Driver licenses
    • Vehicle photos
    • Vehicle registration documents
  • Package Photos: Sender package documentation

8. πŸ’³ Financial Management System

Wallet Management

  • Balance Tracking: Real-time balance updates
  • Escrow System: Payment security during delivery
  • Transaction History: Detailed financial records

Payment Flow

  1. Package Creation: Price calculation and display
  2. Payment Processing: Escrow during delivery
  3. Delivery Confirmation: Automatic fund release
  4. Settlement: Instant wallet updates

Revenue Model

Package Price = Base Calculation + Special Handling + Geographic Factors + Deviation Costs Revenue Distribution: β”œβ”€β”€ Platform Commission (30%) β”œβ”€β”€ Transporter Share (70%) └── Deviation Fees (100% to Transporter) 

9. 🧭 Geographic Integration

Advanced geographic features using Neshan Maps API:

Core Functions

  • Distance/Time Calculation: Route analysis for pricing
  • Intermediate Cities: Waypoint discovery for better matching
  • Coordinate Management: GPS-based location handling
  • Reverse Geocoding: Address extraction from coordinates
  • Static Maps: Route visualization
  • Navigation: Real-time routing for transporters

Geographic Matching

  • Corridor System: Route deviation tolerance (configurable width)
  • GeoJSON Integration: Standard geographic data format
  • Turf.js Library: Advanced geospatial calculations

10. πŸ“Š Dashboard

Our dashboard provides real-time insights and statistics tailored for each user role:

πŸ“ˆ Dashboard Statistics

🚚 Transporter Metrics
Metric Description
πŸš› Completed Trips Successfully finished journeys
⏳ Pending Requests Trip requests awaiting response
πŸ“¦ Not Delivered Packages Packages awaiting delivery
πŸ’° Total Escrowed Amount Funds held in escrow for active deliveries
πŸ“¦ Sender Metrics
Metric Description
πŸ“₯ Not Picked Up Packages Packages awaiting collection
🚚 In Transit Packages Packages currently being delivered
βœ… Delivered Packages Successfully completed deliveries
πŸ’΅ Total Unpaid Amount Outstanding payment amounts

πŸ‘€ Dashboard Profile

  • Personal Details: Full name and profile picture
  • Transporter Info: Experience, rate and bio
  • Financial Status: Wallet balance

11. πŸ”” Notification System

Our notification system keeps users informed about critical events and updates:

System Event Notifications

  • Welcome
  • Package Created
  • Trip Created
  • Trip Request Created, Canceled, Accepted and Rejected
  • New Transporter Note
  • Trip Started and Delayed
  • Package Picked Up and Delivered

πŸ“‚ Folder structure

HamBaar Architecture

πŸš€ Quick Start Guide

πŸ“‹ Prerequisites

Ensure you have the following installed:

Requirement Version Installation
Node.js 22.14+ Download
Docker Latest Download
PostgreSQL 15+ Download
Redis 7+ Download

βš™οΈ Environment Configuration

Create a .env.development or .env.production file with the following configuration:

[Set envs at ./.docker/.env if you use Docker to run project.]

Click to expand Environment Variables
# πŸ—„οΈ Database Configuration DATABASE_URL=postgresql://postgres:postgres@hambaar.postgres:5432/hambaar-db # πŸ”΄ Redis Configuration REDIS_PASSWORD=redis REDIS_URL=redis://:${REDIS_PASSWORD}@hambaar.redis:6379 OTP_REDIS_URL=redis://:${REDIS_PASSWORD}@hambaar.redis:6379/1 SESSION_REDIS_URL=redis://:${REDIS_PASSWORD}@hambaar.redis:6379/2 # πŸ” Security Secrets SESSION_SECRET=your-session-secret-here COOKIE_SECRET=your-cookie-secret-here JWT_ACCESS_SECRET_KEY=your-jwt-access-secret JWT_TEMP_SECRET_KEY=your-jwt-temp-secret JWT_PROGRESS_SECRET_KEY=your-jwt-progress-secret # ☁️ AWS S3 Configuration AWS_ENDPOINT=your-s3-endpoint AWS_ACCESS_KEY=your-access-key AWS_SECRET_KEY=your-secret-key AWS_BUCKET_NAME=your-bucket-name # 🌐 External API Keys MAP_API_KEY=your-neshan-api-key MAP_API_URL=https://api.neshan.org/v1 SMS_API_KEY=your-sms-api-key # βš™οΈ Optional Configuration (With default values) PORT=3000 COOKIE_MAX_AGE=1296000000 # 15 days CORRIDOR_WIDTH=10 # kilometers # Otp Envs OTP_EXPIRATION_TIME=120000 # 2 minutes MAX_SEND_ATTEMPTS=5 MAX_CHECK_ATTEMPTS=10 SEND_WINDOW=30 * 60 * 1000 # in milliseconds BASE_BLOCK_TIME=20 * 60 * 1000 # in milliseconds ## Pricing envs PRICING_BASE_PRICE=50000 PRICING_FUEL_RATE=200 PRICING_WEIGHT_BASE_RATE=8000 PRICING_PLATFORM_COMMISSION=0.3 PRICING_DRIVER_SHARE=0.7 ### Special Handling Multipliers PRICING_FRAGILE_MULTIPLIER=1.25 PRICING_PERISHABLE_MULTIPLIER=1.35 PRICING_BOTH_FRAGILE_PERISHABLE=1.5 ### City Premium Factors PRICING_MAJOR_CITY_ORIGIN=0.9 PRICING_MAJOR_CITY_DESTINATION=1.2 PRICING_BOTH_MAJOR_CITIES=1.0 PRICING_SMALL_CITY_FACTOR=1.15 ### Route Deviation Costs PRICING_DEVIATION_RATE=2000 PRICING_TIME_DEVIATION_RATE=1500 ### Distance Tier Rates (IRR per km) PRICING_TIER_1_RATE=1200 PRICING_TIER_2_RATE=1000 PRICING_TIER_3_RATE=850 PRICING_TIER_4_RATE=750 PRICING_TIER_5_RATE=650 ### Major Cities (comma-separated) PRICING_MAJOR_CITIES=ΨͺΩ‡Ψ±Ψ§Ω†,اءفهان,Ω…Ψ΄Ω‡Ψ―,شیراز,Ψͺبریز,Ψ§Ω‡ΩˆΨ§Ψ²

Running the Application

🐳 Run Project using Docker

Option 1: Using Make (Recommended)
make prod
Option 2: Using Docker Compose Directly
docker compose -f ./docker-compose.yml -p hambaar-app \ --profile frontend --profile backend up -d --build

πŸ’Ύ Database Setup

# Run database migrations npm run prisma:push # Seed initial data (admin user, cities, vehicle models) npm run seed

🌐 Access the Application


πŸ“š API Documentation

Our comprehensive API documentation is available through Swagger UI at /docs when the application is running.


πŸ§ͺ Testing & CI/CD

Testing Framework

  • Automated test suites for core functionality
  • Integration tests for external API interactions
  • Unit tests for business logic components

GitHub Workflow

The project includes a complete CI/CD pipeline:

  1. Code Push: Triggers automated workflow
  2. Test Execution: Runs comprehensive test suite
  3. Build Process: Creates Docker images on test success
  4. Registry Push: Pushes images to Docker Hub
  5. Deployment: Automatic deployment to Liara Cloud
graph LR A[Code Push] --> B[Automated Tests] B --> C{Tests Pass?} C -->|βœ… Yes| D[Build Docker Images] C -->|❌ No| E[Some Tests Are Failed] D --> F[Push to Registry] F --> G[Deploy to Staging] G --> H[Production Deployment] style A fill:#3498db style B fill:#f39c12 style D fill:#27ae60 style G fill:#e74c3c style H fill:#8e44ad 
Loading

🀝 Contributing

We welcome contributions to HamBaar! Please follow our guidelines:

πŸ“ Development Workflow

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ“„ License

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


🌟 Star this repository if you found it helpful!

Built with ❀️ by the HamBaar Team

Revolutionizing package delivery, one match at a time.

About

A modern, scalable package delivery platform that matches package senders with transporters, built with Node.js, NestJS, PostgreSQL, and Redis.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages