# Update Order Dates From CSV Command

## Overview

The `update:order-dates-from-csv` command allows you to update the `created_at` timestamps of existing orders based on approval dates from a CSV file. This command is designed to be used after orders have been created with `create:orders-from-csv` and you need to correct their creation dates.

## Usage

```bash
php artisan update:order-dates-from-csv {file} [--dry-run]
```

### Parameters

- `file`: Path to the CSV file containing order data with approval dates
- `--dry-run`: Optional flag to preview changes without applying them

## CSV Format

The CSV file must contain the same headers as the original order creation CSV, plus an additional header for the approval date:

```csv
اسم الجهة;محفظة المشاريع السابقة;المشروع المعتمد; عدد الأسر المستفيدة ;المنطقة;المركز;العدد;السعة;قيمة المشروع;تاريخ بداية المشروع;تاريخ الاعتماد
جمعية البر الخيرية;محفظة المانح الأول;محطة;100;الرياض;مركز الملك عبدالله;5;1000;50000;01/01/23;27/10/22
```

### Required Headers

- `اسم الجهة` - Association name (used for matching)
- `محفظة المشاريع السابقة` - Donor financial portfolio name (used for matching)
- `المشروع المعتمد` - Order type (used for matching)
- ` عدد الأسر المستفيدة ` - Number of families (used for matching)
- `تاريخ الاعتماد` - **NEW**: Approval date in DD/MM/YY format (e.g., "27/10/22")

### Date Format

The approval date (`تاريخ الاعتماد`) must be in DD/MM/YY format:
- `27/10/22` = October 27, 2022
- `15/11/23` = November 15, 2023

The command automatically converts 2-digit years:
- Years 00-50 are interpreted as 2000-2050
- Years 51-99 are interpreted as 1951-1999

## Order Matching Logic

The command finds orders using the following criteria:
1. **Association**: Exact match by name, then partial match
2. **Order Type**: Mapped from Arabic to system constants
3. **Number of Families**: Exact match (if provided)
4. **Donor Portfolio**: Exact match by name (if provided)

### Safety Features

The command implements several safety measures:

1. **Cautious Matching**: 
   - If exactly 1 order matches → Update proceeds
   - If 0 orders match → Logs warning, skips row
   - If 2+ orders match → Logs warning, skips row for manual review

2. **Dry Run Mode**: Use `--dry-run` to preview changes without applying them

3. **Comprehensive Logging**: All operations are logged with detailed information

4. **Transaction Safety**: Each update is wrapped in a database transaction

## Example Usage

### Preview Changes (Dry Run)
```bash
php artisan update:order-dates-from-csv /path/to/orders_with_dates.csv --dry-run
```

### Apply Changes
```bash
php artisan update:order-dates-from-csv /path/to/orders_with_dates.csv
```

## Sample Output

```
Starting order date updates from CSV...
File: /path/to/orders_with_dates.csv
CSV Headers found: اسم الجهة, محفظة المشاريع السابقة, المشروع المعتمد, عدد الأسر المستفيدة, تاريخ الاعتماد
Found 10 rows to process
Row 2: Updated Order ID 123 created_at from '2024-08-20 10:30:00' to '2022-10-27 00:00:00'
Row 3: Multiple orders found (2) for association 'جمعية البر', type 'محطة' - SKIPPING for safety
  Order IDs: 124, 125
  Manual review required for approval date: 15/11/22
Row 4: Updated Order ID 126 created_at from '2024-08-20 11:15:00' to '2022-11-15 00:00:00'

Order date update completed!
Updated: 8 orders
Multiple matches (skipped): 1 rows
No matches found: 1 rows
Skipped (invalid data): 0 rows

WARNING: 1 rows had multiple matching orders and were skipped for safety.
Please review the log output above for details on which orders need manual review.
```

## Error Handling

The command handles various error scenarios:

1. **Missing Files**: Clear error message if CSV file doesn't exist
2. **Invalid Headers**: Warns about missing headers, requires approval date header
3. **Invalid Dates**: Validates date format and skips invalid dates
4. **Missing Data**: Skips rows with missing required fields
5. **Database Errors**: Rolls back transactions on database errors

## Manual Review Cases

When the command encounters multiple matching orders, it logs details like:
```
Row 3: Multiple orders found (2) for association 'جمعية البر', type 'محطة' - SKIPPING for safety
  Order IDs: 124, 125
  Manual review required for approval date: 15/11/22
```

To resolve these manually:
1. Identify which of the listed Order IDs should be updated
2. Update directly in the database or through FilamentPHP admin panel
3. Use the approval date provided in the log message

## Security Considerations

- Command requires appropriate Laravel permissions (inherent in Artisan commands)
- All database operations use transactions for data integrity
- Input validation prevents invalid date formats
- Cautious matching prevents accidental updates to wrong orders
- Comprehensive audit trail through detailed logging

## Troubleshooting

### Common Issues

1. **"Required header 'تاريخ الاعتماد' not found"**
   - Ensure CSV contains the approval date header
   - Check for encoding issues (file should be UTF-8)

2. **"Invalid date format"**
   - Ensure dates are in DD/MM/YY format
   - Check for extra spaces or special characters

3. **"No matching orders found"**
   - Verify association names match exactly
   - Check that orders were created with the original CSV
   - Verify donor portfolio names match

4. **"Multiple orders found - SKIPPING"**
   - Review duplicate orders manually
   - Consider adding more specific matching criteria
   - Update individual orders through admin panel

### Best Practices

1. Always use `--dry-run` first to preview changes
2. Keep a backup of original data before running updates
3. Review the command output carefully for any warnings
4. Handle multiple match cases manually for accuracy
5. Test with a small subset of data first
