# Bulk Import Feature Implementation

## Overview
This document describes the implementation of the bulk import feature for generating and sending tickets massively from an Excel file.

## Features Implemented

### 1. Database Structure
- **Migrations**:
  - `2025_11_03_132929_create_ticket_pending_table`
  - `2025_12_14_000001_modify_ticket_pending_table_change_columns`
- **Table**: `ticket_pending`
- **Fields**:
  - `id` (Primary Key)
  - `ticket_name` (String) - Name of the ticket type
  - `event_ticket_id` (Foreign Key) - Reference to event_tickets table
  - `name` (String) - Name of the attendee
  - `member_id` (String) - Member ID / Socio number
  - `email` (String) - Email of the attendee
  - `status` (Enum: 'pending', 'generated', 'sent', 'error', default: 'pending')
  - `ticket_id` (Foreign Key, Nullable) - Reference to generated ticket
  - `pdf` (LongText, Nullable) - Base64 encoded PDF
  - `error_message` (Text, Nullable) - Error message if processing failed
  - `created_at` / `updated_at` (Timestamps)

### 2. Model
- **Model**: `App\TicketPending`
- **Location**: `app/TicketPending.php`
- **Features**: Mass assignable fields, proper table name, status casting

### 3. User Interface
- **Location**: `resources/views/livewire/admin/tickets/index.blade.php`
- **Features**:
  - Import button in the tickets admin interface
  - Modal dialog for file upload
  - File format instructions
  - Accepts .xlsx, .xls, .csv files
  - Maximum file size: 10MB

### 4. Import Controller
- **Location**: `app/Http/Controllers/Admin/TicketController.php`
- **Method**: `import(Request $request)`
- **Features**:
  - Excel file validation
  - Column header validation
  - Row data validation
  - Duplicate checking (section + row + seat combination)
  - Error reporting
  - Batch processing

### 5. Background Processing
- **Job**: `App\Jobs\ProcessPendingTickets`
- **Location**: `app/Jobs/ProcessPendingTickets.php`
- **Features**:
  - Processes 20 tickets at a time
  - Replicates the complete payment process from `Company\DashboardController@payment`
  - Creates: Reservation, Order, PaymentReceipt, PaymentReceiptsItems, Ticket
  - Generates PDF tickets
  - **Dispatches email jobs** (SendTicketEmail) with 10-second delay
  - Updates ticket status from 'pending' to 'sent'
  - Comprehensive error handling and logging

### 6. Scheduled Processing
- **Command**: `App\Console\Commands\ProcessPendingTicketsCommand`
- **Location**: `app/Console/Commands/ProcessPendingTicketsCommand.php`
- **Signature**: `tickets:process-pending`
- **Schedule**: Every 5 minutes (configured in `app/Console/Kernel.php`)

### 7. Routes
- **Route**: `POST /admin/tickets/import`
- **Name**: `admin.tickets.import`
- **Location**: `routes/web.php`

## Required Excel Format

The Excel file must contain the following columns:
- **ticket_name**: Exact name of the ticket type (must exist in event_tickets table)
- **name**: Name of the attendee
- **member_id**: Member ID / Socio number of the attendee
- **email**: Email of the attendee (where the ticket will be sent)

## Configuration Required

⚠️ **IMPORTANT**: The following values in `ProcessPendingTickets.php` need to be configured based on your system:

```php
// Lines 91-93 in ProcessPendingTickets.php
$event_id = 1; // Default event ID - should be configurable
$company_id = 1; // Default company ID - should be configurable
$person_id = 1; // Default person ID - should be configurable
```

These should be made configurable through:
- Environment variables
- Database settings
- Configuration files
- Or passed as parameters

## Event Ticket ID Resolution

The system validates `event_ticket_id` during the import process:

- **Validation**: The `ticket_name` column must match an existing ticket name in the `event_tickets` table
- **Import Process**:
  1. Checks if `ticket_name` exists in `event_tickets` for the specified event
  2. If found, stores the `event_ticket_id` in the `ticket_pending` table
  3. If not found, the row is skipped and an error is reported

- **Error Handling**: If no matching event_ticket is found, the import row fails with a descriptive error message indicating which ticket name was not found

## Usage Instructions

1. **Access**: Go to Admin → Tickets for any event
2. **Import**: Click the "Importar Boletas" button
3. **Upload**: Select an Excel file with the required format
4. **Process**: The system will validate and import the data into `ticket_pending` table
5. **Automatic Processing**: The scheduler will process 20 tickets every 5 minutes
6. **Monitor**: Check logs for processing status and any errors

## Dependencies

- Laravel Excel (maatwebsite/excel) - Already installed
- DomPDF - Already installed
- Laravel Queue system
- Laravel Scheduler (requires cron job setup)

## Manual Commands

```bash
# Process pending tickets manually
php artisan tickets:process-pending

# Run scheduler manually (for testing)
php artisan schedule:run

# Process queue jobs (including emails)
php artisan queue:work

# Process all jobs and stop when empty
php artisan queue:work --stop-when-empty
```

## Email Processing

The system automatically sends emails for each processed ticket:

- **Email Job**: Uses the existing `SendTicketEmail` job
- **Delay**: 10 seconds after ticket processing
- **Content**: Individual ticket email with PDF attachment
- **Queue Processing**: Requires `php artisan queue:work` to be running
- **Email Template**: Uses existing email templates from the original system

## Error Handling

- Import errors are displayed to the user immediately
- Processing errors are logged but don't stop the entire batch
- Individual ticket failures are logged with ticket ID for debugging

## Security Considerations

- File upload validation (type, size)
- Data validation for each row
- Duplicate prevention
- Error message sanitization

## Performance Notes

- Processes 20 tickets at a time to prevent memory issues
- Uses database transactions for data integrity
- Includes comprehensive logging for monitoring
- Designed to handle large batches efficiently