| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277 |
- <?php
- namespace App\Service;
- use Carbon\Carbon;
- use Illuminate\Support\Facades\DB;
- class RdGenerateService extends Service
- {
- public function generate(array $data)
- {
- if (empty($data['month'])) {
- return [false, '请选择生成研发人员工时单年月'];
- }
- try {
- DB::transaction(function () use ($data) {
- $this->doGenerate($data['month']);
- });
- } catch (\Throwable $e) {
- return [false, $e->getMessage()];
- }
- return [true, ''];
- }
- protected 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('time', $monthStart)
- ->first();
- if (!$calendar) {
- throw new \Exception('当月日历未配置');
- }
- // 工作日
- $workDays = DB::table('calendar_details')
- ->where('calendar_id', $calendar->id)
- ->where('is_work', 1)
- ->orderBy('time')
- ->pluck('time')
- ->toArray();
- if (empty($workDays)) {
- throw new \Exception('当月无工作日');
- }
- // 启用项目
- $items = DB::table('item')
- ->where('is_use', 1)
- ->where('start_time', '<=', $monthEnd)
- ->where('end_time', '>=', $monthStart)
- ->get();
- // 删除当月所有项目的老数据
- $itemIds = $items->pluck('id')->toArray();
- if (!empty($itemIds)) {
- $rds = DB::table('rd')
- ->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
- $employeeIds = DB::table('item_details')
- ->whereIn('item_id', $itemIds)
- ->where('type', 1)
- ->pluck('data_id')
- ->unique()
- ->toArray();
- // 按员工生成当月工时单
- foreach ($employeeIds as $employeeId) {
- $this->generateEmployeeMonth($employeeId, $items, $workDays, $calendar);
- }
- }
- /**
- * 按员工生成当月工时单,严格保证总工时匹配(通过将分配分钟数取整到 5 的倍数实现)
- */
- protected function generateEmployeeMonth(int $employeeId, $items, array $workDays, $calendar)
- {
- $employeeMonth = DB::table('employee_details')
- ->where('employee_id', $employeeId)
- ->where('time', $calendar->time)
- ->first();
- if (!$employeeMonth || $employeeMonth->total_hours_2 <= 0) {
- return;
- }
- // 员工总分钟数:这里保留了浮点数取整可能带来的微小误差,但这是上游数据决定的
- $totalMinutes = (int)round($employeeMonth->total_hours_2 * 60);
- // --- 核心修复 1: 确保总分钟数是 5 的倍数,否则损失这 $1-4$ 分钟的精度 ---
- // 这是为了让后续的平均分配和余数计算能确保最终分配的总和是 5 的倍数
- $totalMinutes = intval($totalMinutes / 5) * 5;
- // --- 核心修复 1 结束 ---
- $dayMaxMinutes = 510 - 30; // 每天最大分钟数(扣午休)
- // 员工参与的项目
- $employeeItems = [];
- foreach ($items as $item) {
- $exists = DB::table('item_details')
- ->where('item_id', $item->id)
- ->where('type', 1)
- ->where('data_id', $employeeId)
- ->exists();
- if ($exists) $employeeItems[] = $item;
- }
- if (empty($employeeItems)) return;
- // 所有有效工作日(员工参与项目的周期内)
- $validDays = [];
- foreach ($workDays as $day) {
- $dayItems = [];
- foreach ($employeeItems as $item) {
- if ($day >= $item->start_time && $day <= $item->end_time) {
- $dayItems[] = $item;
- }
- }
- if (!empty($dayItems)) {
- $validDays[$day] = $dayItems;
- }
- }
- if (empty($validDays)) return;
- // 每天大约的分钟数
- $avgDailyMinutes = floor($totalMinutes / count($validDays));
- $remainder = $totalMinutes - $avgDailyMinutes * count($validDays);
- foreach ($validDays as $day => $dayItems) {
- $dailyMinutes = $avgDailyMinutes;
- // 最后一天补齐余数
- if ($day === array_key_last($validDays)) {
- $dailyMinutes += $remainder;
- }
- // 随机给当天项目分配分钟数
- $slots = [];
- $remaining = $dailyMinutes;
- $numItems = count($dayItems);
- for ($i = 0; $i < $numItems; $i++) {
- if ($i === $numItems - 1) {
- // 最后一个项目:分配所有剩余时间
- $slotMinutes = $remaining;
- } else {
- // 随机 ±20% 分配
- $max = floor($remaining * 0.8);
- $slotMinutes = mt_rand(1, max(1, $max));
- // --- 核心修复 2: 确保随机分配的工时是 5 的倍数 ---
- $slotMinutes = intval($slotMinutes / 5) * 5;
- // 确保至少是 5 分钟的倍数(如果剩余时间允许)
- $slotMinutes = max(0, $slotMinutes);
- // --- 核心修复 2 结束 ---
- }
- $slots[] = $slotMinutes;
- $remaining -= $slotMinutes;
- }
- // 调整最后剩余:将所有因为取整损失的分钟数,都加给最后一个项目
- if ($remaining > 0) {
- $slots[$numItems - 1] += $remaining;
- }
- // 确保最后一个项目的工时也是 5 的倍数(因为 $dailyMinutes$ 是 5 的倍数,这一步理论上是确保的)
- // 我们需要对最终的 $slots[$numItems - 1] 再次取整,以处理可能的小数取整误差
- $slots[$numItems - 1] = intval($slots[$numItems - 1] / 5) * 5;
- // 创建工时单
- foreach ($dayItems as $idx => $item) {
- // 仅对分配到的工时大于 0 的项目创建记录
- if ($slots[$idx] > 0) {
- $this->createRd($item->id, $day, $slots[$idx], $employeeId);
- }
- }
- }
- }
- /**
- * 创建单条研发工时单
- * 由于传入的 $minutes 已经是 5 的倍数,此方法保证 total_hours 与 $start/$end 严格匹配。
- */
- protected function createRd(int $itemId, int $dayTime, int $minutes, int $employeeId)
- {
- $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);
- $morningMinutes = $lunchStart->diffInMinutes($dayStart);
- $afternoonMinutes = $dayEnd->diffInMinutes($lunchEnd);
- $availableMinutes = $morningMinutes + $afternoonMinutes;
- // 保证总分钟数不超过可用时间
- $minutes = min($minutes, $availableMinutes);
- // 随机生成 start 时间,整5分钟
- if ($minutes <= $morningMinutes) {
- $maxOffset = $morningMinutes - $minutes;
- // $dayStart (8:00) 已经是 5 的倍数
- $offset = 5 * mt_rand(0, intval($maxOffset / 5));
- $start = $dayStart->copy()->addMinutes($offset);
- } elseif ($minutes <= $afternoonMinutes) {
- $maxOffset = $afternoonMinutes - $minutes;
- $offset = 5 * mt_rand(0, intval($maxOffset / 5));
- $start = $lunchEnd->copy()->addMinutes($offset);
- } else {
- // 分两段:上午尽量满,剩余在下午
- $start = $dayStart->copy();
- }
- // 计算结束时间,跨午休自动跳过
- $remaining = $minutes;
- if ($start->lt($lunchStart) && $remaining > $morningMinutes - $start->diffInMinutes($dayStart)) {
- $usedMorning = $morningMinutes - $start->diffInMinutes($dayStart);
- $remaining -= $usedMorning;
- $end = $lunchEnd->copy()->addMinutes($remaining);
- } else {
- $end = $start->copy()->addMinutes($remaining);
- }
- // 调整到整5分钟
- // 🚨 这一步保留,但由于 $minutes 是 5 的倍数,这里的取整不会导致 $end - $start$ 发生变化
- $start->minute = intval($start->minute / 5) * 5;
- $end->minute = intval($end->minute / 5) * 5;
- // crt_time 16:30 ~ 17:00
- $crtTime = Carbon::createFromTimestamp($dayTime)
- ->setTime(16, 30)
- ->addSeconds(mt_rand(0, 30*60))
- ->timestamp;
- $dayPrefix = date('Ymd', $dayTime);
- $orderNumber = 'RD' . $dayPrefix . 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,
- // 重点:使用分配好的 $minutes,现在它已经是 5 的倍数,与 $start/$end$ 匹配
- 'total_hours' => $minutes,
- 'order_number' => $orderNumber,
- 'type' => 1
- ]);
- DB::table('rd_details')->insert([
- 'rd_id' => $rdId,
- 'data_id' => $employeeId,
- 'type' => 1,
- 'crt_time' => $crtTime,
- 'upd_time' => $crtTime,
- ]);
- }
- }
|