RdGenerateService.php 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. <?php
  2. namespace App\Service;
  3. use App\Model\RD;
  4. use Carbon\Carbon;
  5. use Illuminate\Support\Facades\DB;
  6. class RdGenerateService extends Service
  7. {
  8. public function generate(array $data)
  9. {
  10. if (empty($data['month'])) {
  11. return [false, '请选择生成研发人员工时单年月'];
  12. }
  13. try {
  14. // 设置脚本执行时间,防止大数据量时 PHP 超时
  15. set_time_limit(300);
  16. DB::transaction(function () use ($data) {
  17. $this->doGenerate($data['month']);
  18. });
  19. } catch (\Throwable $e) {
  20. return [false, $e->getMessage()];
  21. }
  22. return [true, ''];
  23. }
  24. protected function doGenerate(string $month)
  25. {
  26. $monthStart = Carbon::createFromFormat('Y-m', $month)->startOfMonth()->timestamp;
  27. $monthEnd = Carbon::createFromFormat('Y-m', $month)->endOfMonth()->timestamp;
  28. // 1. 获取日历配置
  29. $calendar = DB::table('calendar')
  30. ->where('del_time', 0)
  31. ->where('time', $monthStart)
  32. ->first();
  33. if (!$calendar) throw new \Exception('当月日历未配置');
  34. $workDays = DB::table('calendar_details')
  35. ->where('del_time', 0)
  36. ->where('calendar_id', $calendar->id)
  37. ->where('is_work', 1)
  38. ->orderBy('time')
  39. ->pluck('time')
  40. ->toArray();
  41. if (empty($workDays)) throw new \Exception('当月无工作日');
  42. // 2. 获取相关项目并清理旧数据
  43. $items = DB::table('item')
  44. ->where('del_time', 0)
  45. ->where('is_use', 1)
  46. ->where('start_time', '<=', $monthEnd)
  47. ->where('end_time', '>=', $monthStart)
  48. ->orderBy('id','desc')
  49. ->get();
  50. $itemIds = $items->pluck('id')->toArray();
  51. if (!empty($itemIds)) {
  52. $rds = DB::table('rd')
  53. ->where('del_time', 0)
  54. ->where('type', RD::type_one)
  55. ->whereIn('item_id', $itemIds)
  56. ->whereBetween('order_time', [$monthStart, $monthEnd])
  57. ->pluck('id')
  58. ->toArray();
  59. if (!empty($rds)) {
  60. foreach (array_chunk($rds, 1000) as $chunk) {
  61. DB::table('rd_details')->whereIn('rd_id', $chunk)->delete();
  62. DB::table('rd')->whereIn('id', $chunk)->delete();
  63. }
  64. }
  65. }
  66. // 3. 预加载所有员工关联关系
  67. $itemDetails = DB::table('item_details')
  68. ->where('del_time', 0)
  69. ->whereIn('item_id', $itemIds)
  70. ->where('type', 1)
  71. ->get()
  72. ->groupBy('data_id');
  73. $employeeIds = $itemDetails->keys()->toArray();
  74. // 4. 预加载员工月工时配置
  75. $employeeMonths = DB::table('employee_details')
  76. ->where('del_time', 0)
  77. ->whereIn('employee_id', $employeeIds)
  78. ->where('time', $calendar->time)
  79. ->get()
  80. ->keyBy('employee_id');
  81. $pendingRds = [];
  82. $rdToEmployeeMap = [];
  83. // 5. 内存循环处理
  84. foreach ($employeeIds as $employeeId) {
  85. $empMonthConfig = $employeeMonths->get($employeeId);
  86. if (!$empMonthConfig || $empMonthConfig->total_hours_2 <= 0) continue;
  87. $myProjectIds = $itemDetails->get($employeeId)->pluck('item_id')->toArray();
  88. $employeeItems = $items->whereIn('id', $myProjectIds);
  89. $this->buildEmployeeRds(
  90. $employeeId,
  91. $employeeItems,
  92. $workDays,
  93. $empMonthConfig,
  94. $pendingRds,
  95. $rdToEmployeeMap
  96. );
  97. }
  98. // 6. 批量写入
  99. if (!empty($pendingRds)) {
  100. foreach (array_chunk($pendingRds, 1000) as $chunk) {
  101. DB::table('rd')->insert($chunk);
  102. }
  103. $insertedRds = DB::table('rd')
  104. ->whereIn('order_number', array_keys($rdToEmployeeMap))
  105. ->select('id', 'order_number', 'crt_time')
  106. ->get();
  107. $pendingDetails = [];
  108. foreach ($insertedRds as $rd) {
  109. $pendingDetails[] = [
  110. 'rd_id' => $rd->id,
  111. 'data_id' => $rdToEmployeeMap[$rd->order_number],
  112. 'type' => 1,
  113. 'crt_time' => $rd->crt_time,
  114. 'upd_time' => $rd->crt_time,
  115. 'del_time' => 0
  116. ];
  117. }
  118. foreach (array_chunk($pendingDetails, 1000) as $chunk) {
  119. DB::table('rd_details')->insert($chunk);
  120. }
  121. }
  122. }
  123. protected function buildEmployeeRds($employeeId, $employeeItems, $workDays, $config, &$pendingRds, &$rdToEmployeeMap)
  124. {
  125. $totalMinutes = intval(round($config->total_hours_2 * 60) / 60) * 60;
  126. $validDays = [];
  127. foreach ($workDays as $day) {
  128. $dayItems = [];
  129. foreach ($employeeItems as $item) {
  130. if ($day >= $item->start_time && $day <= $item->end_time) {
  131. $dayItems[] = $item;
  132. }
  133. }
  134. if (!empty($dayItems)) $validDays[$day] = $dayItems;
  135. }
  136. if (empty($validDays)) return;
  137. $daysCount = count($validDays);
  138. $avgDailyMinutes = intval(floor($totalMinutes / $daysCount) / 60) * 60;
  139. $remainderMinutes = $totalMinutes - ($avgDailyMinutes * $daysCount);
  140. $dailyMinutesMap = [];
  141. foreach (array_keys($validDays) as $day) {
  142. $dailyMinutesMap[$day] = $avgDailyMinutes;
  143. }
  144. if ($remainderMinutes > 0) {
  145. $extraHours = $remainderMinutes / 60;
  146. $dayKeys = array_keys($validDays);
  147. shuffle($dayKeys);
  148. for ($i = 0; $i < $extraHours; $i++) {
  149. $targetDay = $dayKeys[$i % $daysCount];
  150. if ($dailyMinutesMap[$targetDay] < 480) {
  151. $dailyMinutesMap[$targetDay] += 60;
  152. } else {
  153. $extraHours++;
  154. }
  155. }
  156. }
  157. foreach ($validDays as $day => $dayItems) {
  158. $dailyMinutes = $dailyMinutesMap[$day];
  159. if ($dailyMinutes <= 0) continue;
  160. // --- 接力逻辑开始:计算当天统一的随机起点 ---
  161. $availableMinutes = 480;
  162. $maxOffset = $availableMinutes - $dailyMinutes;
  163. $randomOffset = (intval($maxOffset / 30) > 0) ? mt_rand(0, intval($maxOffset / 30)) * 30 : 0;
  164. // 当前时间指针指向当天的 08:00 + 随机偏移
  165. $currentTimePointer = Carbon::createFromTimestamp($day)->setTime(8, 0)->addMinutes($randomOffset);
  166. $lunchStart = Carbon::createFromTimestamp($day)->setTime(11, 30);
  167. $lunchEnd = Carbon::createFromTimestamp($day)->setTime(12, 0);
  168. // --- 接力逻辑结束 ---
  169. $remaining = $dailyMinutes;
  170. $numItems = count($dayItems);
  171. foreach ($dayItems as $idx => $item) {
  172. if ($idx === $numItems - 1) {
  173. $slotMinutes = $remaining;
  174. } else {
  175. $maxSlot = intval(floor($remaining * 0.7) / 60) * 60;
  176. $slotMinutes = ($maxSlot >= 60) ? mt_rand(1, $maxSlot / 60) * 60 : 0;
  177. }
  178. if ($slotMinutes > 0) {
  179. // 使用接力计算函数
  180. $res = $this->calculateSequentialTime(
  181. $item->id,
  182. $slotMinutes,
  183. $employeeId,
  184. $currentTimePointer,
  185. $lunchStart,
  186. $lunchEnd,
  187. $day
  188. );
  189. $pendingRds[] = $res['rowData'];
  190. $rdToEmployeeMap[$res['rowData']['order_number']] = $employeeId;
  191. // 指针移动:下一个项目的开始时间是当前项目的结束时间
  192. $currentTimePointer = $res['nextPointer'];
  193. }
  194. $remaining -= $slotMinutes;
  195. }
  196. }
  197. }
  198. protected function calculateSequentialTime($itemId, $minutes, $employeeId, $startPointer, $lunchStart, $lunchEnd, $dayTime)
  199. {
  200. $start = $startPointer->copy();
  201. $end = $start->copy();
  202. $remaining = $minutes;
  203. // 跨午休逻辑处理
  204. if ($start->lt($lunchStart)) {
  205. $morningLeft = $lunchStart->diffInMinutes($start);
  206. if ($remaining <= $morningLeft) {
  207. $end->addMinutes($remaining);
  208. } else {
  209. // 扣除上午干掉的时间,剩下的从下午开始
  210. $remaining -= $morningLeft;
  211. $end = $lunchEnd->copy()->addMinutes($remaining);
  212. }
  213. } else {
  214. // 如果起点已经在午休后(比如随机偏移很大)
  215. $end->addMinutes($remaining);
  216. }
  217. $crtTime = Carbon::createFromTimestamp($dayTime)->setTime(16, 30)->addSeconds(mt_rand(0, 1800))->timestamp;
  218. $rowData = [
  219. 'crt_id' => $employeeId,
  220. 'crt_time' => $crtTime,
  221. 'order_time' => $dayTime,
  222. 'item_id' => $itemId,
  223. 'start_time_hour' => $start->hour,
  224. 'start_time_min' => $start->minute,
  225. 'end_time_hour' => $end->hour,
  226. 'end_time_min' => $end->minute,
  227. 'total_hours' => $minutes,
  228. 'order_number' => 'RD' . date('Ymd', $dayTime) . mt_rand(1000, 9999) . substr(uniqid(), -3),
  229. 'type' => 1,
  230. 'del_time' => 0
  231. ];
  232. return [
  233. 'rowData' => $rowData,
  234. 'nextPointer' => $end // 返回结束指针
  235. ];
  236. }
  237. }