info('Starting optimized issue management migration...'); $legacyConn = DB::connection('mysql_second'); $query = $legacyConn->table('issue_management'); $totalCount = $query->count(); if ($totalCount === 0) { $this->warn('No issue management records found in legacy database.'); return; } $this->info("Found {$totalCount} legacy issue management records."); $query->orderBy('id')->chunk(50, function ($chunk) { foreach ($chunk as $legacy) { $this->processIssue($legacy); } }); $this->newLine(); $this->info('Issue management migration completed successfully!'); } /** * Process a single legacy issue management record. */ private function processIssue($legacy): void { $idText = "[#{$legacy->id}]"; $idOutput = $legacy->deleted_at ? "{$idText}" : "{$idText}"; $this->output->write("{$idOutput} Processing: ".Str::limit($legacy->description, 40).'... '); try { // Step 1: Insert/Update main record DB::table('issue_management')->updateOrInsert( ['id' => $legacy->id], [ 'media_monitoring_id' => $legacy->media_monitoring, 'location_id' => $legacy->locus, 'sub_location_id' => $legacy->sub_locus, 'classification_id' => $legacy->classification, 'sub_classification_id' => $legacy->sub_classification, 'issue' => $this->mapSentiment($legacy->issue), 'response' => $this->mapSentiment($legacy->response), 'description' => $legacy->description ?? '-', 'created_at' => $legacy->created_at ?? now(), 'updated_at' => $legacy->updated_at ?? now(), 'deleted_at' => $legacy->deleted_at, ] ); // Step 2: Handle Departments pivot mapping $this->handleDepartments($legacy); $this->output->writeln('DONE'); } catch (\Exception $e) { $this->output->writeln('FAILED: '.$e->getMessage().''); } } /** * Handle department pivot table mapping. */ private function handleDepartments($legacy): void { $agencyString = trim($legacy->agency); if (empty($agencyString)) { return; } $agencyNames = array_filter(array_map('trim', explode(',', $agencyString))); foreach ($agencyNames as $agencyName) { // Ensure department exists in master table $department = Department::firstOrCreate( ['name' => $agencyName], [ 'alias' => Str::limit($agencyName, 20, ''), 'is_active' => IsActive::ACTIVE, ] ); // Link to pivot table DB::table('department_issue_management')->updateOrInsert( [ 'department_id' => $department->id, 'issue_management_id' => $legacy->id, ], [ 'created_at' => now(), 'updated_at' => now(), ] ); } } /** * Map sentiment strings to IssueSentiment Enum values. */ private function mapSentiment(?string $legacyValue): int { return match (strtolower($legacyValue ?? '')) { 'positif' => IssueSentiment::POSITIVE->value, 'negatif' => IssueSentiment::NEGATIVE->value, 'netral' => IssueSentiment::NEUTRAL->value, 'krisis' => IssueSentiment::CRISIS->value, default => IssueSentiment::NEUTRAL->value, }; } }