# Cron Class Documentation

## Overview

The `Cron` class extends `CronBase` and implements specific cronjob tasks for the application. It provides a consistent interface for executing various scheduled tasks with proper tracking and error handling.

## Class Structure

### Static Properties

- `$_class_code`: `'0801'` - Class identifier
- `$_class_trans_code`: `'cron-'` - Transaction code prefix
- `$cron_type_to_code`: Mapping of cron type names to codes

### Cron Type to Code Mapping

```php
$cron_type_to_code = array(
    'send-brith-noti' => 'A111',
    'prepare-rebate-session' => 'A002',
    'insert-bet-details' => 'A003',
    'update-4d-win-number' => 'A004',
    'get-4d-bet-details' => 'A005',
    'update-user-game-wallet' => 'A006',
    'cancel-pending-speedpay-payment' => 'A007',
    'update-game-status' => 'A008',
    'update-user-deposit-trunover' => 'A201',
    'calculate-user-rank' => 'A202',
    'expired-feed-the-frog-chance' => 'A203',
    'expired-shuffle-chance' => 'A204',
    'get-bet-details' => 'A205',
    'agent-trunover-comm' => 'A206',
    'user-trunover-comm' => 'A207',
    'distribute-comm' => 'A208',
    'check-wepay-withdrawal-status' => 'A209',
);
```

## Cronjob Methods

### Common Execution Pattern

All cronjob methods follow this general pattern:

1. **Initialize**: Call `static::_initialize()`
2. **Set Codes**: Define `$method_code`, `$actionCode`, `$transCode`
3. **Reset Errors**: Call `static::_reset_errors()`
4. **Validate Date**: Call `static::validate_cron_date($date)`
5. **Check Execution**: Optionally check if already executed
6. **Record Start**: Call `static::_record_cron($cron_code, $date)`
7. **Execute Logic**: Run business logic in try-catch
8. **Handle Errors**: Set error codes and logs on exception
9. **Determine Success**: Check result and error flags
10. **Update Complete**: Call `static::_update_complete_cron($cron_id, $success, $message)`

### Individual Cronjob Methods

#### `send_brith_noti($date)`

**Purpose**: Send birthday notifications

**Code**: `A111`

**Behavior:**
- Validates date
- Checks if already executed
- Calls `User::insert_today_birth($date)`
- Records success/failure

**Dependencies**: `User` model

---

#### `prepare_rebate_session($date)`

**Purpose**: Prepare rebate session for a date

**Code**: `A002`

**Behavior:**
- Validates date
- Checks if already executed (with optional `$rerun` flag)
- Calls `RebateSetting::prepare_rebate_session($date)`
- Records success/failure

**Dependencies**: `RebateSetting` model

**Note**: Has `$rerun` variable reference but parameter not defined (likely bug)

---

#### `insert_bet_details($date)`

**Purpose**: Insert bet details

**Code**: `A003`

**Behavior:**
- Validates date
- Checks if already executed
- **Note**: Business logic is commented out (incomplete implementation)
- Records success/failure

**Status**: Incomplete - business logic missing

---

#### `update_4d_win_number($date)`

**Purpose**: Update 4D winning numbers

**Code**: `A004`

**Behavior:**
- Validates date
- **Note**: Duplicate check is commented out (allows multiple runs)
- Calls `BetDetails::update_4d_win_number($date)`
- Records success/failure

**Dependencies**: `BetDetails` model

**Note**: Missing `$result` variable initialization (potential bug)

---

#### `get_4d_bet_details($date)`

**Purpose**: Retrieve 4D bet details

**Code**: `A005`

**Behavior:**
- Validates date
- **Note**: Duplicate check is commented out
- Calls `BetDetails::get_4d_bet_details($search_date)` with date range
- Records success/failure

**Dependencies**: `BetDetails` model

**Note**: Missing `$result` variable initialization (potential bug)

---

#### `login_user_update_game_wallet($date)`

**Purpose**: Update game wallet for logged-in users

**Code**: `A006`

**Behavior:**
- Validates date
- **Note**: Uses `is_cron_ran_success()` - only runs if previous execution failed
- Calls `UserGameInfo::login_user_update_game_wallet()`
- Records success/failure

**Dependencies**: `UserGameInfo` model

**Note**: Missing `$result` variable initialization (potential bug)

---

#### `update_user_deposit_trunover($date)`

**Purpose**: Update user deposit turnover

**Code**: `A201`

**Behavior:**
- Validates date
- Checks if already executed (with optional `$rerun` flag)
- Calls `User::update_user_deposit_trunover($date)`
- Records success/failure

**Dependencies**: `User` model

**Note**: Has `$rerun` variable reference but parameter not defined

---

#### `calculate_user_rank($date)`

**Purpose**: Calculate user rankings

**Code**: `A202`

**Behavior:**
- Validates date
- Checks if already executed (with optional `$rerun` flag)
- Calls `User::calculate_user_rank($date)`
- Records success/failure

**Dependencies**: `User` model

**Note**: Has `$rerun` variable reference but parameter not defined

---

#### `cancel_expired_speedpay_payment($date)`

**Purpose**: Cancel expired SpeedPay payments

**Code**: `A007`

**Behavior:**
- Validates date
- **Note**: No duplicate check - always executes
- Calls `Activation::cancel_expired_speedpay_payment()`
- Records success/failure

**Dependencies**: `Activation` model

**Note**: Missing `$result` variable initialization (potential bug)

---

#### `update_game_status($date)`

**Purpose**: Update game product status

**Code**: `A008`

**Behavior:**
- Validates date
- **Note**: No duplicate check - always executes
- Calls `GameProduct::check_game_product_status()`
- Records success/failure

**Dependencies**: `GameProduct` model

---

#### `expired_feed_the_frog_chance($date)`

**Purpose**: Expire feed-the-frog chances

**Code**: `A203`

**Behavior:**
- Validates date
- Checks if already executed (with optional `$rerun` flag)
- Calls `UserSpin::check_feed_frog_expired($date)`
- Records success/failure

**Dependencies**: `UserSpin` model

**Note**: Has `$rerun` variable reference but parameter not defined

---

#### `expired_shuffle($date)`

**Purpose**: Expire shuffle chances

**Code**: `A204`

**Behavior:**
- Validates date
- Checks if already executed (with optional `$rerun` flag)
- Calls `UserSpin::check_shuffle_expired($date)`
- Records success/failure

**Dependencies**: `UserSpin` model

**Note**: Has `$rerun` variable reference but parameter not defined

---

#### `get_game_bet_details($date, $type='ETG')`

**Purpose**: Retrieve game bet details with rate limiting

**Code**: `A205`

**Parameters:**
- `$date`: Date in YYYY-MM-DD format
- `$type`: Game type (default: 'ETG')

**Behavior:**
- Validates date
- **Note**: No duplicate check - always executes
- Uses system key locking to prevent concurrent execution
- Processes in batches with limits:
  - `{TYPE}_BET_CRON_LIMIT`: Maximum number of iterations (default: 8)
  - `{TYPE}_BET_CRON_RUNTIME_LIMIT`: Maximum runtime in seconds (default: 52)
- Calls `BetDetails::get_all_bet_details($type)` in a loop
- Stops when no more data or limits reached
- Records success/failure

**Dependencies**: `BetDetails` model, `System` model

**Special Features:**
- Uses system key (`bet_cron_running` or `{type}_bet_cron_running`) to prevent concurrent execution
- Processes data in batches until no more data or time/iteration limits reached

---

#### `agent_turnover_comm($date)`

**Purpose**: Calculate agent turnover commission

**Code**: `A206`

**Behavior:**
- Validates date
- **Note**: No duplicate check - always executes
- Calls `Commission::agent_turnover_comm_v2($date)`
- Records success/failure

**Dependencies**: `Commission` model

---

#### `user_turnover_comm($date)`

**Purpose**: Calculate user turnover commission

**Code**: `A207`

**Behavior:**
- Validates date
- **Note**: No duplicate check - always executes
- Calls `Commission::user_turnover_comm($date)`
- Records success/failure

**Dependencies**: `Commission` model

---

#### `distribute_comm($date, $rerun = false)`

**Purpose**: Distribute commissions

**Code**: `A208`

**Parameters:**
- `$date`: Date in YYYY-MM-DD format
- `$rerun`: Boolean to force rerun even if already executed successfully

**Behavior:**
- Validates date
- Checks if already executed successfully (unless `$rerun` is true)
- Loops through commission types from `Commission::$comm_type_to_code`
- Special handling for `turnover-bonus`:
  - Only distributes on Mondays
  - Distributes for the previous week (Monday to Sunday)
  - Loops through each day in the week
- For other commission types:
  - Distributes for the given date only
- Calls `Commission::distribute_comm()` for each date/type
- Records success/failure

**Dependencies**: `Commission` model

**Special Features:**
- Handles weekly commission distribution
- Supports multiple commission types
- Can force rerun with `$rerun` parameter

---

#### `check_wepay_withdrawal_status()`

**Purpose**: Check WePay withdrawal status

**Code**: `A209`

**Parameters:**
- None (no date parameter)

**Behavior:**
- **Note**: No date validation (runs without date)
- **Note**: No duplicate check - always executes
- Calls `DepositWepay::process_pending_payout()`
- Records success/failure

**Dependencies**: `DepositWepay` model

**Note**: This is a time-based cronjob, not date-based

---

### Utility Methods

#### `validate_cron_date($date)`

**Purpose**: Validate that a date is in the correct format

**Parameters:**
- `$date`: Date string to validate

**Behavior:**
- Validates date format using `Util::verifyDate($date, 'Y-m-d')`
- Throws `Xception` if invalid

**Error Code**: `A410001`

## Common Issues and Patterns

### Issues Found

1. **Undefined `$rerun` variable**: Several methods reference `$rerun` but don't have it as a parameter
2. **Missing `$result` initialization**: Some methods use `$result` without initializing it
3. **Commented duplicate checks**: Some methods have duplicate checks commented out
4. **Incomplete implementations**: `insert_bet_details()` has business logic commented out

### Execution Patterns

1. **Standard Pattern**: Check if ran → Record → Execute → Update
2. **Always Execute**: Record → Execute → Update (no duplicate check)
3. **Rerun on Failure**: Check if ran successfully → Record → Execute → Update
4. **Rate Limited**: Record → Lock → Execute in batches → Unlock → Update

## Dependencies

The Cron class depends on various models:
- `User`
- `RebateSetting`
- `BetDetails`
- `UserGameInfo`
- `Activation`
- `GameProduct`
- `UserSpin`
- `Commission`
- `DepositWepay`
- `System`
- `Util`
- `Log`
