| | |
| | | protected string $rewards_table; |
| | | protected ReferralManager $referral_manager; |
| | | protected array $import_stats = []; |
| | | protected array $skipped_details = []; |
| | | |
| | | // CSV column mapping |
| | | protected array $column_map = [ |
| | |
| | | * |
| | | * @param string $file_path Path to the CSV file |
| | | * @param array $options Import options |
| | | * @return array Import results with stats and errors |
| | | * @return array|WP_Error Import results with stats and errors |
| | | */ |
| | | public function importFromCSV(string $file_path, array $options = []): array |
| | | public function importFromCSV(string $file_path, array $options = []): array|WP_Error |
| | | { |
| | | // Initialize stats |
| | | $this->import_stats = [ |
| | |
| | | return new WP_Error('invalid_csv', 'CSV file is empty or invalid'); |
| | | } |
| | | |
| | | // Trim whitespace from headers to handle inconsistent CSV formats |
| | | $headers = array_map('trim', $headers); |
| | | |
| | | // Map column indices |
| | | $column_indices = $this->mapColumnIndices($headers); |
| | | if (is_wp_error($column_indices)) { |
| | |
| | | return $column_indices; |
| | | } |
| | | |
| | | // Get Patient column index for error reporting |
| | | $patient_name_index = array_search('Patient', $headers); |
| | | |
| | | // Start transaction for data integrity |
| | | $this->wpdb->query('START TRANSACTION'); |
| | | |
| | | try { |
| | | // Process each row |
| | | $row_number = 1; // Header is row 1, data starts at row 2 |
| | | while (($row = fgetcsv($handle)) !== false) { |
| | | $row_number++; |
| | | $this->import_stats['total_rows']++; |
| | | |
| | | $result = $this->processSalesRow($row, $column_indices, [ |
| | |
| | | ]); |
| | | |
| | | if (is_wp_error($result)) { |
| | | $this->import_stats['errors'][] = [ |
| | | 'row' => $this->import_stats['total_rows'], |
| | | 'error' => $result->get_error_message() |
| | | $error_data = [ |
| | | 'row' => $row_number, |
| | | 'patient_guid' => trim($row[$column_indices['patient_guid']] ?? 'Unknown'), |
| | | 'patient_name' => trim($row[$patient_name_index] ?? 'Unknown'), |
| | | 'item' => trim($row[$column_indices['item']] ?? 'Unknown'), |
| | | 'reason' => $result->get_error_message() |
| | | ]; |
| | | |
| | | $this->import_stats['errors'][] = $error_data; |
| | | $this->import_stats['skipped']++; |
| | | } else { |
| | | $this->import_stats['processed']++; |