# Cronjob Setup Guide

This guide details how to set up the daily reward calculation and distribution system.

## Overview

The system uses `django-cronjob-utils` to manage tasks. There are two dependent tasks that must run in sequence for a specific target date (usually "Yesterday" to satisfy the 24-hour hold period).

1.  **Calculate Rewards (`R001`)**: Calculates rewards for a given date.
2.  **Distribute Rewards (`D001`)**: Distributes the rewards calculated in step 1.

## Helper Script

To simplify the execution and ensure correct timezone handling + dependency management, a helper script is provided:

`backend/scripts/run_daily_rewards.sh`

This script:
-   Activates the Python virtual environment.
-   Calculates the correct "Yesterday" date using the Django application's timezone (`Asia/Kuala_Lumpur`).
-   Runs `R001` (Calculate).
-   Runs `D001` (Distribute) **only if** `R001` succeeds.

## Installation

### 1. Make the script executable
Ensure the script has execution permissions:
```bash
chmod +x /path/to/project/backend/scripts/run_daily_rewards.sh
```

### 2. Add to Crontab
Open your crontab editor:
```bash
crontab -e
```

Add the following line to run the job daily at **00:00** (Midnight):

```bash
0 0 * * * /Users/neowong/Sites/mscumec/telegram-earn/backend/scripts/run_daily_rewards.sh >> /Users/neowong/Sites/mscumec/telegram-earn/cron.log 2>&1
```

*Adjust paths as necessary for your deployment.*

## Manual Execution

You can run the script manually for testing or backfilling data.

**Run for Yesterday (Default):**
```bash
./backend/scripts/run_daily_rewards.sh
```

**Run for Specific Date:**
```bash
./backend/scripts/run_daily_rewards.sh 2024-12-05
```

## Monitoring

-   **Logs**: Check the output log defined in crontab (e.g., `cron.log`).
-   **Database**: Check the `django_cronjob_utils_cronexecution` table for detailed execution history and status.
-   **Admin**: If configured, you can view execution history in the Django Admin panel under `Cronjob Utils`.
