RdGenerateService.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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. $calendar = DB::table('calendar')
  27. ->where('del_time', 0)
  28. ->where('time', $monthStart)
  29. ->first();
  30. if (!$calendar) throw new \Exception('当月日历未配置');
  31. $workDays = DB::table('calendar_details')
  32. ->where('del_time', 0)
  33. ->where('calendar_id', $calendar->id)
  34. ->where('is_work', 1)
  35. ->orderBy('time')
  36. ->pluck('time')
  37. ->toArray();
  38. if (empty($workDays)) throw new \Exception('当月无工作日');
  39. $items = DB::table('item')
  40. ->where('del_time', 0)
  41. ->where('is_use', 1)
  42. ->where('start_time', '<=', $monthEnd)
  43. ->where('end_time', '>=', $monthStart)
  44. ->get();
  45. $itemIds = $items->pluck('id')->toArray();
  46. if (!empty($itemIds)) {
  47. $rds = DB::table('rd')
  48. ->where('del_time', 0)
  49. ->where('type',RD::type_one)
  50. ->whereIn('item_id', $itemIds)
  51. ->whereBetween('order_time', [$monthStart, $monthEnd])
  52. ->pluck('id')
  53. ->toArray();
  54. if (!empty($rds)) {
  55. DB::table('rd_details')->whereIn('rd_id', $rds)->delete();
  56. DB::table('rd')->whereIn('id', $rds)->delete();
  57. }
  58. }
  59. $employeeIds = DB::table('item_details')
  60. ->where('del_time', 0)
  61. ->whereIn('item_id', $itemIds)
  62. ->where('type', 1)
  63. ->pluck('data_id')
  64. ->unique()
  65. ->toArray();
  66. foreach ($employeeIds as $employeeId) {
  67. $this->generateEmployeeMonth($employeeId, $items, $workDays, $calendar);
  68. }
  69. }
  70. protected function generateEmployeeMonth(int $employeeId, $items, array $workDays, $calendar)
  71. {
  72. $employeeMonth = DB::table('employee_details')
  73. ->where('del_time', 0)
  74. ->where('employee_id', $employeeId)
  75. ->where('time', $calendar->time)
  76. ->first();
  77. if (!$employeeMonth || $employeeMonth->total_hours_2 <= 0) return;
  78. // 1. 月总工时取整为满小时 (60的倍数)
  79. $totalMinutes = intval(round($employeeMonth->total_hours_2 * 60) / 60) * 60;
  80. $employeeItems = [];
  81. foreach ($items as $item) {
  82. $exists = DB::table('item_details')
  83. ->where('del_time', 0)
  84. ->where('item_id', $item->id)
  85. ->where('type', 1)
  86. ->where('data_id', $employeeId)
  87. ->exists();
  88. if ($exists) $employeeItems[] = $item;
  89. }
  90. if (empty($employeeItems)) return;
  91. $validDays = [];
  92. foreach ($workDays as $day) {
  93. $dayItems = [];
  94. foreach ($employeeItems as $item) {
  95. if ($day >= $item->start_time && $day <= $item->end_time) {
  96. $dayItems[] = $item;
  97. }
  98. }
  99. if (!empty($dayItems)) $validDays[$day] = $dayItems;
  100. }
  101. if (empty($validDays)) return;
  102. // 2. 随机化每日总工时分布
  103. $daysCount = count($validDays);
  104. $avgDailyMinutes = intval(floor($totalMinutes / $daysCount) / 60) * 60;
  105. $remainderMinutes = $totalMinutes - ($avgDailyMinutes * $daysCount);
  106. $dailyMinutesMap = [];
  107. foreach (array_keys($validDays) as $day) {
  108. $dailyMinutesMap[$day] = $avgDailyMinutes;
  109. }
  110. if ($remainderMinutes > 0) {
  111. $extraHours = $remainderMinutes / 60;
  112. $dayKeys = array_keys($validDays);
  113. shuffle($dayKeys);
  114. for ($i = 0; $i < $extraHours; $i++) {
  115. $targetDay = $dayKeys[$i % $daysCount];
  116. if ($dailyMinutesMap[$targetDay] < 480) { // 最高8小时 (480min)
  117. $dailyMinutesMap[$targetDay] += 60;
  118. } else {
  119. $extraHours++;
  120. }
  121. }
  122. }
  123. // 3. 遍历日期并生成明细
  124. foreach ($validDays as $day => $dayItems) {
  125. $dailyMinutes = $dailyMinutesMap[$day];
  126. if ($dailyMinutes <= 0) continue;
  127. $slots = [];
  128. $remaining = $dailyMinutes;
  129. $numItems = count($dayItems);
  130. for ($i = 0; $i < $numItems; $i++) {
  131. if ($i === $numItems - 1) {
  132. $slotMinutes = $remaining;
  133. } else {
  134. // 随机分配项目工时
  135. $maxSlot = intval(floor($remaining * 0.7) / 60) * 60;
  136. $slotMinutes = ($maxSlot >= 60) ? mt_rand(1, $maxSlot / 60) * 60 : 0;
  137. }
  138. $slots[] = $slotMinutes;
  139. $remaining -= $slotMinutes;
  140. }
  141. foreach ($dayItems as $idx => $item) {
  142. if (isset($slots[$idx]) && $slots[$idx] > 0) {
  143. $this->createRd($item->id, $day, $slots[$idx], $employeeId);
  144. }
  145. }
  146. }
  147. }
  148. protected function createRd(int $itemId, int $dayTime, int $minutes, int $employeeId)
  149. {
  150. $dayStart = Carbon::createFromTimestamp($dayTime)->setTime(8, 0);
  151. $lunchStart = Carbon::createFromTimestamp($dayTime)->setTime(11, 30);
  152. $lunchEnd = Carbon::createFromTimestamp($dayTime)->setTime(12, 0);
  153. $dayEnd = Carbon::createFromTimestamp($dayTime)->setTime(16, 30);
  154. $availableMinutes = 480; // 8:00-16:30 扣除 30min 午休
  155. $minutes = min($minutes, $availableMinutes);
  156. // 计算最大可偏移量(单位:分钟),确保不会超出 16:30
  157. $maxOffset = $availableMinutes - $minutes;
  158. // 随机偏移:以 30 分钟为步长进行随机 (0, 30, 60...)
  159. $randomOffset = (intval($maxOffset / 30) > 0) ? mt_rand(0, intval($maxOffset / 30)) * 30 : 0;
  160. $start = $dayStart->copy()->addMinutes($randomOffset);
  161. $end = $start->copy();
  162. $remaining = $minutes;
  163. // 逻辑:如果开始时间在午休前
  164. if ($start->lt($lunchStart)) {
  165. $morningLeft = $lunchStart->diffInMinutes($start);
  166. if ($remaining <= $morningLeft) {
  167. $end->addMinutes($remaining);
  168. } else {
  169. // 跨午休逻辑
  170. $remaining -= $morningLeft;
  171. $end = $lunchEnd->copy()->addMinutes($remaining);
  172. }
  173. } else {
  174. // 开始时间就在午休后
  175. $end->addMinutes($remaining);
  176. }
  177. // 最终校验防止越界(虽然 offset 已做限制)
  178. if ($end->gt($dayEnd)) {
  179. $end = $dayEnd->copy();
  180. }
  181. $crtTime = Carbon::createFromTimestamp($dayTime)->setTime(16, 30)->addSeconds(mt_rand(0, 1800))->timestamp;
  182. $orderNumber = 'RD' . date('Ymd', $dayTime) . mt_rand(1000, 9999) . substr(uniqid(), -3);
  183. $rdId = DB::table('rd')->insertGetId([
  184. 'crt_time' => $crtTime,
  185. 'order_time' => $dayTime,
  186. 'item_id' => $itemId,
  187. 'start_time_hour' => $start->hour,
  188. 'start_time_min' => $start->minute,
  189. 'end_time_hour' => $end->hour,
  190. 'end_time_min' => $end->minute,
  191. 'total_hours' => $minutes,
  192. 'order_number' => $orderNumber,
  193. 'type' => 1,
  194. 'del_time' => 0
  195. ]);
  196. DB::table('rd_details')->insert([
  197. 'rd_id' => $rdId,
  198. 'data_id' => $employeeId,
  199. 'type' => 1,
  200. 'crt_time' => $crtTime,
  201. 'upd_time' => $crtTime,
  202. 'del_time' => 0
  203. ]);
  204. }
  205. }