AdminService.php 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. <?php
  2. namespace App\Module\Admin\Services;
  3. use App\Module\Admin\Enums\ADMIN_ACTION_TYPE;
  4. use App\Module\Admin\Events\AdminActionEvent;
  5. use App\Module\Admin\Utils\SystemInfo;
  6. use Illuminate\Support\Facades\Auth;
  7. use Illuminate\Support\Facades\Cache;
  8. use Illuminate\Support\Facades\Event;
  9. use Illuminate\Support\Facades\Log;
  10. /**
  11. * Admin模块核心服务
  12. */
  13. class AdminService
  14. {
  15. /**
  16. * 获取仪表板数据
  17. *
  18. * @return array
  19. */
  20. public function getDashboardData(): array
  21. {
  22. return Cache::remember('admin.dashboard.data', 300, function () {
  23. $systemInfo = new SystemInfo();
  24. return [
  25. 'system' => [
  26. 'server_info' => $systemInfo->getServerInfo(),
  27. 'php_info' => $systemInfo->getPhpInfo(),
  28. 'database_info' => $systemInfo->getDatabaseInfo(),
  29. 'performance' => $systemInfo->getPerformanceMetrics(),
  30. ],
  31. 'statistics' => [
  32. 'users_online' => $this->getOnlineUsersCount(),
  33. 'total_requests' => $this->getTotalRequestsCount(),
  34. 'error_rate' => $this->getErrorRate(),
  35. 'response_time' => $this->getAverageResponseTime(),
  36. ],
  37. 'alerts' => $this->getSystemAlerts(),
  38. 'recent_actions' => $this->getRecentActions(),
  39. ];
  40. });
  41. }
  42. /**
  43. * 记录管理员操作
  44. *
  45. * @param ADMIN_ACTION_TYPE $actionType
  46. * @param string $description
  47. * @param array $data
  48. * @return void
  49. */
  50. public function logAdminAction(ADMIN_ACTION_TYPE $actionType, string $description, array $data = []): void
  51. {
  52. $adminUser = Auth::guard('admin')->user();
  53. $logData = [
  54. 'admin_id' => $adminUser?->id,
  55. 'admin_name' => $adminUser?->name ?? 'System',
  56. 'action_type' => $actionType->value,
  57. 'description' => $description,
  58. 'data' => $data,
  59. 'ip_address' => request()->ip(),
  60. 'user_agent' => request()->userAgent(),
  61. 'timestamp' => now(),
  62. ];
  63. // 触发事件
  64. Event::dispatch(new AdminActionEvent($logData));
  65. // 记录日志
  66. if ($actionType->needsDetailedLog()) {
  67. Log::channel('admin')->info("Admin Action: {$description}", $logData);
  68. }
  69. // 危险操作额外记录
  70. if ($actionType->isDangerous()) {
  71. Log::channel('admin')->warning("Dangerous Admin Action: {$description}", $logData);
  72. }
  73. }
  74. /**
  75. * 获取在线用户数量
  76. *
  77. * @return int
  78. */
  79. protected function getOnlineUsersCount(): int
  80. {
  81. // 这里可以根据实际需求实现
  82. // 例如:统计最近5分钟内有活动的用户
  83. return Cache::remember('admin.stats.online_users', 60, function () {
  84. // 实现逻辑
  85. return 0;
  86. });
  87. }
  88. /**
  89. * 获取总请求数
  90. *
  91. * @return int
  92. */
  93. protected function getTotalRequestsCount(): int
  94. {
  95. return Cache::remember('admin.stats.total_requests', 300, function () {
  96. // 实现逻辑
  97. return 0;
  98. });
  99. }
  100. /**
  101. * 获取错误率
  102. *
  103. * @return float
  104. */
  105. protected function getErrorRate(): float
  106. {
  107. return Cache::remember('admin.stats.error_rate', 300, function () {
  108. // 实现逻辑
  109. return 0.0;
  110. });
  111. }
  112. /**
  113. * 获取平均响应时间
  114. *
  115. * @return float
  116. */
  117. protected function getAverageResponseTime(): float
  118. {
  119. return Cache::remember('admin.stats.response_time', 300, function () {
  120. // 实现逻辑
  121. return 0.0;
  122. });
  123. }
  124. /**
  125. * 获取系统警报
  126. *
  127. * @return array
  128. */
  129. protected function getSystemAlerts(): array
  130. {
  131. $alerts = [];
  132. $systemInfo = new SystemInfo();
  133. $config = config('admin_module.monitoring.alerts');
  134. // CPU使用率警报
  135. $cpuUsage = $systemInfo->getCpuUsage();
  136. if ($cpuUsage > $config['cpu_threshold']) {
  137. $alerts[] = [
  138. 'type' => 'warning',
  139. 'title' => 'CPU使用率过高',
  140. 'message' => "当前CPU使用率: {$cpuUsage}%",
  141. 'timestamp' => now(),
  142. ];
  143. }
  144. // 内存使用率警报
  145. $memoryUsage = $systemInfo->getMemoryUsage();
  146. if ($memoryUsage['percentage'] > $config['memory_threshold']) {
  147. $alerts[] = [
  148. 'type' => 'warning',
  149. 'title' => '内存使用率过高',
  150. 'message' => "当前内存使用率: {$memoryUsage['percentage']}%",
  151. 'timestamp' => now(),
  152. ];
  153. }
  154. // 磁盘使用率警报
  155. $diskUsage = $systemInfo->getDiskUsage();
  156. if ($diskUsage['percentage'] > $config['disk_threshold']) {
  157. $alerts[] = [
  158. 'type' => 'danger',
  159. 'title' => '磁盘空间不足',
  160. 'message' => "当前磁盘使用率: {$diskUsage['percentage']}%",
  161. 'timestamp' => now(),
  162. ];
  163. }
  164. return $alerts;
  165. }
  166. /**
  167. * 获取最近的操作记录
  168. *
  169. * @param int $limit
  170. * @return array
  171. */
  172. protected function getRecentActions(int $limit = 10): array
  173. {
  174. return Cache::remember("admin.recent_actions.{$limit}", 60, function () use ($limit) {
  175. // 这里应该从数据库获取最近的操作记录
  176. // 暂时返回空数组
  177. return [];
  178. });
  179. }
  180. /**
  181. * 获取系统状态
  182. *
  183. * @return array
  184. */
  185. public function getSystemStatus(): array
  186. {
  187. $systemInfo = new SystemInfo();
  188. return [
  189. 'status' => 'running',
  190. 'uptime' => $systemInfo->getUptime(),
  191. 'load_average' => $systemInfo->getLoadAverage(),
  192. 'memory_usage' => $systemInfo->getMemoryUsage(),
  193. 'disk_usage' => $systemInfo->getDiskUsage(),
  194. 'database_status' => $systemInfo->getDatabaseStatus(),
  195. 'cache_status' => $this->getCacheStatus(),
  196. 'queue_status' => $this->getQueueStatus(),
  197. ];
  198. }
  199. /**
  200. * 获取缓存状态
  201. *
  202. * @return array
  203. */
  204. protected function getCacheStatus(): array
  205. {
  206. try {
  207. Cache::put('admin.cache.test', 'test', 1);
  208. $test = Cache::get('admin.cache.test');
  209. Cache::forget('admin.cache.test');
  210. return [
  211. 'status' => $test === 'test' ? 'healthy' : 'error',
  212. 'driver' => config('cache.default'),
  213. ];
  214. } catch (\Exception $e) {
  215. return [
  216. 'status' => 'error',
  217. 'error' => $e->getMessage(),
  218. ];
  219. }
  220. }
  221. /**
  222. * 获取队列状态
  223. *
  224. * @return array
  225. */
  226. protected function getQueueStatus(): array
  227. {
  228. try {
  229. return [
  230. 'status' => 'healthy',
  231. 'driver' => config('queue.default'),
  232. 'pending_jobs' => 0, // 这里可以实现获取待处理任务数量的逻辑
  233. ];
  234. } catch (\Exception $e) {
  235. return [
  236. 'status' => 'error',
  237. 'error' => $e->getMessage(),
  238. ];
  239. }
  240. }
  241. /**
  242. * 执行系统维护
  243. *
  244. * @param array $options
  245. * @return array
  246. */
  247. public function performMaintenance(array $options = []): array
  248. {
  249. $results = [];
  250. // 清理缓存
  251. if ($options['clear_cache'] ?? true) {
  252. $cacheService = app('admin.cache');
  253. $results['cache'] = $cacheService->clearAll();
  254. }
  255. // 清理日志
  256. if ($options['clean_logs'] ?? false) {
  257. $logService = app('admin.log');
  258. $results['logs'] = $logService->cleanOldLogs();
  259. }
  260. // 优化数据库
  261. if ($options['optimize_database'] ?? false) {
  262. $results['database'] = $this->optimizeDatabase();
  263. }
  264. // 记录维护操作
  265. $this->logAdminAction(
  266. ADMIN_ACTION_TYPE::MAINTENANCE,
  267. '执行系统维护',
  268. ['options' => $options, 'results' => $results]
  269. );
  270. return $results;
  271. }
  272. /**
  273. * 优化数据库
  274. *
  275. * @return array
  276. */
  277. protected function optimizeDatabase(): array
  278. {
  279. try {
  280. // 这里可以实现数据库优化逻辑
  281. return [
  282. 'status' => 'success',
  283. 'message' => '数据库优化完成',
  284. ];
  285. } catch (\Exception $e) {
  286. return [
  287. 'status' => 'error',
  288. 'message' => $e->getMessage(),
  289. ];
  290. }
  291. }
  292. }