| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282 |
- <?php
- namespace App\Service;
- use App\Model\RD;
- 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;
- // 1. 获取日历配置
- $calendar = DB::table('calendar')
- ->where('del_time', 0)
- ->where('time', $monthStart)
- ->first();
- if (!$calendar) throw new \Exception('当月日历未配置');
- $workDays = DB::table('calendar_details')
- ->where('del_time', 0)
- ->where('calendar_id', $calendar->id)
- ->where('is_work', 1)
- ->orderBy('time')
- ->pluck('time')
- ->toArray();
- if (empty($workDays)) throw new \Exception('当月无工作日');
- // 2. 获取相关项目并清理旧数据
- $items = DB::table('item')
- ->where('del_time', 0)
- ->where('is_use', 1)
- ->where('start_time', '<=', $monthEnd)
- ->where('end_time', '>=', $monthStart)
- ->orderBy('id','desc')
- ->get();
- $itemIds = $items->pluck('id')->toArray();
- if (!empty($itemIds)) {
- $rds = DB::table('rd')
- ->where('del_time', 0)
- ->where('type', RD::type_one)
- ->whereIn('item_id', $itemIds)
- ->whereBetween('order_time', [$monthStart, $monthEnd])
- ->pluck('id')
- ->toArray();
- if (!empty($rds)) {
- foreach (array_chunk($rds, 1000) as $chunk) {
- DB::table('rd_details')->whereIn('rd_id', $chunk)->delete();
- DB::table('rd')->whereIn('id', $chunk)->delete();
- }
- }
- }
- // 3. 预加载所有员工关联关系
- $itemDetails = DB::table('item_details')
- ->where('del_time', 0)
- ->whereIn('item_id', $itemIds)
- ->where('type', 1)
- ->get()
- ->groupBy('data_id');
- $employeeIds = $itemDetails->keys()->toArray();
- // 4. 预加载员工月工时配置
- $employeeMonths = DB::table('employee_details')
- ->where('del_time', 0)
- ->whereIn('employee_id', $employeeIds)
- ->where('time', $calendar->time)
- ->get()
- ->keyBy('employee_id');
- $pendingRds = [];
- $rdToEmployeeMap = [];
- // 5. 内存循环处理
- foreach ($employeeIds as $employeeId) {
- $empMonthConfig = $employeeMonths->get($employeeId);
- if (!$empMonthConfig || $empMonthConfig->total_hours_2 <= 0) continue;
- $myProjectIds = $itemDetails->get($employeeId)->pluck('item_id')->toArray();
- $employeeItems = $items->whereIn('id', $myProjectIds);
- $this->buildEmployeeRds(
- $employeeId,
- $employeeItems,
- $workDays,
- $empMonthConfig,
- $pendingRds,
- $rdToEmployeeMap
- );
- }
- // 6. 批量写入
- if (!empty($pendingRds)) {
- foreach (array_chunk($pendingRds, 1000) as $chunk) {
- DB::table('rd')->insert($chunk);
- }
- $insertedRds = DB::table('rd')
- ->whereIn('order_number', array_keys($rdToEmployeeMap))
- ->select('id', 'order_number', 'crt_time')
- ->get();
- $pendingDetails = [];
- foreach ($insertedRds as $rd) {
- $pendingDetails[] = [
- 'rd_id' => $rd->id,
- 'data_id' => $rdToEmployeeMap[$rd->order_number],
- 'type' => 1,
- 'crt_time' => $rd->crt_time,
- 'upd_time' => $rd->crt_time,
- 'del_time' => 0
- ];
- }
- foreach (array_chunk($pendingDetails, 1000) as $chunk) {
- DB::table('rd_details')->insert($chunk);
- }
- }
- }
- protected function buildEmployeeRds($employeeId, $employeeItems, $workDays, $config, &$pendingRds, &$rdToEmployeeMap)
- {
- $totalMinutes = intval(round($config->total_hours_2 * 60) / 60) * 60;
- $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;
- $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) {
- $dailyMinutesMap[$targetDay] += 60;
- } else {
- $extraHours++;
- }
- }
- }
- foreach ($validDays as $day => $dayItems) {
- $dailyMinutes = $dailyMinutesMap[$day];
- if ($dailyMinutes <= 0) continue;
- // --- 接力逻辑开始:计算当天统一的随机起点 ---
- $availableMinutes = 480;
- $maxOffset = $availableMinutes - $dailyMinutes;
- $randomOffset = (intval($maxOffset / 30) > 0) ? mt_rand(0, intval($maxOffset / 30)) * 30 : 0;
- // 当前时间指针指向当天的 08:00 + 随机偏移
- $currentTimePointer = Carbon::createFromTimestamp($day)->setTime(8, 0)->addMinutes($randomOffset);
- $lunchStart = Carbon::createFromTimestamp($day)->setTime(11, 30);
- $lunchEnd = Carbon::createFromTimestamp($day)->setTime(12, 0);
- // --- 接力逻辑结束 ---
- $remaining = $dailyMinutes;
- $numItems = count($dayItems);
- foreach ($dayItems as $idx => $item) {
- if ($idx === $numItems - 1) {
- $slotMinutes = $remaining;
- } else {
- $maxSlot = intval(floor($remaining * 0.7) / 60) * 60;
- $slotMinutes = ($maxSlot >= 60) ? mt_rand(1, $maxSlot / 60) * 60 : 0;
- }
- if ($slotMinutes > 0) {
- // 使用接力计算函数
- $res = $this->calculateSequentialTime(
- $item->id,
- $slotMinutes,
- $employeeId,
- $currentTimePointer,
- $lunchStart,
- $lunchEnd,
- $day
- );
- $pendingRds[] = $res['rowData'];
- $rdToEmployeeMap[$res['rowData']['order_number']] = $employeeId;
- // 指针移动:下一个项目的开始时间是当前项目的结束时间
- $currentTimePointer = $res['nextPointer'];
- }
- $remaining -= $slotMinutes;
- }
- }
- }
- protected function calculateSequentialTime($itemId, $minutes, $employeeId, $startPointer, $lunchStart, $lunchEnd, $dayTime)
- {
- $start = $startPointer->copy();
- $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);
- }
- $crtTime = Carbon::createFromTimestamp($dayTime)->setTime(16, 30)->addSeconds(mt_rand(0, 1800))->timestamp;
- // 获取 order_time 所在月份的第一天凌晨 00:00:00 的时间戳
- $belongMonth = Carbon::createFromTimestamp($dayTime)->startOfMonth()->timestamp;
- $rowData = [
- 'crt_id' => $employeeId,
- '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' => 'RD' . date('Ymd', $dayTime) . mt_rand(1000, 9999) . substr(uniqid(), -3),
- 'type' => RD::type_one,
- 'del_time' => 0,
- 'belong_month' => $belongMonth,
- ];
- return [
- 'rowData' => $rowData,
- 'nextPointer' => $end // 返回结束指针
- ];
- }
- }
|