RdGenerateDeviceService.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. <?php
  2. namespace App\Service;
  3. use App\Jobs\ProcessDataJob;
  4. use App\Model\RD;
  5. use Carbon\Carbon;
  6. use Illuminate\Support\Facades\Cache;
  7. use Illuminate\Support\Facades\DB;
  8. class RdGenerateDeviceService extends Service
  9. {
  10. const job_name = "rd_device_set";
  11. /**
  12. * 外部调用的入口
  13. */
  14. public function generate(array $data)
  15. {
  16. // 1. 基础校验
  17. if (empty($data['month'])) {
  18. return [false, '请选择生成研发设备工时单年月'];
  19. }
  20. $monthStart = Carbon::createFromFormat('Y-m', $data['month'])->startOfMonth()->timestamp;
  21. // 2. 业务状态校验 (提出来的校验逻辑)
  22. $calendar = DB::table('calendar')
  23. ->where('del_time', 0)
  24. ->where('time', $monthStart)
  25. ->first();
  26. if (!$calendar) return [false, '当月日历未配置'];
  27. $hasWorkDays = DB::table('calendar_details')
  28. ->where('del_time', 0)
  29. ->where('calendar_id', $calendar->id)
  30. ->where('is_work', 1)
  31. ->exists();
  32. if (!$hasWorkDays) return [false, '当月无工作日,无法生成'];
  33. $key = self::job_name . $data['month'];
  34. $data['lock_key'] = $key;
  35. list($status,$msg) = $this->limitingSendRequest($key);
  36. if(! $status) return [false, '该月设备数据已在后台处理,请勿重复操作'];
  37. ProcessDataJob::dispatch($data)->onQueue(self::job_name);
  38. return [true, '任务已提交至后台处理,请稍后查看'];
  39. }
  40. public function delTableKey($key){
  41. $this->dellimitingSendRequest($key);
  42. }
  43. public function doGenerate(string $month)
  44. {
  45. $monthStart = Carbon::createFromFormat('Y-m', $month)->startOfMonth()->timestamp;
  46. $monthEnd = Carbon::createFromFormat('Y-m', $month)->endOfMonth()->timestamp;
  47. $calendar = DB::table('calendar')->where('del_time', 0)->where('time', $monthStart)->first();
  48. $workDays = DB::table('calendar_details')
  49. ->where('del_time', 0)
  50. ->where('calendar_id', $calendar->id)
  51. ->where('is_work', 1)
  52. ->orderBy('time')
  53. ->pluck('time')
  54. ->toArray();
  55. // 获取当月启用的研发项目
  56. $items = DB::table('item')
  57. ->where('del_time', 0)
  58. ->where('is_use', 1)
  59. ->where('start_time', '<=', $monthEnd)
  60. ->where('end_time', '>=', $monthStart)
  61. ->get();
  62. if ($items->isEmpty()) return;
  63. $itemIds = $items->pluck('id')->toArray();
  64. // 删除当月该设备类型(type=2)的老数据
  65. $rds = DB::table('rd')
  66. ->where('del_time', 0)
  67. ->where('type', RD::type_two)
  68. ->whereIn('item_id', $itemIds)
  69. ->whereBetween('order_time', [$monthStart, $monthEnd])
  70. ->pluck('id')
  71. ->toArray();
  72. if (!empty($rds)) {
  73. DB::table('rd_details')->whereIn('rd_id', $rds)->delete();
  74. DB::table('rd')->whereIn('id', $rds)->delete();
  75. }
  76. // 直接获取所有有效的设备档案ID
  77. $device_ids = DB::table('device')
  78. ->where('del_time', 0)
  79. ->pluck('id')
  80. ->toArray();
  81. foreach ($device_ids as $device_id) {
  82. // 为每个设备生成月度工时单
  83. $this->generateDeviceMonth($device_id, $items, $workDays, $calendar);
  84. }
  85. }
  86. protected function generateDeviceMonth(int $device_id, $items, array $workDays, $calendar)
  87. {
  88. // 获取该设备在当月的总分配工时配置
  89. $deviceMonth = DB::table('device_details')
  90. ->where('del_time', 0)
  91. ->where('device_id', $device_id)
  92. ->where('time', $calendar->time)
  93. ->first();
  94. if (!$deviceMonth || $deviceMonth->total_hours_2 <= 0) return;
  95. // 1. 月总工时取整为满小时 (60的倍数)
  96. $totalMinutes = intval(round($deviceMonth->total_hours_2 * 60) / 60) * 60;
  97. // 筛选出在该设备有效周期内且在进行的研发项目
  98. $validDays = [];
  99. foreach ($workDays as $day) {
  100. $dayItems = [];
  101. foreach ($items as $item) {
  102. if ($day >= $item->start_time && $day <= $item->end_time) {
  103. $dayItems[] = $item;
  104. }
  105. }
  106. if (!empty($dayItems)) $validDays[$day] = $dayItems;
  107. }
  108. if (empty($validDays)) return;
  109. // 2. 随机化每日总工时分布 (例如 184小时分到23天,每天8小时)
  110. $daysCount = count($validDays);
  111. $avgDailyMinutes = intval(floor($totalMinutes / $daysCount) / 60) * 60;
  112. $remainderMinutes = $totalMinutes - ($avgDailyMinutes * $daysCount);
  113. $dailyMinutesMap = [];
  114. foreach (array_keys($validDays) as $day) {
  115. $dailyMinutesMap[$day] = $avgDailyMinutes;
  116. }
  117. if ($remainderMinutes > 0) {
  118. $extraHours = $remainderMinutes / 60;
  119. $dayKeys = array_keys($validDays);
  120. shuffle($dayKeys);
  121. for ($i = 0; $i < $extraHours; $i++) {
  122. $targetDay = $dayKeys[$i % $daysCount];
  123. if ($dailyMinutesMap[$targetDay] < 480) { // 单日最高 8 小时
  124. $dailyMinutesMap[$targetDay] += 60;
  125. } else {
  126. $extraHours++;
  127. }
  128. }
  129. }
  130. // 3. 遍历日期并“离散化”分配项目工时
  131. foreach ($validDays as $day => $dayItems) {
  132. $dailyMinutes = $dailyMinutesMap[$day];
  133. if ($dailyMinutes <= 0) continue;
  134. $totalHoursToday = $dailyMinutes / 60; // 今天要分配的总小时数
  135. // 初始化每个项目的分钟数容器
  136. $projectMinutes = [];
  137. foreach ($dayItems as $idx => $item) {
  138. $projectMinutes[$idx] = 0;
  139. }
  140. // 获取项目索引并打乱,增加公平性
  141. $itemIndexes = array_keys($dayItems);
  142. // --- 核心离散逻辑:随机发牌法 ---
  143. for ($h = 0; $h < $totalHoursToday; $h++) {
  144. // 如果项目很多(比如20个),这里每次随机选一个
  145. // 结果会非常离散:可能8小时分给了8个不同的项目,每个项目1小时
  146. $randomIndex = $itemIndexes[array_rand($itemIndexes)];
  147. $projectMinutes[$randomIndex] += 60;
  148. }
  149. // 4. 执行生成
  150. foreach ($dayItems as $idx => $item) {
  151. if (isset($projectMinutes[$idx]) && $projectMinutes[$idx] > 0) {
  152. // 调用之前定义的 createRd 写入数据库
  153. $this->createRd($item->id, $day, $projectMinutes[$idx], $device_id);
  154. }
  155. }
  156. }
  157. }
  158. protected function createRd(int $itemId, int $dayTime, int $minutes, int $device_id)
  159. {
  160. $dayStart = Carbon::createFromTimestamp($dayTime)->setTime(8, 0);
  161. $lunchStart = Carbon::createFromTimestamp($dayTime)->setTime(11, 30);
  162. $lunchEnd = Carbon::createFromTimestamp($dayTime)->setTime(12, 0);
  163. $dayEnd = Carbon::createFromTimestamp($dayTime)->setTime(16, 30);
  164. $availableMinutes = 480;
  165. $minutes = min($minutes, $availableMinutes);
  166. $maxOffset = $availableMinutes - $minutes;
  167. $randomOffset = (intval($maxOffset / 30) > 0) ? mt_rand(0, intval($maxOffset / 30)) * 30 : 0;
  168. $start = $dayStart->copy()->addMinutes($randomOffset);
  169. $end = $start->copy();
  170. $remaining = $minutes;
  171. if ($start->lt($lunchStart)) {
  172. $morningLeft = $lunchStart->diffInMinutes($start);
  173. if ($remaining <= $morningLeft) {
  174. $end->addMinutes($remaining);
  175. } else {
  176. $remaining -= $morningLeft;
  177. $end = $lunchEnd->copy()->addMinutes($remaining);
  178. }
  179. } else {
  180. $end->addMinutes($remaining);
  181. }
  182. if ($end->gt($dayEnd)) {
  183. $end = $dayEnd->copy();
  184. }
  185. $crtTime = Carbon::createFromTimestamp($dayTime)->setTime(16, 30)->addSeconds(mt_rand(0, 1800))->timestamp;
  186. $orderNumber = 'DEV' . date('Ymd', $dayTime) . mt_rand(1000, 9999) . substr(uniqid(), -3);
  187. $rdId = DB::table('rd')->insertGetId([
  188. 'crt_time' => $crtTime,
  189. 'order_time' => $dayTime,
  190. 'item_id' => $itemId,
  191. 'start_time_hour' => $start->hour,
  192. 'start_time_min' => $start->minute,
  193. 'end_time_hour' => $end->hour,
  194. 'end_time_min' => $end->minute,
  195. 'total_hours' => $minutes,
  196. 'order_number' => $orderNumber,
  197. 'type' => RD::type_two, // 设备工时单类型为 2
  198. 'del_time' => 0
  199. ]);
  200. DB::table('rd_details')->insert([
  201. 'rd_id' => $rdId,
  202. 'data_id' => $device_id, // 存储设备ID
  203. 'type' => RD::type_two, // 类型为 2
  204. 'crt_time' => $crtTime,
  205. 'upd_time' => $crtTime,
  206. 'del_time' => 0
  207. ]);
  208. }
  209. }