feat: 客户端在线统计(按项目日/周/月在线用户数)

This commit is contained in:
root committed 2026-10-16 15:56:18 +08:00
1 parent c98f761275
commit 70fda65889
9 files changed
+509

No files matched your search

@@ -81,6 +81,22 @@ class InstallationController extends Controller
$this->success($stats);
}
/**
* 在线统计:当前在线 + 日/周/月在线用户数 + 趋势 + 分项目
* GET /api/installations/online-stats?period=day|week|month&project_id=
*/
public function onlineStats(): void
{
$user = $this->getCurrentUser() ?: [];
$projectId = !empty($_GET['project_id']) ? (int) $_GET['project_id'] : null;
$period = $_GET['period'] ?? 'day';
if (!in_array($period, ['day', 'week', 'month'], true)) {
$period = 'day';
}
$this->success(InstallationService::onlineStats($user, $projectId, $period));
}
/**
* 安装详情
* GET /api/installations/{id}
@@ -55,6 +55,7 @@ class InstallationService
$existing['id'],
]
);
self::recordOnline($projectId, $machineId);
return ['install_id' => (int) $existing['id'], 'is_new' => false];
}
@@ -74,9 +75,25 @@ class InstallationService
]
);
self::recordOnline($projectId, $machineId);
return ['install_id' => $installId, 'is_new' => true];
}
/**
* 记录当日在线(按天去重,供日/周/月在线统计)
*/
private static function recordOnline(int $projectId, string $machineId): void
{
$db = Database::getInstance();
$db->execute(
"INSERT INTO {$db->table('online_logs')}
(project_id, machine_id, online_date, first_seen_at, last_seen_at)
VALUES (?, ?, CURDATE(), NOW(), NOW())
ON DUPLICATE KEY UPDATE last_seen_at = NOW()",
[$projectId, $machineId]
);
}
/**
* 仅更新在线时间(心跳)
*/
@@ -235,4 +252,207 @@ class InstallationService
}, $projects),
];
}
/**
* 在线统计:当前在线(5分钟内心跳)+ 按天去重的日/周/月在线用户数 + 趋势 + 分项目
* 统计口径:「在线用户」= 有心跳的机器指纹(machine_id)
*
* @param string $period day|week|month 趋势粒度
*/
public static function onlineStats(array $user, ?int $projectId = null, string $period = 'day'): array
{
$db = Database::getInstance();
$scope = self::scopeLogs($user);
$where = $scope['where'];
$params = $scope['params'];
$projWhere = '';
$projParams = [];
if ($projectId) {
$projWhere = ' AND i.project_id = ?';
$projParams[] = $projectId;
}
// 当前在线:最后心跳在 5 分钟内
$current = (int) $db->fetchColumn(
"SELECT COUNT(*) FROM {$db->table('installations')} i
WHERE i.status = 'active'
AND i.last_online_at >= DATE_SUB(NOW(), INTERVAL 5 MINUTE)
{$where}{$projWhere}",
array_merge($params, $projParams)
);
$logWhere = " AND i.online_date >= DATE_FORMAT(DATE_SUB(CURDATE(), INTERVAL 32 DAY), '%Y-%m-%d')" . $projWhere;
$logParams = $params;
// 今日 / 本周(周一起)/ 本月 去重在线机器数
$counts = $db->fetch(
"SELECT
COUNT(DISTINCT CASE WHEN i.online_date = CURDATE() THEN i.machine_id END) AS today_online,
COUNT(DISTINCT CASE WHEN YEARWEEK(i.online_date, 1) = YEARWEEK(CURDATE(), 1) THEN i.machine_id END) AS week_online,
COUNT(DISTINCT CASE WHEN i.online_date >= DATE_FORMAT(CURDATE(), '%Y-%m-01') THEN i.machine_id END) AS month_online
FROM {$db->table('online_logs')} i
WHERE 1=1 {$logWhere}",
array_merge($logParams, $projParams)
);
// 分项目:当前在线(来自 installations)+ 日/周/月(来自 online_logs)
$curRows = $db->fetchAll(
"SELECT i.project_id, COUNT(*) AS current_online
FROM {$db->table('installations')} i
WHERE i.status = 'active'
AND i.last_online_at >= DATE_SUB(NOW(), INTERVAL 5 MINUTE)
{$where}{$projWhere}
GROUP BY i.project_id",
array_merge($params, $projParams)
);
$logRows = $db->fetchAll(
"SELECT i.project_id, p.name AS project_name,
COUNT(DISTINCT CASE WHEN i.online_date = CURDATE() THEN i.machine_id END) AS today_online,
COUNT(DISTINCT CASE WHEN YEARWEEK(i.online_date, 1) = YEARWEEK(CURDATE(), 1) THEN i.machine_id END) AS week_online,
COUNT(DISTINCT CASE WHEN i.online_date >= DATE_FORMAT(CURDATE(), '%Y-%m-01') THEN i.machine_id END) AS month_online
FROM {$db->table('online_logs')} i
LEFT JOIN {$db->table('projects')} p ON p.id = i.project_id
WHERE 1=1 {$logWhere}
GROUP BY i.project_id, p.name",
array_merge($logParams, $projParams)
);
$projects = [];
foreach ($logRows as $row) {
$pid = (int) $row['project_id'];
$projects[$pid] = [
'project_id' => $pid,
'project_name' => $row['project_name'],
'current_online' => 0,
'today_online' => (int) $row['today_online'],
'week_online' => (int) $row['week_online'],
'month_online' => (int) $row['month_online'],
];
}
foreach ($curRows as $row) {
$pid = (int) $row['project_id'];
if (!isset($projects[$pid])) {
$name = $db->fetchColumn("SELECT name FROM {$db->table('projects')} WHERE id = ?", [$pid]);
$projects[$pid] = [
'project_id' => $pid,
'project_name' => $name ?: ('项目#' . $pid),
'current_online' => 0,
'today_online' => 0,
'week_online' => 0,
'month_online' => 0,
];
}
$projects[$pid]['current_online'] = (int) $row['current_online'];
}
$projects = array_values($projects);
usort($projects, static fn (array $a, array $b) => $b['month_online'] <=> $a['month_online']);
// 趋势
$trend = [];
if ($period === 'week') {
$rows = $db->fetchAll(
"SELECT YEARWEEK(i.online_date, 1) AS yw, COUNT(DISTINCT i.machine_id) AS cnt
FROM {$db->table('online_logs')} i
WHERE i.online_date >= DATE_SUB(CURDATE(), INTERVAL 84 DAY) {$projWhere}
GROUP BY yw",
$projParams
);
$map = [];
foreach ($rows as $r) {
$map[(string) $r['yw']] = (int) $r['cnt'];
}
for ($i = 11; $i >= 0; $i--) {
$d = new \DateTime('today');
$d->modify("-" . ($i * 7) . " days");
$yw = (int) $d->format('oW');
$label = $d->format('o') . '-W' . $d->format('W');
$trend[] = ['label' => $label, 'value' => $map[(string) $yw] ?? 0];
}
} elseif ($period === 'month') {
$rows = $db->fetchAll(
"SELECT DATE_FORMAT(i.online_date, '%Y-%m') AS ym, COUNT(DISTINCT i.machine_id) AS cnt
FROM {$db->table('online_logs')} i
WHERE i.online_date >= DATE_FORMAT(DATE_SUB(CURDATE(), INTERVAL 11 MONTH), '%Y-%m-01') {$projWhere}
GROUP BY ym",
$projParams
);
$map = [];
foreach ($rows as $r) {
$map[$r['ym']] = (int) $r['cnt'];
}
for ($i = 11; $i >= 0; $i--) {
$d = new \DateTime('today');
$d->modify('first day of this month');
$d->modify("-" . $i . " months");
$ym = $d->format('Y-m');
$trend[] = ['label' => $ym, 'value' => $map[$ym] ?? 0];
}
} else {
$rows = $db->fetchAll(
"SELECT DATE(i.online_date) AS d, COUNT(DISTINCT i.machine_id) AS cnt
FROM {$db->table('online_logs')} i
WHERE i.online_date >= DATE_SUB(CURDATE(), INTERVAL 29 DAY) {$projWhere}
GROUP BY d",
$projParams
);
$map = [];
foreach ($rows as $r) {
$map[$r['d']] = (int) $r['cnt'];
}
for ($i = 29; $i >= 0; $i--) {
$d = new \DateTime('today');
$d->modify("-{$i} days");
$key = $d->format('Y-m-d');
$trend[] = ['label' => $d->format('m-d'), 'value' => $map[$key] ?? 0];
}
}
return [
'period' => $period,
'current_online' => $current,
'today_online' => (int) ($counts['today_online'] ?? 0),
'week_online' => (int) ($counts['week_online'] ?? 0),
'month_online' => (int) ($counts['month_online'] ?? 0),
'trend' => $trend,
'projects' => $projects,
];
}
/**
* 在线日志数据范围(online_logs 仅有 project_id 维度;agent 按其有卡密的项目)
* 别名固定为 i,返回 {where, params}
*/
private static function scopeLogs(array $user): array
{
$db = Database::getInstance();
$role = $user['role'] ?? '';
if ($role === 'admin') {
return ['where' => '', 'params' => []];
}
if ($role === 'project_admin') {
$projectIds = $user['project_ids'] ?? [];
if (empty($projectIds)) {
return ['where' => ' AND 1=0', 'params' => []];
}
$placeholders = implode(',', array_fill(0, count($projectIds), '?'));
return [
'where' => " AND i.project_id IN ({$placeholders})",
'params' => array_map('intval', $projectIds),
];
}
// 代理:本人及下级代理有卡密的项目
$agentIds = PermissionService::getAgentIdsUnder((int) ($user['id'] ?? 0));
if (empty($agentIds)) {
return ['where' => ' AND 1=0', 'params' => []];
}
$placeholders = implode(',', array_fill(0, count($agentIds), '?'));
return [
'where' => " AND i.project_id IN (SELECT DISTINCT c.project_id FROM {$db->table('cards')} c WHERE c.use_user_id IN ({$placeholders}))",
'params' => array_map('intval', $agentIds),
];
}
}
@@ -0,0 +1,13 @@
-- 客户端在线日志(按天去重记录每台机器在线,用于日/周/月在线统计)
CREATE TABLE IF NOT EXISTS `ca_online_logs` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`project_id` BIGINT UNSIGNED NOT NULL COMMENT '所属项目ID',
`machine_id` VARCHAR(128) NOT NULL COMMENT '机器指纹',
`online_date` DATE NOT NULL COMMENT '在线日期',
`first_seen_at` DATETIME NOT NULL COMMENT '当日首次上线时间',
`last_seen_at` DATETIME NOT NULL COMMENT '当日最后上线时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uq_proj_date_machine` (`project_id`, `online_date`, `machine_id`),
KEY `idx_online_date` (`online_date`),
KEY `idx_proj_date` (`project_id`, `online_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='客户端在线日志(按天去重)';
+17
View File
@@ -361,6 +361,23 @@ CREATE TABLE `ca_installations` (
KEY `idx_deleted_at` (`deleted_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='安装记录表';
-- ============================================
-- 12b. 客户端在线日志表(按天去重,供日/周/月在线统计)
-- ============================================
DROP TABLE IF EXISTS `ca_online_logs`;
CREATE TABLE `ca_online_logs` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`project_id` BIGINT UNSIGNED NOT NULL COMMENT '所属项目ID',
`machine_id` VARCHAR(128) NOT NULL COMMENT '机器指纹',
`online_date` DATE NOT NULL COMMENT '在线日期',
`first_seen_at` DATETIME NOT NULL COMMENT '当日首次上线时间',
`last_seen_at` DATETIME NOT NULL COMMENT '当日最后上线时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uq_proj_date_machine` (`project_id`, `online_date`, `machine_id`),
KEY `idx_online_date` (`online_date`),
KEY `idx_proj_date` (`project_id`, `online_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='客户端在线日志(按天去重)';
-- ============================================
-- 13. 项目版本/安装包表
-- ============================================
+1
View File
@@ -196,6 +196,7 @@ $router->group('api', function ($router) {
// 安装统计管理 (admin / project_admin / agent)
$router->get('installations', [InstallationController::class, 'list']);
$router->get('installations/stats', [InstallationController::class, 'stats']);
$router->get('installations/online-stats', [InstallationController::class, 'onlineStats']);
$router->get('installations/export', [InstallationController::class, 'export']);
$router->get('installations/{id}', [InstallationController::class, 'detail']);
$router->delete('installations/{id}', [InstallationController::class, 'delete']);
+3
View File
@@ -10,6 +10,9 @@ const installationApi = {
stats(params) {
return request.get('/installations/stats', { params })
},
onlineStats(params) {
return request.get('/installations/online-stats', { params })
},
detail(id) {
return request.get(`/installations/${id}`)
},
+6
View File
@@ -83,6 +83,12 @@ const routes = [
component: () => import('@/views/Installations.vue'),
meta: { title: '安装统计', icon: 'Download' }
},
{
path: 'online-stats',
name: 'OnlineStats',
component: () => import('@/views/OnlineStats.vue'),
meta: { title: '在线统计', icon: 'Odometer' }
},
{
path: 'project-versions',
name: 'ProjectVersions',
+228
View File
@@ -0,0 +1,228 @@
<template>
<div class="online-stats-page">
<!-- 统计卡片 -->
<el-row :gutter="20" class="stats-row">
<el-col :xs="12" :sm="6" :md="6" :lg="6">
<div class="stat-card stat-current">
<div class="stat-icon"><el-icon :size="32"><Odometer /></el-icon></div>
<div class="stat-info">
<div class="stat-value">{{ stats.current_online }}</div>
<div class="stat-label">当前在线(5分钟内)</div>
</div>
</div>
</el-col>
<el-col :xs="12" :sm="6" :md="6" :lg="6">
<div class="stat-card stat-today">
<div class="stat-icon"><el-icon :size="32"><Sunny /></el-icon></div>
<div class="stat-info">
<div class="stat-value">{{ stats.today_online }}</div>
<div class="stat-label">今日在线</div>
</div>
</div>
</el-col>
<el-col :xs="12" :sm="6" :md="6" :lg="6">
<div class="stat-card stat-week">
<div class="stat-icon"><el-icon :size="32"><Calendar /></el-icon></div>
<div class="stat-info">
<div class="stat-value">{{ stats.week_online }}</div>
<div class="stat-label">本周在线(周一起)</div>
</div>
</div>
</el-col>
<el-col :xs="12" :sm="6" :md="6" :lg="6">
<div class="stat-card stat-month">
<div class="stat-icon"><el-icon :size="32"><TrendCharts /></el-icon></div>
<div class="stat-info">
<div class="stat-value">{{ stats.month_online }}</div>
<div class="stat-label">本月在线</div>
</div>
</div>
</el-col>
</el-row>
<!-- 趋势图 -->
<el-card shadow="never" class="main-card">
<div class="chart-toolbar">
<div class="section-title">在线用户数趋势</div>
<div class="chart-controls">
<el-select v-model="projectId" placeholder="全部项目" clearable style="width: 160px" @change="fetchData">
<el-option v-for="p in projects" :key="p.id" :label="p.name" :value="p.id" />
</el-select>
<el-radio-group v-model="period" @change="fetchData">
<el-radio-button value="day">按日(30天)</el-radio-button>
<el-radio-button value="week">按周(12周)</el-radio-button>
<el-radio-button value="month">按月(12月)</el-radio-button>
</el-radio-group>
<el-button :icon="Refresh" circle @click="fetchData" />
</div>
</div>
<div v-loading="loading" ref="chartRef" class="chart-box"></div>
</el-card>
<!-- 分项目统计 -->
<el-card shadow="never" class="main-card">
<div class="section-title">按项目在线统计(在线用户 = 客户端机器指纹去重)</div>
<el-table :data="stats.projects" stripe border class="data-table" v-loading="loading">
<el-table-column prop="project_name" label="项目" min-width="160" show-overflow-tooltip>
<template #default="{ row }">{{ row.project_name || row.project_id }}</template>
</el-table-column>
<el-table-column prop="current_online" label="当前在线" width="110" align="center">
<template #default="{ row }">
<el-tag type="success" size="small">{{ row.current_online }}</el-tag>
</template>
</el-table-column>
<el-table-column prop="today_online" label="今日在线" width="110" align="center" />
<el-table-column prop="week_online" label="本周在线" width="110" align="center" />
<el-table-column prop="month_online" label="本月在线" width="110" align="center" />
</el-table>
<div v-if="!stats.projects?.length && !loading" class="empty-tip">暂无在线记录(自上线后随客户端心跳累积)</div>
</el-card>
</div>
</template>
<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { Refresh, Odometer, Sunny, Calendar, TrendCharts } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import request from '@/api'
import installationApi from '@/api/installations'
const loading = ref(false)
const period = ref('day')
const projectId = ref('')
const projects = ref([])
const chartRef = ref(null)
let chartInstance = null
const stats = ref({
current_online: 0,
today_online: 0,
week_online: 0,
month_online: 0,
trend: [],
projects: []
})
function renderChart() {
const el = chartRef.value
if (!el) return
if (!chartInstance || chartInstance.isDisposed()) {
chartInstance = echarts.init(el)
}
const trend = stats.value.trend || []
chartInstance.setOption({
tooltip: {
trigger: 'axis',
backgroundColor: 'rgba(255,255,255,0.96)',
borderColor: '#e2e8f0', borderWidth: 1,
textStyle: { color: '#333', fontSize: 12 }
},
grid: { left: '3%', right: '4%', top: 16, bottom: 30, containLabel: true },
xAxis: {
type: 'category',
data: trend.map(t => t.label),
axisLine: { lineStyle: { color: '#e2e8f0' } },
axisTick: { show: false },
axisLabel: { fontSize: 10, color: '#94a3b8', interval: 'auto' }
},
yAxis: {
type: 'value', minInterval: 1,
axisLabel: { fontSize: 10, color: '#94a3b8' },
splitLine: { lineStyle: { color: '#f1f5f9', type: 'dashed' } },
axisLine: { show: false }, axisTick: { show: false }
},
series: [{
name: '在线用户数',
type: 'bar',
data: trend.map(t => t.value),
barMaxWidth: 22,
itemStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{ offset: 0, color: '#34d399' },
{ offset: 1, color: '#a7f3d0' }
]),
borderRadius: [6, 6, 0, 0]
}
}]
}, true)
}
async function fetchData() {
loading.value = true
try {
const params = { period: period.value }
if (projectId.value) params.project_id = projectId.value
const res = await installationApi.onlineStats(params)
stats.value = { ...stats.value, ...(res.data || {}) }
await nextTick()
renderChart()
} catch (e) {
console.error(e)
} finally {
loading.value = false
}
}
async function fetchProjects() {
try {
const res = await request.get('/projects/all')
projects.value = res.data.list || res.data || []
if (!Array.isArray(projects.value)) projects.value = []
} catch {
projects.value = []
}
}
function handleResize() {
chartInstance?.resize()
}
onMounted(() => {
fetchProjects()
fetchData()
window.addEventListener('resize', handleResize)
})
onUnmounted(() => {
window.removeEventListener('resize', handleResize)
chartInstance?.dispose()
})
</script>
<style scoped>
.online-stats-page { max-width: 1600px; margin: 0 auto; }
.stats-row { margin-bottom: 20px; }
.stat-card {
display: flex; align-items: center; gap: 12px;
padding: 14px 18px; border-radius: 12px; background: #fff;
border: 1px solid #f0f0f4; transition: all .25s;
}
.stat-card:hover { transform: translateY(-2px); box-shadow: 0 4px 16px rgba(0,0,0,.05); }
.stat-icon {
width: 40px; height: 40px; border-radius: 10px;
display: flex; align-items: center; justify-content: center; flex-shrink: 0;
}
.stat-icon :deep(.el-icon) { font-size: 20px !important; }
.stat-current .stat-icon { background: #ecfdf5; color: #10b981; }
.stat-today .stat-icon { background: #fffbeb; color: #f59e0b; }
.stat-week .stat-icon { background: #eff6ff; color: #3b82f6; }
.stat-month .stat-icon { background: #f5f3ff; color: #8b5cf6; }
.stat-info { display: flex; flex-direction: column; min-width: 0; }
.stat-value { font-size: 22px; font-weight: 700; color: #1d1d1f; line-height: 1.1; letter-spacing: -.3px; }
.stat-label { font-size: 12px; color: #9ca3af; margin-top: 2px; font-weight: 500; }
.main-card { margin-bottom: 20px; border-radius: 16px; border: 1px solid #f0f0f4; }
.main-card:deep(.el-card__body) { padding: 24px; }
.chart-toolbar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 14px; flex-wrap: wrap; gap: 12px; }
.chart-controls { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
.section-title { font-weight: 600; color: #374151; }
.chart-box { height: 320px; }
.data-table { border-radius: 12px; overflow: hidden; }
.data-table:deep(.el-table__header th) { background: #f8f9fb; font-weight: 600; color: #374151; font-size: 13px; border-color: #f0f0f4; }
.data-table:deep(.el-table__body td) { font-size: 13px; color: #374151; border-color: #f5f5f7; }
.empty-tip { text-align: center; color: #9ca3af; font-size: 13px; padding: 24px 0 8px; }
@media (max-width: 768px) {
.chart-toolbar { flex-direction: column; align-items: stretch; }
.main-card:deep(.el-card__body) { padding: 14px; }
.chart-box { height: 240px; }
}
</style>
+5
View File
@@ -67,6 +67,10 @@
<el-icon><Download /></el-icon>
<span>安装统计</span>
</el-menu-item>
<el-menu-item index="/online-stats">
<el-icon><Odometer /></el-icon>
<span>在线统计</span>
</el-menu-item>
<el-menu-item index="/project-versions" v-if="canManage || isAgent">
<el-icon><Upload /></el-icon>
<span>版本推送</span>
@@ -490,6 +494,7 @@ const parentMap = {
'/cards': [{ path: '/dashboard', title: '业务管理' }],
'/authorizations': [{ path: '/dashboard', title: '业务管理' }],
'/installations': [{ path: '/dashboard', title: '业务管理' }],
'/online-stats': [{ path: '/dashboard', title: '业务管理' }],
'/project-versions': [{ path: '/dashboard', title: '业务管理' }],
'/announcements': [{ path: '/dashboard', title: '业务管理' }],
'/orders': [{ path: '/dashboard', title: '订单与代理' }],