RdGenerateService.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. <?php
  2. namespace App\Service;
  3. use Carbon\Carbon;
  4. use Illuminate\Support\Facades\DB;
  5. class RdGenerateService extends Service
  6. {
  7. public function generate(array $data)
  8. {
  9. if (empty($data['month'])) {
  10. return [false, '请选择生成研发人员工时单年月'];
  11. }
  12. try {
  13. DB::transaction(function () use ($data) {
  14. $this->doGenerate($data['month']);
  15. });
  16. } catch (\Throwable $e) {
  17. return [false, $e->getMessage()];
  18. }
  19. return [true, ''];
  20. }
  21. protected function doGenerate(string $month)
  22. {
  23. $monthStart = Carbon::createFromFormat('Y-m', $month)->startOfMonth()->timestamp;
  24. $monthEnd = Carbon::createFromFormat('Y-m', $month)->endOfMonth()->timestamp;
  25. // 日历
  26. $calendar = DB::table('calendar')
  27. ->where('time', $monthStart)
  28. ->first();
  29. if (!$calendar) {
  30. throw new \Exception('当月日历未配置');
  31. }
  32. // 工作日
  33. $workDays = DB::table('calendar_details')
  34. ->where('calendar_id', $calendar->id)
  35. ->where('is_work', 1)
  36. ->orderBy('time')
  37. ->pluck('time')
  38. ->toArray();
  39. if (empty($workDays)) {
  40. throw new \Exception('当月无工作日');
  41. }
  42. // 启用项目
  43. $items = DB::table('item')
  44. ->where('is_use', 1)
  45. ->where('start_time', '<=', $monthEnd)
  46. ->where('end_time', '>=', $monthStart)
  47. ->get();
  48. // 删除当月所有项目的老数据
  49. $itemIds = $items->pluck('id')->toArray();
  50. if (!empty($itemIds)) {
  51. $rds = DB::table('rd')
  52. ->whereIn('item_id', $itemIds)
  53. ->whereBetween('order_time', [$monthStart, $monthEnd])
  54. ->pluck('id')
  55. ->toArray();
  56. if (!empty($rds)) {
  57. DB::table('rd_details')->whereIn('rd_id', $rds)->delete();
  58. DB::table('rd')->whereIn('id', $rds)->delete();
  59. }
  60. }
  61. // 获取所有员工id
  62. $employeeIds = DB::table('item_details')
  63. ->whereIn('item_id', $itemIds)
  64. ->where('type', 1)
  65. ->pluck('data_id')
  66. ->unique()
  67. ->toArray();
  68. // 按员工生成当月工时单
  69. foreach ($employeeIds as $employeeId) {
  70. $this->generateEmployeeMonth($employeeId, $items, $workDays, $calendar);
  71. }
  72. }
  73. /**
  74. * 按员工生成当月工时单,严格保证总工时匹配(通过将分配分钟数取整到 5 的倍数实现)
  75. */
  76. protected function generateEmployeeMonth(int $employeeId, $items, array $workDays, $calendar)
  77. {
  78. $employeeMonth = DB::table('employee_details')
  79. ->where('employee_id', $employeeId)
  80. ->where('time', $calendar->time)
  81. ->first();
  82. if (!$employeeMonth || $employeeMonth->total_hours_2 <= 0) {
  83. return;
  84. }
  85. // 员工总分钟数:这里保留了浮点数取整可能带来的微小误差,但这是上游数据决定的
  86. $totalMinutes = (int)round($employeeMonth->total_hours_2 * 60);
  87. // --- 核心修复 1: 确保总分钟数是 5 的倍数,否则损失这 $1-4$ 分钟的精度 ---
  88. // 这是为了让后续的平均分配和余数计算能确保最终分配的总和是 5 的倍数
  89. $totalMinutes = intval($totalMinutes / 5) * 5;
  90. // --- 核心修复 1 结束 ---
  91. $dayMaxMinutes = 510 - 30; // 每天最大分钟数(扣午休)
  92. // 员工参与的项目
  93. $employeeItems = [];
  94. foreach ($items as $item) {
  95. $exists = DB::table('item_details')
  96. ->where('item_id', $item->id)
  97. ->where('type', 1)
  98. ->where('data_id', $employeeId)
  99. ->exists();
  100. if ($exists) $employeeItems[] = $item;
  101. }
  102. if (empty($employeeItems)) return;
  103. // 所有有效工作日(员工参与项目的周期内)
  104. $validDays = [];
  105. foreach ($workDays as $day) {
  106. $dayItems = [];
  107. foreach ($employeeItems as $item) {
  108. if ($day >= $item->start_time && $day <= $item->end_time) {
  109. $dayItems[] = $item;
  110. }
  111. }
  112. if (!empty($dayItems)) {
  113. $validDays[$day] = $dayItems;
  114. }
  115. }
  116. if (empty($validDays)) return;
  117. // 每天大约的分钟数
  118. $avgDailyMinutes = floor($totalMinutes / count($validDays));
  119. $remainder = $totalMinutes - $avgDailyMinutes * count($validDays);
  120. foreach ($validDays as $day => $dayItems) {
  121. $dailyMinutes = $avgDailyMinutes;
  122. // 最后一天补齐余数
  123. if ($day === array_key_last($validDays)) {
  124. $dailyMinutes += $remainder;
  125. }
  126. // 随机给当天项目分配分钟数
  127. $slots = [];
  128. $remaining = $dailyMinutes;
  129. $numItems = count($dayItems);
  130. for ($i = 0; $i < $numItems; $i++) {
  131. if ($i === $numItems - 1) {
  132. // 最后一个项目:分配所有剩余时间
  133. $slotMinutes = $remaining;
  134. } else {
  135. // 随机 ±20% 分配
  136. $max = floor($remaining * 0.8);
  137. $slotMinutes = mt_rand(1, max(1, $max));
  138. // --- 核心修复 2: 确保随机分配的工时是 5 的倍数 ---
  139. $slotMinutes = intval($slotMinutes / 5) * 5;
  140. // 确保至少是 5 分钟的倍数(如果剩余时间允许)
  141. $slotMinutes = max(0, $slotMinutes);
  142. // --- 核心修复 2 结束 ---
  143. }
  144. $slots[] = $slotMinutes;
  145. $remaining -= $slotMinutes;
  146. }
  147. // 调整最后剩余:将所有因为取整损失的分钟数,都加给最后一个项目
  148. if ($remaining > 0) {
  149. $slots[$numItems - 1] += $remaining;
  150. }
  151. // 确保最后一个项目的工时也是 5 的倍数(因为 $dailyMinutes$ 是 5 的倍数,这一步理论上是确保的)
  152. // 我们需要对最终的 $slots[$numItems - 1] 再次取整,以处理可能的小数取整误差
  153. $slots[$numItems - 1] = intval($slots[$numItems - 1] / 5) * 5;
  154. // 创建工时单
  155. foreach ($dayItems as $idx => $item) {
  156. // 仅对分配到的工时大于 0 的项目创建记录
  157. if ($slots[$idx] > 0) {
  158. $this->createRd($item->id, $day, $slots[$idx], $employeeId);
  159. }
  160. }
  161. }
  162. }
  163. /**
  164. * 创建单条研发工时单
  165. * 由于传入的 $minutes 已经是 5 的倍数,此方法保证 total_hours 与 $start/$end 严格匹配。
  166. */
  167. protected function createRd(int $itemId, int $dayTime, int $minutes, int $employeeId)
  168. {
  169. $dayStart = Carbon::createFromTimestamp($dayTime)->setTime(8, 0);
  170. $lunchStart = Carbon::createFromTimestamp($dayTime)->setTime(11, 30);
  171. $lunchEnd = Carbon::createFromTimestamp($dayTime)->setTime(12, 0);
  172. $dayEnd = Carbon::createFromTimestamp($dayTime)->setTime(16, 30);
  173. $morningMinutes = $lunchStart->diffInMinutes($dayStart);
  174. $afternoonMinutes = $dayEnd->diffInMinutes($lunchEnd);
  175. $availableMinutes = $morningMinutes + $afternoonMinutes;
  176. // 保证总分钟数不超过可用时间
  177. $minutes = min($minutes, $availableMinutes);
  178. // 随机生成 start 时间,整5分钟
  179. if ($minutes <= $morningMinutes) {
  180. $maxOffset = $morningMinutes - $minutes;
  181. // $dayStart (8:00) 已经是 5 的倍数
  182. $offset = 5 * mt_rand(0, intval($maxOffset / 5));
  183. $start = $dayStart->copy()->addMinutes($offset);
  184. } elseif ($minutes <= $afternoonMinutes) {
  185. $maxOffset = $afternoonMinutes - $minutes;
  186. $offset = 5 * mt_rand(0, intval($maxOffset / 5));
  187. $start = $lunchEnd->copy()->addMinutes($offset);
  188. } else {
  189. // 分两段:上午尽量满,剩余在下午
  190. $start = $dayStart->copy();
  191. }
  192. // 计算结束时间,跨午休自动跳过
  193. $remaining = $minutes;
  194. if ($start->lt($lunchStart) && $remaining > $morningMinutes - $start->diffInMinutes($dayStart)) {
  195. $usedMorning = $morningMinutes - $start->diffInMinutes($dayStart);
  196. $remaining -= $usedMorning;
  197. $end = $lunchEnd->copy()->addMinutes($remaining);
  198. } else {
  199. $end = $start->copy()->addMinutes($remaining);
  200. }
  201. // 调整到整5分钟
  202. // 🚨 这一步保留,但由于 $minutes 是 5 的倍数,这里的取整不会导致 $end - $start$ 发生变化
  203. $start->minute = intval($start->minute / 5) * 5;
  204. $end->minute = intval($end->minute / 5) * 5;
  205. // crt_time 16:30 ~ 17:00
  206. $crtTime = Carbon::createFromTimestamp($dayTime)
  207. ->setTime(16, 30)
  208. ->addSeconds(mt_rand(0, 30*60))
  209. ->timestamp;
  210. $dayPrefix = date('Ymd', $dayTime);
  211. $orderNumber = 'RD' . $dayPrefix . mt_rand(1000, 9999) . substr(uniqid(), -3);
  212. $rdId = DB::table('rd')->insertGetId([
  213. 'crt_time' => $crtTime,
  214. 'order_time' => $dayTime,
  215. 'item_id' => $itemId,
  216. 'start_time_hour' => $start->hour,
  217. 'start_time_min' => $start->minute,
  218. 'end_time_hour' => $end->hour,
  219. 'end_time_min' => $end->minute,
  220. // 重点:使用分配好的 $minutes,现在它已经是 5 的倍数,与 $start/$end$ 匹配
  221. 'total_hours' => $minutes,
  222. 'order_number' => $orderNumber,
  223. 'type' => 1
  224. ]);
  225. DB::table('rd_details')->insert([
  226. 'rd_id' => $rdId,
  227. 'data_id' => $employeeId,
  228. 'type' => 1,
  229. 'crt_time' => $crtTime,
  230. 'upd_time' => $crtTime,
  231. ]);
  232. }
  233. }