month = $month ?? Carbon::now()->month; $this->year = $year ?? Carbon::now()->year; } public function handle(): void { $users = User::get(); foreach ($users as $user) { // Nếu là nhân viên chưa chính thức, ko cộng phép if (!$user->is_permanent) { continue; } // Nếu là nhân viên nghỉ việc, ko cộng phép if ($user->is_separated) { continue; } $leaveDay = LeaveDays::where('ld_user_id', $user->id) ->where('ld_year', $this->year) ->first(); if (!$leaveDay) { // Nếu chưa có dữ liệu năm hiện tại, tạo mới $previousYearData = LeaveDays::where('ld_user_id', $user->id) ->where('ld_year', $this->year - 1) ->first(); $ld_additional_day = 0; $ld_note = ''; if ($previousYearData) { $ld_additional_day = $previousYearData->ld_day_total + $previousYearData->ld_additional_day + $previousYearData->ld_special_leave_day; $totalLeaveDaysByMonth = Notes::join('categories', function ($join) { $join->on('notes.n_time_type', '=', 'categories.c_code') ->where('categories.c_type', 'TIME_TYPE'); }) ->select( DB::raw('notes.n_user_id as n_user_id'), DB::raw('notes.n_year as year'), DB::raw('SUM(categories.c_value) as leave_days') ) ->where('notes.n_year', $this->year - 1) ->where('notes.n_user_id', $user->id) ->where('notes.n_reason', 'ONLEAVE') ->groupBy(DB::raw('notes.n_year')) ->first(); if ($totalLeaveDaysByMonth) { $ld_additional_day = $ld_additional_day - $totalLeaveDaysByMonth->leave_days; if ($ld_additional_day < 0) { $ld_additional_day = 0; } } if ($ld_additional_day > 0) { $ld_note = "Cộng " . $ld_additional_day . " ngày phép tồn năm trước. \n"; } } $leaveDay = new LeaveDays([ 'ld_user_id' => $user->id, 'ld_day_total' => $this->month, // Số ngày phép bằng tháng hiện tại 'ld_year' => $this->year, 'ld_additional_day' => $ld_additional_day, 'ld_note' => $ld_note, 'ld_special_leave_day' => 0, ]); $leaveDay->save(); } else { // Check có phải là nhân viên chính thức trong năm nay (Nhân viên mới) if ($user->permanent_date && $user->permanent_date !== '0000-00-00') { $permenantYear = Carbon::parse($user->permanent_date)->year; if ($permenantYear === $this->year) { $permanentCategory = Category::where('c_type', 'PERMANENT_ONLEAVE')->where('c_code', "PERMANENT")->first(); $permanentDefault = (int) $permanentCategory->c_value; // Ngày phép khi thành nv chính thức $permanentMonth = Carbon::parse($user->permanent_date)->month; if ($this->month > $leaveDay->ld_day_total - ($permanentDefault - $permanentMonth)) { $leaveDay->ld_day_total += self::ONLEAVE_PER_MONTH; $leaveDay->save(); } } } // Kiểm tra nếu số ngày phép hiện tại nhỏ hơn tháng hiện tại (Nhân viên cũ) if ($leaveDay->ld_day_total < $this->month) { // Cộng mỗi tháng 1 ngày phép cho nhân viên $leaveDay->ld_day_total += self::ONLEAVE_PER_MONTH; $leaveDay->save(); } } } } }