Skip to content

BSS Rider Workflow - Complete Customer Journey

Overview

This document defines the end-to-end rider experience across all BSS workflows, from discovering services to completing transactions. Unlike the attendant workflow (which focuses on operational station tasks), this document describes the rider's perspective through multiple touchpoints: mobile app interactions, location-based services, payment flows, and service delivery.

Primary Focus: Rider's experience, decision-making, and multi-workflow journey

Attendant Context: Included where attendants facilitate service delivery (e.g., scanning batteries, processing swaps). For detailed attendant operational procedures, see bss-attendant-workflow-enhanced.md.

Multi-Workflow Scope: This document covers the rider's interactions across: - Service Discovery (W1): Finding available services via mobile app - Service Intent (W2): Signaling intent to visit a swap station - Location Authentication (W3): Checking in at the station - Service Execution (W4): Battery swap process - Transaction Finalization (W5): Payment, quota updates, receipts


Visual Workflow Diagrams

Rider-Only Activity Diagram (Swap Service Focus)

Rider Activity Diagram

Shows the battery swap experience from the rider's perspective - their journey from arriving at the station to departing with a charged battery. This is a simplified view focusing on rider touchpoints without attendant operational details.

Complete System Sequence Diagram (All Workflows)

BSS Rider Workflow

Complete sequence diagram showing the end-to-end rider journey from service discovery to transaction finalization, including all five workflow phases (W1-W5) and interactions between UXI, BSS Agent, ARM, MQTT, Fleet Systems, and Billing.

Color Coordination: All diagrams follow the DIRAC Color System: - Wheat = External actors (Riders) - Light Green = Internal actors (Attendants, Staff) - Light Cyan = Core DIRAC systems (ABS, ARM, BSS Agent) - Gold = External systems (Odoo ERP) - Light Gray = Physical assets/infrastructure


Document Organization

This workflow follows the established intent vs implementation separation principle, defining WHAT needs to happen and WHY (business requirements) while allowing agent functions to determine HOW to implement the technical patterns.

Core Principles

Customer-Centric Journey

  • Rider experience prioritizes convenience and speed throughout the entire service journey
  • Mobile app integration provides real-time asset discovery and service coordination
  • Location-based services minimize friction between service discovery and consumption
  • No Partial Service Rule: Service journey must not proceed if any validation fails or conditions are not fully met

Fleet Coordination Architecture

  • BSS Agent works with fleet IDs only; ARM microservice resolves to specific assets
  • MQTT-based communication enables real-time coordination between systems
  • Service intent signaling allows proactive preparation by service personnel
  • Echo patterns provide reliable confirmation of service completion

State Management Requirements

  • Customer-location binding establishes secure service sessions
  • Multi-asset state coordination ensures consistent battery and service tracking
  • Quota management integrates consumption with billing systems
  • Transaction atomicity ensures either complete success or complete rollback

Rider Service Journey

The rider experience follows a logical progression designed for maximum convenience and reliability:

  1. Service Discovery (W1) - Find available services and optimal locations based on rider's service bundle
  2. Service Intent (W2) - Notify service systems and personnel of customer intent and estimated arrival
  3. Location Authentication (W3) - Secure customer-location binding with proper authorization
  4. Service Execution (W4) - Coordinate asset allocation and service delivery through fleet systems
  5. Transaction Completion (W5) - Update service states, process billing, and manage quota consumption

W1: Service Discovery and Fleet Resolution

Purpose

Enable riders to discover available services and identify required fleet resources based on their service bundle configuration and location context.

Process Flow

Service Bundle Analysis → Fleet Type Mapping → Location Context Application → Fleet Dependency Resolution → ARM Integration Handoff

Critical Business Requirements

  • Service Bundle Analysis: Service requirements must be derived from rider's active service bundle
  • Fleet Type Resolution: Service requirements must be mapped to appropriate fleet categories for resource allocation
  • Location Context: Rider's current location must influence fleet selection and availability assessment
  • ARM Integration: Fleet IDs must be provided to ARM for specific asset resolution and location filtering
  • Dependency Mapping: Fleet dependencies must be identified (e.g., swap stations require battery fleets)

Implementation Requirements

  • Bundle to Fleet Mapping: Extract required fleet types from rider's service bundle configuration
  • Location-Aware Resolution: Consider rider location and search radius for relevant fleet identification
  • Fleet Dependency Chain: Identify and return complete dependency chain of required fleets
  • ARM Handoff: Provide fleet IDs to ARM microservice for specific asset resolution
  • Error Handling: Handle scenarios where no compatible fleets are available for rider's requirements

Agent Function Integration

Function: getRequiredAssetIds

Expected Signals: ASSET_IDS_RESOLVED, LOCATION_CONTEXT_APPLIED, DEPENDENCIES_MAPPED, PARTIAL_RESOLUTION, NO_COMPATIBLE_ASSETS

Key Integration Points: - Extract fleet requirements from service bundle configuration - Apply rider location and search radius for geographical relevance - Return fleet IDs for ARM microservice resolution - Handle fleet dependency chains (swap stations → battery fleets → support services) - Support graceful degradation when some fleet types are unavailable


W2: Service Intent Communication

Purpose

Enable customers to communicate service intent to systems and personnel, providing advance notice and preparation time for optimal service delivery.

Process Flow

Customer Context Extraction → Location Validation → Service Requirements Analysis → Intent Signal Composition → System Notification → Confirmation Handling

Critical Business Requirements

  • Customer Authorization: Customer must be authorized to request service at target location
  • Service Compatibility: Target location must be capable of serving customer's service requirements
  • Intent Clarity: Service intent must include sufficient detail for proactive service preparation
  • System Coordination: Multiple systems (personnel, asset management, billing) must be notified
  • Delivery Confirmation: Intent signal delivery must be confirmed for reliable service coordination

Implementation Requirements

  • Customer Context: Extract customer identity, service plan, and service requirements
  • Location Validation: Verify target location can serve customer's specific service bundle
  • Signal Composition: Create comprehensive intent signal with customer and service context
  • Multi-System Notification: Notify service personnel, asset management, and billing systems
  • Delivery Tracking: Monitor signal delivery and handle retry scenarios for failed notifications

Agent Function Integration

Function: emitServiceIntentSignal

Expected Signals: INTENT_SIGNAL_EMITTED, LOCATION_VALIDATED, SERVICE_REQUIREMENTS_RESOLVED, LOCATION_INCOMPATIBLE, CUSTOMER_INELIGIBLE, SIGNAL_RETRY_REQUIRED

Key Integration Points: - Validate customer authorization for target location service - Extract service requirements from customer's service bundle configuration - Compose intent signal with customer context, location details, and service requirements - Use existing GATT topic convention for system notifications - Implement delivery confirmation and retry logic for reliable communication


W3: Customer Location Authentication

Purpose

Establish secure customer-location binding with proper authorization to enable safe and authorized service delivery.

Process Flow

Customer Authentication → Location Verification → Service Authorization → Session Establishment → Security Validation → Context Preparation

Critical Business Requirements

  • Physical Presence Verification: Customer must be verified as physically present at the target location
  • Service Authorization: Customer must be authorized to receive service at this specific location
  • Session Security: Secure service session must be established for subsequent operations
  • Access Control: Customer's access level and service permissions must be validated
  • Location Capability Matching: Location must be verified as capable of serving customer's requirements

Implementation Requirements

  • Multi-Factor Authentication: Support QR code, NFC, manual verification, or biometric authentication methods
  • Location Context Binding: Attach customer's service account to specific location operational context
  • Session Management: Create secure, time-limited session for service operations
  • Authorization Matrix: Validate customer's service tier against location's service capabilities
  • Occupancy Management: Update location occupancy and service queue status

Agent Function Integration

Function: bindCustomerToLocation

Expected Signals: BINDING_ESTABLISHED, SESSION_SECURED, ACCESS_AUTHORIZED, BINDING_REJECTED, PARTIAL_BINDING, LOCATION_BUSY

Key Integration Points: - Implement multiple authentication methods (QR, NFC, manual, biometric) - Validate customer authorization using simplified validator array pattern - Establish secure session with appropriate timeout and encryption - Update both customer and location operational states atomically - Handle location capacity and queue management


W4: Service Execution Coordination

Purpose

Coordinate fleet allocation and service execution through ARM systems while maintaining proper system boundaries and service delivery confirmation.

Process Flow

Fleet Identification → Service Instruction Composition → ARM Coordination Request → Asset Allocation → Service Execution → Completion Confirmation

Critical Business Requirements

  • Fleet to Asset Resolution: BSS provides fleet IDs; ARM resolves to specific available assets
  • Service Instruction Clarity: Fleet must receive complete service context and requirements
  • ARM System Coordination: Proper handoff to ARM for asset-specific allocation and control
  • Echo Confirmation: Service completion must be confirmed through echo pattern
  • Session Continuity: Service execution must respect established customer-location session

Implementation Requirements

  • Fleet Context: Provide fleet ID with location and customer context for ARM resolution
  • Service Specification: Include battery requirements, service priority, and safety protocols
  • MQTT Communication: Use existing GATT topic conventions for fleet instruction
  • Echo Handling: Implement echo listener for service completion confirmation
  • Timeout Management: Handle scenarios where service execution exceeds expected timeframes

Agent Function Integration

Function: sendAssetAllocationSignal

Expected Signals: INSTRUCTION_SENT, FLEET_ALLOCATION_REQUESTED, ECHO_AWAITING, ECHO_RECEIVED, INSTRUCTION_FAILED, ECHO_TIMEOUT

Key Integration Points: - Compose fleet instruction with customer context and service requirements - Use emit/echo MQTT pattern for reliable fleet coordination - Delegate specific asset selection and allocation to ARM microservice - Handle echo responses and timeout scenarios with appropriate retry logic - Maintain service session state throughout execution process

Implementation Requirements

// Target function: sendAssetAllocationSignal
const sendAssetAllocationSignal = async (requestData: RequestData, planState: PlanState): Promise<PartialOutcome> => {
  const fleetId = requestData.target_fleet_id;
  const locationId = requestData.location_id;
  const sequenceType = requestData.service_sequence || 'battery_swap';
  const sessionToken = requestData.session_token;

  // Identify target fleet for service
  // Compose service instruction with customer context
  // Emit MQTT signal to instruct fleet
  // Set up echo listener for service completion
  // ARM resolves fleet to specific available assets

  return {
    signals: ['INSTRUCTION_SENT' | 'FLEET_ALLOCATION_REQUESTED' | 'ECHO_AWAITING' | 'ECHO_RECEIVED' | 'INSTRUCTION_FAILED' | 'ECHO_TIMEOUT'],
    metadata: {
      fleet_instruction: {
        mqtt_topic: `emit/abs/bss/fleet/${fleetId}/allocation_request`,
        fleet_id: fleetId,
        location_context: locationId,
        instruction_payload: {
          sequence_type: sequenceType,
          customer_context: {
            customer_id: planState.customer_id,
            service_plan_id: planState.id,
            session_token: sessionToken
          },
          service_instructions: {
            battery_requirements: 'extracted from service plan',
            service_priority: 'derived from customer tier',
            safety_protocols: ['standard protocols for this fleet']
          },
          arm_resolution_required: {
            resolve_to_specific_assets: true,
            location_filtering: 'apply_location_filter',
            asset_selection_criteria: 'availability_and_proximity'
          }
        }
      },
      arm_delegation: {
        fleet_to_asset_resolution: 'ARM will resolve fleet to specific available assets',
        location_based_selection: 'ARM will filter by location if provided',
        asset_coordination: 'ARM coordinates specific asset allocation and instruction'
      },
      echo_configuration: {
        expected_echo_topic: `echo/abs/bss/fleet/${fleetId}/allocation_completed`,
        timeout_seconds: 300,
        retry_policy: 'configuration for handling timeouts'
      }
    }
  };
};

W5: Service State Updates & Transaction Finalization

Workflow: "Update all service states and handle quota/billing"

Agent Function: updateServiceStatesAndBilling

W5.1: Multi-Asset State Updates

  1. Battery State Updates: Update both old and new battery current_asset assignments
  2. Service Count Updates: Increment swap counts and usage metrics
  3. Energy Increment Tracking: Record energy consumption/transfer amounts
  4. Location Inventory Updates: Update location's battery inventory status
  5. Customer Service History: Record service transaction in customer history

W5.2: Quota Management & Billing Logic

  1. Quota Consumption Calculation: Determine quotas consumed by this service
  2. Multi-Service Quota Check: Check quota status across all underlying services
  3. Quota Exceeded Detection: Identify if any service quotas are exceeded
  4. Invoice Generation Trigger: Create additional invoices for exceeded quotas
  5. Billing State Synchronization: Update billing states and payment cycles

W5.3: Transaction State Coordination

  1. Service Account Updates: Update all relevant service account states
  2. Payment Account Updates: Update payment account balances and transaction history
  3. FSM State Coordination: Update multiple FSM states involved in the transaction
  4. Cross-Service Impact: Handle impacts on related services in the bundle
  5. External System Sync: Sync updates with external billing/analytics systems

Service State Update Outcomes

  • ✅ ALL_STATES_UPDATED: All service states successfully updated
  • 🔋 BATTERY_STATES_SYNCED: Battery asset assignments updated
  • 📊 QUOTAS_UPDATED: Service quotas and usage counts updated
  • 💵 INVOICE_GENERATED: Additional invoice created for quota overages
  • ⚠️ PARTIAL_UPDATE_SUCCESS: Some updates succeeded, others failed
  • ❌ UPDATE_TRANSACTION_FAILED: Critical state update transaction failed
  • 🔄 RETRY_REQUIRED: Temporary failure, retry state updates needed

Implementation Requirements

// Target function: updateServiceStatesAndBilling
const updateServiceStatesAndBilling = async (requestData: RequestData, planState: PlanState): Promise<PartialOutcome> => {
  const serviceDetails = requestData.service_completion_details;
  const oldBatteryId = serviceDetails.old_battery_id;
  const newBatteryId = serviceDetails.new_battery_id;
  const energyTransferred = serviceDetails.energy_transferred;

  // Update battery current_asset assignments for both batteries
  // Increment service counts and usage metrics
  // Record energy consumption/transfer amounts
  // Check quota consumption across all underlying services
  // Generate additional invoices if quotas exceeded
  // Update all relevant service and payment account states

  return {
    signals: ['ALL_STATES_UPDATED' | 'BATTERY_STATES_SYNCED' | 'QUOTAS_UPDATED' | 'INVOICE_GENERATED' | 'PARTIAL_UPDATE_SUCCESS' | 'UPDATE_TRANSACTION_FAILED' | 'RETRY_REQUIRED'],
    metadata: {
      battery_updates: {
        old_battery: {
          battery_id: oldBatteryId,
          previous_current_asset: 'customer assignment',
          new_current_asset: 'location inventory',
          update_timestamp: 'ISO string'
        },
        new_battery: {
          battery_id: newBatteryId,
          previous_current_asset: 'location inventory',
          new_current_asset: planState.customer_id,
          update_timestamp: 'ISO string'
        }
      },
      service_metrics: {
        swap_count_increment: 1,
        energy_transferred: energyTransferred,
        service_duration: serviceDetails.service_duration,
        cumulative_swaps_today: 'updated count',
        total_energy_consumed: 'updated total'
      },
      quota_analysis: {
        quotas_checked: [
          {
            service_id: 'svc-battery-fleet-kenya-premium',
            quota_before: 'number',
            quota_consumed: 1,
            quota_after: 'number',
            quota_exceeded: 'boolean'
          },
          {
            service_id: 'svc-electricity-refuel-kenya',
            quota_before: 'number',
            quota_consumed: energyTransferred,
            quota_after: 'number',
            quota_exceeded: 'boolean'
          }
        ],
        total_services_exceeded: 'number',
        invoice_generation_required: 'boolean'
      },
      billing_updates: {
        invoices_created: [
          {
            invoice_id: 'generated if quota exceeded',
            service_id: 'service that exceeded quota',
            overage_amount: 'amount over quota',
            billing_rate: 'rate for overage billing',
            total_charge: 'calculated overage charge'
          }
        ],
        payment_account_updated: 'boolean',
        billing_cycle_updated: 'boolean'
      },
      state_synchronization: {
        service_account_updated: 'boolean',
        payment_account_updated: 'boolean',
        fsm_states_updated: ['service_cycle', 'payment_cycle'],
        external_systems_synced: ['billing_system', 'analytics_system'],
        transaction_id: 'unique transaction identifier'
      }
    },
    fsmInputs: [
      { cycle: 'service_cycle', input: 'SERVICE_TRANSACTION_COMPLETED' },
      { cycle: 'payment_cycle', input: 'QUOTA_CONSUMED' }
    ]
  };
};

Integration Notes

DIRAC Component Boundaries

The updated workflows respect proper DIRAC component separation:

// BSS Agent: Core service coordination only
interface BSSAgentWorkflows {
  // W1: Fleet dependency resolution (Fleet IDs only)
  getRequiredAssetIds(requestData: RequestData, planState: PlanState): Promise<PartialOutcome>;

  // W2: Service intent signaling via MQTT
  emitServiceIntentSignal(requestData: RequestData, planState: PlanState): Promise<PartialOutcome>;

  // W3: Customer-location binding
  bindCustomerToLocation(requestData: RequestData, planState: PlanState): Promise<PartialOutcome>;

  // W4: Fleet allocation instruction via MQTT
  sendAssetAllocationSignal(requestData: RequestData, planState: PlanState): Promise<PartialOutcome>;

  // W5: Service state updates and billing
  updateServiceStatesAndBilling(requestData: RequestData, planState: PlanState): Promise<PartialOutcome>;
}

// ARM: Asset resolution and location services
interface ARMServices {
  resolveFleetToAssets(fleetIds: string[], locationContext?: any): Promise<AssetData[]>;
  getLocationData(locationIds: string[]): Promise<LocationData[]>;
  providePaginatedAssetList(query: AssetQuery): Promise<PaginatedAssetResponse>;
  allocateSpecificAssets(fleetInstruction: FleetInstruction): Promise<AssetAllocation>;
}

// UXI: User interface and experience
interface UXIServices {
  displayAssetMap(assets: AssetData[]): void;
  displayAssetList(assets: AssetData[]): void;
  handleQRCodeScanning(): Promise<QRCodeData>;
  displayServiceProgress(progress: ServiceProgress): void;
}

MQTT Signal Integration

Following the established MQTT topic structure and emit/echo patterns:

// W2: Service Intent Signal
const intentTopic = `emit/abs/bss/service/${customerId}/intent_signal`;

// W4: Fleet Allocation Signal
const allocationTopic = `emit/abs/bss/fleet/${fleetId}/allocation_request`;
const echoTopic = `echo/abs/bss/fleet/${fleetId}/allocation_completed`;

// MQTT Listener Patterns
const subscriptionPatterns = [
  'emit/abs/bss/+/+/+',        // All ABS BSS emissions
  'echo/abs/bss/+/+/+',        // All ABS BSS echoes
  'emit/abs/bss/service/+/intent_signal',  // Service intents
  'echo/abs/bss/fleet/+/allocation_completed'  // Fleet completion echoes
];

Agent State Management

Following the Validator Array Pattern for state updates:

// State Update Validators
const StateUpdateValidators = [
  {
    name: 'battery_asset_update',
    condition: (updates) => updates.old_battery_id && updates.new_battery_id,
    action: (state, updates) => updateBatteryAssignments(state, updates),
    validation: (result) => result.both_batteries_updated
  },
  {
    name: 'quota_consumption_update',
    condition: (updates) => updates.service_metrics,
    action: (state, updates) => updateServiceQuotas(state, updates),
    validation: (result) => result.quotas_calculated
  },
  {
    name: 'billing_overage_check',
    condition: (updates) => updates.quota_analysis.total_services_exceeded > 0,
    action: (state, updates) => generateOverageInvoices(state, updates),
    validation: (result) => result.invoices_created
  }
];

Error Handling Pattern

Consistent error response structure for all workflows:

if (error) {
  return {
    signals: ['WORKFLOW_ERROR'],
    metadata: {
      error_type: 'mqtt_delivery_failed|state_update_failed|quota_calculation_error',
      error_details: 'detailed error information',
      recovery_actions: 'suggested recovery steps',
      retry_configuration: 'retry policy for this error type'
    }
  };
}


Implementation Priority

Phase 1: Core Service Coordination (Immediate)

  1. W3: bindCustomerToLocation - Essential for secure service access
  2. W1: getRequiredAssetIds - Required for ARM integration
  3. W5: updateServiceStatesAndBilling - Critical for transaction finalization

Phase 2: Signal-Based Communication (Near-term)

  1. W2: emitServiceIntentSignal - MQTT-based service intent notification
  2. W4: sendAssetAllocationSignal - Asset instruction and echo handling

Phase 3: Advanced Integration (Future)

  1. Enhanced quota management - Complex billing scenarios
  2. Multi-asset coordination - Coordinated service across multiple assets
  3. Real-time analytics - Advanced service metrics and optimization

External Component Dependencies

  1. ARM Microservice: Asset query and location data APIs
  2. UXI Mobile App: Asset display and QR code scanning
  3. MQTT Infrastructure: Signal delivery and echo handling
  4. Billing System: Invoice generation and quota management

Expected Signal Flow

📱 UXI App requests asset IDs ➡️ W1: BSS returns asset IDs ➡️ ARM provides asset data
                 ⬇️
📍 Customer arrives at location ➡️ W2: BSS emits intent signal ➡️ Location personnel notified
                 ⬇️
🔒 Customer authenticates ➡️ W3: BSS binds customer to location ➡️ Service session established
                 ⬇️
🔋 Service requested ➡️ W4: BSS signals asset ➡️ Asset performs service ➡️ Echo received
                 ⬇️
✅ Service completed ➡️ W5: BSS updates all states ➡️ Billing and quotas updated

This architecture maintains proper DIRAC component boundaries while enabling efficient service coordination through MQTT signals and state management.