# STK Status Checker - Cron Job Setup

## Overview

This setup will run a command every 5 minutes to check and update the status of STK transactions that are still in 'Launched' status.

## Files Created

1. **Command**: `app/Console/Commands/CheckStkStatus.php`

    - Processes TxnLog records with `stk_status = 'Launched'`
    - Calls the `validateStkPush` function for each record
    - Updates status based on M-Pesa API response

2. **Scheduler**: `routes/console.php`
    - Added scheduled command to run every 5 minutes
    - Processes up to 50 records per run

## Manual Cron Job Setup

### Step 1: Open Crontab

```bash
crontab -e
```

### Step 2: Add the Cron Job

Add this line to your crontab:

```bash
*/5 * * * * cd /Users/josephkitonga/Herd/paceEvents && php artisan schedule:run >> /dev/null 2>&1
```

### Step 3: Save and Exit

-   Press `Ctrl + X` to exit
-   Press `Y` to save
-   Press `Enter` to confirm

## Testing the Setup

### Test the Command Manually

```bash
php artisan stk:check-status --limit=5
```

### View Scheduled Tasks

```bash
php artisan schedule:list
```

### Run Scheduler Manually

```bash
php artisan schedule:run
```

## Command Options

-   `--limit=50` : Maximum number of records to process (default: 50)
-   `--help` : Show command help

## What the Command Does

1. **Finds Launched Transactions**: Queries TxnLog where `stk_status = 'Launched'`
2. **Processes Each Record**: For each record, calls the M-Pesa verify API
3. **Updates Status**: Updates the status based on the API response:
    - `Success` - Payment successful
    - `Failed` - Payment failed
    - `Canceled` - User canceled
    - `Timeout` - Network timeout
    - `Invalid-user-input` - Invalid input
4. **Logs Activity**: Creates log entries for tracking

## Monitoring

### Check Logs

```bash
tail -f storage/logs/laravel.log
```

### Check Recent Activity

```bash
php artisan tinker
```

```php
App\Models\Log::where('source', 'STK Status Update')->latest()->take(10)->get();
```

## Troubleshooting

### If Cron Job Doesn't Run

1. Check if cron service is running: `sudo service cron status`
2. Check cron logs: `tail -f /var/log/cron`
3. Test manually: `php artisan schedule:run`

### If Command Fails

1. Check Laravel logs: `tail -f storage/logs/laravel.log`
2. Test with smaller limit: `php artisan stk:check-status --limit=1`
3. Check database connection and TxnLog table

### Performance Considerations

-   The command processes up to 50 records per run
-   Each API call has a 0.1-second delay to avoid overwhelming M-Pesa
-   The scheduler runs every 5 minutes
-   Use `--limit` option to control processing load

## Security Notes

-   The cron job runs with your user permissions
-   API credentials are stored in environment variables
-   Logs are created for audit purposes
-   Failed requests are logged with full error details
