PointsStatsService.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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 本组织;其他抛错。
  75. *
  76. * @return int 限定的 cpid(0 表示不限定)
  77. */
  78. private function assertCanView(): int
  79. {
  80. $role = (string)Site::getRole();
  81. if ($role === 'superadmin') {
  82. return 0;
  83. }
  84. if ($role === 'admin') {
  85. return (int)Site::getCpid();
  86. }
  87. Utils::throwError('1005:无权查看统计数据');
  88. }
  89. /**
  90. * 构建统计查询(含权限过滤与 group_by 聚合)。
  91. *
  92. * @param array $params 筛选参数
  93. * @param array $groupBy 聚合维度列表
  94. * @return array [查询构建器, 维度=>列映射]
  95. */
  96. private function buildStatsQuery(array $params, array $groupBy)
  97. {
  98. $cpid = $this->assertCanView();
  99. $query = DB::table('mp_points_daily_stats as s')
  100. ->leftJoin('mp_manage_users as u', 'u.id', '=', 's.uid');
  101. if ($cpid > 0) {
  102. $query->where('s.cpid', $cpid);
  103. }
  104. $startDate = (string)getProp($params, 'start_date', date('Y-m-d', strtotime('-29 days')));
  105. $endDate = (string)getProp($params, 'end_date', date('Y-m-d'));
  106. if ($startDate) {
  107. $query->where('s.stat_date', '>=', $startDate);
  108. }
  109. if ($endDate) {
  110. $query->where('s.stat_date', '<=', $endDate);
  111. }
  112. $uid = (string)getProp($params, 'uid', '');
  113. if ($uid !== '') {
  114. $uids = array_values(array_filter(array_map('intval', explode(',', $uid))));
  115. if ($uids) {
  116. $query->whereIn('s.uid', $uids);
  117. }
  118. }
  119. $nickname = trim((string)getProp($params, 'nickname', ''));
  120. if ($nickname !== '') {
  121. $query->where(function ($q) use ($nickname) {
  122. $q->where('u.nickname', 'like', '%' . $nickname . '%')
  123. ->orWhere('u.account', 'like', '%' . $nickname . '%');
  124. });
  125. }
  126. $model = (string)getProp($params, 'model', '');
  127. if ($model !== '') {
  128. $query->where('s.model', $model);
  129. }
  130. $relay = (string)getProp($params, 'relay', '');
  131. if ($relay !== '') {
  132. $query->where('s.relay', $relay);
  133. }
  134. $modelType = (string)getProp($params, 'model_type', '');
  135. if (in_array($modelType, ['chat', 'image', 'video'], true)) {
  136. $query->where('s.model_type', $modelType);
  137. }
  138. $dimToCol = [
  139. 'date' => 's.stat_date',
  140. 'uid' => 's.uid',
  141. 'model' => 's.model',
  142. 'relay' => 's.relay',
  143. ];
  144. $cols = [];
  145. $groupRaw = [];
  146. foreach ($groupBy as $dim) {
  147. $cols[] = $dimToCol[$dim] . ' AS dim_' . $dim;
  148. $groupRaw[] = $dimToCol[$dim];
  149. }
  150. // 按 model 分组时 model_type 有确定值(模型→类型一对一),随分组输出
  151. if (in_array('model', $groupBy, true)) {
  152. $cols[] = 's.model_type AS dim_model_type';
  153. $groupRaw[] = 's.model_type';
  154. }
  155. $cols[] = 'SUM(s.call_count) AS call_count';
  156. $cols[] = 'SUM(s.tokens_consumed) AS tokens_consumed';
  157. $cols[] = 'SUM(s.points_consumed) AS points_consumed';
  158. $query->selectRaw(implode(', ', $cols));
  159. if ($groupRaw) {
  160. $query->groupByRaw(implode(', ', $groupRaw));
  161. }
  162. return [$query, $dimToCol];
  163. }
  164. /**
  165. * 查询统计列表(分页)。
  166. */
  167. public function getStats(array $params): array
  168. {
  169. $groupBy = self::parseGroupBy(getProp($params, 'group_by', ''));
  170. [$query] = $this->buildStatsQuery($params, $groupBy);
  171. $pageSize = (int)getProp($params, 'page_size', 15);
  172. if ($pageSize < 1 || $pageSize > 100) {
  173. $pageSize = 15;
  174. }
  175. $rows = $query->paginate($pageSize)->through(function ($row) use ($groupBy) {
  176. $item = [];
  177. foreach ($groupBy as $dim) {
  178. $item[$dim] = $dim === 'uid' ? (int)$row->{'dim_' . $dim} : (string)$row->{'dim_' . $dim};
  179. }
  180. $item['call_count'] = (int)$row->call_count;
  181. $item['tokens_consumed'] = (int)$row->tokens_consumed;
  182. $item['points_consumed'] = (float)$row->points_consumed;
  183. $item['model_type'] = (string)($row->dim_model_type ?? '');
  184. return $item;
  185. });
  186. $list = $rows->items();
  187. if (in_array('uid', $groupBy, true) && $list) {
  188. $uids = array_unique(array_column($list, 'uid'));
  189. $userMap = DB::table('mp_manage_users')->whereIn('id', $uids)
  190. ->pluck('nickname', 'id')->map(function ($v) {
  191. return (string)$v;
  192. })->all();
  193. foreach ($list as &$item) {
  194. $item['nickname'] = $userMap[$item['uid']] ?? '';
  195. }
  196. unset($item);
  197. }
  198. return [
  199. 'summary' => $this->getSummary($params),
  200. 'meta' => getMeta($rows),
  201. 'list' => $list,
  202. ];
  203. }
  204. /**
  205. * 当前筛选条件下的合计(不按维度分组)。
  206. */
  207. public function getSummary(array $params): array
  208. {
  209. [$query] = $this->buildStatsQuery($params, []);
  210. $row = $query->first();
  211. return [
  212. 'call_count' => (int)($row->call_count ?? 0),
  213. 'tokens_consumed' => (int)($row->tokens_consumed ?? 0),
  214. 'points_consumed' => (float)($row->points_consumed ?? 0),
  215. ];
  216. }
  217. /**
  218. * 筛选项来源:用户/模型/中转站/模型类型/日期范围。
  219. *
  220. * 选项统一为 {name: 显示名称, value: 传给后端的筛选值},前端展示 name、提交 value。
  221. */
  222. public function getFilters(array $params = []): array
  223. {
  224. $cpid = $this->assertCanView();
  225. $users = DB::table('mp_manage_users')
  226. ->when($cpid > 0, function ($q) use ($cpid) {
  227. $q->where('cpid', $cpid);
  228. })
  229. ->where('is_enabled', 1)
  230. ->select('id', 'nickname', 'account')
  231. ->orderBy('id')
  232. ->get()
  233. ->map(function ($u) {
  234. $name = (string)$u->nickname;
  235. if ($name === '') {
  236. $name = (string)$u->account;
  237. }
  238. return [
  239. 'name' => $name,
  240. 'value' => (int)$u->id,
  241. ];
  242. })->all();
  243. $statsQuery = DB::table('mp_points_daily_stats as s');
  244. if ($cpid > 0) {
  245. $statsQuery->where('s.cpid', $cpid);
  246. }
  247. $models = (clone $statsQuery)->distinct()->orderBy('s.model')->pluck('s.model')->values()->map(function ($model) {
  248. return ['name' => (string)$model, 'value' => (string)$model];
  249. })->all();
  250. $relays = (clone $statsQuery)->distinct()->orderBy('s.relay')->pluck('s.relay')->values()->map(function ($relay) {
  251. return ['name' => (string)$relay, 'value' => (string)$relay];
  252. })->all();
  253. $modelTypes = (clone $statsQuery)->distinct()->pluck('s.model_type')->values()->map(function ($type) {
  254. $labels = ['chat' => '文本', 'image' => '图片', 'video' => '视频'];
  255. return [
  256. 'name' => $labels[$type] ?? (string)$type,
  257. 'value' => (string)$type,
  258. ];
  259. })->all();
  260. // $dateRange = (clone $statsQuery)->selectRaw('MIN(stat_date) AS min_date, MAX(stat_date) AS max_date')->first();
  261. return [
  262. 'users' => $users,
  263. 'models' => $models,
  264. 'relays' => $relays,
  265. 'model_types' => $modelTypes,
  266. // 'date_range' => [
  267. // 'min' => $dateRange->min_date ?? null,
  268. // 'max' => $dateRange->max_date ?? null,
  269. // ],
  270. ];
  271. }
  272. /**
  273. * 导出 CSV:列随 group_by 动态变化,末尾追加合计行。
  274. */
  275. public function exportStats(array $params): void
  276. {
  277. $groupBy = self::parseGroupBy(getProp($params, 'group_by', ''));
  278. [$query] = $this->buildStatsQuery($params, $groupBy);
  279. $rows = $query->get();
  280. $dimLabels = [
  281. 'date' => '统计日期',
  282. 'uid' => '用户ID',
  283. 'model' => '模型',
  284. 'relay' => '中转站',
  285. ];
  286. $headers = [];
  287. foreach ($groupBy as $dim) {
  288. $headers[] = $dimLabels[$dim];
  289. }
  290. if (in_array('model', $groupBy, true)) {
  291. $headers[] = '模型类型';
  292. }
  293. $headers[] = '调用次数';
  294. $headers[] = 'token消耗';
  295. $headers[] = '积分消耗';
  296. $csvRows = [];
  297. foreach ($rows as $row) {
  298. $line = [];
  299. foreach ($groupBy as $dim) {
  300. $line[] = $dim === 'uid' ? (string)(int)$row->{'dim_' . $dim} : (string)$row->{'dim_' . $dim};
  301. }
  302. if (in_array('model', $groupBy, true)) {
  303. $line[] = (string)($row->dim_model_type ?? '');
  304. }
  305. $line[] = (string)(int)$row->call_count;
  306. $line[] = (string)(int)$row->tokens_consumed;
  307. $line[] = number_format((float)$row->points_consumed, 1, '.', '');
  308. $csvRows[] = $line;
  309. }
  310. $summary = $this->getSummary($params);
  311. $totalRow = [];
  312. foreach ($groupBy as $index => $dim) {
  313. $totalRow[] = $index === 0 ? '合计' : '';
  314. }
  315. if (in_array('model', $groupBy, true)) {
  316. $totalRow[] = '';
  317. }
  318. $csvRows[] = array_merge($totalRow, [
  319. (string)$summary['call_count'],
  320. (string)$summary['tokens_consumed'],
  321. number_format($summary['points_consumed'], 1, '.', ''),
  322. ]);
  323. $startDate = (string)getProp($params, 'start_date', date('Y-m-d', strtotime('-29 days')));
  324. $endDate = (string)getProp($params, 'end_date', date('Y-m-d'));
  325. $filename = 'points_stats_' . str_replace('-', '', $startDate) . '_' . str_replace('-', '', $endDate);
  326. exportCsv($filename, $headers, $csvRows);
  327. }
  328. }