# SMS Trigger System - Cron Job Documentation

## Overview

The SMS Trigger System is orchestrated by a single main script: `process-sms-triggers.php`

This script handles:
1. **Trigger Processing** - Finding customers who meet trigger conditions and queueing messages
2. **Queue Processing** - Sending queued SMS messages
3. **Retry Processing** - Retrying failed messages

## Files

### Main Entry Point
- **`tasker/process-sms-triggers.php`** - Main orchestrator script for cron

### Supporting Scripts (Legacy - for reference)
- **`tasker/process-triggers.php`** - Standalone trigger processor (can still be used)
- **`tasker/process-sms-queue.php`** - Standalone queue processor (can still be used)

### Core Classes
- **`userfrosting/models/Class/SellerMarketing/SellerMarketingTriggerProcessor.php`** - Trigger processing logic
- **`userfrosting/models/Class/SellerMarketing/SellerMarketingQueueProcessor.php`** - Queue processing logic
- **`userfrosting/models/Class/SellerMarketing/SellerMarketingQueue.php`** - Queue model/database operations
- **`userfrosting/models/Class/SellerMarketing/SellerMarketingTrigger.php`** - Trigger model/database operations

## Installation & Setup

### 1. Make Script Executable
```bash
chmod +x tasker/process-sms-triggers.php
```

### 2. Test the Script
```bash
# Show help
php tasker/process-sms-triggers.php --help

# Dry run for specific store
php tasker/process-sms-triggers.php --store=ou00 --dry-run

# Test with verbose output
php tasker/process-sms-triggers.php --store=ou00 --dry-run --verbose
```

### 3. Setup Cron Jobs

#### Recommended Setup (Combined Processing)

Process triggers and send messages every hour:
```cron
0 * * * * /usr/bin/php /path/to/buyerkiosk-web/tasker/process-sms-triggers.php --all-stores >> /var/log/buyerkiosk/sms-triggers.log 2>&1
```

#### Alternative Setup (Separate Processing)

Option 1: Process triggers hourly, send queue every 5 minutes:
```cron
# Process triggers (find customers, queue messages)
0 * * * * /usr/bin/php /path/to/buyerkiosk-web/tasker/process-sms-triggers.php --all-stores --no-send-queue >> /var/log/buyerkiosk/sms-triggers.log 2>&1

# Send queued messages
0,5,10,15,20,25,30,35,40,45,50,55 * * * * /usr/bin/php /path/to/buyerkiosk-web/tasker/process-sms-triggers.php --all-stores --no-process-triggers >> /var/log/buyerkiosk/sms-queue.log 2>&1
```

Option 2: Retry failed messages once per day:
```cron
# Main processing
0 * * * * /usr/bin/php /path/to/buyerkiosk-web/tasker/process-sms-triggers.php --all-stores >> /var/log/buyerkiosk/sms-triggers.log 2>&1

# Retry failed (once per day at 2am)
0 2 * * * /usr/bin/php /path/to/buyerkiosk-web/tasker/process-sms-triggers.php --all-stores --retry-failed --no-process-triggers --no-send-queue >> /var/log/buyerkiosk/sms-retries.log 2>&1
```

## Command Line Usage

### Basic Syntax
```bash
php tasker/process-sms-triggers.php [options]
```

### Command Line Options

| Option | Description | Default |
|--------|-------------|---------|
| `--store=TYPENUM` | Process specific store (e.g., `ou00`, `pa00`) | None |
| `--all-stores` | Process all active stores | Default if no store specified |
| `--process-triggers` | Find customers and queue messages | Enabled |
| `--no-process-triggers` | Skip trigger processing | - |
| `--send-queue` | Send queued messages | Enabled |
| `--no-send-queue` | Skip queue sending | - |
| `--retry-failed` | Retry failed messages | Disabled |
| `--batch-size=N` | Messages to process per batch | 50 |
| `--dry-run` | Don't actually send, just report | Disabled |
| `--json` | Output summary as JSON | Disabled |
| `--verbose` | Verbose output | Disabled |
| `--help` | Show help message | - |

### Examples

#### Process all stores (triggers + queue)
```bash
php tasker/process-sms-triggers.php --all-stores
```

#### Process specific store
```bash
php tasker/process-sms-triggers.php --store=ou00
```

#### Only process triggers (don't send)
```bash
php tasker/process-sms-triggers.php --all-stores --no-send-queue
```

#### Only send queue (don't process triggers)
```bash
php tasker/process-sms-triggers.php --all-stores --no-process-triggers
```

#### Dry run to see what would happen
```bash
php tasker/process-sms-triggers.php --store=ou00 --dry-run --verbose
```

#### Retry failed messages
```bash
php tasker/process-sms-triggers.php --all-stores --retry-failed --no-process-triggers --no-send-queue
```

#### Process with larger batch size
```bash
php tasker/process-sms-triggers.php --all-stores --batch-size=100
```

#### JSON output for monitoring
```bash
php tasker/process-sms-triggers.php --all-stores --json
```

## Exit Codes

| Code | Meaning |
|------|---------|
| 0 | Success |
| 1 | General error (see logs) |
| 2 | Invalid command line arguments |
| 3 | Lock file error (another instance is running) |

## Logging

### Log Files

Logs are written to: `/path/to/logs/sms-triggers-YYYY-MM-DD.log`

### Log Levels
- **INFO** - Normal operations
- **WARN** - Warnings (non-critical issues)
- **ERROR** - Errors (per-store failures)
- **FATAL** - Fatal errors (system-wide failures)

### What's Logged
- Start/end times
- Stores processed
- Triggers processed
- Messages queued/sent/failed
- Errors and exceptions
- Performance metrics (duration, memory)

### Example Log Output
```
[2025-01-21 10:00:00] INFO: === SMS Trigger Orchestrator Started ===
[2025-01-21 10:00:00] INFO: Options: processTriggers=true, sendQueue=true, retryFailed=false, dryRun=false
[2025-01-21 10:00:00] INFO: Processing all active stores: 45 stores found
[2025-01-21 10:00:01] INFO: --- Processing store: ou00 ---
[2025-01-21 10:00:01] INFO: Processing triggers for store: ou00
[2025-01-21 10:00:02] INFO: Triggers processed: 3, Messages queued: 15
[2025-01-21 10:00:02] INFO: Sending queued messages for store: ou00
[2025-01-21 10:00:05] INFO: Messages sent: 15, Failed: 0
[2025-01-21 10:05:30] INFO: === Processing Complete ===
[2025-01-21 10:05:30] INFO: Duration: 330s, Memory: 45MB, Peak: 67MB
[2025-01-21 10:05:30] INFO: Stores processed: 45, Failed: 0
[2025-01-21 10:05:30] INFO: Triggers: 120, Messages queued: 450
[2025-01-21 10:05:30] INFO: Messages sent: 450, Failed: 3
```

## Output

### Normal Output (Console)

```
================================================================
  SMS Trigger & Queue Orchestrator
================================================================
Started: 2025-01-21 10:00:00
Mode: LIVE
Process Triggers: YES
Send Queue: YES
Retry Failed: NO
Batch Size: 50
----------------------------------------------------------------

Processing store: ou00
    Triggers processed: 3
    Messages queued: 15
    Messages sent: 15
    Messages failed: 0
  Duration: 3.2s

Processing store: pa00
    Triggers processed: 2
    Messages queued: 8
    Messages sent: 8
    Messages failed: 0
  Duration: 1.8s

================================================================
  SUMMARY
================================================================
Duration: 330s
Memory Used: 45MB (Peak: 67MB)

Stores processed: 45
Stores failed: 0

Triggers processed: 120
Messages queued: 450

Messages sent: 450
Messages failed: 3

Completed: 2025-01-21 10:05:30
================================================================
```

### JSON Output (--json flag)

```json
{
    "start_time": "2025-01-21 10:00:00",
    "end_time": "2025-01-21 10:05:30",
    "duration": 330,
    "memory_used_mb": 45,
    "peak_memory_mb": 67,
    "dry_run": false,
    "stores": [
        {
            "store": "ou00",
            "triggers_processed": 3,
            "messages_queued": 15,
            "messages_sent": 15,
            "messages_failed": 0,
            "retries_sent": 0,
            "retries_failed": 0,
            "duration": 3.2,
            "errors": []
        }
    ],
    "totals": {
        "stores_processed": 45,
        "stores_failed": 0,
        "triggers_processed": 120,
        "messages_queued": 450,
        "messages_sent": 450,
        "messages_failed": 3,
        "retries_processed": 0,
        "retries_sent": 0,
        "retries_failed": 0
    },
    "errors": []
}
```

## Safety Features

### Lock File
- Prevents concurrent execution
- Located at: `tasker/process-sms-triggers.lock`
- Automatically removed on completion
- Stale lock files (>1 hour) are automatically cleaned

### Signal Handling
- Graceful shutdown on SIGTERM/SIGINT
- Cleanup of lock file on signal
- Proper logging of shutdown

### Error Handling
- Try-catch around entire process
- Per-store error isolation (one store failure doesn't stop others)
- Email alerts on critical failures
- Proper exit codes for monitoring

### Resource Limits
- Max execution time: 5 minutes (300 seconds)
- Memory tracking and logging
- Batch size limits to prevent overload

## Monitoring & Alerts

### Email Alerts

Critical failures trigger email alerts to: `admin@buyerkiosk.com`

Email includes:
- Context (store or SYSTEM)
- Timestamp
- Error message
- Stack trace

### Monitoring with JSON Output

Use `--json` flag for integration with monitoring systems:

```bash
# Run with JSON output
RESULT=$(php tasker/process-sms-triggers.php --all-stores --json)

# Parse with jq
echo "$RESULT" | jq '.totals.stores_failed'
echo "$RESULT" | jq '.totals.messages_sent'

# Check exit code
if [ $? -eq 0 ]; then
    echo "Success"
else
    echo "Failed"
fi
```

### Key Metrics to Monitor

1. **Exit Code** - Non-zero indicates problems
2. **stores_failed** - Number of stores that had errors
3. **messages_failed** - Number of messages that failed to send
4. **duration** - Processing time (should be < 300s)
5. **errors** array - Specific error messages

## Troubleshooting

### Issue: Lock file error

**Error:** "Another instance is already running"

**Solution:**
1. Check if process is actually running: `ps aux | grep process-sms-triggers`
2. If not running, remove stale lock: `rm tasker/process-sms-triggers.lock`
3. If running, wait for completion or kill if hung

### Issue: No messages being sent

**Possible causes:**
1. No active triggers configured
2. No customers meet trigger conditions
3. Queue is empty
4. SMS service is down

**Debug:**
```bash
# Run with verbose output
php tasker/process-sms-triggers.php --store=ou00 --verbose

# Check trigger count in database
# Check queue table for pending messages
# Check logs for specific errors
```

### Issue: High failure rate

**Possible causes:**
1. Invalid phone numbers
2. SMS service rate limiting
3. SMS service authentication issues
4. Network connectivity issues

**Debug:**
```bash
# Check specific store
php tasker/process-sms-triggers.php --store=ou00 --verbose

# Review queue errors in database
# Check SMS service status
# Review error logs
```

### Issue: Script timing out

**Possible causes:**
1. Too many stores to process
2. Database performance issues
3. SMS service slow response

**Solutions:**
1. Process stores individually: `--store=ou00`
2. Reduce batch size: `--batch-size=25`
3. Split into separate cron jobs (triggers vs queue)
4. Check database indexes and performance

## Performance Guidelines

### Recommended Settings

| Stores | Batch Size | Frequency | Expected Duration |
|--------|------------|-----------|-------------------|
| 1-10   | 50         | 1 hour    | < 30s |
| 11-25  | 50         | 1 hour    | 30s - 90s |
| 26-50  | 50         | 1 hour    | 90s - 180s |
| 50+    | 25-50      | 1 hour    | 180s - 300s |

### Optimization Tips

1. **Use separate cron jobs** - Process triggers hourly, send queue more frequently
2. **Adjust batch size** - Smaller batches for more stores
3. **Monitor execution time** - Should stay well under 5 minutes
4. **Check database performance** - Ensure indexes are optimized
5. **Consider per-store crons** - For high-volume stores

## Database Tables

### seller_marketing_triggers
- Trigger definitions
- Conditions and timing rules

### seller_marketing_queue
- Queued messages
- Status tracking (pending, sent, failed)
- Retry attempts

### seller_marketing_trigger_log
- History of trigger executions
- Customer matches per trigger

### seller_marketing_message_log
- Individual message history
- Send results and errors

## Security Considerations

1. **Lock file** - Prevents DoS via concurrent execution
2. **Batch limits** - Prevents resource exhaustion
3. **Error isolation** - One store failure doesn't affect others
4. **Signal handling** - Graceful shutdown prevents corruption
5. **Prepared statements** - SQL injection prevention (in processor classes)
6. **Input validation** - Command line argument validation

## Maintenance

### Daily
- Review logs for errors
- Monitor success/failure rates
- Check execution times

### Weekly
- Review trigger performance
- Check queue backlog
- Verify SMS delivery rates

### Monthly
- Review trigger effectiveness
- Clean up old logs (>90 days)
- Optimize database tables
- Review and update triggers

## Support

For issues or questions:
- Check logs: `/path/to/logs/sms-triggers-*.log`
- Review this documentation
- Check queue processor documentation
- Contact development team

## Version History

- **1.0.0** (2025-01-21) - Initial release of unified orchestrator
  - Combined trigger and queue processing
  - Command line argument support
  - JSON output for monitoring
  - Lock file protection
  - Email alerts
  - Comprehensive logging
