UserLogLogic.php 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. <?php
  2. namespace App\Module\Game\Logics;
  3. use App\Module\Game\Models\UserLog;
  4. use App\Module\Game\Models\UserLogClearRecord;
  5. use Illuminate\Pagination\LengthAwarePaginator;
  6. use Illuminate\Support\Facades\DB;
  7. use UCore\Helper\Logger;
  8. /**
  9. * 用户日志逻辑类
  10. *
  11. * 负责处理用户日志的业务逻辑,包括:
  12. * 1. 日志记录
  13. * 2. 日志查询
  14. * 3. 日志清理
  15. * 4. 批量处理
  16. */
  17. class UserLogLogic
  18. {
  19. /**
  20. * 记录用户日志
  21. *
  22. * @param int $userId 用户ID
  23. * @param string $message 日志消息
  24. * @param string|null $sourceType 来源类型
  25. * @param int|null $sourceId 来源记录ID
  26. * @param string|null $sourceTable 来源表名
  27. * @return UserLog|null
  28. */
  29. public static function log(
  30. int $userId,
  31. string $message,
  32. ?string $sourceType = null,
  33. ?int $sourceId = null,
  34. ?string $sourceTable = null
  35. ): ?UserLog {
  36. try {
  37. $userLog = new UserLog();
  38. $userLog->user_id = $userId;
  39. $userLog->message = $message;
  40. $userLog->source_type = $sourceType;
  41. $userLog->source_id = $sourceId;
  42. $userLog->source_table = $sourceTable;
  43. $userLog->save();
  44. return $userLog;
  45. } catch (\Exception $e) {
  46. Logger::exception('记录用户日志失败', $e, [
  47. 'user_id' => $userId,
  48. 'message' => $message,
  49. 'source_type' => $sourceType,
  50. 'source_id' => $sourceId,
  51. 'source_table' => $sourceTable,
  52. ]);
  53. return null;
  54. }
  55. }
  56. /**
  57. * 批量记录用户日志
  58. *
  59. * @param array $logs 日志数据数组
  60. * @return bool
  61. */
  62. public static function batchLog(array $logs): bool
  63. {
  64. try {
  65. DB::beginTransaction();
  66. foreach ($logs as $logData) {
  67. $userLog = new UserLog();
  68. $userLog->user_id = $logData['user_id'];
  69. $userLog->message = $logData['message'];
  70. $userLog->source_type = $logData['source_type'] ?? null;
  71. $userLog->source_id = $logData['source_id'] ?? null;
  72. $userLog->source_table = $logData['source_table'] ?? null;
  73. $userLog->save();
  74. }
  75. DB::commit();
  76. return true;
  77. } catch (\Exception $e) {
  78. DB::rollBack();
  79. Logger::exception('批量记录用户日志失败', $e, [
  80. 'logs_count' => count($logs),
  81. ]);
  82. return false;
  83. }
  84. }
  85. /**
  86. * 获取用户日志列表
  87. *
  88. * @param int $userId 用户ID
  89. * @param int $page 页码
  90. * @param int $pageSize 每页数量
  91. * @param array $filters 过滤条件
  92. * @return LengthAwarePaginator
  93. */
  94. public static function getUserLogs(
  95. int $userId,
  96. int $page = 1,
  97. int $pageSize = 20,
  98. array $filters = []
  99. ): LengthAwarePaginator {
  100. try {
  101. $query = UserLog::byUser($userId)->latest();
  102. // 获取用户的最后清理时间,只返回清理时间之后的日志
  103. $lastClearTime = UserLogClearRecord::getUserLastClearTime($userId);
  104. if ($lastClearTime) {
  105. $query->where('created_at', '>', $lastClearTime);
  106. }
  107. // 应用过滤条件
  108. if (!empty($filters['source_type'])) {
  109. $query->bySourceType($filters['source_type']);
  110. }
  111. if (!empty($filters['start_time']) && !empty($filters['end_time'])) {
  112. $query->byTimeRange($filters['start_time'], $filters['end_time']);
  113. }
  114. if (!empty($filters['keyword'])) {
  115. $query->where('message', 'like', '%' . $filters['keyword'] . '%');
  116. }
  117. return $query->paginate($pageSize, ['*'], 'page', $page);
  118. } catch (\Exception $e) {
  119. Logger::exception('获取用户日志列表失败', $e, [
  120. 'user_id' => $userId,
  121. 'page' => $page,
  122. 'page_size' => $pageSize,
  123. 'filters' => $filters,
  124. ]);
  125. // 返回空的分页结果
  126. return new LengthAwarePaginator([], 0, $pageSize, $page);
  127. }
  128. }
  129. /**
  130. * 清空用户日志(逻辑清理)
  131. * 不真实删除日志,而是记录清理时间,只返回清理时间之后的日志给用户
  132. * 这样可以避免影响日志收集备份工作
  133. *
  134. * @param int $userId 用户ID
  135. * @return bool
  136. */
  137. public static function clearUserLogs(int $userId): bool
  138. {
  139. try {
  140. // 获取当前时间作为清理时间
  141. $clearTime = now();
  142. // 记录用户的清理时间
  143. UserLogClearRecord::setUserClearTime($userId, $clearTime);
  144. Logger::info('清空用户日志成功(逻辑清理)', [
  145. 'user_id' => $userId,
  146. 'clear_time' => $clearTime->toDateTimeString(),
  147. ]);
  148. return true;
  149. } catch (\Exception $e) {
  150. Logger::exception('清空用户日志失败', $e, [
  151. 'user_id' => $userId,
  152. ]);
  153. return false;
  154. }
  155. }
  156. /**
  157. * 清理过期日志
  158. *
  159. * @param int $days 保留天数
  160. * @return int 删除的记录数
  161. */
  162. public static function cleanExpiredLogs(int $days = 30): int
  163. {
  164. try {
  165. $expiredDate = now()->subDays($days);
  166. $deletedCount = UserLog::where('created_at', '<', $expiredDate)->delete();
  167. Logger::info('清理过期日志成功', [
  168. 'days' => $days,
  169. 'expired_date' => $expiredDate->toDateTimeString(),
  170. 'deleted_count' => $deletedCount,
  171. ]);
  172. return $deletedCount;
  173. } catch (\Exception $e) {
  174. Logger::exception('清理过期日志失败', $e, [
  175. 'days' => $days,
  176. ]);
  177. return 0;
  178. }
  179. }
  180. /**
  181. * 获取用户日志统计信息
  182. *
  183. * @param int $userId 用户ID
  184. * @return array
  185. */
  186. public static function getUserLogStats(int $userId): array
  187. {
  188. try {
  189. // 获取用户的最后清理时间,只统计清理时间之后的日志
  190. $lastClearTime = UserLogClearRecord::getUserLastClearTime($userId);
  191. $baseQuery = UserLog::byUser($userId);
  192. if ($lastClearTime) {
  193. $baseQuery->where('created_at', '>', $lastClearTime);
  194. }
  195. $stats = [
  196. 'total_count' => (clone $baseQuery)->count(),
  197. 'today_count' => (clone $baseQuery)
  198. ->whereDate('created_at', today())
  199. ->count(),
  200. 'week_count' => (clone $baseQuery)
  201. ->where('created_at', '>=', now()->startOfWeek())
  202. ->count(),
  203. 'month_count' => (clone $baseQuery)
  204. ->where('created_at', '>=', now()->startOfMonth())
  205. ->count(),
  206. ];
  207. // 按来源类型统计
  208. $sourceTypeStats = (clone $baseQuery)
  209. ->select('source_type', DB::raw('count(*) as count'))
  210. ->whereNotNull('source_type')
  211. ->groupBy('source_type')
  212. ->pluck('count', 'source_type')
  213. ->toArray();
  214. $stats['source_type_stats'] = $sourceTypeStats;
  215. return $stats;
  216. } catch (\Exception $e) {
  217. Logger::exception('获取用户日志统计信息失败', $e, [
  218. 'user_id' => $userId,
  219. ]);
  220. return [];
  221. }
  222. }
  223. /**
  224. * 检查用户是否有日志记录
  225. *
  226. * @param int $userId 用户ID
  227. * @return bool
  228. */
  229. public static function hasUserLogs(int $userId): bool
  230. {
  231. try {
  232. $query = UserLog::byUser($userId);
  233. // 获取用户的最后清理时间,只检查清理时间之后的日志
  234. $lastClearTime = UserLogClearRecord::getUserLastClearTime($userId);
  235. if ($lastClearTime) {
  236. $query->where('created_at', '>', $lastClearTime);
  237. }
  238. return $query->exists();
  239. } catch (\Exception $e) {
  240. Logger::exception('检查用户日志记录失败', $e, [
  241. 'user_id' => $userId,
  242. ]);
  243. return false;
  244. }
  245. }
  246. /**
  247. * 获取最新的用户日志
  248. *
  249. * @param int $userId 用户ID
  250. * @param int $limit 数量限制
  251. * @return \Illuminate\Database\Eloquent\Collection
  252. */
  253. public static function getLatestUserLogs(int $userId, int $limit = 10)
  254. {
  255. try {
  256. $query = UserLog::byUser($userId)->latest();
  257. // 获取用户的最后清理时间,只返回清理时间之后的日志
  258. $lastClearTime = UserLogClearRecord::getUserLastClearTime($userId);
  259. if ($lastClearTime) {
  260. $query->where('created_at', '>', $lastClearTime);
  261. }
  262. return $query->limit($limit)->get();
  263. } catch (\Exception $e) {
  264. Logger::exception('获取最新用户日志失败', $e, [
  265. 'user_id' => $userId,
  266. 'limit' => $limit,
  267. ]);
  268. return collect();
  269. }
  270. }
  271. }