RdGenerateDeviceService.php 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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\DB;
  7. class RdGenerateDeviceService extends Service
  8. {
  9. const job_name = "rd_device_set";
  10. /**
  11. * 外部调用的入口 (保持原样,负责分发队列)
  12. */
  13. public function generate(array $data)
  14. {
  15. if (empty($data['month'])) {
  16. return [false, '请选择生成研发设备工时单年月'];
  17. }
  18. $monthStart = Carbon::createFromFormat('Y-m', $data['month'])->startOfMonth()->timestamp;
  19. $calendar = DB::table('calendar')
  20. ->where('del_time', 0)
  21. ->where('time', $monthStart)
  22. ->first();
  23. if (!$calendar) return [false, '当月日历未配置'];
  24. $hasWorkDays = DB::table('calendar_details')
  25. ->where('del_time', 0)
  26. ->where('calendar_id', $calendar->id)
  27. ->where('is_work', 1)
  28. ->exists();
  29. if (!$hasWorkDays) return [false, '当月无工作日,无法生成'];
  30. // try {
  31. // DB::transaction(function () use($data) {
  32. // $this->doGenerate($data['month']);
  33. // });
  34. // } catch (\Exception $e) {
  35. // // 只有这里 throw 了,任务才会进入 failed_jobs 表
  36. // return [false, $e->getMessage()];
  37. //
  38. // }dd(2);
  39. $key = self::job_name . $data['month'];
  40. $data['lock_key'] = $key;
  41. list($status, $msg) = $this->limitingSendRequest($key);
  42. if (!$status) return [false, '该月设备数据已在后台处理,请勿重复操作'];
  43. ProcessDataJob::dispatch($data)->onQueue(self::job_name);
  44. return [true, '任务已放到后台运行'];
  45. }
  46. public function delTableKey($key) {
  47. $this->dellimitingSendRequest($key);
  48. }
  49. /**
  50. * 队列真正执行的逻辑
  51. */
  52. public function doGenerate(string $month)
  53. {
  54. $monthStart = Carbon::createFromFormat('Y-m', $month)->startOfMonth()->timestamp;
  55. $monthEnd = Carbon::createFromFormat('Y-m', $month)->endOfMonth()->timestamp;
  56. // 1. 获取日历和工作日
  57. $calendar = DB::table('calendar')->where('del_time', 0)->where('time', $monthStart)->first();
  58. if (!$calendar) throw new \Exception('当月日历未配置');
  59. $workDays = DB::table('calendar_details')
  60. ->where('del_time', 0)->where('calendar_id', $calendar->id)->where('is_work', 1)
  61. ->orderBy('time')->pluck('time')->toArray();
  62. // 2. 获取当月有效项目
  63. $items = DB::table('item')->where('del_time', 0)->where('is_use', 1)
  64. ->where('start_time', '<=', $monthEnd)->where('end_time', '>=', $monthStart)
  65. ->orderBy('id', 'desc')->get();
  66. if ($items->isEmpty() || empty($workDays)) return;
  67. // 3. 清理旧数据
  68. $rds = DB::table('rd')->where('del_time', 0)->where('type', RD::type_two)
  69. ->whereBetween('order_time', [$monthStart, $monthEnd])->pluck('id')->toArray();
  70. if (!empty($rds)) {
  71. foreach (array_chunk($rds, 1000) as $chunk) {
  72. DB::table('rd_details')->whereIn('rd_id', $chunk)->delete();
  73. DB::table('rd')->whereIn('id', $chunk)->delete();
  74. }
  75. }
  76. // 4. 获取设备配置
  77. $deviceConfigs = DB::table('device_details')->where('del_time', 0)
  78. ->where('time', $calendar->time)->where('total_hours_2', '>', 0)->get();
  79. // --- 核心:按槽位合并逻辑开始 ---
  80. // 5. 内存计算:将所有设备的工时分配到槽位中合并
  81. // $slots[日期][项目ID][时间槽Key] = ['start'=>Carbon, 'end'=>Carbon, 'device_ids'=>[]]
  82. $slots = [];
  83. foreach ($deviceConfigs as $config) {
  84. $this->assignDeviceToSlots($config, $items, $workDays, $slots);
  85. }
  86. // 6. 构造主表批量插入数组
  87. $pendingRds = [];
  88. $rdToDevicesMap = []; // order_number => ['device_ids' => [], 'crt_time' => ...]
  89. foreach ($slots as $day => $projectGroups) {
  90. $baseCrtTime = $day + 59400; // 创建时间从 16:30 开始递增
  91. $sequence = 0;
  92. foreach ($projectGroups as $itemId => $timeBlocks) {
  93. foreach ($timeBlocks as $timeKey => $data) {
  94. // ... 循环内部 ...
  95. $dateStr = date('Ymd', $day);
  96. // 结合项目ID、循环序列和4位随机字符,兼顾了短小和唯一性
  97. $orderNumber = sprintf("RD%s%d%s%s",
  98. $dateStr,
  99. $itemId,
  100. dechex($sequence),
  101. substr(md5(mt_rand()), 0, 4)
  102. );
  103. // $orderNumber = 'RD' . $day . 'P' . $itemId . 'S' . $sequence . uniqid();
  104. $crtTime = $baseCrtTime + ($sequence * 10) + mt_rand(0, 5);
  105. $pendingRds[] = [
  106. 'crt_time' => $crtTime,
  107. 'order_time' => $day,
  108. 'item_id' => $itemId,
  109. 'start_time_hour' => $data['start']->hour,
  110. 'start_time_min' => $data['start']->minute,
  111. 'end_time_hour' => $data['end']->hour,
  112. 'end_time_min' => $data['end']->minute,
  113. 'total_hours' => 60,
  114. 'order_number' => $orderNumber,
  115. 'type' => RD::type_two,
  116. 'del_time' => 0
  117. ];
  118. $rdToDevicesMap[$orderNumber] = [
  119. 'device_ids' => $data['device_ids'],
  120. 'crt_time' => $crtTime
  121. ];
  122. $sequence++;
  123. }
  124. }
  125. }
  126. // 7. 批量插入并同步详情
  127. if (empty($pendingRds)) return;
  128. foreach (array_chunk($pendingRds, 1000) as $chunk) {
  129. DB::table('rd')->insert($chunk);
  130. }
  131. // 通过 order_number 找回生成的 ID
  132. $insertedRds = DB::table('rd')->whereIn('order_number', array_keys($rdToDevicesMap))
  133. ->select('id', 'order_number')->get();
  134. $pendingDetails = [];
  135. foreach ($insertedRds as $rd) {
  136. $mapData = $rdToDevicesMap[$rd->order_number];
  137. foreach ($mapData['device_ids'] as $deviceId) {
  138. $pendingDetails[] = [
  139. 'rd_id' => $rd->id,
  140. 'data_id' => $deviceId,
  141. 'type' => RD::type_two,
  142. 'crt_time' => $mapData['crt_time'],
  143. 'upd_time' => $mapData['crt_time'],
  144. 'del_time' => 0
  145. ];
  146. }
  147. }
  148. foreach (array_chunk($pendingDetails, 1000) as $chunk) {
  149. DB::table('rd_details')->insert($chunk);
  150. }
  151. }
  152. /**
  153. * 计算并分配每个设备的工时到公共槽位
  154. */
  155. protected function assignDeviceToSlots($config, $items, $workDays, &$slots)
  156. {
  157. $totalMinutes = intval(round($config->total_hours_2 * 60) / 60) * 60;
  158. // 筛选有效天
  159. $validDays = [];
  160. foreach ($workDays as $day) {
  161. $dayItems = [];
  162. foreach ($items as $item) {
  163. if ($day >= $item->start_time && $day <= $item->end_time) $dayItems[] = $item;
  164. }
  165. if (!empty($dayItems)) $validDays[$day] = $dayItems;
  166. }
  167. if (empty($validDays)) return;
  168. $dailyMinutesMap = $this->distributeMinutes(count($validDays), $totalMinutes, array_keys($validDays));
  169. foreach ($validDays as $day => $dayItems) {
  170. $dailyMinutes = $dailyMinutesMap[$day];
  171. if ($dailyMinutes <= 0) continue;
  172. // 为了让不同设备能合并,使用固定的 8:00 作为参考起点
  173. $currentTimePointer = Carbon::createFromTimestamp($day)->setTime(8, 0);
  174. $lunchStart = Carbon::createFromTimestamp($day)->setTime(11, 30);
  175. $lunchEnd = Carbon::createFromTimestamp($day)->setTime(12, 0);
  176. $totalHoursToday = $dailyMinutes / 60;
  177. for ($h = 0; $h < $totalHoursToday; $h++) {
  178. // 如果是多个设备同一时间做同一个项目,这里最好保证选择项目的随机种子在同一天内是对齐的,
  179. // 或者业务允许随机。这里按设备随机选一个。
  180. $item = $dayItems[array_rand($dayItems)];
  181. $start = $currentTimePointer->copy();
  182. // 跳过午休起始点
  183. if ($start->gte($lunchStart) && $start->lt($lunchEnd)) {
  184. $start = $lunchEnd->copy();
  185. }
  186. $end = $start->copy()->addMinutes(60);
  187. // 跨午休处理
  188. if ($start->lt($lunchStart) && $end->gt($lunchStart)) {
  189. $end->addMinutes(30);
  190. }
  191. // 生成用于合并的槽位 Key
  192. $timeKey = $start->format('Hi') . '-' . $end->format('Hi');
  193. // 存入合并缓冲区
  194. $slots[$day][$item->id][$timeKey]['start'] = $start;
  195. $slots[$day][$item->id][$timeKey]['end'] = $end;
  196. $slots[$day][$item->id][$timeKey]['device_ids'][] = $config->device_id;
  197. // 指针移动(接力)
  198. $currentTimePointer = $end->copy();
  199. }
  200. }
  201. }
  202. private function distributeMinutes($daysCount, $totalMinutes, $dayKeys) {
  203. $avg = (intval(floor($totalMinutes / $daysCount) / 60)) * 60;
  204. $res = array_fill_keys($dayKeys, $avg);
  205. $rem = ($totalMinutes - ($avg * $daysCount)) / 60;
  206. for($i=0; $i<$rem; $i++) { $res[$dayKeys[$i % $daysCount]] += 60; }
  207. return $res;
  208. }
  209. }