Skip to content
omrajput14Public

About

frontend side of vetra

Resources

Stars

2 stars

Watchers

0 watching

Forks

Latest commit

 

History

80 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

VETRA Header

A mission-critical, offline-first clinical platform and spatial epidemiological surveillance engine for rural livestock ecosystems and field veterinary medicine.

Flutter Dart Spring Boot PostgreSQL PostGIS Riverpod GoRouter

Build Status Coverage Architecture Security Sync Engine License

Executive Summary • Core Capabilities • System Architecture • Spatial Surveillance • Offline Sync • Codebase Topology • API Contracts • Engineering Team • Quick Start • Testing



Executive Summary

Field veterinary healthcare in rural agricultural ecosystems operates under severe infrastructure constraints:

  • Zero-Connectivity Zones: Over 65% of rural farming regions lack dependable cellular networks, leading to data dropouts and fragmented paper logs.
  • Delayed Outbreak Interception: Highly contagious epizootic diseases (e.g., Foot-and-Mouth Disease, Lumpy Skin Disease, Brucellosis) often spread unchecked due to batch-based, non-geolocated reporting.
  • Unverified Identity & Health History: Absence of verifiable digital identity enables livestock identity fraud and invalidates vaccination audit trails.
  • Triage Inefficiency: Rural veterinarians lack clinical prioritization engines, slowing response times during acute emergency cases.

Vetra (Veterinary Operating System / VetOS) solves these challenges through an enterprise-grade mobile application pairing a Flutter 3 Clean Architecture client with Spring Boot microservices, PostGIS spatial clustering, cryptographic Ed25519 animal passports, and an offline-first store-and-forward sync pipeline.


Core Capabilities

Farmer Portal Veterinarian Operating System (VetOS)
  • Livestock Inventory: Register cattle, buffalo, sheep, goats, and swine with breed, age, visual identifiers, and RFID tag IDs.
  • Cryptographic QR Passport: Present tamper-proof digital passports for field inspection and health history verification.
  • Triage-Aware Scheduling: Request on-farm or clinical visits with urgency tags, symptom notes, and booking state tracking.
  • Medical Record Timeline: Access full diagnostic histories, active digital prescriptions, withdrawal alerts, and booster dates.
  • Urgency Triage Queue: Filter consultation requests by clinical severity, location proximity, and herd status.
  • Field EVMR Workbench: Record vitals, diagnostic notes, procedural treatments, and issue cryptographically signed prescriptions.
  • Offline Field Queue: Queue clinical entries securely in local storage; sync automatically when connectivity resumes.
  • Outbreak Reporting: Flag infectious cases instantly to trigger automated PostGIS spatial containment radii.

System Architecture

Vetra enforces strict Clean Architecture conventions with unidirectional data flow and dependency inversion: Presentation Layer -> Domain Layer <- Data Layer.

1. End-to-End System Topology

flowchart TB
    subgraph Client ["Vetra Mobile Client (Flutter 3.x / Dart 3.x)"]
        direction TB
        subgraph PresentationLayer ["Presentation Layer"]
            UI["UI Screens & Widgets\n(Design System Tokens)"]
            Router["GoRouter 14.x\n(Declarative RBAC Guards)"]
            State["Riverpod 2.x\n(StateNotifier & AsyncNotifier)"]
        end

        subgraph DomainLayer ["Domain Layer (Business Core)"]
            UseCases["Use Cases & Interactors\n(Appointment, EVMR, Passport)"]
            Entities["Domain Entities & Value Objects\n(Animal, Diagnosis, Prescription)"]
        end

        subgraph DataLayer ["Data & Infrastructure Layer"]
            RepoImpl["Repository Implementations"]
            LocalCache["Encrypted Local Storage\n(SQLite + AES-256-GCM)"]
            SyncQueue["Store & Forward Mutation Queue\n(Idempotent Sync Engine)"]
            NetworkClient["Dio HTTP Client\n(Auth & Retry Interceptors)"]
        end

        UI --> Router
        UI --> State
        State --> UseCases
        UseCases --> Entities
        UseCases --> RepoImpl
        RepoImpl --> LocalCache
        RepoImpl --> SyncQueue
        RepoImpl --> NetworkClient
    end

    subgraph GatewayLayer ["API Gateway & Microservices Platform (Spring Boot)"]
        Gateway["API Gateway / Reverse Proxy\n(TLS Termination, Rate Limiting)"]
        AuthSvc["Identity & IAM Service\n(JWT Token Engine & RBAC)"]
        AnimalSvc["Animal Passport Service\n(Digital Identity & QR Verification)"]
        ApptSvc["Appointment & Triage Service\n(State Machine Engine)"]
        EVMRSvc["EVMR Ledger Service\n(Clinical & Prescription Store)"]
        SpatialSvc["Spatial Surveillance Engine\n(PostGIS Geo-Clustering)"]
        AISvc["Diagnostic Assist Service\n(Computer Vision Lesion Triage)"]
    end

    subgraph PersistenceLayer ["Persistence & Spatial Infrastructure"]
        Postgres[(PostgreSQL 16 + PostGIS 3.4\nSpatial Tables & Geo-Indices)]
        Redis[(Redis Cluster\nHot Cache & Session Storage)]
        ObjectStorage[(S3 Compatible Storage\nDiagnostic Media & Records)]
    end

    NetworkClient <==>|HTTPS / REST v1| Gateway
    Gateway --> AuthSvc
    Gateway --> AnimalSvc
    Gateway --> ApptSvc
    Gateway --> EVMRSvc
    Gateway --> SpatialSvc
    Gateway --> AISvc

    AuthSvc --> Redis
    AnimalSvc --> Postgres
    ApptSvc --> Postgres
    EVMRSvc --> Postgres
    SpatialSvc --> Postgres
    AISvc --> ObjectStorage
    AISvc --> Postgres
Loading

2. EVMR Clinical Consultation & Immutable Ledger Sequence

sequenceDiagram
    autonumber
    actor Farmer as Livestock Farmer
    actor Vet as Field Veterinarian
    participant Client as Vetra Mobile Client
    participant Queue as Mutation Sync Queue
    participant Gateway as API Gateway
    participant Ledger as EVMR Ledger Service
    participant Spatial as PostGIS Spatial Engine
    participant DB as PostgreSQL Database

    Farmer->>Client: Submit Visit Request (Animal Tag, Symptoms, Urgency: HIGH)
    Client->>Gateway: POST /api/v1/appointments (Status: PENDING)
    Gateway->>DB: Persist Appointment
    Gateway-->>Client: 201 Created (Appointment ID #APT-8492)
    
    Vet->>Client: Inspect Triage Queue
    Vet->>Client: Accept Appointment Request
    Client->>Gateway: PUT /api/v1/appointments/APT-8492/accept
    Gateway-->>Client: 200 OK (Status: CONFIRMED)

    Note over Vet, Client: On-Site Clinical Diagnostic Examination (Zero-Connectivity)

    Vet->>Client: Record Clinical Vitals, Suspected Diagnosis, Drug Regimen
    Client->>Queue: Enqueue EVMR Payload (Encrypted Local Storage)
    Client-->>Vet: UI Confirmation: Staged for Background Sync

    Note over Vet, Client: Cellular Network Connection Restored

    Queue->>Gateway: POST /api/v1/appointments/APT-8492/medical-record (Idempotency Key)
    Gateway->>Ledger: Commit Clinical Record Entry
    Ledger->>DB: INSERT INTO medical_records & UPDATE animal_status
    Ledger->>Spatial: Flag Infectious Case (Latitude, Longitude)
    Spatial->>DB: Recompute Spatial Buffer (ST_Buffer 5km & 15km)
    Ledger-->>Queue: 201 Created (EVMR ID #MED-9102)
    Queue-->>Client: Reconcile Local Cache & Mark Synced
    
    Gateway-->>Farmer: Real-time Notification: Passport Updated & Rx Available
Loading

3. Cryptographic Animal Passport Lifecycle

flowchart LR
    subgraph Registration ["1. Animal Registration"]
        A[Enter Livestock Attributes:\nTag ID, Species, Breed, DOB] --> B[Generate Canonical Payload\n& UUID v4 Identity]
        B --> C[Compute SHA-256 Hash\nof Canonical Metadata]
        C --> D[Sign with Authority Key\nEd25519 Cryptographic Signature]
    end

    subgraph Packaging ["2. QR Passport Encoding"]
        D --> E[Serialize Compact Binary / CBOR Payload\n{TagID, Hash, Signature, Expiry}]
        E --> F[Render QR Code\nError Correction Level H]
    end

    subgraph Verification ["3. Offline Field Inspection"]
        F --> G[Field Inspector / Veterinarian\nScans QR Code]
        G --> H[Extract Payload & Signature]
        H --> I{Verify Against Cached\nAuthority Public Key?}
        I -->|Valid| J[Authentic Identity Confirmed\nDisplay Full Medical Ledger]
        I -->|Invalid| K[Tamper Alert Triggered\nFlag Identity for Audit]
    end
Loading

4. Role-Based Access Control (RBAC) & Router Guard Engine

stateDiagram-v2
    [*] --> Unauthenticated: Application Startup
    
    Unauthenticated --> Authenticating: Provide Credentials (OTP / Password)
    Authenticating --> Unauthenticated: Authentication Failed
    
    state Authenticating {
        [*] --> ValidateToken
        ValidateToken --> ExtractClaims: Parse JWT Payload
        ExtractClaims --> DetermineRole: Read role claim
    }

    Authenticating --> RouteGuard: Valid Claims & Active Session

    state RouteGuard {
        [*] --> RoleEvaluation
        RoleEvaluation --> FarmerStack: role == 'FARMER'
        RoleEvaluation --> VetStack: role == 'VETERINARIAN'
        RoleEvaluation --> AdminStack: role == 'ADMIN'
    }

    state FarmerStack {
        FarmerHome: Farmer Dashboard
        HerdRegistry: Herd & Livestock Register
        BookVisit: Request Consultation
        FarmerPassports: Animal Passport Cards
        ProximityMap: Regional Outbreak Radar
    }

    state VetStack {
        VetHome: Veterinarian Workbench
        TriagePipeline: Priority Triage Queue
        EVMRForm: Clinical EVMR & Rx Writer
        QRScanner: Field Passport Scanner
        IncidentReport: Epizootic Incident Logger
    }

    FarmerStack --> Unauthenticated: Session Expiry / Sign Out
    VetStack --> Unauthenticated: Session Expiry / Sign Out
Loading

Spatial Surveillance Engine

Vetra integrates spatial computing directly into clinical workflows. When a veterinarian logs an infectious diagnosis, the PostGIS engine calculates transmission risk buffers and executes proximity queries to alert nearby livestock holdings.

flowchart TD
    Incident[Veterinarian Submits Contagious Case\nGeoPoint: Lat 18.5204°, Lon 73.8567°] --> Ingestion[API Gateway /api/v1/disease-reports]
    
    subgraph PostGIS_Pipeline ["PostgreSQL / PostGIS Spatial Computing Layer"]
        Ingestion --> SpatialPoint["Construct Geometry Point\nST_SetSRID(ST_MakePoint(lon, lat), 4326)"]
        SpatialPoint --> BufferGen["Generate Spatial Containment Polygons:\n• Quarantine Zone: ST_Buffer(geom::geography, 3000) [3 km]\n• Surveillance Zone: ST_Buffer(geom::geography, 10000) [10 km]"]
        BufferGen --> Clustering["Spatial Clustering Analysis:\nST_ClusterDBSCAN(geom, eps := 0.05, minpoints := 3)\nCompute Outbreak Vector & Epicenter Trajectory"]
        Clustering --> ProximityQuery["Identify At-Risk Herds:\nSELECT DISTINCT farmer_id FROM farm_holdings\nWHERE ST_DWithin(farm_holdings.geom, incident.geom, 10000)"]
    end

    ProximityQuery --> NotificationBroker[Push Notification & SMS Dispatch Broker]
    NotificationBroker --> FarmerDevice[Farmer Alert: Quarantine Advisory & Vaccine Alert]
    NotificationBroker --> DepartmentDashboard[State Animal Husbandry Surveillance Dashboard]
Loading

Offline-First Synchronization Pipeline

flowchart LR
    subgraph ClientAction ["Client Interaction"]
        A[Create Medical Record / Update Livestock] --> B[Store & Forward Interceptor]
    end

    subgraph LocalStorage ["Local Encrypted Storage"]
        B --> C[(SQLite Database\nAES-256-GCM Encrypted)]
        B --> D[(Local Mutation Queue\nOrdered by Timestamp)]
    end

    subgraph SyncWorker ["Background Synchronization Worker"]
        E{Connectivity Status\nOnline?}
        D -.-> E
        E -->|No| F[Remain in Queue]
        E -->|Yes| G[Read FIFO Queue & Pack Batch Payload]
        G --> H[POST /api/v1/sync/mutations\nHeaders: Idempotency-Key]
    end

    subgraph ServerReconciliation ["Backend Services"]
        H --> I[API Gateway & Reconciler]
        I --> J{Version Check / Conflict?}
        J -->|No Conflict| K[Commit to PostgreSQL Ledger]
        J -->|Conflict| L[Reconcile via Vector Clock / CRDT Rule]
        K --> M[Return HTTP 200 / ACK]
        L --> M
    end

    M --> N[Purge Synced Mutations from Local Queue]
Loading

Clean Architecture & Directory Topology

vetra/
├── .github/                      # CI/CD Workflows (Lint, Test, Docker Build)
├── assets/                       # Vector icons and visual identity tokens
├── docs/                         # Architecture, Product, and API Documentation
│   ├── architecture/             # Software Architecture Document (SAD) & ADRs
│   ├── engineering/              # Code standards, security baseline, git guidelines
│   ├── guides/                   # Developer onboarding, testing strategy
│   └── product/                  # Product Requirements Document (PRD)
├── lib/
│   ├── app.dart                  # Root MaterialApp with theme & routing injection
│   ├── main.dart                 # Application entrypoint & dependency bootstrap
│   ├── core/                     # Shared Foundation & Core Utilities
│   │   ├── config/               # AppConfig, ApiConfig, environment profiles
│   │   ├── constants/            # Global routes, keys, API endpoints
│   │   ├── design_system/        # Design tokens, typography, component library
│   │   ├── errors/               # Failure & Exception hierarchy
│   │   ├── models/               # Common response wrappers (ApiResponse<T>)
│   │   ├── network/              # Dio client, AuthInterceptor, RetryPolicy
│   │   ├── router/               # GoRouter declarative router & RBAC guards
│   │   ├── storage/              # Encrypted storage & local SQLite handlers
│   │   └── utils/                # Date helpers, cryptographic utilities, QR helpers
│   └── features/                 # Domain Feature Modules (Clean Architecture)
│       ├── ai/                   # AI Diagnostic Assistant & lesion assessment
│       ├── animal/               # Digital passport, tag registry, QR scanning
│       ├── appointment/          # Triage scheduler & consultation state machine
│       ├── auth/                 # Authentication, session lifecycle, token refresh
│       ├── dashboard/            # Role-based dashboard analytics
│       ├── disease/              # Spatial outbreak logging & surveillance alerts
│       ├── farmer/               # Herd inventory & farmer portal workflows
│       ├── maps/                 # Mapbox / OpenStreetMap PostGIS visualizer
│       ├── medical_record/       # EVMR ledger, diagnostics, digital prescriptions
│       └── veterinarian/         # Field triage queue & clinical workbench
└── test/                         # Comprehensive Multi-Tier Test Suites
    ├── unit/                     # Business logic, state notifiers, use case tests
    ├── widget/                   # UI widget isolation & responsive layout tests
    ├── contract/                 # Backend JSON Schema & DTO contract verifications
    └── integration/              # End-to-end user workflows & offline sync simulation

Capability Matrix

System Feature Farmer Field Veterinarian Para-Veterinary Assistant Health Regulator / Admin
Animal Registration & Profiling Create / Update View / Verify View Only Audit Access
Cryptographic QR Passport Generate & Present Offline Scan & Verify Offline Scan & Verify Global Revocation
Consultation Scheduling Request & Cancel Triage & Accept Assist / View Metric Analytics
EVMR Clinical Records View Read-Only Create, Sign & Update Record Vitals Only Compliance Audit
Digital Prescriptions (Rx) View Active Regimens Issue & Authorize Dispense Log Controlled Drug Audit
Spatial Outbreak Surveillance Proximity Alerts Log Outbreak Case Log Outbreak Case Quarantine Management
Store-and-Forward Sync Client Queue Field Queue Field Queue Cluster Reconciliation

API Contracts & Data Models

REST Endpoints Specification

Method URI Route Authorization Scope Description
POST /api/v1/auth/token Public Authenticate mobile credentials and issue JWT pair
POST /api/v1/animals SCOPE_FARMER Register livestock and generate digital passport
GET /api/v1/animals/{tagId}/passport SCOPE_AUTHENTICATED Retrieve encrypted passport payload and verification signature
POST /api/v1/appointments SCOPE_FARMER Create veterinary consultation request
PUT /api/v1/appointments/{id}/triage SCOPE_VETERINARIAN Update clinical urgency classification
POST /api/v1/appointments/{id}/evmr SCOPE_VETERINARIAN Commit signed EVMR clinical record and prescription
POST /api/v1/surveillance/outbreak SCOPE_VETERINARIAN Report suspected epizootic case and recalculate risk radius
POST /api/v1/sync/mutations SCOPE_AUTHENTICATED Reconcile batch mutations from offline storage queue

Sample Ingestion Contract (POST /api/v1/appointments/{id}/evmr)

{
  "appointmentId": "APT-84920",
  "animalTagId": "IN-MH-1029-8472",
  "veterinarianId": "VET-0294",
  "clinicalExamination": {
    "temperatureCelsius": 39.8,
    "heartRateBpm": 78,
    "respiratoryRateBpm": 26,
    "mucousMembrane": "PALE_ICTERIC",
    "rumenMotilityScore": 2
  },
  "diagnoses": [
    {
      "code": "ICD-VET-A04",
      "name": "Bovine Babesiosis",
      "type": "CONFIRMED",
      "isContagious": true
    }
  ],
  "treatments": [
    {
      "drugName": "Diminazene Aceturate",
      "dosageMgPerKg": 3.5,
      "route": "DEEP_INTRAMUSCULAR",
      "withdrawalPeriodDays": 21
    }
  ],
  "geoCoordinate": {
    "latitude": 18.52043,
    "longitude": 73.85674,
    "altitudeMeters": 560.2
  },
  "timestamp": "2026-08-30T02:45:00Z",
  "digitalSignature": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
}

Security & Data Integrity

  1. Short-Lived JWT Tokens: Ephemeral 15-minute access tokens with encrypted refresh token rotation.
  2. Deterministic PII Sanitization: SanitizedLogInterceptor scrubs identity tokens, GPS micro-offsets, and user contact details prior to logging.
  3. Encrypted Storage at Rest: Local SQLite database and cached files are protected with AES-256-GCM encryption keys held in the platform Keystore / Keychain.
  4. Asymmetric Verification: Clinical records and passport QR codes are signed using Ed25519 keypairs, allowing offline verification without internet access.

Engineering Team

Name Role Core Focus & Architectural Domain
Om Rajput Chief Systems Architect & Lead Engineer Flutter Clean Architecture, System Core, PostGIS Spatial Engine, Offline Sync Pipeline
Mrunmai Joshi Product & Technical Project Manager Domain Architecture, Product Strategy, Sprint Execution, Clinical Workflow Compliance
Khushi Cloud Developer & Communication Lead Cloud Infrastructure, API Gateway Integration, Stakeholder Comms & Technical Narrative
Soham Fullstack Developer Spring Boot Microservices, REST Contract Engineering, Persistence & Database Pipelines
Prachi UI/UX Designer & Presentation Lead Design System Architecture, User Journey Mapping, Visual Assets & Pitch Decks
Dhiraj Research & QA Testing Lead Veterinary Domain Research, Multi-Tier Test Automation, Field Validation & Quality Gates

Quick Start & Local Orchestration

Prerequisites

  • Flutter SDK: ^3.22.0 (Stable)
  • Dart SDK: ^3.4.0
  • Java: JDK 17+ or JDK 21 LTS
  • Docker Engine & Docker Compose: v24+

1. Clone & Fetch Dependencies

git clone https://github.com/omrajput14/vetra.git
cd vetra
flutter pub get

2. Code Generation

Generate immutable entities, Riverpod providers, and JSON serialization files:

dart run build_runner build --delete-conflicting-outputs

3. Spin Up Local Backend Services (Optional)

docker compose -f docker-compose.local.yml up -d

4. Configure Environment Endpoints

Update target host configuration in lib/core/config/api_config.dart:

class ApiConfig {
  static const String stagingBaseUrl = 'https://api.vetra.dpdns.org/api/v1';
  static const String localBaseUrl = 'http://10.0.2.2:8080/api/v1';

  static String get baseUrl => kReleaseMode ? stagingBaseUrl : localBaseUrl;
}

5. Run Application

flutter run

Testing & Verification

Vetra enforces strict quality gates with a 90%+ test coverage baseline:

              ┌───────────────────────────┐
              │    E2E Integration (5%)   │ -> Staging Gateway & Database Verification
              ├───────────────────────────┤
              │   Contract Tests (15%)    │ -> JSON Schema & DTO Payload Validation
              ├───────────────────────────┤
              │    Widget Tests (30%)     │ -> UI Component Rendering & State Bounds
              ├───────────────────────────┤
              │     Unit Tests (50%)      │ -> Domain Logic, UseCases, Crypto & Notifiers
              └───────────────────────────┘

Run Test Suites

# Execute static analysis
flutter analyze --fatal-infos

# Run unit and widget test suites
flutter test --reporter expanded

# Run tests with coverage profiling
flutter test --coverage
genhtml coverage/lcov.info -o coverage/html

# Run contract tests
flutter test test/contract/

Documentation Index

Specification Document Purpose Direct Link
Doc 01: Concept Architecture Strategic Vision, Rural Domain Analysis & Field Ergonomics PDF Architecture Whitepaper
Doc 02: API & Backend Services Microservices Design, PostGIS Query Plans & API Contracts PDF Architecture Whitepaper
Doc 03: AI Architecture Lesion Recognition Models, Computer Vision Triage Pipeline PDF Architecture Whitepaper
Doc 04: Cloud Infrastructure AWS ECS, EKS, RDS PostGIS, Terraform Blueprints PDF Architecture Whitepaper
Doc 05: Mobile Engineering Flutter Clean Architecture, Riverpod State, Offline Engine PDF Architecture Whitepaper
Doc 06: Quality & Reliability Reliability Benchmarks, Chaos Engineering & Test Strategy PDF Architecture Whitepaper

License

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

Developed for enterprise livestock health management, field veterinary resilience, and epidemiological surveillance.

About

frontend side of vetra

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages