PointsStatsService.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. <?php
  2. namespace App\Services;
  3. use App\Facade\Site;
  4. use App\Libs\Utils;
  5. use Illuminate\Support\Facades\DB;
  6. class PointsStatsService
  7. {
  8. /** group_by 合法维度 */
  9. private const GROUP_BY_DIMS = ['date', 'uid', 'model', 'relay'];
  10. /**
  11. * 解析 group_by 参数为合法维度列表;空/非法时回退全部维度,自动去重保序。
  12. */
  13. public static function parseGroupBy($groupBy = ''): array
  14. {
  15. if (!is_string($groupBy) || trim($groupBy) === '') {
  16. return self::GROUP_BY_DIMS;
  17. }
  18. $result = [];
  19. foreach (explode(',', $groupBy) as $part) {
  20. $part = trim($part);
  21. if (in_array($part, self::GROUP_BY_DIMS, true) && !in_array($part, $result, true)) {
  22. $result[] = $part;
  23. }
  24. }
  25. return $result ?: self::GROUP_BY_DIMS;
  26. }
  27. /**
  28. * 聚合指定日期明细到统计表(幂等:先删该日旧数据再批量插入)。
  29. *
  30. * @param string $date Y-m-d
  31. * @return int 写入行数
  32. */
  33. public function statsForDate(string $date): int
  34. {
  35. $start = $date . ' 00:00:00';
  36. $end = $date . ' 23:59:59';
  37. // 模型名解析:charge_info.model 优先,空则 api_type,再空 unknown
  38. $modelExpr = "COALESCE(NULLIF(JSON_UNQUOTE(JSON_EXTRACT(d.charge_info, '$.model')), ''), NULLIF(d.api_type, ''), 'unknown')";
  39. $rows = DB::table('mp_user_points_details as d')
  40. ->leftJoin('mp_model_relay_map as m', 'm.model', '=', DB::raw($modelExpr))
  41. // cpid 以用户表当前所属组织为准(明细历史数据存在同 uid 不同 cpid 的脏数据)
  42. ->leftJoin('mp_manage_users as u', 'u.id', '=', 'd.uid')
  43. ->whereIn('d.type', ['chat', 'image', 'video'])
  44. ->where('d.created_at', '>=', $start)
  45. ->where('d.created_at', '<=', $end)
  46. ->selectRaw("DATE(d.created_at) AS stat_date, d.uid, COALESCE(u.cpid, 0) AS cpid, {$modelExpr} AS model, COALESCE(m.relay_name, 'unknown') AS relay, COALESCE(m.model_type, d.type) AS model_type, COUNT(*) AS call_count, SUM(d.tokens_consumed) AS tokens_consumed, SUM(d.points_consumed) AS points_consumed")
  47. ->groupByRaw("DATE(d.created_at), d.uid, {$modelExpr}, COALESCE(m.relay_name, 'unknown'), COALESCE(m.model_type, d.type)")
  48. ->get()
  49. ->map(function ($row) use ($date) {
  50. return [
  51. 'stat_date' => $date,
  52. 'uid' => (int)$row->uid,
  53. 'cpid' => (int)$row->cpid,
  54. 'model' => (string)$row->model,
  55. 'relay' => (string)$row->relay,
  56. 'model_type' => (string)$row->model_type,
  57. 'call_count' => (int)$row->call_count,
  58. 'tokens_consumed' => (int)$row->tokens_consumed,
  59. 'points_consumed' => (float)$row->points_consumed,
  60. 'created_at' => date('Y-m-d H:i:s'),
  61. 'updated_at' => date('Y-m-d H:i:s'),
  62. ];
  63. })
  64. ->all();
  65. DB::transaction(function () use ($date, $rows) {
  66. DB::table('mp_points_daily_stats')->where('stat_date', $date)->delete();
  67. if ($rows) {
  68. DB::table('mp_points_daily_stats')->insert($rows);
  69. }
  70. });
  71. return count($rows);
  72. }
  73. /**
  74. * 当前角色可查看的统计范围:superadmin 全部;admin 本组织;user 仅自己;其他抛错。
  75. *
  76. * @return array ['cpid' => int 组织限定(0 不限定), 'uid' => int 用户限定(0 不限定)]
  77. */
  78. private function assertCanView(): array
  79. {
  80. $role = (string)Site::getRole();
  81. if ($role === 'superadmin') {
  82. return ['cpid' => 0, 'uid' => 0];
  83. }
  84. if ($role === 'admin') {
  85. return ['cpid' => (int)Site::getCpid(), 'uid' => 0];
  86. }
  87. if ($role === 'user') {
  88. return ['cpid' => (int)Site::getCpid(), 'uid' => (int)Site::getUid()];
  89. }
  90. Utils::throwError('1005:无权查看统计数据');
  91. }
  92. /**
  93. * 构建统计查询(含权限过滤与 group_by 聚合)。
  94. *
  95. * @param array $params 筛选参数
  96. * @param array $groupBy 聚合维度列表
  97. * @return array [查询构建器, 维度=>列映射]
  98. */
  99. private function buildStatsQuery(array $params, array $groupBy)
  100. {
  101. $scope = $this->assertCanView();
  102. $query = DB::table('mp_points_daily_stats as s')
  103. ->leftJoin('mp_manage_users as u', 'u.id', '=', 's.uid');
  104. if ($scope['cpid'] > 0) {
  105. $query->where('s.cpid', $scope['cpid']);
  106. }
  107. if ($scope['uid'] > 0) {
  108. $query->where('s.uid', $scope['uid']);
  109. }
  110. $startDate = (string)getProp($params, 'start_date', date('Y-m-d', strtotime('-29 days')));
  111. $endDate = (string)getProp($params, 'end_date', date('Y-m-d'));
  112. if ($startDate) {
  113. $query->where('s.stat_date', '>=', $startDate);
  114. }
  115. if ($endDate) {
  116. $query->where('s.stat_date', '<=', $endDate);
  117. }
  118. $uid = (string)getProp($params, 'uid', '');
  119. // 普通用户仅能查看自己,忽略传入的 uid 筛选
  120. if ($uid !== '' && $scope['uid'] <= 0) {
  121. $uids = array_values(array_filter(array_map('intval', explode(',', $uid))));
  122. if ($uids) {
  123. $query->whereIn('s.uid', $uids);
  124. }
  125. }
  126. $nickname = trim((string)getProp($params, 'nickname', ''));
  127. if ($nickname !== '') {
  128. $query->where(function ($q) use ($nickname) {
  129. $q->where('u.nickname', 'like', '%' . $nickname . '%')
  130. ->orWhere('u.account', 'like', '%' . $nickname . '%');
  131. });
  132. }
  133. $model = (string)getProp($params, 'model', '');
  134. if ($model !== '') {
  135. $query->where('s.model', $model);
  136. }
  137. $relay = (string)getProp($params, 'relay', '');
  138. if ($relay !== '') {
  139. $query->where('s.relay', $relay);
  140. }
  141. $modelType = (string)getProp($params, 'model_type', '');
  142. if (in_array($modelType, ['chat', 'image', 'video'], true)) {
  143. $query->where('s.model_type', $modelType);
  144. }
  145. $dimToCol = [
  146. 'date' => 's.stat_date',
  147. 'uid' => 's.uid',
  148. 'model' => 's.model',
  149. 'relay' => 's.relay',
  150. ];
  151. $cols = [];
  152. $groupRaw = [];
  153. foreach ($groupBy as $dim) {
  154. $cols[] = $dimToCol[$dim] . ' AS dim_' . $dim;
  155. $groupRaw[] = $dimToCol[$dim];
  156. }
  157. // 按 model 分组时 model_type 有确定值(模型→类型一对一),随分组输出
  158. if (in_array('model', $groupBy, true)) {
  159. $cols[] = 's.model_type AS dim_model_type';
  160. $groupRaw[] = 's.model_type';
  161. }
  162. $cols[] = 'SUM(s.call_count) AS call_count';
  163. $cols[] = 'SUM(s.tokens_consumed) AS tokens_consumed';
  164. $cols[] = 'SUM(s.points_consumed) AS points_consumed';
  165. $query->selectRaw(implode(', ', $cols));
  166. if ($groupRaw) {
  167. $query->groupByRaw(implode(', ', $groupRaw));
  168. }
  169. return [$query, $dimToCol];
  170. }
  171. /**
  172. * 查询统计列表(分页)。
  173. */
  174. public function getStats(array $params): array
  175. {
  176. $groupBy = self::parseGroupBy(getProp($params, 'group_by', ''));
  177. [$query] = $this->buildStatsQuery($params, $groupBy);
  178. $pageSize = (int)getProp($params, 'page_size', 15);
  179. if ($pageSize < 1 || $pageSize > 100) {
  180. $pageSize = 15;
  181. }
  182. // 按日期分组时日期倒序展示
  183. if (in_array('date', $groupBy, true)) {
  184. $query->orderByDesc('s.stat_date');
  185. }
  186. $rows = $query->paginate($pageSize)->through(function ($row) use ($groupBy) {
  187. $item = [];
  188. foreach ($groupBy as $dim) {
  189. $item[$dim] = $dim === 'uid' ? (int)$row->{'dim_' . $dim} : (string)$row->{'dim_' . $dim};
  190. }
  191. $item['call_count'] = (int)$row->call_count;
  192. $item['tokens_consumed'] = (int)$row->tokens_consumed;
  193. $item['points_consumed'] = (float)$row->points_consumed;
  194. $item['model_type'] = (string)($row->dim_model_type ?? '');
  195. return $item;
  196. });
  197. $list = $rows->items();
  198. if (in_array('uid', $groupBy, true) && $list) {
  199. $uids = array_unique(array_column($list, 'uid'));
  200. $userMap = DB::table('mp_manage_users')->whereIn('id', $uids)
  201. ->pluck('nickname', 'id')->map(function ($v) {
  202. return (string)$v;
  203. })->all();
  204. foreach ($list as &$item) {
  205. $item['nickname'] = $userMap[$item['uid']] ?? '';
  206. }
  207. unset($item);
  208. }
  209. return [
  210. 'summary' => $this->getSummary($params),
  211. 'meta' => getMeta($rows),
  212. 'list' => $list,
  213. ];
  214. }
  215. /**
  216. * 当前筛选条件下的合计(不按维度分组)。
  217. */
  218. public function getSummary(array $params): array
  219. {
  220. [$query] = $this->buildStatsQuery($params, []);
  221. $row = $query->first();
  222. return [
  223. 'call_count' => (int)($row->call_count ?? 0),
  224. 'tokens_consumed' => (int)($row->tokens_consumed ?? 0),
  225. 'points_consumed' => (float)($row->points_consumed ?? 0),
  226. ];
  227. }
  228. /**
  229. * 筛选项来源:用户/模型/中转站/模型类型/日期范围。
  230. *
  231. * 选项统一为 {name: 显示名称, value: 传给后端的筛选值},前端展示 name、提交 value。
  232. */
  233. public function getFilters(array $params = []): array
  234. {
  235. $scope = $this->assertCanView();
  236. $users = DB::table('mp_manage_users')
  237. ->when($scope['cpid'] > 0, function ($q) use ($scope) {
  238. $q->where('cpid', $scope['cpid']);
  239. })
  240. ->when($scope['uid'] > 0, function ($q) use ($scope) {
  241. $q->where('id', $scope['uid']);
  242. })
  243. ->where('is_enabled', 1)
  244. ->where('is_deleted', 0)
  245. ->select('id', 'nickname', 'account')
  246. ->orderBy('id')
  247. ->get()
  248. ->map(function ($u) {
  249. $name = (string)$u->nickname;
  250. if ($name === '') {
  251. $name = (string)$u->account;
  252. }
  253. return [
  254. 'name' => $name,
  255. 'value' => (int)$u->id,
  256. ];
  257. })->all();
  258. $statsQuery = DB::table('mp_points_daily_stats as s');
  259. if ($scope['cpid'] > 0) {
  260. $statsQuery->where('s.cpid', $scope['cpid']);
  261. }
  262. if ($scope['uid'] > 0) {
  263. $statsQuery->where('s.uid', $scope['uid']);
  264. }
  265. $models = (clone $statsQuery)->distinct()->orderBy('s.model')->pluck('s.model')->values()->map(function ($model) {
  266. return ['name' => (string)$model, 'value' => (string)$model];
  267. })->all();
  268. $relays = (clone $statsQuery)->distinct()->orderBy('s.relay')->pluck('s.relay')->values()->map(function ($relay) {
  269. return ['name' => (string)$relay, 'value' => (string)$relay];
  270. })->all();
  271. $modelTypes = (clone $statsQuery)->distinct()->pluck('s.model_type')->values()->map(function ($type) {
  272. $labels = ['chat' => '文本', 'image' => '图片', 'video' => '视频'];
  273. return [
  274. 'name' => $labels[$type] ?? (string)$type,
  275. 'value' => (string)$type,
  276. ];
  277. })->all();
  278. // $dateRange = (clone $statsQuery)->selectRaw('MIN(stat_date) AS min_date, MAX(stat_date) AS max_date')->first();
  279. return [
  280. 'users' => $users,
  281. 'models' => $models,
  282. 'relays' => $relays,
  283. 'model_types' => $modelTypes,
  284. // 'date_range' => [
  285. // 'min' => $dateRange->min_date ?? null,
  286. // 'max' => $dateRange->max_date ?? null,
  287. // ],
  288. ];
  289. }
  290. /**
  291. * 导出 CSV:列随 group_by 动态变化,末尾追加合计行。
  292. */
  293. public function exportStats(array $params): void
  294. {
  295. $groupBy = self::parseGroupBy(getProp($params, 'group_by', ''));
  296. [$query] = $this->buildStatsQuery($params, $groupBy);
  297. // 按日期分组时日期倒序导出,与列表顺序一致
  298. if (in_array('date', $groupBy, true)) {
  299. $query->orderByDesc('s.stat_date');
  300. }
  301. $rows = $query->get();
  302. $dimLabels = [
  303. 'date' => '统计日期',
  304. 'uid' => '用户ID',
  305. 'model' => '模型',
  306. 'relay' => '中转站',
  307. ];
  308. $headers = [];
  309. foreach ($groupBy as $dim) {
  310. $headers[] = $dimLabels[$dim];
  311. }
  312. if (in_array('model', $groupBy, true)) {
  313. $headers[] = '模型类型';
  314. }
  315. $headers[] = '调用次数';
  316. $headers[] = 'token消耗';
  317. $headers[] = '积分消耗';
  318. $csvRows = [];
  319. foreach ($rows as $row) {
  320. $line = [];
  321. foreach ($groupBy as $dim) {
  322. $line[] = $dim === 'uid' ? (string)(int)$row->{'dim_' . $dim} : (string)$row->{'dim_' . $dim};
  323. }
  324. if (in_array('model', $groupBy, true)) {
  325. $line[] = (string)($row->dim_model_type ?? '');
  326. }
  327. $line[] = (string)(int)$row->call_count;
  328. $line[] = (string)(int)$row->tokens_consumed;
  329. $line[] = number_format((float)$row->points_consumed, 1, '.', '');
  330. $csvRows[] = $line;
  331. }
  332. $summary = $this->getSummary($params);
  333. $totalRow = [];
  334. foreach ($groupBy as $index => $dim) {
  335. $totalRow[] = $index === 0 ? '合计' : '';
  336. }
  337. if (in_array('model', $groupBy, true)) {
  338. $totalRow[] = '';
  339. }
  340. $csvRows[] = array_merge($totalRow, [
  341. (string)$summary['call_count'],
  342. (string)$summary['tokens_consumed'],
  343. number_format($summary['points_consumed'], 1, '.', ''),
  344. ]);
  345. $startDate = (string)getProp($params, 'start_date', date('Y-m-d', strtotime('-29 days')));
  346. $endDate = (string)getProp($params, 'end_date', date('Y-m-d'));
  347. $filename = 'points_stats_' . str_replace('-', '', $startDate) . '_' . str_replace('-', '', $endDate);
  348. exportCsv($filename, $headers, $csvRows);
  349. }
  350. }