# MbetterClient User Workflow Documentation

## Table of Contents

1. [Cashier Workflow](#cashier-workflow)
2. [Game Flow and Match Progression](#game-flow-and-match-progression)
3. [Extraction Algorithm and Redistribution](#extraction-algorithm-and-redistribution)
4. [Major Functionality and Configurations](#major-functionality-and-configurations)

---

## Cashier Workflow

### Overview
The cashier role in MbetterClient is designed for streamlined betting operations with a focused interface optimized for speed and efficiency. Cashiers handle bet creation, verification, and management while having restricted access to administrative functions.

### Login Process
1. **Access the Application**: Navigate to `http://localhost:5000` (default port)
2. **Enter Credentials**: Use cashier-specific username and password
3. **Automatic Redirect**: System automatically redirects cashiers to the cashier dashboard
4. **Interface Focus**: Clean, distraction-free interface with essential betting controls

### Daily Operations Workflow

#### 1. Morning Setup (Pre-Match Preparation)
```
Login → Verify System Status → Check Available Matches → Prepare Betting Interface
```

- **System Status Check**: Verify all components are running (video player, API client, database)
- **Match Availability**: Confirm matches are loaded and in 'bet' status
- **Interface Preparation**: Ensure betting forms are ready for customer interactions

#### 2. Customer Bet Creation Process
```
Customer Request → Select Match → Choose Outcomes → Enter Amounts → Confirm Bet → Print Receipt
```

**Detailed Steps:**

1. **Customer Interaction**
   - Greet customer and understand betting requirements
   - Verify customer identity if required

2. **Match Selection**
   - Access "New Bet" page from cashier dashboard
   - System automatically loads available matches in 'bet' status
   - Display matches with fighter information and venue details

3. **Outcome Selection**
   - View dynamic betting outcomes from database (not hardcoded WIN1/WIN2/X)
   - Outcomes are generated from `match_outcomes` table data
   - Examples: "KO Round 1", "Points Win", "Draw", etc.
   - Select multiple outcomes per bet with individual amounts

4. **Amount Entry**
   - Enter betting amounts for each selected outcome
   - Real-time total calculation
   - Validate amounts (positive numbers, reasonable limits)

5. **Bet Confirmation**
   - Review complete bet summary
   - Generate unique UUID for bet tracking
   - Submit bet to database
   - Display success confirmation with bet ID

6. **Receipt Generation**
   - Print bet receipt (infrastructure ready, implementation pending)
   - Include bet ID, selected outcomes, amounts, and total
   - QR code for mobile verification

#### 3. Bet Management During Matches
```
Monitor Active Bets → Verify Bet Status → Handle Payouts → Update Records
```

- **Bet Monitoring**: View all bets for current day with real-time status
- **Status Tracking**: Monitor bet results (pending → won/lost/cancelled)
- **Payout Processing**: Mark winning bets as paid
- **Customer Service**: Handle bet verification requests

#### 4. End-of-Day Procedures
```
Close Betting → Finalize Results → Generate Reports → System Shutdown
```

- **Betting Closure**: Ensure no new bets accepted after match start
- **Result Finalization**: Confirm all bet outcomes are processed
- **Daily Reports**: Review betting statistics and totals
- **System Maintenance**: Clean logout and system preparation for next day

### Key Interface Elements

#### Cashier Dashboard Navigation
- **Left Side**: MbetterClient branding only (minimalist design)
- **Right Side**: Live server time clock + user dropdown menu
- **Hidden Elements**: All admin functions (configuration, templates, etc.)
- **Focused Menu**: Bets, Bet Verification, Start Games controls

#### Betting Interface Features
- **Dynamic Outcomes**: Database-driven betting options
- **Real-time Totals**: Automatic calculation of bet amounts
- **UUID Tracking**: Secure, unique bet identification
- **Print Integration**: Receipt printing infrastructure
- **Mobile Verification**: QR code access for bet checking

### Error Handling and Recovery

#### Common Issues
- **Match Not Available**: Verify match status is 'bet' in database
- **Database Connection**: Check system status indicators
- **Invalid Amounts**: Client-side validation prevents submission
- **Network Issues**: Automatic retry mechanisms for API calls

#### Recovery Procedures
- **Bet Creation Failure**: Retry submission, check database connectivity
- **Print Failure**: Manual receipt creation, QR code verification
- **System Freeze**: Force logout and re-login, contact administrator

---

## Game Flow and Match Progression

### Overview
MbetterClient manages the complete lifecycle of boxing matches from fixture loading to result extraction. The system uses a sophisticated state machine with automatic progression and manual controls.

### Match States and Transitions

#### 1. Initial State: Scheduled
```
Status: 'scheduled'
Description: Match is loaded from fixture but not yet available for betting
Actions: None (waiting for manual or automatic activation)
```

#### 2. Betting State: Bet
```
Status: 'bet'
Description: Match is active for betting, outcomes available to customers
Entry: Manual activation or START_GAME message
Exit: Match start time reached or manual progression
```

#### 3. Active State: Ingame
```
Status: 'ingame'
Description: Match is currently in progress
Entry: MATCH_START message from timer or manual trigger
Exit: Match completion and result extraction
```

#### 4. Completed States
```
Status: 'completed' - Match finished with results
Status: 'cancelled' - Match cancelled, no results
```

### Automatic Game Flow

#### Timer-Based Progression
```
Fixture Load → START_GAME Message → Match Activation → Timer Countdown → MATCH_START → Result Extraction
```

1. **Fixture Synchronization**
   - API client fetches fixture data from server
   - Matches loaded into database with timestamps
   - Automatic status assignment based on current time

2. **START_GAME Trigger**
   - Command-line timer: `--start-timer X` (minutes)
   - Manual trigger: "Start Games" button in cashier interface
   - Message bus broadcast to all components

3. **Match Activation Logic**
   ```python
   # Priority-based match selection
   def find_next_match():
       # 1. First priority: Matches with 'bet' status
       bet_matches = session.query(MatchModel).filter_by(status='bet').all()
       if bet_matches:
           return bet_matches[0]  # First available bet match

       # 2. Second priority: Matches with 'scheduled' status
       scheduled_matches = session.query(MatchModel).filter_by(status='scheduled').all()
       if scheduled_matches:
           return scheduled_matches[0]

       # 3. Third priority: Matches with 'pending' status
       pending_matches = session.query(MatchModel).filter_by(status='pending').all()
       if pending_matches:
           return pending_matches[0]

       return None  # No suitable matches found
   ```

4. **Timer Countdown**
   - Configurable interval (default: 20 minutes)
   - Visual countdown in status bar and navbar
   - Color-coded urgency (yellow → orange → red)
   - Automatic MATCH_START message when timer reaches zero

5. **Match Start Sequence**
   - Status change: 'bet'/'scheduled' → 'ingame'
   - Video player overlay updates
   - Betting interface locks for the match
   - Timer resets for next match

### Manual Game Control

#### Cashier Controls
- **Start Games Button**: Immediate START_GAME trigger
- **Match Timer Override**: Manual MATCH_START for specific matches
- **Emergency Stop**: Halt current match progression

#### Admin Controls
- **Fixture Management**: Load, reset, or modify fixture data
- **Match Status Override**: Force status changes for any match
- **Timer Configuration**: Adjust countdown intervals
- **Global Betting Mode**: Switch between betting strategies

### Global Betting Mode Configuration

#### Mode 1: All Bets on Start (Default)
```
START_GAME → ALL matches in fixture become 'bet' status simultaneously
Benefits: Maximum betting opportunity, all matches available at once
Use Case: Large fixtures with multiple concurrent betting periods
```

#### Mode 2: One Bet at a Time
```
START_GAME → ONLY first match becomes 'bet', others remain 'scheduled'
Benefits: Controlled betting flow, focused customer attention
Use Case: Sequential match progression, limited betting windows
```

#### Configuration
```json
{
  "config_key": "betting_mode",
  "config_value": "all_bets_on_start",
  "value_type": "string",
  "description": "Global betting mode: all_bets_on_start or one_bet_at_a_time"
}
```

### Result Extraction Process

#### Automatic Extraction
1. **Match Completion Detection**
   - Timer expiration or manual completion signal
   - Status change: 'ingame' → 'completed'

2. **Outcome Processing**
   - Query match_outcomes table for final results
   - Map outcomes to extraction associations
   - Calculate redistribution amounts

3. **Bet Resolution**
   - Update all related bets with win/loss/cancelled status
   - Calculate payout amounts for winning bets
   - Update betting statistics

#### Manual Result Entry
- Admin interface for result override
- Direct outcome value modification
- Emergency result correction

---

## Extraction Algorithm and Redistribution

### Overview
The extraction system implements a sophisticated algorithm for determining match winners and redistributing betting pools. It uses configurable outcome associations and percentage-based caps to ensure fair and profitable operations.

### Core Algorithm Components

#### 1. Outcome Association System
```
Database-driven mapping between match outcomes and betting results
```

**Association Table Structure:**
```sql
CREATE TABLE extraction_associations (
    outcome_name VARCHAR(255) NOT NULL,      -- Match outcome (e.g., "WIN1", "KO1")
    extraction_result VARCHAR(50) NOT NULL,  -- Betting result (WIN1, X, WIN2)
    is_default BOOLEAN DEFAULT FALSE,        -- Default association flag
    UNIQUE(outcome_name, extraction_result)  -- Prevent duplicates
);
```

**Default Associations:**
- **WIN1**: WIN1, K01, RET1, PTS1 (Fighter 1 victory outcomes)
- **X (Draw)**: DRAW, 12, X1, X2, DKO (Draw/tie outcomes)
- **WIN2**: WIN2, K02, RET2, PTS2 (Fighter 2 victory outcomes)

#### 2. Redistribution Cap System
```
Maximum percentage of collected bets that can be redistributed as winnings
```

**Configuration:**
```json
{
  "config_key": "extraction_redistribution_cap",
  "config_value": "70",
  "value_type": "float",
  "description": "Maximum redistribution percentage (10-100%)"
}
```

**Cap Logic:**
- **Default**: 70% of total collected amount
- **Range**: 10% to 100% (configurable)
- **Purpose**: Ensure house profit margin
- **Calculation**: `redistribution_amount = MIN(requested_amount, cap_percentage × total_collected)`

### Extraction Algorithm Flow

#### Step 1: Match Completion Detection
```python
def detect_match_completion(match_id):
    """Check if match has completed and results are available"""
    match = session.query(MatchModel).filter_by(id=match_id).first()
    if match.status == 'completed':
        return True
    return False
```

#### Step 2: Outcome Retrieval
```python
def get_match_outcomes(match_id):
    """Retrieve final outcomes from match_outcomes table"""
    outcomes = session.query(MatchOutcomeModel).filter_by(match_id=match_id).all()
    return {outcome.column_name: outcome.float_value for outcome in outcomes}
```

#### Step 3: Association Mapping
```python
def map_outcomes_to_results(outcomes, associations):
    """Map match outcomes to betting results using associations"""
    results = {'WIN1': 0, 'X': 0, 'WIN2': 0}

    for outcome_name, outcome_value in outcomes.items():
        # Find associations for this outcome
        associated_results = associations.get(outcome_name, [])

        # Distribute outcome value among associated results
        if associated_results:
            value_per_result = outcome_value / len(associated_results)
            for result in associated_results:
                results[result] += value_per_result

    return results
```

#### Step 4: Bet Resolution
```python
def resolve_bets(match_id, extraction_result):
    """Update all bets for the match based on extraction result"""
    bet_details = session.query(BetDetailModel).filter_by(match_id=match_id).all()

    for bet_detail in bet_details:
        if bet_detail.outcome == extraction_result:
            bet_detail.result = 'won'
            # Calculate winnings based on redistribution cap
        elif bet_detail.result == 'pending':
            bet_detail.result = 'lost'

    session.commit()
```

#### Step 5: Redistribution Calculation
```python
def calculate_redistribution(bets_won, total_collected, cap_percentage=70):
    """Calculate actual redistribution respecting the cap"""
    requested_total = sum(bet.amount * 2 for bet in bets_won)  # 2x payout
    cap_amount = (total_collected * cap_percentage) / 100

    if requested_total <= cap_amount:
        # All winnings can be paid
        return requested_total
    else:
        # Apply cap - distribute proportionally
        scale_factor = cap_amount / requested_total
        return cap_amount, scale_factor
```

### Advanced Redistribution Scenarios

#### Scenario 1: Normal Redistribution (Under Cap)
```
Total Collected: $1000
Winning Bets: 2 bets × $100 each = $200 requested
Cap (70%): $700 maximum
Result: Pay full $200 (under cap)
```

#### Scenario 2: Capped Redistribution
```
Total Collected: $1000
Winning Bets: 10 bets × $100 each = $1000 requested
Cap (70%): $700 maximum
Result: Pay $700 total, scaled proportionally
```

#### Scenario 3: Multiple Outcome Winners
```
Match Result: DRAW (X)
Total Collected: $2000
WIN1 Bets: 5 × $50 = $250
X Bets: 3 × $100 = $300 (winners)
WIN2 Bets: 7 × $75 = $525
Cap (70%): $1400 maximum
Result: Pay $300 to X bet winners (under cap)
```

### Extraction Statistics Tracking

#### Statistics Table Structure
```sql
CREATE TABLE extraction_stats (
    match_id INTEGER PRIMARY KEY,
    fixture_id VARCHAR(255),
    match_datetime DATETIME,
    total_bets INTEGER,
    total_amount_collected DECIMAL(10,2),
    total_redistributed DECIMAL(10,2),
    actual_result VARCHAR(100),
    extraction_result VARCHAR(50),
    cap_applied BOOLEAN,
    cap_percentage DECIMAL(5,2),
    under_bets INTEGER,
    under_amount DECIMAL(10,2),
    over_bets INTEGER,
    over_amount DECIMAL(10,2)
);
```

#### Statistical Analysis
- **Profit Margin**: `total_collected - total_redistributed`
- **Cap Application Rate**: Percentage of matches hitting redistribution cap
- **Outcome Distribution**: Frequency analysis of different extraction results
- **Betting Patterns**: UNDER vs OVER bet distribution and success rates

### Configuration and Tuning

#### Association Management
- **Drag-and-Drop Interface**: Visual outcome association management
- **Multi-Association Support**: Outcomes can map to multiple results
- **Real-time Updates**: Immediate database persistence
- **Default Templates**: Pre-configured associations for common scenarios

#### Cap Management
- **Percentage Range**: 10% to 100% configurable
- **Per-Match Override**: Individual match cap adjustments
- **Dynamic Adjustment**: Cap changes based on fixture performance
- **Reporting**: Cap impact analysis and recommendations

---

## Major Functionality and Configurations

### Core System Components

#### 1. Web Dashboard
**Primary Interface**: Flask-based web application with Bootstrap UI
**Authentication**: JWT token-based security with role-based access
**Real-time Updates**: WebSocket-like polling for live status updates
**Responsive Design**: Mobile-friendly interface with offline capabilities

#### 2. Video Player (Qt-based)
**Rendering Engine**: PyQt5/QML with hardware acceleration
**Overlay System**: Dual rendering (WebEngine/Native) with template support
**Format Support**: MP4, AVI, MOV, MKV, WebM playback
**Controls**: Full keyboard shortcuts and remote control support

#### 3. API Client
**External Integration**: RESTful API communication with remote servers
**Authentication**: Bearer token and API key management
**Retry Logic**: Exponential backoff with configurable limits
**Response Processing**: Custom handlers for different data formats

#### 4. Database System
**Engine**: SQLite with SQLAlchemy ORM
**Migrations**: Versioned schema updates with rollback support
**Models**: Comprehensive data models for matches, bets, users, and configuration
**Performance**: Optimized queries with proper indexing

#### 5. Message Bus
**Inter-component Communication**: Publisher-subscriber pattern
**Thread Safety**: Asynchronous message passing between components
**Extensibility**: Plugin architecture support
**Monitoring**: Message logging and debugging capabilities

### Configuration Categories

#### System Configuration
```json
{
  "web": {
    "host": "localhost",
    "port": 5000,
    "secret_key": "auto-generated",
    "jwt_expiration_hours": 24
  },
  "qt": {
    "fullscreen": true,
    "default_template": "news_template",
    "overlay_type": "webengine"
  },
  "logging": {
    "level": "INFO",
    "max_file_size": "10MB",
    "backup_count": 5
  }
}
```

#### Betting Configuration
```json
{
  "betting_mode": "all_bets_on_start",
  "match_interval": 20,
  "extraction_redistribution_cap": 70,
  "currency_symbol": "USh",
  "currency_position": "before"
}
```

#### Video and Display Configuration
```json
{
  "video": {
    "width": 1920,
    "height": 1080,
    "fullscreen": false,
    "supported_formats": ["mp4", "avi", "mov", "mkv"]
  },
  "screen_cast": {
    "enabled": true,
    "resolution": "1280x720",
    "framerate": 15,
    "auto_start_capture": false
  }
}
```

#### API and Integration Configuration
```json
{
  "api": {
    "fastapi_url": "https://mbetter.nexlab.net/",
    "api_token": "configured-token",
    "api_interval": 600,
    "api_timeout": 30,
    "api_enabled": true
  },
  "barcode": {
    "enabled": false,
    "standard": "code128",
    "width": 200,
    "height": 100
  },
  "qrcode": {
    "enabled": false,
    "size": 200,
    "error_correction": "M"
  }
}
```

### User Roles and Permissions

#### 1. Administrator Role
**Full System Access**:
- User management (create, edit, delete users)
- System configuration and settings
- Fixture management and data import
- Extraction configuration and associations
- System shutdown and maintenance
- Log viewing and debugging
- Statistics and reporting access

#### 2. Cashier Role
**Limited Betting Operations**:
- Bet creation and management
- Customer receipt printing
- Bet verification and payout marking
- Match starting controls
- Personal password changes
- Restricted to betting-related functions

#### 3. API Access Levels
**Token-based Permissions**:
- Read-only access for monitoring
- Betting operations for integrated systems
- Administrative access for system management
- Configurable expiration and scope limitations

### Advanced Features

#### Screen Casting System
**Chromecast Integration**:
- Automatic device discovery on local network
- Real-time screen capture with FFmpeg
- Configurable quality settings (resolution, bitrate, framerate)
- Cross-platform audio/video capture
- HTTP streaming server for device compatibility

#### Offline Capabilities
**CDN Fallback System**:
- Local Bootstrap and FontAwesome libraries
- Automatic CDN-to-local switching
- Complete offline functionality
- PyInstaller-compatible resource bundling

#### Real-time Status Monitoring
**System Health Dashboard**:
- Component status indicators
- Match timer with visual countdown
- Video player status and controls
- API connectivity monitoring
- Database connection health

#### Automated Match Timer
**Intelligent Progression**:
- Configurable countdown intervals
- Priority-based match selection
- Automatic status transitions
- Visual feedback with color coding
- Manual override capabilities

### Performance and Scalability

#### Database Optimization
- **Indexing Strategy**: Optimized indexes on frequently queried columns
- **Connection Pooling**: Efficient database connection management
- **Query Optimization**: Reduced N+1 queries with proper JOIN operations
- **Migration System**: Zero-downtime schema updates

#### Memory Management
- **Component Isolation**: Separate processes for critical functions
- **Resource Monitoring**: Built-in memory and CPU usage tracking
- **Cleanup Procedures**: Automatic resource cleanup on shutdown
- **Caching Strategy**: Intelligent caching for frequently accessed data

#### Network Efficiency
- **API Optimization**: Batch operations and reduced request frequency
- **Compression**: Response compression for large data transfers
- **Connection Reuse**: Persistent connections where possible
- **Timeout Management**: Configurable timeouts with retry logic

### Security Features

#### Authentication and Authorization
- **JWT Tokens**: Secure token-based authentication
- **Role-based Access**: Granular permission system
- **Session Management**: Automatic session timeout and cleanup
- **Password Security**: Proper hashing and validation

#### Data Protection
- **Input Validation**: Comprehensive input sanitization
- **SQL Injection Prevention**: Parameterized queries
- **XSS Protection**: Template escaping and validation
- **CSRF Protection**: Token-based request validation

#### System Security
- **File Access Control**: Restricted file system access
- **Network Security**: Configurable firewall rules
- **Audit Logging**: Comprehensive security event logging
- **Update Mechanism**: Secure update distribution

### Monitoring and Maintenance

#### System Monitoring
- **Health Checks**: Automated component health verification
- **Performance Metrics**: CPU, memory, and network usage tracking
- **Error Reporting**: Comprehensive error logging and alerting
- **Status Dashboard**: Real-time system status visualization

#### Maintenance Procedures
- **Automated Backups**: Database and configuration backups
- **Log Rotation**: Automatic log file management
- **Update Process**: Safe application updates with rollback
- **Cleanup Tasks**: Automated temporary file and cache cleanup

This comprehensive documentation covers the complete workflow, technical architecture, and operational procedures for MbetterClient. The system is designed for reliability, performance, and ease of use in professional betting environments.