simedkom/app/Console/Commands/MigrateCompanyCommand.php

425 lines
15 KiB
PHP

<?php
namespace App\Console\Commands;
use App\Enums\DecisionAdmin;
use App\Enums\MediaClassification;
use App\Enums\MediaType;
use App\Enums\RoleEnum;
use App\Enums\VerificationStatus;
use App\Models\Company;
use App\Models\PartnerMedia;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
class MigrateCompanyCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'migrate:company';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Migrate companies, partner media, and all verification documents from legacy database';
/**
* Cache for migrated IDs with media to avoid redundant processing.
*/
private array $migratedIds = [];
/**
* Cache for migrated partner media IDs.
*/
private array $migratedPartnerMediaIds = [];
/**
* Execute the console command.
*/
public function handle()
{
$this->info('Starting optimized company migration with document support...');
$legacyConn = DB::connection('mysql_second');
$query = $legacyConn->table('companies')->whereNull('deleted_at');
$totalCount = $query->count();
if ($totalCount === 0) {
$this->warn('No companies found in legacy database.');
return;
}
$this->info("Found {$totalCount} legacy company records.");
// Pre-cache migrated IDs using their associated media records
$this->migratedIds = DB::table('media')
->where('model_type', Company::class)
->where('collection_name', 'companies')
->pluck('model_id')
->flip()
->all();
$this->migratedPartnerMediaIds = DB::table('media')
->where('model_type', PartnerMedia::class)
->where('collection_name', 'partnerMedia')
->pluck('model_id')
->flip()
->all();
$query->orderBy('id')->chunk(50, function ($chunk) {
foreach ($chunk as $legacy) {
$this->processCompany($legacy);
}
});
$this->newLine();
$this->info('Company migration completed successfully!');
}
/**
* Process a single legacy company record.
*/
private function processCompany($legacy): void
{
$idText = "[#{$legacy->id}]";
$idOutput = $legacy->deleted_at ? "<fg=red>{$idText}</>" : "<info>{$idText}</info>";
$this->output->write("{$idOutput} Processing: <comment>".Str::limit($legacy->name, 40).'</comment>... ');
try {
$legacyConn = DB::connection('mysql_second');
// Find user
$newUser = DB::table('users')->where('id', $legacy->enhancer)->first();
if (! $newUser) {
$newUser = DB::table('users')->where('email', $legacy->email)->first();
}
if (! $newUser) {
$this->output->writeln('<error>USER NOT FOUND</error>');
return;
}
$legacyUser = $legacyConn->table('users')->where('id', $legacy->enhancer)->first();
// 1. Update/Insert Company
DB::table('companies')->updateOrInsert(
['id' => $legacy->id],
[
'user_id' => $newUser->id,
'name' => $legacy->name,
'email' => $legacy->email,
'phone_number' => $legacy->phone_number,
'address' => $legacy->address,
'director_name' => $legacy->director,
'director_nik' => $legacy->nick_director,
'deed_incorporation' => Str::limit($legacy->deed_of_establishment, 150, ''),
'trade_license' => Str::limit($legacy->trade_license, 150, ''),
'tax_id_number' => Str::limit($legacy->tax_id_number, 150, ''),
'taxable_enterprise' => Str::limit($legacy->taxable_enterprise, 150, ''),
'annual_tax_return' => Str::limit($legacy->annual_tax_statement, 150, ''),
'domicile_certificate' => Str::limit($legacy->domicile, 150, ''),
'profile' => Str::limit($legacy->profile ?? '-', 150, ''),
'created_at' => $legacy->created_at ?? now(),
'updated_at' => $legacy->updated_at ?? now(),
'deleted_at' => $legacy->deleted_at,
]
);
// 2. Verification Request & Review
$this->handleVerification($legacy, $legacyUser, $newUser);
// 3. Partner Media
$this->handlePartnerMedia($legacy);
// 4. Media Documents Migration (Skip if already has media in 'companies' collection)
if (isset($this->migratedIds[$legacy->id])) {
$this->output->writeln('<info>DONE (SKIP DOCS)</info>');
return;
}
$company = Company::withTrashed()->find($legacy->id);
if ($company) {
$this->migrateAllDocuments($company, $legacy);
}
$this->output->writeln('<info>DONE + DOCS</info>');
} catch (\Exception $e) {
$this->output->writeln('<error>FAILED: '.$e->getMessage().'</error>');
}
}
/**
* Handle verification logic.
*/
private function handleVerification($legacy, $legacyUser, $newUser): void
{
$status = $this->mapVerificationStatus($legacyUser->status);
DB::table('verification_requests')->updateOrInsert(
['company_id' => $legacy->id],
[
'submitted_by' => $newUser->id,
'status' => $status,
'created_at' => $legacy->created_at ?? now(),
'updated_at' => $legacy->updated_at ?? now(),
]
);
$decision = $this->mapDecision($legacyUser->status);
if ($decision !== DecisionAdmin::NEED_REVISION->value) {
$verificationRequest = DB::table('verification_requests')->where('company_id', $legacy->id)->first();
$adminUser = User::role(RoleEnum::ADMINISTRATOR)->first();
if ($verificationRequest && $adminUser) {
DB::table('verification_reviews')->updateOrInsert(
['verification_request_id' => $verificationRequest->id],
[
'reviewer_id' => $adminUser->id,
'decision' => $decision,
'note' => $legacy->reject_message,
'created_at' => $legacy->validation_date ? Carbon::parse($legacy->validation_date)->setTime(23, 0, 0) : now(),
'updated_at' => $legacy->updated_at ?? now(),
]
);
}
}
}
/**
* Handle partner media.
*/
private function handlePartnerMedia($legacy): void
{
$legacyConn = DB::connection('mysql_second');
$legacyMediaList = $legacyConn->table('media')->where('company', $legacy->id)->get();
foreach ($legacyMediaList as $legacyMedia) {
DB::table('partner_media')->updateOrInsert(
['id' => $legacyMedia->id],
[
'company_id' => $legacy->id,
'name' => $legacyMedia->name,
'address' => $legacyMedia->address,
'link' => $this->extractMediaLink($legacyMedia->link),
'type' => $this->mapMediaType($legacyMedia->type),
'classification' => $this->mapMediaClassification($legacyMedia->classification),
'journalism_organization' => $legacyMedia->organization,
'press_council_certificate' => $legacyMedia->certificate,
'created_at' => $legacyMedia->created_at ?? now(),
'updated_at' => $legacyMedia->updated_at ?? now(),
'deleted_at' => $legacyMedia->deleted_at,
]
);
// Migrate documents for each partner media
if (! isset($this->migratedPartnerMediaIds[$legacyMedia->id])) {
$partnerMedia = PartnerMedia::withTrashed()->find($legacyMedia->id);
if ($partnerMedia) {
$this->migrateMediaDocuments($partnerMedia, $legacyMedia);
}
}
}
}
/**
* Migrate all company documents from S3.
*/
private function migrateAllDocuments(Company $company, $legacy): void
{
$docMapping = [
'doc_of_nick_director' => 'director_nik',
'doc_of_deed_of_establishment' => 'deed_incorporation',
'doc_of_trade_license' => 'trade_license',
'doc_of_tax_id_number' => 'tax_id_number',
'doc_of_taxable_enterprise' => 'taxable_enterprise',
'doc_of_annual_tax_statement' => 'annual_tax_return',
'doc_of_domicile' => 'domicile_certificate',
'doc_of_profile' => 'profile',
];
foreach ($docMapping as $legacyField => $docTypeSuffix) {
$legacyPath = trim($legacy->{$legacyField} ?? '');
if (empty($legacyPath) || $legacyPath === '-' || $legacyPath === 'no-image.png') {
continue;
}
// Path mapping: old-data/companies/ + path from db
$sourcePath = 'old-data/companies/'.$legacyPath;
$this->importOneDocument($company, $sourcePath, $docTypeSuffix, $legacy);
}
}
/**
* Import a single document to Media Library.
*/
private function importOneDocument(Company $company, string $sourcePath, string $docType, $legacy): void
{
$attempts = 0;
$maxAttempts = 3;
$exists = false;
while ($attempts < $maxAttempts) {
try {
$exists = Storage::disk('s3')->exists($sourcePath);
break;
} catch (\Exception $e) {
$attempts++;
usleep(200000);
}
}
if (! $exists) {
return;
}
try {
$company->addMediaFromDisk($sourcePath, 's3')
->withCustomProperties([
'feature' => 'companies',
'date' => Carbon::parse($legacy->created_at ?? now())->toDateString(),
'doc_type' => $docType, // Match CompanySaveService slug pattern
])
->preservingOriginal()
->toMediaCollection('companies', 's3');
} catch (\Exception $e) {
// Log quietly or handle error
}
}
/**
* Migrate all media documents from S3.
*/
private function migrateMediaDocuments(PartnerMedia $media, $legacyMedia): void
{
$docMapping = [
'doc_of_organization' => 'journalism-organization',
'doc_of_certificate' => 'press-council-certificate',
];
foreach ($docMapping as $legacyField => $docType) {
$legacyPath = trim($legacyMedia->{$legacyField} ?? '');
if (empty($legacyPath) || $legacyPath === '-' || $legacyPath === 'no-image.png') {
continue;
}
// Path mapping: old-data/media/ + path from db
$sourcePath = 'old-data/media/'.$legacyPath;
$this->importOneMediaDocument($media, $sourcePath, $docType, $legacyMedia);
}
}
/**
* Import a single media document to Media Library.
*/
private function importOneMediaDocument(PartnerMedia $media, string $sourcePath, string $docType, $legacyMedia): void
{
$attempts = 0;
$maxAttempts = 3;
$exists = false;
while ($attempts < $maxAttempts) {
try {
$exists = Storage::disk('s3')->exists($sourcePath);
break;
} catch (\Exception $e) {
$attempts++;
usleep(200000);
}
}
if (! $exists) {
return;
}
try {
$media->addMediaFromDisk($sourcePath, 's3')
->withCustomProperties([
'feature' => 'media',
'date' => Carbon::parse($legacyMedia->created_at ?? now())->toDateString(),
'doc_type' => $docType, // Match MediaSaveService slug pattern
])
->preservingOriginal()
->toMediaCollection('partnerMedia', 's3');
} catch (\Exception $e) {
// Log quietly or handle error
}
}
// ... mapping methods (mapVerificationStatus, mapDecision, mapMediaType, mapMediaClassification, extractMediaLink) remain as previously defined
private function mapVerificationStatus($legacyStatus): int
{
return match ((string) $legacyStatus) {
'0' => VerificationStatus::PENDING->value,
'1' => VerificationStatus::APPROVED->value,
'2' => VerificationStatus::REJECTED->value,
default => VerificationStatus::PENDING->value,
};
}
private function mapDecision($legacyStatus): int
{
return match ((string) $legacyStatus) {
'1' => DecisionAdmin::APPROVED->value,
'2' => DecisionAdmin::REJECTED->value,
default => DecisionAdmin::NEED_REVISION->value,
};
}
private function mapMediaType($legacyType): int
{
return match (strtolower($legacyType ?? '')) {
'online' => MediaType::ONLINE->value,
'cetak' => MediaType::PRINT->value,
'radio' => MediaType::RADIO->value,
'televisi' => MediaType::TELEVISION->value,
default => MediaType::ONLINE->value,
};
}
private function mapMediaClassification($legacyClass): int
{
return match (strtolower($legacyClass ?? '')) {
'lokal' => MediaClassification::LOCAL->value,
'regional' => MediaClassification::REGIONAL->value,
'nasional' => MediaClassification::NATIONAL->value,
default => MediaClassification::LOCAL->value,
};
}
private function extractMediaLink(?string $link): ?string
{
if (empty($link)) {
return null;
}
preg_match_all('/(https?:\/\/[^\s]+)/i', $link, $matches);
if (empty($matches[0])) {
return Str::limit($link, 255, '');
}
foreach ($matches[0] as $url) {
$url = rtrim($url, ',');
if (count($matches[0]) > 1 && (str_contains($url, 'google.') || str_contains($url, 'drive.') || str_contains($url, 'share.') || str_contains($url, 'bit.ly'))) {
continue;
}
return Str::limit($url, 255, '');
}
return Str::limit($matches[0][0], 255, '');
}
}