RdGenerateService.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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. // 分片删除,防止 SQL 过长
  59. foreach (array_chunk($rds, 1000) as $chunk) {
  60. DB::table('rd_details')->whereIn('rd_id', $chunk)->delete();
  61. DB::table('rd')->whereIn('id', $chunk)->delete();
  62. }
  63. }
  64. }
  65. // 3. 预加载所有员工关联关系 (核心优化:内存化)
  66. $itemDetails = DB::table('item_details')
  67. ->where('del_time', 0)
  68. ->whereIn('item_id', $itemIds)
  69. ->where('type', 1)
  70. ->get()
  71. ->groupBy('data_id'); // 以员工ID分组
  72. $employeeIds = $itemDetails->keys()->toArray();
  73. // 4. 预加载员工月工时配置
  74. $employeeMonths = DB::table('employee_details')
  75. ->where('del_time', 0)
  76. ->whereIn('employee_id', $employeeIds)
  77. ->where('time', $calendar->time)
  78. ->get()
  79. ->keyBy('employee_id');
  80. $pendingRds = []; // 待插入的主表数据
  81. $rdToEmployeeMap = []; // 临时映射:order_number => employee_id
  82. // 5. 内存循环处理
  83. foreach ($employeeIds as $employeeId) {
  84. $empMonthConfig = $employeeMonths->get($employeeId);
  85. if (!$empMonthConfig || $empMonthConfig->total_hours_2 <= 0) continue;
  86. // 获取该员工参与的项目集合
  87. $myProjectIds = $itemDetails->get($employeeId)->pluck('item_id')->toArray();
  88. $employeeItems = $items->whereIn('id', $myProjectIds);
  89. // 计算该员工全月分布并填充到待插入数组
  90. $this->buildEmployeeRds(
  91. $employeeId,
  92. $employeeItems,
  93. $workDays,
  94. $empMonthConfig,
  95. $pendingRds,
  96. $rdToEmployeeMap
  97. );
  98. }
  99. // 6. 批量插入主表并同步明细表
  100. if (!empty($pendingRds)) {
  101. // 分批插入主表 (MySQL 默认限制一次约 10MB)
  102. foreach (array_chunk($pendingRds, 1000) as $chunk) {
  103. DB::table('rd')->insert($chunk);
  104. }
  105. // 通过 order_number 反查回生成的 ID
  106. $insertedRds = DB::table('rd')
  107. ->whereIn('order_number', array_keys($rdToEmployeeMap))
  108. ->select('id', 'order_number', 'crt_time')
  109. ->get();
  110. $pendingDetails = [];
  111. foreach ($insertedRds as $rd) {
  112. $pendingDetails[] = [
  113. 'rd_id' => $rd->id,
  114. 'data_id' => $rdToEmployeeMap[$rd->order_number],
  115. 'type' => 1,
  116. 'crt_time' => $rd->crt_time,
  117. 'upd_time' => $rd->crt_time,
  118. 'del_time' => 0
  119. ];
  120. }
  121. foreach (array_chunk($pendingDetails, 1000) as $chunk) {
  122. DB::table('rd_details')->insert($chunk);
  123. }
  124. }
  125. }
  126. protected function buildEmployeeRds($employeeId, $employeeItems, $workDays, $config, &$pendingRds, &$rdToEmployeeMap)
  127. {
  128. $totalMinutes = intval(round($config->total_hours_2 * 60) / 60) * 60;
  129. // 过滤有效日期
  130. $validDays = [];
  131. foreach ($workDays as $day) {
  132. $dayItems = [];
  133. foreach ($employeeItems as $item) {
  134. if ($day >= $item->start_time && $day <= $item->end_time) {
  135. $dayItems[] = $item;
  136. }
  137. }
  138. if (!empty($dayItems)) $validDays[$day] = $dayItems;
  139. }
  140. if (empty($validDays)) return;
  141. // 分配每日时长
  142. $daysCount = count($validDays);
  143. $avgDailyMinutes = intval(floor($totalMinutes / $daysCount) / 60) * 60;
  144. $remainderMinutes = $totalMinutes - ($avgDailyMinutes * $daysCount);
  145. $dailyMinutesMap = [];
  146. foreach (array_keys($validDays) as $day) {
  147. $dailyMinutesMap[$day] = $avgDailyMinutes;
  148. }
  149. if ($remainderMinutes > 0) {
  150. $extraHours = $remainderMinutes / 60;
  151. $dayKeys = array_keys($validDays);
  152. shuffle($dayKeys);
  153. for ($i = 0; $i < $extraHours; $i++) {
  154. $targetDay = $dayKeys[$i % $daysCount];
  155. if ($dailyMinutesMap[$targetDay] < 480) {
  156. $dailyMinutesMap[$targetDay] += 60;
  157. } else {
  158. $extraHours++;
  159. }
  160. }
  161. }
  162. // 生成具体数据行
  163. foreach ($validDays as $day => $dayItems) {
  164. $dailyMinutes = $dailyMinutesMap[$day];
  165. if ($dailyMinutes <= 0) continue;
  166. $remaining = $dailyMinutes;
  167. $numItems = count($dayItems);
  168. foreach ($dayItems as $idx => $item) {
  169. if ($idx === $numItems - 1) {
  170. $slotMinutes = $remaining;
  171. } else {
  172. $maxSlot = intval(floor($remaining * 0.7) / 60) * 60;
  173. $slotMinutes = ($maxSlot >= 60) ? mt_rand(1, $maxSlot / 60) * 60 : 0;
  174. }
  175. if ($slotMinutes > 0) {
  176. $rowData = $this->calculateTimeSlots($item->id, $day, $slotMinutes, $employeeId);
  177. $pendingRds[] = $rowData;
  178. $rdToEmployeeMap[$rowData['order_number']] = $employeeId;
  179. }
  180. $remaining -= $slotMinutes;
  181. }
  182. }
  183. }
  184. protected function calculateTimeSlots($itemId, $dayTime, $minutes,$employeeId)
  185. {
  186. $availableMinutes = 480;
  187. $minutes = min($minutes, $availableMinutes);
  188. $maxOffset = $availableMinutes - $minutes;
  189. $randomOffset = (intval($maxOffset / 30) > 0) ? mt_rand(0, intval($maxOffset / 30)) * 30 : 0;
  190. $dayStart = Carbon::createFromTimestamp($dayTime)->setTime(8, 0);
  191. $lunchStart = Carbon::createFromTimestamp($dayTime)->setTime(11, 30);
  192. $lunchEnd = Carbon::createFromTimestamp($dayTime)->setTime(12, 0);
  193. $start = $dayStart->copy()->addMinutes($randomOffset);
  194. $end = $start->copy();
  195. if ($start->lt($lunchStart)) {
  196. $morningLeft = $lunchStart->diffInMinutes($start);
  197. if ($minutes <= $morningLeft) {
  198. $end->addMinutes($minutes);
  199. } else {
  200. $end = $lunchEnd->copy()->addMinutes($minutes - $morningLeft);
  201. }
  202. } else {
  203. $end->addMinutes($minutes);
  204. }
  205. $crtTime = Carbon::createFromTimestamp($dayTime)->setTime(16, 30)->addSeconds(mt_rand(0, 1800))->timestamp;
  206. return [
  207. 'crt_id' => $employeeId,
  208. 'crt_time' => $crtTime,
  209. 'order_time' => $dayTime,
  210. 'item_id' => $itemId,
  211. 'start_time_hour' => $start->hour,
  212. 'start_time_min' => $start->minute,
  213. 'end_time_hour' => $end->hour,
  214. 'end_time_min' => $end->minute,
  215. 'total_hours' => $minutes,
  216. 'order_number' => 'RD' . date('Ymd', $dayTime) . mt_rand(1000, 9999) . substr(uniqid(), -3),
  217. 'type' => 1,
  218. 'del_time' => 0
  219. ];
  220. }
  221. }