feat(frontend): 管理台按原型落地,新增独立消息检索页与演示数据开关

This commit is contained in:
2026-11-04 16:48:46 +08:00
parent 5432d61571
commit d804696fd0
35 changed files with 3903 additions and 633 deletions
+270 -66
View File
@@ -1,100 +1,304 @@
<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { RouterLink, RouterView, useRoute, useRouter } from 'vue-router'
import { api, getToken, setToken } from './api'
import { describeError, notify, toastState, hideToast } from './ui'
import { demoState } from './demo/config'
const route = useRoute()
const router = useRouter()
const user = ref(null)
const loadError = ref('')
const userError = ref(null)
const userLoading = ref(false)
const loggingOut = ref(false)
const instance = ref(null)
const searchText = ref('')
const menuOpen = ref(false)
const dark = ref(localStorage.getItem('qlinker.theme') === 'dark')
const navGroups = [
{
label: '工作空间',
items: [
{ to: '/dashboard', label: '工作台', icon: '▤' },
{ to: '/messages', label: '消息中心', icon: '◫' },
{ to: '/message-search', label: '消息检索', icon: '⌕' },
{ to: '/automation', label: '自动化中心', icon: '⌗' },
{ to: '/ai', label: 'AI 中心', icon: '✦' }
]
},
{
label: '连接与运维',
items: [
{ to: '/connections', label: '接入管理', icon: '⇄' },
{ to: '/ops', label: '运维中心', icon: '◉' },
{ to: '/logs', label: '日志中心', icon: '≡' }
]
},
{
label: '平台管理',
items: [
{ to: '/backup', label: '备份与恢复', icon: '⛁' },
{ to: '/security', label: '安全中心', icon: '⛨' },
{ to: '/settings', label: '系统设置', icon: '◌' }
]
}
]
const mobileNav = [
{ to: '/dashboard', label: '工作台', icon: '▤' },
{ to: '/messages', label: '消息', icon: '◫' },
{ to: '/automation', label: '自动化', icon: '⌗' },
{ to: '/ops', label: '运维', icon: '◉' },
{ to: '/settings', label: '设置', icon: '◌' }
]
const publicPage = computed(() => route.meta.public === true)
const initials = computed(() => (user.value?.displayName || user.value?.username || 'A').slice(0, 1).toUpperCase())
const instanceLabel = computed(() => {
if (instance.value?.instanceUid) return instance.value.instanceUid
return instance.value ? '实例未初始化' : '实例状态读取中'
})
const activePath = computed(() => route.path)
function applyTheme() {
document.documentElement.style.colorScheme = dark.value ? 'dark' : 'light'
}
function toggleTheme() {
dark.value = !dark.value
localStorage.setItem('qlinker.theme', dark.value ? 'dark' : 'light')
applyTheme()
}
async function loadUser() {
if (!getToken()) return
if (!getToken() || publicPage.value) return
userLoading.value = true
userError.value = null
try {
user.value = await api.me()
} catch (e) {
if (e.code === 'UNAUTHENTICATED') {
} catch (error) {
if (error.code === 'UNAUTHENTICATED' || error.httpStatus === 401) {
setToken('')
user.value = null
router.push('/login')
} else {
loadError.value = `${e.message}${e.requestId ? `(请求号 ${e.requestId})` : ''}`
userError.value = describeError(error)
}
} finally {
userLoading.value = false
}
}
async function loadInstance() {
try {
instance.value = await api.initialization()
} catch {
instance.value = null
}
}
async function logout() {
if (loggingOut.value) return
loggingOut.value = true
try {
await api.logout()
} catch {
// 退出接口失败也要清空本地令牌,避免停留在无效会话。
} finally {
setToken('')
user.value = null
loggingOut.value = false
menuOpen.value = false
router.push('/login')
}
}
onMounted(loadUser)
function submitSearch() {
const keyword = searchText.value.trim()
const query = keyword ? { keyword } : {}
router.push({ path: '/message-search', query })
}
function onKeydown(event) {
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'k') {
event.preventDefault()
document.getElementById('global-search-input')?.focus()
}
if (event.key === 'Escape') {
menuOpen.value = false
document.getElementById('global-search-input')?.blur()
}
}
function onDocumentClick(event) {
if (!event.target.closest('.top-actions')) menuOpen.value = false
}
watch(
() => route.path,
() => {
menuOpen.value = false
if (!publicPage.value && getToken() && !user.value) loadUser()
},
{ immediate: true }
)
watch(
() => route.meta.title,
(title) => {
document.title = title ? `${title} · QLinker` : 'QLinker 管理台'
},
{ immediate: true }
)
onMounted(() => {
applyTheme()
loadInstance()
window.addEventListener('keydown', onKeydown)
document.addEventListener('click', onDocumentClick)
})
onBeforeUnmount(() => {
window.removeEventListener('keydown', onKeydown)
document.removeEventListener('click', onDocumentClick)
})
</script>
<template>
<div class="layout">
<header class="topbar">
<span class="brand">QLinker 管理台</span>
<nav>
<RouterLink to="/overview">总览</RouterLink>
<RouterLink to="/bindings">NapCat 连接</RouterLink>
<RouterLink to="/messages">消息</RouterLink>
<RouterLink to="/send">发送</RouterLink>
</nav>
<div class="user">
<span v-if="user">{{ user.username }}</span>
<button v-if="user" class="ghost" @click="logout">退出登录</button>
<div v-if="publicPage" class="auth-shell">
<aside class="auth-brand">
<div class="brand">
<span class="logo">Q</span>
<div class="brand-text">
<strong>QLinker</strong>
<span>QQ 消息管理台</span>
</div>
</div>
</header>
<p v-if="loadError" class="error">{{ loadError }}</p>
<main>
<div class="auth-pitch">
<h1>独立部署的 QQ 消息管理实例</h1>
<p>NapCat 接入 · 可靠入库 · 统一发送 · 审计可追溯</p>
<ul class="auth-points">
<li><span></span>事件先可靠持久化,再进入异步处理</li>
<li><span></span>未知消息类型保留原始结构,不强行归一</li>
<li><span></span>发送经过两阶段确认,结果未知不自动重试</li>
</ul>
</div>
<p class="auth-foot">单管理员实例 · 每个实例拥有独立数据库与对象存储</p>
</aside>
<main class="auth-main">
<RouterView />
</main>
</div>
</template>
<style>
:root {
--bg: #f5f6f8;
--card: #ffffff;
--line: #dfe3e8;
--text: #1f2329;
--muted: #6b7280;
--danger: #c62828;
--ok: #2e7d32;
--warn: #ef6c00;
}
* { box-sizing: border-box; }
body { margin: 0; background: var(--bg); color: var(--text); font-family: system-ui, "Microsoft YaHei", sans-serif; }
.topbar { display: flex; align-items: center; gap: 24px; padding: 12px 20px; background: var(--card); border-bottom: 1px solid var(--line); }
.topbar .brand { font-weight: 700; }
.topbar nav { display: flex; gap: 16px; flex: 1; }
.topbar nav a { color: var(--muted); text-decoration: none; }
.topbar nav a.router-link-active { color: var(--text); font-weight: 600; }
.topbar .user { display: flex; align-items: center; gap: 12px; color: var(--muted); }
main { padding: 20px; max-width: 1200px; margin: 0 auto; }
.card { background: var(--card); border: 1px solid var(--line); border-radius: 8px; padding: 16px; margin-bottom: 16px; }
.card h2 { margin: 0 0 12px; font-size: 16px; }
.grid { display: grid; gap: 12px; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); }
.stat { background: var(--card); border: 1px solid var(--line); border-radius: 8px; padding: 14px; }
.stat .value { font-size: 22px; font-weight: 700; }
.stat .label { color: var(--muted); font-size: 13px; }
table { width: 100%; border-collapse: collapse; font-size: 14px; }
th, td { text-align: left; padding: 8px; border-bottom: 1px solid var(--line); }
th { color: var(--muted); font-weight: 500; }
button { padding: 7px 14px; border: 1px solid var(--line); border-radius: 6px; background: #1f6feb; color: #fff; cursor: pointer; }
button.ghost { background: transparent; color: var(--muted); }
button:disabled { opacity: 0.5; cursor: not-allowed; }
input, select, textarea { padding: 8px; border: 1px solid var(--line); border-radius: 6px; font: inherit; width: 100%; }
label { display: block; margin-bottom: 10px; font-size: 13px; color: var(--muted); }
label > span { display: block; margin-bottom: 4px; }
.error { color: var(--danger); font-size: 14px; }
.ok { color: var(--ok); font-size: 14px; }
.warn { color: var(--warn); font-size: 14px; }
.muted { color: var(--muted); font-size: 13px; }
.row { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; }
pre { background: #f3f4f6; padding: 10px; border-radius: 6px; overflow: auto; font-size: 12px; }
</style>
<div v-else class="app">
<header class="topbar">
<RouterLink to="/dashboard" class="brand" style="text-decoration: none">
<span class="logo">Q</span>
<div class="brand-text">
<strong>QLinker</strong>
<span>QQ 消息管理台</span>
</div>
</RouterLink>
<div class="instance" :title="instanceLabel">
<strong>当前实例</strong>
<span>{{ instanceLabel }}</span>
</div>
<form class="global-search" @submit.prevent="submitSearch">
<span aria-hidden="true">⌕</span>
<input
id="global-search-input"
v-model="searchText"
type="search"
placeholder="搜索消息摘要前缀(Ctrl+K)"
aria-label="全局消息检索"
/>
</form>
<div class="top-actions">
<button class="icon-btn" type="button" :title="dark ? '切换为浅色' : '切换为深色'" @click="toggleTheme">
{{ dark ? '☾' : '☀' }}
</button>
<button
class="icon-btn"
type="button"
title="通知中心未实现:后端未提供通知接口"
@click="notify('通知中心未实现', '后端 /api/v1 尚未提供通知接口,本按钮不代表真实告警。', 'info')"
>
⌁
</button>
<button class="avatar" type="button" aria-label="账号菜单" @click="menuOpen = !menuOpen">
{{ userLoading ? '…' : initials }}
</button>
<div v-if="menuOpen" class="dropdown">
<div class="dd-head">
<strong>{{ user?.displayName || user?.username || '未登录' }}</strong>
<span>{{ user?.username ? `@${user.username}` : '账号信息未加载' }}</span>
</div>
<RouterLink to="/settings" class="btn ghost sm" style="width: 100%">系统设置</RouterLink>
<button type="button" :disabled="loggingOut" @click="logout">
{{ loggingOut ? '正在退出…' : '退出登录' }}
</button>
</div>
</div>
</header>
<div class="shell">
<aside class="sidebar">
<nav v-for="group in navGroups" :key="group.label" class="nav-group" aria-label="主导航">
<div class="nav-label">{{ group.label }}</div>
<RouterLink
v-for="item in group.items"
:key="item.to"
:to="item.to"
class="nav-item"
:class="{ active: activePath === item.to }"
>
<span class="nav-icon" aria-hidden="true">{{ item.icon }}</span>
<span>{{ item.label }}</span>
</RouterLink>
</nav>
<div class="sidebar-bottom">
<strong>演示数据</strong>
<p v-if="demoState.enabled">当前开启,未实现页面显示标注过的演示数据。</p>
<p v-else>当前关闭,未实现页面整体显示「未开发 / 规划中」。</p>
<RouterLink class="btn sm block" to="/settings">前往开关</RouterLink>
</div>
</aside>
<main class="content">
<div v-if="userError" class="notice danger" role="alert" style="margin-bottom: 16px">
<div>
<strong>{{ userError.title }}</strong>
<div style="margin-top: 4px">{{ userError.message }}</div>
<div class="small-muted" style="margin-top: 4px">{{ userError.hint }}</div>
</div>
<button class="btn sm" type="button" @click="loadUser">重试</button>
</div>
<RouterView />
</main>
</div>
<nav class="mobile-nav" aria-label="移动端导航">
<RouterLink
v-for="item in mobileNav"
:key="item.to"
:to="item.to"
:class="{ active: activePath === item.to }"
style="text-decoration: none"
>
<span aria-hidden="true">{{ item.icon }}</span>
{{ item.label }}
</RouterLink>
</nav>
<div class="toast" :class="{ show: toastState.visible }" role="status">
<strong>{{ toastState.title }}</strong>
<span>{{ toastState.body }}</span>
<button class="link" type="button" style="margin-top: 8px" @click="hideToast">关闭</button>
</div>
</div>
</template>
+38 -9
View File
@@ -9,19 +9,45 @@ export function setToken(token) {
else localStorage.removeItem(TOKEN_KEY)
}
/** 后端统一响应:success/code/message/data/requestId。失败时抛出携带 code 与 requestId 的错误。 */
function buildQuery(params) {
const search = new URLSearchParams()
for (const [key, value] of Object.entries(params || {})) {
if (value === undefined || value === null || value === '' || value === 'all') continue
search.set(key, String(value))
}
const text = search.toString()
return text ? `?${text}` : ''
}
/**
* 后端统一响应:success/code/message/data/requestId。
* 失败时抛出携带 code、requestId、httpStatus 的错误,由 ui.describeError 统一转文案。
*/
export async function request(path, options = {}) {
const headers = { 'Content-Type': 'application/json', ...(options.headers || {}) }
const token = getToken()
if (token) headers.Authorization = `Bearer ${token}`
const response = await fetch(path, { ...options, headers })
let response
try {
response = await fetch(path, { ...options, headers })
} catch (e) {
const error = new Error('无法连接后端服务,请确认服务已启动或网络可用')
error.code = 'NETWORK_ERROR'
error.retryable = true
throw error
}
let body = null
try {
body = await response.json()
} catch {
throw new Error(`服务返回非 JSON 响应(HTTP ${response.status})`)
const error = new Error(`服务返回非 JSON 响应(HTTP ${response.status})`)
error.code = 'INVALID_RESPONSE'
error.httpStatus = response.status
throw error
}
if (!body || body.success !== true) {
const error = new Error(body?.message || `请求失败(HTTP ${response.status})`)
error.code = body?.code
@@ -47,6 +73,7 @@ export const api = {
me: () => request('/api/v1/auth/me'),
bindings: () => request('/api/v1/napcat-bindings'),
binding: (uid) => request(`/api/v1/napcat-bindings/${uid}`),
createBinding: (payload) => request('/api/v1/napcat-bindings', { method: 'POST', body: JSON.stringify(payload) }),
rotateToken: (uid, accessToken) =>
request(`/api/v1/napcat-bindings/${uid}/access-token`, {
@@ -55,13 +82,15 @@ export const api = {
}),
deactivateBinding: (uid) => request(`/api/v1/napcat-bindings/${uid}`, { method: 'DELETE' }),
messages: (params) => request(`/api/v1/messages?${new URLSearchParams(params)}`),
message: (uid) => request(`/api/v1/messages/${uid}`),
messages: (params) => request(`/api/v1/messages${buildQuery(params)}`),
message: (uid) => request(`/api/v1/messages/${encodeURIComponent(uid)}`),
conversations: (page = 1, pageSize = 50) =>
request(`/api/v1/messages/conversations${buildQuery({ page, pageSize })}`),
messageStats: () => request('/api/v1/messages/stats'),
mediaStats: () => request('/api/v1/media/stats'),
media: (uid) => request(`/api/v1/media/${uid}`),
mediaAccessUrl: (uid) => request(`/api/v1/media/${uid}/access-url`),
media: (uid) => request(`/api/v1/media/${encodeURIComponent(uid)}`),
mediaAccessUrl: (uid) => request(`/api/v1/media/${encodeURIComponent(uid)}/access-url`),
prepareText: (payload, idempotencyKey) =>
request('/api/v1/send/text', {
@@ -70,11 +99,11 @@ export const api = {
body: JSON.stringify(payload)
}),
executeSend: (uid, confirmToken) =>
request(`/api/v1/send/operations/${uid}/execute`, {
request(`/api/v1/send/operations/${encodeURIComponent(uid)}/execute`, {
method: 'POST',
body: JSON.stringify({ confirmToken })
}),
sendOperation: (uid) => request(`/api/v1/send/operations/${uid}`),
sendOperation: (uid) => request(`/api/v1/send/operations/${encodeURIComponent(uid)}`),
sendOperations: (limit = 50) => request(`/api/v1/send/operations?limit=${limit}`),
sendSummary: () => request('/api/v1/send/summary')
}
+64
View File
@@ -0,0 +1,64 @@
<script setup>
import { onBeforeUnmount, ref, watch } from 'vue'
const props = defineProps({
open: { type: Boolean, default: false },
title: { type: String, default: '确认操作' },
message: { type: String, default: '' },
hint: { type: String, default: '' },
confirmText: { type: String, default: '确认' },
cancelText: { type: String, default: '取消' },
tone: { type: String, default: 'primary' },
busy: { type: Boolean, default: false }
})
const emit = defineEmits(['confirm', 'cancel'])
const cardRef = ref(null)
function onKeydown(event) {
if (event.key === 'Escape' && props.open && !props.busy) emit('cancel')
}
watch(
() => props.open,
(open) => {
if (open) {
document.addEventListener('keydown', onKeydown)
requestAnimationFrame(() => cardRef.value?.focus())
} else {
document.removeEventListener('keydown', onKeydown)
}
},
{ immediate: true }
)
onBeforeUnmount(() => document.removeEventListener('keydown', onKeydown))
</script>
<template>
<Teleport to="body">
<div v-if="open" class="modal-backdrop show" @click.self="!busy && emit('cancel')">
<div ref="cardRef" class="modal" role="dialog" aria-modal="true" :aria-label="title" tabindex="-1">
<div class="modal-head">
<h3>{{ title }}</h3>
<button class="btn sm ghost" type="button" aria-label="关闭" :disabled="busy" @click="emit('cancel')">×</button>
</div>
<p v-if="message" style="margin: 0 0 10px">{{ message }}</p>
<p v-if="hint" class="small-muted" style="margin: 0 0 10px">{{ hint }}</p>
<slot />
<div class="modal-foot">
<button class="btn" type="button" :disabled="busy" @click="emit('cancel')">{{ cancelText }}</button>
<button
class="btn"
:class="tone === 'danger' ? 'danger' : 'primary'"
type="button"
:disabled="busy"
@click="emit('confirm')"
>
{{ busy ? '处理中…' : confirmText }}
</button>
</div>
</div>
</div>
</Teleport>
</template>
+3
View File
@@ -0,0 +1,3 @@
<template>
<span class="demo-badge" title="演示数据:仅用于界面预览,不代表真实业务状态">演示数据</span>
</template>
+45
View File
@@ -0,0 +1,45 @@
<script setup>
import { onBeforeUnmount, watch } from 'vue'
const props = defineProps({
open: { type: Boolean, default: false },
title: { type: String, default: '' },
subtitle: { type: String, default: '' }
})
const emit = defineEmits(['close'])
function onKeydown(event) {
if (event.key === 'Escape') emit('close')
}
watch(
() => props.open,
(open) => {
if (open) window.addEventListener('keydown', onKeydown)
else window.removeEventListener('keydown', onKeydown)
},
{ immediate: true }
)
onBeforeUnmount(() => window.removeEventListener('keydown', onKeydown))
</script>
<template>
<Teleport to="body">
<div v-if="open" class="drawer-backdrop" role="dialog" aria-modal="true" @click.self="$emit('close')">
<div class="drawer">
<div class="drawer-head">
<div>
<h3>{{ title }}</h3>
<p v-if="subtitle">{{ subtitle }}</p>
</div>
<button class="btn sm" type="button" @click="$emit('close')">关闭</button>
</div>
<div class="drawer-body">
<slot />
</div>
</div>
</div>
</Teleport>
</template>
+20
View File
@@ -0,0 +1,20 @@
<script setup>
defineProps({
kicker: { type: String, default: '' },
title: { type: String, required: true },
desc: { type: String, default: '' }
})
</script>
<template>
<header class="page-head">
<div>
<div v-if="kicker" class="eyebrow">{{ kicker }}</div>
<h1 class="page-title">{{ title }}</h1>
<p v-if="desc" class="subtitle">{{ desc }}</p>
</div>
<div v-if="$slots.actions" class="actions">
<slot name="actions" />
</div>
</header>
</template>
+54
View File
@@ -0,0 +1,54 @@
<script setup>
import { computed } from 'vue'
import { formatNumber } from '../ui'
const props = defineProps({
page: { type: Number, default: 1 },
pageSize: { type: Number, default: 20 },
total: { type: Number, default: 0 },
sizes: { type: Array, default: () => [10, 20, 50, 100] }
})
const emit = defineEmits(['change'])
const pageSizeSafe = computed(() => {
const size = Number(props.pageSize)
return size > 0 ? size : 20
})
const pages = computed(() => {
const total = Number(props.total) || 0
return Math.max(1, Math.ceil(total / pageSizeSafe.value))
})
const from = computed(() => {
if (props.total === 0) return 0
return (props.page - 1) * pageSizeSafe.value + 1
})
const to = computed(() => Math.min(props.page * pageSizeSafe.value, props.total))
function go(target) {
if (target < 1 || target > pages.value || target === props.page) return
emit('change', { page: target, pageSize: pageSizeSafe.value })
}
function changeSize(event) {
emit('change', { page: 1, pageSize: Number(event.target.value) })
}
</script>
<template>
<div class="pager">
<div class="pager-info">
共 {{ formatNumber(total) }} 条 · 第 {{ formatNumber(from) }}–{{ formatNumber(to) }} 条 · 第 {{ page }} / {{ pages }} 页
</div>
<div class="pager-actions">
<select :value="pageSize" aria-label="每页条数" @change="changeSize">
<option v-for="size in sizes" :key="size" :value="size">{{ size }} 条/页</option>
</select>
<button class="btn sm" type="button" :disabled="page <= 1" @click="go(page - 1)">上一页</button>
<button class="btn sm" type="button" :disabled="page >= pages" @click="go(page + 1)">下一页</button>
</div>
</div>
</template>
+31
View File
@@ -0,0 +1,31 @@
<script setup>
import { demoState, setDemoEnabled } from '../demo/config'
defineProps({
title: { type: String, default: '该页面尚未开发' },
summary: { type: String, default: '当前后端 /api/v1 尚未提供该页面所需接口,页面按设计说明保留信息架构,功能待后续实现。' },
deps: { type: Array, default: () => [] }
})
</script>
<template>
<section class="card">
<div class="state-block" style="border-style: solid">
<strong>{{ title }}</strong>
<p>{{ summary }}</p>
<ul v-if="deps.length" class="plan-deps">
<li v-for="item in deps" :key="item">{{ item }}</li>
</ul>
<div class="actions">
<button v-if="!demoState.enabled" class="btn primary sm" type="button" @click="setDemoEnabled(true)">
开启演示数据预览
</button>
<slot name="actions" />
</div>
</div>
</section>
</template>
<style scoped>
.plan-deps { margin: 4px 0 0; padding-left: 18px; text-align: left; color: var(--muted); font-size: 12px; line-height: 1.9; }
</style>
+40
View File
@@ -0,0 +1,40 @@
<script setup>
defineProps({
loading: { type: Boolean, default: false },
error: { type: Object, default: null },
empty: { type: Boolean, default: false },
emptyTitle: { type: String, default: '暂无数据' },
emptyText: { type: String, default: '' },
loadingText: { type: String, default: '正在读取…' }
})
defineEmits(['retry'])
</script>
<template>
<div v-if="loading" class="state-block">
<span class="spinner" aria-hidden="true"></span>
<span>{{ loadingText }}</span>
</div>
<div v-else-if="error" class="notice danger" role="alert">
<div>
<strong>{{ error.title }}</strong>
<div style="margin-top: 4px">{{ error.message }}</div>
<div v-if="error.hint" class="small-muted" style="margin-top: 4px">{{ error.hint }}</div>
<div v-if="error.code || error.requestId" class="small-muted" style="margin-top: 4px">
<span v-if="error.code">错误码 {{ error.code }}</span>
<span v-if="error.requestId"> · 请求 {{ error.requestId }}</span>
</div>
</div>
<button class="btn sm" type="button" @click="$emit('retry')">重试</button>
</div>
<div v-else-if="empty" class="state-block">
<strong>{{ emptyTitle }}</strong>
<p v-if="emptyText">{{ emptyText }}</p>
<slot name="empty-actions" />
</div>
<slot v-else />
</template>
+31
View File
@@ -0,0 +1,31 @@
<script setup>
import { computed } from 'vue'
import { formatNumber } from '../ui'
import DemoBadge from './DemoBadge.vue'
const props = defineProps({
label: { type: String, required: true },
value: { type: [String, Number], default: '—' },
foot: { type: String, default: '' },
icon: { type: String, default: '•' },
trend: { type: String, default: '' },
trendTone: { type: String, default: 'up' },
demo: { type: Boolean, default: false }
})
const shown = computed(() => (typeof props.value === 'number' ? formatNumber(props.value) : props.value || '—'))
</script>
<template>
<div class="card">
<div class="stat-top">
<span>{{ label }} <DemoBadge v-if="demo" /></span>
<span class="stat-icon">{{ icon }}</span>
</div>
<div class="stat-value">{{ shown }}</div>
<div class="stat-foot">
<span>{{ foot }}</span>
<span v-if="trend" :class="trendTone" style="margin-left: 6px">{{ trend }}</span>
</div>
</div>
</template>
+17
View File
@@ -0,0 +1,17 @@
<script setup>
import { computed } from 'vue'
import { statusTone } from '../ui'
const props = defineProps({
value: { type: String, default: '' },
label: { type: String, default: '' },
tone: { type: String, default: '' }
})
const text = computed(() => props.label || props.value || '—')
const cls = computed(() => props.tone || statusTone(props.value))
</script>
<template>
<span class="status" :class="cls">{{ text }}</span>
</template>
+23
View File
@@ -0,0 +1,23 @@
import { reactive } from 'vue'
/**
* 演示数据总开关。
*
* 默认开启,便于用 file:// 直接预览完整页面;设置 VITE_ENABLE_MOCK=false 构建后默认关闭。
* 运行时开关保存在 localStorage,关闭后未实现页面整体显示「未开发 / 规划中」,
* 已实现能力继续使用真实接口,不伪造任何成功状态。
*/
const STORAGE_KEY = 'qlinker.demo-enabled'
const envDefault = import.meta.env.VITE_ENABLE_MOCK !== 'false'
const stored = localStorage.getItem(STORAGE_KEY)
export const demoState = reactive({
enabled: stored === null ? envDefault : stored === 'true'
})
export function setDemoEnabled(value) {
demoState.enabled = Boolean(value)
localStorage.setItem(STORAGE_KEY, demoState.enabled ? 'true' : 'false')
}
export const MOCK_NOTE = '当前页面含演示数据,仅用于界面预览,不代表真实业务状态。'
+150
View File
@@ -0,0 +1,150 @@
/**
* 演示数据集(未实现能力的占位内容)。
* 规则:所有引用处必须同时渲染「演示数据」标识;不得与真实接口返回值混用;
* 关闭 MOCK_ENABLED 后这些数据不再渲染,页面回到「未开发 / 规划中」。
*/
export const PLANNED_DEPS = {
dashboard: ['/system/alerts 实时告警', '/messages/stats 今日与时间序列', '/automation/runs 执行统计', '/ai/calls 调用统计'],
automation: ['/automation/rules 规则与草稿', '/automation/rules/{id}/versions 版本', '/automation/debug-runs 调试', '/automation/runs 执行记录'],
ai: ['/ai/providers 与 /ai/providers/{id}/test', '/ai/capabilities', '/ai/calls 与成本统计'],
ops: ['/health 依赖分项(MySQL / MinIO / 队列 / 主机资源)', '/alerts 告警处理(确认 / 分派 / 静默 / 关闭)'],
logs: ['/logs 统一日志', '/traces/{traceId} 链路详情', '/export-tasks 导出任务'],
backup: ['/backups 备份与校验', '/restore-drills 恢复演练'],
security: ['/users /roles /tokens /approvals /audit-events', '紧急停止后端控制'],
settings: ['/settings 实例设置读写']
}
export const dashboardTrend24h = [
28, 36, 31, 44, 39, 58, 49, 65, 54, 75, 60, 84,
72, 62, 89, 70, 95, 80, 67, 88, 61, 75, 54, 68
]
export const dashboardTrend7d = [62, 74, 58, 83, 91, 76, 88]
export const dashboardAlerts = [
{ level: 'warning', title: 'NapCat-03 连接不稳定', detail: '连续重连 3 次 · 8 分钟前', status: '警告' },
{ level: 'error', title: '规则「群消息归档」执行失败', detail: '节点:文件上传 · 21 分钟前', status: '失败' },
{ level: 'success', title: '备份任务已完成', detail: '数据完整性检查通过 · 1 小时前', status: '已恢复' }
]
export const automationSummary = { successRate: 98.6, success: 1266, failed: 18, recent: '群消息智能分流' }
export const automationRules = [
{ name: '群消息智能分流', trigger: '收到群消息', lastRun: '09:44:12', successRate: '99.2%', status: '运行中', version: 'v2.1' },
{ name: '群消息归档', trigger: '收到群消息', lastRun: '09:42:08', successRate: '96.4%', status: '运行中', version: 'v1.3' },
{ name: '关键词自动回复', trigger: '关键词命中', lastRun: '09:31:46', successRate: '98.8%', status: '已停用', version: 'v1.0' }
]
export const automationNodes = [
{ id: 'trigger', kind: 'EVENT', title: '收到群消息', sub: '触发器', x: 18, y: 70 },
{ id: 'condition', kind: 'IF', title: '关键词判断', sub: '条件', x: 300, y: 70 },
{ id: 'ai', kind: 'LLM', title: 'AI 内容分类', sub: 'AI 调用', x: 582, y: 70 },
{ id: 'send', kind: 'SEND', title: '发送处理结果', sub: '动作', x: 864, y: 70 }
]
export const automationRuns = [
{ id: 'run_20261104_01', rule: '群消息智能分流', status: 'SUCCEEDED', startedAt: '09:44:12', duration: '860ms', node: '全部通过' },
{ id: 'run_20261104_02', rule: '群消息归档', status: 'FAILED', startedAt: '09:42:08', duration: '1.4s', node: '文件上传' },
{ id: 'run_20261104_03', rule: '关键词自动回复', status: 'SUCCEEDED', startedAt: '09:31:46', duration: '320ms', node: '全部通过' }
]
export const aiProviders = [
{ name: 'OpenAI 兼容', protocol: 'OpenAI Compatible', model: 'GPT-4.1', todayCalls: 328, budget: 92, status: '已启用', test: '成功 · 09:12' },
{ name: 'DeepSeek', protocol: 'OpenAI Compatible', model: 'V3 / R1', todayCalls: 241, budget: 86, status: '已启用', test: '成功 · 08:58' },
{ name: 'Qwen', protocol: 'OpenAI Compatible', model: 'Plus', todayCalls: 73, budget: 64, status: '已启用', test: '成功 · 08:40' }
]
export const aiCapabilities = [
{ name: '消息智能分类', model: 'GPT-4.1', enabled: true, desc: '按规则对入站消息打标签' },
{ name: '自动摘要', model: 'DeepSeek V3', enabled: true, desc: '群聊与长消息摘要' },
{ name: 'AI 回复建议', model: 'DeepSeek R1', enabled: true, desc: '生成建议草稿,不自动发送' },
{ name: '自动发送回复', model: '—', enabled: false, desc: '高风险:当前未启用' }
]
export const aiCalls = [
{ time: '09:43:20', capability: '消息智能分类', model: 'GPT-4.1', duration: '1.28s', tokens: '1,240', result: '成功' },
{ time: '09:38:12', capability: '自动摘要', model: 'DeepSeek V3', duration: '2.04s', tokens: '3,180', result: '成功' },
{ time: '09:26:44', capability: 'AI 回复建议', model: 'DeepSeek R1', duration: '3.10s', tokens: '2,460', result: '成功' },
{ time: '09:12:03', capability: '消息智能分类', model: 'Qwen Plus', duration: '1.62s', tokens: '980', result: '限流失败' },
{ time: '08:58:37', capability: '自动摘要', model: 'GPT-4.1', duration: '2.38s', tokens: '4,020', result: '成功' }
]
export const opsDependencies = [
{ name: 'QLinker API', status: '正常', latency: '86 ms' },
{ name: 'MySQL', status: '正常', latency: '12 ms' },
{ name: 'MinIO', status: '正常', latency: '24 ms' },
{ name: 'NapCat 连接', status: '部分异常', latency: '—' },
{ name: '任务队列', status: '正常', latency: '28 条积压' }
]
export const opsResources = [
{ name: 'CPU', value: '38%', width: 38 },
{ name: '内存', value: '62%', width: 62 },
{ name: '磁盘', value: '42%', width: 42 }
]
export const opsAlerts = [
{ level: 'warning', title: 'NapCat-03 连续重连', time: '09:36', status: '未确认' },
{ level: 'error', title: '规则执行失败:文件上传节点', time: '09:23', status: '未确认' },
{ level: 'info', title: '备份完整性校验通过', time: '08:40', status: '已关闭' }
]
export const logRows = [
{ time: '09:44:12', level: 'INFO', source: 'event.ingest', summary: '群消息事件已持久化', trace: 'trc_9f21', cost: '12 ms' },
{ time: '09:42:18', level: 'INFO', source: 'media.download', summary: '图片下载完成并写入对象存储', trace: 'trc_9f18', cost: '860 ms' },
{ time: '09:42:08', level: 'ERROR', source: 'automation.run', summary: '节点「文件上传」执行失败:对象存储超时', trace: 'trc_9f16', cost: '1.4 s' },
{ time: '09:38:12', level: 'INFO', source: 'ai.call', summary: '摘要调用完成,tokens=3180', trace: 'trc_9f12', cost: '2.04 s' },
{ time: '09:26:44', level: 'WARN', source: 'send.operation', summary: '发送结果未知,等待人工核实', trace: 'trc_9f09', cost: '5.0 s' },
{ time: '09:12:03', level: 'WARN', source: 'ai.call', summary: '供应商返回限流,已按策略降级', trace: 'trc_9f04', cost: '1.62 s' },
{ time: '08:58:37', level: 'INFO', source: 'napcat.connection', summary: '反向 WebSocket 连接恢复', trace: 'trc_9ef8', cost: '40 ms' },
{ time: '08:40:00', level: 'INFO', source: 'backup.task', summary: '数据库全量备份完成,校验通过', trace: 'trc_9ef1', cost: '6.2 s' }
]
export const backupPlans = [
{ name: '数据库全量', scope: '业务库', schedule: '每日 03:30', retention: '14 天', enabled: true },
{ name: '配置与规则', scope: '规则 / 设置', schedule: '每日 04:00', retention: '30 天', enabled: true },
{ name: '对象存储元数据', scope: 'MinIO 元数据', schedule: '每日 04:20', retention: '30 天', enabled: true },
{ name: '媒体文件', scope: 'MinIO 对象', schedule: '每周日 05:00', retention: '8 周', enabled: true }
]
export const backupRecords = [
{ time: '今天 08:40', scope: '数据库全量', type: '自动', size: '1.8 GB', verify: '校验通过' },
{ time: '今天 04:20', scope: '对象存储元数据', type: '自动', size: '246 MB', verify: '校验通过' },
{ time: '今天 04:00', scope: '配置与规则', type: '自动', size: '12 MB', verify: '校验通过' },
{ time: '昨天 03:30', scope: '数据库全量', type: '自动', size: '1.7 GB', verify: '校验通过' },
{ time: '昨天 05:00', scope: '媒体文件', type: '自动', size: '38 GB', verify: '校验通过' }
]
export const securityUsers = [
{ name: '王明', account: 'admin', role: '系统管理员', status: '启用', lastLogin: '09:02' },
{ name: '李静', account: 'ops_li', role: '运维管理员', status: '启用', lastLogin: '08:41' },
{ name: '陈晨', account: 'msg_chen', role: '消息运营', status: '启用', lastLogin: '08:20' }
]
export const securityRoles = [
{ name: '系统管理员', members: 2, scope: '全部资源', changed: '10-28' },
{ name: '运维管理员', members: 3, scope: '连接 / 运维 / 日志', changed: '10-21' },
{ name: '消息运营', members: 5, scope: '消息 / 发送 / 检索', changed: '10-12' }
]
export const securityTokens = [
{ name: 'napcat-ops', scope: 'NAPCAT_READ', expires: '2026-12-01', status: '有效' },
{ name: 'ci-readonly', scope: 'MESSAGE_READ', expires: '2026-11-09', status: '临期' },
{ name: 'legacy', scope: 'MESSAGE_READ', expires: '2026-10-01', status: '已过期' }
]
export const securityApprovals = [
{ title: '批量停用 3 个 QQ 账号', submitter: '李静', time: '09:41', risk: '高' },
{ title: '修改 AI 自动发送权限', submitter: '陈晨', time: '09:28', risk: '高' }
]
export const settingsValues = {
instanceName: '生产实例 · QL-01',
instanceCode: 'QL-01',
timezone: 'Asia/Shanghai',
retention: '365',
theme: 'system',
realtime: true,
mobileNotify: true
}
+38 -15
View File
@@ -1,24 +1,47 @@
import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import { createRouter, createWebHashHistory } from 'vue-router'
import App from './App.vue'
import BootstrapView from './views/BootstrapView.vue'
import LoginView from './views/LoginView.vue'
import OverviewView from './views/OverviewView.vue'
import BindingsView from './views/BindingsView.vue'
import MessagesView from './views/MessagesView.vue'
import SendView from './views/SendView.vue'
import { getToken } from './api'
import './styles/prototype.css'
import './styles/app.css'
import DashboardView from './views/DashboardView.vue'
import MessagesView from './views/MessagesView.vue'
import MessageSearchView from './views/MessageSearchView.vue'
import ConnectionsView from './views/ConnectionsView.vue'
import AutomationView from './views/AutomationView.vue'
import AiView from './views/AiView.vue'
import OpsView from './views/OpsView.vue'
import LogsView from './views/LogsView.vue'
import BackupView from './views/BackupView.vue'
import SecurityView from './views/SecurityView.vue'
import SettingsView from './views/SettingsView.vue'
import LoginView from './views/LoginView.vue'
import BootstrapView from './views/BootstrapView.vue'
// 使用 hash 路由:构建产物 dist/index.html 可被 file:// 直接打开预览,
// 部署到任意子路径时也不需要额外的服务端路由重写。
const router = createRouter({
history: createWebHistory(),
history: createWebHashHistory(),
routes: [
{ path: '/', redirect: '/overview' },
{ path: '/bootstrap', component: BootstrapView, meta: { public: true } },
{ path: '/login', component: LoginView, meta: { public: true } },
{ path: '/overview', component: OverviewView },
{ path: '/bindings', component: BindingsView },
{ path: '/messages', component: MessagesView },
{ path: '/send', component: SendView }
{ path: '/', redirect: '/dashboard' },
{ path: '/bootstrap', component: BootstrapView, meta: { public: true, title: '首次初始化' } },
{ path: '/login', component: LoginView, meta: { public: true, title: '管理员登录' } },
{ path: '/dashboard', component: DashboardView, meta: { title: '工作台', group: '工作空间' } },
{ path: '/messages', component: MessagesView, meta: { title: '消息中心', group: '工作空间' } },
{ path: '/message-search', component: MessageSearchView, meta: { title: '消息检索', group: '工作空间' } },
{ path: '/connections', component: ConnectionsView, meta: { title: '接入管理', group: '工作空间' } },
{ path: '/automation', component: AutomationView, meta: { title: '自动化规则', group: '工作空间' } },
{ path: '/ai', component: AiView, meta: { title: 'AI 能力', group: '工作空间' } },
{ path: '/ops', component: OpsView, meta: { title: '运维监控', group: '工作空间' } },
{ path: '/logs', component: LogsView, meta: { title: '日志中心', group: '工作空间' } },
{ path: '/backup', component: BackupView, meta: { title: '备份与恢复', group: '平台管理' } },
{ path: '/security', component: SecurityView, meta: { title: '安全中心', group: '平台管理' } },
{ path: '/settings', component: SettingsView, meta: { title: '系统设置', group: '平台管理' } },
{ path: '/:pathMatch(.*)*', redirect: '/dashboard' }
]
})
+218
View File
@@ -0,0 +1,218 @@
/* 在原型 token 之上补齐语义变量与新增组件;所有页面共用同一套颜色与排版。 */
:root {
--line: light-dark(#e5e9f2, #273247);
--line-soft: light-dark(#edf0f5, #253147);
--line-strong: light-dark(#dce2ed, #3a465d);
--muted: light-dark(#8792a7, #9aa7bd);
--muted-strong: light-dark(#6b788f, #b3bed0);
--card-bg: light-dark(#ffffff, #121b2b);
--field-bg: light-dark(#ffffff, #172235);
--soft-bg: light-dark(#f8faff, #182337);
--primary-soft: light-dark(#eaf0ff, #1c2d52);
--danger: #d94841;
--success: #13865c;
}
body { min-height: 100vh; }
a { color: inherit; }
button:disabled { cursor: not-allowed; opacity: .55; }
.brand-text { display: flex; flex-direction: column; line-height: 1.15; }
.brand-text strong { font-size: 18px; letter-spacing: -.4px; }
.brand-text span { font-size: 11px; color: var(--muted); font-weight: 500; letter-spacing: 0; }
.nav-group { display: flex; flex-direction: column; gap: 3px; }
.nav-item .nav-meta { margin-left: auto; font-size: 10px; color: var(--muted); font-weight: 500; }
.nav-item.active .nav-meta { color: inherit; }
.btn.sm { padding: 6px 10px; font-size: 12px; border-radius: 8px; }
.btn.block { width: 100%; justify-content: center; }
.btn.ghost { border-color: transparent; background: transparent; }
.btn.ghost:hover { background: light-dark(#f2f5ff, #1d2a40); border-color: transparent; }
.topbar .instance strong { font-size: 12px; }
.topbar .instance span { font-size: 11px; color: var(--muted); }
.top-actions .avatar { cursor: pointer; }
.top-actions { position: relative; }
.dropdown {
position: absolute; right: 0; top: 46px; min-width: 210px; z-index: 15;
background: var(--card-bg); border: 1px solid var(--line); border-radius: 12px;
box-shadow: 0 18px 46px #10182822; padding: 8px;
}
.dropdown .dd-head { padding: 9px 10px 11px; border-bottom: 1px solid var(--line-soft); margin-bottom: 6px; }
.dropdown .dd-head strong { display: block; font-size: 13px; }
.dropdown .dd-head span { font-size: 11px; color: var(--muted); }
.dropdown button {
display: flex; width: 100%; gap: 8px; align-items: center; padding: 9px 10px;
border: 0; background: transparent; color: inherit; border-radius: 8px; text-align: left;
}
.dropdown button:hover { background: light-dark(#f2f5ff, #1d2a40); }
.demo-badge {
display: inline-flex; align-items: center; gap: 4px; padding: 2px 7px; border-radius: 6px;
background: light-dark(#fff5df, #3d2c13); color: #b7791f; font-size: 10px; font-weight: 700;
border: 1px solid light-dark(#f5e2b8, #5a431c); white-space: nowrap;
}
.demo-banner {
display: flex; gap: 10px; align-items: center; flex-wrap: wrap; margin: -6px 0 18px;
padding: 10px 13px; border-radius: 10px; font-size: 12px;
background: light-dark(#fffaf0, #2c2414); border: 1px solid light-dark(#f3e3c3, #4a3b1c); color: #9a7320;
}
.demo-banner .btn { margin-left: auto; }
.notice {
border: 1px solid light-dark(#dbe3ff, #314a7a); background: light-dark(#f4f7ff, #1a2b4d);
color: light-dark(#25409a, #b7c9ff); border-radius: 10px; padding: 11px 13px; font-size: 12px;
line-height: 1.6; display: flex; gap: 9px; align-items: flex-start;
}
.notice.warn { border-color: light-dark(#f3e3c3, #5a431c); background: light-dark(#fffaf0, #2c2414); color: #9a7320; }
.notice.danger { border-color: light-dark(#f3d2cf, #5c2a2a); background: light-dark(#fff5f4, #341d1f); color: #b23b34; }
.notice + .notice { margin-top: 10px; }
.notice .btn { margin-left: auto; flex-shrink: 0; }
.state-block {
display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 10px;
padding: 42px 20px; color: var(--muted); text-align: center; border-radius: 12px;
border: 1px dashed var(--line-strong); background: var(--soft-bg);
}
.state-block strong { color: inherit; font-size: 14px; }
.state-block p { margin: 0; max-width: 560px; line-height: 1.6; font-size: 12px; }
.skeleton { height: 14px; border-radius: 6px; background: light-dark(#eef1f7, #1f2b3d); animation: pulse 1.4s ease-in-out infinite; }
@keyframes pulse { 0%, 100% { opacity: .55 } 50% { opacity: 1 } }
.pager { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-top: 14px; flex-wrap: wrap; }
.pager .pager-info { font-size: 12px; color: var(--muted); }
.pager .pager-actions { display: flex; gap: 8px; align-items: center; }
.pager select { height: 34px; padding: 0 8px; border: 1px solid var(--line-strong); border-radius: 8px; background: var(--field-bg); color: inherit; }
.form-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px; }
.form-grid .full { grid-column: 1 / -1; }
.fld { display: flex; flex-direction: column; gap: 6px; min-width: 0; }
.fld > label { font-size: 12px; font-weight: 650; color: var(--muted-strong); }
.fld > label .req { color: var(--danger); margin-left: 3px; }
.fld .field { width: 100%; min-width: 0; }
.fld .field.invalid { border-color: #e0827c; box-shadow: 0 0 0 3px #d9484118; }
.fld .field-hint { margin: 0; font-size: 11px; color: var(--muted); line-height: 1.5; }
.fld .field-error { margin: 0; font-size: 11px; color: var(--danger); }
.fld textarea.field { height: auto; min-height: 96px; padding: 9px 11px; resize: vertical; line-height: 1.6; }
.field[disabled], .field:disabled { opacity: .6; }
.kv { display: flex; flex-direction: column; gap: 9px; }
.kv-row { display: flex; justify-content: space-between; gap: 14px; font-size: 12px; }
.kv-row span:first-child { color: var(--muted); flex-shrink: 0; }
.kv-row span:last-child { text-align: right; word-break: break-all; }
.drawer-backdrop {
position: fixed; inset: 0; background: #0b122080; z-index: 40;
display: flex; justify-content: flex-end;
}
.drawer {
width: min(720px, 100%); height: 100%; background: var(--card-bg);
border-left: 1px solid var(--line); display: flex; flex-direction: column;
animation: slide-in .18s ease;
}
@keyframes slide-in { from { transform: translateX(24px); opacity: .6 } to { transform: translateX(0); opacity: 1 } }
.drawer-head { padding: 19px 22px; border-bottom: 1px solid var(--line); display: flex; justify-content: space-between; gap: 12px; align-items: flex-start; }
.drawer-head h3 { margin: 0 0 5px; font-size: 17px; }
.drawer-head p { margin: 0; color: var(--muted); font-size: 12px; }
.drawer-body { padding: 18px 22px 32px; overflow: auto; flex: 1; }
.drawer-section { padding: 16px 0; border-bottom: 1px solid var(--line-soft); }
.drawer-section:last-child { border-bottom: 0; }
.drawer-section h4 { margin: 0 0 12px; font-size: 13px; display: flex; align-items: center; gap: 8px; }
.raw-pre {
margin: 0; padding: 12px; border-radius: 10px; overflow: auto; max-height: 320px;
background: light-dark(#f7f9fd, #0f1929); border: 1px solid var(--line);
font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 11px; line-height: 1.6;
white-space: pre-wrap; word-break: break-all;
}
.segment {
border: 1px solid var(--line); border-radius: 10px; padding: 10px 12px; margin-bottom: 8px;
background: light-dark(#fbfcff, #172235);
}
.segment .seg-head { display: flex; justify-content: space-between; gap: 10px; font-size: 12px; margin-bottom: 6px; }
.segment .seg-body { font-size: 12px; color: var(--muted-strong); word-break: break-all; line-height: 1.6; }
.segment img { max-width: 100%; border-radius: 8px; margin-top: 8px; display: block; }
.bar-chart { display: flex; align-items: flex-end; gap: 6px; height: 170px; padding-top: 8px; }
.bar-chart .bar { flex: 1; background: linear-gradient(180deg, #6d8dff, var(--site-primary)); border-radius: 5px 5px 2px 2px; min-height: 4px; position: relative; }
.bar-chart .bar:hover:after {
content: attr(data-label); position: absolute; left: 50%; bottom: calc(100% + 6px); transform: translateX(-50%);
background: #172033; color: #fff; font-size: 10px; padding: 3px 6px; border-radius: 5px; white-space: nowrap;
}
.chart-axis { display: flex; justify-content: space-between; font-size: 10px; color: var(--muted); margin-top: 8px; }
.auth-shell {
min-height: 100vh; display: grid; grid-template-columns: minmax(320px, 420px) minmax(0, 1fr);
background: light-dark(#f4f6fb, #0c1220);
}
.auth-brand {
padding: 38px 34px; background: light-dark(#172554, #0b1120); color: #fff;
display: flex; flex-direction: column; gap: 34px;
}
.auth-brand .brand-text strong { color: #fff; }
.auth-brand .brand-text span { color: #9fb0d8; }
.auth-brand .logo { background: #fff; color: var(--site-primary); box-shadow: none; }
.auth-pitch h1 { font-size: 26px; line-height: 1.35; letter-spacing: -.6px; margin: 0 0 12px; }
.auth-pitch p { color: #b8c6e6; line-height: 1.7; margin: 0 0 22px; font-size: 13px; }
.auth-points { list-style: none; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 12px; }
.auth-points li { display: flex; gap: 10px; font-size: 12px; color: #cdd8ef; line-height: 1.6; }
.auth-points li span { width: 6px; height: 6px; border-radius: 50%; background: #7c9aFF; margin-top: 7px; flex-shrink: 0; }
.auth-foot { margin: auto 0 0; font-size: 11px; color: #7f90b8; }
.auth-main { display: flex; align-items: center; justify-content: center; padding: 40px 24px; }
.auth-card {
width: min(460px, 100%); background: var(--card-bg); border: 1px solid var(--line);
border-radius: 16px; padding: 28px; box-shadow: 0 22px 60px #10182812;
}
.auth-card-head { margin-bottom: 20px; }
.auth-title { font-size: 23px; margin: 0 0 8px; letter-spacing: -.5px; }
.auth-sub { margin: 0; color: var(--muted); font-size: 12px; line-height: 1.6; }
.auth-form { display: flex; flex-direction: column; gap: 14px; margin-top: 16px; }
.auth-form .input {
height: 40px; border: 1px solid var(--line-strong); border-radius: 9px;
background: var(--field-bg); color: inherit; padding: 0 11px; outline: none; width: 100%;
}
.auth-form .input:focus { border-color: #8299ff; box-shadow: 0 0 0 3px #315efb1c; }
.auth-form .input.invalid { border-color: #e0827c; }
.auth-note { font-size: 11px; color: var(--muted); line-height: 1.7; margin: 16px 0 0; }
.auth-note a { color: var(--site-primary); }
.loading-row { display: flex; gap: 8px; align-items: center; color: var(--muted); font-size: 12px; padding: 10px 0; }
.spinner {
width: 14px; height: 14px; border: 2px solid var(--line-strong); border-top-color: var(--site-primary);
border-radius: 50%; animation: spin .8s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg) } }
.guide-list { display: flex; flex-direction: column; gap: 10px; margin: 4px 0 16px; }
.guide-step { display: flex; gap: 10px; font-size: 12px; color: var(--muted-strong); line-height: 1.55; }
.guide-step b { width: 20px; height: 20px; border-radius: 6px; background: var(--primary-soft); color: var(--site-primary); display: grid; place-items: center; flex-shrink: 0; font-size: 11px; }
.table-actions { display: flex; gap: 8px; flex-wrap: wrap; }
.tabs { overflow-x: auto; }
.tab:disabled { opacity: .55; cursor: not-allowed; }
.form-actions { display: flex; justify-content: flex-end; gap: 9px; margin-top: 4px; }
.filterbar .field { flex: 0 0 auto; }
.filterbar .searchfield { flex: 1 1 240px; }
.filterbar .full { flex-basis: 100%; }
.inline-warn { font-size: 11px; color: #b7791f; }
.switch { cursor: pointer; border: 0; }
.switch.off:after { background: #fff; }
.status.muted { color: #7a869a; background: light-dark(#f0f2f6, #252f40); }
.small-muted { font-size: 11px; color: var(--muted); }
.two-col > .card, .three-col > .card { min-width: 0; }
.card-head .card-title { display: flex; align-items: center; gap: 8px; }
.scroll-area { max-height: 340px; overflow: auto; }
@media (max-width: 1200px) {
.auth-shell { grid-template-columns: 1fr; }
.auth-brand { display: none; }
.form-grid { grid-template-columns: 1fr; }
}
@media (max-width: 760px) {
.auth-main { padding: 24px 13px; }
.auth-card { padding: 20px; border-radius: 12px; }
.drawer { width: 100%; }
.topbar .brand-text { display: none; }
.filterbar .field { flex: 1 1 120px; }
.pager { flex-direction: column; align-items: flex-start; }
}
File diff suppressed because one or more lines are too long
+144
View File
@@ -0,0 +1,144 @@
import { reactive } from 'vue'
/** 全局轻提示。只在真实操作返回后调用,禁止用它在请求前伪造成功。 */
export const toastState = reactive({ visible: false, title: '', body: '', tone: 'info' })
let toastTimer = 0
export function notify(title, body = '', tone = 'info') {
toastState.title = title
toastState.body = body
toastState.tone = tone
toastState.visible = true
window.clearTimeout(toastTimer)
toastTimer = window.setTimeout(() => {
toastState.visible = false
}, 4200)
}
export function hideToast() {
toastState.visible = false
}
export function describeError(error) {
const httpStatus = error?.httpStatus
const code = error?.code || ''
let title = '请求失败'
let hint = '请稍后重试;若持续失败,请查看服务端日志。'
if (code === 'NETWORK_ERROR') {
title = '无法连接后端'
hint = '后端可能未启动或网络不可达。当前页面不会显示任何伪造数据。'
} else if (code === 'UNAUTHENTICATED' || httpStatus === 401) {
title = '会话已过期'
hint = '请重新登录后继续操作。'
} else if (code === 'FORBIDDEN' || httpStatus === 403) {
title = '权限不足'
hint = '当前账号没有执行该操作的权限,如需授权请联系管理员。'
} else if (code === 'RESOURCE_NOT_FOUND' || httpStatus === 404) {
title = '资源不存在或不可见'
hint = '该对象可能已被删除,或不在当前实例的访问范围内。'
} else if (code === 'RESOURCE_CONFLICT' || httpStatus === 409) {
title = '状态冲突'
hint = '对象当前状态不允许该操作,请刷新后确认最新状态。'
} else if (code === 'VALIDATION_ERROR' || httpStatus === 400 || httpStatus === 422) {
title = '请求参数不合法'
hint = '请检查输入内容后重试。'
} else if (httpStatus === 429) {
title = '请求过于频繁'
hint = '已触发限流,请稍后再试。'
} else if (httpStatus >= 500) {
title = '服务异常'
hint = '后端处理失败,请稍后重试并查看服务端日志。'
}
return {
title,
message: error?.message || '未知错误',
hint,
code: error?.code || (httpStatus ? `HTTP_${httpStatus}` : ''),
requestId: error?.requestId || ''
}
}
export function formatTime(value) {
if (!value) return '—'
const date = new Date(value)
if (Number.isNaN(date.getTime())) return String(value)
const pad = (n) => String(n).padStart(2, '0')
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
}
export function formatShortTime(value) {
if (!value) return '—'
const date = new Date(value)
if (Number.isNaN(date.getTime())) return String(value)
const pad = (n) => String(n).padStart(2, '0')
return `${pad(date.getHours())}:${pad(date.getMinutes())}`
}
export function formatNumber(value) {
if (value === null || value === undefined || value === '') return '—'
const number = Number(value)
if (Number.isNaN(number)) return String(value)
return number.toLocaleString('zh-CN')
}
export function formatBytes(value) {
const number = Number(value)
if (!number || Number.isNaN(number)) return '—'
const units = ['B', 'KB', 'MB', 'GB', 'TB']
let size = number
let index = 0
while (size >= 1024 && index < units.length - 1) {
size /= 1024
index += 1
}
return `${size.toFixed(index === 0 ? 0 : 1)} ${units[index]}`
}
/** 连接状态/消息状态到语义色调;未知值一律灰,不猜成功。 */
export function statusTone(value) {
const text = String(value || '').toUpperCase()
if (/FAIL|ERROR|OFFLINE|DISCONNECT|UNBOUND|REJECT/.test(text)) return 'error'
if (/WARN|UNKNOWN|PENDING|RETRY|DOWNLOAD|SILENCED/.test(text)) return 'warning'
if (/CONNECT|ONLINE|SUCCESS|SUCCEED|STORED|NORMAL|BOUND|ACTIVE|UP/.test(text)) return 'success'
if (/RUN|PROCESS|SENDING|QUEUED/.test(text)) return 'info'
return 'muted'
}
export function connectionLabel(value) {
const map = {
forward_websocket: '正向 WebSocket',
reverse_websocket: '反向 WebSocket',
http_callback: 'HTTP 回调'
}
return map[String(value)] || String(value || '—')
}
export function directionLabel(value) {
const text = String(value || '').toUpperCase()
if (text === 'INBOUND') return '收到'
if (text === 'OUTBOUND') return '发出'
return value || '—'
}
export function typeLabel(value) {
const text = String(value || '').toUpperCase()
const map = {
TEXT: '文字',
IMAGE: '图片',
FILE: '文件',
RECORD: '语音',
VOICE: '语音',
VIDEO: '视频',
FACE: '表情',
STICKER: '表情',
REPLY: '引用',
FORWARD: '合并转发',
CARD: '卡片',
JSON: '卡片',
UNKNOWN: '未知'
}
return map[text] || String(value || '—')
}
+124
View File
@@ -0,0 +1,124 @@
<script setup>
import { ref } from 'vue'
import { demoState, MOCK_NOTE } from '../demo/config'
import { PLANNED_DEPS, aiCalls, aiCapabilities, aiProviders } from '../demo/planned'
import PageHead from '../components/PageHead.vue'
import DemoBadge from '../components/DemoBadge.vue'
import PlannedNotice from '../components/PlannedNotice.vue'
import StatusTag from '../components/StatusTag.vue'
const tab = ref('providers')
</script>
<template>
<PageHead kicker="工作空间" title="AI 能力" desc="服务商、模型能力、调用记录与成本。后端尚未提供 AI 接口,本页内容全部为演示数据。">
<template #actions>
<button class="btn" type="button" disabled title="后端未提供 AI 服务商创建接口">新增服务商</button>
<button class="btn primary" type="button" disabled title="后端未提供 AI 测试接口">打开测试台</button>
</template>
</PageHead>
<PlannedNotice
v-if="!demoState.enabled"
title="AI 能力尚未开发"
summary="服务商适配、能力声明、Tool Calling 与调用审计均依赖后端尚未提供的接口;关闭演示数据时页面不展示任何占位数据。"
:deps="PLANNED_DEPS.ai"
/>
<template v-else>
<div class="demo-banner">{{ MOCK_NOTE }}<DemoBadge /></div>
<div class="grid stats">
<div class="card">
<div class="stat-top"><span>已启用服务商<DemoBadge /></span><span class="stat-icon">✦</span></div>
<div class="stat-value">{{ aiProviders.length }}</div>
<div class="stat-foot">全部为 OpenAI 兼容协议</div>
</div>
<div class="card">
<div class="stat-top"><span>今日调用<DemoBadge /></span><span class="stat-icon">≡</span></div>
<div class="stat-value">{{ aiProviders.reduce((sum, item) => sum + item.todayCalls, 0) }}</div>
<div class="stat-foot">含失败与降级调用</div>
</div>
<div class="card">
<div class="stat-top"><span>本月预算使用<DemoBadge /></span><span class="stat-icon">%</span></div>
<div class="stat-value">81%</div>
<div class="stat-foot">超出阈值需人工确认</div>
</div>
<div class="card">
<div class="stat-top"><span>自动执行能力<DemoBadge /></span><span class="stat-icon">!</span></div>
<div class="stat-value">0</div>
<div class="stat-foot">高风险动作必须经人工确认</div>
</div>
</div>
<div class="tabs">
<button class="tab" :class="{ active: tab === 'providers' }" type="button" @click="tab = 'providers'">服务商</button>
<button class="tab" :class="{ active: tab === 'capabilities' }" type="button" @click="tab = 'capabilities'">能力</button>
<button class="tab" :class="{ active: tab === 'calls' }" type="button" @click="tab = 'calls'">调用记录</button>
</div>
<div v-if="tab === 'providers'" class="grid three-col">
<div v-for="provider in aiProviders" :key="provider.name" class="card" v-show="true">
<div class="card-head">
<h3 class="card-title">{{ provider.name }} <DemoBadge /></h3>
<StatusTag value="ACTIVE" :label="provider.status" />
</div>
<div class="kv">
<div class="kv-row"><span>协议</span><span>{{ provider.protocol }}</span></div>
<div class="kv-row"><span>模型</span><span>{{ provider.model }}</span></div>
<div class="kv-row"><span>今日调用</span><span>{{ provider.todayCalls }}</span></div>
<div class="kv-row"><span>预算使用</span><span>{{ provider.budget }}%</span></div>
<div class="kv-row"><span>最近测试</span><span>{{ provider.test }}</span></div>
</div>
<div class="progress" style="margin-top: 12px"><span :style="{ width: `${provider.budget}%` }"></span></div>
<div class="form-actions" style="margin-top: 12px">
<button class="btn sm" type="button" disabled title="后端未提供 AI 服务商测试接口">测试连接</button>
<button class="btn sm" type="button" disabled title="后端未提供 AI 服务商编辑接口">编辑</button>
</div>
</div>
</div>
<div v-else-if="tab === 'capabilities'" class="card">
<div class="card-head">
<h3 class="card-title">模型能力声明<DemoBadge /></h3>
<span class="small-muted">服务商宣传能力不等同于项目已验证能力</span>
</div>
<div class="table-wrap">
<table>
<thead><tr><th>能力</th><th>使用模型</th><th>说明</th><th>状态</th><th>操作</th></tr></thead>
<tbody>
<tr v-for="item in aiCapabilities" :key="item.name">
<td><strong>{{ item.name }}</strong></td>
<td>{{ item.model }}</td>
<td>{{ item.desc }}</td>
<td><StatusTag :value="item.enabled ? 'ACTIVE' : 'DISABLED'" :label="item.enabled ? '已启用' : '未启用'" /></td>
<td><button class="btn sm" type="button" disabled title="后端未提供能力开关接口">配置</button></td>
</tr>
</tbody>
</table>
</div>
</div>
<div v-else class="card">
<div class="card-head">
<h3 class="card-title">调用记录<DemoBadge /></h3>
<span class="small-muted">真实调用日志需后端 /ai/calls 接口</span>
</div>
<div class="table-wrap">
<table>
<thead><tr><th>时间</th><th>能力</th><th>模型</th><th>耗时</th><th>Token</th><th>结果</th></tr></thead>
<tbody>
<tr v-for="call in aiCalls" :key="`${call.time}-${call.capability}`">
<td>{{ call.time }}</td>
<td>{{ call.capability }}</td>
<td>{{ call.model }}</td>
<td>{{ call.duration }}</td>
<td>{{ call.tokens }}</td>
<td><StatusTag :value="call.result === '成功' ? 'SUCCESS' : 'FAILED'" :label="call.result" /></td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
</template>
+133
View File
@@ -0,0 +1,133 @@
<script setup>
import { ref } from 'vue'
import { demoState, MOCK_NOTE } from '../demo/config'
import { PLANNED_DEPS, automationNodes, automationRules, automationRuns, automationSummary } from '../demo/planned'
import PageHead from '../components/PageHead.vue'
import DemoBadge from '../components/DemoBadge.vue'
import PlannedNotice from '../components/PlannedNotice.vue'
import StatusTag from '../components/StatusTag.vue'
const tab = ref('rules')
</script>
<template>
<PageHead kicker="工作空间" title="自动化" desc="规则、版本、节点编排与执行记录。后端尚未提供自动化接口,本页内容全部为演示数据。">
<template #actions>
<button class="btn" type="button" disabled title="后端未提供规则导入接口">导入规则</button>
<button class="btn primary" type="button" disabled title="后端未提供规则创建接口">新建规则</button>
</template>
</PageHead>
<PlannedNotice
v-if="!demoState.enabled"
title="自动化能力尚未开发"
summary="规则引擎、版本隔离、节点编排与执行记录均依赖后端尚未提供的接口。关闭演示数据时不展示任何占位业务数据。"
:deps="PLANNED_DEPS.automation"
/>
<template v-else>
<div class="demo-banner">{{ MOCK_NOTE }}<DemoBadge /></div>
<div class="grid stats">
<div class="card">
<div class="stat-top"><span>执行成功率<DemoBadge /></span><span class="stat-icon">%</span></div>
<div class="stat-value">{{ automationSummary.successRate }}%</div>
<div class="stat-foot">成功 {{ automationSummary.success }} · 失败 {{ automationSummary.failed }}</div>
</div>
<div class="card">
<div class="stat-top"><span>已发布规则<DemoBadge /></span><span class="stat-icon">⌗</span></div>
<div class="stat-value">{{ automationRules.length }}</div>
<div class="stat-foot">含 1 条已停用规则</div>
</div>
<div class="card">
<div class="stat-top"><span>今日执行<DemoBadge /></span><span class="stat-icon">≡</span></div>
<div class="stat-value">1,284</div>
<div class="stat-foot">最近执行「{{ automationSummary.recent }}」</div>
</div>
<div class="card">
<div class="stat-top"><span>高风险动作<DemoBadge /></span><span class="stat-icon">!</span></div>
<div class="stat-value">2</div>
<div class="stat-foot">需人工确认后才允许执行</div>
</div>
</div>
<div class="tabs">
<button class="tab" :class="{ active: tab === 'rules' }" type="button" @click="tab = 'rules'">规则</button>
<button class="tab" :class="{ active: tab === 'canvas' }" type="button" @click="tab = 'canvas'">节点编排</button>
<button class="tab" :class="{ active: tab === 'runs' }" type="button" @click="tab = 'runs'">执行记录</button>
</div>
<div v-if="tab === 'rules'" class="card">
<div class="card-head">
<h3 class="card-title">规则列表<DemoBadge /></h3>
<div class="actions">
<button class="btn sm" type="button" disabled title="后端未提供规则发布接口">发布</button>
<button class="btn sm" type="button" disabled title="后端未提供规则停用接口">停用</button>
</div>
</div>
<div class="table-wrap">
<table>
<thead>
<tr><th>规则</th><th>触发条件</th><th>版本</th><th>状态</th><th>成功率</th><th>最近执行</th><th>操作</th></tr>
</thead>
<tbody>
<tr v-for="rule in automationRules" :key="rule.name">
<td><strong>{{ rule.name }}</strong></td>
<td>{{ rule.trigger }}</td>
<td>{{ rule.version }}</td>
<td><StatusTag :value="rule.status === '运行中' ? 'ACTIVE' : 'DISABLED'" :label="rule.status" /></td>
<td>{{ rule.successRate }}</td>
<td>{{ rule.lastRun }}</td>
<td>
<div class="table-actions">
<button class="btn sm" type="button" disabled title="后端未提供规则编辑接口">编辑</button>
<button class="btn sm" type="button" disabled title="后端未提供规则调试接口">调试</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div v-else-if="tab === 'canvas'" class="card">
<div class="card-head">
<h3 class="card-title">节点编排 · 群消息智能分流<DemoBadge /></h3>
<button class="btn sm" type="button" disabled title="后端未提供编排保存接口">保存草稿</button>
</div>
<div class="node-canvas">
<div v-for="node in automationNodes" :key="node.id" class="node" :style="{ left: `${node.x}px`, top: `${node.y}px` }">
<span class="node-kind">{{ node.kind }}</span>
<strong>{{ node.title }}</strong>
<small>{{ node.sub }}</small>
</div>
</div>
<p class="small-muted" style="margin-top: 10px">节点位置与连线的编辑能力待后端提供规则草稿与版本接口后实现。</p>
</div>
<div v-else class="card">
<div class="card-head">
<h3 class="card-title">执行记录<DemoBadge /></h3>
<span class="small-muted">仅演示,真实执行记录后端未提供</span>
</div>
<div class="table-wrap">
<table>
<thead>
<tr><th>任务</th><th>规则</th><th>开始时间</th><th>耗时</th><th>节点结果</th><th>状态</th><th>操作</th></tr>
</thead>
<tbody>
<tr v-for="run in automationRuns" :key="run.id">
<td>{{ run.id }}</td>
<td>{{ run.rule }}</td>
<td>{{ run.startedAt }}</td>
<td>{{ run.duration }}</td>
<td>{{ run.node }}</td>
<td><StatusTag :value="run.status" :label="run.status" /></td>
<td><button class="btn sm" type="button" disabled title="后端未提供执行详情接口">查看步骤</button></td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
</template>
+103
View File
@@ -0,0 +1,103 @@
<script setup>
import { ref } from 'vue'
import { demoState, MOCK_NOTE } from '../demo/config'
import { PLANNED_DEPS, backupPlans, backupRecords } from '../demo/planned'
import PageHead from '../components/PageHead.vue'
import DemoBadge from '../components/DemoBadge.vue'
import PlannedNotice from '../components/PlannedNotice.vue'
import StatusTag from '../components/StatusTag.vue'
const tab = ref('plans')
</script>
<template>
<PageHead kicker="平台管理" title="备份与恢复" desc="备份策略、备份记录与恢复演练。后端尚未提供备份接口,本页内容全部为演示数据。">
<template #actions>
<button class="btn" type="button" disabled title="后端未提供恢复接口">恢复数据</button>
<button class="btn primary" type="button" disabled title="后端未提供立即备份接口">立即备份</button>
</template>
</PageHead>
<PlannedNotice
v-if="!demoState.enabled"
title="备份与恢复尚未开发"
summary="备份任务、完整性校验与恢复演练依赖后端尚未提供的接口。备份属于高风险操作,未实现前不提供任何触发入口。"
:deps="PLANNED_DEPS.backup"
/>
<template v-else>
<div class="demo-banner">{{ MOCK_NOTE }}<DemoBadge /></div>
<div class="grid stats">
<div class="card">
<div class="stat-top"><span>备份策略<DemoBadge /></span><span class="stat-icon">⛁</span></div>
<div class="stat-value">{{ backupPlans.length }}</div>
<div class="stat-foot">全部启用</div>
</div>
<div class="card">
<div class="stat-top"><span>最近备份<DemoBadge /></span><span class="stat-icon">◷</span></div>
<div class="stat-value">今天 08:40</div>
<div class="stat-foot">数据库全量 · 1.8 GB</div>
</div>
<div class="card">
<div class="stat-top"><span>完整性校验<DemoBadge /></span><span class="stat-icon">✓</span></div>
<div class="stat-value">通过</div>
<div class="stat-foot">最近 5 次全部通过</div>
</div>
<div class="card">
<div class="stat-top"><span>恢复演练<DemoBadge /></span><span class="stat-icon">↺</span></div>
<div class="stat-value">14 天前</div>
<div class="stat-foot">演练结果:通过</div>
</div>
</div>
<div class="tabs">
<button class="tab" :class="{ active: tab === 'plans' }" type="button" @click="tab = 'plans'">备份策略</button>
<button class="tab" :class="{ active: tab === 'records' }" type="button" @click="tab = 'records'">备份记录</button>
</div>
<div v-if="tab === 'plans'" class="card">
<div class="card-head">
<h3 class="card-title">备份策略<DemoBadge /></h3>
<button class="btn sm" type="button" disabled title="后端未提供备份策略创建接口">新建策略</button>
</div>
<div class="table-wrap">
<table>
<thead><tr><th>策略</th><th>范围</th><th>计划</th><th>保留</th><th>状态</th><th>操作</th></tr></thead>
<tbody>
<tr v-for="plan in backupPlans" :key="plan.name">
<td><strong>{{ plan.name }}</strong></td>
<td>{{ plan.scope }}</td>
<td>{{ plan.schedule }}</td>
<td>{{ plan.retention }}</td>
<td><StatusTag :value="plan.enabled ? 'ACTIVE' : 'DISABLED'" :label="plan.enabled ? '启用' : '停用'" /></td>
<td><button class="btn sm" type="button" disabled title="后端未提供备份策略编辑接口">编辑</button></td>
</tr>
</tbody>
</table>
</div>
</div>
<div v-else class="card">
<div class="card-head">
<h3 class="card-title">备份记录<DemoBadge /></h3>
<button class="btn sm" type="button" disabled title="后端未提供备份下载接口">下载</button>
</div>
<div class="table-wrap">
<table>
<thead><tr><th>时间</th><th>范围</th><th>方式</th><th>大小</th><th>校验</th><th>操作</th></tr></thead>
<tbody>
<tr v-for="record in backupRecords" :key="`${record.time}-${record.scope}`">
<td>{{ record.time }}</td>
<td>{{ record.scope }}</td>
<td>{{ record.type }}</td>
<td>{{ record.size }}</td>
<td><StatusTag value="SUCCESS" :label="record.verify" /></td>
<td><button class="btn sm" type="button" disabled title="后端未提供恢复接口">恢复</button></td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
</template>
-124
View File
@@ -1,124 +0,0 @@
<script setup>
import { ref, onMounted } from 'vue'
import { api } from '../api'
const rows = ref([])
const loading = ref(false)
const error = ref('')
const notice = ref('')
const form = ref({ displayName: '', endpoint: '', accessToken: '' })
const creating = ref(false)
const createError = ref('')
const rotating = ref('')
const rotateToken = ref('')
const rotateError = ref('')
async function load() {
loading.value = true
error.value = ''
try {
rows.value = await api.bindings()
} catch (e) {
error.value = `${e.message}${e.requestId ? `(请求号 ${e.requestId})` : ''}`
} finally {
loading.value = false
}
}
async function create() {
createError.value = ''
notice.value = ''
creating.value = true
try {
await api.createBinding({ ...form.value })
form.value = { displayName: '', endpoint: '', accessToken: '' }
notice.value = '绑定已创建。连接与在线状态将在总览页刷新后可见。'
await load()
} catch (e) {
createError.value = `${e.message}${e.requestId ? `(请求号 ${e.requestId})` : ''}`
} finally {
creating.value = false
}
}
async function rotate(bindingUid) {
rotateError.value = ''
try {
await api.rotateToken(bindingUid, rotateToken.value)
rotating.value = ''
rotateToken.value = ''
notice.value = '访问令牌已更新。'
await load()
} catch (e) {
rotateError.value = `${e.message}${e.requestId ? `(请求号 ${e.requestId})` : ''}`
}
}
async function deactivate(row) {
if (!window.confirm(`确认解绑「${row.displayName || row.bindingUid}」?历史消息与事件会保留。`)) return
error.value = ''
try {
await api.deactivateBinding(row.bindingUid)
await load()
} catch (e) {
error.value = `${e.message}${e.requestId ? `(请求号 ${e.requestId})` : ''}`
}
}
onMounted(load)
</script>
<template>
<div>
<div class="card">
<h2>新增 NapCat 绑定</h2>
<p class="muted">
采用正向 WebSocket:QLinker 主动连接 NapCat 的事件上报地址。同一 NapCat 实例最多保留一条有效绑定。
</p>
<form @submit.prevent="create">
<label><span>显示名称</span><input v-model="form.displayName" required /></label>
<label><span>连接地址(ws://…)</span><input v-model="form.endpoint" placeholder="ws://127.0.0.1:3001" required /></label>
<label><span>访问令牌</span><input v-model="form.accessToken" type="password" autocomplete="off" /></label>
<button type="submit" :disabled="creating">{{ creating ? '提交中…' : '创建绑定' }}</button>
<p v-if="createError" class="error">{{ createError }}</p>
</form>
<p v-if="notice" class="ok">{{ notice }}</p>
</div>
<div class="card">
<div class="row" style="justify-content: space-between;">
<h2 style="margin: 0;">绑定列表</h2>
<button class="ghost" :disabled="loading" @click="load">{{ loading ? '刷新中…' : '刷新' }}</button>
</div>
<p v-if="error" class="error">{{ error }}</p>
<table>
<thead>
<tr><th>名称</th><th>地址</th><th>绑定状态</th><th>连接状态</th><th>QQ 账号</th><th>凭据</th><th>操作</th></tr>
</thead>
<tbody>
<tr v-for="row in rows" :key="row.bindingUid">
<td>{{ row.displayName }}</td>
<td class="muted">{{ row.endpoint }}</td>
<td>{{ row.bindingStatus }}</td>
<td>{{ row.connectionStatus }}</td>
<td>{{ row.qqAccountId || '-' }}</td>
<td>{{ row.hasCredential ? '已保存' : '未设置' }}</td>
<td class="row">
<button v-if="rotating !== row.bindingUid" class="ghost" @click="rotating = row.bindingUid">轮换令牌</button>
<button class="ghost" @click="deactivate(row)">解绑</button>
</td>
</tr>
<tr v-if="!rows.length && !loading"><td colspan="7" class="muted">暂无绑定。</td></tr>
</tbody>
</table>
<div v-if="rotating" class="row" style="margin-top: 12px;">
<input v-model="rotateToken" type="password" placeholder="新的访问令牌" style="max-width: 320px;" />
<button @click="rotate(rotating)">确认轮换</button>
<button class="ghost" @click="rotating = ''; rotateToken = ''">取消</button>
</div>
<p v-if="rotateError" class="error">{{ rotateError }}</p>
</div>
</div>
</template>
+226 -40
View File
@@ -1,37 +1,89 @@
<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { computed, onMounted, ref } from 'vue'
import { RouterLink } from 'vue-router'
import { api } from '../api'
import { describeError } from '../ui'
const USERNAME_PATTERN = /^[A-Za-z0-9_.-]{3,64}$/
const router = useRouter()
const bootstrapToken = ref('')
const username = ref('')
const password = ref('')
const confirm = ref('')
const busy = ref(false)
const error = ref('')
const status = ref(null)
const statusLoading = ref(false)
const statusError = ref(null)
let statusSeq = 0
const form = ref({ bootstrapToken: '', username: '', password: '', confirmPassword: '' })
const errors = ref({})
const busy = ref(false)
const submitError = ref(null)
const success = ref(null)
const formEnabled = computed(() =>
Boolean(status.value && !status.value.administratorExists && status.value.bootstrapTokenActive)
)
const closed = computed(() => Boolean(status.value?.administratorExists))
const tokenUnavailable = computed(() =>
Boolean(status.value && !status.value.administratorExists && !status.value.bootstrapTokenActive)
)
const recoveryMessage = computed(() => {
const value = status.value?.recoveryRequired
if (!value) return ''
return typeof value === 'string' ? value : '实例初始化状态或资源身份不一致,可能无法正常读写数据。'
})
async function loadStatus() {
const seq = ++statusSeq
statusLoading.value = true
statusError.value = null
try {
status.value = await api.initialization()
} catch (e) {
error.value = e.message
const value = await api.initialization()
if (seq !== statusSeq) return
status.value = value || null
} catch (error) {
if (seq !== statusSeq) return
statusError.value = describeError(error)
} finally {
if (seq === statusSeq) statusLoading.value = false
}
}
async function submit() {
error.value = ''
if (password.value !== confirm.value) {
error.value = '两次输入的口令不一致'
return
function validate() {
const next = {}
if (!form.value.bootstrapToken.trim()) {
next.bootstrapToken = '请输入引导令牌。'
}
if (!USERNAME_PATTERN.test(form.value.username.trim())) {
next.username = '用户名需为 3–64 位字母、数字、下划线、点或连字符。'
}
if (form.value.password.length < 12) {
next.password = '口令至少 12 位。'
}
if (form.value.confirmPassword !== form.value.password) {
next.confirmPassword = '两次输入的口令不一致。'
}
errors.value = next
return Object.keys(next).length === 0
}
async function submit() {
if (busy.value || !formEnabled.value) return
submitError.value = null
if (!validate()) return
busy.value = true
try {
await api.bootstrap(bootstrapToken.value, username.value, password.value)
router.push('/login')
} catch (e) {
error.value = `${e.message}${e.requestId ? `(请求号 ${e.requestId})` : ''}`
const data = await api.bootstrap(
form.value.bootstrapToken.trim(),
form.value.username.trim(),
form.value.password
)
success.value = {
message: data?.message || '管理员已创建,引导令牌已永久失效。',
username: form.value.username.trim()
}
form.value = { bootstrapToken: '', username: '', password: '', confirmPassword: '' }
errors.value = {}
loadStatus()
} catch (error) {
submitError.value = describeError(error)
} finally {
busy.value = false
}
@@ -41,25 +93,159 @@ onMounted(loadStatus)
</script>
<template>
<div class="card" style="max-width: 460px; margin: 60px auto;">
<h2>首次初始化:创建唯一管理员</h2>
<p v-if="status && status.administratorExists" class="warn">
本实例已存在管理员,引导流程已永久关闭。请直接登录。
<div class="auth-card" style="max-width: 520px">
<div class="auth-card-head">
<p class="eyebrow">FIRST RUN</p>
<h1 class="auth-title">初始化管理员</h1>
<p class="auth-sub">首次启动专用。创建第一个管理员后,引导入口会永久关闭。</p>
</div>
<div v-if="success" class="notice">
<div>
<strong>管理员已创建</strong>
<p style="margin: 4px 0 0">{{ success.message }}</p>
<p class="small-muted" style="margin: 4px 0 0">
引导令牌已永久失效。请使用刚创建的管理员用户名与口令登录管理台。
</p>
</div>
<RouterLink class="btn sm" to="/login">前往登录</RouterLink>
</div>
<template v-else>
<div v-if="statusLoading" class="loading-row">
<span class="spinner" aria-hidden="true"></span>
正在读取初始化状态…
</div>
<div v-else-if="statusError" class="notice danger">
<div>
<strong>{{ statusError.title }}</strong>
<p style="margin: 4px 0 0">{{ statusError.message }}</p>
<p class="small-muted" style="margin: 4px 0 0">{{ statusError.hint }}</p>
</div>
<button class="btn sm" type="button" :disabled="statusLoading" @click="loadStatus">重试</button>
</div>
<template v-else-if="status">
<div v-if="closed" class="notice">
<div>
<strong>实例已完成初始化</strong>
<p style="margin: 4px 0 0">已存在管理员,引导入口已永久关闭,无法再次创建管理员。</p>
<p class="small-muted" style="margin: 4px 0 0">请返回登录页使用已有账号登录。</p>
</div>
<RouterLink class="btn sm" to="/login">返回登录</RouterLink>
</div>
<div v-else-if="tokenUnavailable" class="notice danger">
<div>
<strong>当前没有有效的引导令牌</strong>
<p style="margin: 4px 0 0">
实例尚未创建管理员,但引导令牌未签发或已失效,本页不会接受初始化请求。
</p>
<p class="small-muted" style="margin: 4px 0 0">
请查看实例启动日志或部署配置获取引导令牌,必要时按初始化流程重新签发后再刷新本页。
</p>
</div>
<button class="btn sm" type="button" :disabled="statusLoading" @click="loadStatus">刷新状态</button>
</div>
<div v-if="recoveryMessage && !closed && !tokenUnavailable" class="notice danger">
<div>
<strong>实例需要恢复</strong>
<p style="margin: 4px 0 0">{{ recoveryMessage }}</p>
<p class="small-muted" style="margin: 4px 0 0">
请先核实数据库与对象存储身份,不要在未确认的情况下重新初始化,以免旧数据被遗弃。
</p>
</div>
</div>
<template v-if="formEnabled">
<div class="guide-list">
<div class="guide-step"><b>1</b><span>从实例启动日志或部署配置中获取一次性引导令牌。</span></div>
<div class="guide-step"><b>2</b><span>设置管理员用户名与至少 12 位口令,口令需再次确认。</span></div>
<div class="guide-step"><b>3</b><span>创建成功后令牌永久失效,返回登录页使用新账号登录。</span></div>
</div>
<div v-if="submitError" class="notice danger">
<div>
<strong>{{ submitError.title }}</strong>
<p style="margin: 4px 0 0">{{ submitError.message }}</p>
<p class="small-muted" style="margin: 4px 0 0">{{ submitError.hint }}</p>
</div>
<button class="btn sm" type="button" :disabled="statusLoading" @click="loadStatus">
刷新初始化状态
</button>
</div>
<form class="auth-form" @submit.prevent="submit">
<div class="fld">
<label for="bootstrap-token">引导令牌<span class="req">*</span></label>
<input
id="bootstrap-token"
v-model="form.bootstrapToken"
class="field"
:class="{ invalid: errors.bootstrapToken }"
autocomplete="off"
placeholder="粘贴一次性引导令牌"
/>
<p v-if="errors.bootstrapToken" class="field-error">{{ errors.bootstrapToken }}</p>
<p v-else class="field-hint">令牌来自实例启动日志,仅在首次初始化时有效。</p>
</div>
<div class="fld">
<label for="bootstrap-username">管理员用户名<span class="req">*</span></label>
<input
id="bootstrap-username"
v-model="form.username"
class="field"
:class="{ invalid: errors.username }"
autocomplete="username"
maxlength="64"
placeholder="3–64 位字母、数字、下划线、点或连字符"
/>
<p v-if="errors.username" class="field-error">{{ errors.username }}</p>
</div>
<div class="fld">
<label for="bootstrap-password">管理员口令<span class="req">*</span></label>
<input
id="bootstrap-password"
v-model="form.password"
class="field"
:class="{ invalid: errors.password }"
type="password"
autocomplete="new-password"
placeholder="至少 12 位"
/>
<p v-if="errors.password" class="field-error">{{ errors.password }}</p>
<p v-else class="field-hint">口令由后端做强校验,前端提示不替代后端规则。</p>
</div>
<div class="fld">
<label for="bootstrap-confirm">确认口令<span class="req">*</span></label>
<input
id="bootstrap-confirm"
v-model="form.confirmPassword"
class="field"
:class="{ invalid: errors.confirmPassword }"
type="password"
autocomplete="new-password"
placeholder="再次输入口令"
/>
<p v-if="errors.confirmPassword" class="field-error">{{ errors.confirmPassword }}</p>
</div>
<button class="btn primary block" type="submit" :disabled="busy">
{{ busy ? '正在创建管理员…' : '创建管理员并关闭引导入口' }}
</button>
</form>
</template>
</template>
</template>
<p class="auth-note">
引导入口只允许创建第一个管理员;任何情况下都不应把真实引导令牌写入代码、日志或公开文档。
<RouterLink to="/login">返回登录</RouterLink>
</p>
<p v-else-if="status && !status.bootstrapTokenActive" class="warn">
当前没有有效引导令牌。请查看后端启动日志中的「首次初始化引导令牌」。
</p>
<p v-else class="muted">
引导令牌只输出一次且不可找回;创建管理员后令牌立即失效,无法再次创建管理员。
</p>
<form v-if="status && !status.administratorExists" @submit.prevent="submit">
<label><span>引导令牌</span><input v-model="bootstrapToken" required /></label>
<label><span>管理员用户名</span><input v-model="username" autocomplete="username" required /></label>
<label><span>口令</span><input v-model="password" type="password" autocomplete="new-password" required /></label>
<label><span>确认口令</span><input v-model="confirm" type="password" autocomplete="new-password" required /></label>
<button type="submit" :disabled="busy">{{ busy ? '提交中…' : '创建管理员' }}</button>
<p v-if="error" class="error">{{ error }}</p>
</form>
<p style="margin-top: 16px;"><RouterLink to="/login">返回登录</RouterLink></p>
</div>
</template>
+324
View File
@@ -0,0 +1,324 @@
<script setup>
import { computed, onMounted, ref } from 'vue'
import { api } from '../api'
import { connectionLabel, describeError, formatTime, notify } from '../ui'
import PageHead from '../components/PageHead.vue'
import SectionState from '../components/SectionState.vue'
import StatusTag from '../components/StatusTag.vue'
import DetailDrawer from '../components/DetailDrawer.vue'
import ConfirmDialog from '../components/ConfirmDialog.vue'
const items = ref([])
const loading = ref(false)
const error = ref(null)
const createOpen = ref(false)
const createForm = ref({ displayName: '', endpoint: 'ws://127.0.0.1:3001', accessToken: '' })
const createError = ref(null)
const creating = ref(false)
const rotateTarget = ref(null)
const rotateToken = ref('')
const rotateError = ref(null)
const rotating = ref(false)
const removeTarget = ref(null)
const removing = ref(false)
const removeError = ref(null)
const detail = ref(null)
const online = computed(() => items.value.filter((item) => /CONNECT|ONLINE/.test(String(item.connectionStatus || '').toUpperCase())).length)
const bound = computed(() => items.value.filter((item) => !/UNBOUND/.test(String(item.bindingStatus || '').toUpperCase())).length)
async function load() {
loading.value = true
error.value = null
try {
items.value = (await api.bindings()) || []
} catch (e) {
items.value = []
error.value = describeError(e)
} finally {
loading.value = false
}
}
function openCreate() {
createError.value = null
createForm.value = { displayName: '', endpoint: 'ws://127.0.0.1:3001', accessToken: '' }
createOpen.value = true
}
async function submitCreate() {
if (creating.value) return
createError.value = null
const endpoint = createForm.value.endpoint.trim()
if (!/^wss?:\/\/[^\s]+$/i.test(endpoint)) {
createError.value = { title: '连接地址不合法', message: '仅支持 ws:// 或 wss:// 正向 WebSocket 端点。', hint: '后端会再次校验,http/https 与本地文件协议都会被拒绝。' }
return
}
creating.value = true
try {
await api.createBinding({
displayName: createForm.value.displayName.trim() || null,
endpoint,
accessToken: createForm.value.accessToken.trim() || null
})
createOpen.value = false
notify('绑定已创建', '访问令牌只写不读,接口不会回显明文。', 'success')
await load()
} catch (e) {
createError.value = describeError(e)
} finally {
creating.value = false
}
}
function openRotate(item) {
rotateTarget.value = item
rotateToken.value = ''
rotateError.value = null
}
async function submitRotate() {
if (rotating.value) return
rotateError.value = null
if (!rotateToken.value.trim()) {
rotateError.value = { title: '访问令牌不能为空', message: '请输入新的访问令牌。', hint: '令牌不会在界面回显。' }
return
}
rotating.value = true
try {
await api.rotateToken(rotateTarget.value.bindingUid, rotateToken.value.trim())
rotateTarget.value = null
notify('令牌已更新', '后端未回显明文;正向 WS 握手不校验令牌,凭据是否生效只能靠事件到达确认。', 'success')
} catch (e) {
rotateError.value = describeError(e)
} finally {
rotating.value = false
}
}
async function confirmRemove() {
if (removing.value) return
removeError.value = null
removing.value = true
try {
await api.deactivateBinding(removeTarget.value.bindingUid)
notify('绑定已解绑', '仅停用绑定状态,历史消息与原始事件全部保留。', 'success')
removeTarget.value = null
await load()
} catch (e) {
removeError.value = describeError(e)
} finally {
removing.value = false
}
}
onMounted(load)
</script>
<template>
<PageHead kicker="连接与运维" title="接入管理" desc="一个 QLinker 可绑定多个 NapCat 实例;访问令牌只写不读,任何接口都不回显明文。">
<template #actions>
<button class="btn" type="button" :disabled="loading" @click="load">{{ loading ? '刷新中…' : '刷新' }}</button>
<button class="btn" type="button" disabled title="后端未提供连接测试接口">测试连接</button>
<button class="btn" type="button" disabled title="后端未提供批量导入接口">批量导入</button>
<button class="btn primary" type="button" @click="openCreate">新增绑定</button>
</template>
</PageHead>
<div class="grid stats">
<div class="card">
<div class="stat-top"><span>绑定总数</span><span class="stat-icon">⇄</span></div>
<div class="stat-value">{{ items.length }}</div>
<div class="stat-foot">有效绑定 {{ bound }} 条</div>
</div>
<div class="card">
<div class="stat-top"><span>在线连接</span><span class="stat-icon">◉</span></div>
<div class="stat-value">{{ online }}</div>
<div class="stat-foot">连接状态由 NapCat 上报</div>
</div>
<div class="card">
<div class="stat-top"><span>轮换令牌</span><span class="stat-icon">⌘</span></div>
<div class="stat-value">—</div>
<div class="stat-foot">后端未提供令牌轮换次数统计</div>
</div>
<div class="card">
<div class="stat-top"><span>今日消息</span><span class="stat-icon">◫</span></div>
<div class="stat-value">—</div>
<div class="stat-foot">后端未提供按绑定的今日统计</div>
</div>
</div>
<div class="notice" style="margin-bottom: 16px">
绑定只支持正向 WebSocket(accessType 固定 forward_websocket)。QQ 账号、NapCat 版本、最近事件由 NapCat 上报后回填,未上报时显示「—」。
</div>
<div class="card">
<div class="card-head">
<h3 class="card-title">绑定关系</h3>
<div class="actions">
<button class="btn sm" type="button" disabled title="后端未提供重命名接口">编辑名称</button>
<button class="btn sm" type="button" disabled title="后端未提供批量导出接口">导出</button>
</div>
</div>
<SectionState
:loading="loading"
:error="error"
:empty="!loading && !error && !items.length"
empty-title="尚未绑定 NapCat"
empty-text="新增一个 ws:// 或 wss:// 正向 WebSocket 端点后,事件到达即会写入原始事件与标准化消息。"
@retry="load"
>
<template #empty-actions>
<button class="btn primary sm" type="button" @click="openCreate">新增绑定</button>
</template>
<div class="table-wrap">
<table>
<thead>
<tr>
<th>绑定 / 实例</th>
<th>QQ 账号</th>
<th>连接</th>
<th>状态</th>
<th>NapCat 版本</th>
<th>最近事件</th>
<th>最近错误</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="item in items" :key="item.bindingUid">
<td>
<div class="identity">
<span class="mini-avatar">{{ (item.displayName || 'N').slice(0, 1) }}</span>
<div>
<strong>{{ item.displayName || '—' }}</strong>
<span>{{ item.endpoint || '—' }}</span>
</div>
</div>
</td>
<td>{{ item.qqAccountId || '—' }}</td>
<td>
{{ connectionLabel(item.connectionType) }}
<div class="small-muted">令牌{{ item.hasCredential ? '已保存' : '未保存' }}</div>
</td>
<td>
<StatusTag :value="item.bindingStatus" :label="item.bindingStatus || '—'" />
<div style="margin-top: 4px"><StatusTag :value="item.connectionStatus" :label="item.connectionStatus || '—'" /></div>
</td>
<td>{{ item.napcatVersion || '—' }}</td>
<td>{{ formatTime(item.lastEventAt) }}</td>
<td>
<span v-if="item.lastErrorCode"> <span class="status error">{{ item.lastErrorCode }}</span></span>
<span v-else>—</span>
<div class="small-muted">{{ formatTime(item.lastErrorAt) }}</div>
</td>
<td>
<div class="table-actions">
<button class="btn sm" type="button" @click="detail = item">详情</button>
<button class="btn sm" type="button" @click="openRotate(item)">轮换令牌</button>
<button class="btn sm danger" type="button" @click="removeTarget = item">解绑</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</SectionState>
</div>
<Teleport to="body">
<div v-if="createOpen" class="modal-backdrop show" @click.self="!creating && (createOpen = false)">
<div class="modal" role="dialog" aria-modal="true">
<div class="modal-head">
<h3>新增 NapCat 绑定</h3>
<button class="btn sm ghost" type="button" :disabled="creating" @click="createOpen = false">×</button>
</div>
<div v-if="createError" class="notice danger" style="margin-bottom: 12px">
<div>
<strong>{{ createError.title }}</strong>
<div style="margin-top: 4px">{{ createError.message }}</div>
<div class="small-muted" style="margin-top: 4px">{{ createError.hint }}</div>
</div>
</div>
<div class="form-grid">
<div class="fld full">
<label for="binding-name">绑定名称</label>
<input id="binding-name" v-model="createForm.displayName" class="field" maxlength="100" placeholder="留空则使用端点主机名" />
<p class="field-hint">仅用于界面识别,不改变 NapCat 实例身份。</p>
</div>
<div class="fld full">
<label for="binding-endpoint">连接地址<span class="req">*</span></label>
<input id="binding-endpoint" v-model="createForm.endpoint" class="field" placeholder="ws://127.0.0.1:3001" />
<p class="field-hint">仅支持 ws:// 或 wss://,后端会拒绝 http/https 与用户信息。</p>
</div>
<div class="fld full">
<label for="binding-token">访问令牌</label>
<input id="binding-token" v-model="createForm.accessToken" class="field" type="password" autocomplete="off" placeholder="可选,保存后不回显" />
<p class="field-hint">令牌只写不读;正向 WS 握手不校验令牌,凭据错误只能靠事件到达确认。</p>
</div>
</div>
<div class="modal-foot">
<button class="btn" type="button" :disabled="creating" @click="createOpen = false">取消</button>
<button class="btn primary" type="button" :disabled="creating" @click="submitCreate">
{{ creating ? '正在创建…' : '创建绑定' }}
</button>
</div>
</div>
</div>
</Teleport>
<ConfirmDialog
:open="Boolean(rotateTarget)"
title="轮换访问令牌"
:message="rotateTarget ? `为「${rotateTarget.displayName || rotateTarget.bindingUid}」设置新的访问令牌。` : ''"
hint="后端不回显明文;NapCat 正向 WS 握手不校验令牌,凭据错误只能靠事件到达确认。"
confirm-text="保存新令牌"
:busy="rotating"
@confirm="submitRotate"
@cancel="rotateTarget = null"
>
<div class="fld" style="margin-bottom: 12px">
<label for="rotate-token">新访问令牌<span class="req">*</span></label>
<input id="rotate-token" v-model="rotateToken" class="field" type="password" autocomplete="off" placeholder="输入新令牌" />
<div v-if="rotateError" class="field-error">{{ rotateError.message }}</div>
</div>
</ConfirmDialog>
<ConfirmDialog
:open="Boolean(removeTarget)"
title="解绑 NapCat"
tone="danger"
:message="removeTarget ? `确认解绑「${removeTarget.displayName || removeTarget.bindingUid}」?` : ''"
hint="解绑只做状态标记(UNBOUND),不删除任何历史消息与原始事件。"
confirm-text="确认解绑"
:busy="removing"
@confirm="confirmRemove"
@cancel="removeTarget = null"
>
<div v-if="removeError" class="notice danger">{{ removeError.message }}</div>
</ConfirmDialog>
<DetailDrawer :open="Boolean(detail)" title="绑定详情" :subtitle="detail?.bindingUid" @close="detail = null">
<div v-if="detail" class="kv">
<div class="kv-row"><span>绑定标识</span><span>{{ detail.bindingUid }}</span></div>
<div class="kv-row"><span>实例标识</span><span>{{ detail.instanceUid || '—' }}</span></div>
<div class="kv-row"><span>显示名称</span><span>{{ detail.displayName || '—' }}</span></div>
<div class="kv-row"><span>连接方式</span><span>{{ connectionLabel(detail.connectionType) }}</span></div>
<div class="kv-row"><span>端点</span><span>{{ detail.endpoint || '—' }}</span></div>
<div class="kv-row"><span>绑定状态</span><span>{{ detail.bindingStatus || '—' }}</span></div>
<div class="kv-row"><span>连接状态</span><span>{{ detail.connectionStatus || '—' }}</span></div>
<div class="kv-row"><span>QQ 账号</span><span>{{ detail.qqAccountId || '—' }}</span></div>
<div class="kv-row"><span>NapCat 版本</span><span>{{ detail.napcatVersion || '—' }}</span></div>
<div class="kv-row"><span>令牌</span><span>{{ detail.hasCredential ? '已保存' : '未保存' }}</span></div>
<div class="kv-row"><span>最近连接</span><span>{{ formatTime(detail.lastConnectedAt) }}</span></div>
<div class="kv-row"><span>最近事件</span><span>{{ formatTime(detail.lastEventAt) }}</span></div>
<div class="kv-row"><span>最近错误</span><span>{{ detail.lastErrorCode || '—' }} · {{ formatTime(detail.lastErrorAt) }}</span></div>
</div>
</DetailDrawer>
</template>
+251
View File
@@ -0,0 +1,251 @@
<script setup>
import { computed, onMounted, ref } from 'vue'
import { RouterLink } from 'vue-router'
import { api } from '../api'
import { connectionLabel, describeError, formatNumber, formatTime, statusTone } from '../ui'
import PageHead from '../components/PageHead.vue'
import StatCard from '../components/StatCard.vue'
import SectionState from '../components/SectionState.vue'
import StatusTag from '../components/StatusTag.vue'
import DemoBadge from '../components/DemoBadge.vue'
import { demoState } from '../demo/config'
import { automationRules, automationSummary, dashboardTrend24h } from '../demo/planned'
const health = ref(null)
const loading = ref(false)
const error = ref(null)
const updatedAt = ref('')
const bindings = computed(() => health.value?.napcat?.items || [])
const connections = computed(() => health.value?.napcat?.connections || {})
const messages = computed(() => health.value?.messages || {})
const media = computed(() => health.value?.media || {})
const send = computed(() => health.value?.send || {})
const sendTotal = computed(() =>
['PENDING', 'RUNNING', 'SUCCEEDED', 'FAILED', 'UNKNOWN'].reduce((sum, key) => sum + (Number(send.value[key]) || 0), 0)
)
const attention = computed(() => {
const items = []
if (!health.value) return items
if (Number(messages.value.failedEvents) > 0) {
items.push({ level: 'error', title: `原始事件处理失败 ${formatNumber(messages.value.failedEvents)} 条`, detail: '需要查看运行日志并确认是否可重新处理' })
}
if (Number(messages.value.unprocessedEvents) > 0) {
items.push({ level: 'warning', title: `待处理事件 ${formatNumber(messages.value.unprocessedEvents)} 条`, detail: '事件已入库,异步处理尚未完成' })
}
if (Number(send.value.UNKNOWN) > 0) {
items.push({ level: 'warning', title: `发送结果未知 ${formatNumber(send.value.UNKNOWN)} 条`, detail: '上游可能已执行,禁止自动重试,需人工核实' })
}
if (Number(media.value.FAILED) > 0) {
items.push({ level: 'error', title: `媒体入库失败 ${formatNumber(media.value.FAILED)} 条`, detail: '图片/文件等媒体资源未成功保存到对象存储' })
}
if (Number(media.value.OBJECT_MISSING) > 0) {
items.push({ level: 'warning', title: `对象缺失 ${formatNumber(media.value.OBJECT_MISSING)} 条`, detail: '媒体元数据存在,但对象存储中找不到对应对象' })
}
return items
})
const maxTrend = computed(() => Math.max(1, ...dashboardTrend24h))
async function load() {
loading.value = true
error.value = null
try {
health.value = await api.healthDetail()
updatedAt.value = formatTime(new Date().toISOString())
} catch (e) {
health.value = null
error.value = describeError(e)
} finally {
loading.value = false
}
}
onMounted(load)
</script>
<template>
<PageHead kicker="工作空间" title="工作台" desc="实例运行概览:绑定连接、消息入库、待处理事件与发送状态均来自后端真实接口。">
<template #actions>
<button class="btn" type="button" :disabled="loading" @click="load">{{ loading ? '刷新中…' : '刷新' }}</button>
<RouterLink class="btn primary" to="/connections">接入管理</RouterLink>
</template>
</PageHead>
<div v-if="error" class="notice danger" role="alert" style="margin-bottom: 16px">
<div>
<strong>{{ error.title }}</strong>
<div style="margin-top: 4px">{{ error.message }}</div>
<div class="small-muted" style="margin-top: 4px">{{ error.hint }}</div>
<div v-if="error.code || error.requestId" class="small-muted" style="margin-top: 4px">
错误码 {{ error.code }}<span v-if="error.requestId"> · 请求 {{ error.requestId }}</span>
</div>
</div>
<button class="btn sm" type="button" @click="load">重试</button>
</div>
<SectionState :loading="loading" :error="null">
<div class="grid stats">
<StatCard
label="已绑定账号"
:value="health ? health.napcat.total : '—'"
:foot="`受管连接 ${formatNumber(connections.managedConnections)} · ${connections.receiverEnabled ? '事件接收已启用' : '事件接收未启用'}`"
icon="⇄"
/>
<StatCard
label="消息总量"
:value="health ? messages.totalMessages : '—'"
:foot="`入站 ${formatNumber(messages.inboundMessages)} · 出站 ${formatNumber(messages.outboundMessages)}`"
icon="◫"
/>
<StatCard
label="待处理事件"
:value="health ? messages.unprocessedEvents : '—'"
:foot="`失败 ${formatNumber(messages.failedEvents)} · 未知类型 ${formatNumber(messages.unknownTypeEvents)}`"
icon="≡"
/>
<StatCard
label="发送操作"
:value="health ? sendTotal : '—'"
:foot="`成功 ${formatNumber(send.SUCCEEDED)} · 结果未知 ${formatNumber(send.UNKNOWN)}`"
icon="➤"
/>
</div>
<div v-if="health" class="grid two-col" style="margin-bottom: 18px">
<div class="card">
<div class="card-head">
<h3 class="card-title">接入实例状态</h3>
<RouterLink class="link" to="/connections">管理绑定</RouterLink>
</div>
<div v-if="!bindings.length" class="state-block" style="padding: 24px">暂无绑定。前往「接入管理」新增 NapCat 正向 WebSocket 连接。</div>
<div v-else class="table-wrap">
<table>
<thead>
<tr>
<th>绑定 / 实例</th>
<th>QQ 账号</th>
<th>连接方式</th>
<th>状态</th>
<th>最近事件</th>
<th>今日消息</th>
</tr>
</thead>
<tbody>
<tr v-for="item in bindings" :key="item.bindingUid">
<td>
<div class="identity">
<span class="mini-avatar">{{ (item.displayName || 'N').slice(0, 1) }}</span>
<div>
<strong>{{ item.displayName || '—' }}</strong>
<span>{{ item.endpoint || '—' }}</span>
</div>
</div>
</td>
<td>{{ item.qqAccountId || '—' }}</td>
<td>{{ connectionLabel(item.connectionType) }}</td>
<td>
<StatusTag :value="item.bindingStatus" :label="item.bindingStatus || '—'" />
<div class="small-muted" style="margin-top: 4px">{{ item.connectionStatus || '—' }}</div>
</td>
<td>{{ formatTime(item.lastEventAt) }}</td>
<td class="muted" title="后端未提供按绑定的今日消息统计">—</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="card">
<div class="card-head">
<h3 class="card-title">运行提醒</h3>
<span class="pill">后端真实状态</span>
</div>
<div v-if="!attention.length" class="state-block" style="padding: 28px">
<strong>暂无异常</strong>
<p>失败事件、待处理事件、发送结果未知与媒体异常均为 0。</p>
</div>
<div v-for="item in attention" :key="item.title" class="activity">
<span class="activity-icon" :class="item.level === 'error' ? 'error' : 'warning'">{{ item.level === 'error' ? '!' : 'i' }}</span>
<div>
<p>{{ item.title }}</p>
<small>{{ item.detail }}</small>
</div>
</div>
</div>
</div>
</SectionState>
<div v-if="demoState.enabled" class="grid two-col" style="margin-bottom: 18px">
<div class="card">
<div class="card-head">
<h3 class="card-title">消息趋势(近 24 小时)<DemoBadge /></h3>
<span class="pill">演示</span>
</div>
<div class="bar-chart">
<span
v-for="(value, index) in dashboardTrend24h"
:key="index"
class="bar"
:style="{ height: `${(value / maxTrend) * 100}%` }"
:data-label="`第 ${index + 1} 小时:${value} 条`"
></span>
</div>
<div class="chart-axis"><span>0:00</span><span>6:00</span><span>12:00</span><span>18:00</span><span>24:00</span></div>
<p class="small-muted" style="margin-top: 10px">后端 /messages/stats 只提供累计计数,暂无时间序列接口。</p>
</div>
<div class="card">
<div class="card-head">
<h3 class="card-title">自动化概览 <DemoBadge /></h3>
<RouterLink class="link" to="/automation">查看规则</RouterLink>
</div>
<div class="activity">
<span class="activity-icon success">%</span>
<div>
<p>成功率 {{ automationSummary.successRate }}%</p>
<small>成功 {{ automationSummary.success }} · 失败 {{ automationSummary.failed }} · 最近执行「{{ automationSummary.recent }}」</small>
</div>
</div>
<div v-for="rule in automationRules" :key="rule.name" class="context-line">
<span>{{ rule.name }}</span>
<span class="muted">{{ rule.version }} · {{ rule.status }}</span>
</div>
</div>
</div>
<div v-else class="notice" style="margin-bottom: 18px">
演示数据已关闭:消息趋势与自动化概览依赖的后端接口尚未提供,相关区块不显示。
</div>
<div class="card">
<div class="card-head">
<h3 class="card-title">快捷入口</h3>
<span class="small-muted" v-if="updatedAt">数据更新于 {{ updatedAt }}</span>
</div>
<div class="grid stats" style="margin-bottom: 0">
<RouterLink class="card" to="/messages" style="text-decoration: none">
<div class="stat-top"><span>消息中心</span><span class="stat-icon">◫</span></div>
<div class="stat-value" style="font-size: 18px">查看会话与详情</div>
<div class="stat-foot">消息段、原始 payload、媒体与发送</div>
</RouterLink>
<RouterLink class="card" to="/message-search" style="text-decoration: none">
<div class="stat-top"><span>消息检索</span><span class="stat-icon">⌕</span></div>
<div class="stat-value" style="font-size: 18px">条件筛选与分页</div>
<div class="stat-foot">关键词仅匹配摘要前缀</div>
</RouterLink>
<RouterLink class="card" to="/ops" style="text-decoration: none">
<div class="stat-top"><span>运维监控</span><span class="stat-icon">◉</span></div>
<div class="stat-value" style="font-size: 18px">依赖健康总览</div>
<div class="stat-foot">真实 health-detail 分项</div>
</RouterLink>
<RouterLink class="card" to="/settings" style="text-decoration: none">
<div class="stat-top"><span>系统设置</span><span class="stat-icon">◌</span></div>
<div class="stat-value" style="font-size: 18px">外观与演示开关</div>
<div class="stat-foot">实例设置后端未提供</div>
</RouterLink>
</div>
</div>
</template>
+154 -33
View File
@@ -1,35 +1,69 @@
<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { computed, onMounted, ref } from 'vue'
import { RouterLink, useRouter } from 'vue-router'
import { api, setToken } from '../api'
import { describeError } from '../ui'
const router = useRouter()
const username = ref('')
const password = ref('')
const busy = ref(false)
const error = ref('')
const status = ref(null)
const statusError = ref('')
const statusLoading = ref(false)
const statusError = ref(null)
let statusSeq = 0
const form = ref({ username: '', password: '' })
const errors = ref({})
const busy = ref(false)
const loginError = ref(null)
const canLogin = computed(() => Boolean(status.value?.administratorExists))
const recoveryMessage = computed(() => {
const value = status.value?.recoveryRequired
if (!value) return ''
return typeof value === 'string' ? value : '实例初始化状态或资源身份不一致,可能无法正常读写数据。'
})
const bootstrapHint = computed(() =>
status.value?.bootstrapTokenActive
? '引导令牌当前有效,请前往初始化页创建第一个管理员。'
: '当前没有有效的引导令牌。请查看实例启动日志或部署配置获取令牌,必要时按初始化流程重新签发。'
)
async function loadStatus() {
statusError.value = ''
const seq = ++statusSeq
statusLoading.value = true
statusError.value = null
try {
status.value = await api.initialization()
} catch (e) {
statusError.value = e.message
const value = await api.initialization()
if (seq !== statusSeq) return
status.value = value || null
} catch (error) {
if (seq !== statusSeq) return
statusError.value = describeError(error)
} finally {
if (seq === statusSeq) statusLoading.value = false
}
}
function validate() {
const next = {}
if (!form.value.username.trim()) next.username = '请输入用户名。'
if (!form.value.password) next.password = '请输入口令。'
errors.value = next
return Object.keys(next).length === 0
}
async function submit() {
error.value = ''
if (busy.value) return
loginError.value = null
if (!validate()) return
busy.value = true
try {
const result = await api.login(username.value, password.value)
setToken(result.token)
router.push('/overview')
} catch (e) {
// 后端不区分账号不存在与口令错误,此处只展示统一提示与请求号,便于定位。
error.value = `${e.message}${e.requestId ? `(请求号 ${e.requestId})` : ''}`
const data = await api.login(form.value.username.trim(), form.value.password)
setToken(data.token)
await router.replace('/dashboard')
} catch (error) {
loginError.value = describeError(error)
} finally {
busy.value = false
}
@@ -39,22 +73,109 @@ onMounted(loadStatus)
</script>
<template>
<div class="card" style="max-width: 420px; margin: 60px auto;">
<h2>登录</h2>
<p v-if="statusError" class="warn">无法读取实例状态:{{ statusError }}</p>
<template v-else-if="status && status.bootstrapRequired">
<p class="warn">本实例尚未创建管理员,需要先使用启动日志中的引导令牌完成初始化。</p>
<RouterLink to="/bootstrap">前往初始化</RouterLink>
<div class="auth-card">
<div class="auth-card-head">
<p class="eyebrow">QLINKER ADMIN</p>
<h1 class="auth-title">登录管理台</h1>
<p class="auth-sub">单管理员实例。登录后可查看消息、管理连接、执行受控发送。</p>
</div>
<div v-if="statusLoading" class="loading-row">
<span class="spinner" aria-hidden="true"></span>
正在读取实例状态…
</div>
<div v-else-if="statusError" class="notice danger">
<div>
<strong>{{ statusError.title }}</strong>
<p style="margin: 4px 0 0">{{ statusError.message }}</p>
<p class="small-muted" style="margin: 4px 0 0">{{ statusError.hint }}</p>
</div>
<button class="btn sm" type="button" :disabled="statusLoading" @click="loadStatus">重试</button>
</div>
<template v-else-if="status">
<div v-if="recoveryMessage" class="notice danger">
<div>
<strong>实例需要恢复</strong>
<p style="margin: 4px 0 0">{{ recoveryMessage }}</p>
<p class="small-muted" style="margin: 4px 0 0">
请先按部署文档核实数据库与对象存储身份,不要在未确认的情况下重新初始化。
</p>
</div>
</div>
<div v-if="!status.administratorExists" class="notice warn">
<div>
<strong>实例尚未初始化</strong>
<p style="margin: 4px 0 0">尚未创建管理员,当前无法登录管理台。</p>
<p class="small-muted" style="margin: 4px 0 0">{{ bootstrapHint }}</p>
</div>
<RouterLink class="btn sm" to="/bootstrap">
{{ status.bootstrapTokenActive ? '前往初始化' : '查看初始化页' }}
</RouterLink>
</div>
<div v-else-if="status.bootstrapTokenActive" class="notice warn">
<div>
<strong>引导入口仍然开放</strong>
<p style="margin: 4px 0 0">实例已存在管理员,但引导令牌仍处于有效状态。</p>
<p class="small-muted" style="margin: 4px 0 0">
首次初始化完成后引导入口应永久关闭;如非预期,请检查实例配置。
</p>
</div>
</div>
</template>
<template v-else-if="status && !status.administratorExists && !status.bootstrapTokenActive">
<p class="warn">实例尚未初始化,且当前没有有效引导令牌。请检查后端启动日志或实例状态。</p>
<p v-if="status.recoveryRequired" class="error">{{ status.recoveryRequired }}</p>
</template>
<form v-else @submit.prevent="submit">
<label><span>用户名</span><input v-model="username" autocomplete="username" required /></label>
<label><span>口令</span><input v-model="password" type="password" autocomplete="current-password" required /></label>
<button type="submit" :disabled="busy">{{ busy ? '登录中…' : '登录' }}</button>
<p v-if="error" class="error">{{ error }}</p>
<div v-if="loginError" class="notice danger" style="margin-top: 10px">
<div>
<strong>{{ loginError.title }}</strong>
<p style="margin: 4px 0 0">{{ loginError.message }}</p>
<p class="small-muted" style="margin: 4px 0 0">{{ loginError.hint }}</p>
</div>
</div>
<form v-if="canLogin" class="auth-form" @submit.prevent="submit">
<div class="fld">
<label for="login-username">用户名<span class="req">*</span></label>
<input
id="login-username"
v-model="form.username"
class="field"
:class="{ invalid: errors.username }"
autocomplete="username"
maxlength="64"
placeholder="例如:admin"
/>
<p v-if="errors.username" class="field-error">{{ errors.username }}</p>
</div>
<div class="fld">
<label for="login-password">口令<span class="req">*</span></label>
<input
id="login-password"
v-model="form.password"
class="field"
:class="{ invalid: errors.password }"
type="password"
autocomplete="current-password"
placeholder="输入管理员口令"
/>
<p v-if="errors.password" class="field-error">{{ errors.password }}</p>
</div>
<button class="btn primary block" type="submit" :disabled="busy">
{{ busy ? '正在登录…' : '登录' }}
</button>
<p class="auth-note">
登录失败不会区分「账号不存在」与「口令错误」,避免泄露账号是否存在。连续失败会触发后端限流。
</p>
</form>
<p v-else-if="status && !status.administratorExists" class="auth-note">
管理员创建完成后,本页的登录表单才会开放。
<RouterLink to="/bootstrap">前往初始化</RouterLink>
</p>
</div>
</template>
+104
View File
@@ -0,0 +1,104 @@
<script setup>
import { computed, ref } from 'vue'
import { demoState, MOCK_NOTE } from '../demo/config'
import { PLANNED_DEPS, logRows } from '../demo/planned'
import PageHead from '../components/PageHead.vue'
import DemoBadge from '../components/DemoBadge.vue'
import PlannedNotice from '../components/PlannedNotice.vue'
import StatusTag from '../components/StatusTag.vue'
const level = ref('')
const keyword = ref('')
const filtered = computed(() =>
logRows.filter((row) =>
(!level.value || row.level === level.value) &&
(!keyword.value.trim() || `${row.source} ${row.summary} ${row.trace}`.includes(keyword.value.trim()))
)
)
const errorCount = computed(() => logRows.filter((row) => row.level === 'ERROR').length)
const warnCount = computed(() => logRows.filter((row) => row.level === 'WARN').length)
</script>
<template>
<PageHead kicker="连接与运维" title="运行日志" desc="统一日志检索与链路追踪。后端尚未提供日志查询接口,本页内容全部为演示数据。">
<template #actions>
<button class="btn" type="button" disabled title="后端未提供日志导出接口">导出日志</button>
</template>
</PageHead>
<PlannedNotice
v-if="!demoState.enabled"
title="运行日志尚未开发"
summary="日志检索、链路追踪与导出均依赖后端尚未提供的接口;关闭演示数据时不展示任何占位日志。"
:deps="PLANNED_DEPS.logs"
/>
<template v-else>
<div class="demo-banner">{{ MOCK_NOTE }}<DemoBadge /></div>
<div class="grid stats">
<div class="card">
<div class="stat-top"><span>日志条数<DemoBadge /></span><span class="stat-icon">≡</span></div>
<div class="stat-value">{{ logRows.length }}</div>
<div class="stat-foot">仅演示样本</div>
</div>
<div class="card">
<div class="stat-top"><span>错误<DemoBadge /></span><span class="stat-icon">!</span></div>
<div class="stat-value">{{ errorCount }}</div>
<div class="stat-foot">ERROR 级别</div>
</div>
<div class="card">
<div class="stat-top"><span>警告<DemoBadge /></span><span class="stat-icon">△</span></div>
<div class="stat-value">{{ warnCount }}</div>
<div class="stat-foot">WARN 级别</div>
</div>
<div class="card">
<div class="stat-top"><span>保留策略<DemoBadge /></span><span class="stat-icon">◷</span></div>
<div class="stat-value">7 天</div>
<div class="stat-foot">容量与保留策略待后端配置接口</div>
</div>
</div>
<div class="card">
<div class="card-head">
<h3 class="card-title">日志检索<DemoBadge /></h3>
<span class="small-muted">本地筛选仅作用于演示样本</span>
</div>
<div class="filterbar" style="display: flex; gap: 12px; flex-wrap: wrap; margin-bottom: 12px">
<div class="fld">
<label for="log-level">级别</label>
<select id="log-level" v-model="level" class="field">
<option value="">全部级别</option>
<option value="INFO">INFO</option>
<option value="WARN">WARN</option>
<option value="ERROR">ERROR</option>
</select>
</div>
<div class="fld searchfield">
<label for="log-keyword">来源 / 内容 / 追踪号</label>
<input id="log-keyword" v-model="keyword" class="field" placeholder="例如:object storage、trc_9f16" />
</div>
</div>
<div class="table-wrap">
<table>
<thead><tr><th>时间</th><th>级别</th><th>来源</th><th>摘要</th><th>追踪号</th><th>耗时</th><th>操作</th></tr></thead>
<tbody>
<tr v-for="row in filtered" :key="row.trace">
<td>{{ row.time }}</td>
<td><StatusTag :value="row.level" :label="row.level" /></td>
<td>{{ row.source }}</td>
<td>{{ row.summary }}</td>
<td>{{ row.trace }}</td>
<td>{{ row.cost }}</td>
<td><button class="btn sm" type="button" disabled title="后端未提供链路详情接口">链路详情</button></td>
</tr>
</tbody>
</table>
</div>
<div v-if="!filtered.length" class="state-block" style="margin-top: 12px">没有匹配的演示日志。</div>
<p class="small-muted" style="margin-top: 12px">按用户确认,日志页不再显示「检索延迟 86ms」等无法由后端验证的指标。</p>
</div>
</template>
</template>
+408
View File
@@ -0,0 +1,408 @@
<script setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { api } from '../api'
import { describeError, directionLabel, formatNumber, formatTime, typeLabel } from '../ui'
import PageHead from '../components/PageHead.vue'
import SectionState from '../components/SectionState.vue'
import StatusTag from '../components/StatusTag.vue'
import DetailDrawer from '../components/DetailDrawer.vue'
import Pagination from '../components/Pagination.vue'
const route = useRoute()
const router = useRouter()
const filters = reactive({
keyword: '',
bindingUid: '',
conversationType: '',
conversationId: '',
direction: '',
senderId: '',
from: '',
to: ''
})
const bindings = ref([])
const rows = ref([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(20)
const loading = ref(false)
const error = ref(null)
const validationError = ref('')
const detail = ref(null)
const detailLoading = ref(false)
const detailError = ref(null)
const mediaMap = reactive({})
const applied = ref({})
const appliedList = computed(() => {
const items = []
const source = applied.value
if (source.keyword) items.push(`关键词(摘要前缀):${source.keyword}`)
if (source.bindingUid) items.push(`绑定:${source.bindingUid}`)
if (source.conversationType) items.push(`会话类型:${source.conversationType}`)
if (source.conversationId) items.push(`会话 ID:${source.conversationId}`)
if (source.direction) items.push(`方向:${directionLabel(source.direction)}`)
if (source.senderId) items.push(`发送者:${source.senderId}`)
if (source.from) items.push(`起始时间:${formatTime(source.from)}`)
if (source.to) items.push(`结束时间:${formatTime(source.to)}`)
return items
})
const hasApplied = computed(() => appliedList.value.length > 0)
function localToIso(value) {
if (!value) return ''
const date = new Date(value)
if (Number.isNaN(date.getTime())) return ''
return date.toISOString()
}
function validate() {
validationError.value = ''
if (filters.from && filters.to) {
const from = new Date(filters.from)
const to = new Date(filters.to)
if (from.getTime() > to.getTime()) {
validationError.value = '起始时间不能晚于结束时间。'
return false
}
}
return true
}
async function search(nextPage = 1) {
if (!validate()) return
page.value = nextPage
loading.value = true
error.value = null
const payload = {
keyword: filters.keyword.trim(),
bindingUid: filters.bindingUid,
conversationType: filters.conversationType,
conversationId: filters.conversationId.trim(),
direction: filters.direction,
senderId: filters.senderId.trim(),
from: localToIso(filters.from),
to: localToIso(filters.to),
page: nextPage,
pageSize: pageSize.value
}
applied.value = payload
try {
const data = await api.messages(payload)
rows.value = data?.items || []
total.value = data?.total || 0
page.value = data?.page || nextPage
pageSize.value = data?.pageSize || pageSize.value
} catch (e) {
rows.value = []
total.value = 0
error.value = describeError(e)
} finally {
loading.value = false
}
}
function onPageChange(next) {
pageSize.value = next.pageSize
search(next.page)
}
function clearAll() {
Object.assign(filters, {
keyword: '', bindingUid: '', conversationType: '', conversationId: '',
direction: '', senderId: '', from: '', to: ''
})
applied.value = {}
rows.value = []
total.value = 0
page.value = 1
validationError.value = ''
router.replace({ path: '/message-search' })
}
async function openDetail(row) {
detailLoading.value = true
detailError.value = null
detail.value = { message: row, segments: [], rawPayload: null }
try {
detail.value = await api.message(row.messageUid)
} catch (e) {
detailError.value = describeError(e)
} finally {
detailLoading.value = false
}
}
async function loadMedia(mediaUid) {
if (!mediaUid || mediaMap[mediaUid]?.loading) return
mediaMap[mediaUid] = { loading: true, url: '', error: null }
try {
const data = await api.mediaAccessUrl(mediaUid)
mediaMap[mediaUid] = { loading: false, url: data?.url || '', error: null }
} catch (e) {
mediaMap[mediaUid] = { loading: false, url: '', error: describeError(e) }
}
}
function prettyRaw(value) {
if (!value) return '—'
try {
return JSON.stringify(JSON.parse(value), null, 2)
} catch {
return String(value)
}
}
onMounted(async () => {
try {
bindings.value = (await api.bindings()) || []
} catch {
bindings.value = []
}
if (route.query.keyword) filters.keyword = String(route.query.keyword)
if (route.query.conversationType) filters.conversationType = String(route.query.conversationType)
if (route.query.conversationId) filters.conversationId = String(route.query.conversationId)
if (route.query.bindingUid) filters.bindingUid = String(route.query.bindingUid)
if (route.query.direction) filters.direction = String(route.query.direction)
if (route.query.keyword || route.query.conversationId) search()
})
</script>
<template>
<PageHead kicker="工作空间" title="消息检索" desc="按后端 /api/v1/messages 支持的参数检索已入库消息。关键词只做 raw_summary 前缀匹配,不检索正文与原始 payload。">
<template #actions>
<button class="btn" type="button" disabled title="后端未提供导出接口">导出结果</button>
<button class="btn" type="button" :disabled="loading" @click="search(1)">刷新结果</button>
</template>
</PageHead>
<div class="card" style="margin-bottom: 16px">
<div class="card-head">
<h3 class="card-title">检索条件</h3>
<span class="small-muted">时间按浏览器本地输入,提交时转换为 ISO-8601 UTC</span>
</div>
<form @submit.prevent="search(1)">
<div class="filterbar" style="flex-wrap: wrap; display: flex; gap: 12px">
<div class="fld searchfield">
<label for="ms-keyword">关键词(仅匹配摘要前缀)</label>
<input id="ms-keyword" v-model="filters.keyword" class="field" placeholder="raw_summary 前缀,例如:你好" />
<p class="field-hint">后端以 LIKE '关键词%' 执行,不匹配消息正文、消息段或原始 payload。</p>
</div>
<div class="fld">
<label for="ms-binding">账号 / 绑定</label>
<select id="ms-binding" v-model="filters.bindingUid" class="field">
<option value="">全部绑定</option>
<option v-for="item in bindings" :key="item.bindingUid" :value="item.bindingUid">
{{ item.displayName || item.bindingUid }}{{ item.qqAccountId ? ` · ${item.qqAccountId}` : '' }}
</option>
</select>
</div>
<div class="fld">
<label for="ms-conv-type">会话类型</label>
<select id="ms-conv-type" v-model="filters.conversationType" class="field">
<option value="">全部类型</option>
<option value="GROUP">群聊 GROUP</option>
<option value="FRIEND">私聊 FRIEND</option>
</select>
</div>
<div class="fld">
<label for="ms-conv-id">会话 ID</label>
<input id="ms-conv-id" v-model="filters.conversationId" class="field" placeholder="群号或账号 ID" />
</div>
<div class="fld">
<label for="ms-direction">方向(发送记录)</label>
<select id="ms-direction" v-model="filters.direction" class="field">
<option value="">全部方向</option>
<option value="INBOUND">收到 INBOUND</option>
<option value="OUTBOUND">发出 OUTBOUND(发送记录)</option>
</select>
</div>
<div class="fld">
<label for="ms-sender">发送者 ID</label>
<input id="ms-sender" v-model="filters.senderId" class="field" placeholder="发送者账号 / QQ 号" />
</div>
<div class="fld">
<label for="ms-from">起始时间</label>
<input id="ms-from" v-model="filters.from" class="field" type="datetime-local" :class="{ invalid: validationError }" />
</div>
<div class="fld">
<label for="ms-to">结束时间</label>
<input id="ms-to" v-model="filters.to" class="field" type="datetime-local" :class="{ invalid: validationError }" />
</div>
<div class="fld">
<label for="ms-type">消息类型</label>
<select id="ms-type" class="field" disabled title="后端 /messages 未提供 messageType 筛选参数">
<option>后端未支持(不筛选)</option>
</select>
<p class="field-hint">类型筛选置灰:后端列表接口不支持 messageType 参数。</p>
</div>
<div class="fld">
<label for="ms-status">处理状态</label>
<select id="ms-status" class="field" disabled title="后端 /messages 未提供处理状态筛选参数">
<option>后端未支持(不筛选)</option>
</select>
<p class="field-hint">处理状态置灰:后端列表接口不支持 normalizedStatus 参数。</p>
</div>
<div class="fld">
<label for="ms-size">每页条数</label>
<select id="ms-size" v-model.number="pageSize" class="field">
<option :value="10">10 条/页</option>
<option :value="20">20 条/页</option>
<option :value="50">50 条/页</option>
<option :value="100">100 条/页</option>
</select>
</div>
</div>
<div v-if="validationError" class="field-error" style="margin-top: 10px">{{ validationError }}</div>
<div class="form-actions" style="justify-content: flex-start; margin-top: 14px">
<button class="btn primary" type="submit" :disabled="loading">{{ loading ? '检索中…' : '开始检索' }}</button>
<button class="btn" type="button" :disabled="loading" @click="clearAll">清除条件</button>
</div>
</form>
</div>
<div v-if="hasApplied && !loading && !error" class="notice" style="margin-bottom: 14px">
<div>
<strong>当前生效条件</strong>
<div style="margin-top: 4px">{{ appliedList.join(' · ') }}</div>
<div v-if="!rows.length" class="small-muted" style="margin-top: 4px">没有匹配的消息,可清除部分条件后重试。</div>
</div>
<button class="btn sm" type="button" @click="clearAll">清除</button>
</div>
<div class="card">
<div class="card-head">
<h3 class="card-title">检索结果</h3>
<span class="small-muted">分页按后端 PageData:items / page / pageSize / total</span>
</div>
<SectionState
:loading="loading"
:error="error"
:empty="!loading && !error && !hasApplied"
empty-title="尚未设置检索条件"
empty-text="输入关键词或选择账号、会话、方向、时间范围后开始检索。"
loading-text="正在检索消息…"
@retry="search(page)"
>
<SectionState
:loading="false"
:error="null"
:empty="!rows.length"
empty-title="没有匹配的消息"
empty-text="当前条件未返回任何记录。清除条件或放宽时间范围后重试。"
>
<template #empty-actions>
<button class="btn sm" type="button" @click="clearAll">清除条件</button>
</template>
<div class="table-wrap">
<table>
<thead>
<tr>
<th>消息时间</th>
<th>会话</th>
<th>发送者</th>
<th>方向</th>
<th>类型</th>
<th>摘要</th>
<th>段 / 媒体</th>
<th>处理状态</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="row in rows" :key="row.messageUid">
<td>{{ formatTime(row.messageTime) }}</td>
<td>{{ row.conversationType }} · {{ row.conversationId }}</td>
<td>{{ row.senderName || '—' }}<div class="small-muted">{{ row.senderId || '—' }}</div></td>
<td>{{ directionLabel(row.direction) }}</td>
<td>{{ typeLabel(row.messageType) }}<div class="small-muted">{{ row.messageType }}</div></td>
<td style="max-width: 300px">{{ row.summary || '(无摘要)' }}</td>
<td>{{ row.segmentCount }} / {{ row.mediaCount }}</td>
<td><StatusTag :value="row.normalizedStatus" :label="row.normalizedStatus || '—'" /></td>
<td><button class="btn sm" type="button" @click="openDetail(row)">详情</button></td>
</tr>
</tbody>
</table>
</div>
<Pagination :page="page" :page-size="pageSize" :total="total" @change="onPageChange" />
</SectionState>
</SectionState>
</div>
<DetailDrawer :open="Boolean(detail)" title="消息详情" :subtitle="detail?.message?.messageUid" @close="detail = null">
<div v-if="detailLoading" class="state-block"><span class="spinner"></span>正在读取消息详情…</div>
<div v-else-if="detailError" class="notice danger">
<div>
<strong>{{ detailError.title }}</strong>
<div>{{ detailError.message }}</div>
<div class="small-muted">{{ detailError.hint }}</div>
</div>
</div>
<template v-else-if="detail">
<div class="drawer-section">
<h4>基本信息</h4>
<div class="kv">
<div class="kv-row"><span>消息标识</span><span>{{ detail.message?.messageUid }}</span></div>
<div class="kv-row"><span>来源绑定</span><span>{{ detail.message?.bindingUid || '—' }}</span></div>
<div class="kv-row"><span>会话</span><span>{{ detail.message?.conversationType }} · {{ detail.message?.conversationId }}</span></div>
<div class="kv-row"><span>发送者</span><span>{{ detail.message?.senderName || '—' }} ({{ detail.message?.senderId || '—' }})</span></div>
<div class="kv-row"><span>方向 / 类型</span><span>{{ directionLabel(detail.message?.direction) }} · {{ typeLabel(detail.message?.messageType) }}</span></div>
<div class="kv-row"><span>消息时间</span><span>{{ formatTime(detail.message?.messageTime) }}</span></div>
<div class="kv-row"><span>归一化状态</span><span><StatusTag :value="detail.message?.normalizedStatus" :label="detail.message?.normalizedStatus || '—'" /></span></div>
<div class="kv-row"><span>段 / 媒体</span><span>{{ detail.message?.segmentCount }} / {{ detail.message?.mediaCount }}</span></div>
<div class="kv-row"><span>上游消息 ID</span><span>{{ detail.message?.sourceMessageId || '—' }}</span></div>
<div class="kv-row"><span>原始事件</span><span>{{ detail.rawEventUid || '—' }} · {{ detail.rawEventType || '—' }}</span></div>
</div>
</div>
<div class="drawer-section">
<h4>消息段</h4>
<div v-if="!detail.segments?.length" class="small-muted">该消息没有保存任何消息段。</div>
<div v-for="segment in detail.segments" :key="segment.index" class="segment">
<div class="seg-head">
<span>#{{ segment.index }} · {{ typeLabel(segment.type) }} <span class="small-muted">({{ segment.type }})</span></span>
<StatusTag :value="segment.status" :label="segment.status || '—'" />
</div>
<div class="seg-body">{{ segment.content || '—' }}</div>
<div v-if="segment.mediaUid" style="margin-top: 8px">
<button class="btn sm" type="button" @click="loadMedia(segment.mediaUid)">加载媒体预览</button>
<span class="small-muted" style="margin-left: 8px">{{ segment.mediaUid }}</span>
<div v-if="mediaMap[segment.mediaUid]?.loading" class="loading-row"><span class="spinner"></span>正在获取预签名地址…</div>
<div v-else-if="mediaMap[segment.mediaUid]?.error" class="notice danger" style="margin-top: 8px">
{{ mediaMap[segment.mediaUid].error.message }}
</div>
<div v-else-if="mediaMap[segment.mediaUid]?.url" style="margin-top: 8px">
<img v-if="String(segment.type).toUpperCase() === 'IMAGE'" :src="mediaMap[segment.mediaUid].url" alt="消息媒体预览" loading="lazy" />
<a class="link" :href="mediaMap[segment.mediaUid].url" target="_blank" rel="noopener noreferrer">打开媒体地址</a>
<div class="small-muted">地址为短时效预签名地址,过期后需重新获取。</div>
</div>
</div>
</div>
</div>
<div class="drawer-section">
<h4>原始事件 payload</h4>
<pre class="raw-pre">{{ prettyRaw(detail.rawPayload) }}</pre>
</div>
<div class="drawer-section">
<h4>发送记录</h4>
<p class="small-muted">
后端未提供「按消息反查发送操作」接口。方向筛选为 OUTBOUND 的消息即管理台/规则发出的记录;
发送操作的状态、错误码与尝试次数在 /api/v1/send/operations 中查看。
</p>
</div>
</template>
</DetailDrawer>
</template>
+395 -106
View File
@@ -1,145 +1,434 @@
<script setup>
import { ref, onMounted } from 'vue'
import { computed, onMounted, reactive, ref } from 'vue'
import { RouterLink, useRoute } from 'vue-router'
import { api } from '../api'
import { describeError, directionLabel, formatNumber, formatShortTime, formatTime, notify, typeLabel } from '../ui'
import PageHead from '../components/PageHead.vue'
import SectionState from '../components/SectionState.vue'
import StatusTag from '../components/StatusTag.vue'
import DetailDrawer from '../components/DetailDrawer.vue'
import ConfirmDialog from '../components/ConfirmDialog.vue'
import Pagination from '../components/Pagination.vue'
const filters = ref({ conversationType: '', conversationId: '', keyword: '', direction: '' })
const route = useRoute()
const conversations = ref([])
const convLoading = ref(false)
const convError = ref(null)
const active = ref(null)
const rows = ref([])
const msgLoading = ref(false)
const msgError = ref(null)
const page = ref(1)
const pageSize = ref(20)
const data = ref({ items: [], page: 1, pageSize: 20, total: 0 })
const loading = ref(false)
const error = ref('')
const pageSize = ref(30)
const total = ref(0)
const detail = ref(null)
const detailLoading = ref(false)
const detailError = ref('')
const accessUrl = ref('')
const accessError = ref('')
const detailError = ref(null)
const mediaMap = reactive({})
async function load() {
loading.value = true
error.value = ''
const text = ref('')
const preparing = ref(false)
const prepareError = ref(null)
const pending = ref(null)
const executing = ref(false)
const executeError = ref(null)
const lastResult = ref(null)
const activeBinding = computed(() => active.value?.bindingUid || '')
const canSend = computed(() => Boolean(active.value && activeBinding.value && text.value.trim()) && !preparing.value && !executing.value)
const sendTargetType = computed(() => (String(active.value?.conversationType || '').toUpperCase() === 'GROUP' ? 'group' : 'private'))
const conversationName = (item) => `${item.conversationType || '未知类型'} · ${item.conversationId || '—'}`
const conditionHref = computed(() =>
active.value
? { path: '/message-search', query: { conversationType: active.value.conversationType, conversationId: active.value.conversationId } }
: { path: '/message-search' }
)
const orderedRows = computed(() => [...rows.value].reverse())
async function loadConversations() {
convLoading.value = true
convError.value = null
try {
const params = { page: page.value, pageSize: pageSize.value }
for (const [key, value] of Object.entries(filters.value)) if (value) params[key] = value
data.value = await api.messages(params)
const data = await api.conversations(1, 50)
conversations.value = data?.items || []
const wanted = route.query.conversationId
const hit = wanted && conversations.value.find((item) =>
item.conversationId === wanted && (!route.query.conversationType || item.conversationType === route.query.conversationType))
if (hit) active.value = hit
else if (!active.value && conversations.value.length) active.value = conversations.value[0]
if (active.value) await loadMessages()
} catch (e) {
error.value = `${e.message}${e.requestId ? `(请求号 ${e.requestId})` : ''}`
conversations.value = []
rows.value = []
convError.value = describeError(e)
} finally {
loading.value = false
convLoading.value = false
}
}
async function open(row) {
async function selectConversation(item) {
active.value = item
page.value = 1
detail.value = null
detailError.value = ''
accessUrl.value = ''
accessError.value = ''
lastResult.value = null
await loadMessages()
}
async function loadMessages() {
if (!active.value) return
msgLoading.value = true
msgError.value = null
try {
const data = await api.messages({
page: page.value,
pageSize: pageSize.value,
conversationType: active.value.conversationType,
conversationId: active.value.conversationId
})
rows.value = data?.items || []
total.value = data?.total || 0
page.value = data?.page || page.value
} catch (e) {
rows.value = []
total.value = 0
msgError.value = describeError(e)
} finally {
msgLoading.value = false
}
}
function onPageChange(next) {
page.value = next.page
pageSize.value = next.pageSize
loadMessages()
}
async function openDetail(row) {
detailLoading.value = true
detailError.value = null
detail.value = { message: row, segments: [], rawPayload: null }
try {
detail.value = await api.message(row.messageUid)
} catch (e) {
detailError.value = `${e.message}${e.requestId ? `(请求号 ${e.requestId})` : ''}`
detailError.value = describeError(e)
} finally {
detailLoading.value = false
}
}
async function openMedia(mediaUid) {
accessUrl.value = ''
accessError.value = ''
async function loadMedia(mediaUid) {
if (!mediaUid || mediaMap[mediaUid]?.loading) return
mediaMap[mediaUid] = { loading: true, url: '', error: null, info: mediaMap[mediaUid]?.info || null }
try {
const result = await api.mediaAccessUrl(mediaUid)
accessUrl.value = result.url || ''
accessError.value = result.note || ''
const [urlData, info] = await Promise.all([
api.mediaAccessUrl(mediaUid),
api.media(mediaUid).catch(() => null)
])
mediaMap[mediaUid] = { loading: false, url: urlData?.url || '', error: null, info }
} catch (e) {
accessError.value = e.message
mediaMap[mediaUid] = { loading: false, url: '', error: describeError(e), info: null }
}
}
function search() {
page.value = 1
load()
function prettyRaw(value) {
if (!value) return '—'
try {
return JSON.stringify(JSON.parse(value), null, 2)
} catch {
return String(value)
}
}
function move(delta) {
page.value = Math.max(1, page.value + delta)
load()
function idempotencyKey() {
if (window.crypto?.randomUUID) return window.crypto.randomUUID()
return `qlinker-${Date.now()}-${Math.random().toString(16).slice(2)}`
}
onMounted(load)
async function prepareSend() {
if (!canSend.value) return
preparing.value = true
prepareError.value = null
lastResult.value = null
try {
pending.value = await api.prepareText({
bindingUid: activeBinding.value,
targetType: sendTargetType.value,
targetId: active.value.conversationId,
text: text.value.trim(),
reason: '管理台消息中心手动发送'
}, idempotencyKey())
} catch (e) {
prepareError.value = describeError(e)
} finally {
preparing.value = false
}
}
async function confirmSend() {
if (!pending.value || executing.value) return
executing.value = true
executeError.value = null
try {
const result = await api.executeSend(pending.value.operationUid, pending.value.confirmToken)
lastResult.value = result
pending.value = null
text.value = ''
notify(
result.status === 'SUCCEEDED' ? '发送成功' : result.status === 'UNKNOWN' ? '发送结果未知' : '发送未成功',
result.errorMessage || result.warning || `操作 ${result.operationUid} 状态 ${result.status}`,
result.status === 'SUCCEEDED' ? 'success' : 'warning'
)
await loadMessages()
} catch (e) {
executeError.value = describeError(e)
} finally {
executing.value = false
}
}
onMounted(loadConversations)
</script>
<template>
<div>
<div class="card">
<h2>消息查询</h2>
<div class="row">
<select v-model="filters.conversationType" style="max-width: 160px;">
<option value="">全部会话类型</option>
<option value="group">群聊</option>
<option value="private">私聊</option>
</select>
<input v-model="filters.conversationId" placeholder="会话 ID" style="max-width: 180px;" />
<select v-model="filters.direction" style="max-width: 160px;">
<option value="">全部方向</option>
<option value="INBOUND">接收</option>
<option value="OUTBOUND">发送</option>
</select>
<input v-model="filters.keyword" placeholder="关键词" style="max-width: 220px;" />
<button :disabled="loading" @click="search">{{ loading ? '查询中…' : '查询' }}</button>
</div>
<p v-if="error" class="error">{{ error }}</p>
<p class="muted">共 {{ data.total }} 条,第 {{ data.page }} 页(每页 {{ data.pageSize }} 条)。</p>
<table>
<thead>
<tr><th>时间</th><th>会话</th><th>方向</th><th>发送者</th><th>摘要</th><th>段/媒体</th><th>解析</th></tr>
</thead>
<tbody>
<tr v-for="row in data.items" :key="row.messageUid" @click="open(row)" style="cursor: pointer;">
<td class="muted">{{ row.messageTime }}</td>
<td>{{ row.conversationType }}:{{ row.conversationId }}</td>
<td>{{ row.direction }}</td>
<td>{{ row.senderName || row.senderId || '-' }}</td>
<td>{{ row.summary }}</td>
<td>{{ row.segmentCount }} / {{ row.mediaCount }}</td>
<td>{{ row.normalizedStatus }}</td>
</tr>
<tr v-if="!data.items.length && !loading"><td colspan="7" class="muted">没有符合条件的消息。</td></tr>
</tbody>
</table>
<div class="row" style="margin-top: 12px;">
<button class="ghost" :disabled="loading || page <= 1" @click="move(-1)">上一页</button>
<button class="ghost" :disabled="loading || page * pageSize >= data.total" @click="move(1)">下一页</button>
</div>
</div>
<PageHead kicker="工作空间" title="消息中心" desc="会话与消息详情来自真实入库数据;发送走统一发送服务,两阶段确认,不伪造成功。">
<template #actions>
<button class="btn" type="button" :disabled="convLoading || msgLoading" @click="loadConversations">刷新</button>
<RouterLink class="btn primary" :to="conditionHref">消息检索</RouterLink>
</template>
</PageHead>
<div v-if="detailLoading" class="card">详情加载中…</div>
<div v-else-if="detailError" class="card"><p class="error">{{ detailError }}</p></div>
<div v-else-if="detail" class="card">
<h2>消息详情 {{ detail.message.messageUid }}</h2>
<p class="muted">
会话 {{ detail.message.conversationType }}:{{ detail.message.conversationId }},
来源事件 {{ detail.rawEventUid || '-' }}({{ detail.rawEventType || '-' }})
</p>
<table>
<thead><tr><th>#</th><th>类型</th><th>状态</th><th>内容</th><th>媒体</th></tr></thead>
<tbody>
<tr v-for="seg in detail.segments" :key="seg.index">
<td>{{ seg.index }}</td>
<td>{{ seg.type }}</td>
<td>{{ seg.status }}</td>
<td>{{ seg.content || '-' }}</td>
<td>
<button v-if="seg.mediaUid" class="ghost" @click="openMedia(seg.mediaUid)">访问对象</button>
<span v-else class="muted">-</span>
</td>
</tr>
</tbody>
</table>
<p v-if="accessUrl" class="ok">临时访问地址:<a :href="accessUrl" target="_blank" rel="noreferrer">{{ accessUrl }}</a></p>
<p v-if="accessError" class="warn">{{ accessError }}</p>
<h2 style="margin-top: 16px;">原始事件</h2>
<pre>{{ detail.rawPayload }}</pre>
<SectionState
:loading="convLoading"
:error="convError"
:empty="!convLoading && !convError && !conversations.length"
empty-title="暂无会话"
empty-text="还没有已入库的消息。绑定 NapCat 并等待事件到达后,会话会按「会话类型 + 会话 ID」聚合展示。"
@retry="loadConversations"
>
<template #empty-actions>
<RouterLink class="btn primary sm" to="/connections">前往接入管理</RouterLink>
</template>
<div class="chat-layout">
<aside class="chat-list">
<div class="card-head" style="padding: 2px 6px 12px">
<h3 class="card-title">会话</h3>
<span class="pill">{{ conversations.length }}</span>
</div>
<button
v-for="item in conversations"
:key="`${item.conversationType}-${item.conversationId}`"
type="button"
class="chat-person"
:class="{ active: active && item.conversationId === active.conversationId && item.conversationType === active.conversationType }"
style="width: 100%; border: 0; text-align: left"
@click="selectConversation(item)"
>
<span class="mini-avatar">{{ (item.conversationId || '?').slice(-2) }}</span>
<div>
<strong>{{ conversationName(item) }}</strong>
<span>{{ formatNumber(item.messageCount) }} 条 · {{ formatTime(item.lastMessageTime) }}</span>
</div>
</button>
</aside>
<section class="chat-main">
<div v-if="!active" class="state-block" style="margin: 20px">请选择左侧会话查看消息。</div>
<template v-else>
<div class="chat-header">
<div>
<h3 style="margin: 0 0 4px">{{ conversationName(active) }}</h3>
<span class="small-muted">
绑定 {{ active.bindingUid || '—' }} · 共 {{ formatNumber(active.messageCount) }} 条 · 最近 {{ formatTime(active.lastMessageTime) }}
</span>
</div>
<div class="actions">
<button class="btn sm" type="button" disabled title="后端未提供会话级搜索接口">会话内搜索</button>
<button class="btn sm" type="button" disabled title="消息段组合发送由自动化规则实现,管理台仅支持纯文本">附件 / @</button>
</div>
</div>
<SectionState
:loading="msgLoading"
:error="msgError"
:empty="!msgLoading && !msgError && !rows.length"
empty-title="该会话暂无消息"
empty-text="切换分页或检查筛选条件。"
@retry="loadMessages"
>
<div class="chat-messages">
<div v-for="row in orderedRows" :key="row.messageUid" class="bubble-row" :class="{ mine: row.direction === 'OUTBOUND' }">
<div class="bubble" role="button" tabindex="0" @click="openDetail(row)" @keydown.enter="openDetail(row)">
<div>{{ row.summary || '(无摘要)' }}</div>
<div class="bubble-meta">
{{ formatShortTime(row.messageTime) }} · {{ directionLabel(row.direction) }} · {{ typeLabel(row.messageType) }}
· 段 {{ row.segmentCount }} · 媒体 {{ row.mediaCount }}
</div>
</div>
</div>
</div>
</SectionState>
<Pagination :page="page" :page-size="pageSize" :total="total" @change="onPageChange" />
<div v-if="prepareError" class="notice danger" style="margin-top: 10px">
<div>
<strong>{{ prepareError.title }}</strong>
<div>{{ prepareError.message }}</div>
<div class="small-muted">{{ prepareError.hint }}</div>
</div>
</div>
<div v-if="lastResult" class="notice" :class="lastResult.status === 'UNKNOWN' ? 'warn' : lastResult.status === 'SUCCEEDED' ? '' : 'danger'" style="margin-top: 10px">
<div>
<strong>发送操作 {{ lastResult.status }}</strong>
<div>操作 {{ lastResult.operationUid }} · 尝试 {{ lastResult.attemptCount }} 次</div>
<div v-if="lastResult.errorCode || lastResult.errorMessage">{{ lastResult.errorCode }} {{ lastResult.errorMessage }}</div>
<div v-if="lastResult.status === 'UNKNOWN'" class="small-muted">上游可能已执行且本地未收到确认:禁止自动重试,请人工核实后再决定。</div>
</div>
</div>
<div v-if="!activeBinding" class="notice warn" style="margin-top: 10px">
当前会话缺少绑定信息,无法确定发送账号;请先确认消息来源绑定。
</div>
<form class="chat-composer" @submit.prevent="prepareSend">
<textarea
v-model="text"
class="composer-input"
placeholder="输入纯文本消息,发送前会进入两阶段确认…"
maxlength="4000"
:disabled="preparing || executing"
></textarea>
<div class="composer-bottom">
<span class="small-muted">仅支持纯文本 · 目标 {{ sendTargetType }} · 绑定 {{ activeBinding || '—' }}</span>
<button class="btn primary sm" type="submit" :disabled="!canSend">{{ preparing ? '创建发送操作…' : '发送' }}</button>
</div>
</form>
</template>
</section>
<aside class="context-panel">
<div class="context-section">
<h4>会话信息</h4>
<div v-if="active" class="kv">
<div class="kv-row"><span>会话类型</span><span>{{ active.conversationType || '—' }}</span></div>
<div class="kv-row"><span>会话 ID</span><span>{{ active.conversationId || '—' }}</span></div>
<div class="kv-row"><span>绑定</span><span>{{ active.bindingUid || '—' }}</span></div>
<div class="kv-row"><span>消息数</span><span>{{ formatNumber(active.messageCount) }}</span></div>
<div class="kv-row"><span>最近消息</span><span>{{ formatTime(active.lastMessageTime) }}</span></div>
</div>
<div v-else class="small-muted">未选择会话</div>
</div>
<div class="context-section">
<h4>快捷操作</h4>
<RouterLink class="btn sm block" :to="conditionHref">仅检索该会话</RouterLink>
<RouterLink class="btn sm block" to="/message-search" style="margin-top: 8px">按方向筛选发送记录</RouterLink>
<p class="small-muted" style="margin-top: 10px">发送记录并入消息中心的出站消息与「消息检索」方向筛选,不另设独立页面。</p>
</div>
<div class="context-section">
<h4>媒体预览</h4>
<p class="small-muted">在消息详情中通过 /media/{uid}/access-url 获取短时效预签名地址。</p>
</div>
</aside>
</div>
</div>
</SectionState>
<ConfirmDialog
:open="Boolean(pending)"
title="确认发送消息"
:message="pending ? `将向 ${pending.targetSummary || `${pending.targetType} ${pending.targetId}`} 发送纯文本消息。` : ''"
:hint="pending ? `确认令牌有效期至 ${formatTime(pending.confirmExpiresAt)};执行结果可能为「结果未知」。` : ''"
confirm-text="确认并发送"
:busy="executing"
@confirm="confirmSend"
@cancel="!executing && (pending = null)"
>
<div v-if="pending" class="notice" style="margin-bottom: 12px">
<div>
<strong>待发送内容</strong>
<div style="white-space: pre-wrap; margin-top: 6px">{{ pending.text || text }}</div>
<div class="small-muted" style="margin-top: 6px">操作 {{ pending.operationUid }}</div>
</div>
</div>
<div v-if="executeError" class="notice danger">
<div>
<strong>{{ executeError.title }}</strong>
<div>{{ executeError.message }}</div>
<div class="small-muted">{{ executeError.hint }}</div>
</div>
</div>
</ConfirmDialog>
<DetailDrawer :open="Boolean(detail)" title="消息详情" :subtitle="detail?.message?.messageUid" @close="detail = null">
<div v-if="detailLoading" class="state-block"><span class="spinner"></span>正在读取消息详情…</div>
<div v-else-if="detailError" class="notice danger">
<div>
<strong>{{ detailError.title }}</strong>
<div>{{ detailError.message }}</div>
<div class="small-muted">{{ detailError.hint }}</div>
</div>
</div>
<template v-else-if="detail">
<div class="drawer-section">
<h4>基本信息</h4>
<div class="kv">
<div class="kv-row"><span>消息标识</span><span>{{ detail.message?.messageUid }}</span></div>
<div class="kv-row"><span>来源绑定</span><span>{{ detail.message?.bindingUid || '—' }}</span></div>
<div class="kv-row"><span>会话</span><span>{{ detail.message?.conversationType }} · {{ detail.message?.conversationId }}</span></div>
<div class="kv-row"><span>发送者</span><span>{{ detail.message?.senderName || '—' }} ({{ detail.message?.senderId || '—' }})</span></div>
<div class="kv-row"><span>方向 / 类型</span><span>{{ directionLabel(detail.message?.direction) }} · {{ typeLabel(detail.message?.messageType) }}</span></div>
<div class="kv-row"><span>消息时间</span><span>{{ formatTime(detail.message?.messageTime) }}</span></div>
<div class="kv-row"><span>归一化状态</span><span><StatusTag :value="detail.message?.normalizedStatus" :label="detail.message?.normalizedStatus || '—'" /></span></div>
<div class="kv-row"><span>段 / 媒体</span><span>{{ detail.message?.segmentCount }} / {{ detail.message?.mediaCount }}</span></div>
<div class="kv-row"><span>上游消息 ID</span><span>{{ detail.message?.sourceMessageId || '—' }}</span></div>
<div class="kv-row"><span>原始事件</span><span>{{ detail.rawEventUid || '—' }} · {{ detail.rawEventType || '—' }}</span></div>
</div>
</div>
<div class="drawer-section">
<h4>消息段</h4>
<div v-if="!detail.segments?.length" class="small-muted">该消息没有保存任何消息段。</div>
<div v-for="segment in detail.segments" :key="segment.index" class="segment">
<div class="seg-head">
<span>#{{ segment.index }} · {{ typeLabel(segment.type) }} <span class="small-muted">({{ segment.type }})</span></span>
<StatusTag :value="segment.status" :label="segment.status || '—'" />
</div>
<div class="seg-body">{{ segment.content || '—' }}</div>
<div v-if="segment.mediaUid" style="margin-top: 8px">
<button class="btn sm" type="button" @click="loadMedia(segment.mediaUid)">加载媒体预览</button>
<span class="small-muted" style="margin-left: 8px">{{ segment.mediaUid }}</span>
<div v-if="mediaMap[segment.mediaUid]?.loading" class="loading-row"><span class="spinner"></span>正在获取预签名地址…</div>
<div v-else-if="mediaMap[segment.mediaUid]?.error" class="notice danger" style="margin-top: 8px">
{{ mediaMap[segment.mediaUid].error.message }}
</div>
<div v-else-if="mediaMap[segment.mediaUid]?.url" style="margin-top: 8px">
<img
v-if="String(segment.type).toUpperCase() === 'IMAGE'"
:src="mediaMap[segment.mediaUid].url"
alt="消息媒体预览"
loading="lazy"
/>
<a class="link" :href="mediaMap[segment.mediaUid].url" target="_blank" rel="noopener noreferrer">打开媒体地址</a>
<div class="small-muted">地址为短时效预签名地址,过期后需重新获取。</div>
</div>
</div>
</div>
</div>
<div class="drawer-section">
<h4>原始事件 payload</h4>
<pre class="raw-pre">{{ prettyRaw(detail.rawPayload) }}</pre>
</div>
<div class="drawer-section">
<h4>媒体与发送记录</h4>
<p class="small-muted">媒体通过 /api/v1/media/{uid}/access-url 按需获取;后端未提供按消息反查发送记录,发送记录请使用「消息检索」的方向筛选查看出站消息与发送操作列表。</p>
<RouterLink class="btn sm" :to="conditionHref">在消息检索中查看</RouterLink>
</div>
</template>
</DetailDrawer>
</template>
+160
View File
@@ -0,0 +1,160 @@
<script setup>
import { computed, onMounted, ref } from 'vue'
import { api } from '../api'
import { describeError, formatNumber, formatTime } from '../ui'
import { demoState } from '../demo/config'
import PageHead from '../components/PageHead.vue'
import SectionState from '../components/SectionState.vue'
import StatusTag from '../components/StatusTag.vue'
import DemoBadge from '../components/DemoBadge.vue'
import { opsAlerts, opsResources } from '../demo/planned'
const health = ref(null)
const loading = ref(false)
const error = ref(null)
const sendTotal = computed(() =>
health.value ? ['PENDING', 'RUNNING', 'SUCCEEDED', 'FAILED', 'UNKNOWN'].reduce((sum, key) => sum + (Number(health.value.send?.[key]) || 0), 0) : 0
)
const lastEvent = computed(() => {
const items = health.value?.napcat?.items || []
const times = items.map((item) => item.lastEventAt).filter(Boolean).sort()
return times.length ? times[times.length - 1] : null
})
const rows = computed(() => {
if (!health.value) return []
const m = health.value.messages || {}
const media = health.value.media || {}
const send = health.value.send || {}
const napcat = health.value.napcat || {}
return [
{ name: '应用进程', status: health.value.application || 'UNKNOWN', detail: 'HTTP 存活仅代表进程可响应', at: '—' },
{ name: '实例身份', status: health.value.instance ? 'INITIALIZED' : 'PENDING', detail: health.value.instance || '未取得实例标识', at: '—' },
{
name: 'NapCat 连接',
status: napcat.connections?.receiverEnabled ? 'CONNECTED' : 'DISABLED',
detail: `受管连接 ${formatNumber(napcat.connections?.managedConnections)} · 绑定 ${formatNumber(napcat.total)} · 事件接收${napcat.connections?.receiverEnabled ? '已启用' : '未启用'}`,
at: formatTime(lastEvent.value)
},
{
name: '消息入库',
status: Number(m.failedEvents) > 0 ? 'FAILED' : Number(m.unprocessedEvents) > 0 ? 'PENDING' : 'ACTIVE',
detail: `总量 ${formatNumber(m.totalMessages)} · 待处理 ${formatNumber(m.unprocessedEvents)} · 失败 ${formatNumber(m.failedEvents)}`,
at: '—'
},
{
name: '媒体对象存储',
status: Number(media.FAILED) > 0 ? 'FAILED' : Number(media.OBJECT_MISSING) > 0 ? 'WARN' : 'STORED',
detail: `已入库 ${formatNumber(media.STORED)} · 失败 ${formatNumber(media.FAILED)} · 对象缺失 ${formatNumber(media.OBJECT_MISSING)}`,
at: '—'
},
{
name: '发送操作',
status: Number(send.UNKNOWN) > 0 ? 'UNKNOWN' : Number(send.FAILED) > 0 ? 'FAILED' : 'ACTIVE',
detail: `总计 ${formatNumber(sendTotal.value)} · 成功 ${formatNumber(send.SUCCEEDED)} · 结果未知 ${formatNumber(send.UNKNOWN)}`,
at: '—'
},
{ name: 'MySQL 连接', status: 'UNKNOWN', detail: '后端 health-detail 未提供数据库独立探测结果', at: '—' },
{ name: 'MinIO 连接', status: 'UNKNOWN', detail: '后端 health-detail 未提供对象存储独立探测结果', at: '—' },
{ name: '异步任务队列', status: 'UNKNOWN', detail: '后端 health-detail 未提供队列积压指标', at: '—' }
]
})
async function load() {
loading.value = true
error.value = null
try {
health.value = await api.healthDetail()
} catch (e) {
health.value = null
error.value = describeError(e)
} finally {
loading.value = false
}
}
onMounted(load)
</script>
<template>
<PageHead kicker="连接与运维" title="运维监控" desc="健康总览分项来自后端 health-detail;数据库、对象存储独立探测与主机资源尚未提供,按实显示「未提供」。">
<template #actions>
<button class="btn" type="button" :disabled="loading" @click="load">{{ loading ? '刷新中…' : '刷新' }}</button>
</template>
</PageHead>
<div class="grid stats">
<div class="card">
<div class="stat-top"><span>应用进程</span><span class="stat-icon">◉</span></div>
<div class="stat-value">{{ health?.application || '—' }}</div>
<div class="stat-foot">进程存活不等于全部依赖可用</div>
</div>
<div class="card">
<div class="stat-top"><span>NapCat 受管连接</span><span class="stat-icon">⇄</span></div>
<div class="stat-value">{{ health ? formatNumber(health.napcat?.connections?.managedConnections) : '—' }}</div>
<div class="stat-foot">事件接收{{ health?.napcat?.connections?.receiverEnabled ? '已启用' : '未启用' }}</div>
</div>
<div class="card">
<div class="stat-top"><span>消息失败 / 待处理</span><span class="stat-icon">≡</span></div>
<div class="stat-value">{{ health ? `${formatNumber(health.messages?.failedEvents)} / ${formatNumber(health.messages?.unprocessedEvents)}` : '—' }}</div>
<div class="stat-foot">总量 {{ health ? formatNumber(health.messages?.totalMessages) : '—' }}</div>
</div>
<div class="card">
<div class="stat-top"><span>发送结果未知</span><span class="stat-icon">➤</span></div>
<div class="stat-value">{{ health ? formatNumber(health.send?.UNKNOWN) : '—' }}</div>
<div class="stat-foot">需人工核实,禁止自动重试</div>
</div>
</div>
<SectionState :loading="loading" :error="error" @retry="load">
<div class="card" style="margin-bottom: 18px">
<div class="card-head">
<h3 class="card-title">健康总览</h3>
<span class="small-muted">最近事件已并入本表,不另设独立列表</span>
</div>
<div class="table-wrap">
<table>
<thead><tr><th>依赖项</th><th>状态</th><th>说明</th><th>最近事件</th></tr></thead>
<tbody>
<tr v-for="row in rows" :key="row.name">
<td><strong>{{ row.name }}</strong></td>
<td><StatusTag :value="row.status" :label="row.status" /></td>
<td class="muted">{{ row.detail }}</td>
<td>{{ row.at }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</SectionState>
<template v-if="demoState.enabled">
<div class="demo-banner">以下主机资源与告警为演示数据,仅用于界面预览;后端未提供对应接口。<DemoBadge /></div>
<div class="grid two-col">
<div class="card">
<div class="card-head"><h3 class="card-title">主机资源<DemoBadge /></h3><span class="pill">演示</span></div>
<div v-for="item in opsResources" :key="item.name" style="margin-bottom: 14px">
<div class="context-line"><span>{{ item.name }}</span><span>{{ item.value }}</span></div>
<div class="progress"><span :style="{ width: `${item.width}%` }"></span></div>
</div>
<p class="small-muted">CPU / 内存 / 磁盘使用率需后端主机监控接口。</p>
</div>
<div class="card">
<div class="card-head"><h3 class="card-title">告警<DemoBadge /></h3><span class="pill">演示</span></div>
<div v-for="alert in opsAlerts" :key="alert.title" class="activity">
<span class="activity-icon" :class="alert.level === 'error' ? 'error' : alert.level === 'warning' ? 'warning' : 'success'">!</span>
<div>
<p>{{ alert.title }}</p>
<small>{{ alert.time }} · {{ alert.status }}</small>
</div>
</div>
<div class="form-actions" style="margin-top: 10px">
<button class="btn sm" type="button" disabled title="后端未提供告警确认/分派/关闭接口">处理告警</button>
</div>
</div>
</div>
</template>
<div v-else class="notice">演示数据已关闭:主机资源与告警区块依赖的后端接口尚未提供,因此不显示。</div>
</template>
-87
View File
@@ -1,87 +0,0 @@
<script setup>
import { ref, onMounted } from 'vue'
import { api } from '../api'
const detail = ref(null)
const error = ref('')
const loading = ref(false)
async function load() {
loading.value = true
error.value = ''
try {
detail.value = await api.healthDetail()
} catch (e) {
error.value = `${e.message}${e.requestId ? `(请求号 ${e.requestId})` : ''}`
} finally {
loading.value = false
}
}
onMounted(load)
</script>
<template>
<div>
<div class="card">
<div class="row" style="justify-content: space-between;">
<h2 style="margin: 0;">系统总览</h2>
<button class="ghost" :disabled="loading" @click="load">{{ loading ? '刷新中…' : '刷新' }}</button>
</div>
<p v-if="error" class="error">{{ error }}</p>
<p v-else-if="!detail && !loading" class="muted">暂无数据。</p>
</div>
<template v-if="detail">
<div class="card">
<h2>实例与依赖</h2>
<div class="grid">
<div class="stat"><div class="value">{{ detail.instance || '-' }}</div><div class="label">实例标识</div></div>
<div class="stat"><div class="value">{{ detail.napcat?.total ?? '-' }}</div><div class="label">NapCat 绑定数</div></div>
<div class="stat"><div class="value">{{ detail.messages?.totalMessages ?? '-' }}</div><div class="label">已入库消息</div></div>
<div class="stat"><div class="value">{{ detail.messages?.unprocessedEvents ?? '-' }}</div><div class="label">待处理事件</div></div>
</div>
<p class="muted">
事件处理失败 {{ detail.messages?.failedEvents ?? 0 }} 条,未知类型事件 {{ detail.messages?.unknownTypeEvents ?? 0 }} 条。
未知类型不会被丢弃,但也不会被强行归一化为已知消息。
</p>
</div>
<div class="card">
<h2>NapCat 连接状态</h2>
<p class="muted">在线状态以收到 lifecycle 或有效事件为准,握手成功不代表在线。</p>
<table>
<thead>
<tr><th>绑定</th><th>绑定状态</th><th>连接状态</th><th>QQ 账号</th><th>最近事件</th><th>最近错误</th></tr>
</thead>
<tbody>
<tr v-for="item in detail.napcat?.items || []" :key="item.bindingUid">
<td>{{ item.displayName || item.bindingUid }}</td>
<td>{{ item.bindingStatus }}</td>
<td>{{ item.connectionStatus }}</td>
<td>{{ item.qqAccountId || '-' }}</td>
<td>{{ item.lastEventAt || '-' }}</td>
<td>{{ item.lastErrorCode || '-' }}</td>
</tr>
<tr v-if="!(detail.napcat?.items || []).length">
<td colspan="6" class="muted">尚未绑定 NapCat 实例。</td>
</tr>
</tbody>
</table>
</div>
<div class="card">
<h2>媒体与发送</h2>
<div class="grid">
<div class="stat"><div class="value">{{ detail.media?.STORED ?? 0 }}</div><div class="label">媒体已入库</div></div>
<div class="stat"><div class="value">{{ detail.media?.FAILED ?? 0 }}</div><div class="label">媒体下载失败</div></div>
<div class="stat"><div class="value">{{ detail.media?.SOURCE_EXPIRED ?? 0 }}</div><div class="label">媒体源已过期</div></div>
<div class="stat"><div class="value">{{ detail.send?.SUCCEEDED ?? 0 }}</div><div class="label">发送成功</div></div>
<div class="stat"><div class="value">{{ detail.send?.UNKNOWN ?? 0 }}</div><div class="label">发送结果未知</div></div>
<div class="stat"><div class="value">{{ detail.send?.FAILED ?? 0 }}</div><div class="label">发送失败</div></div>
</div>
<p class="warn">「结果未知」表示上游可能已执行但本地未收到确认,不会自动重试,需要人工核实。</p>
</div>
</template>
</div>
</template>
+155
View File
@@ -0,0 +1,155 @@
<script setup>
import { computed, onMounted, ref } from 'vue'
import { api } from '../api'
import { describeError, formatTime } from '../ui'
import { demoState, MOCK_NOTE } from '../demo/config'
import { PLANNED_DEPS, securityApprovals, securityRoles, securityTokens, securityUsers } from '../demo/planned'
import PageHead from '../components/PageHead.vue'
import DemoBadge from '../components/DemoBadge.vue'
import PlannedNotice from '../components/PlannedNotice.vue'
import SectionState from '../components/SectionState.vue'
import StatusTag from '../components/StatusTag.vue'
const tab = ref('users')
const me = ref(null)
const meLoading = ref(false)
const meError = ref(null)
const permissions = computed(() => me.value?.permissions || [])
async function loadMe() {
meLoading.value = true
meError.value = null
try {
me.value = await api.me()
} catch (e) {
me.value = null
meError.value = describeError(e)
} finally {
meLoading.value = false
}
}
onMounted(loadMe)
</script>
<template>
<PageHead kicker="平台管理" title="安全审计" desc="当前账号与权限来自后端 /auth/me;用户、角色、令牌与审批的后端接口尚未提供,相关页签为演示数据。">
<template #actions>
<button class="btn" type="button" disabled title="后端未提供紧急停止接口">紧急停止</button>
<button class="btn danger" type="button" disabled title="后端未提供用户管理接口">新增用户</button>
</template>
</PageHead>
<div class="card" style="margin-bottom: 16px">
<div class="card-head">
<h3 class="card-title">当前会话(真实)</h3>
<span class="pill">/auth/me</span>
</div>
<SectionState :loading="meLoading" :error="meError" @retry="loadMe">
<div v-if="me" class="kv">
<div class="kv-row"><span>账号</span><span>{{ me.username || '—' }}</span></div>
<div class="kv-row"><span>显示名称</span><span>{{ me.displayName || '—' }}</span></div>
<div class="kv-row"><span>用户标识</span><span>{{ me.userId || '—' }}</span></div>
<div class="kv-row"><span>管理员</span><span>{{ me.hasAdministrator ? '是' : '否' }}</span></div>
<div class="kv-row"><span>权限</span><span>{{ permissions.length ? permissions.join('、') : '—' }}</span></div>
</div>
</SectionState>
</div>
<PlannedNotice
v-if="!demoState.enabled"
title="用户、角色、令牌与审批尚未开发"
summary="后端仅提供单管理员认证与权限声明,未提供用户管理、角色、API 令牌、审批与审计事件接口。关闭演示数据时不展示占位数据。"
:deps="PLANNED_DEPS.security"
/>
<template v-else>
<div class="demo-banner">{{ MOCK_NOTE }}<DemoBadge /></div>
<div class="tabs">
<button class="tab" :class="{ active: tab === 'users' }" type="button" @click="tab = 'users'">用户</button>
<button class="tab" :class="{ active: tab === 'roles' }" type="button" @click="tab = 'roles'">角色</button>
<button class="tab" :class="{ active: tab === 'tokens' }" type="button" @click="tab = 'tokens'">API 令牌</button>
<button class="tab" :class="{ active: tab === 'approvals' }" type="button" @click="tab = 'approvals'">审批</button>
</div>
<div v-if="tab === 'users'" class="card">
<div class="card-head"><h3 class="card-title">用户<DemoBadge /></h3><span class="small-muted">演示数据</span></div>
<div class="table-wrap">
<table>
<thead><tr><th>姓名</th><th>账号</th><th>角色</th><th>状态</th><th>最近登录</th><th>操作</th></tr></thead>
<tbody>
<tr v-for="user in securityUsers" :key="user.account">
<td><strong>{{ user.name }}</strong></td>
<td>{{ user.account }}</td>
<td>{{ user.role }}</td>
<td><StatusTag value="ACTIVE" :label="user.status" /></td>
<td>{{ user.lastLogin }}</td>
<td><button class="btn sm" type="button" disabled title="后端未提供用户编辑接口">编辑</button></td>
</tr>
</tbody>
</table>
</div>
</div>
<div v-else-if="tab === 'roles'" class="card">
<div class="card-head"><h3 class="card-title">角色<DemoBadge /></h3><span class="small-muted">演示数据</span></div>
<div class="table-wrap">
<table>
<thead><tr><th>角色</th><th>成员</th><th>授权范围</th><th>最近变更</th><th>操作</th></tr></thead>
<tbody>
<tr v-for="role in securityRoles" :key="role.name">
<td><strong>{{ role.name }}</strong></td>
<td>{{ role.members }}</td>
<td>{{ role.scope }}</td>
<td>{{ role.changed }}</td>
<td><button class="btn sm" type="button" disabled title="后端未提供角色编辑接口">配置权限</button></td>
</tr>
</tbody>
</table>
</div>
</div>
<div v-else-if="tab === 'tokens'" class="card">
<div class="card-head"><h3 class="card-title">API 令牌<DemoBadge /></h3><span class="small-muted">演示数据</span></div>
<div class="table-wrap">
<table>
<thead><tr><th>名称</th><th>授权范围</th><th>到期</th><th>状态</th><th>操作</th></tr></thead>
<tbody>
<tr v-for="token in securityTokens" :key="token.name">
<td><strong>{{ token.name }}</strong></td>
<td>{{ token.scope }}</td>
<td>{{ token.expires }}</td>
<td><StatusTag :value="token.status === '有效' ? 'ACTIVE' : token.status === '临期' ? 'WARN' : 'EXPIRED'" :label="token.status" /></td>
<td><button class="btn sm" type="button" disabled title="后端未提供令牌吊销接口">吊销</button></td>
</tr>
</tbody>
</table>
</div>
</div>
<div v-else class="card">
<div class="card-head"><h3 class="card-title">高风险审批<DemoBadge /></h3><span class="small-muted">演示数据</span></div>
<div class="table-wrap">
<table>
<thead><tr><th>申请内容</th><th>提交人</th><th>时间</th><th>风险</th><th>操作</th></tr></thead>
<tbody>
<tr v-for="item in securityApprovals" :key="item.title">
<td>{{ item.title }}</td>
<td>{{ item.submitter }}</td>
<td>{{ item.time }}</td>
<td><StatusTag :value="item.risk === '高' ? 'FAILED' : 'WARN'" :label="item.risk" /></td>
<td>
<div class="table-actions">
<button class="btn sm" type="button" disabled title="后端未提供审批接口">通过</button>
<button class="btn sm" type="button" disabled title="后端未提供审批接口">驳回</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
</template>
-152
View File
@@ -1,152 +0,0 @@
<script setup>
import { ref, onMounted } from 'vue'
import { api } from '../api'
const bindings = ref([])
const form = ref({ bindingUid: '', targetType: 'group', targetId: '', text: '', reason: '' })
const phase = ref('idle')
const prepared = ref(null)
const operations = ref([])
const summary = ref(null)
const busy = ref(false)
const error = ref('')
const notice = ref('')
function newIdempotencyKey() {
return typeof crypto !== 'undefined' && crypto.randomUUID
? crypto.randomUUID()
: `idem_${Date.now()}_${Math.random().toString(36).slice(2)}`
}
let idempotencyKey = newIdempotencyKey()
async function loadAll() {
error.value = ''
try {
const [list, ops, sum] = await Promise.all([api.bindings(), api.sendOperations(), api.sendSummary()])
bindings.value = list.filter((b) => b.bindingStatus === 'ACTIVE')
operations.value = ops
summary.value = sum
} catch (e) {
error.value = `${e.message}${e.requestId ? `(请求号 ${e.requestId})` : ''}`
}
}
async function prepare() {
error.value = ''
notice.value = ''
busy.value = true
try {
prepared.value = await api.prepareText({ ...form.value }, idempotencyKey)
phase.value = 'prepared'
} catch (e) {
error.value = `${e.message}${e.requestId ? `(请求号 ${e.requestId})` : ''}`
} finally {
busy.value = false
}
}
async function execute() {
error.value = ''
busy.value = true
try {
const result = await api.executeSend(prepared.value.operationUid, prepared.value.confirmToken)
phase.value = 'done'
if (result.status === 'SUCCEEDED') {
notice.value = `发送成功(操作号 ${result.operationUid})。「上游确认成功」不必然代表接收方已看到消息。`
} else if (result.status === 'UNKNOWN') {
error.value = `结果未知(操作号 ${result.operationUid}):上游可能已执行,系统不会自动重试,请人工核实。`
} else {
error.value = `发送未完成(操作号 ${result.operationUid},状态 ${result.status},错误 ${result.errorCode || '-'})`
}
// 一次操作只允许一次确认执行,之后重新开始,避免重复提交。
idempotencyKey = newIdempotencyKey()
prepared.value = null
await loadAll()
} catch (e) {
error.value = `${e.message}${e.requestId ? `(请求号 ${e.requestId})` : ''}`
} finally {
busy.value = false
}
}
function cancel() {
prepared.value = null
phase.value = 'idle'
idempotencyKey = newIdempotencyKey()
}
onMounted(loadAll)
</script>
<template>
<div>
<div class="card">
<h2>发送文本消息(两阶段确认)</h2>
<p class="muted">第一步只创建发送操作,不产生任何外部副作用;第二步携带确认令牌才真正调用 NapCat。</p>
<template v-if="phase !== 'prepared'">
<label>
<span>NapCat 绑定</span>
<select v-model="form.bindingUid" required>
<option value="" disabled>请选择绑定</option>
<option v-for="b in bindings" :key="b.bindingUid" :value="b.bindingUid">
{{ b.displayName }}({{ b.connectionStatus }})
</option>
</select>
</label>
<div class="row">
<label style="max-width: 160px;">
<span>目标类型</span>
<select v-model="form.targetType">
<option value="group">群</option>
<option value="private">个人</option>
</select>
</label>
<label style="flex: 1;"><span>目标 ID</span><input v-model="form.targetId" required /></label>
</div>
<label><span>消息正文</span><textarea v-model="form.text" rows="4" required></textarea></label>
<label><span>操作原因(写入审计)</span><input v-model="form.reason" /></label>
<button :disabled="busy || !form.bindingUid || !form.targetId || !form.text" @click="prepare">
{{ busy ? '处理中…' : '第一步:创建发送操作' }}
</button>
</template>
<template v-else>
<p class="warn">
即将向 <b>{{ prepared.targetSummary }}</b> 发送消息。确认令牌有效期很短,过期后需要重新创建操作。
</p>
<pre>{{ form.text }}</pre>
<div class="row">
<button :disabled="busy" @click="execute">{{ busy ? '发送中…' : '第二步:确认并发送' }}</button>
<button class="ghost" :disabled="busy" @click="cancel">取消</button>
</div>
</template>
<p v-if="notice" class="ok">{{ notice }}</p>
<p v-if="error" class="error">{{ error }}</p>
</div>
<div class="card">
<h2>发送操作记录</h2>
<p class="muted" v-if="summary">
待发送 {{ summary.PENDING ?? 0 }},发送中 {{ summary.RUNNING ?? 0 }},成功 {{ summary.SUCCEEDED ?? 0 }},
失败 {{ summary.FAILED ?? 0 }},结果未知 {{ summary.UNKNOWN ?? 0 }}
</p>
<table>
<thead>
<tr><th>操作号</th><th>目标</th><th>状态</th><th>尝试</th><th>错误</th><th>创建时间</th><th>完成时间</th></tr>
</thead>
<tbody>
<tr v-for="op in operations" :key="op.operationUid">
<td class="muted">{{ op.operationUid }}</td>
<td>{{ op.targetType }}:{{ op.targetId }}</td>
<td>{{ op.status }}</td>
<td>{{ op.attemptCount }}</td>
<td>{{ op.errorCode || '-' }}</td>
<td class="muted">{{ op.createdAt }}</td>
<td class="muted">{{ op.finishedAt || '-' }}</td>
</tr>
<tr v-if="!operations.length"><td colspan="7" class="muted">暂无发送操作。</td></tr>
</tbody>
</table>
</div>
</div>
</template>
+124
View File
@@ -0,0 +1,124 @@
<script setup>
import { onMounted, ref } from 'vue'
import { api } from '../api'
import { demoState, MOCK_NOTE, setDemoEnabled } from '../demo/config'
import { PLANNED_DEPS, settingsValues } from '../demo/planned'
import PageHead from '../components/PageHead.vue'
import DemoBadge from '../components/DemoBadge.vue'
const tab = ref('basic')
const instance = ref(null)
const instanceError = ref('')
const dark = ref(document.documentElement.style.colorScheme === 'dark')
function setTheme(mode) {
dark.value = mode === 'dark'
document.documentElement.style.colorScheme = dark.value ? 'dark' : 'light'
localStorage.setItem('qlinker.theme', dark.value ? 'dark' : 'light')
}
function toggleDemo() {
setDemoEnabled(!demoState.enabled)
}
onMounted(async () => {
try {
instance.value = await api.initialization()
} catch {
instanceError.value = '实例初始化信息读取失败(后端可能未启动)。'
}
})
</script>
<template>
<PageHead kicker="平台管理" title="系统设置" desc="实例身份来自后端;外观与演示数据开关为本地真实设置;业务配置项后端尚未提供。">
</PageHead>
<div class="card" style="margin-bottom: 16px">
<div class="card-head">
<h3 class="card-title">实例信息</h3>
<span class="pill">后端真实</span>
</div>
<div v-if="instanceError" class="notice danger">{{ instanceError }}</div>
<div v-else class="kv">
<div class="kv-row"><span>实例标识</span><span>{{ instance?.instanceUid || '—' }}</span></div>
<div class="kv-row"><span>初始化状态</span><span>{{ instance ? (instance.initialized ? '已初始化' : '未初始化') : '读取中…' }}</span></div>
<div class="kv-row"><span>数据库</span><span>{{ instance?.databaseName || '—' }}</span></div>
<div class="kv-row"><span>对象存储 Bucket</span><span>{{ instance?.bucketName || '—' }}</span></div>
</div>
</div>
<div class="tabs">
<button class="tab" :class="{ active: tab === 'basic' }" type="button" @click="tab = 'basic'">基础</button>
<button class="tab" :class="{ active: tab === 'notify' }" type="button" @click="tab = 'notify'">通知</button>
<button class="tab" :class="{ active: tab === 'appearance' }" type="button" @click="tab = 'appearance'">外观与预览</button>
<button class="tab" :class="{ active: tab === 'data' }" type="button" @click="tab = 'data'">数据</button>
</div>
<div v-if="tab === 'basic'" class="card">
<div class="card-head"><h3 class="card-title">基础配置<DemoBadge /></h3><span class="small-muted">后端未提供实例设置接口</span></div>
<div class="form-grid">
<div class="fld">
<label for="set-name">实例名称</label>
<input id="set-name" class="field" :value="settingsValues.instanceName" disabled />
</div>
<div class="fld">
<label for="set-code">实例编号</label>
<input id="set-code" class="field" :value="settingsValues.instanceCode" disabled />
</div>
<div class="fld">
<label for="set-tz">时区</label>
<input id="set-tz" class="field" :value="settingsValues.timezone" disabled />
</div>
<div class="fld">
<label for="set-retention">消息保留天数</label>
<input id="set-retention" class="field" :value="settingsValues.retention" disabled />
</div>
</div>
<div class="form-actions">
<button class="btn primary" type="button" disabled title="后端未提供实例设置保存接口">保存设置</button>
</div>
<p class="small-muted" style="margin-top: 10px">依赖:{{ PLANNED_DEPS.settings.join('、') }}</p>
</div>
<div v-else-if="tab === 'notify'" class="card">
<div class="card-head"><h3 class="card-title">通知<DemoBadge /></h3><span class="small-muted">演示数据</span></div>
<div class="context-line"><span>实时事件提醒</span><span>{{ settingsValues.realtime ? '开启' : '关闭' }}</span></div>
<div class="context-line"><span>移动端通知</span><span>{{ settingsValues.mobileNotify ? '开启' : '关闭' }}</span></div>
<div class="form-actions">
<button class="btn" type="button" disabled title="后端未提供通知设置接口">保存</button>
</div>
</div>
<div v-else-if="tab === 'appearance'" class="card">
<div class="card-head"><h3 class="card-title">外观与预览</h3><span class="pill">本地真实设置</span></div>
<div class="context-line"><span>主题</span><span>{{ dark ? '深色' : '浅色' }}</span></div>
<div class="actions" style="margin: 10px 0 18px">
<button class="btn sm" :class="{ primary: !dark }" type="button" @click="setTheme('light')">浅色</button>
<button class="btn sm" :class="{ primary: dark }" type="button" @click="setTheme('dark')">深色</button>
</div>
<p class="small-muted">主题保存在浏览器本地(localStorage),不写入后端配置。</p>
<div class="drawer-section" style="margin-top: 14px">
<h4>演示数据总开关</h4>
<div class="context-line">
<span>演示数据</span>
<button class="btn sm" :class="{ primary: demoState.enabled }" type="button" @click="toggleDemo">
{{ demoState.enabled ? '已开启' : '已关闭' }}
</button>
</div>
<p class="small-muted" style="margin-top: 10px">{{ demoState.enabled ? MOCK_NOTE : '演示数据已关闭:所有未实现页面整体显示「未开发 / 规划中」,按钮保持禁用并标注原因。' }}</p>
<p class="small-muted">默认值由构建变量 VITE_ENABLE_MOCK 决定;本地切换会覆盖默认值并持久化。</p>
</div>
</div>
<div v-else class="card">
<div class="card-head"><h3 class="card-title">数据与迁移<DemoBadge /></h3><span class="small-muted">后端未提供迁移与容量接口</span></div>
<div class="context-line"><span>数据库迁移版本</span><span>—</span></div>
<div class="context-line"><span>对象存储使用量</span><span>—</span></div>
<div class="context-line"><span>日志保留策略</span><span>7 天(演示)</span></div>
<div class="form-actions">
<button class="btn" type="button" disabled title="后端未提供迁移接口">执行迁移</button>
</div>
</div>
</template>
+46 -1
View File
@@ -1,9 +1,44 @@
import fs from 'node:fs'
import path from 'node:path'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// 浏览器会以 CORS 为由拒绝从 file:// 加载外部 module 脚本,
// 因此构建结束后把唯一的 JS/CSS 内联进 index.html,让 dist/index.html 可以直接双击预览。
// 这不会改变接口路径或运行逻辑;通过后端静态托管时同样可用。
function inlineDistPlugin() {
let outDir = ''
return {
name: 'qlinker-inline-dist',
apply: 'build',
configResolved(config) {
outDir = path.resolve(config.root, config.build.outDir)
},
closeBundle() {
const htmlPath = path.join(outDir, 'index.html')
if (!fs.existsSync(htmlPath)) return
let html = fs.readFileSync(htmlPath, 'utf8')
html = html.replace(/<script[^>]*src="\.\/([^"]+\.js)"[^>]*><\/script>/g, (match, src) => {
const js = fs
.readFileSync(path.join(outDir, src), 'utf8')
.replace(/<\/script/gi, '<\\/script')
return `<script type="module">\n${js}\n</script>`
})
html = html.replace(/<link[^>]*rel="stylesheet"[^>]*href="\.\/([^"]+\.css)"[^>]*>/g, (match, href) => {
const css = fs.readFileSync(path.join(outDir, href), 'utf8').replace(/<\/style/gi, '<\\/style')
return `<style>\n${css}\n</style>`
})
fs.writeFileSync(htmlPath, html, 'utf8')
console.log('[qlinker] JS/CSS 已内联到 dist/index.html,可直接双击打开做静态预览')
}
}
}
// 开发期通过代理访问后端,避免在生产配置里写死后端地址。
export default defineConfig({
plugins: [vue()],
plugins: [vue(), inlineDistPlugin()],
// 相对 base:dist 资源使用 ./assets 前缀,可直接双击 dist/index.html 预览。
base: './',
server: {
port: 5173,
proxy: {
@@ -12,5 +47,15 @@ export default defineConfig({
changeOrigin: true
}
}
},
// 预览构建产物时同样把 /api 转发到本地后端,便于在 4173 上做真实联调。
preview: {
port: 4173,
proxy: {
'/api': {
target: 'http://127.0.0.1:8080',
changeOrigin: true
}
}
}
})