RdGenerateService.php 9.8 KB

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