功能:完善通用云管工作台、审计与诊断能力
This commit is contained in:
1 parent
5ac692724d
commit
9f05aa20ea
225 files changed
+14266
-141
No files matched your search
@@ -0,0 +1,89 @@
|
||||
import { test, expect, type Page } from '@playwright/test'
|
||||
|
||||
async function fixture(page: Page, options: { fail?: boolean; deny?: boolean; slow?: boolean } = {}) {
|
||||
const revoked: string[] = [], queries: string[] = []
|
||||
const now = new Date().toISOString(), expires = new Date(Date.now() + 3600000).toISOString()
|
||||
await page.addInitScript(() => sessionStorage.setItem('vdi.accessToken', 'session-fixture'))
|
||||
await page.route('**/api/v1/**', async route => {
|
||||
const request = route.request(), url = new URL(request.url()), path = url.pathname.replace('/api/v1', '')
|
||||
const list = (items: unknown[], total = items.length) => route.fulfill({ json: { items, total, page: 1, pageSize: 20, requestId: 'sessions-ui' } })
|
||||
if (path === '/auth/me') { await route.fulfill({ json: { id: 'owner', username: 'root', displayName: '管理员', role: 'super_admin' } }); return }
|
||||
if (path === '/settings') { await route.fulfill({ json: { mode: 'production', capabilities: ['administrator-sessions'], pveConfigured: true } }); return }
|
||||
if (path === '/overview') { await route.fulfill({ json: { terminalCount: 0, onlineTerminals: 0, desktopCount: 0, runningDesktops: 0, activeSessions: 0, failedTasks: 0, mode: 'production' } }); return }
|
||||
if (path === '/administrators') { await list([{ id: 'owner', username: 'root', displayName: '管理员', role: 'super_admin', enabled: true }, { id: 'other', username: 'maintainer', displayName: '运维', role: 'operator', enabled: true }]); return }
|
||||
const match = path.match(/^\/administrators\/(owner|other)\/sessions(?:\/(.+))?$/)
|
||||
if (match) {
|
||||
const id = match[1]!, key = match[2]
|
||||
if (request.method() === 'DELETE') {
|
||||
revoked.push(`${id}/${key}`)
|
||||
if (options.deny) { await route.fulfill({ status: 403, json: { code: 'forbidden', message: '当前账号没有该操作权限' } }); return }
|
||||
await route.fulfill({ status: 204 }); return
|
||||
}
|
||||
queries.push(id)
|
||||
if (options.fail && id === 'other') { await route.fulfill({ status: 500, json: { code: 'database_error', message: '登录列表暂不可用' } }); return }
|
||||
if (options.slow && id === 'owner') await new Promise(resolve => setTimeout(resolve, 700))
|
||||
const p = Number(url.searchParams.get('page') || 1), size = 20, total = 21 - revoked.filter(r => r.startsWith(`${id}/`)).length
|
||||
await list(Array.from({ length: Math.max(0, Math.min(size, total - (p - 1) * size)) }, (_, i) => ({ key: `${id}-${(p - 1) * size + i}`, createdAt: i === 1 ? null : now, expiresAt: expires, clientIp: i === 1 ? '' : `192.0.2.${(p - 1) * size + i + 1}`, userAgent: 'Example browser <script>alert(1)</script>', current: id === 'owner' && p === 1 && i === 0 })), total); return
|
||||
}
|
||||
if (['/resources', '/desktops', '/users', '/terminals', '/tasks'].includes(path)) { await list([]); return }
|
||||
await route.fulfill({ status: 404, json: { message: '测试接口未定义' } })
|
||||
})
|
||||
await page.goto('/settings'); await page.getByRole('button', { name: '管理员账号', exact: true }).click()
|
||||
await expect(page.getByRole('heading', { name: '管理员账号', exact: true })).toBeVisible()
|
||||
return { revoked, queries }
|
||||
}
|
||||
async function open(page: Page, name: string) {
|
||||
await page.getByRole('row').filter({ hasText: name }).getByRole('button', { name: '在线登录', exact: true }).click()
|
||||
return page.getByRole('dialog', { name: `在线登录 · ${name}`, exact: true })
|
||||
}
|
||||
|
||||
test('登录来源、旧登录未知信息、分页、当前登录保护及深浅窄屏', async ({ page }, info) => {
|
||||
const calls = await fixture(page), dialog = await open(page, 'root')
|
||||
await expect(dialog.getByText('当前登录', { exact: true })).toBeVisible()
|
||||
await expect(dialog.getByRole('row').filter({ hasText: '当前登录' }).getByRole('button', { name: '撤销登录' })).toBeDisabled()
|
||||
await expect(dialog.getByText('升级前登录,时间未知', { exact: true })).toBeVisible()
|
||||
await expect(dialog.getByText('升级前登录,来源未知', { exact: true })).toBeVisible()
|
||||
await page.screenshot({ path: info.outputPath('admin-sessions-dark.png'), fullPage: true, animations: 'disabled' })
|
||||
await dialog.locator('.el-pagination .btn-next').click(); await expect(dialog.getByText('192.0.2.21', { exact: true })).toBeVisible()
|
||||
await dialog.getByRole('button', { name: '关闭', exact: true }).click()
|
||||
await page.getByRole('button', { name: '切换浅色主题' }).click(); await page.setViewportSize({ width: 390, height: 844 })
|
||||
await open(page, 'root'); await expect(dialog.getByText('当前登录', { exact: true })).toBeVisible()
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(391)
|
||||
await page.screenshot({ path: info.outputPath('admin-sessions-mobile.png'), fullPage: true, animations: 'disabled' })
|
||||
expect(calls.revoked).toEqual([])
|
||||
})
|
||||
|
||||
test('撤销指定登录需确认,取消不提交,成功刷新', async ({ page }) => {
|
||||
const calls = await fixture(page), dialog = await open(page, 'maintainer')
|
||||
await expect(dialog.getByText('共 21 次有效登录', { exact: true })).toBeVisible()
|
||||
await dialog.getByRole('button', { name: '撤销登录', exact: true }).first().click()
|
||||
await page.locator('.el-message-box').getByRole('button', { name: '取消', exact: true }).click()
|
||||
expect(calls.revoked).toEqual([])
|
||||
await dialog.getByRole('button', { name: '撤销登录', exact: true }).first().click()
|
||||
await page.locator('.el-message-box').getByRole('button', { name: '确认提交', exact: true }).click()
|
||||
await expect(dialog.getByText('共 20 次有效登录', { exact: true })).toBeVisible()
|
||||
expect(calls.revoked).toEqual(['other/other-0'])
|
||||
})
|
||||
|
||||
test('查询和撤销失败清除旧结果并显示错误,不误报成功', async ({ page }) => {
|
||||
const calls = await fixture(page, { deny: true }), dialog = await open(page, 'maintainer')
|
||||
await dialog.getByRole('button', { name: '撤销登录', exact: true }).first().click()
|
||||
await page.locator('.el-message-box').getByRole('button', { name: '确认提交', exact: true }).click()
|
||||
await expect(dialog.getByText('当前账号没有该操作权限', { exact: true })).toBeVisible()
|
||||
await expect(dialog.getByRole('button', { name: '撤销登录', exact: true })).toHaveCount(0)
|
||||
expect(calls.revoked).toHaveLength(1)
|
||||
await page.unrouteAll(); await fixture(page, { fail: true }); await open(page, 'maintainer')
|
||||
await expect(page.getByRole('dialog').getByText('登录列表暂不可用', { exact: true })).toBeVisible()
|
||||
await expect(page.getByRole('dialog').getByRole('button', { name: '撤销登录', exact: true })).toHaveCount(0)
|
||||
})
|
||||
|
||||
test('切换账号后旧请求不能覆盖新的登录列表', async ({ page }) => {
|
||||
const calls = await fixture(page, { slow: true }), old = await open(page, 'root')
|
||||
await expect.poll(() => calls.queries.includes('owner')).toBe(true)
|
||||
await old.getByRole('button', { name: '关闭', exact: true }).click()
|
||||
const current = await open(page, 'maintainer')
|
||||
await expect(current.getByText('共 21 次有效登录', { exact: true })).toBeVisible()
|
||||
await page.waitForTimeout(850)
|
||||
await expect(current.getByText('当前登录', { exact: true })).toHaveCount(0)
|
||||
expect(calls.revoked).toEqual([])
|
||||
})
|
||||
@@ -0,0 +1,92 @@
|
||||
import { test, expect, type Page } from '@playwright/test'
|
||||
|
||||
async function fixture(page: Page, options: { fail?: boolean; oversized?: boolean; exportFail?: boolean } = {}) {
|
||||
const queries: URLSearchParams[] = [], exports: URLSearchParams[] = [], writes: string[] = []
|
||||
const now = new Date().toISOString()
|
||||
await page.addInitScript(() => sessionStorage.setItem('vdi.accessToken', 'audit-fixture'))
|
||||
await page.route('**/api/v1/**', async route => {
|
||||
const request = route.request(), url = new URL(request.url()), path = url.pathname.replace('/api/v1', '')
|
||||
const list = (items: unknown[], extra = {}) => route.fulfill({ json: { items, total: items.length, page: 1, pageSize: 100, requestId: 'audit-ui', ...extra } })
|
||||
if (request.method() !== 'GET') { writes.push(path); await route.fulfill({ status: 403, json: { message: '不应发送写请求' } }); return }
|
||||
if (path === '/auth/me') { await route.fulfill({ json: { id: 'reader', username: 'reader', displayName: '只读人员', role: 'viewer' } }); return }
|
||||
if (path === '/settings') { await route.fulfill({ json: { mode: 'production', capabilities: ['audit'], pveConfigured: false } }); return }
|
||||
if (path === '/overview') { await route.fulfill({ json: { terminalCount: 0, onlineTerminals: 0, desktopCount: 0, runningDesktops: 0, activeSessions: 0, failedTasks: 0, mode: 'production' } }); return }
|
||||
if (path === '/audit-logs/export') {
|
||||
exports.push(url.searchParams)
|
||||
if (options.exportFail) { await route.fulfill({ status: 413, json: { message: '匹配记录超过 10000 条,请缩小时间范围', code: 'export_too_large', requestId: 'audit-ui' } }); return }
|
||||
await route.fulfill({ contentType: 'text/csv; charset=utf-8', body: '\ufeff时间,操作者\r\n2026-11-11T00:00:00Z,root\r\n' }); return
|
||||
}
|
||||
if (path === '/audit-logs') {
|
||||
queries.push(url.searchParams)
|
||||
if (options.fail && url.searchParams.get('keyword')) { await route.fulfill({ status: 500, json: { message: '审计查询暂不可用', code: 'database_error', requestId: 'audit-ui' } }); return }
|
||||
const p = Number(url.searchParams.get('page') || 1), filtered = !!url.searchParams.get('actor'), total = options.oversized ? 10001 : filtered ? 1 : 45
|
||||
const items = Array.from({ length: Math.min(20, total - (p - 1) * 20) }, (_, i) => ({ id: `audit-${(p - 1) * 20 + i + 1}`, actor: filtered ? 'operator_%' : 'root', action: 'save_alert_rule', target: `node-${(p - 1) * 20 + i + 1}`, result: 'success', requestId: `req-${p}-${i}`, createdAt: now }))
|
||||
await list(items, { total, page: p, pageSize: 20 }); return
|
||||
}
|
||||
if (['/resources', '/desktops', '/users', '/terminals', '/tasks'].includes(path)) { await list([]); return }
|
||||
await route.fulfill({ status: 404, json: { message: '未定义的测试接口' } })
|
||||
})
|
||||
return { queries, exports, writes }
|
||||
}
|
||||
|
||||
test('按需加载审计,真实分页参数和固定截止时间,浅色移动布局', async ({ page }, info) => {
|
||||
const calls = await fixture(page); await page.goto('/tasks')
|
||||
await expect(page.getByRole('tab', { name: '执行任务' })).toBeVisible()
|
||||
expect(calls.queries).toHaveLength(0)
|
||||
await page.getByRole('tab', { name: '操作审计' }).click()
|
||||
await expect(page.getByRole('cell', { name: 'node-1', exact: true })).toBeVisible()
|
||||
await page.locator('.el-pagination .btn-next').click()
|
||||
await expect(page.getByRole('cell', { name: 'node-21', exact: true })).toBeVisible()
|
||||
expect(calls.queries[calls.queries.length - 1]?.get('page')).toBe('2')
|
||||
expect(calls.queries[calls.queries.length - 1]?.get('to')).toBe(calls.queries[0]?.get('to'))
|
||||
await page.screenshot({ path: info.outputPath('audit-dark.png'), fullPage: true, animations: 'disabled' })
|
||||
await page.getByRole('button', { name: '切换浅色主题' }).click(); await page.setViewportSize({ width: 390, height: 844 })
|
||||
await page.screenshot({ path: info.outputPath('audit-mobile-light.png'), fullPage: true, animations: 'disabled' })
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(391)
|
||||
expect(calls.writes).toEqual([])
|
||||
})
|
||||
|
||||
test('操作人、动作、结果与时间筛选传到后端,导出使用已查询条件而非未提交的输入', async ({ page }) => {
|
||||
const calls = await fixture(page); await page.goto('/tasks'); await page.getByRole('tab', { name: '操作审计' }).click()
|
||||
await expect(page.getByRole('cell', { name: 'node-1', exact: true })).toBeVisible()
|
||||
await page.getByRole('textbox', { name: '审计操作者', exact: true }).fill('operator_%')
|
||||
await page.getByRole('textbox', { name: '审计关键词' }).fill('req_trace')
|
||||
await page.getByRole('combobox', { name: '审计动作' }).click(); await page.getByRole('option', { name: '保存告警规则', exact: true }).click()
|
||||
await page.getByRole('combobox', { name: '审计结果' }).click(); await page.getByRole('option', { name: '成功', exact: true }).click()
|
||||
await page.getByRole('combobox', { name: '审计时间范围' }).first().click(); await page.getByRole('button', { name: '最近 7 天', exact: true }).click()
|
||||
await page.getByRole('button', { name: '查询审计', exact: true }).click()
|
||||
await expect(page.getByRole('cell', { name: 'operator_%', exact: true })).toBeVisible()
|
||||
const q = calls.queries[calls.queries.length - 1]!
|
||||
expect(Object.fromEntries(q)).toMatchObject({ actor: 'operator_%', keyword: 'req_trace', action: 'save_alert_rule', result: 'success', page: '1', pageSize: '20' })
|
||||
expect(q.get('from')).toBeTruthy(); expect(q.get('to')).toBeTruthy()
|
||||
await page.getByRole('textbox', { name: '审计关键词' }).fill('还未查询的输入')
|
||||
const downloaded = page.waitForEvent('download'); await page.getByRole('button', { name: '导出查询结果 CSV' }).click()
|
||||
expect((await downloaded).suggestedFilename()).toMatch(/操作审计.*\.csv$/)
|
||||
expect(Object.fromEntries(calls.exports[0]!)).toMatchObject({ actor: 'operator_%', keyword: 'req_trace', action: 'save_alert_rule', result: 'success', from: q.get('from'), to: q.get('to') })
|
||||
expect(calls.exports[0]?.get('page')).toBeNull()
|
||||
await page.getByRole('button', { name: '重置', exact: true }).click()
|
||||
await expect(page.getByRole('cell', { name: 'root', exact: true }).first()).toBeVisible()
|
||||
expect(calls.queries[calls.queries.length - 1]?.get('actor')).toBe('')
|
||||
expect(calls.writes).toEqual([])
|
||||
})
|
||||
|
||||
test('查询失败清除旧结果并禁用导出,允许重试', async ({ page }) => {
|
||||
const calls = await fixture(page, { fail: true }); await page.goto('/tasks'); await page.getByRole('tab', { name: '操作审计' }).click()
|
||||
await expect(page.getByRole('cell', { name: 'node-1', exact: true })).toBeVisible()
|
||||
await page.getByRole('textbox', { name: '审计关键词' }).fill('failure'); await page.getByRole('button', { name: '查询审计', exact: true }).click()
|
||||
await expect(page.getByText(/审计查询暂不可用/)).toBeVisible(); await expect(page.getByRole('cell', { name: 'node-1', exact: true })).toHaveCount(0)
|
||||
await expect(page.getByRole('button', { name: '导出查询结果 CSV' })).toBeDisabled()
|
||||
await page.getByRole('button', { name: '重置', exact: true }).click(); await expect(page.getByRole('cell', { name: 'node-1', exact: true })).toBeVisible()
|
||||
expect(calls.exports).toHaveLength(0)
|
||||
})
|
||||
|
||||
test('导出超量有明确提示,服务端导出错误保留查询结果', async ({ page }) => {
|
||||
await fixture(page, { oversized: true }); await page.goto('/tasks'); await page.getByRole('tab', { name: '操作审计' }).click()
|
||||
await expect(page.getByText(/匹配记录超过 10000 条/)).toBeVisible()
|
||||
await expect(page.getByRole('button', { name: '导出查询结果 CSV' })).toBeDisabled()
|
||||
await page.unrouteAll(); await fixture(page, { exportFail: true }); await page.reload(); await page.getByRole('tab', { name: '操作审计' }).click()
|
||||
await expect(page.getByRole('cell', { name: 'node-1', exact: true })).toBeVisible()
|
||||
await page.getByRole('button', { name: '导出查询结果 CSV' }).click()
|
||||
await expect(page.getByText(/匹配记录超过 10000 条/)).toBeVisible()
|
||||
await expect(page.getByRole('cell', { name: 'node-1', exact: true })).toBeVisible()
|
||||
})
|
||||
@@ -0,0 +1,99 @@
|
||||
import { test, expect, type Page } from '@playwright/test'
|
||||
|
||||
async function fixture(page: Page, options: { role?: string; queryError?: boolean; exportError?: boolean; slow?: boolean; offline?: boolean; pending?: boolean; collectError?: boolean } = {}) {
|
||||
const queries: URLSearchParams[] = [], exports: URLSearchParams[] = [], writes: { path: string; key: string | undefined; body: unknown }[] = []
|
||||
let collected = false, attempts = 0
|
||||
const now = new Date().toISOString()
|
||||
const task = () => ({ id: 'collect-1', kind: 'terminal', action: 'collect-logs', targetId: 't1', targetName: '同名盒子', actor: 'operator', status: collected ? 'success' : 'running', message: collected ? '日志已回传' : '等待设备回执', providerRef: '', createdAt: now, updatedAt: now })
|
||||
await page.addInitScript(() => sessionStorage.setItem('vdi.accessToken', 'diagnostics-fixture'))
|
||||
await page.route('**/api/v1/**', async route => {
|
||||
const request = route.request(), url = new URL(request.url()), path = url.pathname.replace('/api/v1', '')
|
||||
const list = (items: unknown[]) => route.fulfill({ json: { items, total: items.length, page: 1, pageSize: 100 } })
|
||||
if (request.method() !== 'GET') {
|
||||
writes.push({ path, key: request.headers()['idempotency-key'], body: request.postDataJSON() })
|
||||
if (path === '/terminals/t1/commands') {
|
||||
attempts++
|
||||
if (options.collectError && attempts === 1) { await route.fulfill({ status: 503, json: { message: '提交结果尚未确认', code: 'unavailable', requestId: 'diag-ui' } }); return }
|
||||
collected = true; await route.fulfill({ status: 202, json: { ...task(), status: 'queued', message: '采集命令已提交' } }); return
|
||||
}
|
||||
await route.abort(); return
|
||||
}
|
||||
if (path === '/auth/me') { await route.fulfill({ json: { id: 'operator', username: 'operator', displayName: '运维', role: options.role || 'operator' } }); return }
|
||||
if (path === '/settings') { await route.fulfill({ json: { mode: 'production', pveConfigured: true, capabilities: [] } }); return }
|
||||
if (path === '/overview') { await route.fulfill({ json: { activeSessions: 1 } }); return }
|
||||
if (path === '/desktops') { await list([{ id: 'd1', name: '办公桌面', node: 'pve', vmid: 100, powerState: 'running', serviceState: 'unknown', os: 'Windows' }]); return }
|
||||
if (path === '/terminals') { await list(['t1', 't2'].map((id, i) => ({ id, name: '同名盒子', sn: `SN-${i + 1}`, status: options.offline ? 'offline' : 'online', enabled: true, lastSeen: now, sessionDesktopId: null }))); return }
|
||||
if (path === '/resources' || path === '/users') { await list([]); return }
|
||||
if (path === '/tasks') { await list(collected || options.pending ? [options.pending ? { ...task(), status: 'timeout' } : task()] : []); return }
|
||||
if (path === '/diagnostics/export') {
|
||||
exports.push(url.searchParams)
|
||||
if (options.exportError) { await route.fulfill({ status: 413, json: { code: 'export_too_large', message: '诊断事件超过 2000 条', requestId: 'diag-ui' } }); return }
|
||||
await route.fulfill({ contentType: 'application/zip', body: 'fixture-download' }); return
|
||||
}
|
||||
if (path === '/diagnostics') {
|
||||
queries.push(url.searchParams)
|
||||
if (options.queryError && url.searchParams.get('source')) { await route.fulfill({ status: 500, json: { message: '诊断查询暂不可用', requestId: 'diag-ui' } }); return }
|
||||
const target = url.searchParams.get('targetId') || 't1', kind = url.searchParams.get('targetType') || 'terminal', source = url.searchParams.get('source') || '', p = Number(url.searchParams.get('page') || 1)
|
||||
if (options.slow && target === 't1') await new Promise(resolve => setTimeout(resolve, 600))
|
||||
const items = [{ id: `event-${p}`, source: 'logs', time: now, action: 'collect-logs', status: 'success', targetId: target, targetName: target === 't2' ? '第二个同名盒子' : '同名盒子', actor: 'operator', message: target === 't2' ? '第二个设备独立记录' : '终端已回传的日志片段', details: JSON.stringify({ taskId: `task-${p}`, logTail: '<img src=x onerror="window.diagnosticInjected=true">\nnetwork error\n[REDACTED]', bootId: 'test' }) }]
|
||||
await route.fulfill({ json: { subject: { kind, id: target, name: kind === 'desktop' ? '办公桌面' : target === 't2' ? '第二个同名盒子' : '同名盒子', state: options.offline ? 'offline' : kind === 'desktop' ? 'running' : 'online', node: kind === 'desktop' ? 'pve' : '', vmid: kind === 'desktop' ? 100 : 0, lastSeen: now, agentVersion: 'test' }, from: url.searchParams.get('from') || now, to: url.searchParams.get('to') || now, observedAt: now, items, total: source ? 1 : 25, page: p, pageSize: 20, source, counts: { tasks: 10, sessions: 10, logs: 3, alerts: 1, audits: 1 }, notes: ['按唯一标识关联;无记录不代表设备无故障。', '日志为设备回传片段,当前快照独立于历史时间范围。'] } }); return
|
||||
}
|
||||
await route.fulfill({ status: 404, json: { message: '未定义的测试接口' } })
|
||||
})
|
||||
return { queries, exports, writes }
|
||||
}
|
||||
|
||||
test('按对象显式查询,关联来源与详情以纯文本展示,支持分页', async ({ page }) => {
|
||||
const calls = await fixture(page); await page.goto('/diagnostics')
|
||||
await expect(page.getByText('选择需要排查的设备或桌面,再查询诊断记录')).toBeVisible(); expect(calls.queries).toHaveLength(0)
|
||||
await page.getByRole('combobox', { name: '诊断对象', exact: true }).click(); await page.getByRole('option', { name: '同名盒子 / SN-1', exact: true }).click(); await page.getByRole('button', { name: '查询诊断', exact: true }).click()
|
||||
await expect(page.getByRole('heading', { name: '关联事件', exact: true })).toBeVisible(); expect(calls.queries.slice(-1)[0]?.get('targetId')).toBe('t1')
|
||||
await page.getByText('查看关联标识与详情', { exact: true }).click(); await expect(page.locator('.diagnosis-log')).toContainText('<img src=x'); expect(await page.evaluate(() => (window as Window & { diagnosticInjected?: boolean }).diagnosticInjected)).toBeUndefined()
|
||||
await expect(page.locator('.diagnosis-event img')).toHaveCount(0)
|
||||
const cutoff = calls.queries.slice(-1)[0]?.get('to'); await page.locator('.el-pagination .btn-next').click(); await expect.poll(() => calls.queries.slice(-1)[0]?.get('page')).toBe('2'); expect(calls.queries.slice(-1)[0]?.get('to')).toBe(cutoff)
|
||||
expect(calls.writes).toHaveLength(0)
|
||||
})
|
||||
|
||||
test('导出沿用已查询条件,修改筛选立即清除旧记录并禁用导出', async ({ page }) => {
|
||||
const calls = await fixture(page); await page.goto('/diagnostics?targetType=terminal&targetId=t1'); await expect(page.getByRole('heading', { name: '关联事件' })).toBeVisible()
|
||||
const applied = calls.queries.slice(-1)[0]!, download = page.waitForEvent('download'); await page.getByRole('button', { name: '导出诊断包', exact: true }).click(); expect((await download).suggestedFilename()).toContain('.zip')
|
||||
expect(calls.exports[0]?.get('targetId')).toBe(applied.get('targetId')); expect(calls.exports[0]?.get('to')).toBe(applied.get('to')); expect(calls.exports[0]?.get('page')).toBeNull()
|
||||
await page.locator('.diagnosis-query > .el-select').last().click(); await page.getByRole('option', { name: '监控告警', exact: true }).click(); await expect(page.getByRole('heading', { name: '关联事件' })).toHaveCount(0); await expect(page.getByRole('button', { name: '导出诊断包' })).toBeDisabled()
|
||||
await page.getByRole('button', { name: '查询诊断', exact: true }).click(); await expect(page.getByRole('heading', { name: '关联事件' })).toBeVisible(); expect(calls.queries.slice(-1)[0]?.get('source')).toBe('alerts')
|
||||
})
|
||||
|
||||
test('查询失败清除结果,导出超量显示后台错误', async ({ page }) => {
|
||||
const calls = await fixture(page, { queryError: true, exportError: true }); await page.goto('/diagnostics?targetType=terminal&targetId=t1'); await expect(page.getByRole('heading', { name: '关联事件' })).toBeVisible()
|
||||
await page.getByRole('button', { name: '导出诊断包' }).click(); await expect(page.getByText(/诊断事件超过 2000 条/)).toBeVisible()
|
||||
await page.locator('.diagnosis-query > .el-select').last().click(); await page.getByRole('option', { name: '执行任务', exact: true }).click(); await page.getByRole('button', { name: '查询诊断', exact: true }).click(); await expect(page.getByText(/诊断查询暂不可用/)).toBeVisible(); await expect(page.getByRole('heading', { name: '关联事件' })).toHaveCount(0); await expect(page.getByRole('button', { name: '导出诊断包' })).toBeDisabled(); expect(calls.writes).toHaveLength(0)
|
||||
})
|
||||
|
||||
test('切换对象后较晚返回的旧查询不能覆盖新对象', async ({ page }) => {
|
||||
await fixture(page, { slow: true }); await page.goto('/diagnostics?targetType=terminal&targetId=t1')
|
||||
await page.getByRole('combobox', { name: '诊断对象', exact: true }).click(); await page.getByRole('option', { name: '同名盒子 / SN-2', exact: true }).click(); await page.getByRole('button', { name: '查询诊断', exact: true }).click()
|
||||
await expect(page.getByRole('heading', { name: '第二个同名盒子', exact: true })).toBeVisible(); await expect(page.getByText('第二个设备独立记录')).toBeVisible(); await expect(page.getByRole('heading', { name: '同名盒子', exact: true })).toHaveCount(0)
|
||||
})
|
||||
|
||||
test('采集先确认,取消不提交,提交与回执分开,结果失败可复用原幂等标识', async ({ page }) => {
|
||||
const calls = await fixture(page, { collectError: true }); await page.goto('/diagnostics?targetType=terminal&targetId=t1'); await page.getByRole('button', { name: '收集此设备日志' }).click()
|
||||
const confirm = page.locator('.el-message-box'); await expect(confirm).toContainText('不会重启设备'); await confirm.getByRole('button', { name: '取消', exact: true }).click(); expect(calls.writes).toHaveLength(0)
|
||||
await page.getByRole('button', { name: '收集此设备日志' }).click(); await confirm.getByRole('button', { name: '确认提交' }).click(); await expect(page.getByText(/提交结果尚未确认/)).toBeVisible()
|
||||
await page.getByRole('button', { name: '收集此设备日志' }).click(); await confirm.getByRole('button', { name: '确认提交' }).click(); await expect(page.getByText('本次日志采集 · 同名盒子')).toBeVisible(); await expect(page.getByRole('button', { name: '查看本次采集' })).toBeVisible()
|
||||
expect(calls.writes).toHaveLength(2); expect(calls.writes[0]?.key).toBeTruthy(); expect(calls.writes[0]?.key).toBe(calls.writes[1]?.key); expect(calls.writes[1]?.body).toEqual({ action: 'collect-logs' })
|
||||
await page.getByRole('button', { name: '查看本次采集' }).click(); await expect.poll(() => calls.queries.slice(-1)[0]?.get('source')).toBe('logs')
|
||||
})
|
||||
|
||||
for (const options of [{ offline: true }, { pending: true }]) test(`离线或有未知任务时禁止发起新采集 ${JSON.stringify(options)}`, async ({ page }) => {
|
||||
const calls = await fixture(page, options); await page.goto('/diagnostics?targetType=terminal&targetId=t1'); await expect(page.getByRole('button', { name: '收集此设备日志' })).toBeDisabled(); expect(calls.writes).toHaveLength(0)
|
||||
})
|
||||
|
||||
test('只读角色隐藏高级入口且直接访问被拦截', async ({ page }) => {
|
||||
const calls = await fixture(page, { role: 'viewer' }); await page.goto('/overview'); await expect(page.getByRole('navigation', { name: '主导航' }).getByRole('link', { name: '日志与诊断' })).toHaveCount(0)
|
||||
await page.goto('/diagnostics?targetType=terminal&targetId=t1'); await expect(page).toHaveURL(/\/forbidden$/); expect(calls.queries).toHaveLength(0); expect(calls.writes).toHaveLength(0)
|
||||
})
|
||||
|
||||
test('桌面视角与深浅主题、390宽度布局可读', async ({ page }, info) => {
|
||||
const calls = await fixture(page); await page.goto('/diagnostics?targetType=desktop&targetId=d1'); await expect(page.getByRole('heading', { name: '办公桌面', exact: true })).toBeVisible(); await expect(page.getByRole('button', { name: '收集此设备日志' })).toHaveCount(0)
|
||||
await page.screenshot({ path: info.outputPath('diagnostics-dark.png'), fullPage: true, animations: 'disabled' }); await page.getByRole('button', { name: '切换浅色主题' }).click(); await page.screenshot({ path: info.outputPath('diagnostics-light.png'), fullPage: true, animations: 'disabled' })
|
||||
await page.setViewportSize({ width: 390, height: 844 }); expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true); await page.screenshot({ path: info.outputPath('diagnostics-mobile.png'), fullPage: true, animations: 'disabled' }); expect(calls.writes).toHaveLength(0)
|
||||
})
|
||||
@@ -0,0 +1,131 @@
|
||||
import { test, expect, type Page } from '@playwright/test'
|
||||
|
||||
async function fixture(page: Page, options: { role?: string; empty?: boolean; fail?: string; id?: string; saved?: string; timeout?: boolean } = {}) {
|
||||
const writes: { path: string; body: Record<string, unknown> }[] = [], reads: string[] = []
|
||||
let users = options.empty ? [] : [{ id: 'u1', username: 'zhang', displayName: '张三', enabled: true, terminalId: 't1', desktopIds: ['d1'] }, { id: 'u2', username: 'li', displayName: '李四', enabled: false, terminalId: null, desktopIds: [] as string[] }]
|
||||
const desktops = options.empty ? [] : ['d1', 'd2'].map((id, i) => ({ id, name: i ? '备用桌面' : '办公桌面', os: 'Windows', node: 'pve', vmid: 100 + i, powerState: i ? 'stopped' : 'running', serviceState: i ? 'unknown' : 'ready', setupRequired: false, updatedAt: new Date().toISOString() }))
|
||||
const terminals = options.empty ? [] : [{ id: 't1', sn: 'SN-01', name: '前台盒子', enabled: true, status: 'offline', sessionDesktopId: null, lastSeen: new Date().toISOString() }, { id: 't2', sn: 'SN-02', name: '新盒子', enabled: true, status: 'unregistered', sessionDesktopId: null, lastSeen: null }]
|
||||
const task = { id: 'k1', targetId: 'd2', targetName: '备用桌面', kind: 'desktop', action: 'start', status: options.timeout ? 'timeout' : 'success', message: '等待核对', actor: 'admin', createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() }
|
||||
await page.addInitScript(({ id, saved }) => { sessionStorage.setItem('vdi.accessToken', 'editions-fixture'); if (saved) localStorage.setItem(`vdi.console-mode:${id}`, saved) }, { id: options.id || 'admin', saved: options.saved })
|
||||
await page.route('**/api/v1/**', async route => {
|
||||
const request = route.request(), url = new URL(request.url()), path = url.pathname.replace('/api/v1', ''), method = request.method(), body = request.postData() ? request.postDataJSON() : {}
|
||||
const list = (items: unknown[], total = items.length) => route.fulfill({ json: { items, total, page: Number(url.searchParams.get('page') || 1), pageSize: 10, requestId: 'edition-ui' } })
|
||||
if (method !== 'GET') writes.push({ path, body }); else reads.push(path + url.search)
|
||||
if (options.fail === path && method !== 'GET' || options.fail === 'reads' && path === '/desktops' || options.fail === 'alerts' && path === '/monitor/alerts') { await route.fulfill({ status: 503, json: { code: 'unavailable', message: '当前服务不可用', requestId: 'edition-ui' } }); return }
|
||||
if (path === '/auth/me') { await route.fulfill({ json: { id: options.id || 'admin', username: 'admin', displayName: '管理员', role: options.role || 'super_admin' } }); return }
|
||||
if (path === '/settings') { await route.fulfill({ json: { mode: 'production', pveConfigured: true, capabilities: [] } }); return }
|
||||
if (path === '/overview') { await route.fulfill({ json: { activeSessions: 1, desktopCount: desktops.length, onlineTerminals: 0, terminalCount: terminals.length, runningDesktops: 1, failedTasks: 0 } }); return }
|
||||
if (path === '/desktops') { await list(desktops); return }
|
||||
if (path === '/users' && method === 'POST') { const user = { ...body, id: 'new-user', terminalId: null, desktopIds: [], enabled: true }; users.push(user); await route.fulfill({ status: 201, json: user }); return }
|
||||
if (path === '/users') { await list(users); return }
|
||||
if (path === '/terminals' && method === 'POST') { await route.fulfill({ status: 201, json: { id: 'new-terminal', activationSecret: 'one-time-test-secret' } }); return }
|
||||
if (path === '/terminals') { await list(terminals); return }
|
||||
if (path === '/users/batch-bindings') {
|
||||
users = users.map(u => body.userIds.includes(u.id) ? { ...u, desktopIds: body.action === 'grant' ? [...new Set([...u.desktopIds, ...body.desktopIds])] : u.desktopIds.filter(id => !body.desktopIds.includes(id)) } : u)
|
||||
await route.fulfill({ json: { affectedUsers: 1 } }); return
|
||||
}
|
||||
if (path.startsWith('/desktops/') && path.endsWith('/actions')) { await route.fulfill({ status: 202, json: task }); return }
|
||||
if (path === '/tasks') { await list(url.searchParams.get('active') ? options.timeout ? [task] : [] : [task]); return }
|
||||
if (path === '/audit-logs') { await list([{ id: 'a1', target: '张三', action: 'batch_grant_bindings', result: 'success', actor: 'admin', createdAt: new Date().toISOString() }], 21); return }
|
||||
if (path === '/monitor/alerts') { await route.fulfill({ json: { items: [], total: 0, firingCount: 0, unacknowledgedCount: 0 } }); return }
|
||||
if (path === '/resources') { await list([]); return }
|
||||
await route.fulfill({ status: 404, json: { message: '未定义的测试接口' } })
|
||||
})
|
||||
return { writes, reads }
|
||||
}
|
||||
|
||||
test('默认通用版五个入口,切换高级版保留专业深链和账号偏好', async ({ page }) => {
|
||||
const calls = await fixture(page); await page.goto('/')
|
||||
await expect(page).toHaveURL(/\/workbench$/); await expect(page.getByRole('heading', { name: '工作台', exact: true })).toBeVisible(); await expect(page.locator('.simple-stats .panel').first()).toContainText('运行中的桌面1 / 2 台桌面')
|
||||
const nav = page.getByRole('navigation', { name: '主导航' }); await expect(nav.getByRole('link')).toHaveCount(5)
|
||||
await expect(nav.getByRole('link', { name: 'GPU 资源' })).toHaveCount(0)
|
||||
await page.getByRole('button', { name: '高级版', exact: true }).click(); await expect(page).toHaveURL(/\/overview$/)
|
||||
await expect(nav.getByRole('link', { name: 'GPU 资源' })).toBeVisible(); await expect(nav.getByRole('link', { name: '镜像模板' })).toBeVisible()
|
||||
await page.goto('/'); await expect(page).toHaveURL(/\/overview$/)
|
||||
await page.goto('/people'); await expect(page.getByRole('button', { name: '通用版', exact: true })).toHaveAttribute('aria-pressed', 'true')
|
||||
await page.goto('/users'); await expect(page.getByRole('heading', { name: '用户与授权' })).toBeVisible()
|
||||
expect(calls.writes).toHaveLength(0)
|
||||
})
|
||||
|
||||
test('另一个账号默认通用版,存储不可用时仍可切换', async ({ page }) => {
|
||||
await fixture(page, { id: 'reader' }); await page.addInitScript(() => { localStorage.setItem('vdi.console-mode:another-account', 'advanced'); Storage.prototype.setItem = () => { throw new Error('storage disabled') } })
|
||||
await page.goto('/'); await expect(page).toHaveURL(/\/workbench$/)
|
||||
await page.getByRole('button', { name: '高级版', exact: true }).click(); await expect(page).toHaveURL(/\/overview$/)
|
||||
})
|
||||
|
||||
test('授权先展示固定对象方案,确认才提交,追加和撤销保留其余授权', async ({ page }) => {
|
||||
const calls = await fixture(page); await page.goto('/people')
|
||||
const row = page.getByRole('row').filter({ hasText: '张三' }).first()
|
||||
await row.getByRole('button', { name: '分配桌面', exact: true }).click()
|
||||
const dialog = page.getByRole('dialog', { name: '分配已有桌面' }); await dialog.locator('.el-checkbox').filter({ hasText: '备用桌面' }).click()
|
||||
await dialog.getByRole('button', { name: '查看方案' }).click(); await expect(dialog.getByText('确认变更方案')).toBeVisible(); expect(calls.writes).toHaveLength(0)
|
||||
await dialog.getByRole('button', { name: '确认并保存授权' }).dblclick(); await expect(dialog).not.toBeVisible()
|
||||
expect(calls.writes).toEqual([{ path: '/users/batch-bindings', body: { userIds: ['u1'], desktopIds: ['d2'], action: 'grant' } }])
|
||||
await expect(row).toContainText('备用桌面'); await expect(row).toContainText('办公桌面'); await expect(row).toContainText('前台盒子')
|
||||
await row.getByRole('button', { name: '撤销授权' }).click(); const revoke = page.getByRole('dialog', { name: '撤销指定授权' })
|
||||
await revoke.locator('.el-checkbox').filter({ hasText: '备用桌面' }).click(); await revoke.getByRole('button', { name: '查看方案' }).click(); await revoke.getByRole('button', { name: '确认并保存授权' }).click()
|
||||
await expect(revoke).not.toBeVisible(); await expect(row).not.toContainText('备用桌面'); await expect(row).toContainText('办公桌面')
|
||||
expect(calls.writes[1]?.body).toEqual({ userIds: ['u1'], desktopIds: ['d2'], action: 'revoke' })
|
||||
})
|
||||
|
||||
test('授权失败保留方案,不显示成功或自动重发', async ({ page }) => {
|
||||
const calls = await fixture(page, { fail: '/users/batch-bindings' }); await page.goto('/people')
|
||||
await page.getByRole('row').filter({ hasText: '张三' }).first().getByRole('button', { name: '分配桌面' }).click()
|
||||
const dialog = page.getByRole('dialog', { name: '分配已有桌面' }); await dialog.locator('.el-checkbox').filter({ hasText: '备用桌面' }).click(); await dialog.getByRole('button', { name: '查看方案' }).click(); await dialog.getByRole('button', { name: '确认并保存授权' }).click()
|
||||
await expect(page.getByText(/当前服务不可用/)).toBeVisible(); await expect(dialog).toBeVisible(); expect(calls.writes).toHaveLength(1)
|
||||
})
|
||||
|
||||
for (const role of ['viewer', 'operator']) test(`${role}切换版本不提升权限`, async ({ page }) => {
|
||||
const calls = await fixture(page, { role }); await page.goto('/people')
|
||||
await expect(page.getByRole('button', { name: '添加员工' })).toHaveCount(0); await expect(page.getByRole('button', { name: '分配桌面', exact: true })).toHaveCount(0)
|
||||
if (role === 'viewer') await expect(page.getByRole('button', { name: '正常关机', exact: true })).toHaveCount(0)
|
||||
await page.getByRole('button', { name: '高级版', exact: true }).click(); await page.goto('/settings'); await expect(page).toHaveURL(/\/forbidden$/)
|
||||
expect(calls.writes).toHaveLength(0)
|
||||
})
|
||||
|
||||
test('设备诊断只读,区分离线、等待激活与缺少关联', async ({ page }) => {
|
||||
const calls = await fixture(page); await page.goto('/help?terminal=t1')
|
||||
await expect(page.getByText('未收到在线心跳,请检查盒子电源、网络和平台地址。')).toBeVisible(); await expect(page.getByText('使用人:张三')).toBeVisible(); await expect(page.getByText('桌面运行且连接服务就绪', { exact: false })).toBeVisible()
|
||||
await page.goto('/help?terminal=t2'); await expect(page.getByText('设备尚未激活', { exact: false })).toBeVisible(); await expect(page.getByText('请在员工与桌面中关联此设备。')).toBeVisible()
|
||||
expect(calls.writes).toHaveLength(0)
|
||||
})
|
||||
|
||||
test('设备登记返回真实接口激活信息,关闭后移除且不持久化', async ({ page }) => {
|
||||
const calls = await fixture(page); await page.goto('/devices'); await page.getByRole('button', { name: '登记新设备' }).click()
|
||||
await page.getByLabel('新设备名称').fill('新设备'); await page.getByLabel('新设备 SN').fill('SN-NEW'); await page.getByRole('button', { name: '登记并获取激活信息' }).click()
|
||||
const dialog = page.getByRole('dialog', { name: '请保存设备激活信息' }); await expect(dialog.getByLabel('设备激活密钥')).toHaveValue('one-time-test-secret')
|
||||
await dialog.getByRole('button', { name: '已保存,关闭' }).click(); await expect(dialog).not.toBeVisible()
|
||||
expect(await page.evaluate(() => JSON.stringify({ ...localStorage, ...sessionStorage }))).not.toContain('one-time-test-secret')
|
||||
expect(calls.writes[0]).toEqual({ path: '/terminals', body: { name: '新设备', sn: 'SN-NEW', group: '' } })
|
||||
})
|
||||
|
||||
test('电源操作取消不提交,结果未知时阻止重复操作', async ({ page }) => {
|
||||
const calls = await fixture(page, { timeout: true }); await page.goto('/people')
|
||||
const backup = page.getByRole('row').filter({ hasText: '备用桌面' }).last(); await expect(backup.getByRole('button', { name: '开机', exact: true })).toBeDisabled()
|
||||
await page.getByRole('button', { name: '重启桌面', exact: true }).click(); const dialog = page.locator('.el-message-box')
|
||||
await expect(dialog).toContainText('保存文件'); await dialog.getByRole('button', { name: '取消', exact: true }).click(); expect(calls.writes).toHaveLength(0)
|
||||
await page.getByRole('button', { name: '重启桌面', exact: true }).click(); await dialog.getByRole('button', { name: '确认提交', exact: true }).click()
|
||||
await expect.poll(() => calls.writes.length).toBe(1); expect(calls.writes[0]).toEqual({ path: '/desktops/d1/actions', body: { action: 'reboot' } })
|
||||
})
|
||||
|
||||
test('通用记录查历史审计和任务,服务端分页', async ({ page }) => {
|
||||
const calls = await fixture(page); await page.goto('/records'); await expect(page.getByRole('cell', { name: '批量分配桌面' })).toBeVisible()
|
||||
await page.locator('.el-pagination .btn-next').click(); await expect.poll(() => calls.reads.some(p => p.includes('/audit-logs?') && p.includes('page=2'))).toBe(true)
|
||||
await page.getByRole('tab', { name: '设备与桌面任务' }).click(); await expect(page.getByRole('cell', { name: '等待核对' })).toBeVisible()
|
||||
expect(calls.writes).toHaveLength(0)
|
||||
})
|
||||
|
||||
test('空态、告警失败和平台数据失败有明确提示', async ({ page }) => {
|
||||
await fixture(page, { empty: true, fail: 'alerts' }); await page.goto('/people'); await expect(page.getByText('暂无员工,请先添加员工')).toBeVisible()
|
||||
await page.goto('/help'); await expect(page.getByText(/告警读取失败,不能判断是否正常/)).toBeVisible(); await expect(page.getByText('当前没有触发中的告警')).toHaveCount(0)
|
||||
await page.unroute('**/api/v1/**'); await fixture(page, { fail: 'reads' }); await page.goto('/workbench'); await expect(page.getByText('数据刷新失败,当前信息可能已过期')).toBeVisible()
|
||||
})
|
||||
|
||||
test('通用工作台深浅主题与窄屏导航无溢出', async ({ page }, info) => {
|
||||
await fixture(page); await page.goto('/workbench'); await expect(page.getByRole('heading', { name: '你想完成什么?' })).toBeVisible()
|
||||
await page.screenshot({ path: info.outputPath('workbench-dark.png'), fullPage: true })
|
||||
await page.getByRole('button', { name: /切换浅色主题/ }).click(); await page.screenshot({ path: info.outputPath('workbench-light.png'), fullPage: true })
|
||||
await page.setViewportSize({ width: 390, height: 844 }); await page.getByRole('button', { name: '打开导航', exact: true }).click(); await expect(page.getByRole('navigation', { name: '主导航' }).getByRole('link', { name: '员工与桌面' })).toBeVisible()
|
||||
await page.getByRole('button', { name: '关闭导航', exact: true }).click(); expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true)
|
||||
await page.screenshot({ path: info.outputPath('workbench-mobile.png'), fullPage: true })
|
||||
})
|
||||
@@ -0,0 +1,45 @@
|
||||
import { test, expect, type Page } from '@playwright/test'
|
||||
async function fixture(page: Page, options: { role?: string; fail?: boolean; status?: string } = {}) {
|
||||
const writes: string[] = []
|
||||
const task = { id: 'gpu-task', kind: 'gpu-prepare', action: 'prepare-desktop', targetId: 'desk', targetName: '显卡办公桌面', actor: 'device:box', status: options.status || 'timeout', message: '等待核对', providerRef: '{}', createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() }
|
||||
await page.addInitScript(() => sessionStorage.setItem('vdi.accessToken', 'gpu-fixture'))
|
||||
await page.route('**/api/v1/**', async route => {
|
||||
const request = route.request(), url = new URL(request.url()), path = url.pathname.replace('/api/v1', '')
|
||||
const list = (items: unknown[]) => route.fulfill({ json: { items, total: items.length, page: 1, pageSize: 20 } })
|
||||
if (request.method() !== 'GET') {
|
||||
writes.push(path)
|
||||
if (path !== '/tasks/gpu-task/gpu-reconcile') { await route.abort(); return }
|
||||
if (options.fail) { await route.fulfill({ status: 409, json: { code: 'unknown_submission', message: '未记录原 PVE 任务编号,需要在 PVE 手工核对,不能自动重发', requestId: 'gpu-ui' } }); return }
|
||||
task.status = 'failed'; task.message = '管理员已核对原 PVE 任务及实际电源状态,可重新准备桌面'
|
||||
await route.fulfill({ json: { reconciled: true, vmid: '100' } }); return
|
||||
}
|
||||
if (path === '/auth/me') { await route.fulfill({ json: { id: 'admin', username: 'admin', displayName: '管理员', role: options.role || 'operator' } }); return }
|
||||
if (path === '/settings') { await route.fulfill({ json: { mode: 'production', pveConfigured: true, capabilities: [] } }); return }
|
||||
if (path === '/overview') { await route.fulfill({ json: {} }); return }
|
||||
if (path === '/tasks') { await list(url.searchParams.get('active') && task.status !== 'timeout' ? [] : [task]); return }
|
||||
if (['/desktops', '/users', '/terminals', '/resources'].includes(path)) { await list([]); return }
|
||||
await route.fulfill({ status: 404, json: { message: '未定义接口' } })
|
||||
})
|
||||
return writes
|
||||
}
|
||||
|
||||
test('高级版运维先确认再核对,取消无变更,成功后不再提供核对按钮', async ({ page }) => {
|
||||
const writes = await fixture(page); await page.goto('/tasks'); await page.getByRole('button', { name: '显卡办公桌面', exact: true }).click()
|
||||
const drawer = page.getByRole('dialog', { name: '任务详情' }); await drawer.getByRole('button', { name: '核对显卡准备结果', exact: true }).click()
|
||||
const confirm = page.locator('.el-message-box'); await expect(confirm).toContainText('不重发电源操作'); await expect(confirm).toContainText('原任务标记为失败')
|
||||
await confirm.getByRole('button', { name: '取消', exact: true }).click(); expect(writes).toHaveLength(0)
|
||||
await drawer.getByRole('button', { name: '核对显卡准备结果', exact: true }).click(); await confirm.getByRole('button', { name: '确认提交' }).click()
|
||||
await expect(drawer).not.toBeVisible(); expect(writes).toEqual(['/tasks/gpu-task/gpu-reconcile'])
|
||||
await page.getByRole('button', { name: '显卡办公桌面', exact: true }).click(); await expect(drawer.getByRole('button', { name: '核对显卡准备结果' })).toHaveCount(0)
|
||||
})
|
||||
|
||||
test('缺少原任务编号显示后台拒绝,保留未知状态且不自动重发', async ({ page }) => {
|
||||
const writes = await fixture(page, { fail: true }); await page.goto('/tasks'); await page.getByRole('button', { name: '显卡办公桌面', exact: true }).click()
|
||||
const drawer = page.getByRole('dialog', { name: '任务详情' }); await drawer.getByRole('button', { name: '核对显卡准备结果' }).click(); await page.locator('.el-message-box').getByRole('button', { name: '确认提交' }).click()
|
||||
await expect(page.getByText(/未记录原 PVE 任务编号/)).toBeVisible(); await expect(drawer).toBeVisible(); expect(writes).toEqual(['/tasks/gpu-task/gpu-reconcile'])
|
||||
})
|
||||
|
||||
for (const options of [{ role: 'viewer' }, { role: 'operator', status: 'success' }]) test(`角色${options.role}与状态${options.status || 'timeout'}限制核对`, async ({ page }) => {
|
||||
const writes = await fixture(page, options); await page.goto('/tasks'); await page.getByRole('button', { name: '显卡办公桌面', exact: true }).click()
|
||||
await expect(page.getByRole('dialog', { name: '任务详情' }).getByRole('button', { name: '核对显卡准备结果' })).toHaveCount(0); expect(writes).toHaveLength(0)
|
||||
})
|
||||
@@ -0,0 +1,98 @@
|
||||
import { test, expect, type Page } from '@playwright/test'
|
||||
|
||||
async function fixture(page: Page, options: { enabled?: boolean; fail?: boolean; loggedOut?: boolean } = {}) {
|
||||
const writes: { path: string; body: Record<string, string> }[] = []
|
||||
let enabled = options.enabled ?? false
|
||||
const codes = Array.from({ length: 8 }, (_, i) => `AAAAAAAA-BBBBBBBB-CCCCCCCC-${String(i).padStart(8, '0')}`)
|
||||
if (!options.loggedOut) await page.addInitScript(() => sessionStorage.setItem('vdi.accessToken', 'mfa-fixture'))
|
||||
await page.route('**/api/v1/**', async route => {
|
||||
const request = route.request(), path = new URL(request.url()).pathname.replace('/api/v1', ''), body = request.postData() ? request.postDataJSON() : {}
|
||||
if (request.method() !== 'GET') writes.push({ path, body })
|
||||
const fail = (code: string, message: string, status = 400) => route.fulfill({ status, json: { code, message, requestId: 'mfa-ui' } })
|
||||
if (path === '/auth/login') {
|
||||
if (body.password !== 'Correct-password-2026') { await fail('invalid_credentials', '用户名或密码错误', 401); return }
|
||||
if (!body.code) { await fail('mfa_required', '请输入身份验证器动态码或一次性恢复码', 401); return }
|
||||
if (body.code !== '123456' && body.code !== codes[0]) { await fail('mfa_invalid', '验证码错误、已使用或已过期', 401); return }
|
||||
await route.fulfill({ json: { accessToken: 'logged-in-after-mfa', expiresIn: 3600, user: { id: 'reader', username: 'reader', displayName: '查看员', role: 'viewer' } } }); return
|
||||
}
|
||||
if (path === '/auth/me') { await route.fulfill({ json: { id: 'reader', username: 'reader', displayName: '查看员', role: 'viewer' } }); return }
|
||||
if (path === '/auth/mfa' && request.method() === 'GET') { await route.fulfill({ json: { enabled, recoveryRemaining: enabled ? 8 : 0 } }); return }
|
||||
if (path === '/auth/mfa/setup') {
|
||||
if (body.password !== 'Correct-password-2026') { await fail('current_password_invalid', '当前密码不正确'); return }
|
||||
await route.fulfill({ json: { secret: 'JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP', provisioningUri: 'otpauth://totp/VDI%20Cloud:reader?secret=example', expiresAt: new Date(Date.now() + 600000).toISOString() } }); return
|
||||
}
|
||||
if (path === '/auth/mfa/confirm') {
|
||||
if (options.fail || body.code !== '123456') { await fail('mfa_invalid', '验证码错误或已过期'); return }
|
||||
enabled = true; await route.fulfill({ json: { recoveryCodes: codes } }); return
|
||||
}
|
||||
if (path === '/auth/mfa/recovery') { await route.fulfill({ json: { recoveryCodes: codes } }); return }
|
||||
if (path === '/auth/mfa' && request.method() === 'DELETE') { enabled = false; await route.fulfill({ status: 204 }); return }
|
||||
if (path === '/settings') { await route.fulfill({ json: { mode: 'production', capabilities: ['admin-mfa'], pveConfigured: true } }); return }
|
||||
if (path === '/overview') { await route.fulfill({ json: { terminalCount: 0, onlineTerminals: 0, desktopCount: 0, runningDesktops: 0, activeSessions: 0, failedTasks: 0, mode: 'production' } }); return }
|
||||
if (['/resources', '/desktops', '/users', '/terminals', '/tasks'].includes(path)) { await route.fulfill({ json: { items: [], total: 0, page: 1, pageSize: 100, requestId: 'mfa-ui' } }); return }
|
||||
await route.fulfill({ status: 404, json: { message: '测试接口未定义' } })
|
||||
})
|
||||
return { writes, codes }
|
||||
}
|
||||
|
||||
test('只读人员也可绑定本人验证器,确认后才开启,恢复码下载和关闭后不再显示', async ({ page }, info) => {
|
||||
const calls = await fixture(page); await page.goto('/overview'); await page.getByRole('button', { name: '双重验证', exact: true }).click()
|
||||
const dialog = page.getByRole('dialog', { name: '本人双重验证', exact: true })
|
||||
await expect(dialog.getByText('未开启', { exact: true })).toBeVisible()
|
||||
await dialog.getByLabel('双重验证当前密码', { exact: true }).fill('Correct-password-2026')
|
||||
await dialog.getByRole('button', { name: '开始绑定身份验证器' }).click()
|
||||
await expect(dialog.getByLabel('身份验证器密钥')).toBeVisible()
|
||||
expect(calls.writes.map(x => x.path)).toEqual(['/auth/mfa/setup'])
|
||||
await dialog.getByRole('textbox', { name: '绑定动态码' }).fill('123456'); await dialog.getByRole('button', { name: '验证并开启' }).click()
|
||||
await expect(dialog.getByText('恢复码仅显示这一次,请先保存')).toBeVisible()
|
||||
await expect(dialog.getByText(calls.codes[0]!, { exact: true })).toBeVisible()
|
||||
const download = page.waitForEvent('download'); await dialog.getByRole('button', { name: '下载恢复码' }).click(); expect((await download).suggestedFilename()).toBe('vdi-cloud-recovery-codes.txt')
|
||||
await page.screenshot({ path: info.outputPath('mfa-recovery-dark.png'), fullPage: true, animations: 'disabled' })
|
||||
await dialog.getByRole('button', { name: '已保存,关闭' }).click(); await page.getByRole('button', { name: '双重验证', exact: true }).click()
|
||||
await expect(dialog.getByText('已开启', { exact: true })).toBeVisible(); await expect(dialog.getByText(calls.codes[0]!, { exact: true })).toHaveCount(0)
|
||||
expect(await page.evaluate(() => JSON.stringify({ ...localStorage, ...sessionStorage }))).not.toContain('JBSWY3')
|
||||
})
|
||||
|
||||
test('验证码错误保持未完成绑定,窄屏和浅色布局可用,关闭清除密钥', async ({ page }, info) => {
|
||||
await fixture(page, { fail: true }); await page.goto('/overview'); await page.getByRole('button', { name: '切换浅色主题' }).click(); await page.setViewportSize({ width: 390, height: 844 })
|
||||
await page.getByRole('button', { name: '双重验证', exact: true }).click(); const dialog = page.getByRole('dialog', { name: '本人双重验证' })
|
||||
await dialog.getByLabel('双重验证当前密码', { exact: true }).fill('Correct-password-2026'); await dialog.getByRole('button', { name: '开始绑定身份验证器' }).click()
|
||||
await dialog.getByRole('textbox', { name: '绑定动态码' }).fill('111111'); await dialog.getByRole('button', { name: '验证并开启' }).click()
|
||||
await expect(dialog.getByText(/验证码错误或已过期/)).toBeVisible(); await expect(dialog.getByText('恢复码仅显示这一次,请先保存')).toHaveCount(0)
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(391)
|
||||
await page.screenshot({ path: info.outputPath('mfa-setup-mobile-light.png'), fullPage: true, animations: 'disabled' })
|
||||
await dialog.getByRole('button', { name: '关闭', exact: true }).click(); await page.getByRole('button', { name: '双重验证', exact: true }).click(); await expect(dialog.getByText('未开启', { exact: true })).toBeVisible(); await expect(dialog.getByLabel('身份验证器密钥')).toHaveCount(0)
|
||||
})
|
||||
|
||||
test('更新恢复码和关闭需要密码及验证码,取消不提交', async ({ page }) => {
|
||||
const calls = await fixture(page, { enabled: true }); await page.goto('/overview'); await page.getByRole('button', { name: '双重验证', exact: true }).click()
|
||||
const dialog = page.getByRole('dialog', { name: '本人双重验证' })
|
||||
await dialog.getByRole('button', { name: '关闭双重验证', exact: true }).click()
|
||||
await dialog.getByLabel('双重验证当前密码', { exact: true }).fill('Correct-password-2026'); await dialog.getByRole('textbox', { name: '双重验证确认码' }).fill('123456')
|
||||
await dialog.getByRole('button', { name: '确认关闭双重验证' }).click(); await page.locator('.el-message-box').getByRole('button', { name: '取消', exact: true }).click(); expect(calls.writes).toHaveLength(0)
|
||||
await dialog.getByRole('button', { name: '确认关闭双重验证' }).click(); await page.locator('.el-message-box').getByRole('button', { name: '确认提交' }).click()
|
||||
await expect(dialog.getByText('未开启', { exact: true })).toBeVisible(); expect(calls.writes[0]?.body).toEqual({ password: 'Correct-password-2026', code: '123456' })
|
||||
})
|
||||
|
||||
test('重新生成恢复码经过确认后显示新码并支持下载', async ({ page }) => {
|
||||
const calls = await fixture(page, { enabled: true }); await page.goto('/overview'); await page.getByRole('button', { name: '双重验证', exact: true }).click()
|
||||
const dialog = page.getByRole('dialog', { name: '本人双重验证' })
|
||||
await dialog.getByRole('button', { name: '重新生成恢复码', exact: true }).click()
|
||||
await dialog.getByLabel('双重验证当前密码', { exact: true }).fill('Correct-password-2026'); await dialog.getByRole('textbox', { name: '双重验证确认码' }).fill(calls.codes[0]!)
|
||||
await dialog.getByRole('button', { name: '生成新恢复码', exact: true }).click(); expect(calls.writes).toHaveLength(0)
|
||||
await page.locator('.el-message-box').getByRole('button', { name: '确认提交', exact: true }).click()
|
||||
await expect(dialog.getByText('恢复码仅显示这一次,请先保存')).toBeVisible()
|
||||
expect(calls.writes[0]?.path).toBe('/auth/mfa/recovery'); expect(calls.writes[0]?.body.code).toBe(calls.codes[0])
|
||||
const download = page.waitForEvent('download'); await dialog.getByRole('button', { name: '下载恢复码' }).click(); expect((await download).suggestedFilename()).toBe('vdi-cloud-recovery-codes.txt')
|
||||
})
|
||||
|
||||
for (const recovery of [false, true]) test(`登录先验证密码,动态码${recovery ? '使用恢复码' : '错误后重试'}成功前不保存令牌`, async ({ page }) => {
|
||||
const calls = await fixture(page, { loggedOut: true }); await page.goto('/login')
|
||||
await page.getByRole('textbox', { name: '用户名', exact: true }).fill('reader'); await page.getByLabel('密码', { exact: true }).fill('incorrect'); await page.getByRole('button', { name: '登录', exact: true }).click()
|
||||
await expect(page.getByText(/用户名或密码错误/)).toBeVisible(); await expect(page.getByRole('textbox', { name: '登录动态码或恢复码' })).toHaveCount(0)
|
||||
await page.getByLabel('密码', { exact: true }).fill('Correct-password-2026'); await page.getByRole('button', { name: '登录', exact: true }).click()
|
||||
const input = page.getByRole('textbox', { name: '登录动态码或恢复码' }); await expect(input).toBeVisible(); expect(await page.evaluate(() => sessionStorage.getItem('vdi.accessToken'))).toBeNull()
|
||||
await input.fill('111111'); await page.getByRole('button', { name: '登录', exact: true }).click(); await expect(page.getByText(/验证码错误、已使用或已过期/)).toBeVisible(); await expect(input).toHaveValue('')
|
||||
await input.fill(recovery ? calls.codes[0]! : '123456'); await page.getByRole('button', { name: '登录', exact: true }).click(); await expect(page).toHaveURL(/\/workbench$/)
|
||||
expect(await page.evaluate(() => sessionStorage.getItem('vdi.accessToken'))).toBe('logged-in-after-mfa')
|
||||
})
|
||||
@@ -0,0 +1,90 @@
|
||||
import { test, expect, type Page } from '@playwright/test'
|
||||
|
||||
async function fixture(page: Page, options: { fail?: boolean; pending?: boolean; slow?: boolean } = {}) {
|
||||
const queries: URLSearchParams[] = [], exports: URLSearchParams[] = [], writes: string[] = [], now = new Date().toISOString()
|
||||
await page.addInitScript(() => sessionStorage.setItem('vdi.accessToken', 'task-history-fixture'))
|
||||
const task = (i: number, extra = {}) => ({ id: `task-${i}`, kind: 'desktop', action: 'start', targetId: `desk-${i}`, targetName: `历史桌面 ${i}`, actor: 'root', status: 'success', message: '真实回执已保存', providerRef: '', createdAt: now, updatedAt: now, ...extra })
|
||||
await page.route('**/api/v1/**', async route => {
|
||||
const request = route.request(), url = new URL(request.url()), path = url.pathname.replace('/api/v1', '')
|
||||
const list = (items: unknown[], extra = {}) => route.fulfill({ json: { items, total: items.length, page: 1, pageSize: 100, requestId: 'task-ui', ...extra } })
|
||||
if (request.method() !== 'GET') { writes.push(path); await route.fulfill({ status: 403, json: { message: '不应发送业务写请求' } }); return }
|
||||
if (path === '/auth/me') { await route.fulfill({ json: { id: 'reader', username: 'reader', displayName: '任务查看员', role: options.pending ? 'operator' : 'viewer' } }); return }
|
||||
if (path === '/settings') { await route.fulfill({ json: { mode: 'production', capabilities: ['task-history'], pveConfigured: false } }); return }
|
||||
if (path === '/overview') { await route.fulfill({ json: { terminalCount: 0, onlineTerminals: 0, desktopCount: options.pending ? 1 : 0, runningDesktops: 0, activeSessions: 0, failedTasks: 0, mode: 'production' } }); return }
|
||||
if (path === '/tasks/export') { exports.push(url.searchParams); await route.fulfill({ contentType: 'text/csv; charset=utf-8', body: '\ufeff任务标识,状态\r\ntask-1,success\r\n' }); return }
|
||||
if (path === '/tasks') {
|
||||
queries.push(url.searchParams)
|
||||
const p = Number(url.searchParams.get('page') || 1), size = Number(url.searchParams.get('pageSize') || 20), active = url.searchParams.get('active') === 'true'
|
||||
if (active) {
|
||||
const total = options.pending ? 101 : 0
|
||||
await list(Array.from({ length: Math.max(0, Math.min(size, total - (p - 1) * size)) }, (_, i) => task(2000 + (p - 1) * size + i, { status: 'queued', targetId: (p - 1) * size + i === 100 ? 'desk-pending' : `pending-${i}` })), { total, page: p, pageSize: size }); return
|
||||
}
|
||||
const keyword = url.searchParams.get('keyword') || ''
|
||||
if (options.fail && keyword) { await route.fulfill({ status: 500, json: { code: 'database_error', message: '任务查询暂不可用', requestId: 'task-ui' } }); return }
|
||||
if (options.slow && keyword === 'slow') await new Promise(resolve => setTimeout(resolve, 700))
|
||||
const filtered = !!url.searchParams.get('actor') || !!keyword, total = options.pending ? 1500 : filtered ? 1 : 45
|
||||
await list(Array.from({ length: Math.max(0, Math.min(size, total - (p - 1) * size)) }, (_, i) => task((p - 1) * size + i + 1, filtered ? { targetName: keyword || '筛选桌面', actor: url.searchParams.get('actor') || 'root' } : {})), { total, page: p, pageSize: size }); return
|
||||
}
|
||||
if (path === '/desktops' && options.pending) { await list([{ id: 'desk-pending', name: '有旧任务的桌面', vmid: 9000, node: 'test', os: 'Ubuntu', pool: '', provider: 'proxmox', powerState: 'stopped', serviceState: 'unknown', setupRequired: false, endpoint: '192.0.2.1', width: 1920, height: 1080, fps: 30, updatedAt: now }]); return }
|
||||
if (['/resources', '/desktops', '/users', '/terminals', '/audit-logs'].includes(path)) { await list([]); return }
|
||||
await route.fulfill({ status: 404, json: { message: '未定义的测试接口' } })
|
||||
})
|
||||
return { queries, exports, writes }
|
||||
}
|
||||
|
||||
test('任务历史分页、详情和深浅窄屏,历史读取不依赖全局近期任务', async ({ page }, info) => {
|
||||
const calls = await fixture(page); await page.goto('/tasks')
|
||||
await expect(page.getByRole('button', { name: '历史桌面 1', exact: true })).toBeVisible()
|
||||
const initialPages = calls.queries.filter(q => q.get('pageSize') === '20')
|
||||
const cutoffBeforePaging = initialPages[initialPages.length - 1]?.get('to')
|
||||
await page.locator('.el-pagination .btn-next').click(); await expect(page.getByRole('button', { name: '历史桌面 21', exact: true })).toBeVisible()
|
||||
await page.getByRole('button', { name: '历史桌面 21', exact: true }).click()
|
||||
const drawer = page.getByRole('dialog', { name: '任务详情' })
|
||||
await expect(drawer.getByText('task-21', { exact: true })).toBeVisible()
|
||||
await expect(drawer.getByRole('button', { name: /核对/ })).toHaveCount(0)
|
||||
await drawer.locator('.el-drawer__close-btn').click()
|
||||
await page.screenshot({ path: info.outputPath('task-history-dark.png'), fullPage: true, animations: 'disabled' })
|
||||
await page.getByRole('button', { name: '切换浅色主题' }).click(); await page.setViewportSize({ width: 390, height: 844 })
|
||||
await page.screenshot({ path: info.outputPath('task-history-mobile.png'), fullPage: true, animations: 'disabled' })
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(391)
|
||||
const pages = calls.queries.filter(q => q.get('pageSize') === '20')
|
||||
expect(pages[pages.length - 1]?.get('page')).toBe('2'); expect(pages[pages.length - 1]?.get('to')).toBe(cutoffBeforePaging)
|
||||
expect(calls.writes).toEqual([])
|
||||
})
|
||||
|
||||
test('任务筛选和导出沿用已应用条件,修改草稿后导出不混用', async ({ page }) => {
|
||||
const calls = await fixture(page); await page.goto('/tasks'); await expect(page.getByRole('button', { name: '历史桌面 1', exact: true })).toBeVisible()
|
||||
await page.getByRole('textbox', { name: '任务操作者' }).fill('root_%')
|
||||
await page.locator('.el-select').filter({ has: page.getByRole('combobox', { name: '任务状态筛选' }) }).click(); await page.getByRole('option', { name: '成功', exact: true }).click()
|
||||
await page.getByRole('combobox', { name: '任务动作' }).click(); await page.getByRole('option', { name: '开机', exact: true }).click()
|
||||
await page.getByRole('combobox', { name: '任务类型' }).click(); await page.getByRole('option', { name: '桌面电源', exact: true }).click()
|
||||
await page.getByRole('combobox', { name: '任务时间范围' }).first().click(); await page.getByRole('button', { name: '最近 7 天', exact: true }).click()
|
||||
await page.getByRole('button', { name: '查询任务', exact: true }).click(); await expect(page.getByRole('button', { name: '筛选桌面', exact: true })).toBeVisible()
|
||||
await page.getByRole('textbox', { name: '搜索任务' }).fill('尚未应用')
|
||||
const wait = page.waitForEvent('download'); await page.getByRole('button', { name: '导出任务 CSV' }).click()
|
||||
expect((await wait).suggestedFilename()).toMatch(/执行任务.*\.csv$/)
|
||||
expect(Object.fromEntries(calls.exports[0]!)).toMatchObject({ actor: 'root_%', status: 'success', action: 'start', kind: 'desktop', keyword: '' })
|
||||
expect(calls.exports[0]?.get('from')).toBeTruthy(); expect(calls.exports[0]?.get('page')).toBeNull()
|
||||
await page.getByRole('button', { name: '重置', exact: true }).click(); await expect(page.getByRole('button', { name: '历史桌面 1', exact: true })).toBeVisible()
|
||||
expect(calls.writes).toEqual([])
|
||||
})
|
||||
|
||||
test('查询失败清理旧结果并禁用导出,旧响应不能覆盖新条件', async ({ page }) => {
|
||||
await fixture(page, { fail: true }); await page.goto('/tasks'); await expect(page.getByRole('button', { name: '历史桌面 1', exact: true })).toBeVisible()
|
||||
await page.getByRole('textbox', { name: '搜索任务' }).fill('failure'); await page.getByRole('button', { name: '查询任务', exact: true }).click()
|
||||
await expect(page.getByText(/任务查询暂不可用/)).toBeVisible(); await expect(page.getByRole('button', { name: '导出任务 CSV' })).toBeDisabled()
|
||||
await expect(page.getByRole('button', { name: '历史桌面 1', exact: true })).toHaveCount(0)
|
||||
await page.unrouteAll(); await fixture(page, { slow: true }); await page.reload(); await expect(page.getByRole('button', { name: '历史桌面 1', exact: true })).toBeVisible()
|
||||
await page.getByRole('textbox', { name: '搜索任务' }).fill('slow'); await page.getByRole('textbox', { name: '搜索任务' }).press('Enter')
|
||||
await page.getByRole('textbox', { name: '搜索任务' }).fill('new'); await page.getByRole('textbox', { name: '搜索任务' }).press('Enter')
|
||||
await expect(page.getByRole('button', { name: 'new', exact: true })).toBeVisible()
|
||||
await expect.poll(async () => { await page.waitForTimeout(800); return page.getByRole('button', { name: 'slow', exact: true }).count() }).toBe(0)
|
||||
})
|
||||
|
||||
test('全局只取近期一页并分页拉全旧活动任务,旧任务仍阻止操作桌面', async ({ page }) => {
|
||||
const calls = await fixture(page, { pending: true }); await page.goto('/desktops')
|
||||
await expect(page.getByRole('button', { name: '任务执行中', exact: true })).toBeDisabled()
|
||||
expect(calls.queries.some(q => q.get('active') === 'true' && q.get('page') === '2')).toBe(true)
|
||||
expect(calls.queries.some(q => q.get('active') !== 'true' && q.get('page') === '2')).toBe(false)
|
||||
expect(calls.writes).toEqual([])
|
||||
})
|
||||
@@ -0,0 +1,94 @@
|
||||
import { test, expect, type Page } from '@playwright/test'
|
||||
|
||||
async function fixture(page: Page, options: { role?: string; stale?: boolean; resolved?: boolean; fail?: boolean } = {}) {
|
||||
const writes: { path: string; body: Record<string, unknown> }[] = [], now = new Date().toISOString()
|
||||
let acknowledged = false
|
||||
await page.addInitScript(() => sessionStorage.setItem('vdi.accessToken', 'terminal-alert-fixture'))
|
||||
const rules: Record<string, unknown>[] = [{ id: 'temp-rule', name: '终端温度高水位', metric: 'terminal_temperature', threshold: 80, holdSeconds: 120, enabled: true }]
|
||||
await page.route('**/api/v1/**', async route => {
|
||||
const request = route.request(), path = new URL(request.url()).pathname.replace('/api/v1', '')
|
||||
const list = (items: unknown[], extra = {}) => route.fulfill({ json: { items, total: items.length, page: 1, pageSize: 100, requestId: 'alert-ui', ...extra } })
|
||||
if (request.method() !== 'GET') {
|
||||
const body = request.postDataJSON(); writes.push({ path, body })
|
||||
if (path.endsWith('/acknowledge')) { acknowledged = true; await route.fulfill({ json: { accepted: true } }); return }
|
||||
if (path.startsWith('/monitor/rules')) {
|
||||
if (options.fail) { await route.fulfill({ status: 400, json: { message: '温度阈值超出范围', code: 'invalid_request', requestId: 'alert-ui' } }); return }
|
||||
const rule = { ...body, id: path.endsWith('/temp-rule') ? 'temp-rule' : 'created-rule' }
|
||||
if (path.endsWith('/temp-rule')) rules[0] = rule; else rules.push(rule)
|
||||
await route.fulfill({ json: rule }); return
|
||||
}
|
||||
await route.fulfill({ status: 403, json: { message: '不应出现的写操作' } }); return
|
||||
}
|
||||
if (path === '/auth/me') { await route.fulfill({ json: { id: 'alerts-reader', username: 'reader', displayName: '告警人员', role: options.role || 'super_admin' } }); return }
|
||||
if (path === '/settings') { await route.fulfill({ json: { mode: 'production', capabilities: ['terminal-metric-alerts'], pveConfigured: false } }); return }
|
||||
if (path === '/overview') { await route.fulfill({ json: { terminalCount: 1, onlineTerminals: 1, desktopCount: 0, runningDesktops: 0, activeSessions: 0, failedTasks: 0, mode: 'production' } }); return }
|
||||
if (path === '/monitor/rules') { await list(rules); return }
|
||||
if (path === '/monitor/alerts') {
|
||||
await list([{ id: 'temp-alert', ruleId: 'temp-rule', ruleName: '终端温度高水位', metric: 'terminal_temperature', targetId: 'box1', targetName: '测试盒子', value: 86.5, threshold: 80, status: options.resolved ? 'resolved' : 'firing', startedAt: now, openedAt: now, resolvedAt: options.resolved ? now : null, resolveReason: options.resolved ? 'condition_cleared' : '', acknowledgedAt: acknowledged ? now : null, acknowledgedBy: acknowledged ? 'reader' : '', dataFresh: !options.stale }], { firingCount: options.resolved ? 0 : 1, unacknowledgedCount: acknowledged || options.resolved ? 0 : 1 }); return
|
||||
}
|
||||
if (['/resources', '/desktops', '/users', '/terminals', '/tasks', '/audit-logs'].includes(path)) { await list([]); return }
|
||||
await route.fulfill({ status: 404, json: { message: '测试接口未定义', requestId: 'alert-ui' } })
|
||||
})
|
||||
return writes
|
||||
}
|
||||
|
||||
test('新增 SoC 温度规则使用摄氏度和独立上限,切换内存使用百分比', async ({ page }, info) => {
|
||||
const writes = await fixture(page); await page.goto('/monitor')
|
||||
await expect(page.getByRole('cell', { name: '86.5 / 80 °C', exact: true })).toBeVisible()
|
||||
await page.getByRole('tab', { name: '告警规则' }).click()
|
||||
await expect(page.getByRole('cell', { name: '80°C / 120 秒', exact: true })).toBeVisible()
|
||||
await page.getByRole('button', { name: '新增规则', exact: true }).click()
|
||||
const dialog = page.getByRole('dialog', { name: '新增告警规则' })
|
||||
await dialog.locator('.el-select').click(); await page.getByRole('option', { name: '终端 SoC 温度', exact: true }).click()
|
||||
await expect(dialog.getByText('SoC 温度阈值(°C)', { exact: true })).toBeVisible()
|
||||
await expect(dialog.getByRole('spinbutton', { name: '告警阈值' })).toHaveAttribute('aria-valuemax', '150')
|
||||
await expect(dialog.getByText(/重复读取不推进/)).toBeVisible()
|
||||
await dialog.getByRole('textbox', { name: '规则名称' }).fill('盒子过热')
|
||||
await page.screenshot({ path: info.outputPath('terminal-alert-create-dark.png'), fullPage: true, animations: 'disabled' })
|
||||
await dialog.getByRole('button', { name: '保存规则', exact: true }).click()
|
||||
await expect(dialog).toBeHidden()
|
||||
expect(writes[0]?.body).toMatchObject({ name: '盒子过热', metric: 'terminal_temperature', threshold: 80, holdSeconds: 120, enabled: true })
|
||||
await page.getByRole('button', { name: '新增规则', exact: true }).click()
|
||||
await dialog.locator('.el-select').click(); await page.getByRole('option', { name: '终端内存', exact: true }).click()
|
||||
await expect(dialog.getByText('使用率阈值(%)', { exact: true })).toBeVisible()
|
||||
await expect(dialog.getByRole('spinbutton', { name: '告警阈值' })).toHaveAttribute('aria-valuemax', '100')
|
||||
await dialog.getByRole('button', { name: '取消', exact: true }).click()
|
||||
expect(writes).toHaveLength(1)
|
||||
})
|
||||
|
||||
test('过期数据保留告警和最近值,确认不表示恢复', async ({ page }, info) => {
|
||||
const writes = await fixture(page, { role: 'operator', stale: true }); await page.goto('/monitor')
|
||||
await expect(page.getByText('数据已过期或缺失;显示最近告警值,等待有效采样', { exact: true })).toBeVisible()
|
||||
await page.getByRole('button', { name: '确认告警' }).click()
|
||||
await expect(page.getByRole('cell', { name: '正在告警', exact: true })).toBeVisible()
|
||||
await expect(page.getByRole('button', { name: '确认告警' })).toHaveCount(0)
|
||||
await page.getByRole('button', { name: '切换浅色主题' }).click()
|
||||
await page.setViewportSize({ width: 390, height: 844 })
|
||||
await page.screenshot({ path: info.outputPath('terminal-alert-stale-mobile-light.png'), fullPage: true, animations: 'disabled' })
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(391)
|
||||
await page.getByRole('tab', { name: '告警规则' }).click()
|
||||
await expect(page.getByRole('button', { name: '新增规则' })).toHaveCount(0)
|
||||
expect(writes).toHaveLength(1)
|
||||
})
|
||||
|
||||
test('只读人员可看恢复事件和摄氏度,无确认或规则写入口', async ({ page }) => {
|
||||
const writes = await fixture(page, { role: 'viewer', stale: true, resolved: true }); await page.goto('/monitor')
|
||||
await expect(page.getByRole('cell', { name: '已恢复', exact: true })).toBeVisible()
|
||||
await expect(page.getByText('指标恢复', { exact: true })).toBeVisible()
|
||||
await expect(page.getByText(/数据已过期或缺失/)).toHaveCount(0)
|
||||
await expect(page.getByRole('button', { name: '确认告警' })).toHaveCount(0)
|
||||
await page.getByRole('tab', { name: '告警规则' }).click()
|
||||
await expect(page.getByRole('button', { name: '编辑规则' })).toHaveCount(0)
|
||||
expect(writes).toEqual([])
|
||||
})
|
||||
|
||||
test('保存错误保留表单和数值,取消不改变规则', async ({ page }) => {
|
||||
const writes = await fixture(page, { fail: true }); await page.goto('/monitor')
|
||||
await page.getByRole('tab', { name: '告警规则' }).click(); await page.getByRole('button', { name: '编辑规则' }).click()
|
||||
const dialog = page.getByRole('dialog', { name: '编辑告警规则' })
|
||||
await dialog.getByRole('button', { name: '保存规则', exact: true }).click()
|
||||
await expect(page.getByText(/温度阈值超出范围/)).toBeVisible()
|
||||
await expect(dialog).toBeVisible()
|
||||
await dialog.getByRole('button', { name: '取消', exact: true }).click(); await expect(dialog).toBeHidden()
|
||||
expect(writes).toHaveLength(1)
|
||||
})
|
||||
@@ -0,0 +1 @@
|
||||
export const auditActionLabels: Record<string, string> = { export_diagnostics: '导出诊断包', read_diagnostics: '读取终端诊断', 'batch-start': '批量开机提交', 'batch-shutdown': '批量关机提交', 'batch-reboot': '批量重启提交', reconcile_batch_power: '核对批量电源', 'snapshot-create': '创建快照', 'snapshot-delete': '删除快照', 'snapshot-rollback': '还原快照', reconcile_snapshot: '核对快照', 'configure-hardware': '调整 CPU/内存', 'expand-disk': '磁盘扩容', reconcile_hardware: '核对规格', save_pve_connection: '保存 PVE 接入', create_terminal_policy: '创建终端策略', deploy_terminal_policy: '下发终端策略', terminal_policy_applied: '策略应用成功', terminal_policy_failed: '策略应用失败', update_terminal: '更新终端资料', disable_terminal: '停用终端', reactivate_terminal: '重新激活终端', update_user: '更新用户资料', batch_grant_bindings: '批量分配桌面', batch_revoke_bindings: '批量撤销桌面', create_administrator: '新增管理员', update_administrator: '更新管理员', reset_administrator_password: '重置管理员密码', change_own_password: '修改本人密码', reconcile_clone: '核对克隆', clone: '克隆桌面', register_template: '登记模板', update_template: '更新模板', validate_template: '验证模板', save_pool: '保存桌面池', update_pool_members: '更新池成员', configure_desktop: '配置连接', start: '开机', shutdown: '正常关机', reboot: '重启', 'reset-session': '重置会话', 'collect-logs': '收集日志', sync: '同步资源', login: '登录', logout: '退出登录', create_user: '创建用户', enroll_terminal: '登记终端', update_bindings: '更新授权', import_desktop: '纳管桌面', save_alert_rule: '保存告警规则', acknowledge_alert: '确认告警', export_audit_logs: '导出操作审计', export_tasks: '导出任务记录', revoke_administrator_session: '撤销管理员登录', enable_mfa: '开启双重验证', disable_mfa: '关闭双重验证', rotate_mfa_recovery: '更新恢复码', 'prepare-desktop': '准备独占显卡桌面', 'reconcile-gpu-switch': '核对显卡切换' }
|
||||
@@ -2,6 +2,9 @@ import createClient from 'openapi-fetch'
|
||||
import type { paths, components } from './schema'
|
||||
|
||||
export type PveConnectionInput = components['schemas']['PveConnectionInput']
|
||||
export type DiagnosticReport = components['schemas']['DiagnosticReport']
|
||||
export type DiagnosticEvent = components['schemas']['DiagnosticEvent']
|
||||
export type DiagnosticQuery = NonNullable<paths['/diagnostics']['get']['parameters']['query']>
|
||||
export type PowerBatchInput = components['schemas']['PowerBatchInput']
|
||||
export type PowerBatch = components['schemas']['PowerBatch']
|
||||
export type PowerBatchDetail = components['schemas']['PowerBatchDetail']
|
||||
@@ -12,6 +15,8 @@ export type SnapshotItem = components['schemas']['SnapshotItem']
|
||||
export type HardwareInput = components['schemas']['HardwareInput']
|
||||
export type VMHardware = components['schemas']['VMHardware']
|
||||
export type Admin = components['schemas']['Administrator']
|
||||
export type MFAStatus = components['schemas']['MFAStatus']
|
||||
export type MFASetup = components['schemas']['MFASetup']
|
||||
export type ImportPreview = components['schemas']['CsvImportPreview']
|
||||
export type ImportResult = components['schemas']['CsvImportResult']
|
||||
export type CsvImportInput = components['schemas']['CsvImportInput']
|
||||
@@ -28,6 +33,7 @@ export type PolicyDeployment = components['schemas']['PolicyDeployment']
|
||||
export type PolicyDeploymentInput = components['schemas']['PolicyDeploymentInput']
|
||||
export type PolicyResult = components['schemas']['PolicyResult']
|
||||
export type AdministratorAccount = components['schemas']['AdministratorAccount']
|
||||
export type AdministratorSession = components['schemas']['AdministratorSession']
|
||||
export type CreateAdministrator = components['schemas']['CreateAdministrator']
|
||||
export type UpdateAdministrator = components['schemas']['UpdateAdministrator']
|
||||
export type Desktop = components['schemas']['Desktop']
|
||||
@@ -48,6 +54,8 @@ export type GPUInventory = components['schemas']['GPUInventory']
|
||||
export type GPUItem = components['schemas']['GPUItem']
|
||||
export type Task = components['schemas']['Task']
|
||||
export type Audit = components['schemas']['Audit']
|
||||
export type AuditQuery = NonNullable<paths['/audit-logs']['get']['parameters']['query']>
|
||||
export type TaskQuery = NonNullable<paths['/tasks']['get']['parameters']['query']>
|
||||
export type Overview = components['schemas']['Overview']
|
||||
export type Settings = components['schemas']['Settings']
|
||||
export type BindingInput = components['schemas']['BindingInput']
|
||||
@@ -80,6 +88,9 @@ async function result<T>(promise: Promise<Result<T>>): Promise<T> {
|
||||
const commandHeaders = () => ({ 'Idempotency-Key': crypto.randomUUID() })
|
||||
const query = { page: 1, pageSize: 100 }
|
||||
export const api = {
|
||||
diagnostics: (filters: DiagnosticQuery) => result(client.GET('/diagnostics', { params: { query: filters } })),
|
||||
exportDiagnostics: (filters: DiagnosticQuery) => result(client.GET('/diagnostics/export', { params: { query: filters }, parseAs: 'blob' })),
|
||||
collectTerminalLogs: (id: string, key: string) => result(client.POST('/terminals/{id}/commands', { params: { path: { id }, header: { 'Idempotency-Key': key } }, body: { action: 'collect-logs' } })),
|
||||
gpuInventory: (node: string) => result(client.GET('/resources/gpus', { params: { query: { node } } })),
|
||||
pveConnection: () => result(client.GET('/settings/pve')),
|
||||
checkPveConnection: (body: PveConnectionInput) => result(client.POST('/settings/pve/check', { body })),
|
||||
@@ -89,6 +100,7 @@ export const api = {
|
||||
checkDesktopPowerBatch: (body: PowerBatchInput) => result(client.POST('/desktop-batches/check', { body })),
|
||||
submitDesktopPowerBatch: (body: PowerBatchInput, key: string) => result(client.POST('/desktop-batches', { params: { header: { 'Idempotency-Key': key } }, body })),
|
||||
reconcileBatchPower: (id: string) => result(client.POST('/tasks/{id}/batch-power-reconcile', { params: { path: { id } } })),
|
||||
reconcileGPUPrepare: (id: string) => result(client.POST('/tasks/{id}/gpu-reconcile', { params: { path: { id } } })),
|
||||
desktopSnapshots: (id: string) => result(client.GET('/desktops/{id}/snapshots', { params: { path: { id } } })),
|
||||
checkDesktopSnapshot: (id: string, body: SnapshotInput) => result(client.POST('/desktops/{id}/snapshots/check', { params: { path: { id } }, body })),
|
||||
changeDesktopSnapshot: (id: string, body: SnapshotInput, key: string) => result(client.POST('/desktops/{id}/snapshots/actions', { params: { path: { id }, header: { 'Idempotency-Key': key } }, body })),
|
||||
@@ -112,11 +124,18 @@ export const api = {
|
||||
policyDeployments: (page = 1) => result(client.GET('/terminal-policy-deployments', { params: { query: { ...query, page } } })),
|
||||
deployPolicy: (body: PolicyDeploymentInput, key: string) => result(client.POST('/terminal-policy-deployments', { params: { header: { 'Idempotency-Key': key } }, body })),
|
||||
policyResults: (id: string, page = 1) => result(client.GET('/terminal-policy-deployments/{id}/results', { params: { path: { id }, query: { ...query, page } } })),
|
||||
login: (username: string, password: string) => result(client.POST('/auth/login', { body: { username, password } })),
|
||||
login: (username: string, password: string, code?: string) => result(client.POST('/auth/login', { body: { username, password, ...(code ? { code } : {}) } })),
|
||||
mfaStatus: () => result(client.GET('/auth/mfa')),
|
||||
beginMFA: (password: string) => result(client.POST('/auth/mfa/setup', { body: { password } })),
|
||||
confirmMFA: (code: string) => result(client.POST('/auth/mfa/confirm', { body: { code } })),
|
||||
rotateMFARecovery: (password: string, code: string) => result(client.POST('/auth/mfa/recovery', { body: { password, code } })),
|
||||
disableMFA: (password: string, code: string) => result(client.DELETE('/auth/mfa', { body: { password, code } })),
|
||||
me: () => result(client.GET('/auth/me')),
|
||||
logout: () => result(client.POST('/auth/logout')),
|
||||
changeOwnPassword: (currentPassword: string, newPassword: string) => result(client.POST('/auth/password', { body: { currentPassword, newPassword } })),
|
||||
administrators: (page = 1) => result(client.GET('/administrators', { params: { query: { ...query, page } } })),
|
||||
administratorSessions: (id: string, page = 1) => result(client.GET('/administrators/{id}/sessions', { params: { path: { id }, query: { page, pageSize: 20 } } })),
|
||||
revokeAdministratorSession: (id: string, sessionKey: string) => result(client.DELETE('/administrators/{id}/sessions/{sessionKey}', { params: { path: { id, sessionKey } } })),
|
||||
createAdministrator: (body: CreateAdministrator) => result(client.POST('/administrators', { body })),
|
||||
updateAdministrator: (id: string, body: UpdateAdministrator) => result(client.PUT('/administrators/{id}', { params: { path: { id } }, body })),
|
||||
resetAdministratorPassword: (id: string, password: string) => result(client.POST('/administrators/{id}/password', { params: { path: { id } }, body: { password } })),
|
||||
@@ -127,9 +146,13 @@ export const api = {
|
||||
terminals: (page = 1) => result(client.GET('/terminals', { params: { query: { ...query, page } } })),
|
||||
users: (page = 1) => result(client.GET('/users', { params: { query: { ...query, page } } })),
|
||||
tasks: (page = 1) => result(client.GET('/tasks', { params: { query: { ...query, page } } })),
|
||||
activeTasks: (page = 1) => result(client.GET('/tasks', { params: { query: { ...query, page, active: true } } })),
|
||||
taskHistory: (filters: TaskQuery = {}) => result(client.GET('/tasks', { params: { query: filters } })),
|
||||
exportTasks: (filters: TaskQuery) => result(client.GET('/tasks/export', { params: { query: filters }, parseAs: 'blob' })),
|
||||
taskDiagnostics: (id: string) => result(client.GET('/tasks/{id}/diagnostics', { params: { path: { id } } })),
|
||||
reconcileProvision: (id: string) => result(client.POST('/tasks/{id}/reconcile', { params: { path: { id } } })),
|
||||
audits: (page = 1) => result(client.GET('/audit-logs', { params: { query: { ...query, page } } })),
|
||||
audits: (filters: AuditQuery = {}) => result(client.GET('/audit-logs', { params: { query: filters } })),
|
||||
exportAudits: (filters: AuditQuery) => result(client.GET('/audit-logs/export', { params: { query: filters }, parseAs: 'blob' })),
|
||||
discoverVMs: () => result(client.GET('/resources/vms', { params: { query } })),
|
||||
templates: (page = 1) => result(client.GET('/templates', { params: { query: { ...query, page } } })),
|
||||
discoverTemplates: (page = 1) => result(client.GET('/resources/templates', { params: { query: { ...query, page } } })),
|
||||
@@ -166,4 +189,8 @@ export async function allPages<T>(loader: (page: number) => Promise<{ items: T[]
|
||||
}
|
||||
return items
|
||||
}
|
||||
export async function recentAndActiveTasks(): Promise<Task[]> {
|
||||
const [recent, active] = await Promise.all([api.tasks(), allPages(api.activeTasks)])
|
||||
return [...new Map([...recent.items, ...active].map(task => [task.id, task])).values()]
|
||||
}
|
||||
export const errorMessage = (e: unknown) => e instanceof ApiError ? `${e.message}${e.requestId ? `(请求 ${e.requestId})` : ''}` : e instanceof Error ? e.message : '操作失败,请重试'
|
||||
Vendored
+1866
-3
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1 @@
|
||||
.simple-stats{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:18px}.simple-stats .panel{padding:22px}.simple-stats span{color:var(--vdi-muted);font-size:13px}.simple-stats strong{display:block;font-size:32px;margin-top:14px}.simple-stats small{font-size:12px;color:var(--vdi-muted);font-weight:400}.simple-section{padding:24px;margin-top:22px}.simple-section h2{font-size:18px;margin-bottom:12px}.simple-shortcuts{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:14px;margin-top:22px}.simple-shortcuts a{padding:22px;border:1px solid var(--vdi-border);border-radius:12px;background:var(--vdi-panel-2)}.simple-shortcuts strong{display:block;color:var(--vdi-accent);font-size:15px}.simple-shortcuts span{display:block;margin-top:12px;font-size:12px;color:var(--vdi-muted);line-height:1.8}.simple-issues{display:grid;gap:18px;margin:22px 0}.simple-issues a{font-size:14px}.simple-check{display:flex;align-items:flex-start;gap:14px;border-top:1px solid var(--vdi-border);padding:18px 0}.simple-check:first-of-type{margin-top:20px}.simple-check p{color:var(--vdi-muted);line-height:1.8;margin:7px 0 0;font-size:13px}.simple-check strong{font-size:14px}.simple-check .el-tag{flex-shrink:0}.simple-checks{display:grid;margin:20px 0;max-height:45vh;overflow:auto}.simple-checks .el-checkbox{white-space:normal;height:auto;min-height:36px}.simple-checks .el-checkbox__label{white-space:normal}.simple-plan{line-height:1.9;padding:16px;border-radius:12px;background:var(--vdi-panel-2);margin-top:16px}.simple-plan ul{padding-left:20px}.simple-row{display:flex;align-items:center;justify-content:space-between;gap:12px}.simple-section>.el-select{max-width:450px;margin-bottom:18px}@media(max-width:1000px){.simple-shortcuts{grid-template-columns:1fr}.simple-stats{gap:10px}.simple-stats .panel{padding:16px}.simple-stats strong{font-size:24px}}@media(max-width:550px){.simple-stats{grid-template-columns:1fr}.simple-stats strong{margin-top:8px}.simple-section{padding:18px}.simple-check{gap:10px}.simple-section h2{font-size:17px}}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { describe, expect, test } from 'vitest'
|
||||
import { diagnoseTerminal } from './diagnosis'
|
||||
import type { Desktop, Terminal, User } from '../api'
|
||||
const terminal = { id: 't', name: '盒子', status: 'online', enabled: true } as Terminal
|
||||
const user = { id: 'u', displayName: '员工', enabled: true, terminalId: 't', desktopIds: ['d'] } as User
|
||||
const desktop = { id: 'd', name: '桌面', powerState: 'running', serviceState: 'ready', setupRequired: false } as Desktop
|
||||
describe('终端诊断的连接前提', () => {
|
||||
test('运行但服务未检测时不能报告全部通过', () => {
|
||||
const result = diagnoseTerminal(terminal, [user], [{ ...desktop, serviceState: 'unknown' }])
|
||||
expect(result.slice(-1)[0]?.ok).toBe(false)
|
||||
expect(result.slice(-1)[0]?.detail).toContain('不代表一定不可用')
|
||||
})
|
||||
test('已停用设备、员工与待初始化桌面分别说明', () => {
|
||||
const result = diagnoseTerminal({ ...terminal, enabled: false }, [{ ...user, enabled: false }], [{ ...desktop, setupRequired: true }])
|
||||
expect(result.filter(c => !c.ok).map(c => c.title)).toEqual(['设备已启用', '员工已启用', '桌面'])
|
||||
})
|
||||
test('缺少关联时不猜测使用人;失效桌面授权不能报告已分配', () => {
|
||||
expect(diagnoseTerminal(terminal, [], [desktop])).toHaveLength(3)
|
||||
expect(diagnoseTerminal(terminal, [user], []).slice(-1)[0]?.ok).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { Desktop, Terminal, User } from '../api'
|
||||
|
||||
export interface Check { title: string; ok: boolean; detail: string }
|
||||
export function diagnoseTerminal(terminal: Terminal, users: User[], desktops: Desktop[]): Check[] {
|
||||
const user = users.find(u => u.terminalId === terminal.id)
|
||||
const assigned = desktops.filter(d => user?.desktopIds.includes(d.id))
|
||||
const checks: Check[] = [
|
||||
{ title: '设备已启用', ok: terminal.enabled !== false && terminal.status !== 'disabled', detail: terminal.enabled === false || terminal.status === 'disabled' ? '设备已停用,请联系管理员重新激活。' : '设备未被停用。' },
|
||||
{ title: '设备在线', ok: terminal.status === 'online', detail: terminal.status === 'online' ? '平台收到设备在线心跳。' : terminal.status === 'unregistered' ? '设备尚未激活,请在盒子上配置登记时的激活信息。' : '未收到在线心跳,请检查盒子电源、网络和平台地址。' },
|
||||
{ title: '已关联员工', ok: !!user, detail: user ? `使用人:${user.displayName}` : '请在员工与桌面中关联此设备。' },
|
||||
]
|
||||
if (!user) return checks
|
||||
checks.push({ title: '员工已启用', ok: user.enabled, detail: user.enabled ? '员工可申请桌面连接。' : '员工已停用,请由管理员核查。' })
|
||||
checks.push({ title: '已分配桌面', ok: assigned.length > 0, detail: assigned.length ? `已分配 ${assigned.length} 台桌面。` : '请为员工分配已有桌面;失效授权需由管理员清理。' })
|
||||
for (const desktop of assigned) {
|
||||
checks.push({ title: desktop.name, ok: desktop.powerState === 'running' && desktop.serviceState === 'ready' && !desktop.setupRequired,
|
||||
detail: desktop.setupRequired ? '桌面仍需完成初始化,请联系运维。' : desktop.powerState !== 'running' ? '桌面尚未运行,请先开机。' : desktop.serviceState !== 'ready' ? '桌面已运行,但平台尚未确认连接服务就绪;不代表一定不可用,请检查连接配置或联系运维。' : '桌面运行且连接服务就绪;实际网络和画面仍需连接后验证。' })
|
||||
}
|
||||
return checks
|
||||
}
|
||||
@@ -5,8 +5,10 @@ import { ElMessage } from 'element-plus'
|
||||
import { api, allPages, errorMessage, type AdministratorAccount, type UpdateAdministrator } from '../api'
|
||||
import { useAuth } from '../stores/auth'
|
||||
import { useAction } from '../composables/useAction'
|
||||
import AdministratorSessions from './AdministratorSessions.vue'
|
||||
const auth = useAuth(), { confirm } = useAction()
|
||||
const items = ref<AdministratorAccount[]>([]), loading = ref(false), busy = ref(false), error = ref(''), formError = ref(''), keyword = ref('')
|
||||
const sessionTarget = ref<AdministratorAccount>()
|
||||
const visible = ref(false), editing = ref<AdministratorAccount>(), resetTarget = ref<AdministratorAccount>()
|
||||
const form = reactive({ username: '', displayName: '', role: 'viewer' as AdministratorAccount['role'], enabled: true, password: '', confirmation: '' })
|
||||
const reset = reactive({ password: '', confirmation: '' })
|
||||
@@ -16,7 +18,7 @@ const passwordValid = (password: string, confirmation: string) => [...password].
|
||||
const canSave = computed(() => !!form.displayName.trim() && (!!editing.value || (/^[a-zA-Z0-9][a-zA-Z0-9._-]{2,79}$/.test(form.username) && passwordValid(form.password, form.confirmation))))
|
||||
async function load(quiet = false) { if (!quiet) loading.value = true; try { items.value = await allPages(api.administrators); error.value = '' } catch (e) { error.value = errorMessage(e) } finally { loading.value = false } }
|
||||
let timer: ReturnType<typeof setInterval>
|
||||
onMounted(() => { void load(); timer = setInterval(() => { if (!document.hidden && !busy.value && !visible.value && !resetTarget.value) void load(true) }, 5000) })
|
||||
onMounted(() => { void load(); timer = setInterval(() => { if (!document.hidden && !busy.value && !visible.value && !resetTarget.value && !sessionTarget.value) void load(true) }, 5000) })
|
||||
onUnmounted(() => clearInterval(timer))
|
||||
function edit(item?: AdministratorAccount) { editing.value = item; formError.value = ''; Object.assign(form, { username: item?.username || '', displayName: item?.displayName || '', role: item?.role || 'viewer', enabled: item?.enabled ?? true, password: '', confirmation: '' }); visible.value = true }
|
||||
watch(visible, open => { if (!open) { form.password = ''; form.confirmation = ''; formError.value = '' } })
|
||||
@@ -44,10 +46,11 @@ async function resetPassword() {
|
||||
<div class="account-heading"><div><div class="section-kicker">ADMINISTRATOR ACCOUNTS</div><h2>管理员账号</h2><p class="subtext">维护控制台账号、角色与启用状态</p></div><div class="actions"><el-button :icon="Refresh" :loading="loading" @click="load()">刷新</el-button><el-button type="primary" :icon="Plus" @click="edit()">新增管理员</el-button></div></div>
|
||||
<el-alert v-if="error" type="error" :title="error" :closable="false" show-icon style="margin:20px 0" />
|
||||
<div class="toolbar" style="margin-top:24px"><el-input v-model="keyword" placeholder="搜索账号 / 显示名称" aria-label="搜索管理员" clearable /></div>
|
||||
<el-table v-loading="loading" :data="filtered" empty-text="暂无符合条件的管理员"><el-table-column label="账号" min-width="150"><template #default="{ row }"><strong>{{ row.username }}</strong><el-tag v-if="row.id === auth.user?.id" size="small" type="info" style="margin-left:8px">本人</el-tag></template></el-table-column><el-table-column prop="displayName" label="显示名称" min-width="135" /><el-table-column label="角色" min-width="130"><template #default="{ row }">{{ roles[row.role as keyof typeof roles] }}</template></el-table-column><el-table-column label="状态" width="100"><template #default="{ row }"><el-tag :type="row.enabled ? 'success' : 'info'">{{ row.enabled ? '已启用' : '已停用' }}</el-tag></template></el-table-column><el-table-column label="操作" min-width="180"><template #default="{ row }"><el-button link type="primary" :disabled="busy" @click="edit(row)">编辑</el-button><el-button v-if="row.id !== auth.user?.id" link :disabled="busy" @click="resetTarget = row">重置密码</el-button></template></el-table-column></el-table>
|
||||
<el-table v-loading="loading" :data="filtered" empty-text="暂无符合条件的管理员"><el-table-column label="账号" min-width="150"><template #default="{ row }"><strong>{{ row.username }}</strong><el-tag v-if="row.id === auth.user?.id" size="small" type="info" style="margin-left:8px">本人</el-tag></template></el-table-column><el-table-column prop="displayName" label="显示名称" min-width="135" /><el-table-column label="角色" min-width="130"><template #default="{ row }">{{ roles[row.role as keyof typeof roles] }}</template></el-table-column><el-table-column label="状态" width="100"><template #default="{ row }"><el-tag :type="row.enabled ? 'success' : 'info'">{{ row.enabled ? '已启用' : '已停用' }}</el-tag></template></el-table-column><el-table-column label="操作" min-width="240"><template #default="{ row }"><el-button link type="primary" :disabled="busy" @click="edit(row)">编辑</el-button><el-button link type="primary" :disabled="busy" @click="sessionTarget = row">在线登录</el-button><el-button v-if="row.id !== auth.user?.id" link :disabled="busy" @click="resetTarget = row">重置密码</el-button></template></el-table-column></el-table>
|
||||
<p class="account-note">本人密码通过右上角钥匙按钮修改。不能停用自己或修改自己的角色;至少保留一个启用的超级管理员。停用账号会保留历史审计。</p>
|
||||
<el-dialog v-model="visible" :title="editing ? '编辑管理员' : '新增管理员'" width="520px" :close-on-click-modal="false" :close-on-press-escape="!busy" :show-close="!busy"><el-alert v-if="formError" type="error" :title="formError" :closable="false" show-icon /><el-form label-position="top" :disabled="busy"><el-form-item label="账号"><el-input v-model="form.username" :disabled="!!editing" maxlength="80" autocomplete="off" aria-label="管理员账号" placeholder="3~80 位字母、数字、点、下划线或短横线" /></el-form-item><el-form-item label="显示名称"><el-input v-model="form.displayName" maxlength="80" aria-label="管理员显示名称" /></el-form-item><el-form-item label="角色"><el-select v-model="form.role" :disabled="editing?.id === auth.user?.id" aria-label="管理员角色"><el-option v-for="(label, value) in roles" :key="value" :value="value" :label="label" /></el-select></el-form-item><el-form-item v-if="editing" label="启用"><el-switch v-model="form.enabled" :disabled="editing.id === auth.user?.id" aria-label="管理员启用状态" /></el-form-item><template v-else><el-form-item label="初始密码"><el-input v-model="form.password" type="password" show-password maxlength="72" autocomplete="new-password" aria-label="管理员初始密码" /></el-form-item><el-form-item label="确认初始密码"><el-input v-model="form.confirmation" type="password" show-password maxlength="72" autocomplete="new-password" aria-label="确认管理员初始密码" /></el-form-item><p class="subtext">密码至少 12 个字符,UTF-8 编码不超过 72 字节。</p></template></el-form><template #footer><el-button :disabled="busy" @click="visible = false">取消</el-button><el-button type="primary" :loading="busy" :disabled="!canSave" @click="save">保存管理员</el-button></template></el-dialog>
|
||||
<el-dialog :model-value="!!resetTarget" :title="`重置密码 · ${resetTarget?.username || ''}`" width="480px" :close-on-click-modal="false" :close-on-press-escape="!busy" :show-close="!busy" @close="resetTarget = undefined"><el-alert v-if="formError" type="error" :title="formError" :closable="false" /><el-form label-position="top" :disabled="busy"><el-form-item label="新密码"><el-input v-model="reset.password" type="password" show-password autocomplete="new-password" aria-label="重置后的新密码" maxlength="72" /></el-form-item><el-form-item label="确认新密码"><el-input v-model="reset.confirmation" type="password" show-password autocomplete="new-password" aria-label="确认重置后的新密码" maxlength="72" /></el-form-item><p class="subtext">至少 12 个字符,UTF-8 编码不超过 72 字节。保存后该账号所有登录失效。</p></el-form><template #footer><el-button :disabled="busy" @click="resetTarget = undefined">取消</el-button><el-button type="primary" :loading="busy" :disabled="!passwordValid(reset.password, reset.confirmation)" @click="resetPassword">重置密码</el-button></template></el-dialog>
|
||||
<AdministratorSessions :account="sessionTarget" @close="sessionTarget = undefined" />
|
||||
</template>
|
||||
<style scoped>
|
||||
.account-heading{display:flex;align-items:flex-start;justify-content:space-between;gap:18px;flex-wrap:wrap}.account-heading h2{margin-top:6px}.account-note{margin-top:22px;font-size:12px;line-height:1.8;color:var(--vdi-muted)}
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, ref, watch } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { api, errorMessage, type AdministratorAccount, type AdministratorSession } from '../api'
|
||||
import { useAction } from '../composables/useAction'
|
||||
const props = defineProps<{ account?: AdministratorAccount }>()
|
||||
const emit = defineEmits<{ close: [] }>()
|
||||
const { confirm } = useAction()
|
||||
const items = ref<AdministratorSession[]>([]), total = ref(0), page = ref(1), loading = ref(false), busy = ref(false), error = ref('')
|
||||
let generation = 0
|
||||
onBeforeUnmount(() => { generation++ })
|
||||
const time = (value: string | null) => value ? new Date(value).toLocaleString('zh-CN', { hour12: false }) : '升级前登录,时间未知'
|
||||
async function load() {
|
||||
const account = props.account, request = ++generation
|
||||
if (!account) return
|
||||
loading.value = true; error.value = ''; items.value = []
|
||||
try {
|
||||
const result = await api.administratorSessions(account.id, page.value)
|
||||
if (request !== generation) return
|
||||
total.value = result.total
|
||||
if (page.value > 1 && !result.items.length && result.total <= (page.value - 1) * 20) { page.value = Math.max(1, Math.ceil(result.total / 20)); await load(); return }
|
||||
items.value = result.items
|
||||
} catch (e) { if (request === generation) { error.value = errorMessage(e); total.value = 0 } }
|
||||
finally { if (request === generation) loading.value = false }
|
||||
}
|
||||
watch(() => props.account, account => { generation++; items.value = []; total.value = 0; page.value = 1; error.value = ''; if (account) void load() }, { immediate: true })
|
||||
async function revoke(session: AdministratorSession) {
|
||||
const account = props.account
|
||||
if (!account || busy.value || session.current) return
|
||||
busy.value = true
|
||||
try {
|
||||
if (!await confirm(`撤销登录 · ${account.username}`, `撤销来自 ${session.clientIp || '未知来源'} 的这次登录?该登录将无法继续请求管理接口,需要重新登录。`)) return
|
||||
await api.revokeAdministratorSession(account.id, session.key)
|
||||
ElMessage.success('已撤销指定登录'); await load()
|
||||
} catch (e) { error.value = errorMessage(e); items.value = []; total.value = 0 }
|
||||
finally { busy.value = false }
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<el-dialog :model-value="!!account" :title="`在线登录 · ${account?.username || ''}`" width="920px" :close-on-click-modal="false" :close-on-press-escape="!busy" :show-close="!busy" @close="emit('close')">
|
||||
<p class="session-note">显示尚未退出、撤销或到期的登录凭据,不代表浏览器此刻仍在使用。当前登录请通过侧栏退出;撤销其他登录需要确认。来源信息仅供排查。</p>
|
||||
<el-alert v-if="error" :title="error" type="error" :closable="false" show-icon />
|
||||
<div class="session-toolbar"><span>共 {{ total }} 次有效登录</span><el-button :disabled="busy" :loading="loading" @click="load">刷新登录列表</el-button></div>
|
||||
<el-table v-loading="loading" :data="items" empty-text="没有有效登录">
|
||||
<el-table-column label="来源地址" min-width="155"><template #default="{ row }"><span>{{ row.clientIp || '升级前登录,来源未知' }}</span><el-tag v-if="row.current" size="small" type="success" class="current-session">当前登录</el-tag></template></el-table-column>
|
||||
<el-table-column label="登录 / 到期时间" min-width="205"><template #default="{ row }"><div>{{ time(row.createdAt) }}</div><div class="secondary">到期 {{ time(row.expiresAt) }}</div></template></el-table-column>
|
||||
<el-table-column prop="userAgent" label="浏览器 / 客户端" min-width="220" show-overflow-tooltip><template #default="{ row }">{{ row.userAgent || '未知客户端' }}</template></el-table-column>
|
||||
<el-table-column label="操作" width="115" fixed="right"><template #default="{ row }"><el-button link type="danger" :disabled="row.current || busy || loading" @click="revoke(row)">撤销登录</el-button></template></el-table-column>
|
||||
</el-table>
|
||||
<el-pagination v-model:current-page="page" :disabled="busy || loading" :total="total" :page-size="20" layout="total, prev, pager, next" @current-change="load" />
|
||||
<template #footer><el-button :disabled="busy" @click="emit('close')">关闭</el-button></template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
<style scoped>
|
||||
.session-note{color:var(--vdi-muted);font-size:12px;line-height:1.8;margin-bottom:18px}.session-toolbar{display:flex;align-items:center;justify-content:space-between;gap:12px;margin:18px 0;font-size:12px;color:var(--vdi-muted)}.current-session{display:block;width:fit-content;margin-top:7px}.el-pagination{margin-top:20px;flex-wrap:wrap}.secondary{margin-top:5px;font-size:11px}
|
||||
</style>
|
||||
@@ -0,0 +1,70 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, onBeforeUnmount, ref } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { api, errorMessage, type Audit, type AuditQuery } from '../api'
|
||||
import { auditActionLabels } from '../api/audit-labels'
|
||||
import StatusTag from './StatusTag.vue'
|
||||
|
||||
const rows = ref<Audit[]>([]), total = ref(0), page = ref(1), busy = ref(false), exporting = ref(false), error = ref(''), loaded = ref(false)
|
||||
const keyword = ref(''), actor = ref(''), action = ref(''), result = ref(''), range = ref<[Date, Date] | null>(null)
|
||||
const applied = ref<AuditQuery>({})
|
||||
const shortcuts = [1, 7, 30, 90].map(days => ({ text: days === 1 ? '最近 24 小时' : `最近 ${days} 天`, value: () => { const end = new Date(); return [new Date(end.getTime() - days * 86400000), end] } }))
|
||||
const results: Record<string, string> = { success: '成功', submitted: '已提交', failed: '失败', timeout: '结果未确认', denied: '无权限' }
|
||||
const time = (value: string) => new Date(value).toLocaleString('zh-CN', { hour12: false })
|
||||
let generation = 0
|
||||
onBeforeUnmount(() => { generation++ })
|
||||
async function load(reset = false) {
|
||||
if (reset) {
|
||||
if (range.value && range.value[1] <= range.value[0]) { ElMessage.warning('结束时间必须晚于开始时间'); return }
|
||||
applied.value = { keyword: keyword.value, actor: actor.value, action: action.value, result: result.value, from: range.value?.[0].toISOString(), to: range.value?.[1].toISOString() || new Date().toISOString() }
|
||||
page.value = 1
|
||||
}
|
||||
const request = ++generation
|
||||
busy.value = true; error.value = ''; loaded.value = false; rows.value = []
|
||||
try {
|
||||
const response = await api.audits({ ...applied.value, page: page.value, pageSize: 20 })
|
||||
if (request !== generation) return
|
||||
rows.value = response.items; total.value = response.total; loaded.value = true
|
||||
} catch (e) { if (request === generation) { error.value = errorMessage(e); total.value = 0 } }
|
||||
finally { if (request === generation) busy.value = false }
|
||||
}
|
||||
function clear() { keyword.value = ''; actor.value = ''; action.value = ''; result.value = ''; range.value = null; void load(true) }
|
||||
async function download() {
|
||||
exporting.value = true
|
||||
try {
|
||||
const blob = await api.exportAudits(applied.value)
|
||||
const url = URL.createObjectURL(blob), link = document.createElement('a')
|
||||
link.href = url; link.download = `操作审计-${new Date().toISOString().slice(0, 10)}.csv`; link.click()
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000)
|
||||
ElMessage.success('已生成筛选结果的 CSV 文件')
|
||||
} catch (e) { ElMessage.error(errorMessage(e)) } finally { exporting.value = false }
|
||||
}
|
||||
onMounted(() => { void load(true) })
|
||||
</script>
|
||||
<template>
|
||||
<div class="audit-filters">
|
||||
<el-input v-model="keyword" aria-label="审计关键词" placeholder="对象 / 请求标识 / 动作代码" maxlength="200" clearable @keyup.enter="load(true)" />
|
||||
<el-input v-model="actor" aria-label="审计操作者" placeholder="操作者包含" maxlength="200" clearable @keyup.enter="load(true)" />
|
||||
<el-select v-model="action" aria-label="审计动作" placeholder="全部动作" filterable allow-create clearable><el-option v-for="(label, value) in auditActionLabels" :key="value" :value="value" :label="label" /></el-select>
|
||||
<el-select v-model="result" aria-label="审计结果" placeholder="全部结果" filterable allow-create clearable><el-option v-for="(label, value) in results" :key="value" :value="value" :label="label" /></el-select>
|
||||
<el-date-picker v-model="range" type="datetimerange" aria-label="审计时间范围" start-placeholder="开始时间" end-placeholder="结束时间" :shortcuts="shortcuts" format="YYYY-MM-DD HH:mm:ss" />
|
||||
<div class="audit-actions"><el-button type="primary" :loading="busy" @click="load(true)">查询审计</el-button><el-button :disabled="busy" @click="clear">重置</el-button><el-button :loading="exporting" :disabled="busy || !loaded || !total || total > 10000" @click="download">导出查询结果 CSV</el-button></div>
|
||||
</div>
|
||||
<p class="subtext audit-hint">不选时间可查询全部历史。导出按已查询条件,包含全部匹配页,单次最多 10000 条。CSV 时间为 UTC,动作与结果保留原始代码。</p>
|
||||
<p v-if="loaded && applied.to" class="subtext audit-hint">查询结果截至 {{ time(applied.to) }},更新条件后点击“查询审计”。</p>
|
||||
<el-alert v-if="loaded && total > 10000" title="匹配记录超过 10000 条,请缩小时间范围或增加筛选条件后导出。" type="warning" :closable="false" show-icon />
|
||||
<el-alert v-if="error" :title="error" type="error" :closable="false" show-icon />
|
||||
<el-table v-loading="busy" :data="rows" empty-text="没有匹配的审计记录">
|
||||
<el-table-column prop="actor" label="操作者" min-width="110" />
|
||||
<el-table-column label="操作" min-width="150"><template #default="{ row }">{{ auditActionLabels[row.action] || row.action }}<div class="mono secondary">{{ row.action }}</div></template></el-table-column>
|
||||
<el-table-column prop="target" label="对象" min-width="180" show-overflow-tooltip />
|
||||
<el-table-column label="结果" width="125"><template #default="{ row }"><StatusTag :value="row.result" /></template></el-table-column>
|
||||
<el-table-column label="时间" min-width="180"><template #default="{ row }">{{ time(row.createdAt) }}</template></el-table-column>
|
||||
<el-table-column prop="requestId" label="请求标识" min-width="200" show-overflow-tooltip />
|
||||
</el-table>
|
||||
<el-pagination v-model:current-page="page" :disabled="busy" :total="total" :page-size="20" layout="total, prev, pager, next" @current-change="load()" />
|
||||
</template>
|
||||
<style scoped>
|
||||
.audit-filters{display:flex;flex-wrap:wrap;gap:12px;margin:18px 0}.audit-filters>.el-input{width:220px}.audit-filters>.el-select{width:180px}.audit-filters :deep(.el-date-editor){width:390px;flex-grow:0;max-width:100%;box-sizing:border-box}.audit-actions{display:flex;gap:10px;flex-wrap:wrap}.audit-actions .el-button{margin:0}.audit-hint{line-height:1.7;margin:10px 0}.el-alert{margin:12px 0}.el-pagination{margin-top:20px;flex-wrap:wrap}.mono{font-size:11px;margin-top:4px;overflow-wrap:anywhere}
|
||||
@media(max-width:600px){.audit-filters>.el-input,.audit-filters>.el-select{width:100%}.audit-filters :deep(.el-date-editor){width:100%;min-width:0}.audit-actions{width:100%}.audit-actions .el-button:last-child{width:100%}}
|
||||
</style>
|
||||
@@ -0,0 +1,87 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, watch, onBeforeUnmount } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { api, errorMessage, type MFAStatus, type MFASetup } from '../api'
|
||||
import { useAction } from '../composables/useAction'
|
||||
const props = defineProps<{ modelValue: boolean }>()
|
||||
const emit = defineEmits<{ 'update:modelValue': [value: boolean] }>()
|
||||
const { confirm } = useAction()
|
||||
const status = ref<MFAStatus>(), setup = ref<MFASetup>(), recovery = ref<string[]>([]), password = ref(''), code = ref(''), error = ref(''), loading = ref(false), busy = ref(false), action = ref<'disable' | 'rotate'>()
|
||||
let generation = 0
|
||||
onBeforeUnmount(() => { generation++ })
|
||||
watch(() => props.modelValue, open => {
|
||||
generation++; status.value = undefined; setup.value = undefined; recovery.value = []; password.value = ''; code.value = ''; error.value = ''; action.value = undefined
|
||||
if (open) void load()
|
||||
})
|
||||
async function load() {
|
||||
const request = ++generation; loading.value = true; error.value = ''
|
||||
try { const result = await api.mfaStatus(); if (request === generation) status.value = result }
|
||||
catch (e) { if (request === generation) error.value = errorMessage(e) }
|
||||
finally { if (request === generation) loading.value = false }
|
||||
}
|
||||
async function begin() {
|
||||
if (busy.value || !password.value) return
|
||||
busy.value = true; error.value = ''
|
||||
try { setup.value = await api.beginMFA(password.value); password.value = ''; code.value = '' }
|
||||
catch (e) { error.value = errorMessage(e) } finally { busy.value = false }
|
||||
}
|
||||
async function enable() {
|
||||
if (busy.value || !/^\d{6}$/.test(code.value)) return
|
||||
busy.value = true; error.value = ''
|
||||
try { recovery.value = (await api.confirmMFA(code.value)).recoveryCodes; setup.value = undefined; code.value = ''; await load(); ElMessage.success('双重验证已开启,其他登录已失效') }
|
||||
catch (e) { error.value = errorMessage(e) } finally { busy.value = false }
|
||||
}
|
||||
async function change() {
|
||||
if (busy.value || !action.value || !password.value || !code.value.trim()) return
|
||||
busy.value = true; error.value = ''
|
||||
try {
|
||||
const disable = action.value === 'disable'
|
||||
if (!await confirm(disable ? '关闭双重验证' : '重新生成恢复码', disable ? '关闭后登录只需密码,其他登录将失效。确认关闭?' : '现有恢复码将全部作废,其他登录将失效。确认重新生成?')) return
|
||||
if (disable) { await api.disableMFA(password.value, code.value.trim()); ElMessage.success('已关闭双重验证') }
|
||||
else { recovery.value = (await api.rotateMFARecovery(password.value, code.value.trim())).recoveryCodes; ElMessage.success('已更新恢复码,旧恢复码全部作废') }
|
||||
action.value = undefined; password.value = ''; code.value = ''; await load()
|
||||
} catch (e) { error.value = errorMessage(e) } finally { busy.value = false }
|
||||
}
|
||||
function choose(value: 'disable' | 'rotate') { action.value = value; password.value = ''; code.value = ''; error.value = '' }
|
||||
function download() {
|
||||
const blob = new Blob([`VDI Cloud 一次性恢复码\n每条只能使用一次,请离线妥善保存。\n\n${recovery.value.join('\n')}\n`], { type: 'text/plain;charset=utf-8' }), url = URL.createObjectURL(blob), link = document.createElement('a')
|
||||
link.href = url; link.download = 'vdi-cloud-recovery-codes.txt'; link.click(); setTimeout(() => URL.revokeObjectURL(url), 1000)
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<el-dialog :model-value="modelValue" title="本人双重验证" width="560px" :close-on-click-modal="false" :close-on-press-escape="!busy && !recovery.length" :show-close="!busy && !recovery.length" @update:model-value="emit('update:modelValue', $event)">
|
||||
<p class="mfa-note">使用身份验证器生成的 6 位动态码,或一次性恢复码完成登录。仅修改本人账号;开启、关闭或更新恢复码会撤销其他登录。</p>
|
||||
<el-alert v-if="error" type="error" :title="error" :closable="false" show-icon />
|
||||
<div v-loading="loading" class="mfa-body">
|
||||
<template v-if="recovery.length">
|
||||
<el-alert type="warning" title="恢复码仅显示这一次,请先保存" :closable="false" show-icon />
|
||||
<p class="mfa-note">身份验证器不可用时,可用密码和一条恢复码登录。每条只能使用一次;关闭此窗口后无法再次查看。</p>
|
||||
<div class="recovery-codes"><code v-for="value in recovery" :key="value">{{ value }}</code></div>
|
||||
<el-button @click="download">下载恢复码</el-button>
|
||||
</template>
|
||||
<template v-else-if="setup">
|
||||
<p class="mfa-note">在身份验证器中手动添加账号:名称为 VDI Cloud,密钥如下,使用基于时间的 6 位验证码(每 30 秒更新)。</p>
|
||||
<div class="mfa-secret" aria-label="身份验证器密钥">{{ setup.secret }}</div>
|
||||
<p class="mfa-note">绑定有效至 {{ new Date(setup.expiresAt).toLocaleTimeString('zh-CN') }}。输入动态码确认后才会启用。</p>
|
||||
<el-form label-position="top" :disabled="busy" @submit.prevent="enable"><el-form-item label="身份验证器动态码"><el-input v-model="code" aria-label="绑定动态码" autocomplete="one-time-code" inputmode="numeric" maxlength="6" /></el-form-item></el-form>
|
||||
<el-button type="primary" :disabled="!/^\d{6}$/.test(code)" :loading="busy" @click="enable">验证并开启</el-button>
|
||||
</template>
|
||||
<template v-else-if="status">
|
||||
<div class="mfa-state"><strong>当前状态</strong><el-tag :type="status.enabled ? 'success' : 'info'">{{ status.enabled ? '已开启' : '未开启' }}</el-tag></div>
|
||||
<p v-if="status.enabled" class="mfa-note">剩余 {{ status.recoveryRemaining }} 条恢复码。同一动态码只能成功使用一次,刚使用后请等待验证器刷新。</p>
|
||||
<div v-if="status.enabled && !action" class="mfa-actions"><el-button @click="choose('rotate')">重新生成恢复码</el-button><el-button type="danger" plain @click="choose('disable')">关闭双重验证</el-button></div>
|
||||
<el-form v-if="!status.enabled || action" label-position="top" :disabled="busy" @submit.prevent="status.enabled ? change() : begin()">
|
||||
<el-form-item label="当前密码"><el-input v-model="password" type="password" show-password autocomplete="current-password" aria-label="双重验证当前密码" maxlength="200" /></el-form-item>
|
||||
<el-form-item v-if="action" label="动态码或恢复码"><el-input v-model="code" autocomplete="one-time-code" aria-label="双重验证确认码" maxlength="80" /></el-form-item>
|
||||
<el-button v-if="!status.enabled" type="primary" :loading="busy" :disabled="!password" @click="begin">开始绑定身份验证器</el-button>
|
||||
<template v-else><el-button type="primary" :loading="busy" :disabled="!password || !code.trim()" @click="change">{{ action === 'disable' ? '确认关闭双重验证' : '生成新恢复码' }}</el-button><el-button :disabled="busy" @click="action = undefined; password = ''; code = ''">返回</el-button></template>
|
||||
</el-form>
|
||||
</template>
|
||||
<el-button v-else-if="error" @click="load">重新加载验证设置</el-button>
|
||||
</div>
|
||||
<template #footer><el-button :disabled="busy" @click="emit('update:modelValue', false)">{{ recovery.length ? '已保存,关闭' : '关闭' }}</el-button></template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
<style scoped>
|
||||
.mfa-note{font-size:12px;color:var(--vdi-muted);line-height:1.8;margin:14px 0}.mfa-body{min-height:80px;margin-top:18px}.mfa-state{display:flex;justify-content:space-between;align-items:center;margin:18px 0}.mfa-secret{padding:16px;background:var(--vdi-panel-2);border:1px solid var(--vdi-border);border-radius:10px;word-break:break-all;letter-spacing:2px;font-family:monospace;user-select:all}.mfa-actions{display:flex;flex-wrap:wrap;gap:10px;margin:20px 0}.mfa-actions .el-button{margin:0}.recovery-codes{display:grid;gap:10px;margin:18px 0;font-size:12px;overflow-wrap:anywhere}.recovery-codes code{padding:8px 10px;background:var(--vdi-panel-2);border-radius:6px;user-select:all}.mfa-body .el-form{margin-top:20px}
|
||||
</style>
|
||||
@@ -0,0 +1,94 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, onBeforeUnmount, ref, watch } from 'vue'
|
||||
import { api, errorMessage, type Task, type TaskQuery } from '../api'
|
||||
import { auditActionLabels as labels } from '../api/audit-labels'
|
||||
import { usePlatform } from '../stores/platform'
|
||||
import { useAuth } from '../stores/auth'
|
||||
import { useAction } from '../composables/useAction'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import StatusTag from './StatusTag.vue'
|
||||
const data = usePlatform(), auth = useAuth(), { busy, run, confirm } = useAction()
|
||||
const confirmingGPU = ref(false)
|
||||
const rows = ref<Task[]>([]), total = ref(0), page = ref(1), loading = ref(false), loaded = ref(false), error = ref(''), exporting = ref(false), selected = ref<Task | null>(null)
|
||||
const keyword = ref(''), actor = ref(''), status = ref(''), action = ref(''), kind = ref(''), range = ref<[Date, Date] | null>(null), applied = ref<TaskQuery>({})
|
||||
const statuses: Record<string, string> = { queued: '排队中', running: '执行中', success: '成功', failed: '失败', timeout: '结果未确认' }
|
||||
const kinds: Record<string, string> = { desktop: '桌面电源', terminal: '终端命令', provision: '克隆发放', hardware: '规格调整', snapshot: '快照', 'batch-desktop': '批量电源子任务', 'gpu-prepare': '显卡桌面准备', resource: '资源同步' }
|
||||
const shortcuts = [1, 7, 30, 90].map(days => ({ text: days === 1 ? '最近 24 小时' : `最近 ${days} 天`, value: () => { const end = new Date(); return [new Date(end.getTime() - days * 86400000), end] } }))
|
||||
const time = (value: string) => new Date(value).toLocaleString('zh-CN', { hour12: false })
|
||||
let generation = 0
|
||||
onBeforeUnmount(() => { generation++ })
|
||||
async function load(reset = false, background = false) {
|
||||
if (reset) {
|
||||
if (range.value && range.value[1] <= range.value[0]) { ElMessage.warning('结束时间必须晚于开始时间'); return }
|
||||
applied.value = { keyword: keyword.value, actor: actor.value, status: status.value, action: action.value, kind: kind.value, from: range.value?.[0].toISOString(), to: range.value?.[1].toISOString() || new Date().toISOString() }
|
||||
page.value = 1
|
||||
}
|
||||
const request = ++generation
|
||||
if (!background) { loading.value = true; rows.value = []; loaded.value = false }
|
||||
error.value = ''
|
||||
try {
|
||||
const response = await api.taskHistory({ ...applied.value, page: page.value, pageSize: 20 })
|
||||
if (request !== generation) return
|
||||
rows.value = response.items; total.value = response.total; loaded.value = true
|
||||
const current = rows.value.find(task => task.id === selected.value?.id)
|
||||
if (current) selected.value = current
|
||||
} catch (e) { if (request === generation) { error.value = errorMessage(e); rows.value = []; total.value = 0; loaded.value = false } }
|
||||
finally { if (request === generation) loading.value = false }
|
||||
}
|
||||
watch(() => data.updatedAt, () => { if (!loading.value) void load(false, true) })
|
||||
function clear() { keyword.value = ''; actor.value = ''; status.value = ''; action.value = ''; kind.value = ''; range.value = null; void load(true) }
|
||||
async function reconcile(work: () => Promise<unknown>, message: string) { if (await run(work, message)) { selected.value = null; await load() } }
|
||||
async function reconcileGPU() {
|
||||
const task = selected.value
|
||||
if (!task || task.kind !== 'gpu-prepare' || task.status !== 'timeout' || !auth.canOperate || busy.value || confirmingGPU.value) return
|
||||
confirmingGPU.value = true
|
||||
try {
|
||||
if (!await confirm(`核对显卡准备结果 · ${task.targetName}`, '只查询原 PVE 任务及组内桌面的实际电源状态,不重发电源操作。核对完成会结束此未确认流程并释放预留;原任务标记为失败,需要重新准备时请另行操作。')) return
|
||||
await reconcile(() => api.reconcileGPUPrepare(task.id), '已核对原任务并结束未确认流程,未重发电源操作')
|
||||
} finally { confirmingGPU.value = false }
|
||||
}
|
||||
async function downloadDiagnostics(id: string) {
|
||||
try {
|
||||
const diagnostic = await api.taskDiagnostics(id), url = URL.createObjectURL(new Blob([JSON.stringify(diagnostic, null, 2)], { type: 'application/json' }))
|
||||
const link = document.createElement('a'); link.href = url; link.download = `${id}-diagnostics.json`; link.click(); setTimeout(() => URL.revokeObjectURL(url), 1000)
|
||||
} catch (e) { ElMessage.error(errorMessage(e)) }
|
||||
}
|
||||
async function download() {
|
||||
exporting.value = true
|
||||
try {
|
||||
const blob = await api.exportTasks(applied.value), url = URL.createObjectURL(blob), link = document.createElement('a')
|
||||
link.href = url; link.download = `执行任务-${new Date().toISOString().slice(0, 10)}.csv`; link.click(); setTimeout(() => URL.revokeObjectURL(url), 1000)
|
||||
ElMessage.success('已生成筛选任务的 CSV 文件')
|
||||
} catch (e) { ElMessage.error(errorMessage(e)) } finally { exporting.value = false }
|
||||
}
|
||||
onMounted(() => { void load(true) })
|
||||
</script>
|
||||
<template>
|
||||
<div class="task-filters">
|
||||
<el-input v-model="keyword" aria-label="搜索任务" placeholder="目标 / 任务标识 / 执行结果" maxlength="200" clearable @keyup.enter="load(true)" />
|
||||
<el-input v-model="actor" aria-label="任务操作者" placeholder="操作者包含" maxlength="200" clearable @keyup.enter="load(true)" />
|
||||
<el-select v-model="status" aria-label="任务状态筛选" placeholder="全部任务状态" clearable><el-option v-for="(label, value) in statuses" :key="value" :label="label" :value="value" /></el-select>
|
||||
<el-select v-model="action" aria-label="任务动作" placeholder="全部动作" filterable allow-create clearable><el-option v-for="(label, value) in labels" :key="value" :label="label" :value="value" /></el-select>
|
||||
<el-select v-model="kind" aria-label="任务类型" placeholder="全部类型" filterable allow-create clearable><el-option v-for="(label, value) in kinds" :key="value" :label="label" :value="value" /></el-select>
|
||||
<el-date-picker v-model="range" type="datetimerange" aria-label="任务时间范围" start-placeholder="开始时间" end-placeholder="结束时间" :shortcuts="shortcuts" format="YYYY-MM-DD HH:mm:ss" />
|
||||
<div class="task-actions"><el-button type="primary" :loading="loading" @click="load(true)">查询任务</el-button><el-button :disabled="loading" @click="clear">重置</el-button><el-button :loading="exporting" :disabled="loading || !loaded || !total || total > 10000" @click="download">导出任务 CSV</el-button></div>
|
||||
</div>
|
||||
<p class="subtext task-hint">不选时间可查全部历史;按提交时间筛选。任务状态随平台刷新,新增任务请重新查询。导出包含全部匹配页,单次最多 10000 条,时间为 UTC。</p>
|
||||
<p v-if="loaded && applied.to" class="subtext task-hint">查询范围截至 {{ time(applied.to) }},修改条件后点击“查询任务”。</p>
|
||||
<el-alert v-if="error" type="error" :title="error" :closable="false" show-icon />
|
||||
<el-alert v-if="loaded && total > 10000" type="warning" title="匹配任务超过 10000 条,请缩小时间范围或增加筛选条件后导出。" :closable="false" show-icon />
|
||||
<el-table v-loading="loading" :data="rows" empty-text="没有匹配的执行任务">
|
||||
<el-table-column label="操作目标 / 任务" min-width="220"><template #default="{ row }"><el-button link type="primary" @click="selected = row">{{ row.targetName }}</el-button><div class="mono secondary">{{ row.id }}</div></template></el-table-column>
|
||||
<el-table-column label="操作 / 类型" min-width="150"><template #default="{ row }">{{ labels[row.action] || row.action }}<div class="secondary">{{ kinds[row.kind] || row.kind }}</div></template></el-table-column>
|
||||
<el-table-column label="状态" width="125"><template #default="{ row }"><StatusTag :value="row.status === 'running' ? '执行中' : row.status" /></template></el-table-column>
|
||||
<el-table-column prop="actor" label="操作者" width="120" />
|
||||
<el-table-column label="提交 / 更新时间" min-width="185"><template #default="{ row }">{{ time(row.createdAt) }}<div class="secondary">{{ time(row.updatedAt) }}</div></template></el-table-column>
|
||||
<el-table-column prop="message" label="执行结果" min-width="240" show-overflow-tooltip />
|
||||
</el-table>
|
||||
<el-pagination v-model:current-page="page" :disabled="loading" :total="total" :page-size="20" layout="total, prev, pager, next" @current-change="load()" />
|
||||
<el-drawer :model-value="!!selected" title="任务详情" size="580px" @close="selected = null"><el-descriptions v-if="selected" :column="1" border><el-descriptions-item label="任务 ID"><span class="mono">{{ selected.id }}</span></el-descriptions-item><el-descriptions-item label="目标">{{ selected.targetName }}</el-descriptions-item><el-descriptions-item label="操作">{{ labels[selected.action] || selected.action }}</el-descriptions-item><el-descriptions-item label="状态"><StatusTag :value="selected.status === 'running' ? '执行中' : selected.status" /></el-descriptions-item><el-descriptions-item label="结果">{{ selected.message }}</el-descriptions-item><el-descriptions-item label="操作者">{{ selected.actor }}</el-descriptions-item><el-descriptions-item label="PVE 任务标识"><span class="mono">{{ selected.providerRef || '无' }}</span></el-descriptions-item><el-descriptions-item label="更新时间">{{ new Date(selected.updatedAt).toLocaleString('zh-CN') }}</el-descriptions-item></el-descriptions><el-button v-if="selected && auth.canOperate && selected.action === 'collect-logs' && selected.status === 'success'" style="margin-top:20px" @click="downloadDiagnostics(selected.id)">下载诊断日志</el-button><el-button v-if="selected?.kind === 'provision' && selected.status === 'timeout' && selected.providerRef && auth.canAdmin" :loading="busy" style="margin-top:20px" @click="reconcile(() => api.reconcileProvision(selected!.id), '已提交核对,只查询原 PVE 任务')">核对克隆结果</el-button><el-button v-if="selected?.kind === 'hardware' && selected.status === 'timeout' && auth.canAdmin" :loading="busy" style="margin-top:20px" @click="reconcile(() => api.reconcileHardware(selected!.id), '已核对实际规格,未重发修改')">核对规格结果</el-button><el-button v-if="selected?.kind === 'snapshot' && selected.status === 'timeout' && auth.canAdmin" :loading="busy" style="margin-top:20px" @click="reconcile(() => api.reconcileSnapshot(selected!.id), '已核对原快照任务,未重发修改')">核对快照结果</el-button><el-button v-if="selected?.kind === 'batch-desktop' && selected.status === 'timeout' && auth.canOperate" :loading="busy" style="margin-top:20px" @click="reconcile(() => api.reconcileBatchPower(selected!.id), '已核对原电源任务,未重发操作')">核对电源结果</el-button><el-button v-if="selected?.kind === 'gpu-prepare' && selected.status === 'timeout' && auth.canOperate" :loading="busy" :disabled="confirmingGPU" style="margin-top:20px" @click="reconcileGPU">核对显卡准备结果</el-button><p v-if="selected && auth.canOperate && ['terminal', 'desktop', 'gpu-prepare', 'batch-desktop', 'hardware', 'snapshot', 'provision'].includes(selected.kind)" style="margin-top:20px"><router-link :to="{ path: '/diagnostics', query: { targetType: selected.kind === 'terminal' ? 'terminal' : 'desktop', targetId: selected.targetId } }">查看操作对象关联诊断 →</router-link></p><p class="subtext" style="margin-top:22px">结果未确认时先核对实际设备状态,再决定是否重新提交。系统不会自动重放操作。</p></el-drawer>
|
||||
</template>
|
||||
<style scoped>
|
||||
.task-filters{display:flex;flex-wrap:wrap;gap:12px;margin:18px 0}.task-filters>.el-input{width:220px}.task-filters>.el-select{width:180px}.task-filters :deep(.el-date-editor){width:390px;flex-grow:0;max-width:100%;box-sizing:border-box}.task-actions{display:flex;gap:10px;flex-wrap:wrap}.task-actions .el-button{margin:0}.task-hint{line-height:1.7;margin:10px 0}.el-alert{margin:12px 0}.el-pagination{margin-top:20px;flex-wrap:wrap}.mono{font-size:11px;overflow-wrap:anywhere;margin-top:4px}
|
||||
@media(max-width:600px){.task-filters>.el-input,.task-filters>.el-select{width:100%}.task-filters :deep(.el-date-editor){width:100%;min-width:0}.task-actions{width:100%}.task-actions .el-button:last-child{width:100%}}
|
||||
</style>
|
||||
@@ -1,13 +1,24 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { Monitor, Menu, Cpu, User, List, Setting, DataAnalysis, Connection, ArrowRight, SwitchButton, Close, Refresh, Files, Collection, Key } from '@element-plus/icons-vue'
|
||||
import { Monitor, Menu, Cpu, User, List, Setting, DataAnalysis, Connection, ArrowRight, SwitchButton, Close, Refresh, Files, Collection, Key, Lock } from '@element-plus/icons-vue'
|
||||
import { useAuth } from '../stores/auth'
|
||||
import { usePlatform } from '../stores/platform'
|
||||
import { useEdition, type Edition } from '../stores/edition'
|
||||
import '../common/common.css'
|
||||
import ThemeToggle from '../components/ThemeToggle.vue'
|
||||
import ChangePasswordDialog from '../components/ChangePasswordDialog.vue'
|
||||
import MFADialog from '../components/MFADialog.vue'
|
||||
import brandMark from '../assets/brand-mark.svg'
|
||||
const auth = useAuth(), data = usePlatform(), route = useRoute(), router = useRouter()
|
||||
const edition = useEdition()
|
||||
const commonItems = [
|
||||
{ path: '/workbench', title: '工作台', icon: DataAnalysis, group: 'work' },
|
||||
{ path: '/people', title: '员工与桌面', icon: User, group: 'work' },
|
||||
{ path: '/devices', title: '终端设备', icon: Monitor, group: 'work' },
|
||||
{ path: '/help', title: '问题处理', icon: Connection, group: 'work' },
|
||||
{ path: '/records', title: '操作记录', icon: List, group: 'work' },
|
||||
]
|
||||
const items = [
|
||||
{ path: '/overview', title: '云桌面总览', icon: DataAnalysis, group: 'work' },
|
||||
{ path: '/desktops', title: '桌面管理', icon: Monitor, group: 'work' },
|
||||
@@ -21,14 +32,18 @@ const items = [
|
||||
{ path: '/pools', title: '桌面池', icon: Collection, group: 'manage' },
|
||||
{ path: '/users', title: '用户与授权', icon: User, group: 'manage' },
|
||||
{ path: '/tasks', title: '任务与审计', icon: List, group: 'manage' },
|
||||
{ path: '/diagnostics', title: '日志与诊断', icon: Files, group: 'manage' },
|
||||
{ path: '/settings', title: '系统设置', icon: Setting, group: 'manage' },
|
||||
]
|
||||
const navigation = computed(() => edition.mode === 'common' ? commonItems : items)
|
||||
const groups = computed(() => edition.mode === 'common' ? [{ id: 'work', label: '日常管理' }] : [{ id: 'work', label: '云桌面工作台' }, { id: 'manage', label: '资源与管理' }])
|
||||
async function changeEdition(value: Edition) { edition.select(value); await router.push(edition.home) }
|
||||
const roles: Record<string, string> = { super_admin: '超级管理员', operator: '运维人员', viewer: '只读人员' }
|
||||
const pending = computed(() => data.tasks.filter(t => t.status === 'queued' || t.status === 'running').length)
|
||||
const avatar = computed(() => (auth.user?.displayName || auth.user?.username || '管').slice(0, 1))
|
||||
const mockMode = import.meta.env.VITE_API_MODE === 'mock'
|
||||
const navOpen = ref(false)
|
||||
const passwordVisible = ref(false)
|
||||
const passwordVisible = ref(false), mfaVisible = ref(false)
|
||||
watch(() => route.path, () => { navOpen.value = false })
|
||||
let timer: ReturnType<typeof setInterval>
|
||||
onMounted(() => { void data.refresh(); timer = setInterval(() => { if (!document.hidden) void data.refresh() }, 5000) })
|
||||
@@ -39,20 +54,24 @@ async function logout() { try { await auth.logout() } catch { /* Local session i
|
||||
<div class="console-shell">
|
||||
<button v-if="navOpen" class="nav-scrim" aria-label="关闭导航遮罩" @click="navOpen = false" />
|
||||
<aside id="console-navigation" class="sidebar" :class="{ 'is-open': navOpen }">
|
||||
<div class="brand-row"><router-link to="/overview" class="brand"><img :src="brandMark" alt="" /><span>百工万象<small>VDI CLOUD</small></span></router-link><el-button class="mobile-close" text aria-label="关闭导航" @click="navOpen = false"><el-icon><Close /></el-icon></el-button></div>
|
||||
<div class="brand-row"><router-link :to="edition.home" class="brand"><img :src="brandMark" alt="" /><span>百工万象<small>VDI CLOUD</small></span></router-link><el-button class="mobile-close" text aria-label="关闭导航" @click="navOpen = false"><el-icon><Close /></el-icon></el-button></div>
|
||||
<div class="organization"><small>云桌面管理平台</small><strong>VDI Cloud · 管理控制台</strong><span><i :class="{ connected: data.settings?.pveConfigured }" />{{ data.settings?.pveConfigured ? 'Proxmox 已接入' : '等待接入计算资源' }}</span></div>
|
||||
<nav aria-label="主导航"><template v-for="group in [{ id: 'work', label: '云桌面工作台' }, { id: 'manage', label: '资源与管理' }]" :key="group.id"><div class="nav-label">{{ group.label }}</div><router-link v-for="item in items.filter(i => i.group === group.id && (i.path !== '/settings' || auth.canAdmin))" :key="item.path" :to="item.path" :class="{ active: route.path === item.path }" :aria-current="route.path === item.path ? 'page' : undefined"><el-icon :size="18"><component :is="item.icon" /></el-icon><span>{{ item.title }}</span><span v-if="item.path === '/tasks' && pending" class="nav-count">{{ pending }}</span></router-link></template></nav>
|
||||
<div class="edition-switch" role="group" aria-label="控制台版本"><button :class="{ selected: edition.mode === 'common' }" :aria-pressed="edition.mode === 'common'" @click="changeEdition('common')">通用版</button><button :class="{ selected: edition.mode === 'advanced' }" :aria-pressed="edition.mode === 'advanced'" @click="changeEdition('advanced')">高级版</button></div>
|
||||
<nav aria-label="主导航"><template v-for="group in groups" :key="group.id"><div class="nav-label">{{ group.label }}</div><router-link v-for="item in navigation.filter(i => i.group === group.id && (i.path !== '/settings' || auth.canAdmin) && (i.path !== '/diagnostics' || auth.canOperate))" :key="item.path" :to="item.path" :class="{ active: route.path === item.path }" :aria-current="route.path === item.path ? 'page' : undefined"><el-icon :size="18"><component :is="item.icon" /></el-icon><span>{{ item.title }}</span><span v-if="item.path === '/tasks' && pending" class="nav-count">{{ pending }}</span></router-link></template></nav>
|
||||
<div class="sidebar-bottom"><div class="profile"><div class="avatar">{{ avatar }}</div><div class="profile-name"><strong>{{ auth.user?.displayName }}</strong><small>{{ roles[auth.user?.role || ''] }}</small></div><el-button text aria-label="退出登录" title="退出登录" @click="logout"><el-icon :size="18"><SwitchButton /></el-icon></el-button></div><div class="sidebar-footnote">云 · 管 · 端<span>VDI Cloud</span></div></div>
|
||||
</aside>
|
||||
<div class="workspace">
|
||||
<header class="topbar"><div class="topbar-left"><el-button class="mobile-menu" aria-label="打开导航" :aria-expanded="navOpen" aria-controls="console-navigation" @click="navOpen = !navOpen"><el-icon :size="20"><Menu /></el-icon></el-button><div class="breadcrumbs"><span>VDI CLOUD</span><el-icon :size="11"><ArrowRight /></el-icon><span>{{ route.meta.title }}</span></div></div><div class="topbar-right"><span v-if="mockMode || data.settings?.mode === 'demo'" class="environment is-demo"><i />{{ mockMode ? '模拟接口' : '演示环境' }}</span><span v-else-if="data.settings?.mode === 'production'" class="environment"><i />现场联调环境</span><el-button class="header-refresh" text aria-label="刷新平台数据" title="刷新平台数据" @click="data.refresh"><el-icon :size="18"><Refresh /></el-icon></el-button><el-button text aria-label="修改密码" title="修改本人密码" @click="passwordVisible = true"><el-icon :size="18"><Key /></el-icon></el-button><ThemeToggle /></div></header>
|
||||
<header class="topbar"><div class="topbar-left"><el-button class="mobile-menu" aria-label="打开导航" :aria-expanded="navOpen" aria-controls="console-navigation" @click="navOpen = !navOpen"><el-icon :size="20"><Menu /></el-icon></el-button><div class="breadcrumbs"><span>VDI CLOUD</span><el-icon :size="11"><ArrowRight /></el-icon><span>{{ route.meta.title }}</span></div></div><div class="topbar-right"><span v-if="mockMode || data.settings?.mode === 'demo'" class="environment is-demo"><i />{{ mockMode ? '模拟接口' : '演示环境' }}</span><span v-else-if="data.settings?.mode === 'production'" class="environment"><i />现场联调环境</span><el-button class="header-refresh" text aria-label="刷新平台数据" title="刷新平台数据" @click="data.refresh"><el-icon :size="18"><Refresh /></el-icon></el-button><el-button text aria-label="修改密码" title="修改本人密码" @click="passwordVisible = true"><el-icon :size="18"><Key /></el-icon></el-button><el-button text aria-label="双重验证" title="本人双重验证" @click="mfaVisible = true"><el-icon :size="18"><Lock /></el-icon></el-button><el-button v-if="auth.canAdmin && edition.mode === 'common'" text aria-label="系统设置" title="系统设置" @click="router.push('/settings')"><el-icon :size="18"><Setting /></el-icon></el-button><ThemeToggle /></div></header>
|
||||
<main id="main-content" class="page-container"><el-alert v-if="data.error" class="notice" type="error" :closable="false" show-icon title="数据刷新失败,当前信息可能已过期"><template #default>{{ data.error }} <el-button link type="primary" @click="data.refresh">重新加载</el-button></template></el-alert><div v-if="data.loading" class="panel"><el-skeleton :rows="8" animated /></div><router-view v-else /></main>
|
||||
<footer class="workspace-footer"><span><span class="refresh-dot" /><template v-if="route.path === '/gpus'">GPU 清单按需读取,请手动刷新</template><template v-else>{{ data.updatedAt ? `最近刷新 ${data.updatedAt}` : '等待加载' }}<span class="refresh-note"> · 每 5 秒更新</span></template></span><router-link to="/tasks">{{ pending ? `${pending} 个任务等待回执` : '查看任务与审计' }} <el-icon><ArrowRight /></el-icon></router-link></footer>
|
||||
<footer class="workspace-footer"><span><span class="refresh-dot" /><template v-if="route.path === '/gpus'">GPU 清单按需读取,请手动刷新</template><template v-else>{{ data.updatedAt ? `最近刷新 ${data.updatedAt}` : '等待加载' }}<span class="refresh-note"> · 每 5 秒更新</span></template></span><router-link :to="edition.mode === 'common' ? '/records' : '/tasks'">{{ pending ? `${pending} 个任务等待回执` : (edition.mode === 'common' ? '查看操作记录' : '查看任务与审计') }} <el-icon><ArrowRight /></el-icon></router-link></footer>
|
||||
</div>
|
||||
<ChangePasswordDialog v-model="passwordVisible" />
|
||||
<MFADialog v-model="mfaVisible" />
|
||||
</div>
|
||||
</template>
|
||||
<style scoped>
|
||||
.edition-switch{display:flex;gap:4px;background:var(--vdi-panel-2);padding:4px;border:1px solid var(--vdi-border);border-radius:10px}.edition-switch button{flex:1;min-height:34px;border:0;border-radius:7px;color:var(--vdi-muted);background:transparent;cursor:pointer;font:inherit;font-size:12px}.edition-switch button.selected{color:var(--vdi-accent);background:var(--vdi-accent-soft);font-weight:650}
|
||||
|
||||
.console-shell{display:grid;grid-template-columns:248px minmax(0,1fr);min-height:100vh}.sidebar{background:var(--vdi-panel);border-right:1px solid var(--vdi-border);display:flex;flex-direction:column;padding:28px 18px 18px;position:sticky;top:0;height:100vh;overflow-y:auto;z-index:20}.brand-row{display:flex;align-items:center;justify-content:space-between}.brand{display:flex;gap:10px;align-items:center;color:var(--vdi-text);padding:0 10px;font-weight:750;font-size:21px;letter-spacing:1px}.brand img{width:34px;height:34px;object-fit:contain}.brand small{display:block;color:var(--vdi-muted);font-size:9px;font-weight:500;letter-spacing:2.2px;margin-top:5px}.organization{background:var(--vdi-panel-2);border:1px solid var(--vdi-border);border-radius:16px;padding:15px 14px;margin:26px 0 20px}.organization small{color:var(--vdi-muted);display:block;margin-bottom:8px;font-size:11px}.organization strong{font-size:13px;display:block;font-weight:600}.organization>span{display:flex;align-items:center;gap:6px;color:var(--vdi-muted);font-size:10px;margin-top:12px}.organization i,.environment i{width:6px;height:6px;display:inline-block;background:var(--vdi-muted);border-radius:50%}.organization i.connected{background:var(--vdi-ok)}.nav-label{font-size:10px;letter-spacing:1.4px;color:var(--vdi-muted);margin:18px 14px 12px}nav a{display:flex;align-items:center;gap:12px;padding:13px 15px;color:var(--vdi-muted);border-radius:12px;margin-bottom:6px;font-size:14px;min-height:47px}nav a:hover{background:var(--vdi-panel-2);color:var(--vdi-text)}nav a.active{background:var(--vdi-accent-soft);color:var(--vdi-accent);font-weight:650}.nav-count{margin-left:auto;font-size:11px;background:var(--vdi-brand);color:white;min-width:19px;text-align:center;border-radius:5px;padding:2px}.sidebar-bottom{margin-top:auto;padding-top:32px}.profile{background:var(--vdi-accent-soft);border-radius:16px;padding:12px;display:flex;align-items:center;gap:10px}.avatar{width:36px;height:36px;border-radius:11px;flex-shrink:0;background:linear-gradient(145deg,#f5ca91,#c97235);display:grid;place-items:center;color:#fff;font-weight:650}.profile-name{min-width:0;flex:1}.profile strong{font-size:13px;display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.profile small{display:block;font-size:11px;color:var(--vdi-muted);margin-top:3px}.profile .el-button{padding:4px;color:var(--vdi-muted)}.sidebar-footnote{display:flex;justify-content:space-between;color:var(--vdi-muted);font-size:10px;margin:18px 4px 0}.workspace{min-width:0;display:flex;flex-direction:column}.topbar{min-height:82px;padding:20px 42px 0;display:flex;justify-content:space-between;align-items:center;gap:16px}.topbar-left,.topbar-right,.breadcrumbs{display:flex;align-items:center;gap:16px}.breadcrumbs{font-size:11px;color:var(--vdi-muted);letter-spacing:.5px;gap:12px}.topbar-right{gap:12px}.environment{display:flex;align-items:center;gap:7px;font-size:11px;color:var(--vdi-muted)}.environment i{background:var(--vdi-ok)}.environment.is-demo i{background:var(--vdi-warn)}.header-refresh{color:var(--vdi-muted)}.page-container{padding:16px 42px 32px;flex:1;min-width:0;width:100%;max-width:1920px;margin:0 auto}.workspace-footer{padding:16px 42px;display:flex;justify-content:space-between;gap:12px;flex-wrap:wrap;font-size:11px;color:var(--vdi-muted)}.workspace-footer a{display:flex;gap:5px;align-items:center}.refresh-dot{width:5px;height:5px;border-radius:50%;background:var(--vdi-ok);display:inline-block;margin-right:6px}.mobile-menu,.mobile-close{display:none}.nav-scrim{display:none}
|
||||
@media(max-width:1200px){.console-shell{grid-template-columns:222px minmax(0,1fr)}.sidebar{padding:25px 14px 16px}.brand{font-size:20px;padding:0 6px}.page-container{padding:18px 26px 26px}.topbar{padding:18px 26px 0}.workspace-footer{padding:16px 26px}.organization{padding:14px 12px}}
|
||||
@media(max-width:760px){.console-shell{grid-template-columns:minmax(0,1fr)}.sidebar{position:fixed;left:0;top:0;bottom:0;width:248px;transform:translateX(-100%);transition:transform .2s ease}.sidebar.is-open{transform:translateX(0)}.mobile-menu,.mobile-close{display:inline-flex}.mobile-menu{padding:8px;width:38px;height:38px;min-height:38px}.mobile-close{color:var(--vdi-muted);padding:5px}.nav-scrim{display:block;position:fixed;inset:0;background:rgb(0 0 0 / 50%);border:0;z-index:19}.page-container{padding:20px 18px}.topbar{padding:16px 18px 0;min-height:68px}.topbar-left,.topbar-right{gap:10px}.breadcrumbs{gap:7px;font-size:10px}.environment{font-size:10px}.header-refresh{display:none}.workspace-footer{padding:16px 18px}.organization{margin-top:25px}}
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
import { createRouter, createWebHistory } from 'vue-router'
|
||||
import { useAuth } from '../stores/auth'
|
||||
import { useEdition } from '../stores/edition'
|
||||
|
||||
export const router = createRouter({ history: createWebHistory(), routes: [
|
||||
{ path: '/login', component: () => import('../views/Login.vue'), meta: { public: true } },
|
||||
{ path: '/', component: () => import('../layouts/ConsoleLayout.vue'), children: [
|
||||
{ path: '', redirect: '/overview' },
|
||||
{ path: '', component: () => import('../views/CommonWorkbench.vue') },
|
||||
{ path: 'workbench', component: () => import('../views/CommonWorkbench.vue'), meta: { title: '工作台', edition: 'common' } },
|
||||
{ path: 'people', component: () => import('../views/CommonPeople.vue'), meta: { title: '员工与桌面', edition: 'common' } },
|
||||
{ path: 'devices', component: () => import('../views/CommonDevices.vue'), meta: { title: '终端设备', edition: 'common' } },
|
||||
{ path: 'help', component: () => import('../views/CommonHelp.vue'), meta: { title: '问题处理', edition: 'common' } },
|
||||
{ path: 'records', component: () => import('../views/CommonRecords.vue'), meta: { title: '操作记录', edition: 'common' } },
|
||||
{ path: 'overview', component: () => import('../views/Overview.vue'), meta: { title: '总览' } },
|
||||
{ path: 'resources', component: () => import('../views/Resources.vue'), meta: { title: '计算资源' } },
|
||||
{ path: 'gpus', component: () => import('../views/GPUs.vue'), meta: { title: 'GPU 资源' } },
|
||||
@@ -17,6 +23,7 @@ export const router = createRouter({ history: createWebHistory(), routes: [
|
||||
{ path: 'terminal-policies', component: () => import('../views/TerminalPolicies.vue'), meta: { title: '终端策略' } },
|
||||
{ path: 'users', component: () => import('../views/Users.vue'), meta: { title: '用户与授权' } },
|
||||
{ path: 'tasks', component: () => import('../views/Tasks.vue'), meta: { title: '任务与审计' } },
|
||||
{ path: 'diagnostics', component: () => import('../views/Diagnostics.vue'), meta: { title: '日志与诊断', operateOnly: true } },
|
||||
{ path: 'settings', component: () => import('../views/Settings.vue'), meta: { title: '系统设置', adminOnly: true } },
|
||||
{ path: 'forbidden', component: () => import('../views/Forbidden.vue'), meta: { title: '无访问权限' } },
|
||||
{ path: ':pathMatch(.*)*', component: () => import('../views/NotFound.vue'), meta: { title: '页面不存在' } },
|
||||
@@ -25,6 +32,11 @@ export const router = createRouter({ history: createWebHistory(), routes: [
|
||||
router.beforeEach(async to => {
|
||||
const auth = useAuth(); await auth.restore()
|
||||
if (!to.meta.public && !auth.user) return { path: '/login', query: { redirect: to.fullPath } }
|
||||
if (to.path === '/login' && auth.user) return '/overview'
|
||||
if (to.path === '/' && auth.user) return useEdition().home
|
||||
if (to.path === '/login' && auth.user) return useEdition().home
|
||||
if (to.meta.adminOnly && !auth.canAdmin) return '/forbidden'
|
||||
if (to.meta.operateOnly && !auth.canOperate) return '/forbidden'
|
||||
if (auth.user && !to.meta.public && !['/settings', '/forbidden'].includes(to.path) && to.matched.some(r => r.path === to.path && !r.path.includes(':'))) {
|
||||
useEdition().select(to.meta.edition === 'common' ? 'common' : 'advanced')
|
||||
}
|
||||
})
|
||||
@@ -12,8 +12,8 @@ export const useAuth = defineStore('auth', () => {
|
||||
const canOperate = computed(() => !!user.value && user.value.role !== 'viewer')
|
||||
const canAdmin = computed(() => user.value?.role === 'super_admin')
|
||||
function clear() { user.value = null; token.value = ''; initialized.value = true; sessionStorage.removeItem(tokenKey); setAccessToken('') }
|
||||
async function login(username: string, password: string) {
|
||||
const data = await api.login(username, password)
|
||||
async function login(username: string, password: string, code?: string) {
|
||||
const data = await api.login(username, password, code)
|
||||
token.value = data.accessToken; user.value = data.user; initialized.value = true
|
||||
setAccessToken(token.value); sessionStorage.setItem(tokenKey, token.value)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { useAuth } from './auth'
|
||||
|
||||
export type Edition = 'common' | 'advanced'
|
||||
export const useEdition = defineStore('edition', () => {
|
||||
const auth = useAuth(), mode = ref<Edition>('common')
|
||||
const key = () => `vdi.console-mode:${auth.user?.id || ''}`
|
||||
watch(() => auth.user?.id, id => {
|
||||
mode.value = 'common'
|
||||
if (id) { try { if (localStorage.getItem(key()) === 'advanced') mode.value = 'advanced' } catch { /* Storage can be unavailable. */ } }
|
||||
}, { immediate: true, flush: 'sync' })
|
||||
function select(value: Edition) {
|
||||
mode.value = value
|
||||
if (auth.user) { try { localStorage.setItem(key(), value) } catch { /* Navigation still works without persistence. */ } }
|
||||
}
|
||||
const home = computed(() => mode.value === 'common' ? '/workbench' : '/overview')
|
||||
return { mode, home, select }
|
||||
})
|
||||
@@ -1,10 +1,10 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref } from 'vue'
|
||||
import { api, allPages, errorMessage, type Desktop, type Terminal, type User, type Task, type Audit, type Resource, type Settings, type Overview } from '../api'
|
||||
import { api, allPages, recentAndActiveTasks, errorMessage, type Desktop, type Terminal, type User, type Task, type Resource, type Settings, type Overview } from '../api'
|
||||
|
||||
export const usePlatform = defineStore('platform', () => {
|
||||
const desktops = ref<Desktop[]>([]), terminals = ref<Terminal[]>([]), users = ref<User[]>([])
|
||||
const tasks = ref<Task[]>([]), audits = ref<Audit[]>([]), resources = ref<Resource[]>([])
|
||||
const tasks = ref<Task[]>([]), resources = ref<Resource[]>([])
|
||||
const settings = ref<Settings | null>(null), overview = ref<Overview | null>(null)
|
||||
const loading = ref(false), error = ref(''), updatedAt = ref('')
|
||||
let inFlight: Promise<void> | undefined
|
||||
@@ -15,15 +15,15 @@ export const usePlatform = defineStore('platform', () => {
|
||||
const startedGeneration = generation
|
||||
inFlight = (async () => {
|
||||
try {
|
||||
const [d, t, u, k, a, r, s, o] = await Promise.all([allPages(api.desktops), allPages(api.terminals), allPages(api.users), allPages(api.tasks), allPages(api.audits), api.resources(), api.settings(), api.overview()])
|
||||
const [d, t, u, k, r, s, o] = await Promise.all([allPages(api.desktops), allPages(api.terminals), allPages(api.users), recentAndActiveTasks(), api.resources(), api.settings(), api.overview()])
|
||||
if (startedGeneration !== generation) return
|
||||
desktops.value = d; terminals.value = t; users.value = u; tasks.value = k; audits.value = a; resources.value = r.items; settings.value = s; overview.value = o
|
||||
desktops.value = d; terminals.value = t; users.value = u; tasks.value = k; resources.value = r.items; settings.value = s; overview.value = o
|
||||
updatedAt.value = new Date().toLocaleTimeString('zh-CN'); error.value = ''
|
||||
} catch (e) { if (startedGeneration === generation) error.value = errorMessage(e) }
|
||||
finally { if (startedGeneration === generation) { loading.value = false; inFlight = undefined } }
|
||||
})()
|
||||
return inFlight
|
||||
}
|
||||
function clear() { generation++; inFlight = undefined; loading.value = false; desktops.value = []; terminals.value = []; users.value = []; tasks.value = []; audits.value = []; resources.value = []; settings.value = null; overview.value = null; error.value = ''; updatedAt.value = '' }
|
||||
return { desktops, terminals, users, tasks, audits, resources, settings, overview, loading, error, updatedAt, refresh, clear }
|
||||
function clear() { generation++; inFlight = undefined; loading.value = false; desktops.value = []; terminals.value = []; users.value = []; tasks.value = []; resources.value = []; settings.value = null; overview.value = null; error.value = ''; updatedAt.value = '' }
|
||||
return { desktops, terminals, users, tasks, resources, settings, overview, loading, error, updatedAt, refresh, clear }
|
||||
})
|
||||
@@ -0,0 +1,24 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive, ref } from 'vue'
|
||||
import { api } from '../api'
|
||||
import { useAuth } from '../stores/auth'
|
||||
import { usePlatform } from '../stores/platform'
|
||||
import { useAction } from '../composables/useAction'
|
||||
import StatusTag from '../components/StatusTag.vue'
|
||||
const auth = useAuth(), data = usePlatform(), { busy, run } = useAction()
|
||||
const search = ref(''), page = ref(1), creating = ref(false), secret = ref(''), activationSN = ref('')
|
||||
const form = reactive({ name: '', sn: '' })
|
||||
const filtered = computed(() => data.terminals.filter(t => `${t.name} ${t.sn}`.toLowerCase().includes(search.value.toLowerCase())))
|
||||
const rows = computed(() => filtered.value.slice((page.value - 1) * 10, page.value * 10))
|
||||
async function enroll() {
|
||||
if (!auth.canAdmin || !form.name.trim() || !form.sn.trim()) return
|
||||
if (await run(async () => { const result = await api.enroll({ name: form.name.trim(), sn: form.sn.trim(), group: '' }); secret.value = result.activationSecret; activationSN.value = form.sn.trim() }, '设备已登记,请在盒子上完成激活')) { creating.value = false; form.name = ''; form.sn = '' }
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<div class="page-heading"><div><h1>终端设备</h1><p class="subtext">查看盒子是否在线,以及当前使用人</p></div><el-button v-if="auth.canAdmin" type="primary" @click="creating = true">登记新设备</el-button></div>
|
||||
<section class="panel"><div class="toolbar"><el-input v-model="search" aria-label="查找设备" placeholder="设备名称或机身 SN" clearable @input="page = 1" /></div><el-table :data="rows" empty-text="暂无设备,请登记新设备"><el-table-column label="设备" min-width="180"><template #default="{ row }">{{ row.name }}<div class="secondary">{{ row.sn }}</div></template></el-table-column><el-table-column label="在线状态" min-width="105"><template #default="{ row }"><StatusTag :value="row.status" /></template></el-table-column><el-table-column label="使用人" min-width="135"><template #default="{ row }">{{ data.users.find(u => u.terminalId === row.id)?.displayName || '尚未关联' }}</template></el-table-column><el-table-column label="当前桌面" min-width="150"><template #default="{ row }">{{ data.desktops.find(d => d.id === row.sessionDesktopId)?.name || '无活动连接' }}</template></el-table-column><el-table-column label="操作" width="100"><template #default="{ row }"><router-link :to="{ path: '/help', query: { terminal: row.id } }">检查问题</router-link></template></el-table-column></el-table><el-pagination v-model:current-page="page" :total="filtered.length" :page-size="10" layout="prev, pager, next" /></section>
|
||||
<p class="subtext">登记后需要在设备上填写激活信息。设备关联、远程重启、收集日志和策略下发位于高级版。</p>
|
||||
<el-dialog v-model="creating" title="登记新设备" width="480px" :close-on-click-modal="false" :show-close="!busy" :close-on-press-escape="!busy"><el-form label-position="top" :disabled="busy" @submit.prevent="enroll"><el-form-item label="设备名称" required><el-input v-model="form.name" aria-label="新设备名称" maxlength="80" /></el-form-item><el-form-item label="机身 SN" required><el-input v-model="form.sn" aria-label="新设备 SN" maxlength="100" /></el-form-item></el-form><template #footer><el-button :disabled="busy" @click="creating = false">取消</el-button><el-button type="primary" :loading="busy" :disabled="!form.name.trim() || !form.sn.trim()" @click="enroll">登记并获取激活信息</el-button></template></el-dialog>
|
||||
<el-dialog :model-value="!!secret" title="请保存设备激活信息" width="500px" :close-on-click-modal="false" @close="secret = ''"><p>设备 SN:{{ activationSN }}</p><p class="subtext">激活密钥仅显示这一次,请由设备管理员填入盒子配置。</p><el-input :model-value="secret" readonly type="password" show-password aria-label="设备激活密钥" /><template #footer><el-button type="primary" @click="secret = ''">已保存,关闭</el-button></template></el-dialog>
|
||||
</template>
|
||||
@@ -0,0 +1,25 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { api, errorMessage, type AlertRecord } from '../api'
|
||||
import { usePlatform } from '../stores/platform'
|
||||
import { diagnoseTerminal } from '../common/diagnosis'
|
||||
const data = usePlatform(), route = useRoute(), selected = ref(''), alerts = ref<AlertRecord[]>([]), total = ref(0), loading = ref(false), error = ref('')
|
||||
watch(() => route.query.terminal, id => { selected.value = typeof id === 'string' ? id : '' }, { immediate: true })
|
||||
const terminal = computed(() => data.terminals.find(t => t.id === selected.value))
|
||||
const checks = computed(() => terminal.value ? diagnoseTerminal(terminal.value, data.users, data.desktops) : [])
|
||||
async function load() {
|
||||
if (loading.value) return
|
||||
loading.value = true; error.value = ''
|
||||
try { const result = await api.alerts(1, 'firing'); alerts.value = result.items; total.value = result.total }
|
||||
catch (e) { error.value = errorMessage(e); alerts.value = [] }
|
||||
finally { loading.value = false }
|
||||
}
|
||||
onMounted(load)
|
||||
watch(() => data.updatedAt, load)
|
||||
</script>
|
||||
<template>
|
||||
<div class="page-heading"><div><h1>问题处理</h1><p class="subtext">先找原因,再决定下一步;检查过程不会修改设备</p></div></div>
|
||||
<section class="panel simple-section"><h2>盒子为什么没有桌面?</h2><el-select v-model="selected" aria-label="选择要检查的设备" placeholder="选择设备" filterable clearable><el-option v-for="t in data.terminals" :key="t.id" :value="t.id" :label="`${t.name} / ${t.sn}`" /></el-select><p v-if="!selected" class="subtext">选择后检查在线状态、员工关联与桌面条件。</p><el-alert v-else-if="!terminal" title="该设备已不存在,请重新选择" type="warning" :closable="false" /><div v-for="(check, i) in checks" :key="i" class="simple-check"><el-tag :type="check.ok ? 'success' : 'warning'">{{ check.ok ? '已通过' : '需处理' }}</el-tag><div><strong>{{ check.title }}</strong><p>{{ check.detail }}</p></div></div><p v-if="terminal" class="subtext">检查依据为最近一次成功刷新;平台数据刷新失败时请先重新加载。全部通过仍不能替代实际连接验收。</p></section>
|
||||
<section class="panel simple-section"><div class="simple-row"><h2>当前告警</h2><el-button :loading="loading" @click="load">刷新告警</el-button></div><el-alert v-if="error" type="error" :closable="false" :title="error" /><el-empty v-else-if="!loading && !alerts.length" description="当前没有触发中的告警" :image-size="64" /><div v-for="alert in alerts" :key="alert.id" class="simple-check"><el-tag type="warning">需关注</el-tag><div><strong>{{ alert.targetName }} · {{ alert.ruleName }}</strong><p>{{ new Date(alert.openedAt).toLocaleString('zh-CN') }} 开始 · {{ alert.acknowledgedAt ? '已有人关注' : '尚未确认' }}</p></div></div><p class="subtext">{{ error ? '告警读取失败,不能判断是否正常。' : `当前 ${total} 条,展示前 20 条。` }}历史、阈值调整和确认操作请进入高级版的监控告警。</p></section>
|
||||
</template>
|
||||
@@ -0,0 +1,44 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive, ref } from 'vue'
|
||||
import { api, type User, type Desktop, type DesktopAction } from '../api'
|
||||
import { usePlatform } from '../stores/platform'
|
||||
import { useAuth } from '../stores/auth'
|
||||
import { useAction } from '../composables/useAction'
|
||||
import StatusTag from '../components/StatusTag.vue'
|
||||
const data = usePlatform(), auth = useAuth(), { busy, run, confirm } = useAction()
|
||||
const search = ref(''), page = ref(1), creating = ref(false), editing = ref(false), reviewing = ref(false), person = ref<User | null>(null)
|
||||
const form = reactive({ username: '', displayName: '' }), selected = ref<string[]>([]), action = ref<'grant' | 'revoke'>('grant')
|
||||
const filtered = computed(() => data.users.filter(u => `${u.displayName} ${u.username}`.toLowerCase().includes(search.value.toLowerCase())))
|
||||
const rows = computed(() => filtered.value.slice((page.value - 1) * 10, page.value * 10))
|
||||
const desktopName = (id: string) => data.desktops.find(d => d.id === id)?.name || '已失效的桌面'
|
||||
const choices = computed(() => data.desktops.filter(d => action.value === 'grant' ? !person.value?.desktopIds.includes(d.id) : person.value?.desktopIds.includes(d.id)))
|
||||
const desktopSearch = ref(''), desktopPage = ref(1)
|
||||
const desktops = computed(() => data.desktops.filter(d => d.name.toLowerCase().includes(desktopSearch.value.toLowerCase())))
|
||||
const desktopRows = computed(() => desktops.value.slice((desktopPage.value - 1) * 10, desktopPage.value * 10))
|
||||
const pending = (id: string) => data.tasks.some(t => t.targetId === id && ['queued', 'running', 'timeout'].includes(t.status))
|
||||
async function power(desktop: Desktop, operation: DesktopAction) {
|
||||
if (!auth.canOperate || pending(desktop.id) || busy.value || data.error) return
|
||||
const label = { start: '开机', shutdown: '正常关机', reboot: '重启桌面' }[operation]
|
||||
if (!await confirm(`${label} · ${desktop.name}`, operation === 'start' ? '将提交开机任务,连接服务仍需稍后就绪。' : '会中断该桌面上的使用,请先通知使用人保存文件。')) return
|
||||
if (pending(desktop.id) || data.error) return
|
||||
await run(() => api.desktopAction(desktop.id, operation), '操作已提交,请在操作记录中查看实际结果')
|
||||
}
|
||||
function open(user: User, operation: 'grant' | 'revoke') { person.value = { ...user, desktopIds: [...user.desktopIds] }; action.value = operation; selected.value = []; reviewing.value = false; editing.value = true }
|
||||
async function create() {
|
||||
if (!auth.canAdmin || !form.username.trim() || !form.displayName.trim()) return
|
||||
if (await run(() => api.createUser({ username: form.username.trim(), displayName: form.displayName.trim() }), '员工已添加,请继续分配桌面')) { creating.value = false; form.username = ''; form.displayName = '' }
|
||||
}
|
||||
async function save() {
|
||||
if (!auth.canAdmin || !person.value || !selected.value.length || !reviewing.value || busy.value) return
|
||||
const userId = person.value.id, desktopIds = [...selected.value], operation = action.value
|
||||
if (await run(() => api.batchBindings({ userIds: [userId], desktopIds, action: operation }), operation === 'grant' ? '桌面授权已分配' : '指定桌面授权已撤销')) editing.value = false
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<div class="page-heading"><div><h1>员工与桌面</h1><p class="subtext">给员工分配已有桌面,其他授权自动保留</p></div><el-button v-if="auth.canAdmin" type="primary" @click="creating = true">添加员工</el-button></div>
|
||||
<section class="panel"><div class="toolbar"><el-input v-model="search" aria-label="查找员工" placeholder="输入姓名或账号" clearable @input="page = 1" /></div><el-table :data="rows" empty-text="暂无员工,请先添加员工"><el-table-column label="员工" min-width="150"><template #default="{ row }">{{ row.displayName }}<div class="secondary">{{ row.username }} · {{ row.enabled ? '已启用' : '已停用' }}</div></template></el-table-column><el-table-column label="已分配桌面" min-width="210"><template #default="{ row }"><div v-for="id in row.desktopIds" :key="id">{{ desktopName(id) }} <StatusTag v-if="data.desktops.find(d => d.id === id)" :value="data.desktops.find(d => d.id === id)!.powerState" /></div><span v-if="!row.desktopIds.length" class="secondary">尚未分配</span></template></el-table-column><el-table-column label="使用设备" min-width="145"><template #default="{ row }">{{ data.terminals.find(t => t.id === row.terminalId)?.name || '尚未关联设备' }}</template></el-table-column><el-table-column v-if="auth.canAdmin" label="操作" min-width="180"><template #default="{ row }"><el-button link type="primary" @click="open(row, 'grant')">分配桌面</el-button><el-button link :disabled="!row.desktopIds.length" @click="open(row, 'revoke')">撤销授权</el-button></template></el-table-column></el-table><el-pagination v-model:current-page="page" :total="filtered.length" :page-size="10" layout="prev, pager, next" /></section>
|
||||
<section class="panel simple-section"><h2>桌面日常操作</h2><div class="toolbar"><el-input v-model="desktopSearch" aria-label="查找桌面" placeholder="桌面名称" clearable @input="desktopPage = 1" /></div><el-table :data="desktopRows" empty-text="暂无已有桌面,请由运维纳管"><el-table-column prop="name" label="桌面" min-width="150" /><el-table-column label="使用人" min-width="150"><template #default="{ row }">{{ data.users.filter(u => u.desktopIds.includes(row.id)).map(u => u.displayName).join('、') || '尚未分配' }}</template></el-table-column><el-table-column label="状态" min-width="180"><template #default="{ row }"><StatusTag :value="row.powerState" /><div class="secondary">{{ row.setupRequired ? '等待初始化' : row.serviceState === 'ready' ? '连接服务就绪' : '连接服务尚未确认就绪' }}</div><el-tag v-if="pending(row.id)" type="warning" size="small">任务未完成,请先核对</el-tag></template></el-table-column><el-table-column v-if="auth.canOperate" label="操作" min-width="200"><template #default="{ row }"><el-button v-if="row.powerState === 'stopped'" link type="primary" :disabled="busy || pending(row.id) || !!data.error" @click="power(row, 'start')">开机</el-button><template v-if="row.powerState === 'running'"><el-button link :disabled="busy || pending(row.id) || !!data.error" @click="power(row, 'shutdown')">正常关机</el-button><el-button link :disabled="busy || pending(row.id) || !!data.error" @click="power(row, 'reboot')">重启桌面</el-button></template></template></el-table-column></el-table><el-pagination v-model:current-page="desktopPage" :total="desktops.length" :page-size="10" layout="prev, pager, next" /></section>
|
||||
<p class="subtext">分配表示允许后续连接,不会新建桌面或自动开机。关联设备、批量导入、员工停用等管理操作可在高级版中完成。</p>
|
||||
<el-dialog v-model="creating" title="添加员工" width="460px" :close-on-click-modal="false" :show-close="!busy" :close-on-press-escape="!busy"><el-form label-position="top" :disabled="busy" @submit.prevent="create"><el-form-item label="员工姓名" required><el-input v-model="form.displayName" aria-label="员工姓名" maxlength="80" /></el-form-item><el-form-item label="员工账号" required><el-input v-model="form.username" aria-label="员工账号" maxlength="80" /></el-form-item><p class="subtext">此账号用于关联盒子与桌面授权,桌面系统密码单独管理。</p></el-form><template #footer><el-button :disabled="busy" @click="creating = false">取消</el-button><el-button type="primary" :loading="busy" :disabled="!form.displayName.trim() || !form.username.trim()" @click="create">添加员工</el-button></template></el-dialog>
|
||||
<el-dialog v-model="editing" :title="action === 'grant' ? '分配已有桌面' : '撤销指定授权'" width="560px" :close-on-click-modal="false" :show-close="!busy" :close-on-press-escape="!busy"><template v-if="person"><h3>{{ person.displayName }} · {{ person.username }}</h3><p v-if="!person.enabled" class="subtext">员工目前已停用,保存授权后仍需管理员启用才能连接。</p><template v-if="!reviewing"><p class="subtext">选择要{{ action === 'grant' ? '分配' : '撤销' }}的桌面:</p><el-checkbox-group v-model="selected" class="simple-checks"><el-checkbox v-for="d in choices" :key="d.id" :value="d.id">{{ d.name }} · {{ d.os }}</el-checkbox></el-checkbox-group><el-empty v-if="!choices.length" description="没有符合条件的桌面" :image-size="64" /></template><div v-else class="simple-plan"><h3>确认变更方案</h3><p>为 {{ person.displayName }} {{ action === 'grant' ? '追加分配' : '撤销以下' }} {{ selected.length }} 台桌面的使用权限:</p><ul><li v-for="id in selected" :key="id">{{ desktopName(id) }}</li></ul><p>其他桌面授权、员工状态和设备关联保持原值。已有串流不会被强制断开。</p></div></template><template #footer><el-button :disabled="busy" @click="reviewing ? reviewing = false : editing = false">{{ reviewing ? '返回修改' : '取消' }}</el-button><el-button v-if="!reviewing" type="primary" :disabled="!selected.length" @click="reviewing = true">查看方案</el-button><el-button v-else type="primary" :loading="busy" @click="save">确认并保存授权</el-button></template></el-dialog>
|
||||
</template>
|
||||
@@ -0,0 +1,27 @@
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { api, errorMessage, type Task, type Audit } from '../api'
|
||||
import { auditActionLabels } from '../api/audit-labels'
|
||||
import { usePlatform } from '../stores/platform'
|
||||
import StatusTag from '../components/StatusTag.vue'
|
||||
const data = usePlatform(), rows = ref<Task[]>([]), page = ref(1), total = ref(0), loading = ref(false), error = ref(''), search = ref(''), keyword = ref('')
|
||||
const tab = ref('changes'), changes = ref<Audit[]>([])
|
||||
let generation = 0
|
||||
onBeforeUnmount(() => { generation++ })
|
||||
async function load(reset = false) {
|
||||
if (reset) { page.value = 1; keyword.value = search.value }
|
||||
const request = ++generation; loading.value = true; error.value = ''
|
||||
try {
|
||||
const filters = { page: page.value, pageSize: 10, keyword: keyword.value }
|
||||
if (tab.value === 'changes') { const result = await api.audits(filters); if (request === generation) { changes.value = result.items; total.value = result.total } }
|
||||
else { const result = await api.taskHistory(filters); if (request === generation) { rows.value = result.items; total.value = result.total } }
|
||||
}
|
||||
catch (e) { if (request === generation) { error.value = errorMessage(e); rows.value = []; changes.value = []; total.value = 0 } }
|
||||
finally { if (request === generation) loading.value = false }
|
||||
}
|
||||
onMounted(() => load())
|
||||
watch(() => data.updatedAt, () => { void load() })
|
||||
</script>
|
||||
<template>
|
||||
<div class="page-heading"><div><h1>操作记录</h1><p class="subtext">查看员工授权、配置变更与桌面任务结果</p></div></div><section class="panel"><el-tabs v-model="tab" @tab-change="load(true)"><el-tab-pane label="人员与配置变更" name="changes" /><el-tab-pane label="设备与桌面任务" name="tasks" /></el-tabs><div class="toolbar"><el-input v-model="search" aria-label="查找操作记录" placeholder="对象名称或结果" clearable @keyup.enter="load(true)" /><el-button type="primary" :loading="loading" @click="load(true)">查询记录</el-button></div><el-alert v-if="error" type="error" :title="error" :closable="false" /><el-table v-if="tab === 'changes'" v-loading="loading" :data="changes" empty-text="没有匹配的变更记录"><el-table-column prop="target" label="对象" min-width="180" /><el-table-column label="操作" min-width="140"><template #default="{ row }">{{ auditActionLabels[row.action] || row.action }}</template></el-table-column><el-table-column prop="result" label="记录结果" min-width="210" /><el-table-column prop="actor" label="操作人" min-width="110" /><el-table-column label="时间" min-width="170"><template #default="{ row }">{{ new Date(row.createdAt).toLocaleString('zh-CN') }}</template></el-table-column></el-table><el-table v-else v-loading="loading" :data="rows" empty-text="没有匹配的任务"><el-table-column prop="targetName" label="对象" min-width="150" /><el-table-column label="操作" min-width="120"><template #default="{ row }">{{ auditActionLabels[row.action] || row.action }}</template></el-table-column><el-table-column label="结果" min-width="110"><template #default="{ row }"><StatusTag :value="row.status" /></template></el-table-column><el-table-column prop="message" label="说明" min-width="240" /><el-table-column prop="actor" label="操作人" min-width="110" /><el-table-column label="时间" min-width="170"><template #default="{ row }">{{ new Date(row.createdAt).toLocaleString('zh-CN') }}</template></el-table-column></el-table><el-pagination v-model:current-page="page" :disabled="loading" :total="total" :page-size="10" layout="total, prev, pager, next" @current-change="load()" /></section><p class="subtext">结果未确认不代表失败或成功,应由运维核对。更详细的筛选、结果核对和 CSV 导出位于高级版“任务与审计”。</p>
|
||||
</template>
|
||||
@@ -0,0 +1,16 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { usePlatform } from '../stores/platform'
|
||||
import { useAuth } from '../stores/auth'
|
||||
const data = usePlatform(), auth = useAuth()
|
||||
const running = computed(() => data.desktops.filter(d => d.powerState === 'running').length)
|
||||
const unassigned = computed(() => data.users.filter(u => u.enabled && !u.desktopIds.length).length)
|
||||
const offline = computed(() => data.terminals.filter(t => t.enabled !== false && t.status !== 'disabled' && t.status !== 'online').length)
|
||||
const unresolved = computed(() => data.tasks.filter(t => t.status === 'timeout').length)
|
||||
</script>
|
||||
<template>
|
||||
<div class="page-heading"><div><h1>工作台</h1><p class="subtext">{{ auth.user?.displayName }},在这里完成日常桌面管理</p></div><el-tag>通用版</el-tag></div>
|
||||
<div class="simple-stats"><section class="panel"><span>运行中的桌面</span><strong>{{ running }}<small> / {{ data.desktops.length }} 台桌面</small></strong></section><section class="panel"><span>在线设备</span><strong>{{ data.terminals.filter(t => t.status === 'online').length }}<small> / {{ data.terminals.length }} 台</small></strong></section><section class="panel"><span>正在使用</span><strong>{{ data.overview?.activeSessions ?? '—' }}<small> 个连接</small></strong></section></div>
|
||||
<section class="panel simple-section"><h2>你想完成什么?</h2><p class="subtext">选择一件事,按步骤完成。</p><div class="simple-shortcuts"><router-link to="/people"><strong>员工与桌面 →</strong><span>添加员工,分配或撤销已有桌面</span></router-link><router-link to="/devices"><strong>查看终端设备 →</strong><span>看在线状态,登记新盒子</span></router-link><router-link to="/help"><strong>桌面打不开 →</strong><span>检查设备、使用人和桌面连接条件</span></router-link></div></section>
|
||||
<section class="panel simple-section"><h2>需要关注</h2><div class="simple-issues"><router-link to="/people">{{ unassigned }} 位已启用员工尚未分配桌面 →</router-link><router-link to="/devices">{{ offline }} 台设备离线或等待激活 →</router-link><router-link to="/records">{{ unresolved }} 个任务结果尚未确认 →</router-link></div><p class="subtext">数据来自平台最近刷新。连接服务就绪后,仍需在终端验证实际连接和画面;告警详情见问题处理。</p></section>
|
||||
</template>
|
||||
@@ -51,7 +51,7 @@ async function submitImport() { if (!form.name.trim() || !form.node) return; if
|
||||
<el-table v-else :data="rows" empty-text="暂无符合条件的桌面"><el-table-column v-if="auth.canOperate" label="选择" width="60"><template #default="{ row }"><el-checkbox :model-value="batchIds.includes(row.id)" @change="toggleDesktop(row.id)" :aria-label="`选择桌面 ${row.name}`" :disabled="batchIds.length >= 50 && !batchIds.includes(row.id)" /></template></el-table-column><el-table-column label="桌面 / VMID" min-width="175"><template #default="{ row }"><el-button link type="primary" @click="selectedId = row.id">{{ row.name }}</el-button><div class="secondary">VM {{ row.vmid }} · {{ row.provider === 'demo' ? '演示资源' : 'Proxmox' }}</div></template></el-table-column><el-table-column prop="os" label="系统" width="100" /><el-table-column label="节点 / 池" min-width="150"><template #default="{ row }">{{ row.node }}<div class="secondary">{{ row.pool || '未入池' }}</div></template></el-table-column><el-table-column label="电源 / 连接服务" width="155"><template #default="{ row }"><StatusTag :value="row.powerState" /><div class="secondary" style="margin-top:5px">连接服务:{{ row.setupRequired ? '待初始化' : row.serviceState === 'ready' ? '就绪' : '未检测' }}</div></template></el-table-column><el-table-column label="操作" min-width="200"><template #default="{ row }"><div class="actions"><el-button link type="primary" @click="selectedId = row.id">详情</el-button><el-button v-if="auth.canOperate" link type="primary" :disabled="busy || activeTask(row)" @click="action(row, row.powerState === 'stopped' ? 'start' : 'shutdown')">{{ row.powerState === 'stopped' ? '开机' : '关机' }}</el-button><el-button v-if="auth.canOperate" link type="primary" :disabled="busy || row.powerState !== 'running' || activeTask(row)" @click="action(row, 'reboot')">重启</el-button><el-tag v-if="activeTask(row)" size="small">任务中</el-tag></div></template></el-table-column></el-table>
|
||||
<el-pagination v-model:current-page="page" :total="filtered.length" :page-size="10" layout="total, prev, pager, next" />
|
||||
</section>
|
||||
<el-drawer :model-value="!!selected" title="桌面详情" size="560px" @close="selectedId = ''"><template v-if="selected"><h2>{{ selected.name }}</h2><el-descriptions :column="1" border style="margin-top:22px"><el-descriptions-item label="节点 / VMID">{{ selected.node }} / {{ selected.vmid }}</el-descriptions-item><el-descriptions-item label="电源状态"><StatusTag :value="selected.powerState" /></el-descriptions-item><el-descriptions-item label="连接服务">{{ selected.setupRequired ? '待初始化,暂不能连接' : selected.serviceState === 'ready' ? '已就绪' : '尚未检测,不代表不可用' }}</el-descriptions-item><el-descriptions-item label="连接地址">{{ selected.endpoint || '未配置' }}</el-descriptions-item><el-descriptions-item label="连接参数">{{ selected.width }} × {{ selected.height }} / {{ selected.fps }} FPS</el-descriptions-item><el-descriptions-item label="授权用户">{{ data.users.filter(u => u.desktopIds.includes(selected!.id)).map(u => u.displayName).join('、') || '未分配' }}</el-descriptions-item></el-descriptions><p class="subtext" style="margin:20px 0">从模板创建后需完成系统初始化和 Sunshine 配对,再配置连接地址。关机后可管理快照;公共池自动还原待接入。</p><el-button v-if="auth.canAdmin" style="margin-bottom:18px" @click="openConnection(selected)">配置连接</el-button><el-button v-if="auth.canAdmin && selected.provider === 'proxmox'" style="margin-bottom:18px" :disabled="activeTask(selected)" @click="hardwareDesktop = selected">规格管理</el-button><el-button v-if="selected.provider === 'proxmox'" style="margin-bottom:18px" @click="snapshotDesktop = selected">快照与还原</el-button><div class="actions" v-if="auth.canOperate"><el-button :disabled="busy || activeTask(selected) || selected.powerState === 'running'" @click="action(selected, 'start')">开机</el-button><el-button :disabled="busy || activeTask(selected) || selected.powerState === 'stopped'" @click="action(selected, 'shutdown')">正常关机</el-button><el-button :disabled="busy || activeTask(selected) || selected.powerState !== 'running'" @click="action(selected, 'reboot')">重启桌面</el-button></div></template></el-drawer>
|
||||
<el-drawer :model-value="!!selected" title="桌面详情" size="560px" @close="selectedId = ''"><template v-if="selected"><h2>{{ selected.name }}</h2><router-link v-if="auth.canOperate" :to="{ path: '/diagnostics', query: { targetType: 'desktop', targetId: selected.id } }">查看此桌面关联诊断 →</router-link><el-descriptions :column="1" border style="margin-top:22px"><el-descriptions-item label="节点 / VMID">{{ selected.node }} / {{ selected.vmid }}</el-descriptions-item><el-descriptions-item label="电源状态"><StatusTag :value="selected.powerState" /></el-descriptions-item><el-descriptions-item label="连接服务">{{ selected.setupRequired ? '待初始化,暂不能连接' : selected.serviceState === 'ready' ? '已就绪' : '尚未检测,不代表不可用' }}</el-descriptions-item><el-descriptions-item label="连接地址">{{ selected.endpoint || '未配置' }}</el-descriptions-item><el-descriptions-item label="连接参数">{{ selected.width }} × {{ selected.height }} / {{ selected.fps }} FPS</el-descriptions-item><el-descriptions-item label="授权用户">{{ data.users.filter(u => u.desktopIds.includes(selected!.id)).map(u => u.displayName).join('、') || '未分配' }}</el-descriptions-item></el-descriptions><p class="subtext" style="margin:20px 0">从模板创建后需完成系统初始化和 Sunshine 配对,再配置连接地址。关机后可管理快照;公共池自动还原待接入。</p><el-button v-if="auth.canAdmin" style="margin-bottom:18px" @click="openConnection(selected)">配置连接</el-button><el-button v-if="auth.canAdmin && selected.provider === 'proxmox'" style="margin-bottom:18px" :disabled="activeTask(selected)" @click="hardwareDesktop = selected">规格管理</el-button><el-button v-if="selected.provider === 'proxmox'" style="margin-bottom:18px" @click="snapshotDesktop = selected">快照与还原</el-button><div class="actions" v-if="auth.canOperate"><el-button :disabled="busy || activeTask(selected) || selected.powerState === 'running'" @click="action(selected, 'start')">开机</el-button><el-button :disabled="busy || activeTask(selected) || selected.powerState === 'stopped'" @click="action(selected, 'shutdown')">正常关机</el-button><el-button :disabled="busy || activeTask(selected) || selected.powerState !== 'running'" @click="action(selected, 'reboot')">重启桌面</el-button></div></template></el-drawer>
|
||||
<el-dialog v-model="importVisible" title="纳管已有 VM" width="520px"><el-form label-position="top" @submit.prevent="submitImport"><el-form-item label="选择 VM" required><el-select v-model="vmKey" placeholder="选择节点和虚拟机" @change="chooseVM"><el-option v-for="v in discovered" :key="`${v.node}/${v.vmid}`" :value="`${v.node}/${v.vmid}`" :label="`${v.node} / ${v.vmid} / ${v.name}`" /></el-select></el-form-item><el-form-item label="桌面名称" required><el-input v-model="form.name" maxlength="80" /></el-form-item><el-form-item label="操作系统"><el-select v-model="form.os"><el-option v-for="os in (['Windows', 'Ubuntu', '麒麟'] as const)" :key="os" :value="os" /></el-select></el-form-item><el-form-item label="桌面连接地址(可后续补充)"><el-input v-model="form.endpoint" placeholder="VM 的 IP 或主机名" /></el-form-item><p class="subtext">纳管不会修改 VM;使用 Moonlight 前仍需完成 Sunshine 配对。</p><div class="actions" style="justify-content:flex-end;margin-top:22px"><el-button @click="importVisible = false">取消</el-button><el-button type="primary" native-type="submit" :loading="busy" :disabled="!form.node || !form.name.trim()">确认纳管</el-button></div></el-form></el-dialog>
|
||||
<DesktopBatchDialog v-model="batchAction" :desktop-ids="batchIds" /><CloneDesktopDialog v-model="cloneVisible" /><DesktopHardwareDialog v-model="hardwareDesktop" /><DesktopSnapshotsDialog v-model="snapshotDesktop" />
|
||||
<el-dialog :model-value="!!connectionDesktop" title="配置桌面连接" width="560px" :close-on-click-modal="false" @close="connectionDesktop = undefined"><el-form label-position="top" :disabled="busy"><el-alert v-if="connectionDesktop?.setupRequired" title="新桌面尚未初始化,完成以下检查后才能向终端签发连接票据。" type="warning" :closable="false" /><el-form-item label="IP 或主机名"><el-input v-model="connection.endpoint" placeholder="例如 192.168.1.200,不含协议和端口" maxlength="253" /></el-form-item><el-form-item label="请求宽度"><el-input-number v-model="connection.width" :min="640" :max="7680" :precision="0" /></el-form-item><el-form-item label="请求高度"><el-input-number v-model="connection.height" :min="480" :max="4320" :precision="0" /></el-form-item><el-form-item label="请求帧率"><el-input-number v-model="connection.fps" :min="10" :max="120" :precision="0" /></el-form-item><el-checkbox v-if="connectionDesktop?.setupRequired" v-model="connection.initialized">已完成系统身份、IP、Sunshine 服务和终端配对</el-checkbox><p class="subtext" style="margin-top:16px">保存会使旧连接票据失效;有活动连接时请先结束会话。</p></el-form><template #footer><el-button :disabled="busy" @click="connectionDesktop = undefined">取消</el-button><el-button type="primary" :loading="busy" :disabled="!connection.endpoint.trim() || (!!connectionDesktop?.setupRequired && !connection.initialized)" @click="saveConnection">保存连接配置</el-button></template></el-dialog>
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { api, errorMessage, type DiagnosticReport, type DiagnosticQuery, type DiagnosticEvent, type Task } from '../api'
|
||||
import { auditActionLabels } from '../api/audit-labels'
|
||||
import { usePlatform } from '../stores/platform'
|
||||
import { useAuth } from '../stores/auth'
|
||||
import { useAction } from '../composables/useAction'
|
||||
import StatusTag from '../components/StatusTag.vue'
|
||||
const data = usePlatform(), auth = useAuth(), route = useRoute(), { confirm } = useAction()
|
||||
const end = new Date()
|
||||
const form = reactive({ kind: 'terminal' as 'terminal' | 'desktop', id: '', source: '' as NonNullable<DiagnosticQuery['source']>, range: [new Date(end.getTime() - 86400000), end] as [Date, Date] | null })
|
||||
const sources = { tasks: '执行任务', sessions: '桌面会话', alerts: '监控告警', audits: '操作审计', logs: '终端日志' }
|
||||
const lifecycle: Record<string, string> = { 'session-reserved': '开始连接', 'session-connected': '连接已建立', 'session-ended': '连接结束', 'alert-opened': '告警触发', 'alert-resolved': '告警恢复' }
|
||||
const report = ref<DiagnosticReport | null>(null), applied = ref<DiagnosticQuery | null>(null), page = ref(1), loading = ref(false), error = ref(''), exporting = ref(false), collecting = ref(false)
|
||||
const collection = ref<Task | null>(null), collectionTarget = ref('')
|
||||
const currentCollection = computed(() => data.tasks.find(t => t.id === collection.value?.id) || collection.value)
|
||||
const objects = computed(() => form.kind === 'terminal' ? data.terminals.map(t => ({ id: t.id, label: `${t.name} / ${t.sn}` })) : data.desktops.map(d => ({ id: d.id, label: `${d.name} / VM ${d.vmid}` })))
|
||||
const terminal = computed(() => report.value?.subject.kind === 'terminal' ? data.terminals.find(t => t.id === report.value!.subject.id) : undefined)
|
||||
const pending = computed(() => !!terminal.value && data.tasks.some(t => t.kind === 'terminal' && t.targetId === terminal.value!.id && ['queued', 'running', 'timeout'].includes(t.status)))
|
||||
const canCollect = computed(() => auth.canOperate && report.value?.subject.kind === 'terminal' && report.value.subject.state === 'online' && terminal.value?.status === 'online' && terminal.value?.enabled !== false && !data.error && !pending.value)
|
||||
const shortcuts = [1, 24, 168].map(hours => ({ text: hours === 1 ? '最近 1 小时' : hours === 24 ? '最近 24 小时' : '最近 7 天', value: () => { const to = new Date(); return [new Date(to.getTime() - hours * 3600000), to] } }))
|
||||
const time = (value: string) => new Date(value).toLocaleString('zh-CN', { hour12: false })
|
||||
let generation = 0, exportGeneration = 0, collectionKey = '', collectionKeyTarget = ''
|
||||
onBeforeUnmount(() => { generation++; exportGeneration++ })
|
||||
watch(() => [form.kind, form.id, form.source, form.range], () => { generation++; exportGeneration++; report.value = null; applied.value = null; error.value = ''; loading.value = false }, { flush: 'sync', deep: true })
|
||||
function changeKind() { form.id = '' }
|
||||
async function load(reset = false) {
|
||||
if (reset) {
|
||||
if (!form.id || !form.range || form.range[1] <= form.range[0] || form.range[1].getTime() - form.range[0].getTime() > 7 * 86400000) { ElMessage.warning('请选择对象和有效时间范围,最长 7 天'); return }
|
||||
applied.value = { targetType: form.kind, targetId: form.id, source: form.source, from: form.range[0].toISOString(), to: form.range[1].toISOString() }; page.value = 1
|
||||
}
|
||||
if (!applied.value) return
|
||||
const version = ++generation, filters = { ...applied.value, page: page.value, pageSize: 20 }
|
||||
loading.value = true; error.value = ''; report.value = null
|
||||
try { const result = await api.diagnostics(filters); if (version === generation) report.value = result }
|
||||
catch (e) { if (version === generation) error.value = errorMessage(e) }
|
||||
finally { if (version === generation) loading.value = false }
|
||||
}
|
||||
async function download() {
|
||||
if (!report.value || !applied.value || exporting.value || loading.value) return
|
||||
const filters = { ...applied.value }, version = exportGeneration
|
||||
exporting.value = true
|
||||
try {
|
||||
const blob = await api.exportDiagnostics(filters)
|
||||
if (version !== exportGeneration) return
|
||||
const url = URL.createObjectURL(blob), link = document.createElement('a'); link.href = url; link.download = `vdi-diagnostics-${filters.targetType}-${new Date().toISOString().slice(0, 10)}.zip`; link.click(); setTimeout(() => URL.revokeObjectURL(url), 1000)
|
||||
ElMessage.success('诊断包已生成,包含当前筛选的全部匹配事件')
|
||||
} catch (e) { if (version === exportGeneration) ElMessage.error(errorMessage(e)) }
|
||||
finally { exporting.value = false }
|
||||
}
|
||||
async function collect() {
|
||||
if (!canCollect.value || collecting.value || !report.value) return
|
||||
const subject = { ...report.value.subject }; collecting.value = true
|
||||
try {
|
||||
if (!await confirm(`收集终端日志 · ${subject.name}`, '将向此设备提交日志采集命令并等待回执。不会重启设备、断开串流或操作桌面电源;提交成功不代表已取得日志。')) return
|
||||
if (!canCollect.value || report.value?.subject.id !== subject.id) return
|
||||
if (!collectionKey || collectionKeyTarget !== subject.id) { collectionKey = crypto.randomUUID(); collectionKeyTarget = subject.id }
|
||||
const task = await api.collectTerminalLogs(subject.id, collectionKey)
|
||||
collection.value = task; collectionTarget.value = subject.id; collectionKey = ''
|
||||
ElMessage.success('日志采集任务已提交,等待设备回执'); await data.refresh()
|
||||
} catch (e) { ElMessage.error(`${errorMessage(e)};请刷新任务核对,重试同一设备时复用本次请求标识。`) }
|
||||
finally { collecting.value = false }
|
||||
}
|
||||
function showCollection() {
|
||||
form.kind = 'terminal'; form.id = collectionTarget.value; form.source = 'logs'; const to = new Date(); form.range = [new Date(to.getTime() - 3600000), to]; void load(true)
|
||||
}
|
||||
function details(event: DiagnosticEvent): Record<string, unknown> { try { return JSON.parse(event.details) } catch { return {} } }
|
||||
function metadata(event: DiagnosticEvent) { const value = { ...details(event) }; delete value.logTail; return JSON.stringify(value, null, 2) }
|
||||
function applyRoute() {
|
||||
const kind = route.query.targetType, id = route.query.targetId
|
||||
if ((kind === 'terminal' || kind === 'desktop') && typeof id === 'string') { form.kind = kind; form.id = id; void load(true) }
|
||||
}
|
||||
onMounted(applyRoute)
|
||||
watch(() => [route.query.targetType, route.query.targetId], applyRoute)
|
||||
</script>
|
||||
<template>
|
||||
<div class="page-heading"><div><h1>日志与诊断</h1><p class="subtext">按设备或桌面关联日志、会话、告警与操作,追查故障经过</p></div><el-button :loading="exporting" :disabled="!report || loading || report.total > 2000" @click="download">导出诊断包</el-button></div>
|
||||
<section class="panel diagnosis-filters"><el-radio-group v-model="form.kind" aria-label="诊断对象类型" @change="changeKind"><el-radio-button value="terminal">终端设备</el-radio-button><el-radio-button value="desktop">云桌面</el-radio-button></el-radio-group><div class="diagnosis-query"><el-select v-model="form.id" aria-label="诊断对象" :placeholder="form.kind === 'terminal' ? '选择设备名称或 SN' : '选择桌面名称或 VMID'" filterable clearable><el-option v-for="object in objects" :key="object.id" :value="object.id" :label="object.label" /></el-select><el-date-picker v-model="form.range" type="datetimerange" aria-label="诊断时间范围" start-placeholder="开始时间" end-placeholder="结束时间" :shortcuts="shortcuts" format="YYYY-MM-DD HH:mm:ss" /><el-select v-model="form.source" aria-label="诊断记录来源" placeholder="全部记录来源" clearable><el-option v-for="(label, key) in sources" :key="key" :value="key" :label="label" /></el-select><el-button type="primary" :loading="loading" :disabled="!form.id" @click="load(true)">查询诊断</el-button></div><p class="subtext">最长查询 7 天。查询和导出使用相同对象、时间及来源;查询不会自动采集日志或修改设备。</p></section>
|
||||
<section v-if="currentCollection" class="panel diagnosis-collection"><strong>本次日志采集 · {{ currentCollection.targetName }}</strong><StatusTag :value="currentCollection.status" /><p>{{ currentCollection.message }}</p><span class="mono secondary">{{ currentCollection.id }}</span><el-button v-if="currentCollection.status === 'success'" link type="primary" @click="showCollection">查看本次采集</el-button><router-link v-else to="/tasks">查看采集任务 →</router-link></section>
|
||||
<el-alert v-if="error" type="error" :title="error" :closable="false" show-icon class="notice" />
|
||||
<section v-if="loading" class="panel diagnosis-empty"><el-skeleton :rows="6" animated /></section>
|
||||
<template v-else-if="report">
|
||||
<section class="panel diagnosis-subject"><div><h2>{{ report.subject.name }}</h2><p class="mono secondary">{{ report.subject.id }}<span v-if="report.subject.node"> · {{ report.subject.node }} / VM {{ report.subject.vmid }}</span></p><p class="secondary">当前快照 {{ time(report.observedAt) }}<span v-if="report.subject.lastSeen"> · 最近心跳 {{ time(report.subject.lastSeen) }}</span></p></div><div class="diagnosis-subject-actions"><StatusTag :value="report.subject.state" /><el-button v-if="report.subject.kind === 'terminal' && auth.canOperate" :loading="collecting" :disabled="!canCollect" @click="collect">收集此设备日志</el-button></div><p v-if="report.subject.kind === 'terminal'" class="diagnosis-footnote">{{ pending ? '该设备有未完成或结果未知的命令,请先到任务中心核对。' : report.subject.state !== 'online' ? '设备当前不在线,恢复在线后再采集新日志。' : '采集需要设备回执;已存在的日志可在下方查看。' }}</p></section>
|
||||
<div class="diagnosis-counts"><div v-for="(label, key) in sources" :key="key" class="panel"><span>{{ label }}</span><strong>{{ report.counts[key] }}</strong></div></div>
|
||||
<section class="panel diagnosis-timeline"><div class="diagnosis-timeline-heading"><div><h2>关联事件</h2><p class="subtext">{{ time(report.from) }} — {{ time(report.to) }} · {{ report.source ? sources[report.source as keyof typeof sources] : '全部来源' }} · 共 {{ report.total }} 条</p></div><el-tag type="info">按事件时间倒序</el-tag></div><el-alert v-if="report.total > 2000" type="warning" title="事件超过 2000 条,请缩小时间范围或选择记录来源后导出" :closable="false" class="notice" /><el-empty v-if="!report.items.length" description="此范围内没有匹配记录;未采集或未上报不代表没有故障" :image-size="90" /><el-timeline v-else><el-timeline-item v-for="event in report.items" :key="event.id" :timestamp="time(event.time)" placement="top"><article class="diagnosis-event"><div class="diagnosis-event-heading"><el-tag size="small" type="info">{{ sources[event.source] }}</el-tag><strong>{{ lifecycle[event.action] || auditActionLabels[event.action] || event.action }}</strong><StatusTag :value="event.status" /></div><p>{{ event.message }}</p><p class="secondary">{{ event.targetName }}<span v-if="event.actor"> · {{ event.actor }}</span></p><el-collapse><el-collapse-item title="查看关联标识与详情" :name="event.id"><pre v-if="typeof details(event).logTail === 'string'" class="diagnosis-log">{{ details(event).logTail || '设备回传的日志片段为空' }}</pre><pre>{{ metadata(event) }}</pre></el-collapse-item></el-collapse></article></el-timeline-item></el-timeline><el-pagination v-model:current-page="page" :disabled="loading" :total="report.total" :page-size="20" layout="total, prev, pager, next" @current-change="load()" /></section>
|
||||
<section class="panel diagnosis-notes"><h3>查询范围说明</h3><p v-for="note in report.notes" :key="note" class="subtext">{{ note }}</p></section>
|
||||
</template>
|
||||
<section v-else-if="!error" class="panel diagnosis-empty"><el-empty description="选择需要排查的设备或桌面,再查询诊断记录" :image-size="110" /></section>
|
||||
</template>
|
||||
<style scoped>
|
||||
.diagnosis-filters{padding:22px}.diagnosis-query{display:grid;grid-template-columns:minmax(190px,1fr) minmax(320px,1.5fr) 160px auto;gap:12px;margin:18px 0}.diagnosis-query :deep(.el-date-editor){width:100%;min-width:0}.diagnosis-subject{display:flex;justify-content:space-between;align-items:center;gap:18px;flex-wrap:wrap;margin-top:20px}.diagnosis-subject h2{font-size:19px;margin-bottom:8px}.diagnosis-subject p{line-height:1.8;font-size:12px}.diagnosis-subject-actions{display:flex;align-items:center;gap:14px}.diagnosis-footnote{width:100%;color:var(--vdi-muted)}.diagnosis-counts{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:12px;margin:20px 0}.diagnosis-counts .panel{padding:18px;margin:0}.diagnosis-counts span{font-size:12px;color:var(--vdi-muted)}.diagnosis-counts strong{display:block;font-size:26px;margin-top:12px}.diagnosis-timeline-heading{display:flex;justify-content:space-between;align-items:center;gap:16px;margin-bottom:26px;flex-wrap:wrap}.diagnosis-timeline h2{font-size:18px}.diagnosis-timeline :deep(.el-timeline){padding-left:4px}.diagnosis-event{border:1px solid var(--vdi-border);border-radius:12px;padding:16px;background:var(--vdi-panel-2);overflow-wrap:anywhere}.diagnosis-event-heading{display:flex;align-items:center;gap:10px;flex-wrap:wrap}.diagnosis-event-heading strong{font-size:14px}.diagnosis-event p{font-size:13px;line-height:1.9;margin-top:9px}.diagnosis-event pre{white-space:pre-wrap;overflow-wrap:anywhere;font-size:12px;line-height:1.8;max-height:380px;overflow:auto}.diagnosis-log{padding:16px;background:var(--vdi-bg);border:1px solid var(--vdi-border);border-radius:8px;margin:10px 0}.diagnosis-event :deep(.el-collapse){margin-top:12px;--el-collapse-header-bg-color:transparent;--el-collapse-content-bg-color:transparent}.diagnosis-collection{display:flex;align-items:center;gap:12px;flex-wrap:wrap}.diagnosis-collection p{width:100%;font-size:13px}.diagnosis-notes{margin-top:20px}.diagnosis-notes h3{font-size:14px}.diagnosis-notes p{margin-top:12px}.diagnosis-empty{margin-top:20px}@media(max-width:1250px){.diagnosis-query{grid-template-columns:1fr 1fr}.diagnosis-query :deep(.el-date-editor){grid-column:1/-1;grid-row:2}.diagnosis-query>.el-button{grid-column:1/-1}}@media(max-width:600px){.diagnosis-query{grid-template-columns:minmax(0,1fr)}.diagnosis-query :deep(.el-date-editor){height:62px;flex-wrap:wrap;gap:4px}.diagnosis-filters{padding:18px}.diagnosis-counts{grid-template-columns:repeat(2,minmax(0,1fr))}.diagnosis-event{padding:12px}.diagnosis-subject-actions{flex-wrap:wrap}.diagnosis-counts strong{font-size:23px}}
|
||||
</style>
|
||||
@@ -1,24 +1,25 @@
|
||||
<script setup lang="ts">
|
||||
import { reactive, ref } from 'vue'
|
||||
import { reactive, ref, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { Monitor, Connection, Lock, ArrowRight } from '@element-plus/icons-vue'
|
||||
import { useAuth } from '../stores/auth'
|
||||
import { errorMessage } from '../api'
|
||||
import { ApiError, errorMessage } from '../api'
|
||||
import ThemeToggle from '../components/ThemeToggle.vue'
|
||||
import brandMark from '../assets/brand-mark.svg'
|
||||
const auth = useAuth(), router = useRouter(), route = useRoute()
|
||||
const form = reactive({ username: '', password: '' }), busy = ref(false), error = ref('')
|
||||
const form = reactive({ username: '', password: '', code: '' }), busy = ref(false), error = ref(''), mfaRequired = ref(false)
|
||||
watch(() => form.username, () => { mfaRequired.value = false; form.code = ''; error.value = '' })
|
||||
const demo = import.meta.env.VITE_API_MODE === 'mock' || import.meta.env.VITE_DEMO_HINT === 'true'
|
||||
async function submit() {
|
||||
if (!form.username.trim() || !form.password) { error.value = '请输入用户名和密码'; return }
|
||||
busy.value = true; error.value = ''
|
||||
try { await auth.login(form.username.trim(), form.password); const redirect = typeof route.query.redirect === 'string' && route.query.redirect.startsWith('/') && !route.query.redirect.startsWith('//') ? route.query.redirect : '/overview'; await router.replace(redirect) }
|
||||
catch (e) { error.value = errorMessage(e) }
|
||||
try { await auth.login(form.username.trim(), form.password, form.code.trim()); form.password = ''; form.code = ''; const redirect = typeof route.query.redirect === 'string' && route.query.redirect.startsWith('/') && !route.query.redirect.startsWith('//') ? route.query.redirect : '/'; await router.replace(redirect) }
|
||||
catch (e) { if (e instanceof ApiError && (e.code === 'mfa_required' || e.code === 'mfa_invalid')) { mfaRequired.value = true; form.code = '' }; error.value = errorMessage(e) }
|
||||
finally { busy.value = false }
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<main class="login-page"><header class="login-header"><a href="/" class="login-brand"><img :src="brandMark" alt="" /><span>百工万象<small>VDI CLOUD</small></span></a><ThemeToggle /></header><div class="login-main"><section class="login-intro"><div class="eyebrow">VDI CLOUD / MANAGEMENT PLATFORM</div><h1>让每一台桌面<br>有序连接<span>。</span></h1><p>从桌面资源到终端运维,<br>让云端的每一次连接,尽在掌握。</p><div class="intro-capabilities"><span><el-icon><Monitor /></el-icon>桌面管理</span><span><el-icon><Connection /></el-icon>终端接入</span><span><el-icon><Lock /></el-icon>安全授权</span></div><div class="login-art" aria-hidden="true"><div class="art-orbit orbit-one" /><div class="art-orbit orbit-two" /><div class="art-screen screen-back"><div class="art-dots"><i /><i /><i /></div><div class="art-rows"><b /><b /><b /></div></div><div class="art-screen screen-front"><div class="art-dots"><i /><i /><i /></div><div class="art-logo"><img :src="brandMark" alt="" /><div>VDI CLOUD<small>连接工作新方式</small></div></div><div class="art-progress"><i /></div></div><div class="art-badge"><i />云 · 管 · 端</div></div></section><section class="login-form-area"><div class="login-card"><div class="section-kicker">WELCOME BACK</div><h2>登录管理控制台</h2><p class="subtext">使用平台管理员账号,开启工作。</p><el-alert v-if="error" class="notice" style="margin-top:24px" type="error" :title="error" :closable="false" show-icon /><el-form label-position="top" @submit.prevent="submit"><el-form-item label="用户名"><el-input v-model="form.username" name="username" autocomplete="username" size="large" placeholder="请输入用户名" :disabled="busy" /></el-form-item><el-form-item label="密码"><el-input v-model="form.password" name="password" type="password" autocomplete="current-password" size="large" show-password placeholder="请输入密码" :disabled="busy" /></el-form-item><el-button type="primary" size="large" native-type="submit" :loading="busy" class="login-submit">登录<el-icon><ArrowRight /></el-icon></el-button></el-form><p class="login-security"><el-icon><Lock /></el-icon>仅限已授权的平台管理人员访问</p><p v-if="demo" class="demo-hint">演示账号:admin / operator / viewer<br>演示密码:Demo@2026<br><span>仅用于演示模式,正式环境使用独立账号。</span></p></div></section></div><footer class="login-footer"><span>百工万象 · VDI Cloud</span><span>云端服务 / 管理控制台 / 云终端</span></footer></main>
|
||||
<main class="login-page"><header class="login-header"><a href="/" class="login-brand"><img :src="brandMark" alt="" /><span>百工万象<small>VDI CLOUD</small></span></a><ThemeToggle /></header><div class="login-main"><section class="login-intro"><div class="eyebrow">VDI CLOUD / MANAGEMENT PLATFORM</div><h1>让每一台桌面<br>有序连接<span>。</span></h1><p>从桌面资源到终端运维,<br>让云端的每一次连接,尽在掌握。</p><div class="intro-capabilities"><span><el-icon><Monitor /></el-icon>桌面管理</span><span><el-icon><Connection /></el-icon>终端接入</span><span><el-icon><Lock /></el-icon>安全授权</span></div><div class="login-art" aria-hidden="true"><div class="art-orbit orbit-one" /><div class="art-orbit orbit-two" /><div class="art-screen screen-back"><div class="art-dots"><i /><i /><i /></div><div class="art-rows"><b /><b /><b /></div></div><div class="art-screen screen-front"><div class="art-dots"><i /><i /><i /></div><div class="art-logo"><img :src="brandMark" alt="" /><div>VDI CLOUD<small>连接工作新方式</small></div></div><div class="art-progress"><i /></div></div><div class="art-badge"><i />云 · 管 · 端</div></div></section><section class="login-form-area"><div class="login-card"><div class="section-kicker">WELCOME BACK</div><h2>登录管理控制台</h2><p class="subtext">使用平台管理员账号,开启工作。</p><el-alert v-if="error" class="notice" style="margin-top:24px" type="error" :title="error" :closable="false" show-icon /><el-form label-position="top" @submit.prevent="submit"><el-form-item label="用户名"><el-input v-model="form.username" name="username" autocomplete="username" size="large" placeholder="请输入用户名" :disabled="busy" /></el-form-item><el-form-item label="密码"><el-input v-model="form.password" name="password" type="password" autocomplete="current-password" size="large" show-password placeholder="请输入密码" :disabled="busy" /></el-form-item><el-form-item v-if="mfaRequired" label="动态码或恢复码"><el-input v-model="form.code" name="code" aria-label="登录动态码或恢复码" autocomplete="one-time-code" size="large" maxlength="80" placeholder="输入身份验证器动态码或恢复码" :disabled="busy" /></el-form-item><el-button type="primary" size="large" native-type="submit" :loading="busy" class="login-submit">登录<el-icon><ArrowRight /></el-icon></el-button></el-form><p class="login-security"><el-icon><Lock /></el-icon>仅限已授权的平台管理人员访问</p><p v-if="demo" class="demo-hint">演示账号:admin / operator / viewer<br>演示密码:Demo@2026<br><span>仅用于演示模式,正式环境使用独立账号。</span></p></div></section></div><footer class="login-footer"><span>百工万象 · VDI Cloud</span><span>云端服务 / 管理控制台 / 云终端</span></footer></main>
|
||||
</template>
|
||||
<style scoped>
|
||||
.login-page{min-height:100vh;display:flex;flex-direction:column;background:radial-gradient(ellipse at 8% 60%,var(--vdi-accent-soft),transparent 53%),var(--vdi-bg)}.login-header{padding:30px 5%;display:flex;justify-content:space-between;align-items:center}.login-brand{display:flex;align-items:center;gap:11px;color:var(--vdi-text);font-size:23px;font-weight:750;letter-spacing:1px}.login-brand img{width:36px;height:36px}.login-brand small{display:block;color:var(--vdi-muted);font-size:9px;letter-spacing:2.7px;font-weight:500;margin-top:4px}.login-main{flex:1;display:grid;grid-template-columns:1.15fr 1fr;align-items:center;gap:8%;width:min(1160px,88%);margin:35px auto}.login-intro{position:relative;padding-top:12px}.eyebrow{font-size:11px;letter-spacing:2px;margin-bottom:24px}.login-intro h1{font-size:48px;line-height:1.45;letter-spacing:1px;font-weight:750}.login-intro h1 span{color:var(--vdi-brand)}.login-intro>p{color:var(--vdi-muted);line-height:1.9;margin-top:20px;font-size:15px}.intro-capabilities{display:flex;gap:23px;margin-top:25px;flex-wrap:wrap}.intro-capabilities>span{display:flex;align-items:center;gap:7px;color:var(--vdi-muted);font-size:12px}.intro-capabilities .el-icon{color:var(--vdi-accent)}.login-form-area{display:flex;justify-content:center}.login-card{width:440px;max-width:100%;background:var(--vdi-panel);border:1px solid var(--vdi-border);padding:40px;border-radius:22px;box-shadow:var(--vdi-shadow)}.login-card h2{font-size:25px;margin-bottom:10px}.section-kicker{color:var(--vdi-accent);font-size:10px;letter-spacing:2px;margin-bottom:14px}.login-card .el-form{margin-top:34px}.login-card :deep(.el-form-item){margin-bottom:25px}.login-card :deep(.el-input__wrapper){min-height:46px;background:var(--vdi-bg)}.login-submit{width:100%;height:46px;margin-top:7px;font-weight:600}.login-submit .el-icon{margin-left:12px}.login-security{display:flex;justify-content:center;align-items:center;gap:6px;font-size:11px;color:var(--vdi-muted);margin-top:23px}.demo-hint{font-size:12px;line-height:1.9;color:var(--vdi-muted);margin-top:24px;padding-top:20px;border-top:1px solid var(--vdi-border)}.demo-hint span{font-size:11px}.login-footer{display:flex;justify-content:space-between;padding:25px 5%;color:var(--vdi-muted);font-size:11px;gap:16px;flex-wrap:wrap}.login-art{position:relative;width:360px;height:200px;margin-top:32px}.art-orbit{position:absolute;border:1px solid var(--vdi-border);border-radius:50%;width:340px;height:135px;bottom:4px;left:0;transform:rotate(-14deg)}.orbit-two{transform:rotate(15deg);width:300px;bottom:17px;left:20px}.art-screen{position:absolute;background:var(--vdi-panel);border:1px solid var(--vdi-border);border-radius:13px;box-shadow:var(--vdi-shadow);overflow:hidden}.screen-back{width:220px;height:133px;left:8px;top:9px;transform:rotate(-7deg)}.screen-front{width:247px;height:152px;left:89px;top:40px;transform:rotate(5deg)}.art-dots{display:flex;gap:4px;padding:11px;border-bottom:1px solid var(--vdi-border);background:var(--vdi-panel-2)}.art-dots i{width:4px;height:4px;border-radius:50%;background:var(--vdi-muted);opacity:.5}.art-rows{padding:20px 18px}.art-rows b{display:block;height:7px;background:var(--vdi-border);margin-bottom:9px;width:65%;border-radius:3px}.art-rows b:nth-child(2){width:88%}.art-rows b:nth-child(3){width:43%;background:var(--vdi-brand);opacity:.6}.art-logo{display:flex;gap:13px;align-items:center;padding:26px 25px 17px;font-size:14px;letter-spacing:1px;font-weight:600}.art-logo img{width:33px;height:33px}.art-logo small{font-size:9px;display:block;color:var(--vdi-muted);letter-spacing:1px;margin-top:6px;font-weight:400}.art-progress{margin:0 25px;height:4px;background:var(--vdi-panel-2);border-radius:4px}.art-progress i{display:block;height:100%;width:68%;background:linear-gradient(90deg,var(--vdi-brand),#f1ad62);border-radius:4px}.art-badge{position:absolute;right:0;bottom:0;background:var(--vdi-panel);border:1px solid var(--vdi-border);border-radius:9px;padding:9px 14px;font-size:10px;box-shadow:var(--vdi-shadow)}.art-badge i{width:5px;height:5px;border-radius:50%;display:inline-block;background:var(--vdi-ok);margin-right:6px}
|
||||
|
||||
@@ -6,7 +6,7 @@ import { useAuth } from '../stores/auth'
|
||||
import { useAction } from '../composables/useAction'
|
||||
import ResourceTrend from '../components/ResourceTrend.vue'
|
||||
const data = usePlatform(), auth = useAuth(), { run, busy: saving } = useAction()
|
||||
const metricLabels: Record<string, string> = { node_cpu: '节点 CPU', node_memory: '节点内存', node_storage: '节点存储', node_unavailable: '节点不可用 / 采集异常', terminal_offline: '终端离线' }
|
||||
const metricLabels: Record<string, string> = { node_cpu: '节点 CPU', node_memory: '节点内存', node_storage: '节点存储', node_unavailable: '节点不可用 / 采集异常', terminal_offline: '终端离线', terminal_cpu: '终端 CPU', terminal_memory: '终端内存', terminal_temperature: '终端 SoC 温度' }
|
||||
const rules = ref<AlertRule[]>([]), alerts = ref<AlertRecord[]>([]), points = ref<ResourcePoint[]>([])
|
||||
const resourceId = ref(''), hours = ref(24), bucket = ref(300), from = ref(Date.now() - 86400000), to = ref(Date.now())
|
||||
const status = ref(''), keyword = ref(''), page = ref(1), total = ref(0), firing = ref(0), unacknowledged = ref(0), loading = ref(false), error = ref(''), chartError = ref('')
|
||||
@@ -14,6 +14,9 @@ const nodes = computed(() => data.resources.filter(r => r.provider === 'proxmox'
|
||||
const tab = ref('alerts'), dialog = ref(false), editId = ref('')
|
||||
const form = reactive<AlertRuleInput>({ name: '', metric: 'node_cpu', threshold: 90, holdSeconds: 120, enabled: true })
|
||||
const offline = computed(() => ['node_unavailable', 'terminal_offline'].includes(form.metric))
|
||||
const temperature = computed(() => form.metric === 'terminal_temperature')
|
||||
const terminalMetric = computed(() => ['terminal_cpu', 'terminal_memory', 'terminal_temperature'].includes(form.metric))
|
||||
const unit = (metric: string) => ['node_unavailable', 'terminal_offline'].includes(metric) ? '秒' : metric === 'terminal_temperature' ? '°C' : '%'
|
||||
const stamp = (v?: string | null) => v ? new Date(v).toLocaleString('zh-CN', { hour12: false }) : '—'
|
||||
const reasons: Record<string, string> = { condition_cleared: '指标恢复', rule_changed: '规则变更', target_unavailable: '目标移除或停用' }
|
||||
async function chart() {
|
||||
@@ -42,7 +45,7 @@ function edit(rule?: AlertRule) {
|
||||
Object.assign(form, rule ? { name: rule.name, metric: rule.metric, threshold: rule.threshold, holdSeconds: rule.holdSeconds, enabled: rule.enabled } : { name: '', metric: 'node_cpu', threshold: 90, holdSeconds: 120, enabled: true })
|
||||
dialog.value = true
|
||||
}
|
||||
function metricChanged() { form.threshold = offline.value ? 180 : 90; form.holdSeconds = offline.value ? 0 : 120 }
|
||||
function metricChanged() { form.threshold = offline.value ? 180 : temperature.value ? 80 : 90; form.holdSeconds = offline.value ? 0 : 120 }
|
||||
async function save() {
|
||||
if (!form.name.trim()) return
|
||||
const ok = await run(() => api.saveAlertRule(editId.value, { ...form, name: form.name.trim() }), '告警规则已保存')
|
||||
@@ -54,7 +57,7 @@ onMounted(() => { void load(); timer = setInterval(() => { if (!document.hidden
|
||||
onUnmounted(() => clearInterval(timer))
|
||||
</script>
|
||||
<template>
|
||||
<div class="page-heading"><div><h1>监控告警</h1><p class="subtext">节点历史趋势与终端离线告警 · 每 15 秒刷新</p></div><el-button :loading="loading" @click="load()">刷新监控</el-button></div>
|
||||
<div class="page-heading"><div><h1>监控告警</h1><p class="subtext">节点与终端指标告警 · 每 15 秒刷新</p></div><el-button :loading="loading" @click="load()">刷新监控</el-button></div>
|
||||
<el-alert v-if="error" type="error" :title="error" :closable="false" class="notice" />
|
||||
<div class="monitor-summary"><article class="panel"><span>正在告警</span><strong :class="firing ? 'tone-danger' : 'tone-ok'">{{ firing }}</strong></article><article class="panel"><span>等待确认</span><strong>{{ unacknowledged }}</strong></article><article class="panel"><span>启用规则</span><strong>{{ rules.filter(r => r.enabled).length }}</strong></article></div>
|
||||
<section class="panel">
|
||||
@@ -65,15 +68,15 @@ onUnmounted(() => clearInterval(timer))
|
||||
<el-tabs v-model="tab"><el-tab-pane label="告警事件" name="alerts" /><el-tab-pane label="告警规则" name="rules" /></el-tabs>
|
||||
<template v-if="tab === 'alerts'">
|
||||
<div class="alert-filters"><el-input v-model="keyword" aria-label="搜索告警" placeholder="规则或目标名称" clearable @keyup.enter="load(true)" /><el-select v-model="status" aria-label="告警状态"><el-option value="" label="全部状态" /><el-option value="firing" label="正在告警" /><el-option value="resolved" label="已恢复" /></el-select><el-button :loading="loading" @click="load(true)">查询告警</el-button></div>
|
||||
<el-table :data="alerts" empty-text="暂无告警事件"><el-table-column label="规则 / 目标" min-width="190"><template #default="{ row }"><strong>{{ row.ruleName }}</strong><div class="subtext">{{ row.targetName }}</div></template></el-table-column><el-table-column label="状态" min-width="110"><template #default="{ row }"><el-tag :type="row.status === 'firing' ? 'danger' : 'success'">{{ row.status === 'firing' ? '正在告警' : '已恢复' }}</el-tag></template></el-table-column><el-table-column label="观测值 / 阈值" min-width="160"><template #default="{ row }">{{ row.value.toFixed(1) }} / {{ row.threshold }} {{ row.metric.endsWith('offline') || row.metric === 'node_unavailable' ? '秒' : '%' }}<div v-if="row.metric === 'node_unavailable'" class="subtext">含节点离线状态检测</div></template></el-table-column><el-table-column label="发生 / 恢复" min-width="185"><template #default="{ row }"><div>{{ stamp(row.openedAt) }}</div><div class="subtext">{{ row.resolvedAt ? stamp(row.resolvedAt) : '持续中' }}</div><div class="subtext">{{ reasons[row.resolveReason] }}</div></template></el-table-column><el-table-column label="确认" min-width="150"><template #default="{ row }"><span v-if="row.acknowledgedAt">{{ row.acknowledgedBy }}<div class="subtext">{{ stamp(row.acknowledgedAt) }}</div></span><el-button v-else-if="auth.canOperate && row.status === 'firing'" link type="primary" :disabled="saving" @click="acknowledge(row)">确认告警</el-button><span v-else class="secondary">未确认</span></template></el-table-column></el-table>
|
||||
<el-table :data="alerts" empty-text="暂无告警事件"><el-table-column label="规则 / 目标" min-width="190"><template #default="{ row }"><strong>{{ row.ruleName }}</strong><div class="subtext">{{ row.targetName }}</div></template></el-table-column><el-table-column label="状态" min-width="110"><template #default="{ row }"><el-tag :type="row.status === 'firing' ? 'danger' : 'success'">{{ row.status === 'firing' ? '正在告警' : '已恢复' }}</el-tag></template></el-table-column><el-table-column label="观测值 / 阈值" min-width="160"><template #default="{ row }">{{ row.value.toFixed(1) }} / {{ row.threshold }} {{ unit(row.metric) }}<div v-if="row.status === 'firing' && row.dataFresh === false" class="data-unknown" role="status">数据已过期或缺失;显示最近告警值,等待有效采样</div><div v-if="row.metric === 'node_unavailable'" class="subtext">含节点离线状态检测</div></template></el-table-column><el-table-column label="发生 / 恢复" min-width="185"><template #default="{ row }"><div>{{ stamp(row.openedAt) }}</div><div class="subtext">{{ row.resolvedAt ? stamp(row.resolvedAt) : '持续中' }}</div><div class="subtext">{{ reasons[row.resolveReason] }}</div></template></el-table-column><el-table-column label="确认" min-width="150"><template #default="{ row }"><span v-if="row.acknowledgedAt">{{ row.acknowledgedBy }}<div class="subtext">{{ stamp(row.acknowledgedAt) }}</div></span><el-button v-else-if="auth.canOperate && row.status === 'firing'" link type="primary" :disabled="saving" @click="acknowledge(row)">确认告警</el-button><span v-else class="secondary">未确认</span></template></el-table-column></el-table>
|
||||
<el-pagination v-model:current-page="page" :page-size="20" :total="total" layout="prev, pager, next, total" @current-change="load()" /><p class="subtext retention-note">确认表示已知悉,指标恢复后自动结束告警。已恢复事件保留 90 天。</p>
|
||||
</template>
|
||||
<template v-else><div class="panel-heading"><p class="subtext">水位按持续时间触发;离线按秒数触发。修改规则后重新计时。</p><el-button v-if="auth.canAdmin" type="primary" @click="edit()">新增规则</el-button></div><el-table :data="rules" empty-text="暂无规则"><el-table-column prop="name" label="规则名称" min-width="190" /><el-table-column label="指标" min-width="190"><template #default="{ row }">{{ metricLabels[row.metric] }}</template></el-table-column><el-table-column label="阈值 / 持续" min-width="155"><template #default="{ row }">{{ row.threshold }}{{ ['node_unavailable', 'terminal_offline'].includes(row.metric) ? ' 秒离线' : `% / ${row.holdSeconds} 秒` }}</template></el-table-column><el-table-column label="状态" width="100"><template #default="{ row }"><el-tag :type="row.enabled ? 'success' : 'info'">{{ row.enabled ? '启用' : '停用' }}</el-tag></template></el-table-column><el-table-column v-if="auth.canAdmin" label="操作" width="90"><template #default="{ row }"><el-button link type="primary" @click="edit(row)">编辑规则</el-button></template></el-table-column></el-table></template>
|
||||
<template v-else><div class="panel-heading"><p class="subtext">水位按持续时间触发;离线按秒数触发。修改规则后重新计时。</p><el-button v-if="auth.canAdmin" type="primary" @click="edit()">新增规则</el-button></div><el-table :data="rules" empty-text="暂无规则"><el-table-column prop="name" label="规则名称" min-width="190" /><el-table-column label="指标" min-width="190"><template #default="{ row }">{{ metricLabels[row.metric] }}</template></el-table-column><el-table-column label="阈值 / 持续" min-width="155"><template #default="{ row }">{{ row.threshold }}{{ ['node_unavailable', 'terminal_offline'].includes(row.metric) ? ' 秒离线' : `${unit(row.metric)} / ${row.holdSeconds} 秒` }}</template></el-table-column><el-table-column label="状态" width="100"><template #default="{ row }"><el-tag :type="row.enabled ? 'success' : 'info'">{{ row.enabled ? '启用' : '停用' }}</el-tag></template></el-table-column><el-table-column v-if="auth.canAdmin" label="操作" width="90"><template #default="{ row }"><el-button link type="primary" @click="edit(row)">编辑规则</el-button></template></el-table-column></el-table></template>
|
||||
</section>
|
||||
<el-dialog v-model="dialog" :title="editId ? '编辑告警规则' : '新增告警规则'" width="540px" :close-on-click-modal="false" :close-on-press-escape="!saving" :show-close="!saving"><el-form label-position="top"><el-form-item label="规则名称"><el-input v-model="form.name" maxlength="80" aria-label="规则名称" :disabled="saving" /></el-form-item><el-form-item label="监控指标"><el-select v-model="form.metric" aria-label="规则监控指标" :disabled="saving" @change="metricChanged"><el-option v-for="(label, value) in metricLabels" :key="value" :value="value" :label="label" /></el-select></el-form-item><el-form-item :label="offline ? '离线阈值(秒)' : '使用率阈值(%)'"><el-input-number v-model="form.threshold" :min="offline ? 90 : 1" :max="offline ? 86400 : 100" :precision="offline ? 0 : 1" aria-label="告警阈值" :disabled="saving" /></el-form-item><el-form-item v-if="!offline" label="持续时间(秒)"><el-input-number v-model="form.holdSeconds" :min="0" :max="3600" :precision="0" aria-label="告警持续时间" :disabled="saving" /></el-form-item><el-form-item label="启用规则"><el-switch v-model="form.enabled" aria-label="启用告警规则" :disabled="saving" /></el-form-item></el-form><el-alert v-if="editId" title="保存会结束本规则当前告警,并按新规则重新计时。" type="info" :closable="false" /><template #footer><el-button :disabled="saving" @click="dialog = false">取消</el-button><el-button type="primary" :loading="saving" :disabled="!form.name.trim()" @click="save">保存规则</el-button></template></el-dialog>
|
||||
<el-dialog v-model="dialog" :title="editId ? '编辑告警规则' : '新增告警规则'" width="540px" :close-on-click-modal="false" :close-on-press-escape="!saving" :show-close="!saving"><el-form label-position="top"><el-form-item label="规则名称"><el-input v-model="form.name" maxlength="80" aria-label="规则名称" :disabled="saving" /></el-form-item><el-form-item label="监控指标"><el-select v-model="form.metric" aria-label="规则监控指标" :disabled="saving" @change="metricChanged"><el-option v-for="(label, value) in metricLabels" :key="value" :value="value" :label="label" /></el-select></el-form-item><el-form-item :label="offline ? '离线阈值(秒)' : temperature ? 'SoC 温度阈值(°C)' : '使用率阈值(%)'"><el-input-number v-model="form.threshold" :min="offline ? 90 : 1" :max="offline ? 86400 : temperature ? 150 : 100" :precision="offline ? 0 : 1" aria-label="告警阈值" :disabled="saving" /></el-form-item><el-form-item v-if="!offline" label="持续时间(秒)"><el-input-number v-model="form.holdSeconds" :min="0" :max="3600" :precision="0" aria-label="告警持续时间" :disabled="saving" /></el-form-item><el-form-item label="启用规则"><el-switch v-model="form.enabled" aria-label="启用告警规则" :disabled="saving" /></el-form-item></el-form><p v-if="terminalMetric" class="subtext terminal-alert-note">对已激活且启用的终端生效;SoC 温度只使用 soc-thermal 传感器。持续时间按新采样累计,重复读取不推进;采样超过 90 秒或缺失会重新计时,已有告警等待有效正常采样才恢复。此规则只在控制台告警,不发送外部通知。</p><el-alert v-if="editId" title="保存会结束本规则当前告警,并按新规则重新计时。" type="info" :closable="false" /><template #footer><el-button :disabled="saving" @click="dialog = false">取消</el-button><el-button type="primary" :loading="saving" :disabled="!form.name.trim()" @click="save">保存规则</el-button></template></el-dialog>
|
||||
</template>
|
||||
<style scoped>
|
||||
.monitor-summary{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:18px}.monitor-summary .panel{display:flex;justify-content:space-between;align-items:center;gap:12px}.monitor-summary span{font-size:12px;color:var(--vdi-muted)}.monitor-summary strong{font-size:28px}.trend-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:16px;margin-top:20px}.chart-filters,.alert-filters{display:flex;gap:12px;flex-wrap:wrap}.chart-filters .el-select{width:160px}.alert-filters{margin:18px 0}.alert-filters .el-input{width:230px}.alert-filters .el-select{width:150px}.el-pagination{margin-top:20px;flex-wrap:wrap}.retention-note{margin-top:15px}.subtext{line-height:1.7}
|
||||
.monitor-summary{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:18px}.monitor-summary .panel{display:flex;justify-content:space-between;align-items:center;gap:12px}.monitor-summary span{font-size:12px;color:var(--vdi-muted)}.monitor-summary strong{font-size:28px}.trend-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:16px;margin-top:20px}.chart-filters,.alert-filters{display:flex;gap:12px;flex-wrap:wrap}.chart-filters .el-select{width:160px}.alert-filters{margin:18px 0}.alert-filters .el-input{width:230px}.alert-filters .el-select{width:150px}.el-pagination{margin-top:20px;flex-wrap:wrap}.retention-note{margin-top:15px}.subtext{line-height:1.7}.data-unknown{color:var(--el-color-warning);font-size:12px;line-height:1.7;margin-top:6px}.terminal-alert-note{margin:14px 0;font-size:12px}
|
||||
@media(max-width:1200px){.trend-grid{grid-template-columns:1fr}.panel-heading{flex-wrap:wrap;gap:16px}}
|
||||
@media(max-width:600px){.monitor-summary{gap:8px}.monitor-summary .panel{padding:14px;flex-direction:column;align-items:flex-start}.monitor-summary strong{font-size:24px}.chart-filters,.alert-filters{width:100%}.chart-filters .el-select,.alert-filters .el-select{flex:1;min-width:120px}.alert-filters .el-input{width:100%}}
|
||||
</style>
|
||||
@@ -11,7 +11,7 @@ const planned = ['公共池自动领取与退出还原', '新桌面自动初始
|
||||
</script>
|
||||
<template>
|
||||
<div class="page-heading"><div><h1>系统设置</h1><p class="subtext">平台接入状态、访问权限与当前功能范围</p></div></div>
|
||||
<div class="settings-layout"><nav class="panel settings-nav" aria-label="设置分类"><button v-for="item in sections" :key="item.id" :class="{ active: section === item.id }" :aria-pressed="section === item.id" @click="section = item.id"><el-icon :size="17"><component :is="item.icon" /></el-icon>{{ item.title }}</button></nav><div class="settings-content"><section v-if="section === 'platform'" class="panel settings-panel"><div class="section-kicker">PLATFORM CONNECTION</div><h2>平台接入</h2><p class="subtext">统一查看管理服务、计算资源与终端通道</p><div class="setting-row"><div><strong>运行环境</strong><p>使用独立数据库保存平台业务数据</p></div><el-tag :type="data.settings?.mode === 'demo' ? 'warning' : 'success'">{{ data.settings?.mode === 'demo' ? '演示环境' : '现场联调环境' }}</el-tag></div><div class="setting-row"><div><strong>Proxmox 计算平台</strong><p>连接状态以最近同步任务结果为准</p></div><span :class="data.settings?.pveConfigured ? 'tone-ok' : 'secondary'"><i class="health-dot" />{{ data.settings?.pveConfigured ? '已配置' : '尚未配置' }}</span></div><div class="setting-row"><div><strong>终端管理通道</strong><p>设备注册、心跳、命令领取与执行回执</p></div><span class="setting-value">HTTPS</span></div><div class="setting-row"><div><strong>业务数据存储</strong><p>账号、设备、授权关系、任务与审计</p></div><span class="setting-value">PostgreSQL</span></div><div class="setting-row"><div><strong>当前管理员</strong><p>{{ auth.user?.displayName }}</p></div><span class="setting-value">{{ auth.user?.username }}</span></div><el-button v-if="auth.canAdmin" type="primary" style="margin-top:22px" @click="pveVisible = true">配置 Proxmox 接入</el-button><p class="settings-footnote">在控制台检查连接并保存;原密钥不回显,留空可保留。</p></section><section v-else-if="section === 'accounts'" class="panel settings-panel"><AdministratorAccounts /></section><section v-else-if="section === 'permissions'" class="panel settings-panel"><div class="section-kicker">ACCESS CONTROL</div><h2>管理员权限</h2><p class="subtext">三种管理角色,按职责控制访问与操作</p><el-table :data="[{ name: '超级管理员', query: '允许', operate: '允许', assign: '允许' }, { name: '运维人员', query: '允许', operate: '允许', assign: '不允许' }, { name: '只读人员', query: '允许', operate: '不允许', assign: '不允许' }]" style="margin-top:26px"><el-table-column prop="name" label="角色" min-width="120" /><el-table-column prop="query" label="查看资源" min-width="110" /><el-table-column prop="operate" label="设备 / 桌面操作" min-width="145" /><el-table-column prop="assign" label="授权 / 接入" min-width="120" /></el-table><p class="settings-footnote">管理员账号与桌面使用者分开管理。超级管理员可在「管理员账号」维护账号、角色、启停和密码。</p></section><section v-else class="panel settings-panel"><div class="section-kicker">PLATFORM CAPABILITIES</div><h2>功能范围</h2><p class="subtext">当前已接通的能力与后续开发范围</p><div class="capability-group"><h3>当前可用</h3><div class="capability-grid"><span v-for="name in ['登录限流与角色权限', '管理员账号维护与密码修改', '计算资源同步', 'GPU 清单与虚拟机配置引用', '已有桌面纳管与电源管理', '桌面批量开关机、重启与逐台结果', '镜像模板登记与 PVE 克隆', '桌面池容量与成员管理', '桌面连接与规格管理', '关机快照创建、删除与手动还原', '终端注册、分组、停用与重新激活', '用户资料、启停与批量桌面授权', '会话状态、历史与重置', 'CSV 批量导入', '节点趋势与告警', '终端 CPU、内存、SoC 温度与历史趋势', '诊断日志采集', '终端策略版本、下发与应用回执', '任务跟踪与操作审计']" :key="name"><el-icon class="tone-ok"><CircleCheck /></el-icon>{{ name }}</span></div></div><div class="capability-group"><h3>待接入</h3><div class="capability-grid"><span v-for="name in planned" :key="name"><el-icon class="secondary"><Clock /></el-icon>{{ name }}</span></div></div></section></div></div>
|
||||
<div class="settings-layout"><nav class="panel settings-nav" aria-label="设置分类"><button v-for="item in sections" :key="item.id" :class="{ active: section === item.id }" :aria-pressed="section === item.id" @click="section = item.id"><el-icon :size="17"><component :is="item.icon" /></el-icon>{{ item.title }}</button></nav><div class="settings-content"><section v-if="section === 'platform'" class="panel settings-panel"><div class="section-kicker">PLATFORM CONNECTION</div><h2>平台接入</h2><p class="subtext">统一查看管理服务、计算资源与终端通道</p><div class="setting-row"><div><strong>运行环境</strong><p>使用独立数据库保存平台业务数据</p></div><el-tag :type="data.settings?.mode === 'demo' ? 'warning' : 'success'">{{ data.settings?.mode === 'demo' ? '演示环境' : '现场联调环境' }}</el-tag></div><div class="setting-row"><div><strong>Proxmox 计算平台</strong><p>连接状态以最近同步任务结果为准</p></div><span :class="data.settings?.pveConfigured ? 'tone-ok' : 'secondary'"><i class="health-dot" />{{ data.settings?.pveConfigured ? '已配置' : '尚未配置' }}</span></div><div class="setting-row"><div><strong>终端管理通道</strong><p>设备注册、心跳、命令领取与执行回执</p></div><span class="setting-value">HTTPS</span></div><div class="setting-row"><div><strong>业务数据存储</strong><p>账号、设备、授权关系、任务与审计</p></div><span class="setting-value">PostgreSQL</span></div><div class="setting-row"><div><strong>当前管理员</strong><p>{{ auth.user?.displayName }}</p></div><span class="setting-value">{{ auth.user?.username }}</span></div><el-button v-if="auth.canAdmin" type="primary" style="margin-top:22px" @click="pveVisible = true">配置 Proxmox 接入</el-button><p class="settings-footnote">在控制台检查连接并保存;原密钥不回显,留空可保留。</p></section><section v-else-if="section === 'accounts'" class="panel settings-panel"><AdministratorAccounts /></section><section v-else-if="section === 'permissions'" class="panel settings-panel"><div class="section-kicker">ACCESS CONTROL</div><h2>管理员权限</h2><p class="subtext">三种管理角色,按职责控制访问与操作</p><el-table :data="[{ name: '超级管理员', query: '允许', operate: '允许', assign: '允许' }, { name: '运维人员', query: '允许', operate: '允许', assign: '不允许' }, { name: '只读人员', query: '允许', operate: '不允许', assign: '不允许' }]" style="margin-top:26px"><el-table-column prop="name" label="角色" min-width="120" /><el-table-column prop="query" label="查看资源" min-width="110" /><el-table-column prop="operate" label="设备 / 桌面操作" min-width="145" /><el-table-column prop="assign" label="授权 / 接入" min-width="120" /></el-table><p class="settings-footnote">管理员账号与桌面使用者分开管理。超级管理员可在「管理员账号」维护账号、角色、启停和密码。</p></section><section v-else class="panel settings-panel"><div class="section-kicker">PLATFORM CAPABILITIES</div><h2>功能范围</h2><p class="subtext">当前已接通的能力与后续开发范围</p><div class="capability-group"><h3>当前可用</h3><div class="capability-grid"><span v-for="name in ['登录限流与角色权限', '管理员账号维护与密码修改', '计算资源同步', 'GPU 清单与虚拟机配置引用', '已有桌面纳管与电源管理', '桌面批量开关机、重启与逐台结果', '镜像模板登记与 PVE 克隆', '桌面池容量与成员管理', '桌面连接与规格管理', '关机快照创建、删除与手动还原', '终端注册、分组、停用与重新激活', '用户资料、启停与批量桌面授权', '会话状态、历史与重置', 'CSV 批量导入', '节点趋势与告警', '终端系统指标、历史与阈值告警', '诊断日志采集', '日志诊断关联与诊断包', '终端策略版本、下发与应用回执', '任务跟踪与操作审计']" :key="name"><el-icon class="tone-ok"><CircleCheck /></el-icon>{{ name }}</span></div></div><div class="capability-group"><h3>待接入</h3><div class="capability-grid"><span v-for="name in planned" :key="name"><el-icon class="secondary"><Clock /></el-icon>{{ name }}</span></div></div></section></div></div>
|
||||
<PveConnectionDialog v-model="pveVisible" />
|
||||
</template>
|
||||
<style scoped>
|
||||
|
||||
@@ -1,35 +1,14 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue'
|
||||
import { usePlatform } from '../stores/platform'
|
||||
import StatusTag from '../components/StatusTag.vue'
|
||||
import { api, errorMessage } from '../api'
|
||||
import { useAuth } from '../stores/auth'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { useAction } from '../composables/useAction'
|
||||
const { busy, run } = useAction()
|
||||
const auth = useAuth()
|
||||
async function downloadDiagnostics(id: string) {
|
||||
try {
|
||||
const diagnostic = await api.taskDiagnostics(id)
|
||||
const url = URL.createObjectURL(new Blob([JSON.stringify(diagnostic, null, 2)], { type: 'application/json' }))
|
||||
const link = document.createElement('a'); link.href = url; link.download = `${id}-diagnostics.json`; link.click(); URL.revokeObjectURL(url)
|
||||
} catch(e) { ElMessage.error(errorMessage(e)) }
|
||||
}
|
||||
const data = usePlatform(), tab = ref('tasks'), keyword = ref(''), status = ref(''), page = ref(1), selectedId = ref('')
|
||||
const selected = computed(() => data.tasks.find(t => t.id === selectedId.value))
|
||||
const labels: Record<string, string> = { 'batch-start': '批量开机提交', 'batch-shutdown': '批量关机提交', 'batch-reboot': '批量重启提交', reconcile_batch_power: '核对批量电源', 'snapshot-create': '创建快照', 'snapshot-delete': '删除快照', 'snapshot-rollback': '还原快照', reconcile_snapshot: '核对快照', 'configure-hardware': '调整 CPU/内存', 'expand-disk': '磁盘扩容', reconcile_hardware: '核对规格', save_pve_connection: '保存 PVE 接入', create_terminal_policy: '创建终端策略', deploy_terminal_policy: '下发终端策略', terminal_policy_applied: '策略应用成功', terminal_policy_failed: '策略应用失败', update_terminal: '更新终端资料', disable_terminal: '停用终端', reactivate_terminal: '重新激活终端', update_user: '更新用户资料', batch_grant_bindings: '批量分配桌面', batch_revoke_bindings: '批量撤销桌面', create_administrator: '新增管理员', update_administrator: '更新管理员', reset_administrator_password: '重置管理员密码', change_own_password: '修改本人密码', reconcile_clone: '核对克隆', clone: '克隆桌面', register_template: '登记模板', update_template: '更新模板', validate_template: '验证模板', save_pool: '保存桌面池', update_pool_members: '更新池成员', configure_desktop: '配置连接', start: '开机', shutdown: '正常关机', reboot: '重启', 'reset-session': '重置会话', 'collect-logs': '收集日志', sync: '同步资源', login: '登录', logout: '退出登录', create_user: '创建用户', enroll_terminal: '登记终端', update_bindings: '更新授权', import_desktop: '纳管桌面' }
|
||||
const filtered = computed(() => data.tasks.filter(t => `${t.targetName} ${t.id} ${t.actor}`.toLowerCase().includes(keyword.value.toLowerCase()) && (!status.value || t.status === status.value)))
|
||||
const rows = computed(() => filtered.value.slice((page.value - 1) * 10, page.value * 10))
|
||||
const auditFiltered = computed(() => data.audits.filter(a => `${a.actor} ${a.target} ${a.action}`.toLowerCase().includes(keyword.value.toLowerCase())))
|
||||
const auditRows = computed(() => auditFiltered.value.slice((page.value - 1) * 10, page.value * 10))
|
||||
import { ref } from 'vue'
|
||||
import AuditHistory from '../components/AuditHistory.vue'
|
||||
import TaskHistory from '../components/TaskHistory.vue'
|
||||
const tab = ref('tasks')
|
||||
</script>
|
||||
<template>
|
||||
<div class="page-heading"><div><h1>任务与审计</h1><p class="subtext">提交记录、执行回执和最终结果分开显示</p></div><el-button @click="data.refresh">刷新</el-button></div>
|
||||
<div class="page-heading"><div><h1>任务与审计</h1><p class="subtext">提交记录、执行回执和最终结果分开显示</p></div></div>
|
||||
<section class="panel">
|
||||
<el-tabs v-model="tab" @tab-change="page = 1; keyword = ''; status = ''"><el-tab-pane label="执行任务" name="tasks" /><el-tab-pane label="操作审计" name="audit" /></el-tabs><div class="toolbar"><el-input v-model="keyword" placeholder="搜索目标 / 操作者 / 标识" aria-label="搜索任务" clearable @input="page = 1" /><el-select v-if="tab === 'tasks'" v-model="status" aria-label="任务状态筛选" placeholder="全部任务状态" clearable @change="page = 1"><el-option v-for="s in [{ value: 'queued', label: '排队中' }, { value: 'running', label: '执行中' }, { value: 'success', label: '成功' }, { value: 'failed', label: '失败' }, { value: 'timeout', label: '结果未确认' }]" :key="s.value" :label="s.label" :value="s.value" /></el-select></div>
|
||||
<el-table v-if="tab === 'tasks'" :data="rows" empty-text="尚无执行任务"><el-table-column label="操作目标 / 任务" min-width="200"><template #default="{ row }"><el-button link type="primary" @click="selectedId = row.id">{{ row.targetName }}</el-button><div class="mono secondary">{{ row.id.slice(0, 18) }}…</div></template></el-table-column><el-table-column label="操作" width="110"><template #default="{ row }">{{ labels[row.action] || row.action }}</template></el-table-column><el-table-column label="状态" width="125"><template #default="{ row }"><StatusTag :value="row.status === 'running' ? '执行中' : row.status" /></template></el-table-column><el-table-column prop="actor" label="操作者" width="110" /><el-table-column label="提交时间" min-width="170"><template #default="{ row }">{{ new Date(row.createdAt).toLocaleString('zh-CN') }}</template></el-table-column><el-table-column prop="message" label="执行结果" min-width="240" /></el-table>
|
||||
<el-table v-else :data="auditRows" empty-text="尚无审计记录"><el-table-column prop="actor" label="操作者" width="100" /><el-table-column label="操作" min-width="130"><template #default="{ row }">{{ labels[row.action] || row.action }}</template></el-table-column><el-table-column prop="target" label="对象" min-width="180" /><el-table-column label="结果" width="125"><template #default="{ row }"><StatusTag :value="row.result" /></template></el-table-column><el-table-column label="时间" min-width="175"><template #default="{ row }">{{ new Date(row.createdAt).toLocaleString('zh-CN') }}</template></el-table-column><el-table-column prop="requestId" label="请求标识" min-width="180" show-overflow-tooltip /></el-table>
|
||||
<el-pagination v-model:current-page="page" :total="tab === 'tasks' ? filtered.length : auditFiltered.length" :page-size="10" layout="total, prev, pager, next" />
|
||||
<el-tabs v-model="tab"><el-tab-pane label="执行任务" name="tasks" /><el-tab-pane label="操作审计" name="audit" /></el-tabs>
|
||||
<AuditHistory v-if="tab === 'audit'" />
|
||||
<TaskHistory v-else />
|
||||
</section>
|
||||
<el-drawer :model-value="!!selected" title="任务详情" size="580px" @close="selectedId = ''"><el-descriptions v-if="selected" :column="1" border><el-descriptions-item label="任务 ID"><span class="mono">{{ selected.id }}</span></el-descriptions-item><el-descriptions-item label="目标">{{ selected.targetName }}</el-descriptions-item><el-descriptions-item label="操作">{{ labels[selected.action] || selected.action }}</el-descriptions-item><el-descriptions-item label="状态"><StatusTag :value="selected.status === 'running' ? '执行中' : selected.status" /></el-descriptions-item><el-descriptions-item label="结果">{{ selected.message }}</el-descriptions-item><el-descriptions-item label="操作者">{{ selected.actor }}</el-descriptions-item><el-descriptions-item label="PVE 任务标识"><span class="mono">{{ selected.providerRef || '无' }}</span></el-descriptions-item><el-descriptions-item label="更新时间">{{ new Date(selected.updatedAt).toLocaleString('zh-CN') }}</el-descriptions-item></el-descriptions><el-button v-if="selected && auth.canOperate && selected.action === 'collect-logs' && selected.status === 'success'" style="margin-top:20px" @click="downloadDiagnostics(selected.id)">下载诊断日志</el-button><el-button v-if="selected?.kind === 'provision' && selected.status === 'timeout' && selected.providerRef && auth.canAdmin" :loading="busy" style="margin-top:20px" @click="run(() => api.reconcileProvision(selected!.id), '已提交核对,只查询原 PVE 任务')">核对克隆结果</el-button><el-button v-if="selected?.kind === 'hardware' && selected.status === 'timeout' && auth.canAdmin" :loading="busy" style="margin-top:20px" @click="run(() => api.reconcileHardware(selected!.id), '已核对实际规格,未重发修改')">核对规格结果</el-button><el-button v-if="selected?.kind === 'snapshot' && selected.status === 'timeout' && auth.canAdmin" :loading="busy" style="margin-top:20px" @click="run(() => api.reconcileSnapshot(selected!.id), '已核对原快照任务,未重发修改')">核对快照结果</el-button><el-button v-if="selected?.kind === 'batch-desktop' && selected.status === 'timeout' && auth.canOperate" :loading="busy" style="margin-top:20px" @click="run(() => api.reconcileBatchPower(selected!.id), '已核对原电源任务,未重发操作')">核对电源结果</el-button><p class="subtext" style="margin-top:22px">结果未确认时先核对实际设备状态,再决定是否重新提交。系统不会自动重放操作。</p></el-drawer>
|
||||
</template>
|
||||
@@ -40,7 +40,7 @@ async function reactivate(t: Terminal) {
|
||||
<template>
|
||||
<div class="page-heading"><div><h1>终端管理</h1><p class="subtext">设备身份、在线心跳与远程命令</p></div><div v-if="auth.canAdmin" class="heading-actions"><el-button @click="csvVisible = true">批量导入</el-button><el-button type="primary" @click="createVisible = true">登记终端</el-button></div></div>
|
||||
<section class="panel"><div class="toolbar"><el-input v-model="keyword" placeholder="搜索终端名称 / SN" aria-label="搜索终端" clearable @input="page = 1" /><el-select v-model="status" placeholder="全部设备状态" aria-label="终端设备状态筛选" clearable @change="page = 1"><el-option label="在线" value="online" /><el-option label="离线" value="offline" /><el-option label="待激活" value="unregistered" /><el-option label="停用" value="disabled" /></el-select><span class="secondary">共 {{ filtered.length }} 台</span></div><el-table :data="rows" empty-text="暂无终端,先登记设备并完成激活"><el-table-column label="终端 / SN" min-width="185"><template #default="{ row }"><el-button link type="primary" @click="selectedId = row.id">{{ row.name }}</el-button><div class="mono secondary">{{ row.sn }}</div></template></el-table-column><el-table-column prop="group" label="分组" width="100" /><el-table-column label="设备状态" width="100"><template #default="{ row }"><StatusTag :value="row.status" /></template></el-table-column><el-table-column label="当前连接" min-width="150"><template #default="{ row }">{{ desktopName(row.sessionDesktopId) }}</template></el-table-column><el-table-column label="最近心跳" min-width="170"><template #default="{ row }">{{ row.lastSeen ? new Date(row.lastSeen).toLocaleString('zh-CN') : '尚未注册' }}</template></el-table-column><el-table-column label="操作" min-width="280"><template #default="{ row }"><div class="actions"><el-button link type="primary" @click="selectedId = row.id">详情</el-button><el-button v-if="auth.canOperate && !disabled(row)" link type="primary" :disabled="busy || pending(row.id)" @click="command(row, 'reboot')">重启盒子</el-button><el-button v-if="auth.canAdmin" link type="primary" :disabled="busy" @click="edit(row)">编辑资料</el-button></div></template></el-table-column></el-table><el-pagination v-model:current-page="page" :total="filtered.length" :page-size="10" layout="total, prev, pager, next" /></section>
|
||||
<el-drawer :model-value="!!selected" title="终端详情" size="560px" @close="selectedId = ''"><template v-if="selected"><h2>{{ selected.name }}</h2><el-descriptions :column="1" border style="margin-top:22px"><el-descriptions-item label="设备 SN">{{ selected.sn }}</el-descriptions-item><el-descriptions-item label="设备状态"><StatusTag :value="selected.status" /></el-descriptions-item><el-descriptions-item label="Agent 版本">{{ selected.agentVersion || '尚未上报' }}</el-descriptions-item><el-descriptions-item label="配置版本">v{{ selected.configVersion }}</el-descriptions-item><el-descriptions-item label="当前连接">{{ desktopName(selected.sessionDesktopId) }}</el-descriptions-item><el-descriptions-item label="帧率">{{ selected.status === 'online' && selected.fps != null ? `${selected.fps} FPS` : '暂无数据' }}</el-descriptions-item><el-descriptions-item label="网络 RTT">{{ selected.status === 'online' && selected.rtt != null ? `${selected.rtt} ms` : '暂无数据' }}</el-descriptions-item></el-descriptions><el-button style="margin-top:18px" @click="metricsVisible = !metricsVisible">{{ metricsVisible ? '收起运行指标' : '查看运行指标' }}</el-button><TerminalMetrics v-if="metricsVisible" :terminal-id="selected.id" /><p class="subtext" style="margin:20px 0">重置会话只结束终端连接,不会还原或关机云桌面。网络 RTT 不等于整体输入延迟。</p><div class="actions" v-if="auth.canOperate && !disabled(selected)"><el-button :disabled="busy || pending(selected.id)" @click="command(selected, 'reboot')">重启盒子</el-button><el-button :disabled="busy || pending(selected.id)" @click="command(selected, 'reset-session')">重置会话</el-button><el-button :disabled="busy || pending(selected.id)" @click="command(selected, 'collect-logs')">收集日志</el-button></div><div v-if="auth.canAdmin" class="lifecycle-actions"><h3>设备管理</h3><p class="subtext">停用或重新激活会撤销旧凭据。请先结束活动会话并处理未完成命令;重新激活后需在设备上配置新密钥。</p><div class="actions"><el-button :disabled="busy" @click="edit(selected)">编辑资料</el-button><el-button v-if="!disabled(selected)" type="danger" plain :disabled="busy || pending(selected.id) || !!selected.sessionDesktopId" @click="disable(selected)">停用设备</el-button><el-button :disabled="busy || pending(selected.id) || !!selected.sessionDesktopId" @click="reactivate(selected)">重新激活</el-button></div></div></template></el-drawer>
|
||||
<el-drawer :model-value="!!selected" title="终端详情" size="560px" @close="selectedId = ''"><template v-if="selected"><h2>{{ selected.name }}</h2><router-link v-if="auth.canOperate" :to="{ path: '/diagnostics', query: { targetType: 'terminal', targetId: selected.id } }">查看此设备日志与诊断 →</router-link><el-descriptions :column="1" border style="margin-top:22px"><el-descriptions-item label="设备 SN">{{ selected.sn }}</el-descriptions-item><el-descriptions-item label="设备状态"><StatusTag :value="selected.status" /></el-descriptions-item><el-descriptions-item label="Agent 版本">{{ selected.agentVersion || '尚未上报' }}</el-descriptions-item><el-descriptions-item label="配置版本">v{{ selected.configVersion }}</el-descriptions-item><el-descriptions-item label="当前连接">{{ desktopName(selected.sessionDesktopId) }}</el-descriptions-item><el-descriptions-item label="帧率">{{ selected.status === 'online' && selected.fps != null ? `${selected.fps} FPS` : '暂无数据' }}</el-descriptions-item><el-descriptions-item label="网络 RTT">{{ selected.status === 'online' && selected.rtt != null ? `${selected.rtt} ms` : '暂无数据' }}</el-descriptions-item></el-descriptions><el-button style="margin-top:18px" @click="metricsVisible = !metricsVisible">{{ metricsVisible ? '收起运行指标' : '查看运行指标' }}</el-button><TerminalMetrics v-if="metricsVisible" :terminal-id="selected.id" /><p class="subtext" style="margin:20px 0">重置会话只结束终端连接,不会还原或关机云桌面。网络 RTT 不等于整体输入延迟。</p><div class="actions" v-if="auth.canOperate && !disabled(selected)"><el-button :disabled="busy || pending(selected.id)" @click="command(selected, 'reboot')">重启盒子</el-button><el-button :disabled="busy || pending(selected.id)" @click="command(selected, 'reset-session')">重置会话</el-button><el-button :disabled="busy || pending(selected.id)" @click="command(selected, 'collect-logs')">收集日志</el-button></div><div v-if="auth.canAdmin" class="lifecycle-actions"><h3>设备管理</h3><p class="subtext">停用或重新激活会撤销旧凭据。请先结束活动会话并处理未完成命令;重新激活后需在设备上配置新密钥。</p><div class="actions"><el-button :disabled="busy" @click="edit(selected)">编辑资料</el-button><el-button v-if="!disabled(selected)" type="danger" plain :disabled="busy || pending(selected.id) || !!selected.sessionDesktopId" @click="disable(selected)">停用设备</el-button><el-button :disabled="busy || pending(selected.id) || !!selected.sessionDesktopId" @click="reactivate(selected)">重新激活</el-button></div></div></template></el-drawer>
|
||||
<el-dialog v-model="createVisible" title="登记终端" width="480px"><el-form label-position="top" @submit.prevent="enroll"><el-form-item label="设备 SN" required><el-input v-model="form.sn" maxlength="100" /></el-form-item><el-form-item label="终端名称" required><el-input v-model="form.name" maxlength="80" /></el-form-item><el-form-item label="分组"><el-input v-model="form.group" maxlength="80" /></el-form-item><div class="actions" style="justify-content:flex-end"><el-button @click="createVisible = false">取消</el-button><el-button type="primary" native-type="submit" :loading="busy" :disabled="!form.sn.trim() || !form.name.trim()">登记并生成激活信息</el-button></div></el-form></el-dialog>
|
||||
<el-dialog v-model="editVisible" title="编辑终端资料" width="480px" :close-on-click-modal="false" :show-close="!busy" :close-on-press-escape="!busy"><el-form label-position="top" :disabled="busy" @submit.prevent="saveTerminal"><el-form-item label="终端名称"><el-input v-model="editForm.name" maxlength="80" aria-label="编辑终端名称" /></el-form-item><el-form-item label="分组"><el-input v-model="editForm.group" maxlength="80" aria-label="编辑终端分组" /></el-form-item></el-form><template #footer><el-button :disabled="busy" @click="editVisible = false">取消</el-button><el-button type="primary" :loading="busy" :disabled="!editForm.name.trim()" @click="saveTerminal">保存终端资料</el-button></template></el-dialog>
|
||||
<el-dialog v-model="activationVisible" title="终端激活信息" width="530px" @closed="secret = ''"><p class="subtext" style="margin-bottom:16px">激活密钥只在此处显示一次,交给设备管理员配置。设备注册后即失效。</p><p class="subtext" style="margin-bottom:12px">设备 SN:{{ activationSN }}</p><div class="secret mono" data-testid="activation-secret">{{ secret }}</div><template #footer><el-button type="primary" @click="activationVisible = false">已保存,关闭</el-button></template></el-dialog>
|
||||
|
||||
Reference in new issue
Block a user