swiftops-backend / README.md
kamau1's picture
Enhance stats endpoints with time-based breakdowns for richer dashboard analytics
3a13ba4
metadata
title: SwiftOps API
colorFrom: blue
colorTo: green
sdk: docker
pinned: true
license: mit

SwiftOps Backend

A Next-Generation Field Service Management (FSM) Platform built to orchestrate complex field operations, manage distributed workforces, and automate financial reconciliation.

About The Project

SwiftOps is a comprehensive ERP solution designed specifically for field service providers (ISPs, Utility Companies, Maintenance Contractors). Unlike simple ticketing systems, SwiftOps manages the entire lifecycle of a field operation: from the initial Sales Order, through Inventory Allocation and Ticket Dispatch, to final Invoicing and Payroll Calculation.

It solves critical challenges in the gig-economy/contractor ecosystem, such as verifying work done, calculating complex split-commissions, and tracking assets in real-time.

System Architecture

The project is built on a modern, high-performance stack designed for scalability and real-time responsiveness.

Tech Stack

  • Framework: FastAPI (Python 3.11+) - Async-first web framework.
  • Database: PostgreSQL 15+ with SQLAlchemy 2.0 (ORM).
  • Caching & Sessions: Redis 7+ (Optimistic locking & session storage).
  • Task Queue: Celery (for background processing).
  • Integrations:
    • Storage: Cloudinary (Media), Supabase (Auth/Storage).
    • Communication: Resend (Email), WASender (WhatsApp), AfricasTalking (SMS).
    • Geo: Google Maps Platform (Routing & Geocoding).
    • Monitoring: Sentry.

Key Features & Modules

The SwiftOps platform is designed to handle the full lifecycle of field operations, from user onboarding to final reporting.

1. User & Profile Management

The Foundation. Before any work begins, the system establishes a secure, hierarchical environment for all stakeholders.

  • Permission Hierarchy:
    • Platform Admin: Full unrestricted access.
    • Client/Contractor Admin: Manages their specific organization's users.
    • Managers (PM/Dispatcher): Operational control within their org.
  • Organization Transfers: Safe protocols for moving users between Contractors or Clients, ensuring data cleanup.
  • Profile Management: Granular control over user status (Active, Suspended, Invited) and roles.

2. Intelligent Sales Order Management

The Input. Work enters the system through high-volume sales channels, requiring intelligent ingestion.

  • Smart Region Assignment: Automatically assigns new orders to the correct operational hub based on fuzzy text matching of the address or GPS proximity to the nearest warehouse.
  • Customer Deduplication: Uses fuzzy logic algorithms to prevent duplicate customer profiles by analyzing:
    • Phone number variations (e.g., +254 vs 07...).
    • Name typos (Levenshtein distance).
    • Email username matches.
  • Bulk Import Engine: Robust CSV parser capable of ingesting thousands of orders while validating data integrity and flagging errors row-by-row.

3. Advanced Journey Tracking & Fraud Detection

The Execution. As agents deploy to fulfill orders, the system ensures compliance and safety.

  • Algorithmic Fraud Detection: Automatically flags "impossible" journeys based on:
    • Excessive Speed: Detection of GPS spoofing or impossible travel times.
    • Route Detours: Analysis of detour ratios (Actual Distance vs Straight Line) to detect personal errands during work hours.
    • Time Anomalies: Flagging suspiciously short or long durations for standard tasks.
  • Public Customer Tracking: Customers can verify their phone number via OTP to see their assigned technician's real-time location on a map.
  • Breadcrumb History: Stores granular GPS points for full historical playback of any assignment.

4. Real-Time Timesheets

The Record. While work is being performed, the system automatically builds an immutable record of time.

  • Event-Driven Aggregation: Timesheets are automatically constructed from business events (assignment_created, ticket_completed, expense_approved).
  • Immutability: Past timesheets are locked to prevent historical revisionism.
  • Optimistic Locking: Prevents data race conditions when multiple events (e.g., a ticket completion and an expense submission) happen simultaneously.
  • Graceful Degradation: Timesheet failures do not block core operational workflows.

5. Money-Safe Expense Management

The Cost. Expenses incurred during the job are handled with banking-grade integrity.

  • Transactional & Atomic: All financial operations are ACID complaint.
  • Automatic Location Verification: The system checks if the agent was actually at the customer's site when the expense was incurred.
  • Approval Workflow: Submitted -> Pending Review -> Approved/Rejected -> Paid.
  • Policy Enforcement: Prevents modification of approved expenses and ensures expenses fall within valid ticket dates.

6. Enterprise Invoicing & Public Viewing

The Output. Once work is complete, validated, and costed, the system generates auditable invoices.

  • Copy-on-Write Versioning: Every edit to a sent invoice creates a new version (v1, v2, etc.) while preserving the audit trail of the original.
  • Public Viewing Portals: Secure, token-based links allow clients to view invoices without logging in.
  • Data Enrichment: Invoices are linked with ticket details, proof-of-work images, and completion data.
  • Audit Logging: Every action (Create, View, Update, Pay) is cryptographically logged.

7. Advanced Reporting & BI

The Feedback Loop. Finally, the system aggregates all data to provide high-level business intelligence.

  • SLA Compliance: Tracks violation margins (in hours) against due dates for both Customer and Infrastructure tickets.
  • User Performance: Aggregates efficiency metrics (Completion Rate, On-Time %, Avg Resolution Time).
  • Financial Summaries: Unified ledger view combining Project Revenue and Field Expenses.
  • Inventory Usage: Tracks asset consumption across projects and regions.
  • Export Engine: All reports can be streamed as CSVs with UTF-8 BOM support for Excel compatibility.

Getting Started

Prerequisites

  • Python 3.11+
  • PostgreSQL
  • Redis
  • Git

Installation

  1. Clone the repository

    git clone https://huggingface.co/spaces/kamau1/swiftops-backend
    cd swiftops-backend
    
  2. Create virtual environment

    python -m venv venv
    # Windows
    .\venv\Scripts\activate
    # Linux/Mac
    source venv/bin/activate
    
  3. Install dependencies

    $env:PYTHONPATH="D:\atomio\swiftops-backend\src"  
    pip install -r requirements.txt
    
  4. Environment Configuration Copy the example environment file and fill in your secrets (DB credentials, API keys).

    cp .env.example .env
    
  5. Run Migrations Initialize the database schema.

    alembic upgrade head
    
  6. Start the Server

    # Run from the repository root
    uvicorn src.app.main:app --reload
    

    The API will be available at http://localhost:8000. Interactive Docs: http://localhost:8000/api/docs.

Project Structure

src/app/
β”œβ”€β”€ api/            # Route handlers (v1 endpoints)
β”œβ”€β”€ core/           # Config, Logging, Security, Middleware
β”œβ”€β”€ models/         # SQLAlchemy Database Models (The Source of Truth)
β”œβ”€β”€ schemas/        # Pydantic Objects for Validation & Serialization
β”œβ”€β”€ services/       # Complex Business Logic & Service Layers
β”‚   β”œβ”€β”€ sales_order_service.py        # Intelligent order ingestion
β”‚   β”œβ”€β”€ journey_service.py            # Fraud detection & analytics
β”‚   β”œβ”€β”€ tracking_service.py           # Public customer tracking
β”‚   β”œβ”€β”€ contractor_invoice_service.py # Enterprise invoicing logic
β”‚   β”œβ”€β”€ report_service.py             # BI & CSV generation
β”‚   β”œβ”€β”€ ticket_expense_service.py     # Financial transaction logic
β”‚   └── timesheet_realtime_service.py # Event-driven tracking
β”œβ”€β”€ repositories/   # DB Interaction Layer
β”œβ”€β”€ tasks/          # Celery Background Tasks
└── integrations/   # Wrappers for External APIs (Maps, MPesa, etc)

Contributors

Lewis Kimaru Sole Designer & Engineer

Special Credits

Joel Kamiru For helping pick the name "SwiftOps"

License

Proprietary - All rights reserved.