year = $year ?? Carbon::now()->year; } /** * Execute the job. */ public function handle(): void { $users = User::get(); $ld_day_total = Carbon::now()->month; // Khởi tạo phép hiện có bằng tháng hiện tại foreach ($users as $user) { // Check nhân viên nghỉ việc if ($user->is_separated) { continue; } // Kiểm tra xem dữ liệu của user này đã tồn tại cho năm hiện tại chưa $existingData = LeaveDays::where('ld_user_id', $user->id) ->where('ld_year', $this->year) ->first(); if ($existingData) { // Nếu dữ liệu đã tồn tại, bỏ qua user này continue; } // Kiểm tra dữ liệu của user này trong năm trước $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; $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"; } } // Tạo dữ liệu cho năm hiện tại LeaveDays::insert([ 'ld_user_id' => $user->id, 'ld_day_total' => $user->is_permanent ? $ld_day_total : 0, // Nếu là nhân viên mới, ko cấp phép 'ld_year' => $this->year, 'ld_additional_day' => $ld_additional_day, 'ld_note' => $ld_note, 'created_at' => now(), 'updated_at' => now(), ]); } } }