Files
MBTI_wang/api/app/controller/admin/Analytics.php
Ghost a411bf7b21 高考版优化
审核模式优化
2026-04-29 18:01:26 +08:00

101 lines
3.3 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace app\controller\admin;
use app\BaseController;
use app\common\AnalyticsEventLabels;
use think\facade\Db;
use think\facade\Request;
/**
* 小程序埋点(企业/平台管理端,受企业用户范围约束)
*/
class Analytics extends BaseController
{
/**
* 单用户旅程:与 superadmin.Analytics/userJourney 数据结构一致,
* 额外校验目标 userId 属于当前管理员可见企业user_profile
*
* GET /api/v1/admin/analytics/user-journey?userId=&days=30
*/
public function userJourney()
{
$auth = $this->request->user ?? null;
if (!$auth) {
return error('未登录', 401);
}
if (!in_array($auth['role'] ?? '', ['admin', 'enterprise_admin'])) {
return error('无权限访问', 403);
}
$userId = (int) Request::param('userId', 0);
if ($userId <= 0) {
return error('userId 不能为空', 400);
}
$enterpriseId = $auth['enterpriseId'] ?? null;
if (!$enterpriseId) {
$adminRow = Db::name('users')->where('id', $auth['userId'] ?? 0)->find();
$enterpriseId = $adminRow['enterpriseId'] ?? null;
}
if ($enterpriseId) {
$has = Db::name('user_profile')
->where('userId', $userId)
->where('enterpriseId', (int) $enterpriseId)
->find();
if (!$has) {
return error('无权限查看该用户', 403);
}
}
$days = min(180, max(1, (int) Request::param('days', 30)));
$since = date('Y-m-d H:i:s', time() - $days * 86400);
$page = max(1, (int) Request::param('page', 1));
$pageSize = min(100, max(1, (int) Request::param('pageSize', 20)));
$offset = ($page - 1) * $pageSize;
try {
$baseQ = Db::name('analytics_events')
->where('userId', $userId)
->where('createdAt', '>=', $since);
$total = (int) (clone $baseQ)->count();
$rows = (clone $baseQ)
->order('id', 'desc')
->limit($offset, $pageSize)
->select()
->toArray();
foreach ($rows as &$r) {
if (!empty($r['propsJson'])) {
$decoded = json_decode($r['propsJson'], true);
$r['props'] = is_array($decoded) ? $decoded : null;
} else {
$r['props'] = null;
}
unset($r['propsJson']);
}
unset($r);
$rows = AnalyticsEventLabels::withCn($rows);
return success([
'userId' => $userId,
'days' => $days,
'list' => $rows,
'total' => $total,
'page' => $page,
'pageSize' => $pageSize,
]);
} catch (\Throwable $e) {
return success([
'userId' => $userId,
'days' => $days,
'list' => [],
'total' => 0,
'page' => $page,
'pageSize' => $pageSize,
'tableMissing' => true,
]);
}
}
}