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

87 lines
3.0 KiB
PHP

<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Models\User;
use App\Models\AttendanceRecord;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
class SyncLegacyDailyShifts extends Command
{
protected $signature = 'import:legacy-shifts {start_date?} {end_date?}';
protected $description = 'Sweeps legacy employee_daily_shifts to synchronize proper working/rest day tracking into the core attendance engine natively.';
public function handle()
{
$startDate = $this->argument('start_date') ?: '2026-01-11';
$endDate = $this->argument('end_date') ?: '2026-01-25';
$this->info("Initializing Legacy Shift Matrix Sync: $startDate to $endDate");
$employees = User::where('type', 'employee')->whereHas('employee')->get();
$bar = $this->output->createProgressBar(count($employees));
$legacyUsers = DB::connection('legacy')->table('users')->get(['id', 'name']);
$newUserIdMap = [];
foreach ($legacyUsers as $lu) {
$matchingLocal = User::where('name', $lu->name)->first();
if ($matchingLocal) {
// Key = local user ID, Value = legacy user ID
$newUserIdMap[$matchingLocal->id] = $lu->id;
}
}
foreach ($employees as $user) {
if (!isset($newUserIdMap[$user->id])) {
$bar->advance();
continue;
}
$legacyUserId = $newUserIdMap[$user->id];
$currentDate = Carbon::parse($startDate);
$periodEndObj = Carbon::parse($endDate);
while ($currentDate->lte($periodEndObj)) {
$dateString = $currentDate->toDateString();
// 1. Fetch the master schedule template from the old legacy DB
$shiftRecord = DB::connection('legacy')
->table('employee_daily_shifts')
->where('user_id', $legacyUserId)
->where('date', $dateString)
->first();
// If shift_id is physically blank/null, they are totally OFF.
$isRestDay = (!$shiftRecord || empty($shiftRecord->shift_id));
if ($isRestDay) {
// Update or Force-create an explicit RD token in our local Database
AttendanceRecord::updateOrCreate(
[
'employee_id' => $user->id,
'date' => $dateString
],
[
'is_rest_day' => true,
'is_absent' => false,
'status' => 'present', // Bypass penalty
'created_by' => 1
]
);
}
$currentDate->addDay();
}
$bar->advance();
}
$bar->finish();
$this->info("\nMatrix Sync Complete. Physical Rest Days locked locally.");
}
}