# 🌍 SAFFIS (ሳፊስ) — Next-Generation Multi-Modal Mobility & Commerce SuperApp
> **Master System Architecture, Engineering Specification & Mobile/Web Strategy**
> **(Telegram Multi-Bots • Web Operations Portal • Smart Bidding Engine • Android Studio Native Apps • Public WebApp)**

---

## 📌 1. Executive Summary & Vision

**Saffis (ሳፊስ)** is an integrated digital ecosystem engineered to formalize, streamline, and scale urban transit (Bajaj/TukTuk, Electric Vehicles, Motorcycles, Taxis), on-demand merchant deliveries (food, groceries, clothing boutiques, spare parts, pharmacies), and inter-city bus transit across Ethiopian regional cities (Dessie, Kombolcha, Hawassa, Adama, Addis Ababa) and nationwide.

```mermaid
graph TD
    subgraph CHANNELS ["Access Channels"]
        TG["🤖 5 Specialized Telegram Bots<br/>(20M+ Ethiopian Users, Zero Install)"]
        WEB["💻 Web Operations Portal & Public WebApp<br/>(Telemetry, Bot CMS & mudai.com.et)"]
        APP["📱 Native Android & iOS Apps<br/>(Android Studio / Flutter / Vector Maps)"]
    end

    subgraph CORE ["Core Saffis Backend Engine"]
        API["⚡ Central REST & WebSocket API Server<br/>Node.js Express + Socket.IO"]
        BID["🧠 Smart Multi-Driver Bidding Engine<br/>Composite Scoring & Trade-Off Badges"]
        COMM["💰 Dynamic Commission Engine<br/>Fixed (1 ETB) vs Percentage (3-5%)"]
        GEO["🗺️ PostGIS Geodesic Spatial Engine<br/>Landmark Auto-Learning & Proximity Dispatch"]
        LEDGER["💳 Atomic FinTech Ledger Engine<br/>Wallets, Bounties & P2P Transfers"]
        CMS["🛠️ Dynamic Bot CMS Engine<br/>Multi-Language Menus & Grid Layouts"]
    end

    subgraph DATA ["Data & Infrastructure"]
        DB[("🗄️ PostgreSQL 15 + PostGIS<br/>bajaj_db (Isolated Private VLAN)")]
    end

    TG --> API
    WEB --> API
    APP --> API
    API --> BID
    API --> COMM
    API --> GEO
    API --> LEDGER
    API --> CMS
    BID --> DB
    COMM --> DB
    GEO --> DB
    LEDGER --> DB
    CMS --> DB
```

### Core Value Pillars:
1. **Multi-Channel Omnipresence:** Access via **5 Telegram Bots** (zero friction, immediate adoption), **Web Portal / MiniApps**, and high-performance **Android Studio native apps**.
2. **Smart Multi-Driver Bidding & Trade-Offs:** Intelligent composite ranking that balances fare, proximity, driver ratings, and EV electric priority.
3. **Flexible Multi-Tier Commission:** Fixed commission (**1.00 ETB**) for short roadside town bajaj trips vs. percentage commission (**3% – 5%**) for negotiated long-distance, out-of-town, and intercity routes.
4. **Strict Multi-Language Separation:** Clean separation between **Amharic (🇪🇹 አማርኛ)** and **English (🇬🇧 English)** with dedicated database columns, ready for **Afaan Oromoo (🌳 Oromiffa)**, **Tigrinya**, and **Somali**.
5. **Cashless & Hybrid Financial Settlement:** Instant Telebirr QR scan-to-pay, CBE Birr deep-linking, physical cash-in via terminal agents, and internal closed-loop prepaid wallets.
6. **National Fayda ID Compliance:** Verified driver and merchant KYC aligned with Ethiopia's National ID framework.
7. **Green Mobility & Micro-Logistics:** Dedicated algorithms prioritizing **Electric Vehicles (EVs)** and zero-emission bicycle couriers.

---

## 🧠 2. Smart Multi-Driver Bidding & Composite Trade-Off Engine

When a passenger requests a ride with an offered fare, the system alerts the nearest candidate drivers simultaneously. When multiple drivers submit offers, the engine handles complex real-world trade-offs:

```mermaid
graph TD
    OFFER["🚶 Passenger Ride Offer (e.g. 80 ETB)"] --> DISPATCH["📍 PostGIS Spatial Dispatch (Top 3 Nearest Online Drivers)"]
    DISPATCH --> BIDS["🚖 Candidate Drivers Submit Bids"]
    
    subgraph SCENARIOS ["Real-World Scenarios"]
        S1["Scenario 1: Identical Prices<br/>(All 3 offer 120 ETB)"]
        S2["Scenario 2: Price vs Distance Trade-off<br/>(100 ETB @ 1.2km vs 120 ETB @ 300m)"]
        S3["Scenario 3: Close Distance (50m delta)<br/>(105 ETB vs 115 ETB vs 125 ETB)"]
    end
    
    BIDS --> SCENARIOS
    SCENARIOS --> SCORE["🧮 Multi-Factor Composite Scoring Formula<br/>Score = (Wp*Sp) + (Wd*Sd) + (Wr*Sr) + (Wev*Sev)"]
    SCORE --> BADGES["🏷️ Smart Badges Assignment<br/>• 💰 Best Price (Lowest Fare)<br/>• ⚡ Fastest Arrival (Closest ETA)<br/>• 🌱 Eco EV (Electric Bajaj)<br/>• ⭐ Top Rated (Highest Score)"]
    BADGES --> CARD["📱 Interactive Multi-Offer Comparison Card<br/>Presented to Passenger in Telegram"]
```

### 2.1 Multi-Factor Scoring Formula
$$\text{Composite Score} = (W_{\text{price}} \times S_{\text{price}}) + (W_{\text{distance}} \times S_{\text{distance}}) + (W_{\text{rating}} \times S_{\text{rating}}) + (W_{\text{ev}} \times S_{\text{ev}})$$

* **Price Score ($S_{\text{price}}$):** $1.0 - \frac{\text{Fare} - P_{\min}}{P_{\max} - P_{\min}}$ *(Cheapest offer = 1.0)*
* **Distance Score ($S_{\text{distance}}$):** $1.0 - \frac{\text{Dist} - D_{\min}}{\max(D_{\max} - D_{\min}, 100)}$ *(Closest driver = 1.0)*
* **Rating Score ($S_{\text{rating}}$):** $\frac{\text{Rating} - 1.0}{4.0}$ *(1.0–5.0 scaled to 0.0–1.0)*
* **EV Eco Bonus ($S_{\text{ev}}$):** $1.0$ for Electric Bajajs, $0.0$ for Petrol.

### 2.2 Scenario Resolutions:
* **Identical Fares (Scenario 1):** Tie-breakers sort by proximity (closest ETA), driver rating, and EV eco-bonus. The closest driver is badged with `⚡ ፈጣን መድረሻ (Fastest Arrival)`.
* **Price vs. Proximity Trade-Off (Scenario 2):** The passenger receives a badged comparison board displaying both the `💰 ምርጥ ዋጋ (100 ETB)` and `⚡ ፈጣን መድረሻ (120 ETB, 300m)` options with direct 1-tap accept buttons.
* **Close Distance (Scenario 3):** When distance difference is negligible (< 100m), lower price wins decisively.
* **Strict 3-Round Bargaining Limit:** Both passenger and driver are bounded by a maximum of 3 counter-offer rounds to prevent negotiation deadlocks.
* **Automated Next-Driver Cascade:** If a driver declines or fails to agree, the system excludes that driver and cascades the request to the next nearest batch.

---

## 💰 3. Configurable Multi-Tier Commission Engine

Saffis implements a dynamic, database-driven commission engine (`commission_rules` table) that can be adjusted in real time from the Web Admin Portal without service restarts:

| Rule Key | Service Category | Calculation Model | Default Rate | Threshold / Limits | Use Case |
| :--- | :--- | :--- | :--- | :--- | :--- |
| `bajaj_short_fixed` | Intra-City Ride | **Fixed (ETB)** | **1.00 ETB** | $\le 50.00$ ETB | Standard roadside Bajaj pick-up and drop-off in town. |
| `bajaj_negotiated` | Private / Long Ride | **Percentage (%)** | **5.00 %** | $> 50.00$ ETB (Min 1 ETB, Max 20 ETB) | Off-road, charter, or negotiated private Bajaj trips (100–200 ETB). |
| `taxi_ride` | Taxi / Sedan | **Percentage (%)** | **7.00 %** | Min 5 ETB, Max 50 ETB | Standard automotive sedan and private cab hailing. |
| `delivery_order` | Merchant Delivery | **Fixed (ETB)** | **1.00 ETB** | Min 1 ETB, Max 15 ETB | On-demand food, boutique goods, and grocery deliveries. |
| `intercity_bus` | Inter-City Transit | **Fixed (ETB)** | **25.00 ETB** | 25 ETB Platform / 25 ETB Agent Bounty | Highway bus tickets (Dessie ⇄ Addis Ababa, Dessie ⇄ Kombolcha). |

* **Atomic Ledger Deduction:** Upon trip completion, commission is deducted atomically from the driver's prepaid wallet balance, preventing overdrafts and logging a permanent financial transaction (`wallet_transactions`).

---

## 🤖 4. The 5 Specialized Telegram Bots

| Bot Role | Telegram Handle | Core Responsibilities |
| :--- | :--- | :--- |
| 🚖 **Driver Bot** | `@saffis_driver_bot` | Proximity dispatch alerts, quick (+20/+50) & custom bidding, live GPS tracking, permanent payment QR code, in-trip state machine (`📍 መድረሴን አሳውቅ`, `▶️ ጉዞ ጀምር`, `🏁 ጉዞውን ጨርስ`), wallet balance. |
| 🚶 **Passenger Bot** | `@saffis_passengers_bot` | Intra-city Bajaj hailing, multi-offer comparison card, 3-round counter-bargaining, landmark auto-detection, store shopping cart, intercity booking, driver calling. |
| 🏪 **Store Bot** | `@saffis_store_bot` | Merchant catalog management, Excel/CSV bulk import, order acceptance, prioritized 3km micro-courier dispatch, 4-digit PIN verification handshake. |
| 🏢 **Agent Bot** | `@saffis_agent_bot` | Bus station ticketing (`SAT...` codes), passenger boarding QR scanner, physical cash-in wallet top-ups, bounty earnings (`25 ETB/ticket`). |
| 🛡️ **Admin Bot** | `@saffis_admin_bot` | Real-time platform metrics, 1-click driver KYC approvals (+50 ETB bonus crediting), wallet deposits, emergency broadcast alerts. |

---

## 🌐 5. Web Presence & Domain Configuration (`mudai.com.et` & `safi.et`)

### 5.1 Do We Need a Public-Facing User Interface Website?
**YES.** Here is why and how it fits into the ecosystem:

1. **Public Brand & Landing Website (`mudai.com.et` / `safi.et`):**
   * **Why it is essential:** Customers, drivers, merchants, and corporate partners need a trusted public webpage explaining what Saffis is, safety features, pricing transparency, and 1-tap buttons to open Telegram bots.
   * **Key Components:**
     * 📲 **"Launch on Telegram"** 1-click buttons for all 5 bots.
     * 📱 **Download Android APK** button for drivers and passengers.
     * 🚖 **Driver Online Registration Portal** (allows new drivers to sign up on the web).
     * 🏪 **Merchant Sign-up & Catalog Portal** (for boutiques, cafes, juice bars).
     * 🚌 **Intercity Bus Schedule & Ticket Checker**.

2. **Telegram WebApps (Mini Apps) inside Telegram:**
   * Embedded interactive HTML/JS web views that open directly inside Telegram chat without switching apps (e.g., interactive pin-drop map, visual food/clothing store catalog, seat selection).

3. **Web Admin & Operations Portal (`/var/www/bajaj-api/public`):**
   * Real-time telemetry, driver KYC validation, bot CMS layout customization, dynamic dispatch scoring sliders, and commission management.

### 5.2 Domain Setup Blueprint:
* **Interim / Staging Domain:** `mudai.com.et` (active while Ethiotelecom domain activation is underway).
* **Production Domains:** `safi.et` / `safi.com.et` / `saffis.et`.
* **Nginx Multi-Domain Routing:**
  ```nginx
  server {
      listen 80;
      server_name mudai.com.et safi.et safi.com.et saffis.et www.mudai.com.et;

      location / {
          proxy_pass http://127.0.0.1:3000;
          proxy_http_version 1.1;
          proxy_set_header Upgrade $http_upgrade;
          proxy_set_header Connection 'upgrade';
          proxy_set_header Host $host;
          proxy_cache_bypass $http_upgrade;
      }
  }
  ```

---

## 📁 6. Local Asset & Screenshot Workflow (`C:\Users\sule\Desktop\saffis`)

For organizing screenshots, UI mockups, brand assets, and spreadsheets from your laptop:

* **Local Windows Path:** `C:\Users\sule\Desktop\saffis\`
* **Recommended Folder Structure on your Laptop:**
  ```text
  C:\Users\sule\Desktop\saffis\
  ├── screenshots/         # UI progress screenshots & bug captures
  ├── merchant_catalogs/   # Excel (.xlsx) & CSV product lists for stores
  ├── branding/            # Logos, banners, icons (SVG/PNG)
  └── documents/           # Route agreements, KYC templates, licenses
  ```
* **How to Share with the Assistant:**
  * You can drag and drop any image, screenshot, or spreadsheet directly into the chat window.
  * The assistant can parse uploaded spreadsheets, ingest merchant catalogs, and analyze screenshots directly.

---

## 📱 7. Mobile App Architecture (Android Studio & Flutter)

```mermaid
graph TD
    subgraph ANDROID_STUDIO ["Android Studio (Koala / Ladybug)"]
        FLUTTER["Flutter Cross-Platform Engine<br/>(Android APK/AAB + iOS IPA)"]
        FG["Foreground Location Service<br/>(3s GPS Broadcast)"]
        ALERT["System Alert Window<br/>(Floating Ride Popup)"]
        MAP["MapLibre / Google Maps 60fps Vector Map"]
    end

    FLUTTER --> FG
    FLUTTER --> ALERT
    FLUTTER --> MAP
    FG -->|WebSocket / REST| API["⚡ Central Saffis Server<br/>(http://192.168.8.102:3000 / mudai.com.et)"]
```

### Driver-First Android Optimizations:
1. **Persistent Foreground Service:** Ensures GPS location updates every 3 seconds even when the phone screen is off or Google Maps navigation is on top.
2. **Floating Ride Alert Overlay (`SYSTEM_ALERT_WINDOW`):** Pops up interactive ride offers over any running app with audio chime and 15-second timer.
3. **WakeLock & Offline SQLite Queue:** Prevents CPU deep sleep during active trips and caches offline breadcrumbs when traversing mountain passes with spotty connectivity.

---

## 🧪 8. System Verification & Test Coverage

The platform is backed by **14 automated end-to-end test suites (100% Pass Rate)**:

| Test Suite | Focus Area | Status |
| :--- | :--- | :--- |
| `test-smart-bid-ranking.js` | Multi-driver trade-offs, tie-breakers, composite scoring, and badging | ✅ **PASSED (30/30)** |
| `test-live-bot-interactions.js` | Live Telegram API connectivity, 3-round bidding, cascade routing, KYC | ✅ **PASSED (37/37)** |
| `test-master-e2e-simulation.js` | Complete 5-bot ecosystem, PostGIS spatial queries, and REST APIs | ✅ **PASSED (59/59)** |
| `test-driver-bidding-flow.js` | Driver counter-bidding, accept/decline callbacks, and in-trip progression | ✅ **PASSED** |
| `test-micro-deliveries.js` | 3km courier radius, bicycle priority, and 4-digit delivery PIN handshake | ✅ **PASSED** |
| `test-wallet-fintech.js` | Atomic P2P transfers, agent cash-ins, float deduction, and ledger audit | ✅ **PASSED** |
| `test-hyperlocal-poi.js` | Hyperlocal Amharic POI fuzzy search and intra-city guardrails | ✅ **PASSED** |
| `test-qr-payments.js` | Dynamic and permanent Telebirr QR code payment generation | ✅ **PASSED** |
| `test-store-delivery.js` | Merchant store product catalog and checkout order pipeline | ✅ **PASSED** |
| `test-promotions-referrals.js`| Multi-tier viral referral tracking and bonus payouts | ✅ **PASSED** |
| `test-proximity-dispatch.js` | PostGIS spatial distance calculations and candidate ring expansion | ✅ **PASSED** |
| `test-lifecycle.js` | Trip state machine integrity and driver offline protection guards | ✅ **PASSED** |
| `test-frontend-drivers-table.js`| Driver table taxonomy rendering and category/class filtering | ✅ **PASSED** |
| `test-db.js` | Database connection, PostGIS extensions, and schema constraints | ✅ **PASSED** |

---

## 🏁 9. Current Operational Status

* **PM2 Multi-Bot Daemon:** `multi-bot` is online and handling all 5 bot instances concurrently.
* **Web Admin Portal & CMS:** Live at `http://192.168.8.102:3000`.
* **Database:** PostgreSQL 15 + PostGIS active on `192.168.8.101/bajaj_db` with migrations applied up to `021_dispatch_and_scoring_settings.sql`.
