startOfMonth()->timestamp; // 2. 业务状态校验 (提出来的校验逻辑) $calendar = DB::table('calendar') ->where('del_time', 0) ->where('time', $monthStart) ->first(); if (!$calendar) return [false, '当月日历未配置']; $hasWorkDays = DB::table('calendar_details') ->where('del_time', 0) ->where('calendar_id', $calendar->id) ->where('is_work', 1) ->exists(); if (!$hasWorkDays) return [false, '当月无工作日,无法生成']; $key = self::job_name . $data['month']; $data['lock_key'] = $key; list($status,$msg) = $this->limitingSendRequest($key); if(! $status) return [false, '该月设备数据已在后台处理,请勿重复操作']; ProcessDataJob::dispatch($data)->onQueue(self::job_name); return [true, '任务已提交至后台处理,请稍后查看']; } public function delTableKey($key){ $this->dellimitingSendRequest($key); } public function doGenerate(string $month) { $monthStart = Carbon::createFromFormat('Y-m', $month)->startOfMonth()->timestamp; $monthEnd = Carbon::createFromFormat('Y-m', $month)->endOfMonth()->timestamp; $calendar = DB::table('calendar')->where('del_time', 0)->where('time', $monthStart)->first(); $workDays = DB::table('calendar_details') ->where('del_time', 0) ->where('calendar_id', $calendar->id) ->where('is_work', 1) ->orderBy('time') ->pluck('time') ->toArray(); // 获取当月启用的研发项目 $items = DB::table('item') ->where('del_time', 0) ->where('is_use', 1) ->where('start_time', '<=', $monthEnd) ->where('end_time', '>=', $monthStart) ->get(); if ($items->isEmpty()) return; $itemIds = $items->pluck('id')->toArray(); // 删除当月该设备类型(type=2)的老数据 $rds = DB::table('rd') ->where('del_time', 0) ->where('type', RD::type_two) ->whereIn('item_id', $itemIds) ->whereBetween('order_time', [$monthStart, $monthEnd]) ->pluck('id') ->toArray(); if (!empty($rds)) { DB::table('rd_details')->whereIn('rd_id', $rds)->delete(); DB::table('rd')->whereIn('id', $rds)->delete(); } // 直接获取所有有效的设备档案ID $device_ids = DB::table('device') ->where('del_time', 0) ->pluck('id') ->toArray(); foreach ($device_ids as $device_id) { // 为每个设备生成月度工时单 $this->generateDeviceMonth($device_id, $items, $workDays, $calendar); } } protected function generateDeviceMonth(int $device_id, $items, array $workDays, $calendar) { // 获取该设备在当月的总分配工时配置 $deviceMonth = DB::table('device_details') ->where('del_time', 0) ->where('device_id', $device_id) ->where('time', $calendar->time) ->first(); if (!$deviceMonth || $deviceMonth->total_hours_2 <= 0) return; // 1. 月总工时取整为满小时 (60的倍数) $totalMinutes = intval(round($deviceMonth->total_hours_2 * 60) / 60) * 60; // 筛选出在该设备有效周期内且在进行的研发项目 $validDays = []; foreach ($workDays as $day) { $dayItems = []; foreach ($items as $item) { if ($day >= $item->start_time && $day <= $item->end_time) { $dayItems[] = $item; } } if (!empty($dayItems)) $validDays[$day] = $dayItems; } if (empty($validDays)) return; // 2. 随机化每日总工时分布 (例如 184小时分到23天,每天8小时) $daysCount = count($validDays); $avgDailyMinutes = intval(floor($totalMinutes / $daysCount) / 60) * 60; $remainderMinutes = $totalMinutes - ($avgDailyMinutes * $daysCount); $dailyMinutesMap = []; foreach (array_keys($validDays) as $day) { $dailyMinutesMap[$day] = $avgDailyMinutes; } if ($remainderMinutes > 0) { $extraHours = $remainderMinutes / 60; $dayKeys = array_keys($validDays); shuffle($dayKeys); for ($i = 0; $i < $extraHours; $i++) { $targetDay = $dayKeys[$i % $daysCount]; if ($dailyMinutesMap[$targetDay] < 480) { // 单日最高 8 小时 $dailyMinutesMap[$targetDay] += 60; } else { $extraHours++; } } } // 3. 遍历日期并“离散化”分配项目工时 foreach ($validDays as $day => $dayItems) { $dailyMinutes = $dailyMinutesMap[$day]; if ($dailyMinutes <= 0) continue; $totalHoursToday = $dailyMinutes / 60; // 今天要分配的总小时数 // 初始化每个项目的分钟数容器 $projectMinutes = []; foreach ($dayItems as $idx => $item) { $projectMinutes[$idx] = 0; } // 获取项目索引并打乱,增加公平性 $itemIndexes = array_keys($dayItems); // --- 核心离散逻辑:随机发牌法 --- for ($h = 0; $h < $totalHoursToday; $h++) { // 如果项目很多(比如20个),这里每次随机选一个 // 结果会非常离散:可能8小时分给了8个不同的项目,每个项目1小时 $randomIndex = $itemIndexes[array_rand($itemIndexes)]; $projectMinutes[$randomIndex] += 60; } // 4. 执行生成 foreach ($dayItems as $idx => $item) { if (isset($projectMinutes[$idx]) && $projectMinutes[$idx] > 0) { // 调用之前定义的 createRd 写入数据库 $this->createRd($item->id, $day, $projectMinutes[$idx], $device_id); } } } } protected function createRd(int $itemId, int $dayTime, int $minutes, int $device_id) { $dayStart = Carbon::createFromTimestamp($dayTime)->setTime(8, 0); $lunchStart = Carbon::createFromTimestamp($dayTime)->setTime(11, 30); $lunchEnd = Carbon::createFromTimestamp($dayTime)->setTime(12, 0); $dayEnd = Carbon::createFromTimestamp($dayTime)->setTime(16, 30); $availableMinutes = 480; $minutes = min($minutes, $availableMinutes); $maxOffset = $availableMinutes - $minutes; $randomOffset = (intval($maxOffset / 30) > 0) ? mt_rand(0, intval($maxOffset / 30)) * 30 : 0; $start = $dayStart->copy()->addMinutes($randomOffset); $end = $start->copy(); $remaining = $minutes; if ($start->lt($lunchStart)) { $morningLeft = $lunchStart->diffInMinutes($start); if ($remaining <= $morningLeft) { $end->addMinutes($remaining); } else { $remaining -= $morningLeft; $end = $lunchEnd->copy()->addMinutes($remaining); } } else { $end->addMinutes($remaining); } if ($end->gt($dayEnd)) { $end = $dayEnd->copy(); } $crtTime = Carbon::createFromTimestamp($dayTime)->setTime(16, 30)->addSeconds(mt_rand(0, 1800))->timestamp; $orderNumber = 'DEV' . date('Ymd', $dayTime) . mt_rand(1000, 9999) . substr(uniqid(), -3); $rdId = DB::table('rd')->insertGetId([ 'crt_time' => $crtTime, 'order_time' => $dayTime, 'item_id' => $itemId, 'start_time_hour' => $start->hour, 'start_time_min' => $start->minute, 'end_time_hour' => $end->hour, 'end_time_min' => $end->minute, 'total_hours' => $minutes, 'order_number' => $orderNumber, 'type' => RD::type_two, // 设备工时单类型为 2 'del_time' => 0 ]); DB::table('rd_details')->insert([ 'rd_id' => $rdId, 'data_id' => $device_id, // 存储设备ID 'type' => RD::type_two, // 类型为 2 'crt_time' => $crtTime, 'upd_time' => $crtTime, 'del_time' => 0 ]); } }