Skip to content

Campus Operations Architecture ​


1. Executive Summary & Domain Model ​

Debelu's foundational market differentiator is its hyperlocal university campus commerce ecosystem. Unlike traditional nationwide e-commerce, intra-campus commerce operates under unique real-world constraints:

  • Hostel & Dormitory Logistics: Traditional street-address couriers cannot enter university residential halls, departmental complexes, or restricted student hostels.
  • Curfew & Academic Schedules: Campus operating hours fluctuate with academic semesters, examinations, weekend gate restrictions, and institutional curfews.
  • Localized Price Sensitivity & Micro-Fulfillment: Delivery fees must remain fractional (e.g., ₦200 – ₦500), fulfilled through student couriers and centralized campus pickup stations.
  • Immutable Operational Snapshots: Orders placed within a campus must remain tied to that campus context forever, even if the vendor subsequently relocates.
mermaid
graph TD
    subgraph Client Surfaces
        B[Buyer Storefront]
        V[Vendor Portal]
        CO[Campus Operator Console]
    end

    subgraph API & Domain Services
        COS[CampusOperationsService]
        CORD[CampusOrderService]
        AUTH[Supabase Auth / RBAC]
    end

    subgraph Data & Storage Layer
        DB[(Supabase Postgres)]
        CAMP[public.campuses]
        ORD[public.orders.operation_campus]
        CASE[public.campus_order_cases]
        AUDIT[public.audit_logs]
    end

    B -->|Browse by Campus / Place Order| CORD
    CO -->|Manage Hub / Zones / Hours| COS
    CO -->|Triage & Resolve Order Cases| CORD

    COS -->|Verify Revision & Write Snapshot| CAMP
    COS -->|Append Immutable Receipt| AUDIT
    CORD -->|Immutable Campus Order Snapshot| ORD
    CORD -->|Versioned Case Transitions| CASE

    AUTH -->|Enforce campus_scope text[]| DB

2. System Architecture & Service Contracts ​

Campus operations are governed by two specialized backend domain services:

2.1 CampusOperationsService (debelu-backend/src/services/CampusOperationsService.ts) ​

Controls platform configuration for physical campus hubs, delivery zones, fee schedules, and operating hours.

  • Optimistic Concurrency Control: Every change command mandates the current revision (integer). A version mismatch or concurrent edit throws PostgreSQL error 40001 (Serialization Failure), mapped to 409 Conflict.
  • Discriminated Command Model: Mutates campus configuration strictly via three discriminated actions:
    • hub: Updates GPS coordinates (locationLat, locationLng), activation status (isActive), and geofenceRadiusKm (up to 100 km).
    • zones: Array of named sub-campus zones (e.g., "New Hall", "Faculty of Science", "Jaja Hall") with custom delivery fees (fee $\in [0, 1000000]$ NGN) and transit estimates (estimated_minutes $\in [1, 1440]$). Zone IDs must be unique.
    • hours: Strict 7-day schedule (monday through sunday). Each day defines open (HH:MM), close (HH:MM), and optional closed boolean, strictly validated to ensure open < close.
  • Audit Receipt Verification: Every mutation generates an immutable cryptographic receipt containing before_data, after_data, actor_id, action, revision, and mandatory reason (1–2000 chars). The service verifies that receipt.revision === before.revision + 1 and after_data === updated_campus before committing.

2.2 CampusOrderService (debelu-backend/src/services/CampusOrderService.ts) ​

Governs the operational lifecycle, investigation, and dispute triage of orders within a campus boundary.

  • Scoped Order Queues: Operators only see orders whose operation_campus matches their administrative campus_scope.
  • Case Governance Lifecycle: Manages order incidents (open, claim, release, note, escalate, resolve, reopen).
  • Operator Assignment Exclusivity: Once claimed, an order case can only be resolved by the assigned operator. Other operators attempting resolution are blocked with 42501 (Forbidden).

3. Data Models & Database Constraints ​

3.1 Entity Relationship Diagram ​

mermaid
erDiagram
    campuses ||--o{ orders : "routes to"
    campuses ||--o{ campus_operation_receipts : "audits configuration"
    orders ||--o| campus_order_cases : "monitored by"
    campus_order_cases ||--o{ campus_order_events : "appends history"
    admin_roles ||--o{ profiles : "scopes operator"

    campuses {
        text id PK
        text name
        text short_name
        boolean is_active
        numeric location_lat
        numeric location_lng
        numeric geofence_radius_km
        jsonb delivery_zones
        jsonb operating_hours
        bigint operation_revision
        timestamptz updated_at
    }

    orders {
        uuid id PK
        uuid user_id FK
        uuid vendor_id FK
        numeric total
        text operation_campus
        text status
        jsonb items
        timestamptz created_at
    }

    campus_order_cases {
        uuid id PK
        uuid order_id FK
        text status
        uuid assigned_to FK
        bigint revision
        text reason
        text outcome
        uuid created_by FK
        timestamptz created_at
        timestamptz updated_at
        timestamptz resolved_at
    }

    campus_order_events {
        uuid id PK
        uuid case_id FK
        uuid actor_id FK
        text action
        text note
        bigint revision
        timestamptz created_at
    }

    admin_roles {
        uuid id PK
        text slug
        jsonb permissions
        text_array campus_scope
    }

3.2 Immutability Invariant: orders.operation_campus ​

To prevent fraud and preserve financial integrity, the campus routing assigned at order placement is strictly immutable:

sql
-- Database constraint preventing alteration of operation_campus post-creation
ALTER TABLE public.orders 
  ADD CONSTRAINT check_immutable_campus 
  CHECK (operation_campus IS NOT NULL);
  • Vendor Relocation Safety: If Vendor $V$ moves from UNILAG to University of Ibadan while Order $O$ is in transit, $O$'s operation_campus remains 'unilag'. Any SQL UPDATE targeting operation_campus throws error 23514 (Check Violation).

4. Case Management State Machine ​

Campus order cases govern exceptions (delayed pickup, damaged goods at hub, curfew containment).

mermaid
stateDiagram-v2
    [*] --> Unopened : Order Exception Flagged
    Unopened --> Open : decide_order_case('open')
    Open --> InProgress : decide_order_case('claim') [Assigned to Operator]
    
    state InProgress {
        [*] --> ActiveWork
        ActiveWork --> ActiveWork : decide_order_case('note')
        ActiveWork --> Escalated : decide_order_case('escalate')
        Escalated --> ActiveWork : decide_order_case('claim')
    }

    InProgress --> Open : decide_order_case('release') [Unassigns Operator]
    InProgress --> Resolved : decide_order_case('resolve') [Assigned Operator Only]
    
    Resolved --> Open : decide_order_case('reopen')
    Resolved --> [*]

State Transition Rules & Revision Locks ​

  1. Atomic Revisions: Every transition increments revision by $+1$. If two operators attempt concurrent actions, the second receives 40001 (Serialization Failure).
  2. Assignment Enforcement: Action resolve requires actor_id === case.assigned_to. Third-party intervention raises 42501.
  3. Atomic Audit Coupling: If insertion into public.audit_logs fails during a case decision, a PostgreSQL transaction trigger rolls back both the case transition and the event append simultaneously.

5. Security & Multi-Tenant Scoping (Row-Level Security) ​

Debelu implements strict tenant isolation across university campuses:

5.1 Role-Based Scope Enforcement (campus_scope) ​

Campus managers and operators have scoped roles defined in public.admin_roles:

sql
CREATE TABLE public.admin_roles (
    id uuid PRIMARY KEY,
    slug text NOT NULL,
    permissions jsonb DEFAULT '{}',
    campus_scope text[] DEFAULT '{}' -- e.g. ARRAY['unilag']
);

5.2 Fail-Closed Query Evaluation ​

  • Explicit Match: Operator with campus_scope = '{unilag}' querying list_campus_orders only receives records where operation_campus = 'unilag'.
  • Zero-Leak Filtering: Attempting to query an order from another campus (p_campus = 'ui') returns an empty dataset (total: 0) rather than revealing order existence.
  • Corrupted / Unknown Scope Fail-Closed: If an operator's role contains an unrecognized campus alias (e.g. '{unilag, unknown_campus}'), queries fail immediately with 42501 (Unauthorized) rather than falling back to permissive defaults.

6. Operating Hours, Geofencing & Validation Rules ​

CampusOperationsService enforces strict Zod validation schemas before evaluating database RPCs:

typescript
// Strict time format HH:MM
const time = z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/);

// Day validation ensuring chronological consistency
const day = z.object({
  open: time,
  close: time,
  closed: z.boolean().optional()
}).strict().refine(d => d.closed === true || d.open < d.close, {
  message: "Opening time must precede closing time"
});

// Delivery zone boundary definitions
const zones = z.array(z.object({
  id: z.string().trim().min(1).max(100),
  name: z.string().trim().min(1).max(100),
  fee: z.number().finite().min(0).max(1000000),
  estimated_minutes: z.number().int().min(1).max(1440)
}).strict()).max(100).refine(z => new Set(z.map(v => v.id)).size === z.length, {
  message: "Zone IDs must be unique within a campus"
});

7. Edge Cases & Resilience Protocols ​

Incident ScenarioSystem BehaviorRecovery Protocol
Academic Strike / ASUU ShutdownCampus administrator triggers hub patch setting isActive: false.Storefront disables checkout for vendors located on that campus. In-transit orders route to designated off-campus border pickup points.
Hostel Curfew Lockoutoperating_hours triggers automated daily closure.Storefront displays "Closed for Tonight" banner. Orders placed post-curfew queue automatically for next morning's delivery batch.
Unclaimed Package at Hub (>72h)Background worker triggers order exception.Case automatically created with status unopened and note "Unclaimed package timer expired". Operator issues return-to-vendor (RTV) voucher.
Concurrent Operator InterventionTwo operators claim order simultaneously.Operator A succeeds (revision: 1). Operator B receives 409 Conflict ("Order work could not be verified. Refresh before deciding").

Released under Proprietary Enterprise License.