# Testing Examples Based on Your Actual Data

## 📊 Understanding Your Records

### **Record #362: "TimeBased"**
```json
{
  "name": "TimeBased",
  "module_action_operation": "created_at",  // ← Monitor creation date
  "rule_type": "date",
  "duration": "1_day",                      // ← Preset: 1 day
  "trigger_time": "after",                  // ← 1 day AFTER
  "time": "5_minutes"
}
```
**Meaning:** Run automation **1 day after lead is created**

---

### **Record #363: "Lead Time Before"**
```json
{
  "name": "Lead Time Before",
  "module_action_operation": "updated_at",  // ← Monitor update date
  "rule_type": "date",
  "duration": "custom",                     // ← Custom duration
  "duration_custom_value": "2",             // ← 2
  "duration_custom_period": "days",         // ← days
  "trigger_time": "after"                   // ← 2 days AFTER
}
```
**Meaning:** Run automation **2 days after lead is updated**

---

### **Record #364: "Lead-Automation date"**
```json
{
  "name": "Lead-Automation date",
  "module_action_operation": "updated_at",
  "rule_type": "date",
  "duration": "custom",
  "duration_custom_value": "1",
  "duration_custom_period": "days",
  "trigger_time": "after",
  "time": "custom",
  "custom_time": "03:39"                    // ← Run at specific time
}
```
**Meaning:** Run automation **1 day after lead is updated** at **3:39 AM**

---

### **Record #366: "Task" (BEFORE example)**
```json
{
  "name": "Task",
  "module_action_name": "TASK",
  "module_action_operation": "to_date",     // ← Monitor task due date
  "rule_type": "date",
  "duration": "1_day",
  "trigger_time": "before"                  // ← 1 day BEFORE
}
```
**Meaning:** Run automation **1 day before task is due**

---

## 🧪 Test Case 1: Record #362 - "1 Day After Lead Created"

### Setup Test Data:
```sql
-- Create a test lead from yesterday
INSERT INTO crm_leads (
    seller_user_id, 
    lead_id, 
    buyer_user_id, 
    created_at,
    updated_at,
    is_automation_created
) VALUES (
    2091,                                   -- Your user_id
    'TEST-001', 
    100, 
    DATE_SUB(NOW(), INTERVAL 1 DAY),       -- Created yesterday
    DATE_SUB(NOW(), INTERVAL 1 DAY),
    0
);
```

### Run Automation:
```bash
php artisan app:lead-automation-date-based
```

### Expected Output:
```
Found 1 date-based lead automations
Processing automation: TimeBased (ID: 362)
Monitoring field: created_at
Duration: 1 days
Direction: after
Target date: 2026-02-02 [current_time]
Window: 2026-02-02 [time-2h] → 2026-02-02 [time+1h]
Found 1 matching leads
✓ Triggered automation for lead #[lead_id]
```

### Verify Results:
```sql
-- Check execution record
SELECT * FROM automation_executions 
WHERE automation_id = 362 
ORDER BY id DESC LIMIT 1;

-- Check note was created
SELECT * FROM crm_notes 
WHERE unique_id = [your_lead_id]
ORDER BY id DESC LIMIT 1;
-- Should contain: "Hello Notes"

-- Check running log
SELECT * FROM automation_running_logs
WHERE automation_id = 362
ORDER BY id DESC LIMIT 1;
```

---

## 🧪 Test Case 2: Record #363 - "2 Days After Lead Updated"

### Setup Test Data:
```sql
-- Create a test lead updated 2 days ago
INSERT INTO crm_leads (
    seller_user_id, 
    lead_id, 
    buyer_user_id, 
    created_at,
    updated_at,                             -- ← This is monitored
    is_automation_created
) VALUES (
    2091,
    'TEST-002', 
    101, 
    DATE_SUB(NOW(), INTERVAL 5 DAY),       -- Created 5 days ago
    DATE_SUB(NOW(), INTERVAL 2 DAY),       -- Updated 2 days ago
    0
);
```

### Run Automation:
```bash
php artisan app:lead-automation-date-based
```

### Expected Behavior:
- Command monitors `updated_at` field (not `created_at`)
- Looks for leads updated exactly 2 days ago
- Creates note: "Hello - Notes"

---

## 🧪 Test Case 3: Test "BEFORE" Trigger (Record #366)

### Understanding "BEFORE":
```
If trigger_time = "before"
Then we look FORWARD, not backward

Example: "1 day BEFORE to_date"
- Today: Feb 3, 2026
- Target: Feb 4, 2026 (1 day from now)
- Find: Tasks with to_date = Feb 4
```

### Setup Test Data:
```sql
-- Create a task due tomorrow
INSERT INTO task_informations (
    user_id,
    to_date,                               -- ← This is monitored
    created_at
) VALUES (
    2091,
    DATE_ADD(NOW(), INTERVAL 1 DAY),      -- Due tomorrow
    NOW()
);
```

### What Happens:
- Command calculates: `now()->addDays(1)` (because "before")
- Finds tasks due on that date
- Executes automation

---

## 🔍 Understanding Duration Parsing

### Your Command Handles Both Formats:

#### Preset Format (e.g., "1_day"):
```php
duration = "1_day"
↓
Parses to: ['value' => 1, 'unit' => 'day']
↓
Carbon: now()->subDays(1)
```

#### Custom Format (e.g., "custom"):
```php
duration = "custom"
duration_custom_value = "2"
duration_custom_period = "days"
↓
Parses to: ['value' => 2, 'unit' => 'days']
↓
Carbon: now()->subDays(2)
```

---

## 📊 How Different Fields Work Together

### Example Combinations:

#### Combination 1: Simple "1 Day After"
```json
{
  "duration": "1_day",
  "trigger_time": "after",
  "module_action_operation": "created_at"
}
```
**Result:** Find leads created 1 day ago

#### Combination 2: Custom "2 Days After"
```json
{
  "duration": "custom",
  "duration_custom_value": "2",
  "duration_custom_period": "days",
  "trigger_time": "after",
  "module_action_operation": "updated_at"
}
```
**Result:** Find leads updated 2 days ago

#### Combination 3: "1 Day Before"
```json
{
  "duration": "1_day",
  "trigger_time": "before",
  "module_action_operation": "to_date"
}
```
**Result:** Find tasks due tomorrow

---

## 🧪 Complete Testing Script

### Step 1: Setup
```bash
# SSH to your server or local environment
cd /path/to/your/project
```

### Step 2: Create Test Leads
```sql
mysql -u root -p your_database << EOF

-- Test lead for "1 day after created"
INSERT INTO crm_leads (seller_user_id, lead_id, buyer_user_id, created_at, updated_at, is_automation_created)
VALUES (2091, 'TEST-362', 100, DATE_SUB(NOW(), INTERVAL 1 DAY), NOW(), 0);

-- Test lead for "2 days after updated"
INSERT INTO crm_leads (seller_user_id, lead_id, buyer_user_id, created_at, updated_at, is_automation_created)
VALUES (2091, 'TEST-363', 101, DATE_SUB(NOW(), INTERVAL 5 DAY), DATE_SUB(NOW(), INTERVAL 2 DAY), 0);

-- Test lead for "1 day after updated" with custom time
INSERT INTO crm_leads (seller_user_id, lead_id, buyer_user_id, created_at, updated_at, is_automation_created)
VALUES (2091, 'TEST-364', 102, DATE_SUB(NOW(), INTERVAL 3 DAY), DATE_SUB(NOW(), INTERVAL 1 DAY), 0);

EOF
```

### Step 3: Run Command
```bash
php artisan app:lead-automation-date-based
```

### Step 4: Check Results
```sql
-- Should see 3 execution records
SELECT 
    ae.id,
    ae.automation_id,
    a.name as automation_name,
    ae.related_record_pk as lead_id,
    ae.execution_started_at
FROM automation_executions ae
JOIN automations a ON a.id = ae.automation_id
WHERE ae.automation_id IN (362, 363, 364)
ORDER BY ae.id DESC;

-- Should see 3 notes created
SELECT * FROM crm_notes 
WHERE unique_id IN (
    SELECT id FROM crm_leads WHERE lead_id LIKE 'TEST-%'
)
ORDER BY id DESC;

-- Should see 3 running logs
SELECT * FROM automation_running_logs
WHERE automation_id IN (362, 363, 364)
ORDER BY id DESC;
```

---

## 🐛 Debugging Your Specific Records

### If Automation #362 Doesn't Run:

```bash
# Check if automation is active
mysql -u root -p your_database -e "
SELECT id, name, status, rule_type 
FROM automations 
WHERE id = 362;"

# Check if there are matching leads
mysql -u root -p your_database -e "
SELECT id, lead_id, created_at 
FROM crm_leads 
WHERE seller_user_id = 2091 
AND DATE(created_at) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)
LIMIT 5;"

# Check if already processed
mysql -u root -p your_database -e "
SELECT * FROM automation_running_logs 
WHERE automation_id = 362 
ORDER BY id DESC LIMIT 5;"
```

---

## 📝 Expected Behavior Summary

| Automation ID | Name | Monitors | Duration | Direction | When Runs |
|--------------|------|----------|----------|-----------|-----------|
| 362 | TimeBased | created_at | 1 day | after | 1 day after lead created |
| 363 | Lead Time Before | updated_at | 2 days | after | 2 days after lead updated |
| 364 | Lead-Automation date | updated_at | 1 day | after | 1 day after lead updated @ 3:39 AM |
| 366 | Task | to_date | 1 day | before | 1 day before task due |

---

## ✅ Success Criteria

After running the command, you should see:

1. ✅ Console output showing automations processed
2. ✅ Records in `automation_executions` table
3. ✅ Notes created in `crm_notes` table
4. ✅ Entries in `automation_running_logs` table
5. ✅ No duplicate executions on second run
6. ✅ Only leads from correct time window processed

---

## 🚀 Next Steps

1. Test with the examples above
2. Verify results in database
3. Check logs: `tail -f storage/logs/laravel.log`
4. Once working, schedule in cron
5. Monitor for 24-48 hours
6. Adjust time window if needed

Your data structure is clear now - the command is perfectly tailored to it! 🎯


# CORRECTED: Understanding Duration + Time

## 🎯 The Truth About Your Time Field

Looking at your data more carefully:

```json
{
  "duration": "1_day",       // Main delay: 1 day
  "time": "5_minutes",       // Additional delay: + 5 minutes
  "trigger_time": "after"
}
```

**This means:** "1 day **AND** 5 minutes after lead created"

NOT "check every 5 minutes" ❌  
BUT "1 day + 5 minutes total delay" ✅

---

## 📊 Real Examples from Your Data

### Example 1: Record #362
```json
{
  "duration": "1_day",
  "time": "5_minutes",
  "trigger_time": "after",
  "module_action_operation": "created_at"
}
```

**Translation:** Run automation **1 day AND 5 minutes** after lead created

**Timeline:**
```
Day 0                           Day 1                           Day 1
Lead Created                    24 hours later                  + 5 minutes
Feb 1, 10:00 AM                Feb 2, 10:00 AM                 Feb 2, 10:05 AM
                                                                ✅ TRIGGER HERE
```

**Calculation:**
```php
$now = Carbon::parse('2026-02-02 12:00:00');  // When cron runs

// Step 1: Subtract main duration (1 day)
$target = $now->subDays(1);  // Feb 1, 12:00 PM

// Step 2: Subtract additional time (5 minutes)
$target->subMinutes(5);      // Feb 1, 11:55 AM

// Result: Find leads created on Feb 1 around 11:55 AM
```

---

### Example 2: Record #363
```json
{
  "duration": "custom",
  "duration_custom_value": "2",
  "duration_custom_period": "days",
  "time": "5_minutes",
  "trigger_time": "after"
}
```

**Translation:** Run automation **2 days AND 5 minutes** after lead updated

**Timeline:**
```
Day 0                    Day 2                    Day 2
Lead Updated             48 hours later           + 5 minutes
Feb 1, 10:00 AM         Feb 3, 10:00 AM          Feb 3, 10:05 AM
                                                  ✅ TRIGGER HERE
```

**Calculation:**
```php
$now = Carbon::parse('2026-02-03 12:00:00');

// Step 1: Subtract 2 days
$target = $now->subDays(2);  // Feb 1, 12:00 PM

// Step 2: Subtract 5 minutes
$target->subMinutes(5);      // Feb 1, 11:55 AM

// Find leads updated on Feb 1 around 11:55 AM
```

---

### Example 3: Record #364 with Custom Time
```json
{
  "duration": "custom",
  "duration_custom_value": "1",
  "duration_custom_period": "days",
  "time": "custom",
  "custom_time": "03:39",
  "trigger_time": "after"
}
```

**Translation:** Run automation **1 day after at 3:39 AM**

**Timeline:**
```
Day 0                    Day 1 at 3:39 AM
Lead Updated             Exactly 1 day later at 3:39 AM
Feb 1, 2:00 PM          Feb 2, 3:39 AM
                        ✅ TRIGGER HERE
```

**Calculation:**
```php
$now = Carbon::parse('2026-02-02 12:00:00');

// Step 1: Subtract 1 day
$target = $now->subDays(1);  // Feb 1, 12:00 PM

// Step 2: Set specific time
$target->setTime(3, 39, 0);  // Feb 1, 3:39 AM

// Find leads updated on Feb 1 around 3:39 AM
```

---

## 🔍 The Complete Logic

### Your System Has THREE Components:

1. **`duration`** → Main delay amount
   - `"1_day"` = 1 day
   - `"custom"` = use custom_value + custom_period

2. **`time`** → Additional delay OR specific time
   - `"5_minutes"` = add 5 minutes to duration
   - `"1_hour"` = add 1 hour to duration
   - `"custom"` = ignore duration time, use custom_time instead

3. **`trigger_time`** → Direction
   - `"after"` = subtract (look backward)
   - `"before"` = add (look forward)

---

## 💡 Different Time Scenarios

### Scenario A: Duration + Time (Both Preset)
```json
{
  "duration": "1_day",
  "time": "5_minutes",
  "trigger_time": "after"
}
```
**Total delay:** 1 day + 5 minutes = 1 day and 5 minutes
```php
$target = now()->subDays(1)->subMinutes(5);
```

---

### Scenario B: Duration + Time (Hours)
```json
{
  "duration": "1_day",
  "time": "1_hour",
  "trigger_time": "after"
}
```
**Total delay:** 1 day + 1 hour = 25 hours total
```php
$target = now()->subDays(1)->subHours(1);
```

---

### Scenario C: Custom Duration + Time
```json
{
  "duration": "custom",
  "duration_custom_value": "2",
  "duration_custom_period": "days",
  "time": "10_minutes",
  "trigger_time": "after"
}
```
**Total delay:** 2 days + 10 minutes
```php
$target = now()->subDays(2)->subMinutes(10);
```

---

### Scenario D: Duration + Custom Time (Specific Time of Day)
```json
{
  "duration": "1_day",
  "time": "custom",
  "custom_time": "03:39",
  "trigger_time": "after"
}
```
**Total delay:** 1 day, but at 3:39 AM specifically
```php
$target = now()->subDays(1)->setTime(3, 39, 0);
```

---

## 🧪 Real-World Test Cases

### Test 1: "1 day + 5 minutes after"

**Setup:**
```sql
-- Create lead at Feb 1, 10:00 AM
INSERT INTO crm_leads (seller_user_id, lead_id, created_at)
VALUES (2091, 'TEST-1', '2026-02-01 10:00:00');
```

**When cron runs on Feb 2 at 10:05 AM:**
```php
$now = '2026-02-02 10:05:00';

// Calculate target
$target = now()->subDays(1)->subMinutes(5);
// Result: '2026-02-01 10:00:00'

// Window (±2 hours for day-based)
// From: Feb 1, 8:00 AM
// To:   Feb 1, 11:00 AM

// Lead created at Feb 1, 10:00 AM
// ✅ MATCH! Process lead
```

---

### Test 2: "2 days + 10 minutes after"

**Setup:**
```sql
-- Create lead at Feb 1, 11:50 AM
INSERT INTO crm_leads (seller_user_id, lead_id, created_at)
VALUES (2091, 'TEST-2', '2026-02-01 11:50:00');
```

**When cron runs on Feb 3 at 12:00 PM:**
```php
$now = '2026-02-03 12:00:00';

// Calculate target
$target = now()->subDays(2)->subMinutes(10);
// Result: '2026-02-01 11:50:00'

// Window
// From: Feb 1, 9:50 AM
// To:   Feb 1, 12:50 PM

// Lead created at Feb 1, 11:50 AM
// ✅ MATCH! Process lead
```

---

### Test 3: "1 day at 3:39 AM"

**Setup:**
```sql
-- Create lead at Feb 1, 3:30 AM
INSERT INTO crm_leads (seller_user_id, lead_id, created_at)
VALUES (2091, 'TEST-3', '2026-02-01 03:30:00');
```

**When cron runs on Feb 2 at 3:39 AM:**
```php
$now = '2026-02-02 03:39:00';

// Calculate target
$target = now()->subDays(1)->setTime(3, 39, 0);
// Result: '2026-02-01 03:39:00'

// Window
// From: Feb 1, 1:39 AM
// To:   Feb 1, 4:39 AM

// Lead created at Feb 1, 3:30 AM
// ✅ MATCH! Process lead
```

---

## 📝 Code Logic Explained

```php
// STEP 1: Parse duration
$duration = ['value' => 1, 'unit' => 'days'];

// STEP 2: Parse additional time
$time = ['value' => 5, 'unit' => 'minutes'];

// STEP 3: Calculate target
$target = now();  // Feb 2, 10:05 AM

// Apply duration (AFTER means subtract)
$target->subDays(1);  // Feb 1, 10:05 AM

// Apply additional time (AFTER means subtract more)
$target->subMinutes(5);  // Feb 1, 10:00 AM

// RESULT: Find leads created on Feb 1 at 10:00 AM
```

---

## ⚡ Why This Makes Sense

The `time` field is **NOT**:
- ❌ When to run the cron
- ❌ How often to check
- ❌ A separate schedule

The `time` field **IS**:
- ✅ Additional delay on top of duration
- ✅ Part of the total time calculation
- ✅ Fine-tuning the exact moment

### Think of it like:
```
"Send email 1 day and 5 minutes after signup"
             ↑           ↑
          duration      time
```

NOT:
```
"Send email 1 day after signup, checking every 5 minutes" ❌
```

---

## ✅ Summary

| Field | Purpose | Example | Effect |
|-------|---------|---------|--------|
| `duration` | Main delay | `"1_day"` | Subtract 1 day |
| `time` | Additional delay | `"5_minutes"` | Subtract 5 more minutes |
| `custom_time` | Specific time | `"03:39"` | Set to 3:39 AM |
| `trigger_time` | Direction | `"after"` | Use subtract (look back) |

**Combined:**
```
duration: "1_day" + time: "5_minutes" + trigger_time: "after"
= Look for records from (1 day + 5 minutes) ago
= now() - 1 day - 5 minutes
```

Now the code is correct! 🎯