Files
HRM-System/app/Console/Commands/SyncLegacyDepartments.php
2026-04-20 00:20:10 +08:00

88 lines
3.5 KiB
PHP

<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use App\Models\User;
use App\Models\Employee;
class SyncLegacyDepartments extends Command
{
protected $signature = 'import:legacy-departments';
protected $description = 'Sync legacy departments and designations to the local database, and map employees';
public function handle()
{
$this->info("Importing Legacy Departments...");
// 1. Fetch Legacy Departments
$legacyDepts = DB::connection('legacy')->table('departments')->get();
foreach ($legacyDepts as $dept) {
DB::table('departments')->updateOrInsert(
['id' => $dept->id], // Preserving ID mapping is critical for designations and employee foreign keys
[
'name' => $dept->name,
'branch_id' => 1, // Defaulting to Main Branch
'description' => 'Imported from legacy',
'status' => 'active',
'created_by' => 1,
'created_at' => now(),
'updated_at' => now(),
]
);
}
$this->info("Synced " . count($legacyDepts) . " departments.");
// 2. Fetch Legacy Designations
$this->info("Importing Legacy Designations...");
$legacyDesigs = DB::connection('legacy')->table('designations')->get();
foreach ($legacyDesigs as $desig) {
DB::table('designations')->updateOrInsert(
['id' => $desig->id], // Preserving ID for employee foreign mapping
[
'name' => $desig->name,
'department_id' => $desig->department_id,
'description' => 'Imported from legacy',
'status' => 'active',
'created_by' => 1,
'created_at' => now(),
'updated_at' => now(),
]
);
}
$this->info("Synced " . count($legacyDesigs) . " designations.");
// 3. Update Employees
$this->info("Remapping Employee Profiles...");
// Legacy system stored the roles directly on the users table
$legacyUsers = DB::connection('legacy')->table('users')->get();
$mappedCount = 0;
foreach ($legacyUsers as $legacyUser) {
if (!$legacyUser || !isset($legacyUser->email)) continue;
$localUser = User::where('email', $legacyUser->email)->first();
if (!$localUser) continue;
// Map the imported departments/designations to the mapped Employee
$payload = [
'department_id' => $legacyUser->team_id ?? $legacyUser->department_id ?? null,
'designation_id' => $legacyUser->designation_id ?? null,
'date_of_birth' => $legacyUser->dob ? \Carbon\Carbon::parse($legacyUser->dob)->toDateString() : null,
'gender' => $legacyUser->gender ?? null,
'branch_id' => 1 // Legacy default
];
// If the legacy profile had an authentic string ID like SEB2018-2008T, override the generic EMP-XXXXX ID
if (!empty($legacyUser->code)) {
$payload['employee_id'] = $legacyUser->code;
}
Employee::where('user_id', $localUser->id)->update($payload);
$mappedCount++;
}
$this->info("Successfully mapped $mappedCount employee profiles to their native roles!");
}
}