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

183 lines
7.4 KiB
PHP

<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use App\Models\User;
use App\Models\Employee;
use App\Models\Shift;
use App\Models\AttendanceRecord;
use Carbon\Carbon;
class ImportLegacyRamesebData extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'import:legacy-rameseb';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Import users, employees, shifts, and attendances from legacy database rame_seb_legacy';
/**
* Execute the console command.
*/
public function handle()
{
$this->info("Checking legacy database setup...");
// Ensure legacy DB exists using the default connection (same host)
DB::connection('mysql')->statement('CREATE DATABASE IF NOT EXISTS rame_seb_legacy');
$sqlPath = base_path('rame_seb.sql');
if (file_exists($sqlPath)) {
$this->info("Importing rame_seb.sql structure and data into rame_seb_legacy (this may take a minute)...");
// Switch to the newly created legacy connection
$legacyDb = DB::connection('legacy');
// Only import if shifts table doesn't already exist to prevent re-running overhead on multiple tries
$tables = $legacyDb->select('SHOW TABLES LIKE "shifts"');
if (empty($tables)) {
$legacyDb->unprepared(file_get_contents($sqlPath));
$this->info("SQL import completed.");
} else {
$this->info("SQL structure already found, skipping raw dump import.");
}
} else {
$this->warn("Could not find rame_seb.sql in the project root!");
}
$this->newLine();
$this->info("Starting Legacy Data Migration...");
$legacyDb = DB::connection('legacy');
// 1. IMPORT SHIFTS (The 48 Shifts)
$this->info("Importing Shifts...");
$legacyShifts = $legacyDb->table('shifts')->get();
$this->withProgressBar($legacyShifts, function ($legacyShift) {
Shift::updateOrCreate(
['id' => $legacyShift->id],
[
'name' => $legacyShift->name,
'description' => "Legacy Shift {$legacyShift->code}",
'start_time' => $legacyShift->start_time,
'end_time' => $legacyShift->end_time,
'break_duration' => 0, // Fallback, could calculate if needed
'is_night_shift' => $legacyShift->start_time > $legacyShift->end_time ? true : false,
'status' => 'active',
'created_by' => 1,
// Retain ID to maintain relations
]
);
});
$this->newLine();
// 2. IMPORT USERS & EMPLOYEES
$this->info("Importing Users and Employees...");
$legacyUsers = $legacyDb->table('users')->get();
$employeeIdMap = []; // old_user_id => new_employee_id
$newUserIdMap = []; // old_user_id => new_user_id
$this->withProgressBar($legacyUsers, function ($legacyUser) use (&$employeeIdMap, &$newUserIdMap) {
// Create or update Auth User
$user = User::updateOrCreate(
['email' => $legacyUser->email],
[
'name' => trim($legacyUser->first_name . ' ' . $legacyUser->last_name),
'password' => Hash::make('123456'), // As requested
'type' => 'employee',
'is_enable_login' => 1,
'status' => 'active',
'created_by' => 1, // Fix for missing employees list visibility
]
);
// Assign standard Spatie employee role if available
$employeeRole = \Spatie\Permission\Models\Role::where('name', 'employee')->first();
if ($employeeRole) {
$user->assignRole($employeeRole);
}
// Create or update Employee profile
$employee = Employee::updateOrCreate(
['user_id' => $user->id],
[
'employee_id' => 'EMP-' . str_pad($legacyUser->id, 5, '0', STR_PAD_LEFT),
'phone' => $legacyUser->phone,
'address_line_1' => $legacyUser->address,
'emergency_contact_name' => $legacyUser->emergency_contact_name,
'emergency_contact_relationship' => $legacyUser->emergency_contact_relationship,
'emergency_contact_number' => $legacyUser->emergency_contact_phone,
'shift_id' => 1,
'date_of_joining' => $legacyUser->created_at ? Carbon::parse($legacyUser->created_at)->toDateString() : now()->toDateString(),
'employee_status' => 'active',
'created_by' => 1,
]
);
$employeeIdMap[$legacyUser->id] = $employee->id;
$newUserIdMap[$legacyUser->id] = $user->id;
});
$this->newLine();
// 3. IMPORT ATTENDANCES
$this->info("Importing Attendances...");
$legacyAttendances = $legacyDb->table('attendances')->get();
$this->withProgressBar($legacyAttendances, function ($legacyAttendance) use ($newUserIdMap) {
// Check if the related user was successfully ported over
if (!isset($newUserIdMap[$legacyAttendance->user_id])) {
return;
}
// attendance_records.employee_id is actually a foreign key to users.id inside the current schema.
$actualUserId = $newUserIdMap[$legacyAttendance->user_id];
// Transform Status
$isAbsent = $legacyAttendance->status === 'absent';
$isLate = ($legacyAttendance->late_hours > 0);
$newStatus = 'present';
if ($legacyAttendance->status === 'leave') $newStatus = 'on_leave';
if ($legacyAttendance->status === 'absent') $newStatus = 'absent';
if ($legacyAttendance->status === 'half-Day') $newStatus = 'half_day';
$clockIn = $legacyAttendance->check_in_time ? Carbon::parse($legacyAttendance->check_in_time)->format('H:i:s') : null;
$clockOut = $legacyAttendance->check_out_time ? Carbon::parse($legacyAttendance->check_out_time)->format('H:i:s') : null;
AttendanceRecord::updateOrCreate(
[
'employee_id' => $actualUserId,
'date' => $legacyAttendance->date,
],
[
'shift_id' => $legacyAttendance->shift_id ?? 1,
'clock_in' => $clockIn,
'clock_out' => $clockOut,
'total_hours' => $legacyAttendance->working_hours,
'break_hours' => $legacyAttendance->break_hours,
'overtime_hours' => $legacyAttendance->overtime_hours,
'is_late' => $isLate,
'is_absent' => $isAbsent,
'status' => $newStatus,
'created_by' => 1,
]
);
});
$this->newLine();
$this->info("Migration completed successfully.");
}
}